Q: adding inertia to a UIPanGestureRecognizer I am trying to move a sub view across the screen which works, but i also want to add inertia or momentum to the object.
My UIPanGestureRecognizer code that i already have is below.
Thanks in advance.
UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self       action:@selector(handlePan:)];
[self addGestureRecognizer:panGesture];

(void)handlePan:(UIPanGestureRecognizer *)recognizer
{

    CGPoint translation = [recognizer translationInView:self.superview];
    recognizer.view.center = CGPointMake(recognizer.view.center.x + translation.x,
                                     recognizer.view.center.y + translation.y);
    [recognizer setTranslation:CGPointMake(0, 0) inView:self.superview];

    if (recognizer.state == UIGestureRecognizerStateEnded) {
        [self.delegate card:self.tag movedTo:self.frame.origin];
    }
}

Again thanks.

A: Have a look at RotationWheelAndDecelerationBehaviour.  there is an example for how to do the deceleration for both linear panning and rotational movement. Trick is to see what is the velocity when user ends the touch and continue in that direction with a small deceleration.

A: Well, I'm not a pro but, checking multiple answers, I managed to make my own code with which I am happy.
Please tell me how to improve it and if there are any bad practices I used.
- (IBAction)handlePan:(UIPanGestureRecognizer *)recognizer {

CGPoint translatedPoint = [recognizer translationInView:self.postViewContainer];
CGPoint velocity = [recognizer velocityInView:recognizer.view];

float bottomMargin = self.view.frame.size.height - containerViewHeight;
float topMargin = self.view.frame.size.height - scrollViewHeight;

if ([recognizer state] == UIGestureRecognizerStateChanged) {

    newYOrigin = self.postViewContainer.frame.origin.y + translatedPoint.y;

    if (newYOrigin <= bottomMargin  && newYOrigin >= topMargin) {
        self.postViewContainer.center = CGPointMake(self.postViewContainer.center.x, self.postViewContainer.center.y + translatedPoint.y);
    }
    [recognizer setTranslation:CGPointMake(0, 0) inView:self.postViewContainer];
}

if ([recognizer state] == UIGestureRecognizerStateEnded) {

    __block float newYAnimatedOrigin = self.postViewContainer.frame.origin.y + (velocity.y / 2.5);

    if (newYAnimatedOrigin <= bottomMargin && newYAnimatedOrigin >= topMargin) {
        [UIView animateWithDuration:1.2 delay:0
                            options:UIViewAnimationOptionCurveEaseOut
                         animations:^ {
                             self.postViewContainer.center = CGPointMake(self.postViewContainer.center.x, self.postViewContainer.center.y + (velocity.y / 2.5));
                         }
                         completion:^(BOOL finished) {
                             [self.postViewContainer setFrame:CGRectMake(0, newYAnimatedOrigin, self.view.frame.size.width, self.view.frame.size.height - newYAnimatedOrigin)];
                         }
         ];
    }
    else {
        [UIView animateWithDuration:0.6 delay:0
                            options:UIViewAnimationOptionCurveEaseOut
                         animations:^ {
                             if (newYAnimatedOrigin > bottomMargin) {
                                 self.postViewContainer.center = CGPointMake(self.postViewContainer.center.x, bottomMargin + self.postViewContainer.frame.size.height / 2);
                             }

                             if (newYAnimatedOrigin < topMargin) {
                                 self.postViewContainer.center = CGPointMake(self.postViewContainer.center.x, topMargin + self.postViewContainer.frame.size.height / 2);
                             }
                         }
                         completion:^(BOOL finished) {
                             if (newYAnimatedOrigin > bottomMargin)
                                 [self.postViewContainer setFrame:CGRectMake(0, bottomMargin, self.view.frame.size.width, scrollViewHeight)];

                             if (newYAnimatedOrigin < topMargin)
                                 [self.postViewContainer setFrame:CGRectMake(0, topMargin, self.view.frame.size.width, scrollViewHeight)];
                         }
         ];
    }
}

}
I have used two different animation, one is the default inertia one and the other if for when the user flings the containerView with high velocity.
It works well under iOS 7.

A: I took the inspiration from the accepted answer's implementation. Here is a Swift 5.1 version.

Logic:

*

*You need to calculate the angle changes with the velocity at which the pan gesture ended and keep rotating the wheel in an endless timer until the velocity wears down because of deceleration rate.

*Keep decreasing the current velocity in every iteration of the timer
with some factor (say, 0.9).

*Keep a lower limit on the velocity to
invalidate the timer and complete the deceleration process.

Main function used to calculate deceleration:
// deceleration behaviour constants (change these for different deceleration rates)
private let timerDuration = 0.025
private let decelerationSmoothness = 0.9
private let velocityToAngleConversion = 0.0025

private func animateWithInertia(velocity: Double) {
    _ = Timer.scheduledTimer(withTimeInterval: self.timerDuration, repeats: true) { [weak self] timer in
        guard let this = self else {
            return
        }
        let concernedVelocity = this.currentVelocity == 0.0 ? velocity : this.currentVelocity
        let newVelocity = concernedVelocity * this.decelerationSmoothness
        this.currentVelocity = newVelocity
        var angleTraversed = newVelocity * this.velocityToAngleConversion * this.maximumRotationAngleInCircle
        if !this.isClockwiseRotation {
            angleTraversed *= -1
        }
        // exit condition
        if newVelocity < 0.1 {
            timer.invalidate()
            this.currentVelocity = 0.0
        } else {
            this.traverseAngularDistance(angle: angleTraversed)
        }
    }
}

Full working code with helper functions, extensions and usage of aforementioned function in the handlePanGesture function.
// deceleration behaviour constants (change these for different deceleration rates)
private let timerDuration = 0.025
private let decelerationSmoothness = 0.9
private let velocityToAngleConversion = 0.0025

private let maximumRotationAngleInCircle = 360.0

private var currentRotationDegrees: Double = 0.0 {
    didSet {
        if self.currentRotationDegrees > self.maximumRotationAngleInCircle {
            self.currentRotationDegrees = 0
        }
        if self.currentRotationDegrees < -self.maximumRotationAngleInCircle {
            self.currentRotationDegrees = 0
        }
    }
}
private var previousLocation = CGPoint.zero
private var currentLocation = CGPoint.zero
private var velocity: Double {
    let xFactor = self.currentLocation.x - self.previousLocation.x
    let yFactor = self.currentLocation.y - self.previousLocation.y
    return Double(sqrt((xFactor * xFactor) + (yFactor * yFactor)))
}

private var currentVelocity = 0.0
private var isClockwiseRotation = false

@objc private func handlePanGesture(panGesture: UIPanGestureRecognizer) {
    let location = panGesture.location(in: self)

    if let rotation = panGesture.rotation {
        self.isClockwiseRotation = rotation > 0
        let angle = Double(rotation).degrees
        self.currentRotationDegrees += angle
        self.rotate(angle: angle)
    }

    switch panGesture.state {
    case .began, .changed:
        self.previousLocation = location
    case .ended:
        self.currentLocation = location
        self.animateWithInertia(velocity: self.velocity)
    default:
        print("Fatal State")
    }
}

private func animateWithInertia(velocity: Double) {
    _ = Timer.scheduledTimer(withTimeInterval: self.timerDuration, repeats: true) { [weak self] timer in
        guard let this = self else {
            return
        }
        let concernedVelocity = this.currentVelocity == 0.0 ? velocity : this.currentVelocity
        let newVelocity = concernedVelocity * this.decelerationSmoothness
        this.currentVelocity = newVelocity
        var angleTraversed = newVelocity * this.velocityToAngleConversion * this.maximumRotationAngleInCircle
        if !this.isClockwiseRotation {
            angleTraversed *= -1
        }
        if newVelocity < 0.1 {
            timer.invalidate()
            this.currentVelocity = 0.0
            this.selectAtIndexPath(indexPath: this.nearestIndexPath, shouldTransformToIdentity: true)
        } else {
            this.traverseAngularDistance(angle: angleTraversed)
        }
    }
}

private func traverseAngularDistance(angle: Double) {
    // keep the angle in -360.0 to 360.0 range
    let times = Double(Int(angle / self.maximumRotationAngleInCircle))
    var newAngle = angle - times * self.maximumRotationAngleInCircle
    if newAngle < -self.maximumRotationAngleInCircle {
        newAngle += self.maximumRotationAngleInCircle
    }
    self.currentRotationDegrees += newAngle
    self.rotate(angle: newAngle)
}

Extensions being used in above code:
extension UIView {
    func rotate(angle: Double) {
        self.transform = self.transform.rotated(by: CGFloat(angle.radians))
    }
}

extension Double {
    var radians: Double {
        return (self * Double.pi)/180
    }

    var degrees: Double {
        return (self * 180)/Double.pi
    }
}


Q: nullpointerexecption when trying to execute delete method of databasehelper I'm new to android and i m creating application contact application
I m trying to delete a row from table but its giving me nullpointerexception as shown in log below
this indicates that delete method is getting null value but through bundle i m getting the correct value and i m passing the same val in deketecontact method.
com.example.ViewRecord
public class ViewRecord extends Activity {
int val;
SQLiteDatabase sdb;
databaseHelper dbh;
//=new databaseHelper(getBaseContext(), "stud", null, 1);
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_view_record);
    Bundle b = getIntent().getExtras();
    if(b!=null){
        String n=b.getString("pname").toUpperCase(Locale.ENGLISH);
        TextView t= (TextView) findViewById(R.id.tv1);
        t.setText("WELCOME "+ n);
        val = b.getInt("pid");

    }
    Button del= (Button) findViewById(R.id.button1);
    del.setOnClickListener(new OnClickListener() {

        public void onClick(View v) {
            // TODO Auto-generated method stub
            AlertDialog.Builder builder = new AlertDialog.Builder(ViewRecord.this);
            builder.setMessage(R.string.deleteContact)
           .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
               public void onClick(DialogInterface dialog, int id) {
                  dbh.deleteContact(val);
                  Toast.makeText(getApplicationContext(), "Deleted Successfully",
                  Toast.LENGTH_SHORT).show();
                  Intent intent = new Intent(getApplicationContext(),AddRecord.class);
                  startActivity(intent);
               }
            })
           .setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
               public void onClick(DialogInterface dialog, int id) {
                  // User cancelled the dialog
               }
            });
            AlertDialog d = builder.create();
            d.setTitle("Are you sure");
            d.show();

        }
    });
}

}

  //and this is delete method in databasehelper.class
  public Integer deleteContact (Integer id)
   {
      Log.d("val1", ""+id);
      SQLiteDatabase db = this.getWritableDatabase();
     // db.delete("studrec", "id=", null);
      return db.delete("studrec",
      "id = ? ",new String[] { Integer.toString(id) });
   }

log file
    01-10 19:19:00.680: E/AndroidRuntime(10261): FATAL EXCEPTION: main
