text:
Q: JavaScript design pattern or node packages for nesting of de-normalized/flattened database query results I'm a bit new to NodeJS and using Javascripts for these types of problems, so am feeling a bit stuck here. I'm working with a traditional relational database backend (Postgres) that has a fairly typical hierarchical (i.e. normalized) table/entity structure. One of my requirements for my NodeJs application is to pull data for a page (HTML report) that essentially incorporates all tables, but the page needs to show the data very hierarchically as well. Imagine a query result like this:
[
{"CompanyId":1,"CompanyType":"Technology","CompanyEmployess":3000,"DepartmentId":12,"DepartmentName":"Analytics", "DepartmentEmployees":50, "EmployeeId":1234,"EmployeeName":"Fred","EmployeeHireDate":"2012-09-05"},
{"CompanyId":1,"CompanyType":"Technology","CompanyEmployess":3000,"DepartmentId":12,"DepartmentName":"Analytics", "DepartmentEmployees":50, "EmployeeId":145,"EmployeeName":"Joana","EmployeeHireDate":"2019-09-01"},
{"CompanyId":1,"CompanyType":"Technology","CompanyEmployess":3000,"DepartmentId":8,"DepartmentName":"Accounting", "DepartmentEmployees":25, "EmployeeId":1752,"EmployeeName":"Mary","EmployeeHireDate":"2020-08-01"},
{"CompanyId":1,"CompanyType":"Technology","CompanyEmployess":3000,"DepartmentId":8,"DepartmentName":"Accounting", "DepartmentEmployees":25, "EmployeeId":658,"EmployeeName":"Jose","EmployeeHireDate":"2018-12-01"},
{"CompanyId":1,"CompanyType":"Technology","CompanyEmployess":3000,"DepartmentId":1,"DepartmentName":"Executive", "DepartmentEmployees":4, "EmployeeId":9,"EmployeeName":"Maurice","EmployeeHireDate":"2011-10-01"}
]

But, the best structure for display purposes (in the reporting tools like jsreport) would be more representative of the actual hierarchy, so I can loop through and make nested <tables> and/or <divs>. Like this:
[
  {
    "CompanyId": 1,
    "CompanyType": "Technology",
    "CompanyEmployees": 3000,
    "Departments": [
      {
        "DepartmentId": 12,
        "DepartmentName": "Analytics",
        "DepartmentEmployees": 50,
        "Employees": [
          {
            "EmployeeId": 1234,
            "EmployeeName": "Fred",
            "EmployeeHireDate": "2012-09-05"
          },
          {
            "EmployeeId": 145,
            "EmployeeName": "Joana",
            "EmployeeHireDate": "2019-09-01"
          }
        ]
      },
      {
        "DepartmentId": 8,
        "DepartmentName": "Accounting",
        "DepartmentEmployees": 25,
        "Employees": [
          {
            "EmployeeId": 1752,
            "EmployeeName": "Mary",
            "EmployeeHireDate": "2020-08-01"
          },
          {
            "EmployeeId": 658,
            "EmployeeName": "Jose",
            "EmployeeHireDate": "2018-12-01"
          }
        ]
      },
      {
        "DepartmentId": 1,
        "DepartmentName": "Executive",
        "DepartmentEmployees": 4,
        "Employees": [
          {
            "EmployeeId": 9,
            "EmployeeName": "Maurice",
            "EmployeeHireDate": "2011-10-01"
          }
        ]
      }
    ]
  }
]

I would like to, keep pulling data in a single query call as shown and doing something like array.reduce() or package like 'normalizr' to re-structure the data. I'm open to ideas though.
Where I'm getting lost in the array.reduce() logic is pulling multiple elements that represent a parent object/entity up to the higher level. I would think it would be a common problem, but I can't seem to find examples of people using array.reduce() to do this particular use case.

A: Here is an approach:

const array = [
    {
        "CompanyId": 1,
        "CompanyType": "Technology",
        "CompanyEmployess": 3000,
        "DepartmentId": 12,
        "DepartmentName": "Analytics",
        "DepartmentEmployees": 50,
        "EmployeeId": 1234,
        "EmployeeName": "Fred",
        "EmployeeHireDate": "2012-09-05"
    },
    {
        "CompanyId": 1,
        "CompanyType": "Technology",
        "CompanyEmployess": 3000,
        "DepartmentId": 12,
        "DepartmentName": "Analytics",
        "DepartmentEmployees": 50,
        "EmployeeId": 145,
        "EmployeeName": "Joana",
        "EmployeeHireDate": "2019-09-01"
    },
    {
        "CompanyId": 1,
        "CompanyType": "Technology",
        "CompanyEmployess": 3000,
        "DepartmentId": 8,
        "DepartmentName": "Accounting",
        "DepartmentEmployees": 25,
        "EmployeeId": 1752,
        "EmployeeName": "Mary",
        "EmployeeHireDate": "2020-08-01"
    },
    {
        "CompanyId": 1,
        "CompanyType": "Technology",
        "CompanyEmployess": 3000,
        "DepartmentId": 8,
        "DepartmentName": "Accounting",
        "DepartmentEmployees": 25,
        "EmployeeId": 658,
        "EmployeeName": "Jose",
        "EmployeeHireDate": "2018-12-01"
    },
    {
        "CompanyId": 1,
        "CompanyType": "Technology",
        "CompanyEmployess": 3000,
        "DepartmentId": 1,
        "DepartmentName": "Executive",
        "DepartmentEmployees": 4,
        "EmployeeId": 9,
        "EmployeeName": "Maurice",
        "EmployeeHireDate": "2011-10-01"
    }
];

const result = array.reduce((prev, curr) => {
    const company_found = prev.find(x => x.CompanyId === curr.CompanyId);
    if (!company_found) {
        prev.push({
            CompanyId: curr.CompanyId,
            CompanyType: curr.CompanyType,
            CompanyEmployees: curr.CompanyEmployees,
            Departments: [
                {
                    DepartmentId: curr.DepartmentId,
                    DepartmentName: curr.DepartmentName,
                    DepartmentEmployees: curr.DepartmentEmployees,
                    Employees: [
                        {
                            EmployeeId: curr.EmployeeId,
                            EmployeeName: curr.EmployeeName,
                            EmployeeHireDate: curr.EmployeeHireDate
                        }
                    ]
                }
            ]
        })
    }
    else {
        let department_found = company_found.Departments.find(x => x.DepartmentId === curr.DepartmentId);
        if (department_found) {
            department_found.Employees.push({
                EmployeeId: curr.EmployeeId,
                EmployeeName: curr.EmployeeName,
                EmployeeHireDate: curr.EmployeeHireDate
            });
        }
        else{
            company_found.Departments.push({
                DepartmentId: curr.DepartmentId,
                DepartmentName: curr.DepartmentName,
                DepartmentEmployees: curr.DepartmentEmployees,
                Employees: [
                    {
                        EmployeeId: curr.EmployeeId,
                        EmployeeName: curr.EmployeeName,
                        EmployeeHireDate: curr.EmployeeHireDate
                    }
                ]
            })
        }
    }

    return prev;
}, []);

console.log(JSON.stringify(result, null, 4));

const array = [
    {
        "CompanyId": 1,
        "CompanyType": "Technology",
        "CompanyEmployess": 3000,
        "DepartmentId": 12,
        "DepartmentName": "Analytics",
        "DepartmentEmployees": 50,
        "EmployeeId": 1234,
        "EmployeeName": "Fred",
        "EmployeeHireDate": "2012-09-05"
    },
    {
        "CompanyId": 1,
        "CompanyType": "Technology",
        "CompanyEmployess": 3000,
        "DepartmentId": 12,
        "DepartmentName": "Analytics",
        "DepartmentEmployees": 50,
        "EmployeeId": 145,
        "EmployeeName": "Joana",
        "EmployeeHireDate": "2019-09-01"
    },
    {
        "CompanyId": 1,
        "CompanyType": "Technology",
        "CompanyEmployess": 3000,
        "DepartmentId": 8,
        "DepartmentName": "Accounting",
        "DepartmentEmployees": 25,
        "EmployeeId": 1752,
        "EmployeeName": "Mary",
        "EmployeeHireDate": "2020-08-01"
    },
    {
        "CompanyId": 1,
        "CompanyType": "Technology",
        "CompanyEmployess": 3000,
        "DepartmentId": 8,
        "DepartmentName": "Accounting",
        "DepartmentEmployees": 25,
        "EmployeeId": 658,
        "EmployeeName": "Jose",
        "EmployeeHireDate": "2018-12-01"
    },
    {
        "CompanyId": 1,
        "CompanyType": "Technology",
        "CompanyEmployess": 3000,
        "DepartmentId": 1,
        "DepartmentName": "Executive",
        "DepartmentEmployees": 4,
        "EmployeeId": 9,
        "EmployeeName": "Maurice",
        "EmployeeHireDate": "2011-10-01"
    }
];

const result = array.reduce((prev, curr) => {
    const company_found = prev.find(x => x.CompanyId === curr.CompanyId);
    if (!company_found) {
        prev.push({
            CompanyId: curr.CompanyId,
            CompanyType: curr.CompanyType,
            CompanyEmployees: curr.CompanyEmployees,
            Departments: [
                {
                    DepartmentId: curr.DepartmentId,
                    DepartmentName: curr.DepartmentName,
                    DepartmentEmployees: curr.DepartmentEmployees,
                    Employees: [
                        {
                            EmployeeId: curr.EmployeeId,
                            EmployeeName: curr.EmployeeName,
                            EmployeeHireDate: curr.EmployeeHireDate
                        }
                    ]
                }
            ]
        })
    }
    else {
        let department_found = company_found.Departments.find(x => x.DepartmentId === curr.DepartmentId);
        if (department_found) {
            department_found.Employees.push({
                EmployeeId: curr.EmployeeId,
                EmployeeName: curr.EmployeeName,
                EmployeeHireDate: curr.EmployeeHireDate
            });
        }
        else{
            company_found.Departments.push({
                DepartmentId: curr.DepartmentId,
                DepartmentName: curr.DepartmentName,
                DepartmentEmployees: curr.DepartmentEmployees,
                Employees: [
                    {
                        EmployeeId: curr.EmployeeId,
                        EmployeeName: curr.EmployeeName,
                        EmployeeHireDate: curr.EmployeeHireDate
                    }
                ]
            })
        }
    }

    return prev;
}, []);

