text:
Q: Share Extension is not showing data -- ios I am trying to create a share Extension. I am showing them into Table view. My data is coming but i am not able to see.  Also it freezes (Like we have data and popup but not showing).
here is my sample code
//
//  ShareViewController.m
//  myAppShare
//
//
//
//

#import "ShareViewController.h"
#import "MBProgressHUD.h"

@import MobileCoreServices;

static NSString *const AppGroupId = @"group.tag.BiblioHive7";

@implementation ShareViewController
{
    NSArray *arrayCategory;
    __weak IBOutlet UITextField *textFieldCategoryName;
    __weak IBOutlet UIButton *btnPost;
    __weak IBOutlet UIBarButtonItem *btnCancel;
    __weak IBOutlet UINavigationItem *nayTitle;
    __weak IBOutlet UINavigationBar *navBar;
}
-(void)viewDidLoad
{
    sharedUserDefaults = [[NSUserDefaults alloc] initWithSuiteName:AppGroupId];
    [sharedUserDefaults setObject:@"hello" forKey:@"hello"];

    NSString *userId= [sharedUserDefaults objectForKey:@"userId"];

    NSLog(@"%@", [[sharedUserDefaults objectForKey:@"categories"] class]);
    NSError* error;
    [self didSelectPost];
    if (userId==nil || [userId isEqualToString:@""] )
    {
        [self hideBackground];
        self.view.hidden= YES;

        UIAlertController * alert=   [UIAlertController
                                      alertControllerWithTitle:@"Error"
                                      message:@"Please login into myApp"
                                      preferredStyle:UIAlertControllerStyleAlert];

        UIAlertAction *defaultAction = [UIAlertAction actionWithTitle:@"Ok" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
            [self hideExtentionView];

        }];

        [alert addAction:defaultAction];
        [self presentViewController:alert animated:YES completion:nil];

    }
    else
    {
    self.view.hidden= NO;

    id jsonObject = [NSJSONSerialization JSONObjectWithData:[sharedUserDefaults objectForKey:@"categories"] options: NSJSONReadingMutableContainers error:&error];
    arrayCategory= [NSArray arrayWithArray:jsonObject];

    // here i am able to print object
    NSLog(@"%@", [arrayCategory class]);

    NSMutableArray *cityArray = [[NSMutableArray alloc] init];
    NSMutableArray *testFeeds = [NSJSONSerialization JSONObjectWithData: [sharedUserDefaults objectForKey:@"categories"] options:NSJSONReadingMutableContainers error:nil];
    [cityArray addObjectsFromArray:testFeeds];
    NSLog(@"%lu", (unsigned long)[cityArray count]);

//    [self.tableViewmyApp reloadData];
    // here you must have to provide your app group id that you already created
}
}

-(void) hideBackground
{
    [self.view setBackgroundColor:[UIColor clearColor]];
    [self.tableViewmyApp setBackgroundColor:[UIColor clearColor]];
    [textFieldCategoryName setBackgroundColor:[UIColor clearColor]];
    [nayTitle setTitle:@""];
    [btnPost setHidden:YES];
    [navBar setHidden:YES];
}

- (BOOL)isContentValid {
    // Do validation of contentText and/or NSExtensionContext attachments here
    return YES;
}

- (void)didSelectPost {

    // This is called after the user selects Post. Do the upload of contentText and/or NSExtensionContext attachments.

    // Inform the host that we're done, so it un-blocks its UI. Note: Alternatively you could call super's -didSelectPost, which will similarly complete the extension context.

    inputItem = self.extensionContext.inputItems.firstObject;
    NSItemProvider *urlItemProvider = [[inputItem.userInfo valueForKey:NSExtensionItemAttachmentsKey] objectAtIndex:0];

    if ([urlItemProvider hasItemConformingToTypeIdentifier:(__bridge NSString *)kUTTypeURL])
    {
        [urlItemProvider loadItemForTypeIdentifier:(__bridge NSString *)kUTTypeURL options:nil completionHandler:^(NSURL *url, NSError *error)
         {
             if (error)
             {
                 NSLog(@"Error occured");
             }
             else
             {
                 if ([sharedUserDefaults objectForKey:@"userId"]==nil)
                 {
                     UIAlertController * alert=   [UIAlertController
                                                   alertControllerWithTitle:@"Error"
                                                   message:@"You must be logged In to share"
                                                   preferredStyle:UIAlertControllerStyleAlert];

                     UIAlertAction* ok = [UIAlertAction
                                          actionWithTitle:@"OK"
                                          style:UIAlertActionStyleDefault
                                          handler:nil];

                     [alert addAction:ok];
                     [self presentViewController:alert animated:YES completion:nil];

                     return;

                 }

                 NSMutableArray *previousUrlsArray = [[NSMutableArray alloc]initWithArray:[sharedUserDefaults objectForKey:@"urlsArray"]];
                 if (previousUrlsArray==nil)
                 {
                     previousUrlsArray =[[NSMutableArray alloc]init];

                 }
                 [previousUrlsArray addObject:url.absoluteString];
                 NSMutableDictionary *dict= [[NSMutableDictionary alloc]init];
                 [dict setObject:previousUrlsArray forKey:@"urls"];
                 [sharedUserDefaults setObject:dict forKey:@"urlsDictionary"];

                 [sharedUserDefaults setObject:previousUrlsArray forKey:@"urlsArray"];
               //  [sharedUserDefaults synchronize];
                 [sharedUserDefaults setObject:url.absoluteString forKey:@"siteURL"];

                 [sharedUserDefaults setObject:[NSString stringWithFormat:@"%@",url.absoluteString] forKey:@"sURL"];
                 NSLog(@"%@",[sharedUserDefaults objectForKey:@"sURL"]);

//                 NSMutableArray *arrSites;
//                 if ([sharedUserDefaults valueForKey:@"SharedExtension"])
//                     arrSites = [sharedUserDefaults valueForKey:@"SharedExtension"];
//                 else
//                     arrSites = [[NSMutableArray alloc] init];
//                 NSDictionary *dictSite = [NSDictionary dictionaryWithObjectsAndKeys:self.contentText, @"Text", url.absoluteString, @"URL",nil];
//                 [arrSites addObject:dictSite];
//                 [sharedUserDefaults setObject:arrSites forKey:@"SharedExtension"];
//                 [sharedUserDefaults synchronize];

//                 UIAlertController * alert=   [UIAlertController
//                                               alertControllerWithTitle:@"Success"
//                                               message:@"Posted Successfully."
//                                               preferredStyle:UIAlertControllerStyleAlert];
//
//                    UIAlertAction* ok = [UIAlertAction
//                                      actionWithTitle:@"OK"
//                                      style:UIAlertActionStyleDefault
//                                      handler:^(UIAlertAction * action)
//                                      {
//                                          [UIView animateWithDuration:0.20 animations:^
//                                           {
//                                               self.view.transform = CGAffineTransformMakeTranslation(0, self.view.frame.size.height);
//                                           }
//                                                           completion:^(BOOL finished)
//                                           {
//                                               [self.extensionContext completeRequestReturningItems:nil completionHandler:nil];
//                                           }];
//                                      }];
//
//                 [alert addAction:ok];
//                 [self presentViewController:alert animated:YES completion:nil];
             }
         }];
    }
}

- (NSArray *)configurationItems {
    // To add configuration options via table cells at the bottom of the sheet, return an array of SLComposeSheetConfigurationItem here.
    return @[];
}

-(UITableViewCell*) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MyIdentifier"];

    /*
     *   If the cell is nil it means no cell was available for reuse and that we should
     *   create a new one.
     */
    if (cell == nil) {

        /*
         *   Actually create a new cell (with an identifier so that it can be dequeued).
         */

        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"MyIdentifier"] ;

        cell.selectionStyle = UITableViewCellSelectionStyleDefault;

    }
    cell.textLabel.text=[[arrayCategory objectAtIndex:indexPath.row] valueForKey:@"category_name"];
    return cell;
}

-(NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [arrayCategory count];
}

-(void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self saveInUserDefaultsWithCategoryName:[[arrayCategory objectAtIndex:indexPath.row] valueForKey:@"category_name"] andId:[[[arrayCategory objectAtIndex:indexPath.row] valueForKey:@"id"] integerValue]];

}
- (IBAction)postBtnTapped:(id)sender {

    [self saveInUserDefaultsWithCategoryName:textFieldCategoryName.text andId:-1];

}

-(void) saveInUserDefaultsWithCategoryName : (NSString*) categoryName andId : (NSInteger) categoryId
{

    if ([categoryName stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]].length==0)
    {
        UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"Please choose a category or create a new one "
                                                                       message:@""
                                                                preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"Ok" style:UIAlertActionStyleCancel handler:nil];
        [alert addAction:okAction];

        [self presentViewController:alert animated:YES completion:nil];

        return;
    }

    NSString *stringId=[sharedUserDefaults objectForKey:@"id"];

    ([stringId length]>0) ? [sharedUserDefaults setObject:[NSString stringWithFormat:@"%@,%ld",stringId, (long)categoryId] forKey:@"id"] : [sharedUserDefaults setObject:[NSString stringWithFormat:@"%ld", (long)categoryId] forKey:@"id"];
    NSLog(@"%@", [sharedUserDefaults objectForKey:@"id"]);

    NSString *stringCategoryName=[sharedUserDefaults objectForKey:@"category_name"];

    ([stringCategoryName length]>0) ? [sharedUserDefaults setObject:[NSString stringWithFormat:@"%@,%@",stringCategoryName, categoryName] forKey:@"category_name"] : [sharedUserDefaults setObject:[NSString stringWithFormat:@"%@",categoryName] forKey:@"category_name"];
    NSLog(@"%@", [sharedUserDefaults objectForKey:@"category_name"]);

    NSString *stringURL=[sharedUserDefaults objectForKey:@"URL"];

    ([stringURL length]>0) ? [sharedUserDefaults setObject:[NSString stringWithFormat:@"%@,%@",stringURL, [sharedUserDefaults objectForKey:@"sURL"]] forKey:@"URL"] : [sharedUserDefaults setObject:[NSString stringWithFormat:@"%@",[sharedUserDefaults objectForKey:@"sURL"]] forKey:@"URL"];
    NSLog(@"%@", [sharedUserDefaults objectForKey:@"URL"]);

    NSDictionary *categoryDictionary = [NSDictionary dictionaryWithObjectsAndKeys:categoryName,@"categoryName", nil];
    NSArray *categoryArray = [NSArray arrayWithObject:categoryDictionary];

    NSMutableDictionary *mainDictionary = [[NSMutableDictionary alloc]init];
    [mainDictionary setObject:categoryArray forKey:@"categories"];
    [mainDictionary setObject:@"0" forKey:@"categoryType"];
    [mainDictionary setObject:[sharedUserDefaults objectForKey:@"siteURL"] forKey:@"url"];
    [mainDictionary setObject:[sharedUserDefaults objectForKey:@"access_token"] forKey:@"access_token"];

    AppServices *appServices = [AppServices sharedInstance];
    appServices.delegate = self;
    [appServices postCategoriesOnServer:mainDictionary withSucessBlock:nil withfailureBlock:nil];
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
   // [self enableUserInteraction:NO];
   // [[AppServices sharedInstance] sendData:nil withSucessBlock:nil withfailureBlock:nil];