01-10 19:19:00.680: E/AndroidRuntime(10261): Process: com.assign6, PID: 10261
01-10 19:19:00.680: E/AndroidRuntime(10261): java.lang.NullPointerException: Attempt to invoke                                   virtual method 'java.lang.Integer com.assign6.databaseHelper.deleteContact(java.lang.Integer)' on a null object reference
01-10 19:19:00.680: E/AndroidRuntime(10261):    at com.assign6.ViewRecord$1.onClick(ViewRecord.java:66)
01-10 19:19:00.680: E/AndroidRuntime(10261):    at android.view.View.performClick(View.java:4756)
01-10 19:19:00.680: E/AndroidRuntime(10261):    at android.view.View$PerformClick.run(View.java:19749)
01-10 19:19:00.680: E/AndroidRuntime(10261):    at android.os.Handler.handleCallback(Handler.java:739)
01-10 19:19:00.680: E/AndroidRuntime(10261):    at android.os.Handler.dispatchMessage(Handler.java:95)
01-10 19:19:00.680: E/AndroidRuntime(10261):    at android.os.Looper.loop(Looper.java:135)
01-10 19:19:00.680: E/AndroidRuntime(10261):    at android.app.ActivityThread.main(ActivityThread.java:5221)
01-10 19:19:00.680: E/AndroidRuntime(10261):    at java.lang.reflect.Method.invoke(Native Method)
01-10 19:19:00.680: E/AndroidRuntime(10261):    at java.lang.reflect.Method.invoke(Method.java:372)
01-10 19:19:00.680: E/AndroidRuntime(10261):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
01-10 19:19:00.680: E/AndroidRuntime(10261):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)

A:
NullPointerException: Attempt to invoke virtual method
  'java.lang.Integer com.example.databaseHelper.deleteContact

Because you are not initializing dbh object of databaseHelper class before calling deleteContact using dbh object. Initialize it before calling method:
dbh=new databaseHelper(...);
dbh.deleteContact(val);


Q: how to feed the `find` output as the argument for bash? I find a list of bam files using
$bams=$(find /data/and/ -type f -regex ".*\.bam")
#/data/DNA128441.bam
#/data/DNA128442.bam
#/data/DNA128443.bam

And wanted to feed in a script test.sh
#!/bin/bash
bam="$@"
echo "You provided the arguments:" ${bam}
s=${bam##*/}
r1=${s%.bam}_R1.fastq
r2=${s%.bam}_R2.fastq
echo $r1
echo $r2

But when I run:
$bams=$(find /data/and/ -type f -regex ".*\.bam")
./test.sh $bam
You provided the arguments: /data/and/DNA128441.bam /data/and/DNA128342.bam /data/and/DNA128343.bam
DNA128343_R1.fastq
DNA128343_R2.fastq

My question is how to make it process one by one such like a desired output:
$bams=$(find /data/and/ -type f -regex ".*\.bam")
./test.sh $bam
You provided the arguments: /data/and/DNA128341.bam
DNA128341_R1.fastq
DNA128341_R2.fastq
You provided the arguments: /data/and/DNA128342.bam
DNA128342_R1.fastq
DNA128342_R2.fastq
You provided the arguments: /data/and/DNA128343.bam
DNA128343_R1.fastq
DNA128343_R2.fastq


Q: How can UTF 8 encoding in a varchar field be transfered to an nvarchar field? The UTF-8 characters (nearly a million records) were imported into varchar(max) as western european.  Is there any known method of fixing this in SQL? We have verified that the "garbage" characters that are showing up are, in fact, based on the incorrect characters in the Western European encoding representing the UTF-8 hexidecimal values.  It would seem that the underlying hexidecimal in varchar field is correct.  Ideally we would like to be able to fix this in SQL rather than re-importing the data.

A: You'll need to re-import the data directly into an nvarchar column.

A: I've only seen application-side coding conversions used to fix the scenario you described (converting from UTF-8 to UTF16 or UCS2 format).


Q: How to prevent vaadin default styles and how to increase width and height of textfield I am developing application using vaadin framework. I am new in vaadin framework.
I have lot of confusion in designing.
1) I am creating layout to display loginform  but it will come with some default styles. That styles collapsed my desgin.
Please any one say How can I remove or prevent that vaadin default styles.
2) If I increase text-field height it automatically changed to text-area.
Please help any one How can I increase text-field height.

A: answer for number 2 :
Setting height for TextField also has a side-effect that puts TextField into multiline mode (aka "textarea"). Multiline mode can also be achieved by calling setRows(int). The height value overrides the number of rows set by setRows(int).
If you want to set height of single line TextField, call setRows(int) with value 0 after setting the height. Setting rows to 0 resets the side-effect.

A: I cannot see any function setRow and setHeight doesnt allow to edit more lines. Only one line vertically i middle. Vaadin 7

A: for question 1, you should first setPrimaryStyleName and if you need other style, addStyleName


Q: C# Google Sheets API - Delete Row I searched everything already on the whole internet :) and did not find a solution for this.
I can add new rows, update old rows and do a lot of things in google sheets via C#, but I can't delete a row in a google sheet... can someone, please help me with this?
[EDITED]
OK, I finally found how to delete the rows...
So, what I had to do was first to build list of all indexes that are to be deleted. After doing that I had to build list of key pairs values with start and end of the index to delete, BUT for the end I had to add +1, as it seems like starts and ends are not deleted, only things that are between..
Finally I had to loop the list of key pairs from the end till the start and this deleted the rows...
The code to delete is here. Maybe this will help someone else who is looking how to delete rows in google sheets:
   List<KeyValuePair<int, int>> _listStartEndIndexToDelete = new List<KeyValuePair<int, int>>();
    List<int> _tempListOfAllIndex = new List<int>();

    for (int i = 1; i <= ValuesInternal.Values.Count() - 1; i++)
    {
        if (ValuesInternal.Values[i][1] != null && ValuesInternal.Values[i][1].ToString().ToUpper() == "TASK COMPLETE")
        {
            _tempListOfAllIndex.Add(i);
        }
    }

    for (int rowNumber = 0; rowNumber <= _tempListOfAllIndex.Count() - 1; rowNumber++)
    {
        int tempStart = _tempListOfAllIndex[rowNumber];
        if(rowNumber != _tempListOfAllIndex.Count() - 1)
        {
            while (_tempListOfAllIndex[rowNumber] + 1 == _tempListOfAllIndex[rowNumber + 1])
            {
                rowNumber++;
                if (rowNumber == _tempListOfAllIndex.Count() - 1) { break; }
            }
        }

        int tempEnd = _tempListOfAllIndex[rowNumber] + 1;

        KeyValuePair<int, int> tempPair = new KeyValuePair<int, int>(tempStart, tempEnd);
        _listStartEndIndexToDelete.Add(tempPair);
    }

    for(int keyValuePair = _listStartEndIndexToDelete.Count()-1; keyValuePair >= 0; keyValuePair--)
    {
        List<Request> deleteRequestsList = new List<Request>();
        BatchUpdateSpreadsheetRequest _batchUpdateSpreadsheetRequest = new BatchUpdateSpreadsheetRequest();
        Request _deleteRequest = new Request();
        _deleteRequest.DeleteDimension = new DeleteDimensionRequest();
        _deleteRequest.DeleteDimension.Range = new DimensionRange();
        _deleteRequest.DeleteDimension.Range.SheetId = SheetIDnumberWhereDeleteShouldBeDone;
        _deleteRequest.DeleteDimension.Range.Dimension = "ROWS";
        _deleteRequest.DeleteDimension.Range.StartIndex = _listStartEndIndexToDelete[keyValuePair].Key;
        _deleteRequest.DeleteDimension.Range.EndIndex = _listStartEndIndexToDelete[keyValuePair].Value;

        deleteRequestsList.Add(_deleteRequest);
        _batchUpdateSpreadsheetRequest.Requests = deleteRequestsList;
        sheetsService.Spreadsheets.BatchUpdate(_batchUpdateSpreadsheetRequest, SheetIDInternal).Execute();
    }

A: I checked the links that You provided here, but non of them solved the problem.
For example this one:
Request request = new Request()
  .setDeleteDimension(new DeleteDimensionRequest()
    .setRange(new DimensionRange()
      .setSheetId(0)
      .setDimension("ROWS")
      .setStartIndex(30)
      .setEndIndex(32)
    )
  );

The problem is that, there is no such a thing like .setDeleteDimension under Request. This shouldn't be such a problem, but it is....
Below You can find my code. What does it do, is to take data from one sheet (internal) and put it to another sheet (internal archive). When this is done (and this works well), I want to delete data from internal as it is already archived... and that part is not working. I just don't know how to delete the rows.. if anyone could have a look on this, it would be great. Thanks for your help...
public void RunArchiveInternal2(bool testRun)
{
    //internal
    string SheetIDInternal = "googlesheetid_internal";
    string RangeInternal = testRun ? "test_task tracking" : "Task Tracking - INTERNAL";
    SpreadsheetsResource.ValuesResource.GetRequest getRequestInternal = sheetsService.Spreadsheets.Values.Get(SheetIDInternal, RangeInternal);
    ValueRange ValuesInternal = getRequestInternal.Execute();

    //internal archive
    string SheetIDInternalArchive = "googlesheetid_internal_archive";
    string RangeInternalArchive = testRun ? "test_archive_internal" : "Sheet1";
    SpreadsheetsResource.ValuesResource.GetRequest getRequestInternalArchive = sheetsService.Spreadsheets.Values.Get(SheetIDInternalArchive, RangeInternalArchive);
    ValueRange ValuesInternalArchive = getRequestInternalArchive.Execute();

    //Get data from internal and put to internal archive
    List<IList<object>> listOfValuesToInsert = new List<IList<object>>();

    for (int i = 1; i <= ValuesInternal.Values.Count() - 1; i++)
    {
        List<object> rowToUpdate = new List<object>();

        if (ValuesInternal.Values[i][1] != null && ValuesInternal.Values[i][1].ToString().ToUpper() == "TASK COMPLETE")
        {
            rowToUpdate = (List<object>)ValuesInternal.Values[i];
            listOfValuesToInsert.Add(rowToUpdate);
        }
    }
    SpreadsheetsResource.ValuesResource.AppendRequest insertRequest = sheetsService.Spreadsheets.Values.Append(new ValueRange { Values = listOfValuesToInsert }, SheetIDInternalArchive, RangeInternalArchive + "!A1");
    insertRequest.ValueInputOption = SpreadsheetsResource.ValuesResource.AppendRequest.ValueInputOptionEnum.USERENTERED;
    insertRequest.Execute();

    //delete things from internal
    BatchUpdateSpreadsheetRequest batchUpdateSpreadsheetRequest = new BatchUpdateSpreadsheetRequest();
    List<DeleteDimensionRequest> requests = new List<DeleteDimensionRequest>();

    for (int i = ValuesInternal.Values.Count() - 1; i >= 1; i--)
    {
        DeleteDimensionRequest request = new DeleteDimensionRequest();
        //Request request = new Request();

        if (ValuesInternal.Values[i][1] != null && ValuesInternal.Values[i][1].ToString().ToUpper() == "TASK COMPLETE")
        {
            request.Range = new DimensionRange
            {
                Dimension = "ROWS",
                StartIndex = i,
                EndIndex = i
            };
            requests.Add(request);
        }
    }
    batchUpdateSpreadsheetRequest.Requests = requests;//this is wrong
    SpreadsheetsResource.BatchUpdateRequest Deletion = sheetsService.Spreadsheets.BatchUpdate(batchUpdateSpreadsheetRequest, SheetIDInternal);
    Deletion.Execute();
}


Q: PHP Website - Navigation links with sub directories I have a site with this directory structure:
index.php
folder1/index.php
folder2/index.php
inc/nav.php

All the index.php pages include the nav.php page which contains the top horizontal navigation bar, e.g.:
<?php include_once 'inc/nav.php' ?>

Inside the nav.php file are the links to various pages, eg. home and logout etc. These work fine when on the index.php file at the site root, but when on any of the index.php pages in any of the subfolders these don't work as they link to:
http://www.mywebsite.com/folder1/logout.php