console.log(JSON.stringify(result, null, 4));```


text:
Q: trying to sum two strings and store the result in another string? I was trying to sum two strings together, this is my attempt:

*

*convert strings to numbers using strtol, because it's safer than atoi.

*compute sum.

*find number of digits using log (base 10) rounded using floor + 1. (it's the fastest method to do that task). (I've used floor, because floor rounds number to the nearest integer at the left hand side).

*I've allocated enough memory in the heap to store each digit.

*I've used snprintf to store the number in the string.

the problem is that the function returns only "4", and not "42". I think the delicate part is the last step.
another thing is: "possible loss of data: from double to size_t". but it's rounded, therefore it shouldn't be a problem, but I still have it in the error/warning list. (I use visual studio).

#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <stdio.h>

char* sum_of_strings(const char* a, const char* b) {
    int x = strtol(a, NULL, 10); int y = strtol(b, NULL, 10);
    int sum = x + y;
    size_t length = floor(log10(sum)) + 1;
    char* str = malloc(length +1);
    if (str == NULL) {
        return NULL;
    }
    snprintf(str, length, "%d", sum);
    return str;
}

int main(void) {
    char a[] = "34";
    char b[] = "8";
    char* str = sum_of_strings(a, b);

    free(str);
    return 0;
}

A: You may be overthinking the problem.
The maximum size of the output string is [considerably] less than 64 bytes.
So, if we use a fixed size buffer to do sprintf on, we can eliminate all the floating point rounding altogether:
char *
sum_of_strings(const char *a,const char *b)
{
    int x = strtol(a,NULL,10);
    int y = strtol(b,NULL,10);

    int sum = x + y;

    char str[64];
    sprintf(str, "%d", sum);

    return strdup(str);
}

The above code is pretty simple and fast.
However, strdup has to [effectively] scan the string twice: once to get the length and a second time to copy it to the allocated buffer.
We can [probably] make this slightly faster:
char *
sum_of_strings(const char *a,const char *b)
{
    long x = strtol(a,NULL,10);
    long y = strtol(b,NULL,10);

    long sum = x + y;

    char str[64];
    ssize_t len = sprintf(str, "%ld", sum);

    // add space for EOS
    ++len;

    char *ret = malloc(len);
    if (ret != NULL)
        memcpy(ret,str,len);

    return ret;
}

Rather than using floating point, the usual way to get the number of digits is something like:
size_t len = (sum != 0) ? 0 : 1;
for (long tmp = sum;  tmp != 0;  tmp /= 10, ++len);

Arguably, this may be slower than the floating point [on systems that have fast H/W FPUs]. I presume you've benchmarked both ways [to be able to state your F.P. method is fastest]. If not, the above may be a drop in replacement for your F.P. code.
Is floor(log10(sum)) really faster [on average] than 5 fixed point divides?

But even that doesn't account for hidden costs.
sprintf et. al. has to do much the same when generating its output (e.g. sum % 10 and sum /= 10).
If we're "crazy" for speed, and if we do our own limited version of what sprintf does, we can do the length calculation in the same loop as the digit stores:
#include <stdlib.h>
#include <string.h>

#define MAXBUF  64

char *
sum_of_strings(const char *a,const char *b)
{
    long x = strtol(a,NULL,10);
    long y = strtol(b,NULL,10);

    long sum = x + y;

    char str[MAXBUF];
    char *lhs = &str[MAXBUF];

    // store digits in right-to-left order
    for (;  sum != 0;  sum /= 10)
        *--lhs = (sum % 10) + '0';

    // get number of digits
    size_t len = &str[MAXBUF] - lhs;

    // handle special case of sum being zero
    if (len == 0) {
        *--lhs = '0';
        ++len;
    }

    // allocate the space
    char *ret = malloc(len);

    // copy out the data
    if (ret != NULL) {
        memcpy(ret,lhs,len);
        ret[len] = 0;
    }

    return ret;
}

Of course, which method is "best" depends on simplicity/complexity vs. [benchmarked] speed. That is, is added complexity for [possible] speed gains worth it?
YMMV ...

A: I've modified your sum_of_strings code and it seems to now be working based on your example.
Changes include the following:

*

*Data types are now longs instead of ints

*I've added two bytes to the length to account for the floor and the null byte

*The last byte of the string is set to the null byte which makes printing work correctly

char* sum_of_strings(const char* a, const char* b) {
    long const x = strtol(a, NULL, 10);
    long const y = strtol(b, NULL, 10);
    long const sum = x + y;
    size_t const length = floor(log10(sum)) + 2;
    char * const str = malloc(length);
    if (str == NULL) {
        return NULL;
    }
    snprintf(str, length, "%ld", sum);
    str[length - 1] = '\0';
    return str;
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Connect to database without using session Is there a way to connect to database and store my transient object but without using session.
I was asked in an interview if this thing is possible.

A: When you connect to a database you call it connection, not session. And yes, if you want to write an object to a database you need a connection (and also a transaction).
BUT transient means something like temporary - you never store transient object into the database. If you mark an attribut as transient it won't get loaded/stored during a read or write to the database.


text:
Q: I am getting Migration error whenever i am creating a new Realm class? I have created a class that extends RealmObject and whenever i try to run the class i get runTime exception as follows:

06-09 00:58:16.333 30719-30719/com.khaalijeb.inkdrops
  E/AndroidRuntime: FATAL EXCEPTION: main
      Process: com.khaalijeb.inkdrops, PID: 30719
      io.realm.exceptions.RealmMigrationNeededException: Migration is required due to the following errors:
      - Class 'transactionacknowledgedata' has been added.
          at io.realm.internal.OsSharedRealm.nativeGetSharedRealm(Native Method)
          at io.realm.internal.OsSharedRealm.(OsSharedRealm.java:171)
          at io.realm.internal.OsSharedRealm.getInstance(OsSharedRealm.java:241)
          at io.realm.BaseRealm.(BaseRealm.java:136)
          at io.realm.BaseRealm.(BaseRealm.java:105)
          at io.realm.Realm.(Realm.java:164)
          at io.realm.Realm.createInstance(Realm.java:435)
          at io.realm.RealmCache.doCreateRealmOrGetFromCache(RealmCache.java:342)
          at io.realm.RealmCache.createRealmOrGetFromCache(RealmCache.java:282)
          at io.realm.Realm.getDefaultInstance(Realm.java:343)
          at com.khaalijeb.inkdrops.Fragment.NewPendingFragment.onCreate(NewPendingFragment.java:147)
          at android.support.v4.app.Fragment.performCreate(Fragment.java:2236)
          at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1285)
          at android.support.v4.app.FragmentTransition.addToFirstInLastOut(FragmentTransition.java:1085)
          at android.support.v4.app.FragmentTransition.calculateFragments(FragmentTransition.java:976)
          at android.support.v4.app.FragmentTransition.startTransitions(FragmentTransition.java:95)
          at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2198)
          at android.support.v4.app.FragmentManagerImpl.optimizeAndExecuteOps(FragmentManager.java:2155)
          at android.support.v4.app.FragmentManagerImpl.execSingleAction(FragmentManager.java:2034)
          at android.support.v4.app.BackStackRecord.commitNowAllowingStateLoss(BackStackRecord.java:626)
          at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:143)
          at android.support.v4.view.ViewPager.populate(ViewPager.java:1268)
          at android.support.v4.view.ViewPager.populate(ViewPager.java:1116)
          at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1642)
          at android.view.View.measure(View.java:23167)
          at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:715)
          at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:461)
          at android.view.View.measure(View.java:23167)
          at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:715)
          at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:461)
          at android.view.View.measure(View.java:23167)
          at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6749)
          at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
          at android.view.View.measure(View.java:23167)
          at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6749)
          at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
          at android.support.v7.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:139)
          at android.view.View.measure(View.java:23167)
          at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6749)
          at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1535)
          at android.widget.LinearLayout.measureVertical(LinearLayout.java:825)
          at android.widget.LinearLayout.onMeasure(LinearLayout.java:704)
          at android.view.View.measure(View.java:23167)
          at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6749)
          at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
          at android.view.View.measure(View.java:23167)
          at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6749)
          at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1535)
          at android.widget.LinearLayout.measureVertical(LinearLayout.java:825)
          at android.widget.LinearLayout.onMeasure(LinearLayout.java:704)
          at android.view.View.measure(View.java:23167)
          at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6749)
          at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
          at com.android.internal.policy.DecorView.onMeasure(DecorView.java:716)
  06-09 00:58:16.334 30719-30719/com.khaalijeb.inkdrops
  E/AndroidRuntime:     at android.view.View.measure(View.java:23167)
          at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2693)
          at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1559)
          at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1830)
          at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1447)
          at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:7130)
          at android.view.Choreographer$CallbackRecord.run(Choreographer.java:935)
          at android.view.Choreographer.doCallbacks(Choreographer.java:747)
          at android.view.Choreographer.doFrame(Choreographer.java:682)
          at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:921)
          at android.os.Handler.handleCallback(Handler.java:873)
          at android.os.Handler.dispatchMessage(Handler.java:99)
          at android.os.Looper.loop(Looper.java:193)
          at android.app.ActivityThread.main(ActivityThread.java:6642)
          at java.lang.reflect.Method.invoke(Native Method)
          at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
          at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)

i dont know why i am getting this error. Anyone out there faced this problem?

A: Remember when in SQLite you wanted to add a table, so you had to do this:
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    int currentVersion = oldVersion;
    if(currentVersion == 1) {
        db.execSql("CREATE TABLE Blah(personId int, name varchar(255))");
        currentVersion++;
    }
    ...
}

And so on?
Well Realm is not SQLite, but it still needs you to modify the schema to add the new model classes and apply schema changes you want.
So you need to define a Migration (see this whole section about it in the docs) that handles the schema version change from X to Y.

So you create a migration:
public class Migration implements RealmMigration {

    @Override
    public void migrate(final DynamicRealm realm, long oldVersion, long newVersion) {
        ...
    }

    @Override
    public int hashCode() { return Migration.class.hashCode(); }

    @Override
    public boolean equals(Object obj) { return obj != null && obj instanceof Migration; }
}

Bump the schema version and specify the migration to the RealmConfiguration
Realm.setDefaultConfiguration(new RealmConfiguration.Builder()
                                    .schemaVersion(currentVersion+1) // probably a constant somewhere
                                    .migration(new Migration())
                                    .build());

And you actually need to write the migration using the DynamicRealm API that adds the newly added class.
@Override
public void migrate(DynamicRealm realm, long oldVersion, long newVersion) {
    RealmSchema schema = realm.getSchema();
    if(oldVersion == 0) {
        RealmObjectSchema transactionacknowledgedata =
                               schema.create("transactionacknowledgedata");
        transactionacknowledgedata.addField("name", String.class);
        oldVersion++;
    }
}

Well it's either that, or you set new RealmConfiguration.Builder().deleteIfMigrationNeeded().build() and you'll delete (and recreate) the Realm whenever there is a model change.


text:
Q: Load XIB this class is not key value coding-compliant for the key I just create custom UIView with name PopupViewForViewMoreDetail and I want to add this custom view in my ViewController but each time getting below error

Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<0x7f8155f2e430> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key mainView.'

if I remove IBOutlet  of mainView then It will be display error for another variable.
Below is my code
import UIKit

class PopupViewForViewMoreDetail: UIView {

    @IBOutlet var darkBGView: UIView!
    @IBOutlet var outerView: UIView!
    @IBOutlet var mainView: UIView!
    @IBOutlet var btnClose: UIButton!

    override init(frame: CGRect) {
        super.init(frame: frame)
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
}

and I'm adding this view in my viewController class like below.
 let viewMoreDetailPopUp =  Bundle.main.loadNibNamed("PopupViewForViewMoreDetail", owner: self, options: nil)?.first as! PopupViewForViewMoreDetail
        self.view.addSubview(viewMoreDetailPopUp)

Below is my screenshot for IBOutlets

I also checked below answer but didn't help me.
What does this mean? "'NSUnknownKeyException', reason: … this class is not key value coding-compliant for the key X"
Guide me where I'm going wrong in my code ?

A: try this :

step 1:

let viewMoreDetailPopUp =  UINib(nibName: "PopupViewForViewMoreDetail", bundle: nil).instantiate(withOwner: self, options: nil).first as! PopupViewForViewMoreDetail

step 2:
  make sure you're setting class for the view instead of File's Owner

Step 3 :
  Remove all outlets and re-outlet again

A: For me it was that I copied a xib to make a new variation and it unchecked inherit module from target.


text:
Q: constrained bayesian linear regression I am trying to carry out bayesian linear regression subject to linear inequality constraints on the coefficients. I have no idea how to add constraints in a bayesian framework.
Is this even possible?

A: Hi Muhammad Asif Rana,
I suggest using bnlearn package in R. It support data with linear relations, i tried the package with generated linear Gaussian distribution and it estimated the coefficients perfectly (it can also estimate uniform distribution). Moreover, you can add constraint by first modelling the DAG of the Bayesian network and score it OR you can use attached penalizing function from the same package (check the package book for penalizing details).


text:
Q: Visual C++ errors C3867 and C2664 #define UCHAR unsigned char

typedef bool (*FUNC)(UCHAR uc1, UCHAR uc2);
typedef void(*PF)(FUNC, UCHAR*);
PF    Assign;

class Class  {
    private:
       UCHAR buf[32];
       bool func(UCHAR c1, UCHAR c2)  { }

    public:
       Class::Class(void)  {
          Assign( func, buf );         // <<< Microsoft VC++ error C3867
       }

       Class::~Class()  { }
};

error C3867: 'Class::func': function call missing argument list;
  use '&Class::func' to create a pointer to member

If I try the suggestion in the error message above

Assign( &Class::func, buf );         // <<< Microsoft VC++ error C2664

I get this error:

error C2664: 'void (FUNC,unsigned char *)' : cannot convert
  parameter 1 from 'bool (__thiscall Class::* )(unsigned char,unsigned char)'
  to 'FUNC'
  There is no context in which this conversion is possible

Without changing anything else how can I get this Assign() function to compile?
These typedefs are from a library that I need to interface with.

A: func is a non-static member function, so its type is bool (Class::*)(UCHAR, UCHAR), while Assign requires bool (*)(UCHAR, UCHAR). You cannot convert a non-static member function to a non-member function.
To be able to pass func into Assign, you'll have to make func static.

A: The type-aliases FUNC and PF are not a member function pointers, and can only be used to point to static member functions. The reason being that all non-static member functions have an implicit first argument for the this pointer.
If you need generic function "pointers" you should look into std::function:
typedef std::function<bool(UCHAR uc1, UCHAR uc2)> FUNC;
typedef std::function<void(FUNC, UCHAR*)> PF;
PF    Assign;

Class::Class(void)  {
    Assign( std::bind(&Class::func, *this), buf );
}


text:
Q: Updating d3.layout.force v3 to d3.forceSimulation v7 I am trying to update a force-directed graph written using d3js version 3 to d3js version 7.
The following code snippet is the working implementation using d3js v3:

var svg = d3.select("svg"),
  width = +svg.attr("width"),
  height = +svg.attr("height");

graph = {
  nodes: [],
  links: [],
}

var simulation = d3.layout.force()
  .size([width, height])
  .nodes(graph.nodes)
  .links(graph.links)
  .on("tick", function() {
    svg.selectAll('.link')
      .attr("x1", function (d) { return d.source.x })
      .attr("y1", function (d) { return d.source.y })
      .attr("x2", function (d) { return d.target.x })
      .attr("y2", function (d) { return d.target.y })

    svg.selectAll('.node')
      .attr("cx", function (d) { return d.x })
      .attr("cy", function (d) { return d.y })
      .attr("transform", function (d) {
        return "translate(" + d.x + "," + d.y + ")";
      })
  });

function update() {
  // update links
  var link = svg.selectAll('.link').data(graph.links);
  link.enter()
    .insert('line', '.node')
    .attr('class', 'link')
    .style('stroke', '#d9d9d9');
  link
    .exit()
    .remove()

  // update nodes
  var node = svg.selectAll('.node').data(graph.nodes);
  var g = node.enter()
            .append('g')
            .attr('class', 'node');
  g.append('circle')
    .attr("r", 20)
    .style("fill", "#d9d9d9");
  g.append('text')
    .attr("class", "text")
    .text(function (d) { return d.name });
  node
    .exit()
    .remove();

  // update simulation
  simulation
    .linkDistance(100)
    .charge(-200)
    .start();
};

function addNode(node) {
  graph.nodes.push(node);
  update();
};

function connectNodes(source, target) {
  graph.links.push({
    source: source,
    target: target,
  });
  update();
};

addNode({
  id: "you",
  name: "you",
});

let index = 1;

// add a new node every three seconds and connect to 'you'
const interval = window.setInterval(() => {
  let id = Math.random().toString(36).replace('0.','');
  id = id.slice(0,4);
  addNode({
      id: id,
      name: id
  });

  connectNodes(0, index);
  index++;
}, 3000);

// no more than 8 nodes
setTimeout(() => {
  clearInterval(interval)
}, 3000 * 8);
<html>
<head>
  <script src="https://d3js.org/d3.v3.min.js"></script>
</head>
<body>
  <svg width="400" height="200"></svg>
</body>
</html>

The following code snippet my attempt of implementing the above code snippet using d3js v7:

var svg = d3.select("svg"),
  width = +svg.attr("width"),
  height = +svg.attr("height");

graph = {
  nodes: [],
  links: [],
}

var simulation = d3.forceSimulation()
  .force("center", d3.forceCenter(width / 2, height / 2).strength(0.01))
  .nodes(graph.nodes)
  .force("link", d3.forceLink(graph.links).distance(100))
  .on("tick", function() {
    svg.selectAll('.link')
      .attr("x1", function (d) { return d.source.x })
      .attr("y1", function (d) { return d.source.y })
      .attr("x2", function (d) { return d.target.x })
      .attr("y2", function (d) { return d.target.y })

    svg.selectAll('.node')
      .attr("cx", function (d) { return d.x })
      .attr("cy", function (d) { return d.y })
      .attr("transform", function (d) {
        return "translate(" + d.x + "," + d.y + ")";
      })
  });

function update() {
  // update links
  var link = svg.selectAll('.link').data(graph.links);
  link.enter()
    .insert('line', '.node')
    .attr('class', 'link')
    .style('stroke', '#d9d9d9');
  link
    .exit()
    .remove()

  // update nodes
  var node = svg.selectAll('.node').data(graph.nodes);
  var g = node.enter()
            .append('g')
            .attr('class', 'node');
  g.append('circle')
    .attr("r", 20)
    .style("fill", "#d9d9d9");
  g.append('text')
    .attr("class", "text")
    .text(function (d) { return d.name });
  node
    .exit()
    .remove();

  // update simulation
  simulation
    .nodes(graph.nodes)
    .force("link", d3.forceLink(graph.links).distance(100))
    .force("charge", d3.forceManyBody().strength(-200))
    .restart()
};

function addNode(node) {
  graph.nodes.push(node);
  update();
};

function connectNodes(source, target) {
  graph.links.push({
    source: source,
    target: target,
  });
  update();
};

addNode({
  id: "you",
  name: "you",
});

let index = 1;

// add a new node every three seconds and connect to 'you'
const interval = window.setInterval(() => {
  let id = Math.random().toString(36).replace('0.','');
  id = id.slice(0,4);
  addNode({
      id: id,
      name: id
  });

  connectNodes(0, index);
  index++;
}, 3000);

// no more than 8 nodes
setTimeout(() => {
  clearInterval(interval)
}, 3000 * 8);
<html>
<head>
  <script src="https://d3js.org/d3.v7.min.js"></script>
</head>
<body>
  <svg width="400" height="200"></svg>
</body>
</html>

The d3js v7 code snippet does not produce the same results as d3js v3 - why is this? The exact changes I have done are seen in this diff: https://www.diffchecker.com/wdq7AFbU.
Even without adding any connections, there is a difference between the two implementations. The v3 implementation makes the "you" node fly in from random directions, whilst with the v7 implementation the "you" node always flies in from the same direction.
There also seems to be some discrepancy on how the force is being applied since the new nodes in the v7 implementation get stuck in the top-left corner.

A: I've noticed the attributes of DOMs are reflecting the status alright. It's just that the simulation just stopped prematurely.
In short, the default value of d3.force.alphaDecay is too short for the intended result; alphaDecay dictates the end of simulation. Try expand the value a little bit. The latest default value for alphaDecay is 0.001, according to d3-force github readme. In my testing session, setting the value to 1/5(0.0002) seems to be enough for the same result.
try run the code below. it works fine.
Tips
When working with DOMs and SVGs, try add matching data-ooo tag to see if the d3.selection is working properly. I've added properties of node data such as .index and .target, .source to attributes like data-index,data-id,data-target,data-source... and noticed that everything is in place.

var svg = d3.select("svg"),
  width = +svg.attr("width"),
  height = +svg.attr("height");

graph = {
  nodes: [],
  links: [],
}

var simulation = d3.forceSimulation()
  .force("center", d3.forceCenter(width / 2, height / 2).strength(0.01))
  .nodes(graph.nodes)
  .force("link", d3.forceLink(graph.links).distance(100))
  .on("tick", function() {
    svg.selectAll('.link')
      .attr("x1", function (d) { return d.source.x })
      .attr("y1", function (d) { return d.source.y })
      .attr("x2", function (d) { return d.target.x })
      .attr("y2", function (d) { return d.target.y })

    svg.selectAll('.node')
      .attr("cx", function (d) { return d.x })
      .attr("cy", function (d) { return d.y })
      .attr("transform", function (d) {
        return "translate(" + d.x + "," + d.y + ")";
      })
  }).alphaDecay(0.0002) // just added alpha decay to delay end of execution

function update() {
  // update links
  var link = svg.selectAll('.link').data(graph.links);
  link.enter()
    .insert('line', '.node')
    .attr('class', 'link')
    .style('stroke', '#d9d9d9');
  link
    .exit()
    .remove()

  // update nodes
  var node = svg.selectAll('.node').data(graph.nodes);
  var g = node.enter()
            .append('g')
            .attr('class', 'node');
  g.append('circle')
    .attr("r", 20)
    .style("fill", "#d9d9d9");
  g.append('text')
    .attr("class", "text")
    .text(function (d) { return d.name });
  node
    .exit()
    .remove();

  // update simulation
  simulation
    .nodes(graph.nodes)
    .force("link", d3.forceLink(graph.links).distance(100))
    .force("charge", d3.forceManyBody().strength(-200))
    .restart()
};

function addNode(node) {
  graph.nodes.push(node);
  update();
};

function connectNodes(source, target) {
  graph.links.push({
    source: source,
    target: target,
  });
  update();
};

addNode({
  id: "you",
  name: "you",
});

let index = 1;

// add a new node every three seconds and connect to 'you'
const interval = window.setInterval(() => {
  let id = Math.random().toString(36).replace('0.','');
  id = id.slice(0,4);
  addNode({
      id: id,
      name: id
  });

  connectNodes(0, index);
  index++;
}, 3000);

// no more than 8 nodes
setTimeout(() => {
  clearInterval(interval)
}, 3000 * 8);
<html>
<head>
  <script src="https://d3js.org/d3.v7.min.js"></script>
</head>
<body>
  <svg width="400" height="200"></svg>
</body>
</html>

Edit: What is alpha and alphaDecay?

doing simulation.restart().alpha(0.3) seem to give the same effect which was mentioned in an answer to my earlier post. Is there any difference between the two?

d3-force github readme says alpha stands for entropy. In easy words, alpha stands for the life of simulation; alpha=1 stands for start and alpha=0 stands for the end.

https://github.com/d3/d3-force#simulation_alpha
alpha is roughly analogous to temperature in simulated annealing. It decreases over time as the simulation "cools down". When alpha reaches alphaMin, the simulation stops

here's a simple pseudocode that illustrates the idea.
alpha = 1
alphaDecay = 0.002
function tick() {
  alpha = alpha - alphaDecay
}

loop {
  tick()
  if alpha equals to 0 then end simulation
}

the previous answer mentioned in the comment increased alpha when restart because he wanted to give simulation more time after a reset.
in my answer, I've set alphaDecay to a lower number so that the simulation can work for a longer period of time.

*

*increasing alphaDecay/decreasing alpha = simulation ends quicker

*decreasing alphaDecay/increasing alpha  = simulation ends later

Edit: Changes in d3-force since D3 v4?

Also, there is still some difference between the v3 and v7 implementation; 1) the collisions in v3 is more elastic and 2) the new nodes being added come in from random directions. Do you know what could be fixed to get 1) and 2) in the v7 implementation?

please read this d3-force v1 github changelog; d3-force became a separate package since d3 v4 and this changelog explains the changes.
1. d3-force has become more accurate.
The changelog mentions many improvements:

The force simulation now uses velocity Verlet integration rather than position Verlet, tracking the nodes' positions (node.x, node.y) and velocities (node.vx, node.vy) rather than their previous positions (node.px, node.py).
The new link force replaces force.linkStrength and employs better default heuristics to improve stability.

The physics integration of d3-force has improved for better accuracy. This is why it looks different from v3 implementation.
Although it is possible to tune the simulation look like in a specific way but what does more elastic mean? Does it mean stronger reaction force? or does it mean faster animation(but in same amount of time)? it surely can be tuned in, only if the request was more detailed. And every d3 package has surprisingly simple structure and formulas. It is possible to look inside and change its inner function.
2. manipulating positions of nodes
https://github.com/d3/d3-force#simulation_nodes
manipulate .x and .y of nodes during the simulation to change their positions.
addNode({ id: /* ... */, x: 0, y: 100}) // like this

edit: there were some typos in my answer about the increase-decrease relation of alpha and time.


text:
Q: How to achieve fixed thread pool without using ExecutorService I have code block like this
   static ExecutorService executor = Executors.newFixedThreadPool(4);
   Runnable worker = new CsvToJavaObject(newFilePath);
   executor.execute(worker);

I want to limit the number of threads to n(4) and not use Executor Service.How can i do it ?

A: What about ThreadPoolExecutor?
ThreadPoolExecutor threadPool = new ThreadPoolExecutor(5, 5, 5, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());

A: Is "4" the count of your cores? Are you trying to limit your parallel executions to the number of cores in the system?
If so: I would just use TPL (e.g "new Task(Action)") instead, which is already respecting your system setup.
If you want, you can even manually set the number of threads the threadpool offers, see ThreadPool.SetMinThreads, but there are only a few situations where that would make sense...
Edit: My mistake, thought it was a c# issue...

A: If you want to spawn a task only as required you actually want a modified BlockingQueue.
When the thread pool has a free thread, it performs a blocking take() on the queue.  Your modified Queue could create a task on demand.


text:
Q: ionic cannot open url in browser within http request i'm unable to open a link using window.open whithin a http request.
Here is how i tried:
     const config = {
      headers: {token: this.apiKey, authtoken: token},
    };
    const url = `https://api.eatsmartapp.de/delivery/users/receipt?id=${this.orderId}`;
    // @ts-ignore
    this.http.get<any>(url, config).subscribe(dataset => {
      window.open('link', '_blank');

    }, error => {

    });