//    [sharedUserDefaults setObject:[NSNumber numberWithInteger:categoryId] forKey:@"id"];
//    [sharedUserDefaults setObject:categoryName forKey:@"category_name"];

//    NSMutableDictionary *dict=[[NSMutableDictionary alloc] init];
//
//    [dict setObject:categoryName forKey:@"category_name"];
//    [dict setObject:[NSNumber numberWithInteger:categoryId] forKey:@"id"];
//    NSLog(@"%@", [sharedUserDefaults objectForKey:@"siteURL"]);
//
//    [dict setObject:[sharedUserDefaults objectForKey:@"siteURL"] forKey:@"siteurl"];
//
//
//    [sharedUserDefaults setObject:[self dictToJson:dict] forKey:@"categorydictionary"];
}

-(NSString *)dictToJson:(NSDictionary *)dict
{
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject: dict
                                                       options:(NSJSONWritingOptions)  (/* DISABLES CODE */ (YES) ? NSJSONReadingMutableContainers : 0)
                                                         error:&error];

    if (! jsonData) {
        NSLog(@"bv_jsonStringWithPrettyPrint: error: %@", error.localizedDescription);
        return @"{}";
    } else {
        return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    }

}

- (IBAction)cancelBtnTapped:(id)sender {
    [self hideExtentionView];
}

-(void) hideExtentionView
{
    [self.extensionContext completeRequestReturningItems: nil completionHandler: nil];

}

-(void) showAlertViewWithMessage:(NSString *)message
{
    UIAlertController* alert = [UIAlertController alertControllerWithTitle:nil
                                                                   message:message
                                                            preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *defaultAction = [UIAlertAction actionWithTitle:@"Ok" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
        [self hideExtentionView];

    }];

    [alert addAction:defaultAction];
    [self presentViewController:alert animated:YES completion:nil];

}

-(void)enableUserInteraction:(BOOL)enable
{
    [self.view setUserInteractionEnabled:enable];
}

#pragma mark- AppServicesDelegate methods
-(void)showMessage:(NSString *)message
{
    [MBProgressHUD hideHUDForView:self.view animated:YES];
  //  [self enableUserInteraction:YES];
    [self showAlertViewWithMessage:message];
}

@end

A: Your problem is that you want to populate table cell textLabel with an array object which is not saved with key value.
In
-(UITableViewCell*) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

method you try to take an object which is not saved yet on that key.
cell.textLabel.text=[[arrayCategory objectAtIndex:indexPath.row] valueForKey:@"category_name"];

and in
-(void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
     [self saveInUserDefaultsWithCategoryName:[[arrayCategory objectAtIndex:indexPath.row] valueForKey:@"category_name"] andId:[[[arrayCategory objectAtIndex:indexPath.row] valueForKey:@"id"] integerValue]];
}

method, here you save the object.
This is a bad practice.


text:
Q: DrawerView is clearing when I rotate a phone When I rotate a phone my DrawerView is clearing . When I rotate my phone in my class DrawerView is running onSizeChanged and after that my drawView is empty. I have added android:configChanges="keyboardHidden|orientation|screenSize" in my AndroidManifest  but it doesn't work.
This is my drawer view :
public class DrawerView extends View {
    private Bitmap mBitmap;
    private Canvas mCanvas;
    private Path mPath;
    private Paint mBitmapPaint;
    private float mX, mY, sX, sY;
    private boolean isSigned = false;

    public DrawerView(Context c) {
        super(c);
        mPath = new Path();
        mBitmapPaint = new Paint(Paint.DITHER_FLAG);
        mBitmapPaint.setColor(Color.WHITE);
    }

    public DrawerView(Context c, Bitmap bitmap) {
        super(c);
        mPath = new Path();
        mBitmapPaint = new Paint(Paint.DITHER_FLAG);
        mBitmapPaint.setColor(Color.WHITE);
        mBitmap = bitmap;
    }

    public void setIsSigned(boolean isSigned) {
        this.isSigned = isSigned;
    }

    public boolean isSigned() {
        return isSigned;
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        mBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.RGB_565);
        mCanvas = new Canvas(mBitmap);
        mCanvas.drawColor(Color.WHITE);

    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.drawBitmap(mBitmap, 0, 0, mBitmapPaint);
        canvas.drawPath(mPath, mPaint);
    }

    public void clear() {
        setDrawingCacheEnabled(true);
        mCanvas.drawColor(Color.WHITE);
        invalidate();
    }

    private void drawDot(float x, float y) {
        mCanvas.drawCircle(x, y, 2.0f, mPaint);
    }

    private void touch_start(float x, float y) {
        mPath.reset();
        mPath.moveTo(x, y);
        mX = x;
        mY = y;
        sX = x;
        sY = y;
    }

    private void touch_move(float x, float y) {
        mPath.quadTo(mX, mY, (x + mX) / 2, (y + mY) / 2);
        mX = x;
        mY = y;
        mCanvas.drawPath(mPath, mPaint);
    }

    private void touch_up() {
        mPath.lineTo(mX, mY);
        mCanvas.drawPath(mPath, mPaint);
        mPath.reset();
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        this.isSigned = true;
        float x = event.getX();
        float y = event.getY();
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                touch_start(x, y);
                break;
            case MotionEvent.ACTION_MOVE:
                touch_move(x, y);
                break;
            case MotionEvent.ACTION_UP:
                if (x == sX && y == sY) {
                    drawDot(x, y);
                }
                touch_up();
                break;
        }
        invalidate();
        return true;
    }
}

When I rotate a phone this is doing and
  @Override
  protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        mBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.RGB_565);
        mCanvas = new Canvas(mBitmap);
        mCanvas.drawColor(Color.WHITE);
  }

and my drawer is clearing
this is my whole class :
public class SignatureActivity extends Activity implements Handler.Callback {
File mCurrentPhotoPath;
private FrameLayout drawerBox;
private Button save, clear;
private DrawerView mv;
private Paint mPaint;
private boolean existingSign;
private Intent intent;
private String signature;
private File imagesDir;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.drawer_act_lay);
    existingSign = getIntent().hasExtra(getPackageName() + "_signaturePath");
    initializeView();
    setListeners();
    Intent iin = getIntent();
    Bundle b = iin.getExtras();
    if (b != null) {
        signature = (String) b.get("signaturePath");
    }

}

@Override
protected void onResume() {
    super.onResume();
}

@Override
protected void onDestroy() {
    super.onDestroy();
}

@Override
public void onBackPressed() {
    setResult(RESULT_CANCELED);
    finish();
}

private void initializeView() {
    drawerBox = this.findViewById(R.id.drawerContainer);
    save = findViewById(R.id.saveBtn);
    clear = findViewById(R.id.clearBtn);
    if (existingSign) {
        mv = new DrawerView(this, BitmapFactory.decodeFile(getIntent()
                .getStringExtra(getPackageName() + "_signaturePath")));
    } else {
        mv = new DrawerView(this);
    }
    mv.setDrawingCacheEnabled(false);
    mv.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.MATCH_PARENT));
    drawerBox.addView(mv);
    mPaint = new Paint();
    mPaint.setAntiAlias(true);
    mPaint.setDither(true);
    mPaint.setColor(Color.BLACK);
    mPaint.setStyle(Paint.Style.STROKE);
    mPaint.setStrokeJoin(Paint.Join.ROUND);
    mPaint.setStrokeCap(Paint.Cap.ROUND);
    mPaint.setStrokeWidth(3);
    mv.setDrawingCacheEnabled(true);
}

@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {

    mCurrentPhotoPath = (File) savedInstanceState.getSerializable(MY_CURRENT_PHOTO_PATH_KEY);
    super.onRestoreInstanceState(savedInstanceState);
}

@Override
protected void onSaveInstanceState(Bundle outState) {

    outState.putSerializable(MY_CURRENT_PHOTO_PATH_KEY, mCurrentPhotoPath);
    super.onSaveInstanceState(outState);
}

private void setListeners() {
    save.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {

            if (!mv.isSigned()) {
                Toast.makeText(SignatureActivity.this, R.string.empty_sign, Toast.LENGTH_SHORT).show();
            } else {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss", Locale.US);
                String currentDateandTime = sdf.format(new Date());
                String name = "sign_" + currentDateandTime;
                Bitmap bitmap = mv.getDrawingCache();
                File imagesFolder = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
                imagesFolder.mkdirs();
                File file = new File(imagesFolder, name + ".jpg");
                try {
                    if (!file.exists()) {
                        file.createNewFile();
                    }
                    FileOutputStream ostream = new FileOutputStream(file);
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 80, ostream);
                    ostream.close();
                    mv.invalidate();
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    mv.setDrawingCacheEnabled(true);
                }
                Intent data = new Intent();
                data.putExtra(getPackageName() + "_signaturePath", file.getPath());
                setResult(RESULT_OK, data);

                finishWithResult(file.getPath());
                if (signature != null) {
                    File file1 = new File(signature);
                    file1.delete();
                }
            }
        }
    });
    clear.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            mv.clear();
            mv.setIsSigned(false);
        }
    });

}

private void finishWithResult(String path) {
    Intent intent = new Intent();
    setResult(RESULT_OK, intent);
    intent.putExtra("path", path);
    finish();
}

@Override
public boolean handleMessage(Message msg) {
    return false;
}

public class DrawerView extends View {
    private Bitmap mBitmap;
    private Canvas mCanvas;
    private Path mPath;
    private Paint mBitmapPaint;
    private float mX, mY, sX, sY;
    private boolean isSigned = false;

    public DrawerView(Context c) {
        super(c);
        mPath = new Path();
        mBitmapPaint = new Paint(Paint.DITHER_FLAG);
        mBitmapPaint.setColor(Color.WHITE);
    }

    public DrawerView(Context c, Bitmap bitmap) {
        super(c);
        mPath = new Path();
        mBitmapPaint = new Paint(Paint.DITHER_FLAG);
        mBitmapPaint.setColor(Color.WHITE);
        mBitmap = bitmap;
    }

    public void setIsSigned(boolean isSigned) {
        this.isSigned = isSigned;
    }

    public boolean isSigned() {
        return isSigned;
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        mBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.RGB_565);
        mCanvas = new Canvas(mBitmap);
        mCanvas.drawColor(Color.WHITE);

    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.drawBitmap(mBitmap, 0, 0, mBitmapPaint);
        canvas.drawPath(mPath, mPaint);
    }

    public void clear() {
        setDrawingCacheEnabled(true);
        mCanvas.drawColor(Color.WHITE);
        invalidate();
    }

    private void drawDot(float x, float y) {
        mCanvas.drawCircle(x, y, 2.0f, mPaint);
    }

    private void touch_start(float x, float y) {
        mPath.reset();
        mPath.moveTo(x, y);
        mX = x;
        mY = y;
        sX = x;
        sY = y;
    }

    private void touch_move(float x, float y) {
        mPath.quadTo(mX, mY, (x + mX) / 2, (y + mY) / 2);
        mX = x;
        mY = y;
        mCanvas.drawPath(mPath, mPaint);
    }

    private void touch_up() {
        mPath.lineTo(mX, mY);
        mCanvas.drawPath(mPath, mPaint);
        mPath.reset();
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        this.isSigned = true;
        float x = event.getX();
        float y = event.getY();
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                touch_start(x, y);
                break;
            case MotionEvent.ACTION_MOVE:
                touch_move(x, y);
                break;
            case MotionEvent.ACTION_UP:
                if (x == sX && y == sY) {
                    drawDot(x, y);
                }
                touch_up();
                break;
        }
        invalidate();
        return true;
    }
}

}