whereas the link should be to:
http://www.mywebsite.com/logout.php

The nav.php has links like this:

 Logout

so I see how that only works when called from the root index.php page but can't work out how to have it so that it works from any index.php page whether at the site root level or a subfolder.

A: Assuming that you've logout.php on the root, use a slash before the page name like this, to point the page from the root.

 Logout

As what you are using is just logout.php which will point the page name in that specific directory, but the server will return 404 as it may be available when you are on the root, but it will fail when you are in the directory.
If it still complicates the navigation, you can also use if conditions to change the paths accordingly.


Q: Remove/delete embeds from a message I made my own Discord bot for my Minecraft server with an order system (for developers).
When you react on the ,essage for the order, the message should edit to The Order was claimed by @Discord
And that works, but I also want to remove the EmbedMessage, that was sent with.
But there doesn't exists a method like message.removeEmbeds() or message.deleteEmbeds().
So, how is it possible to do that?

A: The documentation for MessageAction explains:

When updating a Message, unset fields will be ignored by default. To override existing fields with no value (remove content) you can use override(true). Setting this to true will cause all fields to be considered and will override the Message entirely causing unset values to be removed from that message.
This can be used to remove existing embeds from a message:
message.editMessage("This message had an embed").override(true).queue()


Q: pass std::map object to thread Mycode is trying to pass a std::map as reference to thread but it seems something is bad and result in
error: invalid conversion from ‘void* (*)(std::map<std::basic_string<char>,
       std::vector<std::basic_string<char> > >)’ to ‘void* (*)(void*)’ [-fpermissive]

I need to pass
map to thread and insert the key and value of map in that thread and after successful. In main process i need to update or copy(thread map) in another object of same map i.e myMapcache
int main()
{
std::map< std::pair<std::string , std::string> , std::vector<std::string> > myMap,myMapCache;

  pthread_t threads;

  //how to pass map object in thread as reference

  int rc = pthread_create(&threads, NULL, myfunction, std::ref(myMap));
  if (rc)
  {
     cout << "Error:unable to create thread," << rc << endl;
     exit(-1);
   }

   // if true then update to local myMapCache

   if(update)
    {
      std::copy(myMap.begin(), myMap.end(), std::inserter(MyMapCache, myMapCache.end()) );
    }

}

void * myfunction (std::map< std::pair<std::string , std::string> , std::vector<std::string> >& myMap)
{

  // here i will insert data in a map
  myMap[std::make_pair(key1,key2)].push_back(value);

  // if update make the flag true
    Update=true;

}