If i try to open the link outside the subscription area its working fine but if i try to open it in my subscription, nothing is happening on my mobile device

A: Try using window as a service. In your module.ts file
providers: [
    { provide: Window, useValue: window }
]

Then in your component.ts, or wherever
constructor(private window: Window) {
    // ...
}

in which case your window.open would be like
this.http.get<any>(url, config).subscribe(dataset => {
      this.window.open(dataset.url, '_blank');

    }


text:
Q: Jetty only serving static files For some weird reason I can not get jetty to properly deploy my gwt project.
I have put the war folder in the webapps folder and renamed it to root after that i can start jetty and it recognizes the project and its web.xml.
2013-12-03 12:27:49.576:INFO:oejs.Server:main: jetty-9.0.6.v20130930
2013-12-03 12:27:49.699:INFO:oejdp.ScanningAppProvider:main: Deployment monitor [file:/home/spydon/bin/jetty/webapps/] at interval 1
2013-12-03 12:27:50.841:INFO:oejsh.ContextHandler:main: Started o.e.j.w.WebAppContext@321236f4{/,file:/home/spydon/bin/jetty/webapps/root/,AVAILABLE}{/root}
2013-12-03 12:27:50.943:INFO:oejs.ServerConnector:main: Started ServerConnector@5f909402{HTTP/1.1}{0.0.0.0:8080}

But when visiting the page(146.185.176.150:8080/) I can only see the static welcome page. No errors are recorded to the logs.
This is basically my web.xml, except that there is a lot more servlet mappings in the real one.
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"                                                                     [89/1588]
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
              http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
         version="2.5"
         xmlns="http://java.sun.com/xml/ns/javaee">

  <!-- Servlets -->

  <servlet>
    <servlet-name>missionServlet</servlet-name>
    <servlet-class>net.mindlevel.server.MissionServiceImpl</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>missionServlet</servlet-name>
    <url-pattern>/mindlevel/mission</url-pattern>
  </servlet-mapping>

  <!-- Default page to serve -->
  <welcome-file-list>
    <welcome-file>Mindlevel.html</welcome-file>
  </welcome-file-list>

</web-app>

It is jetty-9.0.6.v20130930 running on debian 7.0 x64

A: My fault, all of the GWT generated files did not make it to the server on deploy. So jetty was working perfectly fine all the time.


text:
Q: Aggregation and extra values with Django I have a model which looks like this:
class MyModel(models.Model)
    value = models.DecimalField()
    date = models.DatetimeField()

I'm doing this request:
MyModel.objects.aggregate(Min("value"))

and I'm getting the expected result:
{"mymodel__min": the_actual_minimum_value}

However, I can't figure out a way to get at the same time the minimum value AND the associated date (the date at which the minimum value occured).
Does the Django ORM allow this, or do I have to use raw SQL ?

A: What you want to do is annotate the query, so that you get back your usual results but also have some data added to the result. So:
MyModel.objects.annotate(Min("value"))

Will return the normal result with mymodel__min as an additional value
In reply to your comment, I think this is what you are looking for? This will return the dates with their corresponding Min values.
MyModel.objects.values('date').annotate(Min("value"))

Edit: In further reply to your comment in that you want the lowest valued entry but also want the additional date field within your result, you could do something like so:
MyModel.objects.values('date').annotate(min_value=Min('value')).order_by('min_value')[0]

This will get the resulting dict you are asking for by ordering the results and then simply taking the first index which will always be the lowest value.
See more


text:
Q: How can I carry out multiple different animations at different times with the same UIButton? I am creating an animation sequence where when one button is pressed one object fades out. When the same button is pressed again another object fades out. This keeps happening until 8 objects are faded out. I have tried and played around with code and so far have got the code to fade out one object, and two or more at a time, but have not successfully been able to do it as described above. This is my code so far:
import UIKit

class DrinkWaterViewController: UIViewController {

    @IBOutlet weak var glassOne: UIImageView!
    @IBOutlet weak var glassTwo: UIImageView!
    @IBOutlet weak var glassThree: UIImageView!
    @IBOutlet weak var glassFour: UIImageView!
    @IBOutlet weak var glassFive: UIImageView!
    @IBOutlet weak var glassSix: UIImageView!
    @IBOutlet weak var glassSeven: UIImageView!
    @IBOutlet weak var glassEight: UIImageView!

    override func viewDidLoad() {
        super.viewDidLoad()

        self.glassOne.alpha = 1.0
        self.glassTwo.alpha = 1.0
    }

    @IBAction func drunkOne(_ sender: Any){

        if self.glassOne.alpha == 1.0{

        UIView.animate(withDuration: 1.5, delay: 0.2, animations:
            {self.glassOne.alpha = CGFloat(0.1)}
        )
    }
}

A: Put your glasses into an array glasses and add a property to keep track of nextToFade.  Then just fade the glasses[nextToFade] and increment nextToFade by 1:
class DrinkWaterViewController: UIViewController {

    @IBOutlet weak var glassOne: UIImageView!
    @IBOutlet weak var glassTwo: UIImageView!
    @IBOutlet weak var glassThree: UIImageView!
    @IBOutlet weak var glassFour: UIImageView!
    @IBOutlet weak var glassFive: UIImageView!
    @IBOutlet weak var glassSix: UIImageView!
    @IBOutlet weak var glassSeven: UIImageView!
    @IBOutlet weak var glassEight: UIImageView!

    // array to hold the glasses so that they can be indexed
    var glasses = [UIImageView]()

    // index of next glass to fade
    var nextToFade = 0

    override func viewDidLoad() {
        super.viewDidLoad()

        // put the glasses into the array
        glasses = [glassOne, glassTwo, glassThree, glassFour,
                    glassFive, glassSix, glassSeven, glassEight]

        // make sure they're all visible
        glasses.forEach { $0.alpha = 1.0 }
    }

    @IBAction func drunkOne(_ sender: Any) {
        // make sure not to index beyond the end of the array
        guard nextToFade < glasses.count else { return }

        let glass = glasses[nextToFade]
        nextToFade += 1
        UIView.animate(withDuration: 1.5, delay: 0.2, animations:
            { glass.alpha = 0.1 }
        )
    }
}


text:
Q: How to Create a function that returns the total number of boomerangs in an array A boomerang is a V-shaped sequence that is either upright or upside down. Specifically, a boomerang can be defined as: sub-array of length 3, with the first and last digits being the same and the middle digit being different.
Some boomerang examples:
[3, 7, 3], [1, -1, 1], [5, 6, 5]

Create a function that returns the total number of boomerangs in an array.
To illustrate:
[3, 7, 3, 2, 1, 5, 1, 2, 2, -2, 2]
# 3 boomerangs in this sequence:  [3, 7, 3], [1, 5, 1], [2, -2, 2]

Be aware that boomerangs can overlap, like so:
[1, 7, 1, 7, 1, 7, 1]
# 5 boomerangs (from left to right): [1, 7, 1], [7, 1, 7], [1, 7, 1], [7, 1, 7], and [1, 7, 1]

Examples:
count_boomerangs([9, 5, 9, 5, 1, 1, 1]) ➞ 2
count_boomerangs([5, 6, 6, 7, 6, 3, 9]) ➞ 1
count_boomerangs([4, 4, 4, 9, 9, 9, 9]) ➞ 0

Note:
[5, 5, 5] (triple identical digits) is NOT considered a boomerang because the middle digit is identical to the first and last.

A: Very simple approach (sorry, in Python):
def boomerangs(l):
    count = 0
    for i in range(len(l) - 2):
        if l[i] == l[i+2] and l[i] != l[i+1]:
            count += 1
    return count

print(boomerangs([3, 7, 3, 2, 1, 5, 1, 2, 2, -2, 2]))
print(boomerangs([1, 7, 1, 7, 1, 7, 1]))

A: Some verbose way to do this:
class Array
  def same_values?
    self.uniq.length == 1
  end
end

def find_boomerangs(arr)
  split_amount = 3 # count of a possible boomerang
  scan_amount = split_amount - 1 # scanning by index for array
  new_arr = []
  arr.each_with_index { |_, indx| # we only care for the indx
    end_of_indx = indx + scan_amount
    arry = arr[indx .. end_of_indx] # collect new possible boomerang from array
    next unless arry.count == split_amount # only check if possible boomerang is length of three

    new_arr << arry if arry.values_at(0, -1).same_values? && !arry.values_at(0, 1).same_values? # checks that the values at the start and end are the same and that the middle value is not the same as the first
  }
  new_arr # holds the boomerangs | call .count if you want the count
end

A: def count_boomerangs(arr)
  arr.each_cons(3).count { |a,b,c| a == c && a !=b }
end

count_boomerangs [3, 7, 3, 2, 1, 5, 1, 2, 2, -2, 2] #=> 3
count_boomerangs [1, 7, 1, 7, 1, 7, 1]              #=> 5
count_boomerangs [9, 5, 9, 5, 1, 1, 1]              #=> 2
count_boomerangs [5, 6, 6, 7, 6, 3, 9]              #=> 1
count_boomerangs [4, 4, 4, 9, 9, 9, 9]              #=> 0

See Enumerable#each_cons.

A: get_bommerangs = lambda arr: sum(
    arr[i - 1] == arr[i + 1] and arr[i - 1] != arr[i] for i in range(1, len(arr) - 1)
)

bommerangs = get_bommerangs([2, 1, 2, 3, 3, 4, 2, 4])


text:
Q: Twitter API friendships/create not working I'm having a problem with the Twitter API. I'm trying to follow a specific user but the API always return the following error:
{"errors":[{"code":108,"message":"Cannot find specified user."}]}

I've tried passing user_id, screen_name and both, but I always get the same result, although I'm pretty sure I'm actually passing the right values.
This is the code I'm using:
    $options = array(
        CURLOPT_HTTPHEADER => $header,
        CURLOPT_HEADER => false,
        CURLOPT_URL => $this->url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 10,
        CURLOPT_SSL_VERIFYHOST => false,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_POSTFIELDS => $postfields,
        CURLOPT_POST => true
    );
    $feed = curl_init();
    curl_setopt_array($feed, $options);
    $json = curl_exec($feed);
    curl_close($feed);

where $postfields is an associative array containing either user_id with the id of the user to follow of screen_naam with the screen name. I get both values from the Twitter API, so they should be correct. I've tried other users as well, bt the result is the same.
Both the APP consumer id/key as the oauth token/secret as read/write and working (if I change them, I get an authentication error).
Any ideas?

A: Worked this one out quite a while ago, just forgot about this question here. Turned out to be some small problem with the curl request, not with the Twitter API. From the heart, I believe it was the presence of CURLOPT_POST in the options array. Removing that did still do a POST (probably because CURLOPT_POSTFIELDS was still present), but did make the call work as expected.

A: To whom you want to follow the user has blocked or is not allowing to follow him. In that case it gives the error "Cannot find specified user" in Twitter (api).


text:
Q: How can I use AppleScriptObjC to close my Xcode application? I have an AppleScriptObjC Xcode application.  Within this application, I've built an updater that checks for updates on startup and will prompt the user to download them.  Everything works wonderfully - except for one thing.  I need the app to restart when it is updated, so the changes can take effect.  I've searched high and low on the internet for this, but I can't figure it out.  I cannot to "tell application \"MyApp\" to quit", because Xcode doesn't allow that.  Any ideas?

A: This is an Objective-C-Method to re-launch. May be you can use the idea.
+(void)restart:(id)sender
{
    NSString *restartScript = @"while ps -p $1 > /dev/null; do sleep 0.1; done; open \"$2\"";
    NSArray *arguments = [NSArray arrayWithObjects:
                          @"-c", restartScript,
                          @"",
                          [NSString stringWithFormat:@"%d",[[NSProcessInfo processInfo] processIdentifier]],
                          [[NSBundle mainBundle] bundlePath],
                          nil];
    [NSTask launchedTaskWithLaunchPath:@"/bin/sh" arguments:arguments];
    [NSApp terminate:self];
}

A: If you just want to quit the app, using the command quit seems to work fine. If you want it to relaunch (without using Objective-C) you could try starting a separate script just before quitting that does something like this:
delay 2
tell application "Name of Application" to activate

I hope this idea helps.


text:
Q: $Cov(X, e) =0$ implies $Cov(X^{2}, e) = 0$? In regression analysis where we assume that $E(e|X) = 0$, I wish to understand whether the implication in the title holds true. I understand that
$Cov(X, e) = Cov(X, E(e|X))$
But is it true that if $E(e|X) = 0$ then $E(e|X^{2}) = 0$?
Because if that is the case then the result is straightforward.
Please help me understand if I'm missing some important point here.

A: For your query, let $Y=g(X)$ be a deterministic function of $X$, using the law of iterated expectation, we have
$$\mathbb E[e|Y]=\mathbb E[\mathbb E[e|X,Y]|Y]=\mathbb E[\mathbb E[e|X,g(X)]|g(X)]$$
It's obvious that $\mathbb E[e|X,g(X)]=\mathbb E[e|X]=0$. So, the expected value above becomes
$$\mathbb E[e|Y] = \mathbb E[0|g(X)]=0$$
Whether $g(X)$ is $X^2$ or not is not relevant here.
About the covariance, another way to see it is
$$\operatorname{cov}(X^2,e)=\mathbb E[X^2e]=\mathbb E[\mathbb E[X^2e|X]]=\mathbb E[X^2\mathbb E[e|X]]=0$$


text:
Q: php mysql query not being sent to database Hi i have written this function to register users on my site. it was all working fine until recently the only change i have done is added extra columns into the table could this have an effect on the way i need to write this function?
function register($link){
    $username = mysqli_real_escape_string($link, $_POST['username']);
    $email = mysqli_real_escape_string($link, $_POST['email']);
    $password = mysqli_real_escape_string($link, $_POST['password']);
    $password2 = mysqli_real_escape_string($link, $_POST['password2']);
    if($password == $password2){
        $password= md5($password);
        $sql = "INSERT INTO users(UserName,email,password)VALUES('$username','$email','$password')";
        mysqli_query($link,$sql);
        $_SESSION['message'] = "You are now registered";
        $_SESSION['username'] = $username;
        header("location: index.php");
    }else{
        $_SESSION['message'] = "Passwords do not match";
    }
}

A: It will have an effect if the columns are set-up to be NON NULL.  If you aren't sure, you can check the table definition with describe in a mysql console.


text:
Q: Resizing Image Without Affecting Look of Original Canvas? I have a canvas where a user draws. After tapping a button, I do a few things in a second canvas such as trimming away the white space and re-centering the drawing (so as to not affect the original canvas).
I also create a third canvas so I can resize the output to a certain size. My problem is that I don't want the original canvas where users draw to be affected. Right now everything works and my image is resized, but so is the original canvas. How to I leave the original canvas unaffected?
Here's my function:
            //Get Canvas
            c = document.getElementById('simple_sketch');

            //Define Context
            var ctx = c.getContext('2d');

            //Create Copy of Canvas
            var copyOfContext = document.createElement('canvas').getContext('2d');

            //Get Pixels
            var pixels = ctx.getImageData(0, 0, c.width, c.height);

            //Get Length of Pixels
            var lengthOfPixels = pixels.data.length;

            //Define Placeholder Variables
            var i;
            var x;
            var y;
            var bound = {
              top: null,
              left: null,
              right: null,
              bottom: null
            };

            //Loop Through Pixels
            for (i = 0; i < lengthOfPixels; i += 4) {

                if (pixels.data[i+3] !== 0) {
                  x = (i / 4) % c.width;
                  y = ~~((i / 4) / c.width);

                  if (bound.top === null) {
                    bound.top = y;
                  }

                  if (bound.left === null) {
                    bound.left = x;
                  } else if (x < bound.left) {
                    bound.left = x;
                  }

                  if (bound.right === null) {
                    bound.right = x;
                  } else if (bound.right < x) {
                    bound.right = x;
                  }

                  if (bound.bottom === null) {
                    bound.bottom = y;
                  } else if (bound.bottom < y) {
                    bound.bottom = y;
                  }
                }
            }

            //Calculate Trimmed Dimensions
            var padding = 1;
            var trimmedHeight = bound.bottom + padding - bound.top;
            var trimmedWidth = bound.right + padding - bound.left;

            //Get Longest Dimension (We Need a Square Image That Fits the Drawing)
            var longestDimension = Math.max(trimmedHeight, trimmedWidth);

            //Define Rect
            var trimmedRect = ctx.getImageData(bound.left, bound.top, trimmedWidth, trimmedHeight);

            //Define New Canvas Parameters
            copyOfContext.canvas.width = longestDimension;
            copyOfContext.canvas.height = longestDimension;
            copyOfContext.putImageData(trimmedRect, (longestDimension - trimmedWidth)/2, (longestDimension - trimmedHeight)/2);
            copyOfContext.globalCompositeOperation = "source-out";
            copyOfContext.fillStyle = "#fff";
            copyOfContext.fillRect(0, 0, longestDimension, longestDimension);

            //Define Resized Context
            var resizedContext = c.getContext('2d');
            resizedContext.canvas.width = 32;
            resizedContext.canvas.height = 32;
            resizedContext.drawImage(copyOfContext.canvas, 0, 0, 32, 32);

            //Get Cropped Image URL
            var croppedImageURL = resizedContext.canvas.toDataURL("image/jpeg");

            //Open Image in New Window
            window.open(croppedImageURL, '_blank');

A: How to make a "spare" copy of an html5 canvas:
var theCopy=copyCanvas(originalCanvas);

function copyCanvas(originalCanvas){
    var c=originalCanvas.cloneNode();
    c.getContext('2d').drawImage(originalCanvas,0,0);
    return(c);
}

Make a spare copy of the original canvas you don't want affected. Then after you've altered the original, but want the original contents back ...
// optionally clear the canvas before restoring the original content

originalCanvasContext.drawImage(theCopy,0,0);


text:
Q: $_REQUEST['id'] from page inside a php file called by a javascript to another php page I'm trying to get the value 3 from this link: index.php?subtopic=example&id=3
Normally I would use the $_REQUEST['id'] but I'm facing another situation here.
I got the example1.php:

...

And then the chatbox.js:
setInterval( function() {
$('#chat_box').load('chatbox.php');
} , 100 );

And finally the chatbox.php:
echo $_REQUEST['id'];

but I can't get the id value here :/  Please Help!!!

A: Basically you want to parse the id out of the URL and send it to the chat - let's do this:

...

...
setInterval( function() {
$('#chat_box').load(chaturl);
} , 100 );

A: I solved it here:
example1.php
echo "";

echo '

';

and chatbox.php:
echo $_GET['id'];


text:
Q: prove no two cycles in a graph will share an edge if all the cycles in the graph are of odd length I am trying to use induction but cant make any headway on this problem.
Was considering using the property that biparted graphs have no cycles of odd length but Im not sure if that helps

A: Suppose there are two (odd) cycles in your graph, say $C_1 = [u_1, u_2, \dots, u_n, u_1]$ and $C_2 = [v_1, v_2, \dots, v_m, v_1]$, that have k common edges. These edges lie between $k+1$ vertices in either cycle.
Now, we know that $n$ and $m$ are odd, so $n=2a-1$ and $m=2b-1$, for some $a,b \in \mathbb{N}$. Therefore the number of vertices in the big cycle (the one obtained by forgetting the common edges) is equal to $n-(k-1))+m-(k-1) = 2a-1+2b-1-2k+2=2(a+b-k)$, which is an even number, a contradiction.

A: Suppose that we have two cycles $C_1$ and $C_2$ that share an edge. Without loss of generality, these cycles intersect in a path. Why? If not, then we have two points $v, w$ in both $C_1$ and $C_2$, and two paths $v, v_1, \ldots, v_n, w$ and $v, w_1, \ldots, w_m, w$ in $C_1$ and $C_2$ respectively. Consider the least $i$ such that $v_i \neq w_i$, and the least $j \ge i$ such that $v_j$ belongs on the other path (i.e. is equal to $w_k$ for some $k \ge i$). Then
$$v_{i-1}, v_i, \ldots,v_j, w_{k-1},\ldots,w_{i-1}$$
is a cycle, where $v_{i-1} = w_{i - 1}$ is $v$ when $i = 1$, that intersects with $C_1$ (and $C_2$) in a path.
So, we have three paths $P_1, P_2, P_3$ such that $C_1 = P_1 \cup P_2$ and $C_2 = P_2 \cup P_3$. Consider the cycle $C_3$ made up of $P_1$ and $P_3$. Then,
\begin{align*}
|C_1| &= |P_1| + |P_2| \\
|C_2| &= |P_2| + |P_3| \\
|C_3| &= |P_1| + |P_3|.
\end{align*}
Each $|C_i|$ is odd, but when we sum these expressions,
$$|C_1| + |C_2| + |C_3| = 2(|P_1| + |P_2| + |P_3|),$$
which is even. This is a contradiction. Hence, the cycles cannot share an edge.


text:
Q: Can I unlock other resolutions? Its running on 1024x768 and I need 1280x720 or 1920 × 1080
Possible Duplicate:
How to change screen resolution?

I've installed ubuntu 12.04 LTS and it doesn't get my screen resolution right. what should I do?

A: Have you checked whether these resolutions are availabe in "Displays" in your system settings?

If they are not available probably some drivers are missing, if this is the case you have to provide some more information.


text:
Q: Можно ли настроить прозрачность fillRect в Java2D? Можно ли настроить прозрачность fillRect?

A: Можно:
Graphics2D g2d = ...;
AlphaComposite alphaComposite = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.5);
g2d.setComposite(alphaComposite);
g2d.fillRect(x1, y1, x2, y2);