A: You could save the touch events in some type of List and then recreate them after configuration changes. This is already explained in here.
Your class should look like this
public class DrawerView extends View {
private Bitmap mBitmap;
private Canvas mCanvas;
private Path mPath;
private Paint mBitmapPaint;
private float mX, mY, sX, sY;
private boolean isSigned = false;

private static final String EXTRA_STATE = "exta_state";
private static final String EXTRA_EVENT_LIST = "exta_event_list";

private ArrayList<MotionEvent> motionEvents = new ArrayList<>();
private ArrayList<MotionEvent> auxMotionEvents = new ArrayList<>();

public DrawerView(Context c) {
    super(c);
    mPath = new Path();
    mBitmapPaint = new Paint(Paint.DITHER_FLAG);
    mBitmapPaint.setColor(Color.WHITE);
    setSaveEnabled(true);
}

public DrawerView(Context c, AttributeSet attributeSet) {
    super(c, attributeSet);
    mPath = new Path();
    mBitmapPaint = new Paint(Paint.DITHER_FLAG);
    mBitmapPaint.setColor(Color.WHITE);
    setSaveEnabled(true);
}

public DrawerView(Context c, Bitmap bitmap) {
    super(c);
    mPath = new Path();
    mBitmapPaint = new Paint(Paint.DITHER_FLAG);
    mBitmapPaint.setColor(Color.WHITE);
    mBitmap = bitmap;
    setSaveEnabled(true);
}

@Override
public Parcelable onSaveInstanceState() {

    Bundle bundle = new Bundle();
    bundle.putParcelable(EXTRA_STATE, super.onSaveInstanceState());
    bundle.putParcelableArrayList(EXTRA_EVENT_LIST, motionEvents);

    return bundle;
}

@Override
public void onRestoreInstanceState(Parcelable state) {
    if (state instanceof Bundle) {

        auxMotionEvents = new ArrayList<>();
        motionEvents = new ArrayList<>();

        Bundle bundle = (Bundle) state;
        super.onRestoreInstanceState(bundle.getParcelable(EXTRA_STATE));
        auxMotionEvents = bundle.getParcelableArrayList(EXTRA_EVENT_LIST);
        if (auxMotionEvents == null) {
            auxMotionEvents = new ArrayList<>();
        }

        return;
    }
    super.onRestoreInstanceState(state);
}

private void performTouch(MotionEvent event) {
    this.isSigned = true;
    float x = event.getX();
    float y = event.getY();
    switch (event.getAction()) {
        case MotionEvent.ACTION_DOWN:
            touch_start(x, y);
            break;
        case MotionEvent.ACTION_MOVE:
            touch_move(x, y);
            break;
        case MotionEvent.ACTION_UP:
            if (x == sX && y == sY) {
                drawDot(x, y);
            }
            touch_up();
            break;
    }
    invalidate();
    motionEvents.add(MotionEvent.obtain(event));
}

public void setIsSigned(boolean isSigned) {
    this.isSigned = isSigned;
}

public boolean isSigned() {
    return isSigned;
}

@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
    super.onSizeChanged(w, h, oldw, oldh);
    mBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.RGB_565);
    mCanvas = new Canvas(mBitmap);
    mCanvas.drawColor(Color.WHITE);

    if (auxMotionEvents != null) {
        for (MotionEvent motionEvent : auxMotionEvents) {
            performTouch(motionEvent);
        }
    }

}

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    canvas.drawBitmap(mBitmap, 0, 0, mBitmapPaint);
    canvas.drawPath(mPath, mBitmapPaint);
}

public void clear() {
    setDrawingCacheEnabled(true);
    mCanvas.drawColor(Color.WHITE);
    invalidate();
}

private void drawDot(float x, float y) {
    mCanvas.drawCircle(x, y, 2.0f, mBitmapPaint);
}

private void touch_start(float x, float y) {
    mPath.reset();
    mPath.moveTo(x, y);
    mX = x;
    mY = y;
    sX = x;
    sY = y;
}

private void touch_move(float x, float y) {
    mPath.quadTo(mX, mY, (x + mX) / 2, (y + mY) / 2);
    mX = x;
    mY = y;
    mCanvas.drawPath(mPath, mBitmapPaint);
}

private void touch_up() {
    mPath.lineTo(mX, mY);
    mCanvas.drawPath(mPath, mBitmapPaint);
    mPath.reset();
}

@Override
public boolean onTouchEvent(MotionEvent event) {

    switch (event.getAction()) {
        case MotionEvent.ACTION_DOWN:
        case MotionEvent.ACTION_MOVE:
        case MotionEvent.ACTION_UP:
            performTouch(event);
    }

    return true;
}

}
Remember to remove android:configChanges="keyboardHidden|orientation|screenSize" from your manisfest and to give the view an id so it can be recreated.
To set an id for your view use setId() after you instantiate DrawerView in your initializeView(). It should look something like this
private void initializeView() {
drawerBox = this.findViewById(R.id.drawerContainer);
save = findViewById(R.id.saveBtn);
clear = findViewById(R.id.clearBtn);
if (existingSign) {
    mv = new DrawerView(this, BitmapFactory.decodeFile(getIntent()
            .getStringExtra(getPackageName() + "_signaturePath")));
} else {
    mv = new DrawerView(this);
}

mv.setId(View.generateViewId());

mv.setDrawingCacheEnabled(false);
mv.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
        ViewGroup.LayoutParams.MATCH_PARENT));
drawerBox.addView(mv);
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setDither(true);
mPaint.setColor(Color.BLACK);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeJoin(Paint.Join.ROUND);
mPaint.setStrokeCap(Paint.Cap.ROUND);
mPaint.setStrokeWidth(3);
mv.setDrawingCacheEnabled(true);

}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Ruby variable regular expression in Array Select I'm trying to exclude elements from an array of strings using array.select. I have this method:
def filter_out_other_bad_vals(array_of_strs, things_i_want)
  array_of_strs = array_of_strs.select { |line| /"#{things_i_want}"/.match(line) }
end

I want to pass a string as a variable things_i_want. But this does not return any matches:
array = ["want_this", "do_not_want", "do_not_want","want_this", "want_this"]
pattern = 'want_this'
array = filter_out_other_bad_vals(array, pattern)

This returns an empty array. But if I hardcode the value in the match expression, I get what I want.
def filter_out_other_bad_vals(array_of_strs, things_i_want)
  array_of_strs = array_of_strs.select { |line| /want_this/.match(line) }
end

How do I put a variable in the regex? What am I doing wrong?
I could just traverse the array, check each item, and then save the value in another array, but that's not very ruby-like, is it?

A: You include quotes in regex definition:
 /"#{things_i_want}"/

remove them and it should work:
/#{things_i_want}/

EDIT:
By the way, you don't have to use regex for exact matching, you can use equality check (==) or #include? depending if you need a string to be equal to thing you want or just include it:
> array = ["want_this", "do_not_want", "do_not_want","want_this", "want_this"]
> array.select{|line| line == 'want_this'}
# => ["want_this", "want_this", "want_this"]
> array.select{|line| line.include? 'want_this'}
# => ["want_this", "want_this", "want_this"]


text:
Q: Append string in the beginning and the end of a line containing certain string all
I want to know how to append string in the beginning and the end of a line containing certain string using perl?
So for example, my line contains:
%abc %efd;
and I want to append 123 at the beginning of the line and 456 at the end of the line, so it would look like this:
123 %abc %efd 456
8/30/16 UPDATE--------------------------------
So far I have done something like this:
foreach file (find . -type f)
perl -ne 's/^\%abc\s+(\S*)/**\%abc $1/; print;' $file > tmp; mv tmp $file
end
foreach file (find . -type f)
perl -ne 's/$\%def\;\s+(\S*)/\%def\;**\n $1/; print;' $file > tmp; mv tmp $file
end
so this does pretty well except that when abc and def are not in one string.
for example:
%abc
something something something
%def
this would turn out to be
%abc
something something something
%def;
which is not what I want.
Thank you

A: Welcome to StackOverflow. We strive to help people solve problems in their existing code and learn languages, rather than simply answer one-off questions, the solutions to which can be easily found in 101 tutorials and documentation. The type of question you've posted doesn't leave a lot of room for learning, and doesn't do much to help future learners. It would help us greatly if you could post a more complete example, including what you've tried so far to get it working.
All that being said, there are two main ways to prepend and append to a string in Perl: 1. the concatenation operator, . and 2. string interpolation.

*

*Concatenation
Use a . to join two strings together. You can chain operations together to compose a longer string.
my $str = '%abc %efd';
$str = '123 ' . $str . ' 456';
say $str; # prints "123 %abc %efd 456" with a trailing newline

*Interpolation
Enclose a string in double quotes to instruct Perl to interpolate (i.e. find and evaluate) any Perl-style variables enclosed within the string.
my $str = '%abc %efd';
$str = "123 $str 456";
say $str; # prints "123 %abc %efd 456" with a trailing newline