A: pthread_create is not a template, and it does not understand C++ types. It takes a void*, which is what C libraries do in order to fake templates (kind of).
You can pass a casted pointer instead of a C++ reference wrapper object:
int rc = pthread_create(&threads, NULL, myfunction, static_cast<void*>(&myMap));
// ...
void* myfunction(void* arg)
{
   using T = std::map<std::pair<std::string, std::string>, std::vector<std::string>>;
   T& myMap = *static_cast<T*>(arg);

…or, better yet, use boost::thread (C++98) or std::thread (C++11 and later) to get type safety and a longer lifespan. You're not writing a C program.


Q: Is Google App Engine better than Webfaction for a beginner in Django dev? I am a beginner in developing websites by Django.
I run small discussion websites similar to SO.
I have an account at Bluehost which has been a nightmare in developing by Django.
I have found that Webfaction and Google App Engine seems to be the best choices for Django.
However, I am not sure which one is the best for me.
Is Google App Engine better than Webfaction in running small websites?

A: I can't speak for Google App Engine, but as a rather recent Django user myself I recently moved my development site over to a WebFaction server and I must say I was extremely impressed. They are extremely friendly to Django setups (among others) and the support staff answered any small problems I had promptly. I would definitely recommend them.
For other Django-friendly hosts, check out Djangofriendly.com.

A: If you have already written your django application, it may be really difficult to install it on Google App Engine, since you will have to adapt your data model. GAE uses big table, a (key,data) store, instead of a traditional relational model. It is great for performance but makes your programming more difficult (no built in many-to-many relationship handlers, for example).
Furthermore, most apps available for django will not work on GAE since these apps use the relational data model. The most obvious problem is that the great admin app of django will not work. Furthermore, GAE tends to make you use google accounts for identification. This can be circumvented but again, not using readily available django apps.  This could be great for you, but it can be a hassle (for example, lots of user names are already taken at google).
So, my final advice is that, if you are a beginner, you should avoid GAE.
If you are based in Europe, djangohosting.ch is also a good choice, instead of webfaction.

A: A bit late with my answer, but nevertheless... I am Django beginner and have my first Django App up and running at GAE. It was App Engine Patch that made it happen. Using it you have django admin and several other apps available out of the box. If you'd like to try it, go for the trunk version. This project is reasonably well documented and have responsive community.

A: I'm a Google app engine developer, so I can't say much about webfaction, but as far as I have used it setting up a web app with app-engine is pretty straight forward¹. The support staff however is not quite good.
1- http://code.google.com/appengine/articles/django.html

A: Webfaction:
Plus:

*

*Great shell access. Ability to install python modules, or anything else you might need. You will love checking out source code from shell to update your production (no need for FTPing anything anymore!)

*Very good performance and reliability

*Great support + wealth of info on help knowledge base and in the forums. (FORGET bluehost or anything else you ever tried). I was surprised by amount of answers I found to what I thought would be difficult questions.

*You can use regular database and you can do joins (see app engine minus #2)

Minus:

*

*Setting up initial deployment can be a bit tricky the first few times around (as is to be expected from shell).

*Growing-scaling can be expensive and you probably will not survive beign "slashdotted"

App Engine
Plus:

*

*Free to start with

*Initial database is easier to setup.

*Deployment is a breeze

*Enforcement of "good" design principles from the start which help you with #5. (Such as hard limits, db denormalizing etc)

*Scalability (but this does not come free - you need to think ahead).

*No maintanence: auto backups, security comes for free, logging + centralized dashboard, software updates are automatic.

Minus:

*

*Setting up Django on App Engine is not so straightforward, as well as getting used to this setup. The webapp framework from google is weak.

*Database model takes a little bit of time to wrap your head around. THis is not your moma's SQL server. For example you have to denormalize your DB from the start, and you cannot do Joins (unless they are self joins)

*The usual things you are used to are not always there. Some things such as testing and data-importing are not that easy anymore.

*You are tied down to App Engine and migrating your data to another DB or server, while not impossible, is not easy. (Not that you do data migration that often! Probably never)

*Hard limits in requests, responses and file sizes (last time I heard about 1MB).

*App Engine currently supports Python 2.5 only.

Can't think of anything else so far.
I am currently with Webfaction and am testing App Engine as well. I have no difficulty going from Django-Webfaction to App-Engine way of thinking. However, I am not sure if the AppEngine -> Standalone servers route would be just as easy.
References
Talks:

*

*Guido on Google App Engine http://www.youtube.com/watch?v=CmyFcChTc4M

*Task Queues in App Engine: http://www.youtube.com/watch?v=o3TuRs9ANhs

A: The thing to remember about GAE is that it works differently than a standard python install and apps you have may not work well (or at all) in that environment.  The biggest difference is the database.  While there are advantages to the non-relational database available with GAE, you need to treat it differently and there are many things that your code may be expecting your database to be able to do that it cannot.
If you are starting from scratch on an app, either platform would work fine.  If you have an existing python app, getting it to work on GAE will take considerable work.


Q: Not able to globally install electron on MacOS due to error I'm getting an error while trying to globally install electron, I'm not sure why.
npm ERR! code 1
npm ERR! path /usr/local/lib/node_modules/electron
npm ERR! command failed
npm ERR! command sh -c node install.js
npm ERR! HTTPError: Response code 404 (Not Found) for https://github.com/electron/electron/releases/download/v19.0.9/electron-v19.0.9-darwin-ia32.zip
npm ERR!     at EventEmitter.<anonymous> (/usr/local/lib/node_modules/electron/node_modules/got/source/as-stream.js:35:24)
npm ERR!     at EventEmitter.emit (node:events:390:28)
npm ERR!     at module.exports (/usr/local/lib/node_modules/electron/node_modules/got/source/get-response.js:22:10)
npm ERR!     at ClientRequest.handleResponse (/usr/local/lib/node_modules/electron/node_modules/got/source/request-as-event-emitter.js:155:5)
npm ERR!     at Object.onceWrapper (node:events:510:26)
npm ERR!     at ClientRequest.emit (node:events:402:35)
npm ERR!     at ClientRequest.origin.emit (/usr/local/lib/node_modules/electron/node_modules/@szmarczak/http-timer/source/index.js:37:11)
npm ERR!     at HTTPParser.parserOnIncomingClient [as onIncoming] (node:_http_client:623:27)
npm ERR!     at HTTPParser.parserOnHeadersComplete (node:_http_common:128:17)
npm ERR!     at TLSSocket.socketOnData (node:_http_client:487:22)

npm ERR! A complete log of this run can be found in:

A: For some reason I don't know, your npm tries to install Electron with the ia32 architecture, resulting in a downloadable zip file which is not provided by the Electron maintainers. That's why you're getting a 404 HTTP status code.
Going back in Electron's releases page, I cannot seem to find any darwin-ia32 assets (darwin is the codeame for macOS).
You can try forcing npm to install the appropriate architecture using
npm install --arch=x64 electron

as suggested in Electron's installation guide.


Q: What axioms are stronger than the Axiom of choice? What other axioms in set theory are stronger than AC ? I mean what are those axioms that will imply AC ?

A: *

*The axiom For every infinite set $X$ if $Y$ is such that $|X|\lt|Y|$ and $|Y|\leq|\mathcal P(X)|$, then $|Y|=|\mathcal P(X)|$. which is also known as the Generalized Continuum Hypothesis.

*In turn this axiom is equivalent (as it turns out) to For every ordinal $\alpha$, $2^{\aleph_\alpha}=\aleph_{\alpha+1}$. While the equivalent may not be true in ZF, it is certainly true in ZFC. Both formulations imply the axiom of choice.
(This axiom follows from $V=L$ mentioned in the other answers, but does not imply it. It does not follow from $V=HOD$.)

*There exists an ordinal $\alpha$ such that there is no set $X$ for which there is a chain of cardinals between $X$ and $\mathcal P(X)$ of order type $\alpha$. (i.e. the "distance" between $X$ and $\mathcal P(X)$ is never longer than $\alpha$).
Equally this can be required about $X$ and $X^2$. However assuming choice $|X|=|X^2|$ for infinite sets, so this turns out to be equivalent; whereas we can use class forcing to push power sets far enough so there are such sequences of any length.

Generally speaking, let $\varphi$ be a proposition which is consistent with ZFC but not provable from ZFC, then AC+$\varphi$ is an axiom stronger than the axiom of choice.
In the fashion above, we can think about $\varphi$ being "the axiom of choice holds, and $\lozenge_\kappa$ is true for all $\kappa<\aleph_\omega$." or something like that.

A: Many large cardinal hypotheses imply AC, when stated in a certain natural way.
For example, the assertion over ZF that there are unboundedly many inaccessible
cardinals, defined as uncountable regular strong limit cardinals,
implies the axiom of choice.
Indeed, even having a proper class of strong limit cardinals
implies the axiom of choice.
What's more, the axiom of choice is equivalent over ZF to the assertion "there are unboundedly many strong limit cardinals".
The forward direction is simply the usual proof in ZFC that there is a closed unbounded class of strong limit cardinals. For the reverse implication, we define that $\kappa$ is a strong limit if and only if
it is an initial ordinal for which $\beta\lt\kappa\implies P(\beta)\lt\kappa$. Note that this implies in particular that the
power set $P(\beta)$ is well-orderable for $\beta\lt\kappa$, since it injects into $\kappa$, which is well-orderable. Thus, if there are a proper
class of such $\kappa$, then every well-orderable set will have a
well-orderable power set. It is a non-obvious fact (and in fact a quite slippery fact, which  beginners often get wrong when first trying to prove it) that if every well-orderable set has a well-orderable power set, then AC holds.
To see that there are several natural but inequivalent
formulations of inaccessibility and of strong limit cardinals in ZF, see the treatment in A. Blass, I. Dimitriou, B. Loewe,
Inaccessible cardinals without the axiom of choice.

A: The Axiom of Constructibility implies the Axiom of Choice, as well as many other results independent of ZFC, such as the continuum hypothesis.

A: The axiom of global choice. Technically this isn't really an axiom: global choice (GC) states that there is a formula $\phi(x, y)$ such that the relation $$ A\le_\phi B:= V\models \phi(A, B)$$ is a well-ordering of the universe $V$. This can't be stated as a single formula, so in some sense it's a meta-axiom. It clearly implies choice, and is implied by $V=L$: we already have a partition of the universe into $L_0$, $L_1$, . . . , $L_\alpha$, . . ., and we can get from here to a full (class-)well-ordering of the universe by fixing at the outset some well-ordering of formulas in the language of set theory (since at each stage in the construction of $L$ we are only taking definable powersets; this is why this argument doesn't work in just $ZFC$).
A couple comments on why I think global choice is interesting (even though it's not expressible in the language of set theory):

*

*Although the relative consistency of Choice was proven rather early, it was via $L$, which satisfies $GC$ as well; the result that, assuming the consistency of $ZFC$, there is a model of $ZFC$ with no definable well-ordering of the universe came much later [NOTE: this is based on foggy memory, and I don't recall exactly when this result happened; can someone remind me?], and generally telling whether a model of $ZFC$ satisfies $GC$ is very hard.

*Basically by reversing the argument that it is true in $L$, one can make an informal argument that GC implies that the universe is small (contains only "buildable" things). So there's a somewhat intuitive argument for $AC+\neg GC$: the universe should be "big enough" that for each family of sets, we have a choice function, but the universe should also be big enough that any specific definable well-order "misses something."

*$GC$ is useful in other set theories. First of all, as noted above, even stating $GC$ needs a class theory like Morse-Kelley or NBG (expansions of $ZFC$ to also talk about classes). We can also ask about the status of $GC$ in really odd set theories like New Foundations (EDIT: As Ali points out below, in NF/NFU Choice and Global Choice are essentially one and the same - but the point still stands that global choice could still be interesting in set theories different than $ZFC$.)

*$GC$ makes sense even outside of set theories! It doesn't make sense to ask whether a given ring $R$ satisfies the axiom of choice, since elements of $R$ aren't (at least on the face of things) sets, but it does make sense to ask whether there is a formula in the language of rings which well-orders $R$.

A: The axiom "every set is constructible" (denoted V = L), and the axiom "every set is definable from an ordinal parameter" (denoted often as V= HOD, and sometimes as V= OD) each implies AC, and each is provably stronger than AC.

More specifically, it is well-known that:
(a) (Within ZF), V = L implies V = HOD, and V = HOD implies AC.
(b) Neither of the above implications is reversible.

Historical Note:  The axiom V = L was introduced by Gödel in his seminal work on the consistency of AC and GCH with ZF. The axiom V= HOD was first publicly introduced in a joint paper of Myhill and Scott, but their paper acknowledges that the axiom was independently considered by a number of people, including Gödel, Post, and the joint work of Vopěnka and Balcar.


Q: Passing json to mvc controller I am trying to post some data via jQuery ajax to an Asp.Net MVC controller. I have the follow class which I am working with:
public class InnerStyle
{
   [JsonProperty("color")]
   public string HeaderColor { get; set; }
   [JsonProperty("font-size")]
   public string HeaderFontSize { get; set; }
   [JsonProperty("font-family")]
   public string HeaderFontFamily { get; set; }
}

The post method looks like:
public JsonResult UpdateRecord(InnerStyle innerStyle)
{
   //Do some validation

   return Json("OK");
}

And my jQuery looks like:
$('#font-size-ddl').change(function () {
   var value = $(this).val();
   headerObj["font-size"] = value;
   console.log(JSON.stringify({ innerStyle: headerObj }));
   $.ajax({
          type: "POST",
          url: "@Url.Action("UpdateRecord", "Document")",
          data: JSON.stringify({ innerStyle: headerObj}),
          contentType: "application/json; charset=utf-8",
          success: function (data) {
          console.log(data);
          }
     });
});

The console.log in the above change event produces the following JSON string:
{"innerStyle":{"text-align":"","font-size":"20px","color":""}}

Now the issue I am having is if I set a break point on my UpdateRecord Action and see what is coming through the innerStyle object is null. Can someone tell me where I am going wrong please.

A: I tried using the below code and it's working fine.
$.ajax({
          type: "POST",
          url: "@Url.Action("UpdateRecord", "Document")",
          data: JSON.stringify({"text-align":"","font-size":"20px","color":""}),
          contentType: "application/json; charset=utf-8",
          success: function (data) {
          console.log(data);
          }
     });

I simply removed the parameter name "innerStyle". I just noticed one thing which might be a typo error. You are passing a property "text-align":"" instead of "font-family". So it's not populating all properties inside the controller's action UpdateRecord(InnerStyle innerStyle). You should pass similar to the below json object to map the entire object on controller's action UpdateRecord(InnerStyle innerStyle)
{
  "color": "sample string 1",
  "font-size": "sample string 2",
  "font-family": "sample string 3"
}

A: @Code, your code is fine. It's just you cannot use [Json Property] while you are hitting controller via ajax. you have to use real class properties.
 $('#font-size-ddl').change(function () {
    var value = $(this).val();
    var headerObj = {};
    headerObj["HeaderColor"] = "Red";
    headerObj["HeaderFontSize"] = value;
    headerObj["HeaderFontFamily"] = "Arial";
    console.log(JSON.stringify({ custom: headerObj }));
    $.ajax({
        type: "POST",
        url: "@Url.Action("UpdateRecord", "Employee")",
        traditional: true,
        data: JSON.stringify({ custom: headerObj }),
        dataType: JSON,
        contentType: "application/json; charset=utf-8",
        success: function (data) {
            console.log(data);
        }
    });
});


Q: Required parameters for launching headless chrome What are the required options for launching google chrome headless from C#? These are the options I’ve got now:
        var options = new ChromeOptions();
        options.AddArgument("--headless");
        options.AddArgument("start-maximized");
        options.AddArgument("--disable-gpu");
        options.AddArgument("--disable-extensions");
        options.AddArgument("--window-size=1024,768");
        var driver = new ChromeDriver(options);

A: It would appear that when running headless chrome from, at least, inside Visual Studio the "no-sandbox" option is required.
options.AddArgument("no-sandbox");

Found by accident here:
https://stackoverflow.com/a/39299877/71376


Q: Firefox WebExtensions API how to make AJAX call to current tab website I want my web extension to make an AJAX call to the website which the user is currently looking at. I know that the current website has an endpoint available at /foo/bar?query=.
Is there anything blocking me from using the fetch API or an XMLHttpRequest to contact this endpoint?
My attempts to use these methods just tell me that a server error has occurred, and nothing comes up in the network tab while I'm trying to debug my extension. I feel like there should be a WebExtensions API for this task, but I can't find one.

A: You can get an object describing the current tab the user is looking at using browser.tabs.getCurrent(). This object has a property url, which you can then use to make an XMLHttpRequest.
browser.tabs.getCurrent().then(currentTab => {
    let xhr = new XMLHttpRequest();
    xhr.open("GET", currentTab.url);
    // ...
});

Edit:
As pointed out by Makyen, tabs.currentTab is not actually what you want. Instead tabs.query with active: true should be used. Something like that should work:
browser.tabs.query({active: true, currentWindow: true}).then(tabs => {
    let currentTab = tabs[0];
    let xhr = new XMLHttpRequest();
    xhr.open("GET", currentTab.url);
    // ...
})

In order to make cross origin requests, you will need to get permission in your manifest.json file:
{
  ...
  "permissions": [
    "tabs",
    "<all_urls>"
  ],
  ...
}

<all_urls>for instance will allow you to make http requests to any url.
You can read more here.


Q: How to perform a unittest on a unittest How do you do a unittest on a unittest. I have a unittest and obviously when it is succesfully it generates an ok message in the terminal but I have struggled to find a way of creating a test for the test based upon that.
Basically looking for a way to test if the below test returns ok.
The Test Below:
import unittest

class TestSum(unittest.TestCase):
    def test_sum(self):
        self.assertEqual(2+2, 4)

if __name__ == '__main__':
    unittest.main()

What this returns in the shell :
Ran 1 test in 0.000s
OK

A: First of all you have to have function that does the calculation, so you pass that function to the test case.
Example:
import unittest

# Defined the function that does the calculation
def sum_numbers(x, y):
    return x + y

class TestSum(unittest.TestCase):
    def test_sum(self):
        self.assertEqual(sum_numbers(2, 2), 4)

if __name__ == '__main__':
    unittest.main()

Now this test will evaluate to ok and you can add more test to test_sum


Q: How to use a python package - shouldn't i be able to access anything listed in __all__? I'm trying to use the pyupnp package (http://code.google.com/p/pyupnp/)
I've built and installed it and in my code I have:
import pyupnp
b = pyupnp.UpnpBase()
...

But I get this error: AttributeError: 'module' object has no attribute 'UpnpBase'
Now I had a look in the code for the package, and it has the following:
__all__ = [
  'UpnpNamespace',
  'UpnpDevice',
  'UpnpBase',
  ...

I thought that I would be able to access anything in the __all__ list? What am I doing wrong?
Thanks so much

A: Looking at this package, you should import pyupnp.upnp, not pyupnp. The contents of __all__ are irrelevant here.


Q: Convolution of an Airy function with a Gaussian I wonder if the convolution
\begin{equation}
f(y)=\int_{-\infty}^{+\infty}  \mathrm{Airy}(a\cdot x)\cdot e^{-b(y-x)^2} dx
\end{equation}
can be solved analytically. Or in case not, if there is an analytic expression for the zeros of $f(y) = 0$ and for which values of $a$ and $b$ they exist.
edit: $a>0$ and $b>0$

A: Here's a proof sketch of
$$(*) \quad \int_{-\infty}^\infty e^{-b \ u^2}\text{Ai}(a(u+y))du = \frac{\sqrt{\pi}}{\sqrt{b}}
\exp{\big(\frac{a^6}{96b^3} + \frac{a^3y}{4b}}\big)\text{Ai}\big(a(y+\frac{a^3}{16b})\big).$$
The following formula will be used twice:
$$  (1) \quad \frac{1}{2\pi} \int_{-\infty}^\infty \exp{\big(iu^3/3-u^2\ t/2+i\ u \ x\big) } = \exp{\big(t^3/12 + t \ x/2 \big)} \text{Ai}\big( x+t^2/4 \big)$$
Also used used is the well-known
$$  (2) \quad \int_{-\infty}^\infty  \exp{\big(-iz \ t - \frac{z^2}{4b} \big) }dz = 2 \sqrt{b \pi } e^{-b t^2} $$
and the Fourier integral representation of the Dirac delta function,
$$  (3) \quad \frac{1}{2 \pi} \int_{-\infty}^\infty \exp{\big(i x (u-z) \big)} dx = \delta(u-z) .$$
Starting with (1), apply $\int_{-\infty}^\infty \exp{(-ix \ z)}dx/(2\pi) .$  Use (3), then (1) to get $ \exp{(-iz^3/3-z^2 \ t/2)} $= $\exp(t^3/3)\int_{-\infty}^\infty \exp{(-ix \ z + t\,x/2)} Ai(x+t^2/4)dx .$ Shift $z \to z-it/2$ to get a simpler looking integral. Let $t/2 \to y.$ The parameters can be rescaled to get the attractive intermediate form
$$  (4) \quad a \int_{-\infty}^\infty \exp{(-iu \ z)}\text{Ai}(a(u+y)) du = \exp{(i\frac{z^3}{3a^3}+iy \ z)}$$
Apply (2) to (4), use (1) again, and simplify to get (*).
The proof uses interchange of integrations that have not been justified, and I don't want to do it, hence I call it a proof sketch.  Also, I expected something with a nice closed form as $(*)$ to have been discovered before.  It has, in  arXive:0906.3666v4 29 Sept 2009, 'Zeros of Airy Function and Relaxation Process,' M, Katori and H. Tanemura.  See formula 3.10.  Their proof is different, but it also involves an interchange of $\int$ about which nothing is said. If starting from their 3.10, you'll need to work in a scaling parameter.  That formula is part of an appendix that has some references that I have not read, so I don't know if their equivalent to $(*)$ is the first time it appears in the literature.


Q: Migrating stripe express into stripe standard I already have a stripe standard account but a platform created a stripe espress account for me. Even though I used the same email address for both, they are now two separate accounts managed in two separate places with two separate dashboards even though both are for my business. Is there a way of migrating the express data into the standard account? My goal is to close the Express account and have All my transactions and management in one location
I had come across some documentation that indicated creating an express account with the same email as an existing standard account would automatically merge the accounts but I can't seem to find that documentation again.


Q: UWP service to app call I have UWP app service with TimeTrigger. Every time this trigger fires i'm trying to download some data from the internet.
Is there anyway my service can notify my second UWP UI app about data load success|fail? The only way i've found is to run the second service in UI app thread and call it to send the notification.
The original task is to create an always-running data update checking service and load a data consuming UWP UI app that may or may not be running.


Q: Moving from one div to another on click of a menu link I want to make an animation effect on my website where, when we click on a menu link (say, about-section), it will animate to that div in a parallax style.
So guys if you know any jquery plugin that can help me in this context, then please let me know, and it would be better if you demonstrate me a example of that as well.
See the code for help:

.Home-section {
  height: 500px;
  background: deepskyblue;
}
.About-section {
  height: 300px;
  background: deeppink;
}

Home
About

 Hello

Bye

So, According to the code i want to animate to About-section on click on the link stating About

A: Hope you want this. Thanks

// handle links with @href started with '#' only
$(document).on('click', 'a[href^="#"]', function(e) {
    // target element id
    var id = $(this).attr('href');

    // target element
    var $id = $(id);
    if ($id.length === 0) {
        return;
    }

    // prevent standard hash navigation (avoid blinking in IE)
    e.preventDefault();

    // top position relative to the document
    var pos = $(id).offset().top - 10;

    // animated top scrolling
    $('body, html').animate({scrollTop: pos});
});
.Home-section {
  height:500px;
  background: deepskyblue;
  }

.About-section {
  height:300px;
  background:deeppink;
  }

Home
About

 Hello

Bye

A: To get more like a parallax effect, you can add background-attachment: fixed;
.About-section {
  height: 300px;
  background: url('http://lorempicsum.com/futurama/627/200/3') no-repeat;
  background-size: cover;
  background-attachment: fixed;
}

Like this
Note : I use @sagar kodte JS code which works good for the animation.

A: please try this
.Home-section {
  height:500px;
  background: deepskyblue;
  }

.About-section {
  height:300px;
  background:deeppink;
  }
a{cursor:pointer}

html code

 Home
 About

 Hello

Bye

and also js fiddlde here

A:

.Home-section {
  height: 500px;
  background: deepskyblue;
}
.About-section {
  height: 300px;
  background: deeppink;
}
Home
About

 Hello

Bye

Try this.


Q: I want to add a custom field in the rss title of each post, but don't want it to be shown on the site I've seen that other sites have done this but didn't manage to do it myself.
I have certain custom fields for each post and I want one of these custom fields to be shown in the RSS feed in the title for each item after the item's actual title. For example, if the post is named "Abracadabra and hocus pocus" and is written by James A. Author I would like the feed item title to be "Abracadabra and hocus pocus by James A. Author".
How can this be done?

A: I've never actually tried this, but I think the following should work:
function wpse_96096_append_author( $title, $post_id ) {
    if( is_feed() ) {
        $author = get_post_meta( $post_id, '{YOUR CUSTOM FIELD KEY}', true );
        $title = $title . ' by ' . $author;
    }
    return $title;
}
add_filter( 'the_title', 'wpse_96096_append_author', 10, 2 );

What this does is add a filter to the title field that is only applied when is_feed() returns true. When it does, it queries the custom field and tacks it on to the title.


Q: Deserialize Dynamic JSON Object I am using a thirdparty API and the Json response that I receive back is as below.
Usually, using something like
Newtonsoft.Json.JsonConvert.DeserializeObject<MyModel>(response);

I can easily create a .Net model. However, I am struggling on how to formulate the below. I've tried KeyValuePairs, strings, modifying the actual Json but cannot seem to get any joy.
What am I missing?
{
  "1": [
    {
      "qty": 1,
      "discount": "flat",
      "price": 71.68
    }
  ],
  "2": [
    {
      "qty": 1,
      "discount": "flat",
      "price": 62.75
    }
  ],
  "3": [
    {
      "qty": 1,
      "discount": "flat",
      "price": 77.28
    }
  ],
  "4": [
    {
      "qty": 1,
      "discount": "flat",
      "price": 82.88
    }
  ],
  "5": [
    {
      "qty": 1,
      "discount": "flat",
      "price": 67.84
    }
  ]
}

Now, what is throwing me is that the numbers(1,2,3,4,5) are Identifiers so will not stay constant and could change each time you receive the response.

A: I think Newtonsoft can do this for you.
string json = @"{
  'Email': 'james@example.com',
  'Active': true,
  'CreatedDate': '2013-01-20T00:00:00Z',
  'Roles': [
    'User',
    'Admin'
  ]
}";

var jsonReturn = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>( json );
Console.WriteLine( jsonReturn.Email );

Based on this link:
https://www.newtonsoft.com/json/help/html/DeserializeObject.htm
This is the most basic explanation. Use a foreach to iterate over de nodes

A: Using @Liam's suggestion of JObject I have come up with this working solution
public class MyObject
{
        public int id { get; set; }
        public int qty { get; set; }
        public string discount { get; set; }
        public decimal price { get; set; }
}

and then after retrieving the JSON response...
        var jsonObj = JsonConvert.DeserializeObject<JObject>(response);

        List<MyObject> myObjects = new List<MyObject>();

        foreach (var item in jsonObj.AsJEnumerable())
        {
                var csp = JsonConvert.DeserializeObject<List<MyObject>>(item.First.ToString());

                csp.ForEach(a => { a.product_id = Convert.ToInt32(item.Path); });

                myObjects.AddRange(csp);
         }


Q: _e printed before layout WPML/Wordpress/PHP I am using WPML to translate English to a different language.
Everything works fine except the mail form.
For some reason when is use the _e() function the string gets printed before the layout.
But still inside the body element. Please help here is the code:

if(trim($_POST['contactSubject']) === '') {
       $subjectError = _e('Please enter a subject.', 'wpml_contact');
       $hasError = true;
} else {
       $subject = trim($_POST['contactSubject']);
}

A: You should use the __() function (codex link). This function returns the translated string:
if(trim($_POST['contactSubject']) === '') {
   $subjectError = __('Please enter a subject.', 'wpml_contact');
   $hasError = true;
} else {
   $subject = trim($_POST['contactSubject']);
}

The _e() function returns and displays the translated string.


Q: Returning the Most Negative Two's Complement Number in C with Bitwise Operators I have a function in C that should return the most negative two's complement number:
int mostNegTwosComp(void) {

    return 0;
}

I am constrained to using a maximum of 4 bitwise operators. These operators include: ! ~ & ^ | + << >>. How would I go about doing this? Wouldn't the most negative two's comp number be dependent on how many bits the selected number is? For instance, 10000 would be the most negative two's comp number of a 16 bit int?

A: return ~ (~0u >> 1);

~ turns on all bits in the unsigned zero. Then >> 1 shifts right, resulting in the high bit becoming zero. Then ~ inverts all bits, producing one in the high bit and zero in the rest.
Then the return converts this to int. This has implementation-defined behavior, but class assignments of this sort generally presume a behavior suitable for the exercise.

A: If you don't need a portable version, you can abuse the knowledge that integers are almost always 4 bytes.
return 0x80000000;

In fact, if you know the size of the type you're going to return, you can skip the bitwise game and cheat with the format:

*

*In 0x__, each number is 4 bits.This means 2 digits are one byte.

*You want the first bit to be 1, and all other bits to be 0.

*0x8 = 0b1000

*As such, you can represent the value as 0x80 + 2 '0's for every byte of the type past the first.

But to answer the rest of your question.

How would I go about doing this?

If you're templating, you'd (probably) use the bitwise trick the other answer suggests. Otherwise you can cheat with the above code or use a definition from limits.h (iirc).
~ (~0u >> 1);

Would be a portable solution.

Wouldn't the most negative two's comp number be dependent on how many bits the selected number is?

The most negative two's compliment is dependent upon the size of the containing variable, so I suppose you could say "selected number". In fact, the range of values depends on the size of the containing variable.

For instance, 10000 would be the most negative two's comp number of a 16 bit int?

For 16 bits, the most negative two's comp would be 0x8000, 0b1000000000000000 or -32768, depending on how you'd like it represented.


Q: What (pedantically) defines a "central force", as in "central force law of areas", etc.? A typical description of a central force is found here Lecture L15 - Central Force Motion:  Kepler’s Laws (pdf).

"When the only force acting on a particle is always directed to wards a fixed point, the motion is  called central force motion."

The two cases I am familiar with are the inverse square force, and the mass on a spring.
I am assuming a free test particle (e.g., a planet) not subject to friction nor any other force.
Other that having a "central attractor", what other conditions must be met to qualify as a "central force problem"?  For example, can the force at a field point change with time? Can the force depend on radial angle?  This latter proposition appears to require a potential gradient with a non-radial component, so violates the central force requirement.

A: Taken literally, a central force problem is one in which the force on a particle is given by
$$\mathbf F(\mathbf r,t) = f(\mathbf r,t) \hat r$$
where $\hat r \equiv \mathbf r/|\mathbf r|$.  This is a rather broad class of physical models, and not much can be said about them at this level of generality.
Most of the time when we talk about central forces, we mean forces which can be derived from a time-independent central potential, i.e.
$$\mathbf F(\mathbf r,t) = -\nabla V(\mathbf r)$$
These are the forces which e.g. conserve angular momentum, and it is these forces which are the subject of Bertrand's theorem on stable orbits.
As far as I know, there is no universal convention as to which type is meant when one says the words "central force problem." Presumably if you come across a discussion of central forces, a reasonably careful author would define what those words are supposed to mean. If they don't, then it will probably become apparent in short order which definition they're using, and if it doesn't, then that would be a good time to ask.

This latter proposition appears to require a potential gradient with a non-radial component, so violates the central force requirement.

This argument fails because a generic force simply can't be derived from a potential. If the force is conservative, then this argument holds, which is a quick way to see that conservative central forces must be spherically symmetric (i.e. $V(\mathbf r) = V(r)$).


Q: using a pushbutton's call back in an other callback in matlab I have two push buttons in my MATLAB GUI. I am trying to recognize a push button in button1's callback function and do something with regard to which button was pressed. I have tried to use button group and put all my buttons in that group. It seems as if there is no code when any of these push buttons is clicked. Why?
Here is my code:
function uibuttongroup1_SelectionChangeFcn(hObject,eventdata)
    switch get(eventdata.NewValue,'Tag') % Get Tag of selected object.
    case 'notSimul'
          disp('notSimul clicked')
    case 'simul'
        % Code for when radiobutton2 is selected.
    case 'stopTest'
        % Code for when togglebutton1 is selected.
    case 'start'
        % Code for when togglebutton2 is selected.
    % Continue with more cases as necessary.
    otherwise
        % Code for when there is no match.
end

A: If I understand your question correctly that you placed a push button in a button group, the answer is it would not work because button group is supposed to be composed of only toggle button and radio button. When I tried putting a push button in a button group, nothing would happen, just as you described.


Q: How to search CalDav Blob from MySql Db? I'm currently trying to integrate a CalDav Calendar into my website.
I'm using "baikal" and it actually works fine, i'm already able to access my
calendar via iphone, macbook and so on.
What I wanna do now is reading the Events from the mysql database and display
them in my own calendar.
It works fine so far, I found a library that can parse these Blobs which stores all calendardata.
My problem now is:
How can I search through this blob? For example, i want to display all events between date x and y, or display all events that contain "concert" in the summary/title.
I did some research on this but i wasn't able to find anything so I thought I ask!
looking forward to your replies and thanks in advance!
david

A: Why dont you use CalDAV to access the calendar, instead of trying to directly hit the MySQL DB ? From what I understand, you don't even own the schema as it comes from the Baikal server (?...) so you are running the risk of having to redo the work if/when Baikal changes the way they store the data.
Another advantage is that you are guaranteed to get a more consistent result: for example, time range queries (from date x to date y) can be tricky so by using CalDAV queries, both CalDAV clients and your calendar are going to return the same set of events whereas by trying to implement something on your own, you will likely diverge from what the CalDAV server returns.
There are php CalDAV clients. See for example Is there any php CalDav client library?
See https://www.rfc-editor.org/rfc/rfc4791#section-7.8.1 for a timerange based CalDAV query.


Q: R value of i and j in a loop I am learning to run a loop (2 rounds of loop) for a DCC GARCH model. However, the loop is out of my control because:
Problem 1: Round 1, I want R to run for i from 1 to n-1 (n is total numbers of countries): however
it keeps run from i==0 --> I put i in (2:length(msci)-1); so it is ok for now, but I just don't understand why there is the case.
Round 2, I want R to run for j from i+1 to n. Somehow, R run j until n+ 1 --> I bypass it by setting
j in (i+1:length(msci)-1
It is ok for i=1 (it runs for j from 2 to 49). When i=2, it runs from 3 to 50
So it issues the error: "[1] "Now is loop j 50"
Error in [.data.frame(msci, j) : undefined columns selected"
Any help (how to stop j reach the value of 50) is greatly appreciated. thanks
My code is:
library(R.oo)
library(rmgarch)
library(tidyverse)
setwd("C:/data/Garch output")
#define the function####
my_model <- function(country1, country2) {
  uspec <- ugarchspec(variance.model = list(model="eGARCH",garchOrder = c(1,1)),mean.model = list(armaOrder = c(2,2)))
  mspec=multispec(replicate(2,uspec))
  multf=multifit(mspec,data=data.frame(country1,country2),solver = "nlminb",fit.control = list(stationarity = 1, fixed.se = 0, scale = 1, rec.init = "all"))

  #define the DCC model
  spec1=dccspec(uspec=mspec,dccOrder=c(1,1), model = "DCC",distribution="mvnorm")
  #estimate DCC
  fit1=dccfit(spec1,data=data.frame(country1,country2),fit.control = list(eval.e=TRUE),fit=multf)
  return(fit1)

}

for (i in 2: length(msci)-1) {

  print(paste("LOOP i IS NOW", i))

  if (j >= i+1:length(msci)-1) {
    if (i != j) {
      print(paste("Now is loop j", j))
      print(paste("this is the loop of correlation between", names(msci[i]), "and", names(msci[j])))
      #create name for the output
      temp_name <- paste0("fit_",names(msci[i]), "_", names(msci[j]))
      file_name <- temp_name
      #estimate model
      temp_name <- tryCatch({my_model(msci[i], msci[j])},
                            error = function(e) {cat("There is a error in", names(msci[i]), "and", names(msci[j]), "\n")}
      )
      saveRDS(temp_name, file = paste0(file_name,".RDS"))
      print(paste("Finish loop of correlation between", names(msci[i]), "and", names(msci[j])))
    }

    }}

my data is in the below google link.
https://docs.google.com/spreadsheets/d/1ygaoOvby4mTpFIfHTkcyjq-Uwby671yQWI-xfU3Li7Y/edit#gid=0

A: Your issue is order of operations -- in R, : has higher precedence than + and -.
## Demonstration:
1:5 - 1
# [1] 0 1 2 3 4
1:(5 - 1)
# [1] 1 2 3 4

## In your case
## change this:
for (i in 2: length(msci)-1)
## to this:
for (i in 1:(length(msci) - 1))

## I don't see `j` defined in your code, but I assume you have the same issue and need
for (j in (i + 1):n))


Q: Orthogonally diagonalizable matrix and orthonormal basis How is an orthogonally diagonalizable matrix related to eigenvectors and an orthonormal basis?

A: "Orthogonally diagonalizable" means precisely "has an orthonormal basis of eigenvectors".

A: We say that a matrix $A$ is orthogonally diagonalizable if we can write $A=D^{-1}SD$ such that $S$ is a diagonal matrix and its diagonal elements are eigenvalues of $A$ and rows of $D$ are eigenvectors of $A$. Rows of $D$ are a orthonormal basis, it means they or mutually perpendicular and because of this fact $D^T=D^{-1}$.
As an example you can find all symmetric matrices orthogonally diagonalizable.


Q: How to round up to the higher 10 in C#? I have to write a program at school that allows the user to input a 7-digits of a GTIN-8 barcode and calculate check digit. To calculate the check digit the seven input numbers are multiplied by 3, 1, 3, 1 etc.
for (i = 0; i < 7; i++)
{
    //Convert String to Character
    ch = gtinNum[i];

    //Convert Character to Integer
    number = Convert.ToInt32(ch);
    product = number * weights[i];
    total = total + product;
}//end for loop

After that, the total is taken away from the nearest higher ten. For example if the total was 43 then it would be 50-43.
In the simplest way possible, how do I round up to the higher ten?

A: You can use Math.Ceiling, you just need to divide by ten first and multiply by 10 afterwards. Divide by 10.0 to avoid integer division(Math.Ceiling takes double):
int num = 43;
int nextHigherTen = (int)Math.Ceiling(num / 10.0) * 10;

This "rounds" 41-50 up to 50. If you want it from 40-49 you could use this:
int nextHigherTen = (int)Math.Ceiling((num + 1) / 10.0) * 10;


Q: How can I pass a class object from Activity to a class to be able to call its methods? I need to create an object of the BLE class in the Activity, in onCreate, I tried to implement it with Parcel (passing the object via Intent), but I have an application crash from it.
As it turned out, the reason was that in the BLE class when I accept The content:
mDeviceListAdapter = getEnableIntent().getParcelableExtra("lVAdapter");
mDeviceListAdapter == null

Later I learned that the Intent serves to transfer data only in the onCreate from one Activity to another.
Please tell me how I can transfer objects of the created classes to other classes (not Activity). Thankful in advance.


Q: How to view Lambda results in CloudWatch Event Logs? I was following Tutorial: Schedule AWS Lambda Functions Using CloudWatch Events - Amazon CloudWatch Events on how to Schedule AWS Lambda Functions Using CloudWatch Events.
It all makes sense and work as expected, but in my logs I cannot find the results of the lambda calls, but only custom logs that were written in the code and I can see the incoming payloads.
Are results supposed to show or do I specifically need to Log them in my code?

A: If lambda has got these IAM permissions it will show the custom loggers as well as default AWS invocation/error logs
"logs:CreateLogGroup",
"logs:CreateLogStream",
"logs:PutLogEvents"


Q: How to animate two moving dots joined by a line in tikzpicture Can someone explain how to animate (using tikz animation, chapter 26 in pgfmanual 3.1.9a) two small colored dots (small filled circles) moving slowly in different directions (along position coordinates), continuously joined by a colored straight line, built with
\documentclass[dvisvgm]{standalone}
\usepackage{tikz}

and the SVG to be created with either latex example.tex or dvilualatex example.tex plus dvisvgm example --font-format=woff and either ...

*

*a) repeating the movement continuously

*b) or with a separate "click me" node to start the animation

Despite the 85 examples, I am as yet unable to put this example together. I am just learning animation.
Finally, would you recommend the BEAMER package for 'speed and flexibilty' (I believe I do not use the shapes modules)?

A: With some experimentation I came up with the following answer. Although in the final use case the coordinates are almost a straight line, here I use three coordinates that form a large angle (for demonstration purposes).
Case a) repeating continuously
In the code I added a 3 second delay before each animation starts:
\usetikzlibrary {animations}
\begin{tikzpicture}
\useasboundingbox (0,0) rectangle (6,4);

\node at (0.5,1) :position = { 0s = "{(0.5,1)}", 3s = "{(0.5,1)}", 5s = "{(1,2.5)}" , 8s = "{(2,2)}", repeat }
[fill = blue!20, draw = blue, ultra thick, circle] (node1) {};

\node at (2,2) :position = { 0s = "{(2,2)}", 3s = "{(2,2)}", 5s = "{(4,3)}", 8s = "{(5,3.5)}", repeat }
[fill = red!20, draw = red, ultra thick, circle] (node2) {};

\draw [green] (node1) -- (node2) :path = { 0s = "{(node1) -- (node2)}", 3s = "{(node1) -- (node2)}",
5s = "{(1,2.5) -- (4,3)}", 8s = "{(2,2) -- (5,3.5)}", repeat };
\end{tikzpicture}

Here is the SVG (I hope this works):

Criticism: I do not like that the connecting line grows in length up to the center of both circles - I need to subtract the radii of the two ending circles.
Case b) with a start button
\usetikzlibrary {animations}
\begin{tikzpicture}
\draw (5,5) node[minimum height =0cm,draw,scale=1.5] (Go) {Go!};

\node at (0.5,1) :position = { 0s = "{(0.5,1)}", 2s = "{(1,2.5)}" , 5s = "{(2,2)}", begin on={click, of=Go} }
[fill = blue!20, draw = blue, ultra thick, circle] (node1) {};

\node at (2,2) :position = { 0s = "{(2,2)}", 2s = "{(4,3)}", 5s = "{(5,3.5)}", begin on={click, of=Go} }
[fill = red!20, draw = red, ultra thick, circle] (node2) {};

\draw [green] (node1) -- (node2) :path = { 0s = "{(node1) -- (node2)}", 2s = "{(1,2.5) -- (4,3)}",
5s = "{(2,2) -- (5,3.5)}", begin on={click, of=Go} };

\end{tikzpicture}

Here is the SVG (sorry, the button works in the created SVG though):

Criticism: if the node1 and node2 coordinates are extracted into a \begin{scope} [animate = { .... }] .... \end{scope} section, within the :position list of arguments begin on={click, of=Go} is ignored, i.e. the animation never starts.
Case a2) repeating continuously
The gradually extending line that connects the nodes (hard to see in the examples above) can be removed using phantom nodes. See: Phantom nodes for TikZ animation
\usetikzlibrary {animations}
\begin{tikzpicture}
\useasboundingbox (0,0) rectangle (6,4);