text:
Q: Trying Graph Explorer to find out Intune managedAppRegistrtaion per user I am trying to figure out the managedAppRegistration of a user using Microsoft Grpah Explorer. But it is not going through. Can someone suggest solution?
Here's the request I am trying:

GET https://graph.microsoft.com/beta/users/user@domain.com/managedAppRegistrations
GET https://graph.microsoft.com/beta/users/user@domain.com/registeredDevice

None of this seems to work.

A: according to docs you need subscription for for using Graph API for intunes service. Could you check if you have subscription and login with correct account info to use graph api.

Note: Using the Microsoft Graph APIs to configure Intune controls and
  policies still requires that the Intune service is correctly licensed
  by the customer.


text:
Q: Numerical Integration of KdV Equation by Runge-Kutta 4 I have been asked to reduce the KdV ODE Equation
$d^3/dX^3=(c+6f)df/dX $
to a first order ODE and then solve this ODE by RK4 (Runge-Kutta 4) Numerical Integration.
Analytically, letting c=1 for simplicity, we integrate to get
$f''-3f^2-f=C$
Where $C$ is integration constant. Then Multiply by $f'$ and Integrate to get
$(f')^2/2 -f^3 -f^2/2=Cf +D$
Where $D$ is another integration constant. Now Solve for $f'$ we get
$df/dX=\sqrt(2f^3+f^2+2Cf+2D)$
I have been given initial conditions:
$f(0)=-1/2$, $df/dX=0$, and $df^2/dX^2=1/4$
I have been told to:
Use RK4 to integrate numerically the first-order reduction of the ODE from $X = 0$
forward $X_n = n * h, n = 0, 1, . . .N$ and for sufficiently large $X$ (i.e. large $N$). You will
need to be plotting $f$ vs $X$ to see if the solution is settling to determine when to stop the
integration.
Use your judgement as to how small a step size you need to solve this system accurately.
If you cannot figure this out from pure thought, experiment with different step sizes and
use $δC = |(C(t) − C(t = 0))/C(t = 0)|$ to determine the accuracy. If $δC$ is smaller than
$10^{−3}$ for all integration times, then you have acceptable accuracy.
Show in a plot your solution for $f(X)$, for $X \in [−20, 20]$.
Here is my Code:
ti = -\[Pi];
tf = \[Pi];
i = 256;
\[CapitalDelta]t = (tf - ti)/i;
X = Range[ti, tf, \[CapitalDelta]t] // N;
F = ConstantArray[0., i + 1];
D1 = ConstantArray[0., i + 1];
D2 = ConstantArray[0., i + 1];
(*Runge Kutta of Order 4*)
F[[1]] = -1/2;
D1[[1]] = 0.;
D2[[1]] = 1/4;

Do[
 k1 = \[CapitalDelta]t*\[Sqrt]Abs[(2 F[[n]]^3 + F[[n]]^2 +
       2*(D2[[n]] - 3 F[[n]]^2 - F[[n]])* F[[n]] +
       2*(1/2 D1[[n]]^2 - F[[n]]^3 - 1/2 F[[n]]^2 - D2[[n]] -
          3 F[[n]]^2 - F[[n]]* F[[n]]))];
 k2 = \[Sqrt]Abs[(2 F[[n]]^3 + F[[n]]^2 +
       2*(D2[[n]] - 3 F[[n]]^2 - F[[n]])* F[[n]] +
       2*(1/2 D1[[n]]^2 - F[[n]]^3 - 1/2 F[[n]]^2 - D2[[n]] -
          3 F[[n]]^2 - F[[n]]* F[[n]]))] + \[CapitalDelta]t*k1/2;
 k3 = \[Sqrt]Abs[(2 F[[n]]^3 + F[[n]]^2 +
       2*(D2[[n]] - 3 F[[n]]^2 - F[[n]])* F[[n]] +
       2*(1/2 D1[[n]]^2 - F[[n]]^3 - 1/2 F[[n]]^2 - D2[[n]] -
          3 F[[n]]^2 - F[[n]]* F[[n]]))] + \[CapitalDelta]t*k2/2;
 k4 = \[Sqrt]Abs[(2 F[[n]]^3 + F[[n]]^2 +
       2*(D2[[n]] - 3 F[[n]]^2 - F[[n]])* F[[n]] +
       2*(1/2 D1[[n]]^2 - F[[n]]^3 - 1/2 F[[n]]^2 - D2[[n]] -
          3 F[[n]]^2 - F[[n]]* F[[n]]))] + \[CapitalDelta]t*k3/2;
 D1[[n + 1]] = D1[[n]] + 1/6*\:f000k1 + 2 k2 + 2 k3 + k4\:f006,
 D2[[n + 1]] = D2[[n]] + 1/6*\:f000k1 + 2 k2 + 2 k3 + k4\:f006,
 F[[n + 1]] = F[[n]] + 1/6*\:f000k1 + 2 k2 + 2 k3 + k4\:f006,
 {n, 1, i}]

So I tried to use 3 vectors with 3 initial values given, and iterate until all the values are filled. but I don't know how to compute the next values of D1 and D2, based on the initial values.
On the other hand, apparently there must be a function with two variable inputs, where it returns a only one F back. I found this online:
Y, T, h = initialize_all(y0, t0, t1, n)
for i in xrange(1, n):
K1 = f(T[i-1], Y[i-1])
tplus = (T[i] + T[i-1]) * .5
K2 = f(tplus, Y[i-1] + .5 * h * K1)
K3 = f(tplus, Y[i-1] + .5 * h * K2)
K4 = f(T[i], Y[i-1] + h * K3)
Y[i] = Y[i-1] + (h / 6.) * (K1 + 2 * K2 + 2 * K3 + K4)
return T, Y

Which is in another language. but clearly my code should follow this pattern. I have tried hard to solve it, but couldn't figure it out. If anyone can help me, I really appreciate their help.
Thanks

A: We should note first that point $X=0$ is a branching point for the first order equation. Therefore we need to make special step before RK4. Using initial condition we calculate, that $C=D=0$, therefore first order equation looks like $$y'=\pm \sqrt {2 y^3+y^2}$$
Code for RK4 we can organize with Module as follows
rk4[f_, h_, x0_, y0_, n_] :=
 Module[{k1, k2, k3, k4}, T[0] = x0; Y[0] = y0;
  Do[k1 = f[T[i - 1], Y[i - 1]]; T[i] = T[i - 1] + h;
   tplus = (T[i] + T[i - 1])*.5;
   k2 = f[tplus, Y[i - 1] + .5*h*k1];
   k3 = f[tplus, Y[i - 1] + .5*h*k2];
   k4 = f[T[i], Y[i - 1] + h*k3];
   Y[i] = Y[i - 1] + (h/6.)*(k1 + 2*k2 + 2*k3 + k4);, {i, 1, n}];
  ysol = Table[{T[i], Y[i]}, {i, 0, n}];
  ysol]

Now we use it in two branches with first step calculation
fp[x_, y_] := Sqrt[2 y^3 + y^2]; h1 = 10^-6; y1 = -1/2 + h1^2/2 *1/4;

yp = rk4[fp, .1, h1, y1, 200];

fm[x_, y_] := -Sqrt[2 y^3 + y^2]; ym = rk4[fm, -.1, -h1, y1, 200];

Finally we plot solution
ListPlot[{ym, yp}, PlotRange -> All, Frame -> True]

To plot function $y(x-t)$ we can use code
ys = Interpolation[Join[ym, yp]];

Plot[Evaluate[Table[ys[x - t], {t, 0, 5, 1}]], {x, -10, 10},
 PlotLegends -> Table[t, {t, 0, 5, 1}], Frame -> True]

To compute parameter $C=y''-3 y^2-y$ for numerical solution we should remember that we solve first order ODE, and therefore we need some interpolation of numerical solution to calculate a second derivative. For this problem we use code
uu[h_, h1_, n_] :=
 Module[{hh = h, nn = n}, fp[x_, y_] := Sqrt[2 y^3 + y^2];
  y1 = -1/2 + h1^2/2 *1/4;
  yp = rk4[fp, hh, h1, y1, nn]; fm[x_, y_] := -Sqrt[2 y^3 + y^2];
  ym = rk4[fm, -hh, -h1, y1, nn]; un = Join[ym, {{0, -1/2}}, yp]; un]

Let evaluate uu with input data h=h1=.1;n=200 then we have numerical solution as interpolation function
y = Interpolation[uu[.1, .1, 200], InterpolationOrder -> 4]

With this function we can compute C and plot it in a big and small scale  as follows (here ch=C but we can't use letter C as a name since it is the default form for the parameter or constant generated in representing the results of various symbolic computations)
ch = y''[x] - 3 y[x]^2 - y[x];

{LogPlot[Abs[ch], {x, -20, 20}, PlotRange -> All, Frame -> True],
 LogPlot[Abs[ch], {x, -2, 2}, PlotRange -> All, Frame -> True]}


text:
Q: Using class object in different cpp file I was starting to learn to use class object in different .cpp file..
What I did:

*

*Created a class of node in one file and saved it with node.h

*Created another file with name node_pair.cpp and included node.h

*Created a function named pair() and called it from main()
Now, I want to ask two things:

*

*I am getting error: reference to 'pair' is ambiguous
Here is the code for node.h file
#include "iostream"
#include"stdlib"
using namespace std;

class node
{
    int data;
public:
    node *next;
    int insert(node*);
    node* create();
    int display(node *);
} *start = NULL, *front, *ptr, n;

int node::insert(node* np)
{
    if (start == NULL)
    {
        start = np;
        front = np;
    }
    else
    {
        front->next = np;
        front = np;
    }
    return 0;
}

node* node::create()
{
    node *np;
    np = (node*)malloc(sizeof(node)) ;
    cin >> np->data;
    np->next = NULL;
    return np;
}

int node::display(node* np)
{
    while (np != NULL)
    {
        cout << np->data;
        np = np->next;
    }
    return 0;
}

int main_node()
{
    int ch;
    cout << "enter the size of the link list:";
    cin >> ch;
    while (ch--)
    {
        ptr = n.create();
        n.insert(ptr);
    }
    n.display(start);
    cout << "\n";
    return 0;
}

and here is the code for node_pair.cpp
#include"iostream"
#include"node.h"
using namespace std;

node obj;

int pair()
{
    node* one, *two, *save;
    one = start;
    two = start->next;
    while (two != NULL)
    {
        save = two->next;
        two->next = one;
        one->next = save;
    }
}

int main()
{
    main_node();
    pair();
    obj.display(start);
    return 0;
}

What should I do to resolve this error
And now the second problem
    2. I want to keep node* next pointer to be private in node class but if I do so then I will not get access for it in pair() function.
Please answer, thanks in advance.

A: Some tips:

*

*Your function pair clashes with std::pair.

*Don't use using namespace std;. It's a bad practice and creates errors like this.

*Mixing node.js and C++ is an advanced topic. If you just begun to learn OOP, I recommend that you stick to pure C++.

A: You have a name collision with your pair() and std::pair.
Best practice is to avoid using the entire namespace std -- just use what you need. For example, if you only need std::cin you can use using std::cin; to add it to the global namespace but not std::pair. You can also replace all instances of cin with std::cin instead.
If you really want to use the entire namespace std you can also create your own namespace to put your code in -- in particular, you'd need to put your pair() in this new namespace. You do it like this:
namespace mynamespace {
  int pair() {
    // ...
  }

// ... other code in mynamespace
} // end mynamespace


text:
Q: Calling a blocking method from Constructor - Java I would like to know if it is a bad idea to call a blocking method from within constructor itself.
I am curious to know if we have any guidelines/rules in such a scenario, that we should never call blocking methods in Constructor.
Basically I am trying to do this:
class A
{
    // Many instance variables that is to be initialized on instantiaion
    String tempVar = null;

    public A()
    {
        // Initialize all the instance variables
        tempVar=objectClassB.**callBlockingMethod**(); // this method call would return
                                                       // some data from ClassB Object
    }

    public static void main(String args ...)
    {
        A a = new A();
        // Or should I call the blocking method call only after instantiation according
        // to any guidelines of Java pertaining to performance ?

        // IMPORTANT: It's only when the blocked method returns value , should the main
        // thread proceed as the object 'a' would be sent for further processing
    }
}

PS: Eh ,I'm sorry if my question sounds very basic.

A: I thought its better you can create one method like connect () inside the class A. After creating object you can call like
A a = new A()
A.connect()
Inside connect method you define the blocking method
 StreamConnection con=notifier.acceptAndOpen()
.....
if your blocking call doesn't return in specified time period, you consider some mechanism to recover this scenario


text:
Q: Missing SQLite.Net.Plaform.XamarinIOS assembly I'm working on POC project for android and iOS.
Setup:

*

*Xamarin.Forms (current version 2.0.1)

*MvvmCross (current version 4.0.0-beta8)

I'm trying to add support for sqlite via:

*

*MvvmCross.Plugin.SQLitePCL (v 4.0.0-beta8)

*SQLite.Net.Async-PCL (v 3.1.1)

*SQLite.net-PCL (v 3.1.1)

Android application works perfectly fine under this configuration, however on the first use of
SQLiteAsyncConnection

I get following exception:

Could not load file or assembly 'SQLite.Net.Platform.XamarinIOS, Version=3.1.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies.

Anybody knows how to fix it or how to find a workaround?

A: This is because the iOS version is based on monotouch instead of Xamarin.iOS. There  is an issue for that: https://github.com/MvvmCross/MvvmCross/issues/1181#issuecomment-173034613
This also has been fixed recently: https://github.com/MvvmCross/MvvmCross-Plugins/pull/51
Next release it will work like expected.


text:
Q: How to filter dictionary keys by regex in swift Let's say I have the following Swift dictionary:
var studioAlbums = ["Led Zeppelin":1969, "Led Zeppelin II": 1969, "Led  Zeppelin III": 1970, "Led Zeppelin IV": 1971, "Houses of the Holy":1973, "Physical Graffiti": 1975, "Presence":1976, "In Through the Out Door":1979, "Coda":1982]

And I want a new dictionary which only contains "Led Zeppelin..."
(i.e. Led Zeppelin,  Led Zeppelin II, ..., Led Zeppelin IV).
I've created extension methods for Dictionary and Array as per
https://stackoverflow.com/a/41435190/7384373
then I could use string 'range of' method to find 'Led Zeppelin' as the following:
let filtered = studioAlbums.filteredDictionary( { $0.0.range(of: "Led Zeppelin") != nil } )

// print(filtered) output: "["Led Zeppelin IV": 1971, "Led Zeppelin III": 1970, "Led Zeppelin": 1969, "Led Zeppelin II": 1969]\n"

My question is for more complicated filtering I would prefer to use Regular Expression(regex), but I can't figure out any simple solution with Regex in let's say max 5 lines of code. (excluding any extension methods).

A: I think this is the extension you are looking for:
extension Dictionary where Key: ExpressibleByStringLiteral, Value: Any {
    func filterDictionaryUsingRegex(withRegex regex: String) -> Dictionary<Key, Value> {
        return self.filter({($0.key as! String).range(of: regex, options: .regularExpression) != nil}).toDictionary(byTransforming: {$0})
    }
}

The extension is restrained to Dictionaries of type <String, Any> to avoid any Key to String conversion errors.
Result:
let studioAlbums = ["Led Zeppelin":1969, "Led Zeppelin II": 1969, "Led  Zeppelin III": 1970, "Led Zeppelin IV": 1971, "Houses of the Holy":1973, "Physical Graffiti": 1975, "Presence":1976, "In Through the Out Door":1979, "Coda":1982]
let filtered = studioAlbums.filterDictionaryUsingRegex(withRegex: "Led")
// ["Led Zeppelin IV": 1971, "Led Zeppelin III": 1970, "Led Zeppelin ": 1969, "Led Zeppelin II": 1969]

Edit: This does require the Extension of user7367341: Filtering Dictionary Stack Overflow Question
extension Array
{
  func toDictionary<H:Hashable, T>(byTransforming transformer: (Element) -> (H, T)) -> Dictionary<H, T>
  {
    var result = Dictionary<H,T>()
    self.forEach({ element in
      let (key,value) = transformer(element)
      result[key] = value
    })
    return result
  }
}


text:
Q: Does OpenGL/DirectX converts other texture formats to RGBA format internally? As title said, I have a dynamic texture (which is updated in every frame) from a RGB565 color buffer, I don't know which way will have better performance:

*

*Creating a texture with RGB565 format and upload RGB565 color buffer to GPU in every frame.

*Creating a texture with RGBA8888 format and convert RGB565 color buffer to RGBA8888 before upload to GPU.

I think if OpenGL/DirectX converts other formats to RGBA8888 internally, then the creating RGBA8888 texture and convert data myself before upload to GPU way may be faster.

A: Don't know which one is more performant?
Benchmark it.
That being said, 5-6-5 mode is this weird for a reason - it's exactly 16 bits. GPUs typically support all of those in hardware, so if a format is present, you can assume the hardware instructions for handling it are there.

A: It also may depends on the global workload you put on your gpu, and on the gpu characteristics : Putting 565 texture onto video memory and reading back from this texture in a shader will consume half the memory bandwidth of the 888 counterpart, but it might (and not for sure) consume a bit more processing power.
So benchmark it, if possible on multiple configurations :)

A: I doubt that converting the RGB565 data to RGBA8888 yourself would ever be faster.
First of all, RGB565 is a format that's pretty widely used, and there is a high likelihood that your hardware supports it directly. If the precision is high enough for your use case, it will use half the memory of RGBA8888, and most likely be at least as efficient, due to the reduced memory bandwidth and correspondingly higher cache hit rates.
Even if the hardware does not support it, I still don't think converting it to RGBA8888 yourself will be more efficient. Any driver worth its money will have highly optimized code for format conversion. And even more importantly, it might be able to apply the format conversion during a data copy it will have to make anyway, which avoids one copy of the data compared to your code doing the conversion.


text:
Q: Rotate Custom Object in Animation Loop I created some Functions, these will draw Rectangles, Circles, Hexagons etc.
One of them looks like this:
rotation = 45;
function hex(hex_sides, hex_size, hex_color){
  x = ctx.canvas.width/2;
  y = ctx.canvas.height/2;

  ctx.save();
  ctx.rotate(rotation*Math.PI/180);
  ctx.translate(ctx.canvas.width/2, ctx.canvas.height/2);
  ctx.moveTo(x + hex_size * Math.cos(0), y + hex_size * Math.sin(0));
  ctx.restore();

  for (i = 0; i < hex_sides+1; i++) {
    ctx.lineTo(x + hex_size * Math.cos(i * 2 * Math.PI / hex_sides), y + hex_size * Math.sin(i * 2 * Math.PI / hex_sides));
  }

  ctx.strokeStyle = hex_color;
  ctx.stroke();
}

Now i call the Functions to Draw the Shapes inside my animation loop.
function loop() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  circle(200);
  circle(220);
  hex(6, 180, "#fff");
  rotation += 0.4;
  requestAnimationFrame(loop);
}