You'll notice that in both examples we prepended and appended to the existing string. You can also create new variable(s) to hold the result(s) of these operations. Other methods of manipulating and building strings include the printf and sprintf functions, the substr function, the join function, and regular expressions, all of which you will encounter as you continue learning Perl.
As far as looking to see if a string contains a certain substring before performing the operation, you can use the index function or a regular expression:
if (index($str, '%abc %efd') >= 0) {
# or...
if ($str =~ /%abc %efd/) {

Remember to use strict; at the top of your Perl scripts and always (at least while you're learning) declare variables with my. If you're having trouble with the say function, you may need to add the statement use feature 'say'; to the top of your script.
You can find an index of excellent Perl tutorials at learn.perl.org. Good luck and have fun!
UPDATE Here is (I believe) a complete answer to your revised question:
find . -type f -exec perl -i.bak -pe's/^(%abc)\s+(\S*)\s+(%def;)$/**\1 \2 \3**/'

This will modify the files in place and create backup files with the extension .bak. Keep in mind that the expression \S* will only match non-whitespace characters; if you need to match strings that contain whitespace, you will need to update this expression (something like .*? might be workable for you).

A: In you case, you want to append string when line of file match the certain string, it means match and replace.
Firstly, read each line of your input file.
Secondly, check if it match with the string you want to append string into the beginning and the end.
Then replace the match string by the new string which contain additional beginning string, the match string and additional end string.
my $input_file = 'your file name here';
my $search_string = '%abc %efd';
my $add_begin = '123';
my $add_end = '456';
# Read file
open(my $IN, '<', $input_file) or die "cannot open file $input_file";
# Check each line of file
while (my $row = <$IN>) {
  chomp $row;
  $row =~ s/^($search_string)$/$add_begin $1 $add_end/g;
  print $row."\n";
}

Try with input file as below:
%abc %efd
asdahsd
234234
%abc
%efd
%abc%efd

You will receive the result as we expected:
123 %abc %efd 456
asdahsd
234234
%abc
%efd
%abc%efd

Modify the code as your requirement and contact me if there's any issue.

A: Use m modifier to replacing beginning and ending with line by line.
 s/^\%abc/123 $&/mg;
 s/\%def$/ 456/mg;

Used together, as /ms, they let the "." match any character whatsoever, while still allowing "^" and "$" to match, respectively, just after and just before newlines within the string. source


text:
Q: trying to print output from an ECR image with python boto3 I am trying to print output from an ECR image with python boto3. I can get it to print out the imageDigest, but would like to add the imageTag. Can anyone think of a way to add the imageTag? Everyway I have tried has errored out.
import json
import boto3

def get_reponames():
    client = boto3.client('ecr')
    reponames = [repo['repositoryName'] for repo in client.describe_repositories()['repositories']]

    return reponames

def get_imageids(prepo):
    client = boto3.client('ecr')
    imageids = [img['imageDigest'] for img in client.list_images(repositoryName=prepo,)['imageIds']]

    return imageids

def lambda_handler(event, context):

    output = get_reponames()
    for rn in output:
        print(rn)
        outputii = get_imageids(rn)
        for ii in outputii:
            print(ii)

    return {
        'body': json.dumps("hello world")
    }

I'll post the output for list_images below. The above code works to display imageDigest, but I want to add imageTag too.
{
    'imageIds': [
        {
            'imageDigest': 'sha256:764f63476bdff6d83a09ba2a818f0d35757063724a9ac3ba5019c56f74ebf42a',
            'imageTag': 'precise',
        },
    ],
    'ResponseMetadata': {
        '...': '...',
    },
}

A: Your get_imageids function only return imageDigest so you can not access it on lambda_handler function. You need to return imageTag as well to read it on lambda_handler
import json
import boto3

def get_reponames():
    client = boto3.client('ecr')
    reponames = [repo['repositoryName'] for repo in client.describe_repositories()['repositories']]

    return reponames

def get_imageids(prepo):
    client = boto3.client('ecr')
    imageids = [
        {"digest": img['imageDigest'], "tag": img.get('imageTag', None)} for img in
        client.list_images(repositoryName=prepo, )['imageIds']
    ]

    return imageids

def lambda_handler(event, context):
    output = get_reponames()
    for rn in output:
        print(rn)
        outputii = get_imageids(rn)
        for ii in outputii:
            print(f"digest : {ii['digest']}, tag: {ii['tag']}")

    return {
        'body': json.dumps("hello world")
    }


text:
Q: How do add classes to elements and change page title through AngularJS? So, I've recently stumbled upon some amazing Framework, AngularJS.
I really like it, and it seems to be the perfect fit for me, therefore, I need a few things before I can move forward.
I would like to be able to change the page title of the page, based on
(a) The page URL, and/or
(b) Data received, such as a form being submitted, rather than showing an alert, the title of the page will change, and the page contents may change
Also, I'm looking to add classes to the menu links based on what the current page is. Therefore, if the current page is Home, I want to add a class to the
 element of "Home", and not others, and when on "About", the
 element for that page should have the active class for that nav item.
Thanks.

A: The first requirement can be solved by utilizing $routeParams and the second by ngClass.
Here is a quick example plunker to get you started:
Javascript
var app = angular.module('plunker', []);

app.config(function ($routeProvider) {
    $routeProvider
        .when('/', { template: '
Home page
'})
        .when('/:title', { template: '
Page for {{ name }}
', controller: 'MainCtrl'})
        .otherwise({
            redirectTo: '/'
        });
});

app.controller('MainCtrl', function ($scope, $routeParams) {
    $scope.$on('$routeChangeSuccess', function (event, current, prev) {
        $scope.name = $routeParams.title || 'World';
    });
});

HTML
<!DOCTYPE html>

    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>

    <link rel="stylesheet" href="style.css" />

 Hello {{ name }}!

Bob

Harry

Home

CSS
.nav-bar {
  display: block;
  width: 100%;
}

.nav-bar li {
  display: inline-block;
  text-decoration: none;
  width: 50px;
}

.Bob {
  background-color: yellow;
}

.Harry {
  background-color: orange;
}


text:
Q: Wrong directory in passwd file. How to edit properly? I have the following value under /etc/passwd file:
web3:x:5006:5006::/var/www/clients/client2/web3:/bin/false

Now, the correct value should be:
web3:x:5006:5006::/var/www/clients/client1/web3:/bin/false

That is, client1 and not client2.
I know that it's not advisable to edit the passwd file directly using vi or other text editor. I learned that it should be edited using this command vipw -s. But when I run vipw -s, I cannot find this line /var/www/clients/client1/web3:/bin/false. What I can see is this web3:!:15869:0:99999:7:::.
So how can I change the value from client2 to client1?

A: Try:
usermod -d /var/www/clients/client1/web3 web3 or just vipw without -s.


text:
Q: Trouble implementing recursion | python I am having some trouble implementing recursion into some of my code and the task I have been given must be completed via recursion. Any help would be much appreciated.
Task 1 requires me to return the smallest value in a list through the use of recursion and I keep on getting an error
Code:
lst = [12, 1, 44, 61, 0]

def smallestNum(lst):
    if len(lst) == 0:
        raise ValueError("List is empty")
    elif len(lst) == 1:
        print(lst[0])
    return min(lst[0], smallestNum(lst[1:])

print(smallestNum(lst))

Error:
ValueError: List is empty

A: Example for the first task.
def smallestNum(lst):
    return min(lst[0],smallestNum(lst[1:])) if len(lst)>1 else lst[0]

lst = [12, 1, 30, 44, 61]
print(smallestNum(lst))


text:
Q: PHPUnit and Zend Framework assertRedirectTo() issue I'm having an issue with assertRedirectTo() in a test I have created, below is the code I have used:
public function testLoggedInIndexAction() {
  $this->dispatch('/');
  $this->assertController('index');
  $this->resetResponse();
  $this->request->setPost(array(
   'type' => 'login',
   'username' => 'root',
   'password' => 'asdasd',
  ));
  $this->request->setMethod('POST');
  $this->dispatch('/');
  $this->assertRedirectTo('/feed/');
}

You log in through / (index.php/) and submit post details there and the it redirects you to /feed/ (index.php/feed/). The details I have supplied are correct and should work however I am having issues whereby PHPUnit is saying they are incorrect:
There was 1 failure:

1) IndexControllerTest::testLoggedInIndexAction
Failed asserting response redirects to "/feed/"

/home/public_html/mashhr/library/Zend/Test/PHPUnit/Constraint/Redirect.php:190
/home/public_html/mashhr/library/Zend/Test/PHPUnit/ControllerTestCase.php:701
/home/public_html/mashhr/tests/application/controllers/UserControllerTest.php:36

A: @poelinca: No, it is simply a case of Zend_Test being unreliable in registering a redirect (even if it has been called correctly!)
In his case, the real app is no doubt redirecting the user properly, but the Zend_Test environment is having trouble registering properly called redirects. The best response I can think of is to omit any failing assertRedirect which actually works in the application.
This is not an optimal situation, but unless you're prepared to dig into the Zend code to see where the problem is, this may be your best bet for efficiency. This is an example of what causes unit testing to get a bad name: Having to alter code to pass tests which actually work already.
See http://framework.zend.com/issues/browse/ZF-7496 Which is misleadingly specific in its title: the problem relates to all redirects, especially those which must set headers and exit instead of dispatching the original controller.
For whatever reason, this behavior causes Redirects not to always fail, but to be highly unreliable instead! If anyone knows a better workaround to this problem (which is general, and probably unrelated to the OP's code) please let us know.

A: stumbled on this question while having the same problem. I ended up doing the following:
$this->assertRedirect();
$responseHeaders = $this->response->getHeaders();
$this->assertTrue(count($responseHeaders) != 0);
$this->assertArrayHasKey('value', $responseHeaders[0]);
// in my case I'm redirecting to another module
$this->assertEquals('/module/controller/action', $responseHeaders[0]['value']);

A: I've responded this answer in http://zend-framework-community.634137.n4.nabble.com/Zend-Test-failing-on-AssertRedirectTo-td3325845.html#a4451217
I'm having this same issue... A possible way to assert it could be in

*

*PHPUnit and Zend Framework assertRedirectTo() issue
But the problem is there.. My example is (wich actually works if done manually):
// controller modules/picking/orders/product
$orderId = $this->_getParam('oId');
if (empty($orderId)) {
    return $this->_redirect('picking/orders/browse/invalid/empty');
}

// test
$this->dispatch('picking/orders/product');
$this->assertRedirect(); // ok
$this->assertRedirectTo('picking/orders/browse'); // error
$this->assertRedirectTo('picking/orders/browse/invalid/empty'); // error

After I've found the error!

Actually, following the example above i've found that the string comparizon in my example has an error:
'.../public//picking/orders/browse/invalid/empty'
'.../public/picking/orders/browse/invalid/empty'

... fixing the preprended slash solve the problem! ;)

A: So if i understand right , you wrote a test that fails ( id say this is perfect ) .
In order to make the test pass you need to debug you're app and see where the problem is , in this case you need to have a look at the actual redirection ( or eaven the post fields sent by the form ) , maybe check the routing too . I gues nobody here will be able to answer you're question unless you post the code in you're index controller/form/view and feed controller .

A: For future reference, I had this issue today and it was caused by the Url class failing to build a valid url (I was passing the wrong parameters) but not reporting an error to PHPUnit (probably because PHPUnit masks the error).
Correcting the url parameters fixes the url and with it the assertion.


text:
Q: Proper way to size a byte array type punning of a struct in C Suppose I have this definition:
struct A {
    union {
        struct {
             T1 f1;
             T2 f2;
             T3 f3;
             ...
        };
        char bytes[...];
};

Is there a way, in standard C (or gnu-c++14 where as far as I understand union type punning is allowed to a certain extent) to automatically size the bytes array to be as big as the unnamed struct it is unioned with?

A: To match the size of the anonymous struct, it would have to be not anonymous but then within standard C, you couldn't address its members transparently.
typedef int T1,T2,T3; //example types
struct name{ //originally anonymous struct given a name
     T1 f1;
     T2 f2;
     T3 f3;
};
struct A{
    union {
        struct name embedded;
        char bytes[sizeof(struct name)];
        //^can size it now that is has a name
    } ;
}u;

Under extended C (-fms-extensions/-fplan9-extensions with gcc) you can do:
typedef int T1,T2,T3;
struct name{
     T1 f1;
     T2 f2;
     T3 f3;
};
struct A{
    union {
        struct name; //embed struct name transparently
        char bytes[sizeof(struct name)];
    } ;
}u;

but in any case, none of this is necessary as the C standard explicitly allows you to reinterpret any object as a char array without causing any undefined behavior (Simply cast the pointer to the object to char* and pretend you're reading a char array).
Edit: if you need reinterpreting via a type other than char, you could use a macro as in:
typedef int T1,T2,T3;
#define ANON_STRUCT \
    struct { \
         T1 f1; \
         T2 f2; \
         T3 f3; \
    }
struct A{
    union {
        ANON_STRUCT;
        ANON_STRUCT named_anon;
        #if __cplusplus
        char bytes[sizeof(named_anon)];
        #else
        char bytes[sizeof(ANON_STRUCT)];
        #endif
    } ;
}u;

but last time I checked you couldn't use unions for reinterpreting in C++ (only in C) -- you had to stick to using the currently active member.


text:
Q: Revert ProgressBar color from Material to old one I am using new Material design in my app. On pre-Lolipop devices ProgressBar is standard gray color and on new Lolipop devices it's greenish color. How do I force Lolipop devices to use gray color like pre-Lolipop devices use without making the new drawable for ProgressBar.
Thanks!


text:
Q: Open Travelling Salesman Problem I am trying to find a linear program for the open Travelling Salesman Problem, where the salesman does not need to return to the starting point. More precisely, I have to do this with multiple possible depots and multiple salesmen (trucks).
The formulation for the non open version of the problem is the following (forget about the green box):
LP for closed multi depot vehicle routing problem:
N is the number of customers, M is the number of depots, K is the number of trucks. My idea was to delete constraint (3) and (4), because still every place needs to be visited, but not from all places a truck needs to leave. But when I put this in the solver, he gives me tours with subtours.
Why is that the case and/or are there other ways to solve this?

A: The easiest way to handle the Open TSP is to consider a regular TSP, and to change the cost function such that every arc to the depot has cost $0$. Keep all the constraints, and just change $c_{i,depot}=0$ for all nodes $i$.


text:
Q: consulta UPDATE aveces falla MYSQL PHP Buenas tardes tengo un problema al descontar un numero de mi tabla, es decir mayormente resta bien pero existen ocaciones en las que la resta no se da.
mi tabla es la siguiente:
productos:
-------------------
|id_producto|unidades|
-------------------
|     100   |   100  |
|     200   |   20   |
----------------------

mi conexion a mi base de datos mysql desde php:
$bd = new mysqli("localhost","host","clave","basededatos");
$bd->set_charset("utf8");

y mi consulta a la base de datos es:
$unidades_descontar = 10;
$id_producto = 100;
$bd->query("update productos set unidades=unidades-".$unidades_descontar." where id_producto=".$id_producto);

$unidades_descontar = 20;
$id_producto = 100;
$bd->query("update productos set unidades=unidades-".$unidades_descontar." where id_producto=".$id_producto);

$unidades_descontar = 10;
$id_producto = 200;
$bd->query("update productos set unidades=unidades-".$unidades_descontar." where id_producto=".$id_producto);

Yo lo e probado y mayormente todo funciona correcto, pero existen ocaciones en las que no se descuenta el stock y yo valido y verifico las variables $id_producto & variable $unidades_descontar.
Notas:

*

*Esto solo es un ejemplo pero en realidad yo recorro un foreach y en cada ciclo ejecuto el update pero esto es basicamente lo mismo

*Esta funcion varias veces es ejecutada por 2 o 3 usuarios al mismo tiempo ( aunque esto paresca ser lo que genera el error son muy pocas veces las que un usuario interactual al mismo segudo que otro)


text:
Q: Flutter: HTTP Get The getter 'length' was called on null My http get function cannot receive response from my laravel backend. It just keep stating the getter 'length' was called on null. When I tested the api http://localhost/ioio/public/api/settings on my browser or postman it is able to receive data and response, so I am not sure why in flutter I would not be able to receive the response.
This is my repository function. I tried to print out to see where the code faced an error. It was stopped at the final response =... line and then it will lead to error at the catch function. I also tried using await http.get('http://localhost/ioio/public/api/settings'); but the result is the same.
Future<Setting> initSettings() async {
  Setting _setting;
  final String url = '${GlobalConfiguration().getString('api_base_url')}settings';
  try {
    final response = await http.get(url, headers: {HttpHeaders.contentTypeHeader: 'application/json'});
    if (response?.statusCode == 200 && response.headers.containsValue('application/json')) {
      if (json.decode(response.body)['data'] != null) {
        SharedPreferences prefs = await SharedPreferences.getInstance();
        await prefs.setString('settings', json.encode(json.decode(response.body)['data']));
        _setting = Setting.fromJSON(json.decode(response.body)['data']);
        if (prefs.containsKey('language')) {
          _setting.mobileLanguage.value = Locale(prefs.get('language'), '');
        }
        _setting.brightness.value = prefs.getBool('isDark') ?? false ? Brightness.dark : Brightness.light;
        setting.value = _setting;
        // ignore: invalid_use_of_visible_for_testing_member, invalid_use_of_protected_member
        setting.notifyListeners();
      }
    } else {
      print(CustomTrace(StackTrace.current, message: response.body).toString());
    }
  } catch (e) {
    print(CustomTrace(StackTrace.current, message: url).toString());
    return Setting.fromJSON({});
  }
  return setting.value;
}

This is the messages where the catch error printed out.
Error in (initSettings (package:ioio/src/repository/settings_repository.dart:52:34)) | [http://localhost/ioio/public/api/settings]
I/flutter (10877): NoSuchMethodError: The getter 'length' was called on null.
I/flutter (10877): Receiver: null
I/flutter (10877): Tried calling: length

This is where my main class is calling the initSettings function during initialization.
@override
  void initState() {
    settingRepo.initSettings(); //this line
    settingRepo.getCurrentLocation();
    userRepo.getCurrentUser();
    super.initState();
  }

This is the line number 52
print(CustomTrace(StackTrace.current, message: url).toString());

This is the line where exception occur
final response = await http.get(url, headers: {HttpHeaders.contentTypeHeader: 'application/json'});


text:
Q: Google map not showing map pointer image on the exact point This map is working fine but the problem is that the map is not showing the map pointer as the map is being displayed for easy location. how can i add google map point on the map for easy tracking of the location.
<!DOCTYPE html>

        <title>Google Maps JavaScript API v3 Example: Map Simple</title>
        <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no"/>
        <meta charset="utf-8"/>

A: the page on the google developers website talks all about it:
https://developers.google.com/maps/documentation/javascript/examples/marker-simple
function initialize() {
var myLatlng = new google.maps.LatLng(-25.363882,131.044922);
var mapOptions = {
zoom: 4,
center: myLatlng
}
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);

var marker = new google.maps.Marker({
  position: myLatlng,
  map: map,
  title: 'Hello World!'
});
}

use this in your map along with the script:
google.maps.event.addDomListener(window, 'load', initialize);


text:
Q: How to use createAsyncComponent in VueRouter@4.0.0 (Vue3)? When I fill the component field in createRouter() like this:
{
    path: '/article/post',
    name: 'article-post',
    component: defineAsyncComponent({
      loader: () => import('@/views/article-post/index.vue'),
      loadingComponent: () => import('@/views/article-post/skeleton.vue'),
    }),
},

Seems like it's not working.
What I want it to show a loading page when the actual page is loading.
How do I do that?

A: The loadingComponent value must be a component definition, and cannot itself be an async component:
import { createRouter } from 'vue-router'
import { defineAsyncComponent } from 'vue'
import Skeleton from '@/views/article-post/skeleton.vue'

export default createRouter({
  routes: [
    {
      path: '/article/post',
      name: 'article-post',
      component: defineAsyncComponent({
        loader: () => import('@/views/article-post/index.vue'),
        //loadingComponent: () => import('@/views/article-post/skeleton.vue'), ❌ cannot be dynamic import
        loadingComponent: Skeleton ✅
      }),
    },
  ]
})

Also note that the loading component (Skeleton) is only shown once, i.e., if the component definition is not already in cache. This Codesandbox adds an artifical delay in loader() to demonstrate.

A: You can load components asynchronously like this:
{
    path: '/article/post',
    name: 'article-post',
    component: () => ({
        component: import('@/views/article-post/index.vue')
        loading: import('@/views/article-post/skeleton.vue')
    })
},

A: Note
Do not use Async components for routes. Async components can still be used inside route components but route component themselves are just dynamic imports.


text:
Q: Why does wp_insert_term return WP_Error / Invalid Taxonomy when the taxonomy exists? I'm calling wp_insert_term in my code, and the result is a WP_Error instance.
It seems this would be the result if the taxonomy does not exist.
So I added a line prior to wp_insert_term...
if (taxonomy_exists('the_taxonomy')) {
    error_log('it exists');
}

And in my log output, I see it exists.
So, what other reasons might wp_insert_term give me an error as a result?
Maybe I should also mention that I'm running this code in a stand-alone script.
I have also gone to the place in my code where the taxonomy is registered, and put an echo 'here'; statement to make sure that file is being executed at the right time, and it is. I see here in my log before any other output, so that leads me to believe the taxonomy definitely exists.


text:
Q: Change isEnabled visual state for datepicker I am trying to change the DatePicker visual state in a Windows Store App so that when the DatePicker is disabled, it is not as transparent as it usually is when an element is disabled. So far this is what I have:
<Style x:Key="DateDueStyle" TargetType="DatePicker">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="DatePicker">
                <Border>
                    <Grid>
                        <VisualStateManager.VisualStateGroups>
                            <VisualStateGroup x:Name="CommonStates">
                                <VisualStateGroup.States>
                                    <VisualState x:Name="Disabled">
                                        <Storyboard>
                                            <DoubleAnimation Storyboard.TargetName="DateDuePicker" Storyboard.TargetProperty="Opacity" To="1" Duration="0"/>
                                        </Storyboard>
                                    </VisualState>
                                </VisualStateGroup.States>
                            </VisualStateGroup>
                        </VisualStateManager.VisualStateGroups>
                    </Grid>
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

The issue is that if I set my DatePicker style to use this style, the entire DatePicker disappears. Am I doing something wrong with the visual state?

A: From what I can see you have removed the entire template.
In your code the DatePicker now consists of an empty Grid inside a Border.
Start by selecting your Date Picker -> Edit Template -> Edit a Copy, then further improve the control by adding visual states.


text:
Q: React Native Scrollview height not changing to fit children elements I have gone through a lot of posts here on StackOverflow and elsewhere on the web, but could not find a similar issue.
I am working on a React Native app that has a ScrollView, but the problem is that its height is not increasing to fit the children elements and the screen cannot be scrolled to see all the content.
The layout of the screen similar to this one: https://codesandbox.io/s/youthful-bogdan-moges?file=/src/App.js or https://snack.expo.dev/ZnhfpNHoc (please select iOS instead of Web) - I have given background colour to the outer and inner ScrollView elements to highlight the issue. While in CodeSandbox you can scroll to the bottom, on mobile you cannot actually scroll below the bottom border of the blue element.
I have tried a lot of things like setting flex: 1 to SafeAreaView, main View and both style and contentContainerStyle for ScrollView. It is possible to increase the height of scrollable area by setting minHeight (commented-out in CodeSandbox), but I need it to be dynamic as the amount of data can be anything.
Big thanks if anyone knows a solution to this one.

A: you can use this property flexGrow: 1, instead of flex:1
 contentContainer: {
    //flex:1,
     flexGrow: 1,
    // minHeight: '300%',
    backgroundColor: "cyan"
  },


text:
Q: Creating a specific pattern using loops I am trying to figure out how I would make my code print the right pattern using this logic;
Enter len:7
Enter repeat:3
\--\--\
--\--\-
-\--\--
\--\--\
--\--\-
-\--\--
\--\--\
Bye

This is the code I have written;
for(int i = 0; i < len; i++)
    {
        for(int j = 0; j < len; j++)
        {
            if((j%repeat == 0))
                System.out.print("\\");
            else
                System.out.print("-");
        }

        System.out.println();
    }
    System.out.println("Bye");

However if I put in the same value for len and repeat it gives this;
\--\--\
\--\--\
\--\--\
\--\--\
\--\--\
\--\--\
\--\--\
Bye

How do I make mine work like this? I know the difference through the lines is the position is off by one position but how to implement that is my problem.

A: for(int i = 0; i < len; i++)
{
    for(int j = 0; j < len; j++)
    {
        if(((i+j)%repeat == 0))
            System.out.print("\\");
        else
            System.out.print("-");
    }

    System.out.println();
}
System.out.println("Bye");

i + j


text:
Q: Nginx - set cookie from one url to another for different users I'm trying to set up hortonworks schema-registry with openresty.
we have google oauth enabled for our schema-registry ui. The google oauth passes a cookie called "_token" to /ui and all other subsequent paths except /api
This is because we may want to hit /api directly as well. (without google authentication).
The problem is since /api is exluded from the list, I'm unable to pass the cookie "_token" to any of the requests under /api
In my access_by_lua , there is a condition where I check for the cookie,
if the cookie is present - the user is authenticated and then he can move ahead
if not - we do some other checks to validate the request, and pass it ahead accordingly or return an error statement
My question is, if I want to pass the cookie from /ui to /api, how do I go ahead with it?
Also , the cookie should be set only for that particular user so that my other apps can communicate quickly.
What I've tried till now:
I tried setting a global cookie _token after reading it from the /ui path.
This doesnt seem to work since it sets the cookie for all requests (even the ones coming from apps) and the value of the cookie is static based on the first _token it receives from /ui


text:
Q: box2d vertical edge or wall collision detection I am experimenting with collision detection using Box2d Between a ball and four walls of a rectangular block which I call the gameBed.
I am using the below code to setup the ball and the LeftEdge(left wall in this case) Bodies. For brevity I am giving the code only for the left wall.
  b2World = new World(new Vector2(0, 0), false);
  World.setVelocityThreshold(0);
  GameBed gameBed = levelManager.retGameBed();   // rectangular block
  Vector2 origin = new Vector2();

  BodyDef leftWallDef = new BodyDef();
  leftWallDef.type = BodyType.StaticBody;
  leftWallDef.position.set(gameBed.position); // gameBed.position is the world co-ordinate of the bottom left corner of the rectangular block
  Body body = b2World.createBody(leftWallDef);
    PolygonShape leftWallShape = new PolygonShape();
    origin.x = 0.005f;
    origin.y = (float)(gameBed.bounds.getHeight()) / 2;
    float widthOfLeftWall = BallsMania_Constants.VIEWPORT_WIDTH/(2 * Gdx.graphics.getWidth());
    Gdx.app.log(TAG, "Width of Left Wall is " + widthOfLeftWall);
    leftWallShape.setAsBox(.1f,
            gameBed.bounds.height/2, origin, 0); // setting the half of width to .1f so that it represents an edge. The height of the edge should be as long as the rectangular edge.
    FixtureDef leftWallFixtureDef = new FixtureDef();
    leftWallFixtureDef.shape = leftWallShape;
    leftWallFixtureDef.restitution = 0.9f;
    body.createFixture(leftWallFixtureDef);

    leftWallShape.dispose();

  // Defining shape and fixture for ball
          Ball ball = new Ball();
     BodyDef ballBodyDef = new BodyDef();
     ballBodyDef.type = BodyType.DynamicBody;
     ballBodyDef.position.set(ball.position);
     ballBodyDef.linearDamping = 0.4f;
     ball.body = b2World.createBody(ballBodyDef);
     CircleShape ballShape = new CircleShape();
     ballShape.setPosition(new Vector2(0, -1 * (float)(BallsMania_Constants.VIEWPORT_HEIGHT/2.0
           - BallsMania_Constants.bottomBaseDelta
           + ball.dimension.x/2)));
     ballShape.setRadius(ball.dimension.x/2);
     FixtureDef ballBodyFixture = new FixtureDef();
     ballBodyFixture.shape = ballShape;
     ballBodyFixture.friction = 0.5f;
     ballBodyFixture.restitution = 0.5f;
     ball.body.createFixture(ballBodyFixture);
     ballShape.dispose();

Problem:
The ball doesn't collide with the leftedge; it just permiates through it and doesn't bounce.
Any guidance would be appreciated.


text:
Q: Converting a group of Scalable Vector Graphics (SVG) into Web Font Format, aka a WOFF font I am looking for a way to SVG graphics into a WOFF font. A software solution would be ideal for the use case, though I would welcome a programatic solution if the lib/api/module (whatever it is) is robust enough. There is a module I have been using, but it cuases a million NPM errors, and sometimes I get an error in a conversion, but when I run it again it works. The module is for Node.js, and isn't maintained, I was hoping to find somthing a little more reliable. As I stated, a software solution would be best, as I need to only do a 1 time conversion, but I need to do it several times. In other words, I am not writing a program that needs the ability to convert the images into a font, but I am writing an extension for VS Code, and during the development process I may need to update the WOFF font several times. Once the extension is finished though, it just needs the WOFF font, not the ability to convert from SVG to WOFF.

*

*My OS is: Fedora 36: Workstation x64
any ideas?

A: If there are tools available then hand the files to them with a for in do or find --exec {}\


text:
Q: Play Streaming Video in iPhone i am trying to play video in my app by live streaming using MPMoviewPlayerController its work fine for those videos which are saved in my bundle but its not working for live streaming i am using this
 //for Bundle Video
     NSString *urlStr = [[NSBundle mainBundle] pathForResource:@"Video.mp4" ofType:nil];

//for Streaming Video
    NSURL *videoURL = [NSURL URLWithString:@"http://streaming.disponivel.uol.com.br/video360p2/288148-1192657.mp4"];

    self.playerController = [[MPMoviePlayerViewController alloc] initWithContentURL:videoURL];
    [self.view addSubview:self.playerController.view];
    self.playerController.view.frame = CGRectMake(0, 0, 320, 400);
    [self.playerController.moviePlayer play];

How I stream live video?

A: Please Use Following code for the fetch the Mp4 File From the bundle
 NSString *url = [[NSBundle mainBundle] pathForResource:@"Video" ofType:@"mp4"];
   MPMoviePlayerController *player = [[MPMoviePlayerController alloc] initWithContentURL:[NSURL fileURLWithPath:url]];

May this Help to solve your problem
Edited
NSURL *url = [NSURL URLWithString:@"http://streaming.disponivel.uol.com.br/video360p2/288148-1192657.mp4"];
moviePlayer = [[MPMoviePlayerController alloc] initWithContentURL:url];
[moviePlayer setControlStyle:MPMovieControlStyleDefault];
moviePlayer.scalingMode = MPMovieScalingModeAspectFit;
CGRect frame;
if(self.interfaceOrientation ==UIInterfaceOrientationPortrait)
    frame = CGRectMake(20, 69, 280, 170);
else if(self.interfaceOrientation ==UIInterfaceOrientationLandscapeLeft || self.interfaceOrientation ==UIInterfaceOrientationLandscapeRight)
    frame = CGRectMake(20, 61, 210, 170);
[moviePlayer.view setFrame:frame];  // player's frame must match parent's
[self.view addSubview: moviePlayer.view];
[self.view bringSubviewToFront:moviePlayer.view];

[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(moviePlayBackDidFinish:)
                                             name:MPMoviePlayerPlaybackDidFinishNotification
                                           object:moviePlayer];

[moviePlayer prepareToPlay];
[moviePlayer play];

A: I don't know the exact reason but the MPMoviePlayerController needs to be a strong property declared. If you not declare its property strongly then only black view will appear.
So declare a strong property for MPMoviePlayerController
@property (strong, nonatomic) MPMoviePlayerController *moviePlayer;

and
NSURL *url = [NSURL URLWithString:@"http://devimages.apple.com/iphone/samples/bipbop/bipbopall.m3u8"];
self.moviePlayer = [[MPMoviePlayerController alloc] initWithContentURL:url];
[self.moviePlayer setControlStyle:MPMovieControlStyleDefault];
self.moviePlayer.scalingMode = MPMovieScalingModeAspectFit;
CGRect frame = CGRectMake(20, 80, 280, 280); //change according to your need

[self.moviePlayer.view setFrame:frame];  // player's frame must match parent's
[self.view addSubview: self.moviePlayer.view];
[self.view bringSubviewToFront:self.moviePlayer.view];

[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(moviePlayBackDidFinish:)
                                             name:MPMoviePlayerPlaybackDidFinishNotification
                                           object:self.moviePlayer];

[self.moviePlayer prepareToPlay];
[self.moviePlayer play];

and
- (void) moviePlayBackDidFinish:(NSNotification*)notification {
    NSError *error = [[notification userInfo] objectForKey:@"error"];
    if (error) {
       NSLog(@"Did finish with error: %@", error);
     }
 }


text:
Q: Why I am getting this error when adding object to coredata relationship? I want one managedobject to contain a mutablearray. The way I do it is to have an NSString like managedobject called CDstring and then my managedObject will have a many to one relationship with that
CDString.h
@class CDParent;

@interface CDString : NSManagedObject

@property (nonatomic, retain) NSString * strString;
@property (nonatomic, retain) CDParent *asCatalogsIDs;

@end

CDParent.h
@interface CDParent : NSManagedObject

@property (nonatomic, retain) NSNumber * intCatalogCount;
@property (nonatomic, retain) NSNumber * intUnreadCatalogCount;
@property (nonatomic, retain) NSString * strCountry;
@property (nonatomic, retain) NSString * strImageURL;
@property (nonatomic, retain) NSString * strParentId;
@property (nonatomic, retain) NSString * strTitle;
@property (nonatomic, retain) NSOrderedSet *arCatalogIDs;
@end

@interface CDParent (CoreDataGeneratedAccessors)

- (void)insertObject:(CDString *)value inArCatalogIDsAtIndex:(NSUInteger)idx;
- (void)removeObjectFromArCatalogIDsAtIndex:(NSUInteger)idx;
- (void)insertArCatalogIDs:(NSArray *)value atIndexes:(NSIndexSet *)indexes;
- (void)removeArCatalogIDsAtIndexes:(NSIndexSet *)indexes;
- (void)replaceObjectInArCatalogIDsAtIndex:(NSUInteger)idx withObject:(CDString *)value;
- (void)replaceArCatalogIDsAtIndexes:(NSIndexSet *)indexes withArCatalogIDs:(NSArray *)values;
- (void)addArCatalogIDsObject:(CDString *)value;
- (void)removeArCatalogIDsObject:(CDString *)value;
- (void)addArCatalogIDs:(NSOrderedSet *)values;
- (void)removeArCatalogIDs:(NSOrderedSet *)values;
@end

Now when I run this code:
(lldb) po catalogIDasCDString
$1 = 0x1e277d40 <CDString: 0x1e277d40> (entity: CDString; id: 0x1e27d830 <x-coredata://448B312F-9280-4CA3-9088-1186A50F252A/CDString/p402> ; data: {
    asCatalogsIDs = nil;
    strString = 519478bcbbe3850420ec005d;
})
(lldb) po pcd
$2 = 0x1e283110 <CDParent: 0x1e283110> (entity: CDParent; id: 0x1e2c63d0 <x-coredata://448B312F-9280-4CA3-9088-1186A50F252A/CDParent/p401> ; data: {
    arCatalogIDs =     (
    );
    intCatalogCount = nil;
    intUnreadCatalogCount = nil;
    strCountry = Indonesia;
    strImageURL = nil;
    strParentId = "7-eleven_id";
    strTitle = "7-Eleven";
})

 (lldb)

    [pcd addArCatalogIDsObject:catalogIDasCDString];

I got this error:
2013-06-21 11:42:31.816 domainname[567:1803] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[NSSet intersectsSet:]: set argument is not an NSSet'
*** First throw call stack:
(0x33cc32a3 0x3b96897f 0x33c6545f 0x345b8883 0x34550c4b 0x345b8765 0x33ab8f67 0x1d75ef 0x20c7eb 0x1cecdb 0x1b1fd5 0x1b25d3 0x1ce70f 0x34558d41 0x345505c1 0x345c8be3 0x3bd8011f 0x3bd8e259 0x3bd8e3b9 0x3bdb4a11 0x3bdb48a4)
libc++abi.dylib: terminate called throwing an exception

WHat is the problem?
Doing it like this:
NSMutableOrderedSet * mos =  [pcd mutableOrderedSetValueForKey:NSStringFromSelector(@selector(arCatalogIDs))];
[mos addObject:catalogIDasCDString]; works though

But I thought
       [pcd addArCatalogIDsObject:catalogIDasCDString]; is equivalent?


text:
Q: Upload Images Cross Domain I'm trying to make an upload images from one domain to another (CORS).
The code works perfectly on Localhost but when I try in a real domain I keep receiving this message at the Developer Console:
Invalid request

upload-file.js:
function upload() {
  var formData = new FormData();
  formData.append('img', $('#profimg')[0].files[0]);
  $.ajax({
       url : 'https://example2.com/upload.php,
       type : 'POST',
       data : formData,
       cache: false,
       contentType: false,
       processData: false,
       crossDomain: true,
       success: function(h) {
         alert(h);
       }
});
}

upload.php:
<?php
    header('Access-Control-Allow-Origin: https://example1.com');
    header('Access-Control-Allow-Credentials: true');
    header('Access-Control-Allow-Headers: Content-Type, Content-Range, Content-Disposition, Content-Description');
    require 'c.upload.php';
    $tsUpload = new tsUpload();
    echo $tsUpload['response']; //It have to respond a message like Uploaded Image or Image cannot Upload, not the message that I receive on the developer console.

I tried everything, like changing headers, not sending data from the Ajax Function, changing from https to http, writing the code from-scratch, but I always get that message.
My question is What is the problem? Am I doing something wrong?
Thank you.

A: If you got the Invalid request that means the request can not be create, that error is occur before http create .The $.ajax has a error() callback also, you can add it and check the detail error message.
Buy the way, the page'url which you send the ajax is http or https


text:
Q: How do you tell if a maxima or minima is global or local If I have the function $\ f(x) = x^2 + x - 2\ $ defined when $\ -5 \le x \le 10$,
then we have $f'(x) = 2x + 1\ $ and $\ f''(x) = 2$.
I can easily find that there is a critical point at $x = -1/2$. It clearly is a minimum since the second derivative is positive at this $x = -1/2$. I know (since its a parabola) that this is a global minima, but how do I prove that this is global and not local?

A: Note that the global minimum of a continuous function $f(x)$ in a closed interval $[a,b]$ is the minimum over the following candidates:

*

*Evaluating $f$ at the endpoints: $f(a),f(b)$.

*Evaluating $f$ at the critical points: $f(c)$, where $f'(c)=0$ or $f$ is not differentiable at $c$.

Hence, since $f(-5) = 18$ and $f(10) = 108$ are both larger than $f(-1/2) = -9/4$, it follows that the local minimum at $x=-1/2$ is also a global minimum, as desired.


text:
Q: Clear value after button clicked I have three different lighting component:

*

*Lightning input rich text

*Lightning input search

*Lightning input file

*Lightning datatable

After a button is clicked I want to delete all the values the user inputted the problem is that after redaing how to delete the inputs it is not working. Inside of my handleButtonAction I have this:
if(result == 'success'){
            this.filesData = [];
            this.showToast('Success', 'success', 'Notificación enviada a todos los miembros.');

            this.template.querySelectorAll('lightning-input').forEach(element => {
                element.value ='';
            })
            this.template.querySelector('lightning-input-rich-text').forEach(element => {
                element.value = '';
            })
            let deselectedRecs = this.selectedRowsRows
             .filter(x => !selRows.includes(x))
             .concat(selRows.filter(x => !this.selectedRows.includes(x)));

        }else{
            this.showToast('Error', 'error', result);
        }

It is not working with none of them. Could anybody help me?
Thanks
For my datatable I want to unchecked rows that area records from an object:


text:
Q: What does correlation filtering actually do?
In the slide, $G(i, j)$ is the sum of the values of all these different colours. But what does $F(u, v)*I(i, j)$ represents? And what is $G(i, j)$ as well?

A: G is the output image (on the right side)
F is the filter kernel (the 5x5 image hovering over I)
I is the input image (the image on the left)
So every outputpixel (i,j) is set to value G(i,j) which is calculated by the given formula.
u,v are coordinates within F, so F(u,v) is a value of the filter kernel.
You basically sum up pixel-wise products of values of your input and your filter array.
The Filter is moved across the image and for every pixel you calculate G(i,j) using the only the pixels of I that lie under F. At the end you have a new image I that consists of those calculated values.
Read this for further info:
http://www.cs.umd.edu/~djacobs/CMSC426/Convolution.pdf


text:
Q: Exception: java.lang.OutOfMemoryError, unable to create a new native thread I am creating new threads every 5 seconds and using Threadpool exector. I am making sure threads are getting closed. But I am getting
Exception in thread "Timer-0" java.lang.OutOfMemoryError: unable to create new native thread.
Is it happening because I am creating to many threads and not closing them? or creating new ones frequently?
Can someone please tell me IF I am doing anything wrong in the code?
public class API{
    private   MongoStoreExecutor executor = new MongoStoreExecutor(10,50);
    private class MongoStoreExecutor extends ThreadPoolExecutor {
        public MongoStoreExecutor(int queueSize, int maxThreadPoolSize) {
            super(10, maxThreadPoolSize, 30, TimeUnit.SECONDS,
                new ArrayBlockingQueue<Runnable>(queueSize),
                new ThreadPoolExecutor.CallerRunsPolicy());
        }
    }

    public TimerTask alertingPoolsData() throws Exception, UnknownHostException {
        TimeerTask task  = new TimerTask(){
            public void run(){
                Pools = alertingPools.values().toArray();
                List<Future<?>> tasks = new ArrayList<Future<?>>(Pools.length);
                for (Object pool : Pools) {
                    tasks.add(executor.submit(new DataAccumulation(timeStartSecData,
                        timeEndSec,pool, jsonArrayResult,dataResult)));
                }
                for( Future<?> f: tasks) {
                    f.get(2 * 1000L, TimeUnit.MILLISECONDS);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        long interval = 5 * 1000L;
        tm.scheduleAtFixedRate(task,(interval -
            (System.currentTimeMillis() % interval)), interval);
        return task;
    }
}

A: My hunch has to do with the code that we can't see: I suspect that you're calling alertingPoolsData over and over again somewhere.  As a result, I suspect that you are scheduling that TimerTask over and over again.  Each one of those component TimerTasks is then repeatedly creating some unknown number of Future<?>s (one for each of the elements of Pools), each of which is going to your MongoStoreExecutor.
If all of the above is the case, you've got a positive first derivative on your thread count curve.  As a result, you're going to see a quadratic increase in your thread count over time.  You'll start hitting the upper limits of your native threads pretty quickly.
As suggested in the comments, you could easily modify your current implementation.  I'd suggest a combination of a ScheduledExecutorService and a ForkJoinPool.


text:
Q: Did Worf not serve in Starfleet before? Why would he dispute Picard's order? One of the scenes that were used to show and develop the character of Worf as Klingon was him objecting to Captain Picard's order to comand the separated Enterprise saucer section in "Encounter at Farpoint" ST:TNG episode.

"I am a Klingon, sir. For me to seek escape when my Captain goes into battle..."
"You are a Starfleet officer, Lieutenant!"

While that's useful to show Klingon nature, this seeems majorly implausible and breaks any suspension of disbelief for me, that a seasoned senior officer would even remotely think to not only dispute a direct order but stand around like an opera singer discussing how he feels about it - in combat situation no less!
Is that addressed/retconned somewhere? Or merely a result of the writers not having a first clue how military works?

A: I agree with Bobby that Worf just wants to stay with his Captain.
Also remember that this is a brand new crew and not used to working with each other yet. They don't really know what they're doing as a team quite yet. I'd like to think Worf was just trying to prove that he's not a coward and he would stand by his Captain. Probably one of the many junior officers that had tried to impress the Captain since he got onboard.
Contrast this to say the episode "Allegiance", where Picard can easily communicate his intent to the bridge officers with non-verbal signals and get the exact result he was looking for. By then the Captain and the officers knew how to gel together, and knew when it was appropriate to discuss arguments with Picard, which they do, but behind closed doors and not in a position that jeopardizes unity of command (unless drama dictates otherwise of course). It takes time to build this level of teamwork that neither Picard nor the crew have gotten to yet so early in the series, which is why in hindsight this outburst looks so out of place.
It's not until later that the working relationship between Worf and Picard builds up a level of trust that would put Worf into a position to be more opinionated with Picard; enough so that he can say silly things like "Captain I must protest, I am not a merry man!" and know he wasn't out of bounds, as well as the times Worf and Riker would remind Picard that he shouldn't go on that away mission but he does anyway. They knew where their boundaries were.
Of course this relationship is strained in the First Contact movie for this very same kind of outburst, but at the end Picard knew Worf was right.
You should check out how Worf interacts when meeting Sisko in the DS9 episode "Way of the Warrior", and compare that to how he interacts with him as a seasoned Commander throughout that series vs. how he acted with Picard as a junior Lieutenant, it's a good way to see how his character developed. Another episode into Worf's development as a commander can be seen in "Rules of Engagement".

A: I don't see anything special there, let's just alter the phrase a little bit:

"I am a Marine, sir. For me to seek escape when my Captain goes into battle..."

Worf protested against the order simply because he wanted to stay, fight and do his duty alongside his commander. I think mentioning that he's Klingon does just underline this statement, by simply saying "I'm a warrior and you're my captain, I'm not leaving while you stay".

A: Out-of-universe:
I always saw that as heavy-handed scriptwriting. As the pilot episode, they had to establish the characters and their roles, to an audience of both Trek afficionados and newbies. A Trek newbie might not have known what a Klingon is or anything about their cultural stereotype. There was a lot of exposition which was either unnecessary or could have been delivered with more subtlety for the afficionados, but the scriptwriters (and maybe the actors) probably felt they had to go a little over the top with it so the newbies could follow along.
A lot of TNG's first season, and parts of the second season had IMHO, numerous cringe-worthy moments like that. They had disappeared by season 3.


text:
Q: Duplicate function First, I did my resarch about that. But I couldn't find any solution for that.
Here what I want to do.
I have multiple files with the same function name, during my test I didn't specify that function and kept it simple.
The mulitple files will be included, but since the function already been declared, I'm getting that Fatal error cannot redeclare function ..., previously declared in ...
I know how to avoid that fatal error but since I include multiple files with the same function it don't fix it.
My question, is it logical, or should I rethink and do someting diffrent.
My friend told me that could be handled with objects and so on.
thanks for any suggestion.

A: Are the functions identical? In that case, you may be able to "hack" around the problem by wrapping the function declarations with a function_exists() clause, see How to avoid fatal error Cannot redeclare function in PHP:
<?php
if (!function_exists('utility')) {
  function utility() {
    // ...
  }
}
?>

Alternatively, it might be worth your time to read up on namespaces:

In the PHP world, namespaces are designed to solve two problems that
  authors of libraries and applications encounter when creating
  re-usable code elements such as classes or functions:

*

*Name collisions between code you create, and internal PHP
  classes/functions/constants or third-party
  classes/functions/constants.

*Ability to alias (or shorten) Extra_Long_Names designed to
  alleviate the first problem, improving readability of source code. (source)

A: If your functions have the same name then they should do the same thing. If they don't then you should rename them to reflect what it is that they do. That way you can include all your functions once (at the start of your script) and use them wherever you have to.
I wouldn't recommend using objects solely as a means to solving this problem (though I would recommend using them for a host of other reasons).
So to answer part of your question

My question, is it logical, or should I rethink and do someting diffrent.

Yes you should do something different, even if it means namespacing your functions (put the area of concern followed by an underscore for example)
function user_rename(){

}

function category_rename(){

}

function group_rename(){

}

A: // A.php
Class A {

 static function myFunc(){
 .................
 }

}
// B.php
Class B {

 static function myFunc(){
 .................
 }

}
// C.php
Class C {

 static function myFunc(){
 .................
 }

}

// foo.php
include_once('A.php');
include_once('B.php');
include_once('C.php');
A::myFunc();
B::myFunc();
C::myFunc();

A: I think you said it "...or should I rethink and do someting diffrent."
It doesn't has to be a object. But why not outsourcing all common function in one file (i.e. common.php) and include it from all other files with require_once 'common.php'?


text:
Q: ssrs with visible filter I have the above SSRS Report. I used adventurewoorks2014. Any adventureworks will do. My problem is that I want to filter by month in this example October 2011 so that the corresponding graph will turn yellow and others are still in blue and visible.
In other words, whenever I choose a value from the top the corresponding graph should turn yellow and I can still see other graph but in blue. Any question please let me know. Many thanks in advance
    ----Query FROM Adventureworks
SELECT [SalesOrderID]
      ,[OrderDate]
,DATENAME(MONTH,[OrderDate])+' '+DATENAME(YEAR,[OrderDate]) AS MonthYear
FROM [Sales].[SalesOrderHeader]

    enter code here
--------Parameter query
SELECT distinct
DATENAME(MONTH,[OrderDate])+' '+DATENAME(YEAR,[OrderDate]) AS MonthYear
FROM [AdventureWorks2014].[Sales].[SalesOrderHeader]

A: Create an expression on the backcolor for the graph which sets to yellow if the corresponding label is the same as the selected parameter and blue if not.
Note that if the parameter is changed then the report will need to be regenerated in order for the colour to change. There is no alternative to this behaviour in SSRS.


text:
Q: "Women hold up half the sky." meaning
Women hold up half the sky.

This is an old Chinese saying. I wonder what hold up mean here. hold up is a phrasal verb, meaning *to remain strong or successful. Nevertheless, in the example, this sense does not seem to work. Perhaps we do not have a phrasal verb here. What does the sentence mean exactly?
P.S.
In Macmillan Dictionary, there are five senses for hold up:
hold something high
prevent someone/something from falling
cause a delay
steal by threat of violence
stay in good condition

I think in this context the sense prevent someone/something from falling works flawlessly.

A: I think that in this sentence hold up means the same as support, carry or shoulder the weight. The sky is above us and it takes, metaphorically, a lot of work to keep it up there.

In other words, your interpretation prevent something from falling is a good match.

Compare with Atlas from Greek mythology, condemned to hold up all of the heavens by himself.
Mao used this saying in one of his speeches, commending women for their role in building/running the society. Anyway, the meaning is just that. Women amount to half the population and hence half the workforce. People entertaining traditional gender roles may occasionally forget this, and this saying is an eloquent reminder.


text:
Q: Customise as_json response in ruby I am building rest APIs in ruby
I am using @object.as_json() for the response in json format
I am getting stuck in the mid while transfer the data in as_json. I need to more customize the response
I am listing what exactly I want and where I am getting stuck
I am using below code
@videos = Video.all.map{|m| m.as_json(
  only: [:title],
  method: [:watch_count],
  include: {
    user: {
      only: [:first_name],
      method: [:role]
    }
  }
).merge(
    is_upvoted: m.is_upvoted(current_user)
) }

But I need to customise it.
1- I need to pass manual key and value (which is not in db) in video and user object, currently it can be possible with video but not with user. It should e possible with parent object and its child associate object. I don't want to to use :method for the same
2-I need to pass parameter in :method, like video model has a method is_upvoted but having a parameter like current user. So I am unable to pass parameter in :method. currently I can do with merge as I am doing but It can not be possible with user object.
3- I need to change key name while use include: {user: {method: []}}.
I need to use key "owner" at the place of "user"
Many Thanks in Advance

A: You can do it with JBuilder, which much more flexible and allow to make all things from your list. Result code will be like this:
@videos = JBuilder.encode do |json|
  json.array! Video.all do |video|
    json.(video, :title, :watch_count)
    json.is_upvoted video.is_upvoted(current_user)

    json.owner do
      json.(video.user, :first_name, :role)
      json.field video.user.with_param(some_param)
    end
  end
end

You may find details about JBuilder in documentation.


text:
Q: Convert Custom Script Tags Into A New Script With Anchor Tags Via PHP I need some help with converting a string in PHP. I've been trying to do this for hours but I can only seem to convert simple scripts with str_replace().
I'm trying to convert the custom script below:
<start=0:03>Line one goes here<end=0:09>
<start=0:09>Line two goes here<end=0:12>
<start=0:20>Line three goes here<end=0:26>
<start=0:32>Line four goes here<end=0:42>

Into a new script with anchor tags like this:
Line one goes here
Line two goes here
Line three goes here
Line four goes here

Can anyone help please?
Thank you.

A: For this kind of a little elaborate search/replacement, the most handy is to use a regex pattern with preg_replace:
$re = '/<(start=\d+:\d+)(>.*?<)(end=\d+:\d+)>/s';
$subst = '';
$result = preg_replace($re, $subst, $yourstring);

pattern details:
/                  # pattern delimiter
<                  # literal <
(start=\d+:\d+)    # group 1: literal "start=", one or more digits,
                   # literal ":" and one or more digits
(>.*?<)            # group 2: literal >, all characters until <, that must be followed
(end=\d+:\d+>)     # by capture the group 3
/s                 # pattern delimiter, and s modifier

By default the . matches all characters except the newline character, the s modifier allows it to match newlines too.
replacement:
$1, $2, $3 refers to the content captured by the groups


text:
Q: Is it possible to extract class/interface functions with ts-json-schema-generator? I am working on a Builder for a typescript sdk library and I am trying to extract all the sdk classes with their respective functions into a json that the Builder can use.
I am trying to accomplish this:
class Form {
 propA: string
 propB: string

 funcA(value: boolean, text: string) {
 ...
 }
}

to
{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "definitions": {
    "Form": {
      "type": "object",
      "properties": {
        "propA": {
          "type": "string"
        },
        "propB": {
          "type": "string"
        },
        "NamedParameters<typeof funcA>": {
          "type": "object",
          "properties": {
            "value": {
              "type": "boolean"
            },
            "text": {
              "type": "string"
            }
          },
          "required": [
            "value",
            "text"
          ],
          "additionalProperties": false
        }
      },
      "additionalProperties": false
    }
  }
}

But there seems to be no way to accomplish this. Does anyone know an alternative or a solution?


text:
Q: Benchmarking in V10.1.0 not showing the correct verision of Mathematica? Bug introduced in 10.1 and fixed in 10.3

This was done in V10.1.0, but it's showing that as if it was done in V10.0.0?
Computer Specs:(for those who are interested)
CPU:  i7 4790K
RAM:  32GB (4 X 8G)
GPU:  GTX980M

Just bought this for my research last week!

A: This has been fixed as of version 10.3.0.


text:
Q: dir-paginate in table with nested ng-repeat I'm using dir-paginate in a table which is a populated from nested ng-repeat data.
Tables are correctly populated but sorting and pagination when done in one table is resulting all remaining tables also. I used track by $index also, but not working.

    {{PData.item}}

   <tr dir-paginate="item in pData.appraisals|orderBy:sortKey:reverse|filter:GenericSearch|itemsPerPage
:10" pagination-id="policyHolderAppraisals"

 {{item.b}}
 {{item.a}}

A: Yes this can be done by using the  pagination-id to uniquely identify and group each pagination control for sorting, filtering etc.
e.g.

{{ customer.name }}

<dir-pagination-controls pagination-id="cust"></dir-pagination-controls>

{{ customer.name }}

<dir-pagination-controls pagination-id="branch"></dir-pagination-controls>

More information can be found here
https://github.com/michaelbromley/angularUtils/tree/master/src/directives/pagination#multiple-pagination-instances-on-one-page


text:
Q: enable submit when date is selected from datepicker submit button gets enabled when I type date manually but when I select it from datepicker it does not gets enabled
<html>
<body>
    <input type="date" id="txt" onkeyup="manage(this)" class="form-control" name=<?php echo 'actual_date__' . $cur['id'] . '__' . $cur['master_id'] ?> value="<?php echo $filtered_row_result1["actual_date"] ?? ''; ?>" >
    <input type="submit" id="btSubmit" disabled />
</body>
<script>
    function manage(txt) {
        var bt = document.getElementById('btSubmit');
        if (txt.value != '') {
            bt.disabled = false;
        }
        else {
            bt.disabled = true;
        }
    }
<script>
</html>

A:

<html>
<body>
    <input type="date" id="txt" onchange="manage(this)" class="form-control" name="_name" value="1990-01-01" >
    <input type="submit" id="btSubmit" disabled />
</body>
<script>
    function manage(txt) {
    console.log(txt);
        let bt = document.getElementById('btSubmit');
        if (txt.value != '') {
            bt.disabled = false;
        }
        else {
            bt.disabled = true;
        }
    }
</script>
</html>

check out this solution. I changed the input name - because I can't use php here. change to yours

A: Use onchange instead of onkeyup

function manage(txt) {
  var bt = document.getElementById('btSubmit');
  if (txt.value != '') {
    bt.disabled = false;
  } else {
    bt.disabled = true;
  }
}
<html>

<body>
  <input type="date" id="txt" onchange="manage(this)" class="form-control" name=<?php echo 'actual_date__' . $cur[ 'id'] . '__' . $cur[ 'master_id'] ?> value="
  <?php echo $filtered_row_result1["actual_date"] ?? ''; ?>" >
  <input type="submit" id="btSubmit" disabled />
</body>

</html>