\node at (0.5,1) :position = { 0s = "{(0.5,1)}", 3s = "{(0.5,1)}", 5s = "{(1,2.5)}" , 8s = "{(2.5,1.5)}", 10s = "{(2.5,1.5)}", repeat }
[fill = blue!05, draw = blue, thick, circle, radius = 0.6] (node1) {};

\node at (2,2) :position = { 0s = "{(2,2)}", 3s = "{(2,2)}", 5s = "{(4,3)}", 8s = "{(5,0.5)}", 10s = "{(5,0.5)}", repeat }
[fill = red!05, draw = red, thick, circle, radius = 0.6] (node2) {};

\begin{lrbox}{0}
\node at (1,2.5) [draw, circle, radius = 0.6, opacity = 0.2] (n1) {};
\node at (2.5,1.5) [draw, circle, radius = 0.6, opacity = 0.2] (n2) {};
\node at (4,3) [draw, circle, radius = 0.6, opacity = 0.2] (n3) {};
\node at (5,0.5) [draw, circle, radius = 0.6, opacity = 0.2] (n4) {};
\end{lrbox}

\draw [brown] (node1) -- (node2) :path = { 0s = "{(node1) -- (node2)}", 3s = "{(node1) -- (node2)}", 5s = "{(n1) -- (n3)}", 8s = "{(n2) -- (n4)}", 10s = "{(n2) -- (n4)}", repeat };