I'm incrementing the var rotation inside the loop but it does not rotate the whole shape but just one line of it instead. Other Shapes i cant get to rotate at all.
I think i got a wrong approach, maybe because of my confusion about .save() and .restore() or .beginPath() and .closePath().
In General the behaviour is very strange when i start to use .translate() and .rotate()

The entire Code is here.

UPDATE
It is definitely something about this line:
ctx.translate(ctx.canvas.width/2, ctx.canvas.height/2);

Somehow it does not translate correctly. The rotation now happens around the right middle side of the normal shape position but i want the rotation around its own axis.
I changed the hex() function to:
ctx.save();
ctx.translate(ctx.canvas.width/2, ctx.canvas.height/2);
ctx.rotate(rotation*Math.PI/180);
ctx.moveTo(x + hex_size * Math.cos(0), y + hex_size * Math.sin(0));
for (i = 0; i < hex_sides+1; i++) {
  ctx.lineTo(x + hex_size * Math.cos(i * 2 * Math.PI / hex_sides), y + hex_size * Math.sin(i * 2 * Math.PI / hex_sides));
}
ctx.strokeStyle = hex_color;
ctx.stroke();
ctx.restore();

Again, entire Code is here.

A: Nevermind... figured it out, i have forgotten to substract half of the shapes width from the translation point and also the order seems to be more important then i tought.
Working Code
function hex(hex_sides, hex_size, hex_color){
    x = ctx.canvas.width/2;
    y = ctx.canvas.height/2;

    ctx.save();
    ctx.translate(x,y);
    ctx.rotate(rotation*Math.PI/180);
    //ctx.moveTo(x + hex_size * Math.cos(0), y + hex_size * Math.sin(0));
    ctx.moveTo(0,0);
    for (i = 0; i < hex_sides+1; i++) {
        ctx.lineTo(x/hex_size + hex_size * Math.cos(i * 2 * Math.PI / hex_sides), y/hex_size + hex_size * Math.sin(i * 2 * Math.PI / hex_sides));
    }
    ctx.strokeStyle = hex_color;
    ctx.stroke();
    ctx.restore();
}


text:
Q: update variable string value in bash script I need to update the value of a variable in a bash script and write the changes to the file. My attempts have either replace the key without strings or deleted the value.
Here's what ive tried :
   sed -ri 's|^(VARIABLE_KEY\s*=\s*).*|\new_java-microservice.jar|' path_to_file/bashscript.sh

   sed -i  "s#\(.*VARIABLE_KEY =\)\( .*\)#\1 "new_java-microservice.jar"#" path_to_file/bashscript.sh

   sed -i 's/VARIABLE_KEY =.*/VARIABLE_KEY ="new_java-microservice.jar"/' path_to_file/bashscript.sh

script
#!/bin/bash

COMMAND="$1"
HOME="/root/service/"
BASE="${HOME}/javaservice"
VARIABLE_KEY="existing-java.jar"

case "${COMMAND}" in
    "start")
        nohup java -jar ${BASE}/${VARIABLE_KEY} start > /dev/null 2>&1 &
    ;;

    "stop")
        #....
    ;;

    *)
        echo "Usage: $0 {start|stop}"
    ;;
esac

A: sed -i 's/^VARIABLE_KEY=.*/VARIABLE_KEY="new_java-microservice.jar"/' path_to_file/bashscript.sh


text:
Q: I can't wait for the task to be completed I'm using ManagementEventWatcher to monitor a process. If the process is opened or modified I run a task. I'd like to await for the task to be completed in the main thread (note that the task is initialized in the event thread, and it starts there. But I'd like to stop the code execution in the form_load till the task finishes) I tried several ways for this but none of them works. This is one.
static string summonerId = null;
static Task summonerIdTask;