\end{tikzpicture}

The SVG is here:

If you comment out the beginning and end of the {lrbox}, you see faint images of where the phantom nodes are placed:

This is a good solution, but cumbersome to code. I've since seen (on page 382 of the TikZ manual:

So, all in all, I'm satisfied with this solution, which will use Python to create the .tex file anyway. If anyone can improve on it, I'd be pleased to see your version.

A: ADDENDUM to my previous answer
Apologies! To avoid clutter I am posting complete compilable code (as requested) here. Unlike GitHub, I am unable to upload a ZIP file.
This code example shows two animations side by side: the one on the left using phantom nodes, i.e. the "correct" example; the one on the right is the "incorrect" example I had initially (without phantom nodes) where the connecting line slowly grows from touching the circles to "circle mid-point to circle mid-point".
Why this happens is rather obvious: I begin by using the initial "rest position" nodes, which have a defined boundary. Lacking nodes in future animation-time, I switch to coordinates, i.e. the center of the circles. The following example shows this much more clearly than the original "Case a" I posted above.

Python code (tested in Windows 10 with Python 3.9.4 and MiKTeX 21.12):
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

# Standard library imports
import os, sys, time

# ---------- DOCUMENT INITIALIZATION ----------
def beginSVG():
    tex = r"""\documentclass[dvisvgm]{standalone}
\usepackage{tikz}
\definecolor{auburn}{rgb}{0.43, 0.21, 0.1}
\begin{document}
"""
    return tex