private async void Form1_Load(object sender, EventArgs e)
{
    string tick = "0.1";
    string processName = "LeagueClient.exe";

    string query = String.Format(@"
        SELECT *
        FROM __InstanceOperationEvent
        WITHIN {0}
        WHERE TargetInstance ISA 'Win32_Process'
        AND TargetInstance.Name = '{1}'", tick, processName
    );

    string scope = @"\\.\root\CIMV2";

    ManagementEventWatcher watcher = new ManagementEventWatcher(scope, query);
    watcher.EventArrived += new EventArrivedEventHandler(OnEventArrived);
    watcher.Start();

    summonerIdTask.Wait();
}

// Detect when the process is running/closed/modificated.
private static void OnEventArrived(object sender, EventArrivedEventArgs e)
{

    summonerIdTask = new Task(() => getSummonerId());
    // If process is closed.
    if (e.NewEvent.ClassPath.ClassName.Contains("InstanceDeletionEvent"))
        summonerId = null;

    // If summonerName is null
    if (summonerId == null && !summonerIdTask.Status.Equals(TaskStatus.Running))
        // If process is open or is modificated.
        if (e.NewEvent.ClassPath.ClassName.Contains("InstanceCreationEvent"))
            summonerIdTask.Start();
        else
            summonerIdTask.Start();
}

static LCUConnector connect;
static LCUEndpoints api;

static async void getSummonerId()
{
    connect = new LCUConnector();
    api = new LCUEndpoints(connect);

    summonerId = JObject.Parse(await api.getSession())["summonerId"].ToString();
    Console.WriteLine("1");
}

What'd be the correct way to wait for the task to be completed and send it to the form_load thread?


text:
Q: Google Cloud cancel replacing instances in group How is it possible to cancel replacing instances in instance group without website going offline? We have a managed instance group of compute engine instances, we start replace operation with maximum unavailable instances set to 0, if new instance for some reason doesn't become healthy there is an option to remove instance. However it removes all instances making website to go down until a new instance is created. Is it supposed to happen?

A: This seems to be expected behavior. Please have a look at rolling update in order to update your instance.  Striving for 0 downtime could be achievable. To make your servers more responsive and less disruptive, you may consider the following two strategies:
Max surge. This will create instances above the target size in order to speed up the update process.
Opportunistic update.  "An opportunistic update is only applied when new instances are created by the managed instance group"


text:
Q: menu flyout mouse left click I'm a little bit lost, I have a ContextFlyout in a TextBlock, and it works with right mouse click, but I want it to work with left mouse click.
How can I do it? Is this the wrong way to display the menu?
<TextBlock x:Name="Livro1Texto" Text="Livro 1" >
 <TextBlock.ContextFlyout>
  <MenuFlyout>
     <MenuFlyoutSubItem Text="Título I Da Lei Criminal">
       <MenuFlyoutSubItem Text="Princípios Gerais">
         <MenuFlyoutItem Text="Artigo 1º Princípio da legalidade" x:Name="Art1Fly" Click="Art1Fly_Click"/>
         <MenuFlyoutItem Text="Artigo 2º Aplicação no tempo"  x:Name="Art2Fly" Click="Art2Fly_Click"/>
         <MenuFlyoutItem Text="Artigo 3º Momento da prática do fato" />
         <MenuFlyoutItem Text="Artigo 4º Aplicação no espaço: princípio geral"/>
         <MenuFlyoutItem Text="Artigo 5º Fatos praticados fora do território português"/>
         <MenuFlyoutItem Text="Artigo 6º Restrições à aplicação da lei portuguesa"/>
         <MenuFlyoutItem Text="Artigo 7º Lugar da pratica do fato" />
         <MenuFlyoutItem Text="Artigo 8º Aplicação subsidiária do Código Penal"/>
         <MenuFlyoutItem Text="Artigo 9º Disposições especiais para jovens"/>
         </MenuFlyoutSubItem>
         </MenuFlyoutSubItem>

      <MenuFlyoutItem Text="Título II Do Facto"/>
    </MenuFlyout>
 </TextBlock.ContextFlyout>
</TextBlock>

A:
but I want it to work with left mouse click. How can I do it?

For your requirement, you could use FlyoutBase.AttachedFlyout to realize this feature.
To associate a MenuFlyout with TextBlock, use the FlyoutBase.AttachedFlyout attached property. When a MenuFlyout is assigned to other UI elements using FlyoutBase.AttachedFlyout, you must call either the ShowAt method or the static ShowAttachedFlyout method to display the flyout.
<TextBlock x:Name="Livro1Texto" Text="Livro 1" VerticalAlignment="Center" HorizontalAlignment="Center" Tapped="Livro1Texto_Tapped">
    <FlyoutBase.AttachedFlyout>
           <MenuFlyout>
            <MenuFlyoutSubItem Text="Título I Da Lei Criminal">
                <MenuFlyoutSubItem Text="Princípios Gerais">
                    <MenuFlyoutItem Text="Artigo 1º Princípio da legalidade" x:Name="Art1Fly" Click="Art1Fly_Click" />
                    <MenuFlyoutItem Text="Artigo 2º Aplicação no tempo"  x:Name="Art2Fly" Click="Art2Fly_Click" />
                    <MenuFlyoutItem Text="Artigo 3º Momento da prática do fato" />
                    <MenuFlyoutItem Text="Artigo 4º Aplicação no espaço: princípio geral" />
                    <MenuFlyoutItem Text="Artigo 5º Fatos praticados fora do território português" />
                    <MenuFlyoutItem Text="Artigo 6º Restrições à aplicação da lei portuguesa" />
                    <MenuFlyoutItem Text="Artigo 7º Lugar da pratica do fato" />
                    <MenuFlyoutItem Text="Artigo 8º Aplicação subsidiária do Código Penal" />
                    <MenuFlyoutItem Text="Artigo 9º Disposições especiais para jovens" />
                </MenuFlyoutSubItem>
            </MenuFlyoutSubItem>
            <MenuFlyoutItem Text="Título II Do Facto" />
        </MenuFlyout>
    </FlyoutBase.AttachedFlyout>
</TextBlock>

Invoke ShowAttachedFlyout in TextBlock Tapped event handler.
private void Livro1Texto_Tapped(object sender, TappedRoutedEventArgs e)
 {
     FrameworkElement element = sender as FrameworkElement;
     if (element != null)
     {
         FlyoutBase.ShowAttachedFlyout(element);
     }
 }


text:
Q: filter data between 2 dates in crystal report vb.net I need some help for creating Crystal Reports in VB 2005.
I want to filter data between two dates (like from date and to date) with datetimepicker.
I'm using SQL Server 2000 for the connection.
Update:
Thanks for the link, but I'm trying using record selection formula....
Here's my code:
Try
        Dim cryRpt As New ReportDocument
        With cryRpt
            .FileName = ("C:\Documents and Settings\Ratna Ayu\My Documents\Visual Studio 2005\Projects\Denda\Denda\CrystalReport1.rpt")
            .RecordSelectionFormula = "{pinjam.tglkembali}>='" & DateTimePicker1.Value.ToString("dd/MM/yyyy") & "' and {pinjam.tglkembali} =<'" & DateTimePicker2.Value.ToString("dd/MM/yyyy") & "'"

        End With
        CrystalReportViewer1.ReportSource = cryRpt
        CrystalReportViewer1.Refresh()
    Catch ex As Exception
        MsgBox("tdk ada data", , "")
    End Try

A: Have a look at this link
How to Load and Display Crystal Reports in VB.NET

The following code shows how to load
  Crystal Reports in VB.NET, solving all
  the issues of logon, including sub
  reports and parameter passing. You can
  view your reports by simply calling
  the required functions with its
  parameters.

A: Public Sub ConfigureCrystalReportsPhotoAlbum2012ByDateNew()
        On Error Resume Next
        sReport = New ReportDocument()
        Dim reportPath As String = Application.StartupPath & "\" & "PhotoAlbum2012.rpt"
        sReport.Load(reportPath)
        Dim selectionFormula As String = "{MemberDetails.Birthdate} >= #" _
            & CDate(frmCustomReport.txtFrom.Text) _
            & "# and {MemberDetails.Birthdate}" _
            & "<=" _
            & "#" _
            & CDate(frmCustomReport.txtTo.Text) _
            & "#"
        Dim myConnectionInfo As ConnectionInfo = New ConnectionInfo()
        'myConnectionInfo.ServerName = "192.168.0.2\SQLExpress" 'Network
        myConnectionInfo.ServerName = ".\SQLExpress"   'Local
        myConnectionInfo.DatabaseName = "Photo Album 2012"

        myConnectionInfo.UserID = "limitedPermissionAccount"
        myConnectionInfo.Password = ""

        myConnectionInfo.IntegratedSecurity = True
        SetDBLogonForReport(myConnectionInfo, sReport)
        frmMain.CrystalReportViewerMain.SelectionFormula = selectionFormula

        frmMain.CrystalReportViewerMain.ReportSource = sReport
        frmMain.CrystalReportViewerMain.Zoom(100)
        frmMain.CrystalReportViewerMain.BackColor = Color.AliceBlue
    End Sub

A: That's going to far just use this code its very easy.
I built a sample contact application and a report for it and used the code below to filter contacts according to start and end date. DateTimePicker1 is start and DateTimePicker2 is end.
Private Sub filter_dates()
    Dim objcr As New CrystalReport1
    Dim da As New MySqlDataAdapter("select * from Contacts where CDate>='" & CDate(DateTimePicker1.Text) & "' and CDate<='" & CDate(DateTimePicker2.Text) & "' ", conn)
    Dim dt As New DataTable
    da.Fill(dt)
    objcr.SetDataSource(dt)
    CrystalReportViewer1.ReportSource = objcr
    CrystalReportViewer1.RefreshReport()
End Sub


text:
Q: Adding an attribute to html  tag using Javascript or Jquery. - WordPress Case I have a WordPress installation and I share some links like the following to students watching courses - presentations online.
https://emgncv.net/wp-content/uploads/2020/10/108_I_Interpretation_Case_Study.mp4
The big issue that I am facing here is that I want to find a piece of code (probably Javascript or Jquery) to add "On document ready" so when students load the presentations on their browsers not being able to download the video from the 3-dots menu on the right bottom corner of the media player. Please, view the screenshot attached.

For the records, I have noticed this only on Google Chrome and Microsoft Edge. Mozilla does not offer such a download option.
What I have already tried is the following:
$('video').attr('controlsList', 'nodownload');
FYI, I have placed this code in a section where my WordPress theme provider lets me add some custom JS code. The section works pretty fine. I have already implemented others functions and everything works properly.
Do you have any ideas on what I will need to look at to achieve the following by default when my students load their courses on browsers?

Thank you so much in advance,
George.


text:
Q: How to make the CommandBar point down in UWP The CommandBar expands upward when the button is pressed. How to make the CommandBar expand in the opposite direction?

Code:
     <CommandBar>
        <AppBarToggleButton Icon="Shuffle" Label="Shuffle" />
        <AppBarToggleButton Icon="RepeatAll" Label="Repeat"/>
        <AppBarSeparator/>
        <AppBarButton Icon="Back" Label="Back" />
        <AppBarButton Icon="Stop" Label="Stop" />
        <AppBarButton Icon="Play" Label="Play" />
        <AppBarButton Icon="Forward" Label="Forward"/>

        <CommandBar.Content>
            <TextBlock Text="Now playing..." Margin="12,14"/>
        </CommandBar.Content>
    </CommandBar>

A: You should edit the ControlTemplate as suggested here.
There is a full code example available on GitHub:
<CommandBar Style="{StaticResource OpenDownCommandBar}">
    <CommandBar.Content>
        ...
    </CommandBar.Content>
</CommandBar>


text:
Q: Keep old URLs when implementing UrlRewriter.net I added UrlRewriter.net to my site today and it works fine with redirecting my SEO links to actual pages. The question is if there is any way to keep my old links in site and have ResolveUrl() using the rules to output links in my page. The "old" links should never be viewed by either search bots or users.
Example link in page:
<a href="<%= ResolveUrl("~/Help.aspx") %>">Help

I added rewrite code like this in web.config:
<rewrite url="~/help" to="~/help.aspx" />
<rewrite url="~/help/(.+)" to="~/help.aspx?section=$1" />

First it would be great to have the links rendered without any extra job like MVC has. The second best is if there is a nice way to just add rules for "the other way" as well in the rewrite list.
This would also enable me to easally turn off/on redirecting when debugging.

A: Ok. I implemented the Routing tecnique used in MVC routing in my web.forms instead which allowed me to use below code:
ASPX:
<%= Url.RouteUrl("article", new { name="my-name-for-artcile"}) %>

And register all routes in one place like:
routes.MapWebFormRoute("articles", "artiklar", "~/articles.aspx");

I used the code Phil Haack made about Webform routing but modified it in a small way to get it working with master pages and also added som web.config settigns to get it working smoothly on server with non-aspx urls.
http://blog.joakimfischer.se/post/2009/11/08/Web-Form-Routing.aspx
Now it works as intended but I stoped using UrlRewriter.net to get the functionality I wanted.