# ---------- DOCUMENT FINALIZATION ----------
def endSVG():
    tex = r"""\end{document}
"""
    return tex

############ MAIN ############
if __name__ == '__main__':      # execute if run explicitly

    if sys.version_info[0] < 3:
        raise Exception("This runs with Python 3")

    args = "" if "-v" in set(sys.argv[1:]) else "-interaction=batchmode -halt-on-error "
    keeplog = True if "-log" in set(sys.argv[1:]) else False
    keeptex = True if "-tex" in set(sys.argv[1:]) else False
    modelua = True if "-lua" in set(sys.argv[1:]) else False

    filename = "example"
    texname = filename + ".tex"
    dviname = filename + ".dvi"
    svgname = filename + ".svg"

    if os.path.exists(svgname):
        try:
            os.remove(svgname)
        except PermissionError:
            print("\nERROR: please close '{}' so it can be re-created".format(svgname))
            sys.exit(0)
    if os.path.exists(texname):
        os.remove(texname)

    outfile = open(texname, mode="w", encoding="utf8")
    outfile.write(beginSVG())

    # TEST CASE: runs continuously
    tex = r"""\usetikzlibrary {animations}
\begin{tikzpicture}
\useasboundingbox (0,0) rectangle (10,4);

\node at (0.5,1) :position = { 0s = "{(0.5,1)}", 3s = "{(0.5,1)}", 5s = "{(1,2.5)}" , 8s = "{(2.5,1.5)}", 10s = "{(2.5,1.5)}", repeat }
[fill = blue!05, draw = blue, thick, circle, radius = 0.6] (node1) {};

\node at (2,2) :position = { 0s = "{(2,2)}", 3s = "{(2,2)}", 5s = "{(4,3)}", 8s = "{(5,0.5)}", 10s = "{(5,0.5)}", repeat }
[fill = red!05, draw = red, thick, circle, radius = 0.6] (node2) {};

\begin{lrbox}{0}
\node at (1,2.5) [draw, circle, radius = 0.6, opacity = 0.2] (n1) {};
\node at (2.5,1.5) [draw, circle, radius = 0.6, opacity = 0.2] (n2) {};
\node at (4,3) [draw, circle, radius = 0.6, opacity = 0.2] (n3) {};
\node at (5,0.5) [draw, circle, radius = 0.6, opacity = 0.2] (n4) {};
\end{lrbox}

\draw [auburn] (node1) -- (node2) :path = { 0s = "{(node1) -- (node2)}", 3s = "{(node1) -- (node2)}", 5s = "{(n1) -- (n3)}", 8s = "{(n2) -- (n4)}", 10s = "{(n2) -- (n4)}", repeat };

% second example on the right demonstrates the expanding line when no phantom nodes are used...

\node at (4.5,1) :position = { 0s = "{(4.5,1)}", 3s = "{(4.5,1)}", 5s = "{(5,2.5)}" , 8s = "{(6.5,1.5)}", 10s = "{(6.5,1.5)}", repeat }
[fill = blue!05, draw = blue, thick, circle, radius = 0.6] (node3) {};

\node at (6,2) :position = { 0s = "{(6,2)}", 3s = "{(6,2)}", 5s = "{(8,3)}", 8s = "{(9,0.5)}", 10s = "{(9,0.5)}", repeat }
[fill = red!05, draw = red, thick, circle, radius = 0.6] (node4) {};

\draw [auburn] (node3) -- (node4) :path = { 0s = "{(node3) -- (node4)}", 3s = "{(node3) -- (node4)}", 5s = "{(5,2.5) -- (8,3)}", 8s = "{(6.5,1.5) -- (9,0.5)}", 10s = "{(6.5,1.5) -- (9,0.5)}", repeat };

\end{tikzpicture}
"""

    outfile.write(tex)
    outfile.write(endSVG())

    outfile.close()
    if os.path.exists(svgname):
        os.remove(svgname)

# ----------- TEX -> DVI

    msg = " creating {}".format(dviname)
    if modelua:
        prg = "lualatex"
        command = 'lualatex --output-format=dvi {}'.format(args + texname)
    else:
        prg = "latex"
        command = 'latex {}'.format(args + texname)

    print()     # blank line before "This is pdfTeX, ..."
    os.system(command)
    print("'{}' finished".format(prg) + msg)

# ----------- DVI -> SVG

    time.sleep(1)   # unnecessary
    msg = " creating {}".format(svgname)
    command = 'dvisvgm {}'.format(filename)

    if args == "":
        os.system(command)
        print("finished" + msg)
    else:
        returned_value = os.system(command)
        if returned_value != 0:
            if msg != "":
                print("ERROR detected while creating SVG file")
            else:
                print("!!   ERROR detected while creating SVG file   !!")
                print("!! Append '-v' or '-log' for more information !!")
        else:
            print("finished" + msg)

    if not keeptex: os.remove(texname)
    if not keeplog:
        if os.path.isfile(filename + ".log"):
            os.remove(filename + ".log")
    if os.path.isfile(filename + ".aux"):
        os.remove(filename + ".aux")

One can use the following command line parameters:

*

*-v verbose console output

*-log preserve the log file

*-tex preserve the tex file

*-lua use Luatex instead of Latex to create the DVI file


Q: Firebase: ¿Como puedo hacer un perfil para cada usuario? mi pregunta es como puedo crear un sistema que me permita que cada usuario que se registre, tenga cada uno un perfil, es decir que si tengo x usuario que se registra con su email, contraseña (firebase auth) y tambien escribe en un input su nombre y apellido, yo pueda hacer un perfil para cada uno (Algo asi como las redes sociales)
Avance bastante desde que hice la pregunta de arriba (Jamás la publique porque leyendo la documentación pude avanzar), pero ahora me estanque varios días con algo que no puedo realizar,
Como explica el primer párrafo, tengo un registro con firebase auth
    const auth = getAuth()
  createUserWithEmailAndPassword(auth, email, password)
  .then ((userCredential) => {
    console.log('Registrado') //Mensaje de registro exitoso
    const user = userCredential.user  //Guarda el usuario
    console.log(user.uid)
    console.log(user.email)
    backend(user);
  })
  .catch((error) => {
    const errorCode = error.code
    const errorMessage = error.message
    console.log('error: ' + errorMessage + 'Error code  ' + errorCode)

    let errorHTML = document.getElementById('error');
    errorHTML.innerHTML = errorMessage;

  })

Y luego cuando llamo a la funcion backend, envia a firestore lo siguiente:
    const backend = async (user) => {
  const docRef = await addDoc(collection(db, "users"), {
    firstName: firstName,
    lastName: lastName,
    username: username,
    userID: user.uid,
  });
  console.log("Document written with ID: ", docRef.id);
}

Y una vez enviado todo eso (Lo cual funciona bien), me gustaría que se redireccione a una pantalla donde según el nombre que puso, aparezca en pantalla el mismo (en otro archivo .jsx)
Según lo que leí, era muy importante guardar el uid de cada registro, así que lo envió también a firestore, pero me estanque, agradezco enormemente su ayuda.
Saludos

A: Una vez que el usuario ya esta creado en autenticacion y en la coleccion de usuarios debes crear un estado que guarde al usuario al momento de hacer login,y asi puedes acceder al usuario autenticado en el estado user y STATUS="LOAGEADO",aqui lo importante es hacer uso de un Contexto de seguridad que encapsule toda la APP
EN TU APP.JSX debes encapsularlo en un contexto global,asi podras acceder al usuario todo el tiempo
<SecurityContextProvider>
          <AppRender />
        </SecurityContextProvider>

Y en ese contexto haces la autenticacion y declaras el estado del usuario
   let [user, setuser] = React.useState({
  id: "",
  first_name: "",
  last_name: "",
  status: "NO_LOGGIN",
});

const loginFirebase = async ({ email, password }) => {
  firebase
    .auth()
    .signInWithEmailAndPassword(email, password)
    .then((data) => {
      //aqui busca el usuario segun el id de la autenticación al obtenerlo seteaas el usuario en estado LOGEADO
    })
    .catch((err) => {
      if (err.code == "auth/user-not-found") {
        registerFirebase({ email, password });
      }
    });
};


Q: java Jar's library conflicts
I've been struggling for a while trying to figure out which war application is using a couple of libraries (ie  "cxf-2.0.3-incubator.jar" & "cxf-manifest-incubator.jar") that are causing me troubles at the moment of deploying a new war application on a jboss.4.0.5.GA java application server. The thing is that if I remove those jars, the conflict disappears and the newly deployed application works fine. However trying to deploy this application without removing the mentioned jars fails.
Is there any tool or (linux bash command) suitable for listing all jar dependencies for war applications? (I've already tried tattletale tool, but it seems to work only with jars components).
Regards

A: If you can then try to mavenize your web application project to get all the dependencies that are required and to get away from all the non-required ones.


Q: How to parse nested keys and values using JsonReader? I am learning Java and I'm trying to make a Fortnite stat tracking app. I'm using the Fortnite tracker API and JsonReader to read the keys and values that get returned. This works fine but the problem is the stats like 'kills' etc are nested and I'm not sure how to read those.
Can I read nested keys and values using JsonReader?
I tried JSONObject but I'm not entirely sure I was using it correctly so I didn't get very far.
{   "accountId": "c48bb072-f321-4572-9069-1c551d074949",   "platformId": 1,   "platformName": "xbox",   "platformNameLong": "Xbox",   "epicUserHandle": "playername",   "stats": {
    "p2": {
      "trnRating": {
        "label": "TRN Rating",
        "field": "TRNRating",
        "category": "Rating",
        "valueInt": 1,
        "value": "1",
        "rank": 852977,
        "percentile": 100.0,
        "displayValue": "1"
      },
      "score": {
        "label": "Score",
        "field": "Score",
        "category": "General",
        "valueInt": 236074,
        "value": "236074",
        "rank": 6535595,
        "percentile": 3.0,
        "displayValue": "236,074"
      }

Above is a sample of the information that I pulled so that you can see the structure
public class MainActivity extends AppCompatActivity {

    TextView tv;
    TextView tv2;
    TextView tv3;
    Button submit;
    EditText tbplatform;
    EditText tbhandle;
    String TAG = "TESTRUN";
    String id = "";

    InputStreamReader responseBodyReader;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        tv = (TextView) findViewById(R.id.tvOne);
        tv2 = (TextView) findViewById(R.id.tvTwo);
        tv3 = (TextView) findViewById(R.id.tvThree);
        submit = (Button) findViewById(R.id.btnSubmit);
        tbplatform = (EditText) findViewById(R.id.tbPlatform);
        tbhandle = (EditText) findViewById(R.id.tbHandle);

        submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                final String platform = String.valueOf(tbplatform.getText());
                final String username = String.valueOf(tbhandle.getText());

        AsyncTask.execute(new Runnable() {
            @Override
            public void run() {
                // All your networking logic
                // should be here

                // Create URL
                URL githubEndpoint = null;
                try {
                    githubEndpoint = new URL("https://api.fortnitetracker.com/v1/profile/" + platform+ "/" + username);
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                }

                // Create connection
                HttpsURLConnection myConnection = null;
                try {
                    myConnection =
                            (HttpsURLConnection) githubEndpoint.openConnection();
                } catch (IOException e) {
                    e.printStackTrace();
                }

                myConnection.setRequestProperty("TRN-Api-Key", "API_KEY_HERE");

                try {
                    if (myConnection.getResponseCode() == 200) {
                        InputStream responseBody = myConnection.getInputStream();
                        responseBodyReader =
                                new InputStreamReader(responseBody, "UTF-8");

                        JsonReader jsonReader = new JsonReader(responseBodyReader);

                        jsonReader.beginObject(); // Start processing the JSON object

                        while (jsonReader.hasNext()) { // Loop through all keys
                            final String key = jsonReader.nextName(); // Fetch the next key

                            //Log.v(TAG, key);

                            if (key.equals("epicUserHandle") || key.equals("platformName") || key.equals("accountId")) { // Check if desired key
                                // Fetch the value as a String
                                final String value = jsonReader.nextString();

                                if (key.equals("epicUserHandle")) {
                                    Log.v(TAG, "Gamertag: " + value);

                                }
                                if (key.equals("platformName")) {
                                    Log.v(TAG, "Console: " + value);
                                }
                                if (key.equals("stats")) {

                                    Log.v(TAG, "Kills: " + value);
                                }

                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {

                                        //stuff that updates ui
                                        if(key.equals("epicUserHandle")) {
                                            tv.setText("Username: " + value);
                                        }
                                        if(key.equals("platformName")) {
                                            tv2.setText("Platform: " +value);
                                        }
                                        if(key.equals("accountId")) {
                                            tv3.setText("Account ID: " +value);
                                        }
                                    }
                                });
                                //Log.v(TAG, "" +value);

                                // Do something with the value
                                // ...

                                //break; // Break out of the loop
                            } else {
                                jsonReader.skipValue(); // Skip values of other keys
                            }

                        }

                        jsonReader.close();

                        myConnection.disconnect();
                    } else {
                        // Error handling code goes here
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
     }
    });
    }
}

A: I think this may help you

You Need To Create Some Classes As Given Below

class Score implements Serializable {
private String label;
private String field;
private String category;
private Integer valueInt;
private String value;
private Integer rank;
private Double percentile;
private String displayValue;

public Score() {
    this("", "", "", 0, "", 0, 0.0, "");
}

public Score(String label, String field,
             String category, Integer valueInt,
             String value, Integer rank,
             Double percentile, String displayValue) {
    this.label = label;
    this.field = field;
    this.category = category;
    this.valueInt = valueInt;
    this.value = value;
    this.rank = rank;
    this.percentile = percentile;
    this.displayValue = displayValue;
}

public String getLabel() {
    return label;
}

public void setLabel(String label) {
    this.label = label;
}

public String getField() {
    return field;
}

public void setField(String field) {
    this.field = field;
}

public String getCategory() {
    return category;
}

public void setCategory(String category) {
    this.category = category;
}

public Integer getValueInt() {
    return valueInt;
}

public void setValueInt(Integer valueInt) {
    this.valueInt = valueInt;
}

public String getValue() {
    return value;
}

public void setValue(String value) {
    this.value = value;
}

public Integer getRank() {
    return rank;
}

public void setRank(Integer rank) {
    this.rank = rank;
}

public Double getPercentile() {
    return percentile;
}

public void setPercentile(Double percentile) {
    this.percentile = percentile;
}

public String getDisplayValue() {
    return displayValue;
}

public void setDisplayValue(String displayValue) {
    this.displayValue = displayValue;
}
}

class TRNRating implements Serializable {

private String label;
private String field;
private String category;
private Integer valueInt;
private String value;
private Integer rank;
private Double percentile;
private String displayValue;

public TRNRating() {
    this("", "", "", 0, "", 0, 0.0, "");
}

public TRNRating(String label, String field,
                 String category, Integer valueInt,
                 String value, Integer rank,
                 Double percentile, String displayValue) {
    this.label = label;
    this.field = field;
    this.category = category;
    this.valueInt = valueInt;
    this.value = value;
    this.rank = rank;
    this.percentile = percentile;
    this.displayValue = displayValue;
}

public String getLabel() {
    return label;
}

public void setLabel(String label) {
    this.label = label;
}

public String getField() {
    return field;
}

public void setField(String field) {
    this.field = field;
}

public String getCategory() {
    return category;
}

public void setCategory(String category) {
    this.category = category;
}

public Integer getValueInt() {
    return valueInt;
}

public void setValueInt(Integer valueInt) {
    this.valueInt = valueInt;
}

public String getValue() {
    return value;
}

public void setValue(String value) {
    this.value = value;
}

public Integer getRank() {
    return rank;
}

public void setRank(Integer rank) {
    this.rank = rank;
}

public Double getPercentile() {
    return percentile;
}

public void setPercentile(Double percentile) {
    this.percentile = percentile;
}

public String getDisplayValue() {
    return displayValue;
}

public void setDisplayValue(String displayValue) {
    this.displayValue = displayValue;
}
}

class P2 implements Serializable {
private TRNRating trnRating;
private Score score;

public P2() {
    this(new TRNRating(), new Score());
}

public P2(TRNRating trnRating, Score score) {
    this.trnRating = trnRating;
    this.score = score;
}

public TRNRating getTrnRating() {
    return trnRating;
}

public void setTrnRating(TRNRating trnRating) {
    this.trnRating = trnRating;
}

public Score getScore() {
    return score;
}

public void setScore(Score score) {
    this.score = score;
}
}

class Stats implements Serializable {
private P2 p2;

public Stats() {
    this(new P2());
}

public Stats(P2 p2) {
    this.p2 = p2;
}
}

//You Need To Change Name Of This Class
class Response implements Serializable {
private String accountId;
private Integer platformId;
private String platformName;
private String platformNameLong;
private String epicUserHandle;
private Stats stats;

public Response() {
    this("", 0, "", "", "", new Stats());
}

public Response(String accountId, Integer platformId,
                String platformName, String platformNameLong,
                String epicUserHandle, Stats stats) {
    this.accountId = accountId;
    this.platformId = platformId;
    this.platformName = platformName;
    this.platformNameLong = platformNameLong;
    this.epicUserHandle = epicUserHandle;
    this.stats = stats;
}

public String getAccountId() {
    return accountId;
}

public void setAccountId(String accountId) {
    this.accountId = accountId;
}

public Integer getPlatformId() {
    return platformId;
}

public void setPlatformId(Integer platformId) {
    this.platformId = platformId;
}

public String getPlatformName() {
    return platformName;
}

public void setPlatformName(String platformName) {
    this.platformName = platformName;
}

public String getPlatformNameLong() {
    return platformNameLong;
}

public void setPlatformNameLong(String platformNameLong) {
    this.platformNameLong = platformNameLong;
}

public String getEpicUserHandle() {
    return epicUserHandle;
}

public void setEpicUserHandle(String epicUserHandle) {
    this.epicUserHandle = epicUserHandle;
}

public Stats getStats() {
    return stats;
}

public void setStats(Stats stats) {
    this.stats = stats;
}
}

If your response is same as explained in question. Then this will work.

//In your code after status check you need to do like this
if (myConnection.getResopnseCode() == 200) {
    BufferedReader br=new BufferedReader(responseBodyReader);
    String read = null, entireResponse = "";
    StringBuffer sb = new StringBuffer();
    while((read = br.readLine()) != null) {
        sb.append(read);
    }
    entireResponse = sb.toString();

    //You need to change name of response class
    Response response = new Gson().fromJson(entireResponse , Response.class);

}


Q: Dojo: Saving changes with EnhancedGrid using JsonRestStore? I'm trying to use a EnhancedGrid and a JsonRestStore:

On the server side I have a Rest service which handles Get, Put, Post and Delete requests.
I have two distinct problems, but I wonder wether they are linked:
1- When I double click on any of the editable cells it works fine, I can change the cells' content. But then I can't edit any other editable cell. No matter on which one I click, I won't be able to edit it. For instance if I double click on the 'Select' cell, I will be able to select between the two values, ON or OFF. But then I can no longer edit any other cell. The cell I've just edited will remain displayed with an arrow, and his row will remain selected.
2- The server will never receive any PUT requests. It will receive the GET requests on the initial display and when I scroll the grid, but this is the only REST request I will get on the server side. So I can't figure how to make and save any changes in the grid!
Any clue?