text:
Q: Java reflection: casting Integer coming from a class's field I have recently run into the following error which really confuses me. I have imported reflect. I have a class (called worker) with a field which is a private int called numOfJobs. In the constructor of Worker, numOfJobs is set to 0. Then, in a tester class, I create an instance of type worker:
    waterBenders[0] = new Worker();
    Field []fields = waterBenders[0].getClass().getDeclaredFields();
    Field privateFieldJobs = fields[0];
    privateFieldJobs.setAccessible(true);

    try{

          System.out.println(privateFieldJobs.get(waterBenders[0]));

          System.out.println(privateFieldJobs.get(waterBenders[0]).getClass());

          System.out.println((int)privateFieldJobs.get(waterBenders[0]));
    }

It is the third line in the try box which is contains the error.
The first two lines print:
    0
    class java.lang.Integer

This makes sense to me. However, if the object privateFieldJobs.get(waterBenders[0]) is an object of type Integer with "value" 0, then why should (int)privateFieldJobs.get(waterBenders[0]) throw the error:
    Cannot cast from java.lang.Object to int

If I was to create a normal object of type Integer, then this type of casting usually works. What is so special about this example? I imagine it has something to do with the fact that this Integer object is coming from the fields array.
My worker class is essentially:
    public class Worker extends Unit{
      private int numOfJobs;

      public Worker(Tile position, double hp, String faction) {
        super(position, hp, 2, faction);
        this.numOfJobs = 0;
      }

      public int getNumOfJobs(){
        return this.numOfJobs;
      }
    }

Any help would be appreciated.

A: It is because Field#get returns an Object, and you can not cast any Object type to a primitive type in java. If you want the primitive integer value from an Integer object, you can do something like this
Integer field = (Integer) privateFieldJobs.get(waterBenders[0]);
int value = field.intValue();

A: Basically you are attempting this:
Integer i=1;
Object o=i;
int val=(int)o;

It has no reason to work, that is why it does not.
Either cast it back to Integer (as you see, it is not necessary for a println, as the correct toString() gets invoked anyway, but it is required for unboxing), or you can try using getInt():
int val1=(Integer)privateFieldJobs.get(waterBenders[0]);
int val2=privateFieldJobs.getInt(waterBenders[0]);

Well, I was wrong about the latter: while both of them work for an int, but getInt() does not work on an Integer:

import java.lang.reflect.*;

class Ideone {
    public Integer objInt=23;
    public int valInt=42;

    public static void main (String[] args) throws java.lang.Exception {
        Field objField=Ideone.class.getField("objInt");
        Field valField=Ideone.class.getField("valInt");

        Ideone test=new Ideone();

        System.out.print("objInt-get: ");
        System.out.println(objField.get(test));

        System.out.print("objInt-getInt: ");
        try{
            System.out.println(objField.getInt(test));
        } catch (Exception ex) {
            System.out.println(ex.getClass());
        }

        System.out.print("valInt-get: ");
        System.out.println(valField.get(test));

        System.out.print("valInt-getInt: ");
        System.out.println(valField.getInt(test));
    }
}

(class is called Ideone, because it can be tried there: https://ideone.com/91xzmc)
Output:

objInt-get: 23
objInt-getInt: class java.lang.IllegalArgumentException
valInt-get: 42
valInt-getInt: 42

So one can use both get() and getInt() on an int field, but when the field is Integer, only get works. (The ex.getClass() magic is just about shortening the message, by default there is a long explanation which does not fit in a line).
Side note: usage of number classes, like Integer, means creating objects, on the heap (which can add to heap fragmentation, and can make extra work for the garbage collector). If you do not specifically need a number to be null-able, or to be an object for any other reason (some exotic serializers may need that), use int. It is faster, lighter and even shorter to type, plus needs no touch of Shift (for I).


text:
Q: What does " warning: ClientCursor::yield can't unlock b/c of recursive lock" means? I have one collection, say "resource.pool", which emulates the resource pool.
There are 2 states of resource:
1. FREE, it means we can acquire this resource, by setting its flag to OCCUPIED (using findAndModify)
2. OCCUPIED, it means the resource is already occupied by another process. But if it is in OCCUPIED state for too long, we can acquire it by checking if currentTime - lastFreeTime >= expiredAge.
In order to acquire one resources, I plan 1 query: expiredAge is 600000 msec.
db.resource.pool.findAndModify({
 groupId:"groupId",
 $or :[{state:"FREE"},{state:{$ne:"FREE"}, $where:"currentTime - this.lastFreeTime >= 600000"}]
},{state:"OCCUPIED, lastFreeTime:currentTime})

That query is always shown in mongodb.log file, and generated for 1-3 warning per second. What is the meaning of this warning?
Note that I use $where which evaluate the javascript. I also have created index of groupId and state.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Python urlencode with double quotes I have a dict like this:
d = {'orderBy': 'XXXXX'}

When I call urlencode (), it transforms into:
orderBy = XXXXX

But I needed it to look like this:
orderBy = "XXXXX"

Does anyone know how I add these two quotes using urllib?
Thank you!

A: Just set your dict with the doble quotes:
>>> d = { 'orderBy': '"XXXXX"' }
>>> urlencode(d)
'orderBy="XXXXX"'


text:
Q: UIStoryboardSegue animates property in subclass I have a UIStoryboardSegue subclass for replacing current view controller with next view controller.
As we have a Animates property in interface editor, I want to access this property in the subclass.

My code is following:
class ReplaceSegue: UIStoryboardSegue {

    override func perform() {
        var viewControllers = source.navigationController?.viewControllers.dropLast() ?? []
        viewControllers.append(destination)
        source.navigationController?.setViewControllers(viewControllers.map {$0}, animated: true) // I dont want this `true` to be hardcoded
    }
}

A: As per comments in UIStoryBoardSegue class

The segue runtime will call +[UIView setAnimationsAreEnabled:] prior
  to invoking this method, based on the value of the Animates checkbox
  in the Properties Inspector for the segue.

So obviously you can read the value of animate check box by using
UIView.areAnimationsEnabled

So in my custom segue
class MySegue: UIStoryboardSegue {
    override func perform() {
        debugPrint(UIView.areAnimationsEnabled)
    }
}

This prints false if animate checkbox is unchecked or true if it is checked :)
So in your case
class ReplaceSegue: UIStoryboardSegue {
    override func perform() {
            var viewControllers = source.navigationController?.viewControllers.dropLast() ?? []
            viewControllers.append(destination)
            source.navigationController?.setViewControllers(viewControllers.map {$0}, animated: UIView.areAnimationsEnabled)
    }
}

I hope whats happening is already clear, incase you still have doubt, here is the explanation, iOS checks the animates checkbox value and uses it to set whether animations are enabled or not by calling setAnimationsAreEnabled with the value of animates check box in interface prior to calling perform() method.
So when the control reaches inside perform you can be assured that iOS has already read the value of animates check box and used it to set setAnimationsAreEnabled all you have to do now is to ask areAnimationsEnabled to get the value of animates check box.
So that should provide you the value of animates checkbox :)
Hope it helps :)

A: You shouldn't need a UIStoryboardSegue subclass for this. The docs state "You can subclass UIStoryboardSegue in situations where you want to provide a custom transition between view controllers". This means that a replacement without without any animation isn't a custom transition, thus shouldn't use a segue subclass.
The correct way to do replacement is to use a Show Detail (e.g. Replace) segue and inside the parent view controller that is managing the child view controllers implement the method showDetailViewController and replace the children, e.g.
@implementation DetailNavigationController

- (void)showDetailViewController:(UIViewController *)vc sender:(id)sender{
    [self setViewControllers:@[vc] animated:NO];
}

If you didn't know, the Show Detail segue (after magically instantiating the destination view controller) has a perform method that just calls showDetailViewController on self, and the base UIViewController implementation searches up the view controller hierarchy looking for one that overrides showDetailViewController, so you can intercept it and perform your custom code, before say it goes up to another parent that might implement it also like a split view.


text:
Q: Mapping to a nested class I am getting the following error when my application runs:

System.InvalidOperationException: The type
  'ContactModels+Contact' was not mapped. Check that the
  type has not been explicitly excluded by using the Ignore method or
  NotMappedAttribute data annotation. Verify that the type was defined
  as a class, is not primitive, nested or generic, and does not inherit
  from EntityObject.

It is failing when my DBContext class tries to initialize the entities:
public class DB : DbContext
{
    public DbSet<ContactModels.Contact> Contacts { get; set; }
    ....
}

The Contact model is as follows:
public class ContactModels
{
    public class Contact
    {
        public int ID { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        ...
    }
}

Connection string:
<add name="DB" connectionString="Data Source=XXXXX;Initial Catalog=XXXX;Trusted_Connection=True"
  providerName="System.Data.SqlClient" />

I get the error whether the database exists or even if it does not exist and I have it being initialized:
protected void Application_Start()
{
    Database.SetInitializer(new CreateDatabaseIfNotExists<Models.DB>());
    ....
}

This is my first time using EF, I've followed a few tutorials but I am using SQL Server 2008 R2 and would prefer to have the database created myself rather than have EF create it for me.  Though at this point I'll take either if it works.

A: The wrong part is that you are trying to map nested class. It is not supported by entity framework.

A: I don't know what is wrong with your code but if you want to start with a database and generate the C# code use the entity framework power tools CTP1 http://blogs.msdn.com/b/adonet/archive/2011/05/18/ef-power-tools-ctp1-released.aspx


text:
Q: Execute sql queries asynchronously in C++ I have an application that reads data into a map and writes them to a sqlite database. The application does a lot of other things and is asynchronous (uses boost asio) except for writing to db part. Here is the sample pseudo code:
struct records;
std::map<int, records> list;
void read() {
    // Dump(read) X records into list
    // If record id doesn't exist, add it. dirty = true
    // If it exists, update all other fields. dirty = true if any fields changed.
}

void writeDB() {
    sqlite3_prepare_v2();
    for(const auto& record : list) { // iterate map
        if(!record.dirty())
            continue;
        sqlite3_bind(); // bind record fields
        sqlite3_step(); // execute sql
        sqlite3_reset(); // reset
    }
    sqlite3_finalize();
}

main() {
    while(1) {
        read();
        writeDB();
    }
}

My initial plan was to spawn a new thread inside the for loop which would write each record in the database in parallel. There are two issues.
1) May need to implement db locking.
2) The sqlite bind(), step() and reset() operate on the same statement. So, the records have to be written sequentially.
I am using C++ 17. Any suggestions on making the database calls async? Thanks for helping!

A: You don't have to implement locking. SQLite does provide ACID guarantees which means that you don't have to implement locking around your inserts.
That being said, spawning a thread for each insert operation is for sure overkill. You can consider splitting your list into a number of parts equal to the number of cores on the machine and executing N parallel loops to insert. But anything beyond that is probably overkill in my opinion.
But don't take my word for granted. Consider instrumenting your code and benchmarking both the single-threaded version you have now as well as any parallel implementation you may choose. You can test for various # of threads (but keep in mind that there is a relation between multi-threaded code performance and # of available cores) as well as the concurrency implementation: either C++17 std parallel execution, or boost variants etc.


text:
Q: How to solve render problem in android studio? Am facing an series problem from few days back only. Before that i didn't recieve this error. I can able to build the project but errors are showing only in Layout files alone
Following is error code in layout files:
android.view.InflateException: Class not found LinearLayout
at android.graphics.drawable.DrawableInflater_Delegate.inflateFromClass(DrawableInflater_Delegate.java:63)
at android.graphics.drawable.DrawableInflater.inflateFromClass(DrawableInflater.java:201)
at android.graphics.drawable.DrawableInflater.inflateFromXmlForDensity(DrawableInflater.java:141)
at android.graphics.drawable.Drawable.createFromXmlInnerForDensity(Drawable.java:1402)
at android.graphics.drawable.Drawable.createFromXmlForDensity(Drawable.java:1361)
at android.graphics.drawable.Drawable.createFromXml(Drawable.java:1336)
at com.android.layoutlib.bridge.impl.ResourceHelper.getDrawable(ResourceHelper.java:360)
at android.content.res.BridgeTypedArray.getDrawable(BridgeTypedArray.java:694)
at android.view.View.<init>(View.java:5535)
at android.widget.TextView.<init>(TextView.java:996)
at android.widget.TextView.<init>(TextView.java:990)
at androidx.appcompat.widget.AppCompatTextView.<init>(AppCompatTextView.java:108)
at com.google.android.material.textview.MaterialTextView.<init>(MaterialTextView.java:93)
at com.google.android.material.textview.MaterialTextView.<init>(MaterialTextView.java:88)
at com.google.android.material.textview.MaterialTextView.<init>(MaterialTextView.java:83)
at com.google.android.material.theme.MaterialComponentsViewInflater.createTextView(MaterialComponentsViewInflater.java:61)
at androidx.appcompat.app.AppCompatViewInflater.createView(AppCompatViewInflater.java:121)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
at android.view.BridgeInflater.lambda$createViewFromCustomInflater$0(BridgeInflater.java:259)
at android.view.BridgeInflater.createViewFromCustomInflater(BridgeInflater.java:285)
at android.view.BridgeInflater.onCreateView(BridgeInflater.java:122)
at android.view.LayoutInflater.onCreateView(LayoutInflater.java:928)
at android.view.LayoutInflater.onCreateView(LayoutInflater.java:948)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:1002)
at android.view.BridgeInflater.createViewFromTag(BridgeInflater.java:309)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:959)
at android.view.LayoutInflater.rInflate_Original(LayoutInflater.java:1121)
at android.view.LayoutInflater_Delegate.rInflate(LayoutInflater_Delegate.java:72)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:1095)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:1082)
at android.view.LayoutInflater.inflate(LayoutInflater.java:680)
at android.view.LayoutInflater.inflate(LayoutInflater.java:499)
at com.android.layoutlib.bridge.impl.RenderSessionImpl.inflate(RenderSessionImpl.java:353)
at com.android.layoutlib.bridge.Bridge.createSession(Bridge.java:431)
at com.android.tools.idea.layoutlib.LayoutLibrary.createSession(LayoutLibrary.java:141)
at com.android.tools.idea.rendering.RenderTask.createRenderSession(RenderTask.java:714)
at com.android.tools.idea.rendering.RenderTask.lambda$inflate$7(RenderTask.java:870)
at com.android.tools.idea.rendering.RenderExecutor$runAsyncActionWithTimeout$2.run(RenderExecutor.kt:187)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
at java.base/java.lang.Thread.run(Thread.java:834)
Caused by: java.lang.ClassNotFoundException: LinearLayout not found.
at com.android.tools.idea.rendering.LayoutlibCallbackImpl.findClass(LayoutlibCallbackImpl.java:899)
at android.graphics.drawable.DrawableInflater_Delegate.inflateFromClass(DrawableInflater_Delegate.java:45)
... 43 more

Due to this error my layout is not showing properly.
 Textinputlayouts are not visible properly. Kindly advise me
and my gradle file is
plugins {
id 'com.android.application'
id 'com.google.gms.google-services'
}

android {
compileSdkVersion 31
buildToolsVersion "30.0.3"

defaultConfig {
    applicationId 'com.zenovic.trust'
    minSdkVersion 28
    targetSdkVersion 31
    versionCode 1
    versionName '1.0.1'
    multiDexEnabled true

    testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}

buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
    }
}

compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
}
sourceSets {
    main {
        assets {
            srcDirs 'src\\main\\assets'
        }
    }
}
}

 dependencies {

implementation 'androidx.appcompat:appcompat:1.4.0'
implementation 'com.google.android.material:material:1.4.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.2'
implementation 'com.google.firebase:firebase-auth:21.0.1'
implementation 'com.google.firebase:firebase-database:20.0.3'
implementation 'com.google.firebase:firebase-messaging:23.0.0'
implementation 'com.google.firebase:firebase-core:20.0.2'
implementation platform('com.google.firebase:firebase-bom:28.4.1')
implementation 'com.google.firebase:firebase-messaging'
implementation 'com.google.firebase:firebase-analytics'
implementation 'com.orhanobut:dialogplus:1.11@aar'
implementation 'com.firebaseui:firebase-ui-database:7.1.1'
implementation 'com.google.firebase:firebase-auth'
implementation 'com.google.firebase:firebase-storage:20.0.0'
implementation 'net.yslibrary.keyboardvisibilityevent:keyboardvisibilityevent:3.0.0-RC3'
implementation 'com.airbnb.android:lottie:3.7.1'
implementation 'com.squareup.picasso:picasso:2.71828'
implementation "androidx.multidex:multidex:2.0.1"

testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}

And my XML file is:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/background"
tools:context=".user.LoginActivity">

<TextView
    android:id="@+id/loginText1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/welcome_to"
    android:textColor="@color/colorWhite"
    android:textSize="30sp"
    android:textStyle="bold|italic"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.07999998" />

<TextView
    android:id="@+id/loginText2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/zenovic_trust"
    android:textColor="@color/colorWhite"
    android:textSize="30sp"
    android:textStyle="bold|italic"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/loginText1"
    app:layout_constraintVertical_bias="0.01999998" />

<TextView
    android:id="@+id/loginText3"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="80dp"
    android:text="@string/login1"
    android:textColor="@color/colorWhite"
    android:textSize="30sp"
    android:textStyle="bold|italic"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/loginText2"
    app:layout_constraintVertical_bias="0.04000002" />

<com.google.android.material.textfield.TextInputLayout
    android:id="@+id/emailLayout"
    style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_marginStart="32dp"
    android:layout_marginTop="40dp"
    android:layout_marginEnd="32dp"
    android:hint="@string/email"
    android:textColorHint="@color/colorWhite"
    android:theme="@style/ThemeOverlay.AppTheme.TextInputEditText.Outlined"
    app:boxCornerRadiusBottomEnd="10dp"
    app:boxCornerRadiusBottomStart="10dp"
    app:boxCornerRadiusTopEnd="10dp"
    app:boxCornerRadiusTopStart="10dp"
    app:boxStrokeColor="@color/colorWhite"
    app:boxStrokeWidth="2dp"
    app:boxStrokeWidthFocused="2dp"
    app:endIconMode="clear_text"
    app:endIconTint="@color/colorWhite"
    app:errorTextColor="@color/colorWhite"
    app:hintTextColor="@color/colorWhite"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/loginText3"
    app:startIconDrawable="@drawable/ic_email"
    app:startIconTint="@color/colorWhite">

    <com.google.android.material.textfield.TextInputEditText
        android:id="@+id/inputLoginEmail"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="textEmailAddress"
        android:textColor="@color/colorWhite"
        android:textCursorDrawable="@drawable/color_cursor"
        android:textSize="18sp" />
</com.google.android.material.textfield.TextInputLayout>

<com.google.android.material.textfield.TextInputLayout
    android:id="@+id/passwordLayout"
    style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_marginStart="32dp"
    android:layout_marginTop="30dp"
    android:layout_marginEnd="32dp"
    android:hint="@string/password"
    android:textColorHint="@color/colorWhite"
    android:theme="@style/ThemeOverlay.AppTheme.TextInputEditText.Outlined"
    app:boxCornerRadiusBottomEnd="10dp"
    app:boxCornerRadiusBottomStart="10dp"
    app:boxCornerRadiusTopEnd="10dp"
    app:boxCornerRadiusTopStart="10dp"
    app:boxStrokeColor="@color/colorWhite"
    app:boxStrokeWidth="2dp"
    app:boxStrokeWidthFocused="2dp"
    app:endIconMode="password_toggle"
    app:endIconTint="@color/colorWhite"
    app:errorTextColor="@color/colorWhite"
    app:hintTextColor="@color/colorWhite"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/emailLayout"
    app:passwordToggleEnabled="true"
    app:startIconDrawable="@drawable/ic_security"
    app:startIconTint="@color/colorWhite">

    <com.google.android.material.textfield.TextInputEditText
        android:id="@+id/inputLoginPassword"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:imeOptions="actionGo"
        android:inputType="textPassword"
        android:textColor="@color/colorWhite"
        android:textCursorDrawable="@drawable/color_cursor"
        android:textSize="18sp" />
</com.google.android.material.textfield.TextInputLayout>

<androidx.appcompat.widget.AppCompatButton
    android:id="@+id/btnLogin"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="10dp"
    android:background="@drawable/btn_bg"
    android:text="@string/login"
    android:textSize="20sp"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/checkBox" />

<TextView
    android:id="@+id/textViewSignUp"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginBottom="40dp"
    android:text="@string/don_t_have_an_account_signup_here"
    android:textColor="@color/colorWhite"
    android:textSize="18sp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent" />

<TextView
    android:id="@+id/forgotPassword"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginStart="35dp"
    android:layout_marginTop="20dp"
    android:layout_marginEnd="32dp"
    android:text="@string/forgot_password"
    android:textColor="@color/colorWhite"
    android:textSize="18sp"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/btnLogin" />

<CheckBox
    android:id="@+id/checkBox"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="10dp"
    android:buttonTint="@color/colorWhite"
    android:text="@string/stay_logged_in"
    android:textColor="@color/colorWhite"
    android:textSize="18sp"
    app:layout_constraintStart_toStartOf="@+id/passwordLayout"
    app:layout_constraintTop_toBottomOf="@+id/passwordLayout" />

  </androidx.constraintlayout.widget.ConstraintLayout>


text:
Q: Calculate exact date difference in years using SQL I receive reports in which the data is ETL to the DB automatically.  I extract and transform some of that data to load it somewhere else.  One thing I need to do is a DATEDIFF but the year needs to be exact (i.e., 4.6 years instead of rounding up to five years.
The following is my script:
select *, DATEDIFF (yy, Begin_date, GETDATE()) AS 'Age in Years'
from Report_Stage;

The 'Age_In_Years' column is being rounded.  How do I get the exact date in years?

A: I think that division by 365.2425 is not a good way to do this. No division can to this completely accurately (using 365.25 also has issues).
I know the following script calculates an accurate date difference (though might not be the most speedy way):
        declare @d1 datetime ,@d2 datetime
        --set your dates eg:
        select @d1 = '1901-03-02'
        select @d2 = '2016-03-01'

        select DATEDIFF(yy, @d1, @d2) -
            CASE WHEN MONTH(@d2) < MONTH(@d1) THEN 1
                 WHEN MONTH(@d2) > MONTH(@d1) THEN 0
                 WHEN DAY(@d2) < DAY(@d1) THEN 1
                 ELSE 0 END

         -- = 114 years

For comparison:
         select datediff(day,@d1 ,@d2) / 365.2425
         -- = 115 years => wrong!

You might be able to calculate small ranges with division, but why take a chance??
The following script can help to test yeardiff functions (just swap cast(datediff(day,@d1,@d2) / 365.2425 as int)  to whatever the function is):
   declare @d1 datetime set @d1 = '1900-01-01'

   while(@d1 < '2016-01-01')
   begin
    declare @d2 datetime set @d2 = '2016-04-01'

    while(@d2 >= '1900-01-01')
    begin
        if (@d1 <= @d2 and dateadd(YEAR,     cast(datediff(day,@d1,@d2) / 365.2425 as int)      , @d1) > @d2)
        begin
            select 'not a year!!', @d1, @d2, cast(datediff(day,@d1,@d2) / 365.2425 as int)
        end

        set @d2 = dateadd(day,-1,@d2)
    end

    set @d1 = dateadd(day,1,@d1)
  end

A: All datediff() does is compute the number of period boundaries crossed between two dates. For instance
datediff(yy,'31 Dec 2013','1 Jan 2014')

returns 1.
You'll get a more accurate result if you compute the difference between the two dates in days and divide by the mean length of a calendar year in days over a 400 year span (365.2425):
datediff(day,{start-date},{end-date},) / 365.2425

For instance,
select datediff(day,'1 Jan 2000' ,'18 April 2014') / 365.2425

return 14.29461248 — just round it to the desired precision.

A: You want the years difference, but reduced by 1 when the "day of the year" of the future date is less than that of the past date. So like this:
SELECT *
,DATEDIFF(YEAR, [Begin_date], [End_Date])
 + CASE WHEN CAST(DATENAME(DAYOFYEAR, [End_Date]) AS INT)
          >= CAST(DATENAME(DAYOFYEAR, [Begin_date]) AS INT)
   THEN 0 ELSE -1 END
 AS 'Age in Years'
from [myTable];

A: Have you tried getting the difference in months instead and then calculating the years that way? For example 30 months / 12 would be 2.5 years.
Edit: This SQL query contains several approaches to calculate the date difference:
SELECT CONVERT(date, GetDate() - 912) AS calcDate
      ,DATEDIFF(DAY, GetDate() - 912, GetDate()) diffDays
      ,DATEDIFF(DAY, GetDate() - 912, GetDate()) / 365.0 diffDaysCalc
      ,DATEDIFF(MONTH, GetDate() - 912, GetDate()) diffMonths
      ,DATEDIFF(MONTH, GetDate() - 912, GetDate()) / 12.0 diffMonthsCalc
      ,DATEDIFF(YEAR, GetDate() - 912, GetDate()) diffYears

A: For me I calculate the difference in days
Declare @startDate datetime
Declare @endDate datetime
Declare @diff int
select @diff=datediff(day,@startDate,@endDate)
if (@diff>=365) then select '1Year'
if (@diff>=730) then select '2Years'

-----etc

A: I have found a better solution.  This makes the assumption that the first date is less than or equal to the second date.
declare @dateTable table (date1 datetime, date2 datetime)
insert into @dateTable
    select '2017-12-31', '2018-01-02' union
    select '2017-01-03', '2018-01-02' union
    select '2017-01-02', '2018-01-02' union
    select '2017-01-01', '2018-01-02' union
    select '2016-12-01', '2018-01-02' union
    select '2016-01-03', '2018-01-02' union
    select '2016-01-02', '2018-01-02' union
    select '2016-01-01', '2018-01-02'
select date1, date2,
        case when ((DATEPART(year, date1) < DATEPART(year, date2)) and
                    ((DATEPART(month, date1) <= DATEPART(month, date2)) and
(DATEPART(day, date1) <= DATEPART(day, date2)) ))
                    then DATEDIFF(year, date1, date2)
            when (DATEPART(year, date1) < DATEPART(year, date2))
                    then DATEDIFF(year, date1, date2) - 1
            when (DATEPART(year, date1) = DATEPART(year, date2))
                    then 0
        end [YearsOfService]
from @dateTable

date1                   date2                   YearsOfService
----------------------- ----------------------- --------------
2016-01-01 00:00:00.000 2018-01-02 00:00:00.000 2
2016-01-02 00:00:00.000 2018-01-02 00:00:00.000 2
2016-01-03 00:00:00.000 2018-01-02 00:00:00.000 1
2016-12-01 00:00:00.000 2018-01-02 00:00:00.000 1
2017-01-01 00:00:00.000 2018-01-02 00:00:00.000 1
2017-01-02 00:00:00.000 2018-01-02 00:00:00.000 1
2017-01-03 00:00:00.000 2018-01-02 00:00:00.000 0
2017-12-31 00:00:00.000 2018-01-02 00:00:00.000 0


text:
Q: How to disable External Entity Resolution in xerces C++ DOMLSParser We are using Xerces C++ DOMLSParser. I want to disable External Entities but could not find anything for DOMLSParser.
How to disable Loading External Entities to prevent XXE attacks?

A: xercesc::DOMImplementation* impl = xercesc::DOMImplementationRegistry::getDOMImplementation (u"LS");
xercesc::DOMLSParser* parser = impl->createLSParser(xercesc::DOMImplementationLS::MODE_SYNCHRONOUS, nullptr);
xercesc::DOMConfiguration* conf = parser->getDomConfig();
conf->setParameter(xercesc::XMLUni::fgDOMEntities, false);

Documentation: https://xerces.apache.org/xerces-c/program-dom-3.html (search for fgDOMEntities)


text:
Q: Create the game matrix Each of two players shows one or two fingers (simultaneously) and $C$ pays to $R$ a sum equal to the total number of fingers shown. Write the game matrix. Show that the game is strictly determined and find the value and optimal strategies.
I'm brand new at game theory and just learned how to tell if a game is fair or strictly determined. I think I'm thinking about this wrong but if there are only two options and I need the game to be strictly determined wouldn't the answer be a matrix with all one's or all two's?

A: The specific arrangement of how you insert the information varies based on textbook, but a common way to write it out would be such as the following:
$\begin{array}{r|c|c|}&C~\text{shows}&C~\text{shows}\\&\text{1 finger}&\text{2 fingers}\\\hline R~\text{shows 1 finger}\\
\hline R~\text{shows 2 fingers}\\\hline \end{array}$
writing values into the table according to how much money $R$ would win (which is the same amount that $C$ would lose) if those selections were simultaneously made.
For example, in the top left entry with $R$ showing one finger and $C$ showing one finger, there would be a total of two fingers shown implying that $C$ would need to pay $R$ two dollars (or whatever currency they happen to be using).
As for deciding strategies... $C$ knows that if he chooses to show more fingers he'll lose more money than if he chose to show only one finger... so $C$'s strategy will be to _______.
Similarly, $R$ wants to make as much money as possible so the more fingers $R$ shows the more money he'll stand to make so $R$'s strategy will be to ______.
Since both players are dead-set on what strategies they'll be following, we can expect that every time they play this game the outcome will be identical every time... i.e. it is indeed a strictly determined game, and the outcome every time they play will be that $R$ wins ______ dollars from $C$.
Since the expected outcome of the game is not zero, the game is not fair.


text:
Q: Hacer invisibles controles en JavaFX ¿Hay alguna forma de esconder controles en javaFX de forma que éstos no ocupen espacio? He visto que en android es posible: control.setVisibility(View.GONE);
Lo que se me ocurre es esto:
control.setVisible(false);
control.setMinSize(0,0);
control.setMaxSize(0,0);
control.setPrefSize(0,0);

pero me conserva el espacio y me obliga a restaurar los tamaños originales una vez que los controles vuelven a ser visibles.

A: Esta opción que intentaste, únicamente funciona usando el Android SDK :
control.setVisibility(View.GONE);

Para esconder un control en JavaFX, Puedes realizarlo con:
 control.setVisible(false);

o si no deseas que ocupe espacio tienes que removerlo:
contenedor.getChildren().remove(control);

Este es un ejemplo removiendo un botón:

A: Puedes intentar con el método Node.setVisible(false) que oculta el nodo, o puedes intentar con setManaged que va un poco más allá y deja de administrar el nodo, de esta forma no e realizan cálculos con el.
Puedes comprobar si esta administrado (Managed) con el método isManaged()

A: Al final he creado dos métodos, uno para esconder un control y otro para mostrarlo:
void esconderControl (Control control) {
        control.setVisible(false);
        control.setManaged(false);
}
void mostrarControl (Control control) {
        control.setVisible(true);
        control.setManaged(true);
}
esconderControl (miControl); // hace desaparecer miControl de pantalla
mostrarControl (miControl);  // hace aparecer miControl de pantalla

El método setManaged(boolean) deja de gestionar el control, pero puede seguir apareciendo en la pantalla de forma inesperada en cualquier sitio dentro de su contenedor así que es imprescindible también utilizar el método SetVisible(bolean)


text:
Q: Trigger pl/sql insert data on table i'm new in pl/sql. I'm trying to create a trigger that insert datas in specific tables.
I have datas that arrives in real-time on my table EV_48h. To know on which table I have to insert the data i have to know it Ref_equip (Ref_equip is on an other table named C_Equip).
I've made quickly this littre merise to be more understandable:
merise
As I said  I have data that arrives on real-time on the table EV_48H and I have to put them automatically on the tables that are named 'EVV_'+Ref_equip.
So, here is my code. I don't have any error but it don't work. I know i missed of forget something but i don't know what.
TRIGGER "SIVO"."NEWtrigger3EV_48H"
BEFORE INSERT
ON SIVO.EV_48H
REFERENCING NEW AS NEW OLD AS OLD
FOR EACH ROW

declare
clef_var number(4,0);
ref_equip varchar2(40);
V_Nom_table varchar2(1000) ;
V_nom_seq Varchar2(2000) ;
stmt varchar2(200);

begin
SELECT clef_var
INTO :New.Clef_Var
FROM sivo.c_variable
WHERE Ref_Var= :new.Ref_Var;
  -- Conversion des formats Date-Heure en DateHeure oracle
  :New.EV_DATEAUTO := to_date(:New.EV_DATE || ' ' || :New.EV_HEURE, 'DD/MM/YY HH24:MI:SS');
  stmt:='begin select clef_var into :New.Clef_Var From sivo.C_variable; end';
  EXECUTE IMMEDIATE stmt using out clef_var;

  IF clef_var is not null then

    stmt :='begin select Ref_equip into :New.Ref_Equip FROM sivo.C_Equip WHERE Ref_var= :New.Ref_Var; end';
    EXECUTE IMMEDIATE Stmt USING OUT Ref_Equip;
    V_nom_table := 'EVV_'||Ref_Equip;
    stmt :='insert into' ||V_nom_table || '(:New.Clef_Var, :New.Ev_DateAuto, :New.Ev_Valeur )';
    EXECUTE IMMEDIATE stmt USING Ref_Equip;

  ELSE
  INSERT INTO SIVO.EV_48H_VAR_INCONNUES (REF_VAR, EV_DATE, EV_HEURE, EV_VALEUR)
  VALUES ( :New.REF_VAR, :New.EV_DATE, :New.EV_HEURE, :New.EV_VALEUR);

  end if;
END;

If someone can help me or put me on the right way. I don't know if I give all informations so tell me if I missed something.
Thanks

A: In your execute immediate you are missing the end of statement indicator colon after END
this should be
begin select clef_var into :New.Clef_Var From sivo.C_variable; end;

However there are other design choices that you should be aware of:

*

*using execute immediate is handy but if you don't have to use it you shouldn't. The work can be done by a cursor or even a simple select statement if only one value will come back.  In fact it appears you do the work twice. First you insert into the :new.clef_var then you do the same thing again with the execute immediate.  Try commenting out the execute immediate.

*by using execute immediate any errors are harder to track

*using a trigger means the real time data source cannot end the transaction until the trigger completes.  Why not run a scheduled job every minute to check for new data and process it?  This breaks the transaction into two parts: data entry and data processing

*is there any update of records that your process needs to capture?


text:
Q: Best practice for show data inside Laravel view What is the best practice, for example to show user data?

*

*Retrieve user in show function inside UserContoller, and pass user variable to the view?

*Return view in show function, passing the $user_id, and retrieve the user on the view?
Example 1:
public function show($id)
{
    $user = User::findOrFail($id);
    return view('config.users.show')->withUser($user);
}

Example 2:
public function show($id)
{
    return view('config.users.show')->withId($id);
}

A: Views are responsible for data representation.

A view can be any output representation of information, such as a
chart or a diagram. Multiple views of the same information are
possible, such as a bar chart for management and a tabular view for
accountants.
The model directly manages the data, logic and rules of the
application.
The third part, the controller, accepts input and converts it to
commands for the model or view

Source
You should pass the data to the view. and output there, So your first example is correct one.
Instead of withUser() keep using with(key, value)
Example:
public function show($id)
{
    $user = User::findOrFail($id);
    return view('config.users.show')->with('user', $user);
}

In view:
{{ $user->name }} //assuming user have a name attribute

A: Adding to xdevnull's answer, id like to add and share some more information on passing data as when i was first learning laravel this was one the bigger areas i struggled with so i feels you:)
return view('config.users.show')->withUser($user);

Is a Laravel's dynamic function capabilities which should work.
but personally i prefer the ->with('user',$user); method
then in your blade view:
{{$user->propertyname}}

I know in your case youre only needing one model, but id thought id share some examples of passing multiple things
Sometimes you find yourself passing more than one model or piece of data:
 $user = User::findOrFail($id);
 $someOtherModel = Model::findOrFail($id);

in which case you should use the with way and pass an array of your stuff:
return view('config.users.show')->with([

    'user'=> $user,
    'otherModel'=>$someOtherModel

]);

Then in your view:
{{$otherModel->propertyname}}
{{$user->propertyname}}
and recently i find myself retrieving all results of which id like to be able to use specific ones in different parts of my view. I asked a question regarding this so one of the answers i was given was to make my collection of models into an array. As i said Sometimes you may be retrieving all results and want to pick certain ones by a a specific column or value.
For example i have a model to keep track of site data(phone, address,social media links,etc) and wanted to pass them to my view and access them in specific parts of the page according to their name:
$site_meta = \App\SiteMeta::lists('value', 'name');

return view($page_string, compact('site_meta');

On my blade template:
{{$site_meta['Facebook']}}

Hope this helps you somehow, i know it sure did me when i was learning it:)


text:
Q: Intellij idea - spring project - don't see my files under the project While working on my project in intellij idea using spring I've pressed some option unintentionally and now I don't see any of the classes under the project except for:
pom and iml.
Any one knows how to revert it?
(All the files are located at place - there weren't erased. Also the files that are still opened in idea are now marked with a red circle with the letter "J" in the middle)

A: Found it!!!
Settings -> Maven - > Ignored Files
I had the pom file checked to ignore.


text:
Q: Spark: sparkSession read from the result of an http response Small question regarding Spark and how to read from the result of a http response please.
It is well known Spark can take as datasource some database, or CSV, etc...
sparkSession.read().format("csv").load("path/to/people.csv");

sparkSession.read().format("org.apache.spark.sql.cassandra").options(properties).load()

May I ask how to read from the result of an http call directly please?
Without having to dump the data back inside another intermediate csv / intermediate database table.
For instance the csv and database would contains millions of rows, and once read, the job needs to perform some kind of map reduce operation.
Now, the exact same data comes from the result of an http call. It is small enough for the network layer, but the information contained inside the payload is big, so I would like to apply the same map reduce.
How to read from the response of an http call please?
Thank you

A: You have two options for reading data in Spark:

*

*Read directly to the driver and distribute to the executors (not scalable as everything passes through driver)

*Read directly from the executors

The built in data sources like csv, parquet etc all implement reading from the executors so the job can scale with the data. They define how each partition of the data should be read - e.g. if we have 10 executors, how do you cut up the data source into 10 sections so each executor can directly read one section.
If you want to load from a HTTP request you will either have to read through the driver and distribute, which may be OK if you know the data is going to be less than ~10mb. Otherwise you would need to implement a custom data source to allow the executors to each read partition, can read here for more:  https://aamargajbhiye.medium.com/speed-up-apache-spark-job-execution-using-a-custom-data-source-fd791a0fa4b0
Will finish by saying that this second option is almost definitely an anti-pattern. You will likely be much better off providing an intermediate staging environment (e.g. S3/GCS), calling the server to load the data to the intermediate store and then reading to Spark on completion. In scenario 2, you will likely end up putting too much load on the server, amongst other issues.

A: In previous lifetimes, I created a custom datasource. It is not the most trivial thing to do, but this GitHub repo explains it: https://github.com/jgperrin/net.jgp.books.spark.ch09.
When it comes to reading from a network stream, make sure that only one executor does it.


text:
Q: SQL - Trigger for auto-incrementing number of signed in people I am having a little bit of trouble with making a trigger in my SQL. I have two tables:
This one
Create table [user]
(
    [id_user] Integer Identity(1,1) NOT NULL,
    [id_event] Integer NULL,
    [name] Nvarchar(15) NOT NULL,
    [lastname] Nvarchar(25) NOT NULL,
    [email] Nvarchar(50) NOT NULL, UNIQUE ([email]),
    [phone] Integer NULL, UNIQUE ([phone]),
    [pass] Nvarchar(50) NOT NULL,
    [nick] Nvarchar(20) NOT NULL, UNIQUE ([nick]),
Primary Key ([id_user])
)
go

and this one
Create table [event]
(
    [id_event] Integer Identity(1,1) NOT NULL,
    [id_creator] Integer NOT NULL,
    [name] Nvarchar(50) NOT NULL,
    [date] Datetime NOT NULL, UNIQUE ([date]),
    [city] Nvarchar(50) NOT NULL,
    [street] Nvarchar(50) NOT NULL,
    [zip] Integer NOT NULL,
    [building_number] Integer NOT NULL,
    [n_signed_people] Integer Default 0 NOT NULL Constraint [n_signed_people] Check (n_signed_people <= 20),
Primary Key ([id_akce])
)

Now I need a trigger for when I insert a new user with and id_event, or update existing one with one, to take the id_event I inserted, look in the table of events and increment the n_signed_people in a line with a coresponding id_event, until it is 20. When it is 20, it should say that the event is full. I made something like this, it is working when I add a new user with id, but now I need it to stop at 20 and say its full and also I am not sure if it will work, when I'll try to update existing user, by adding an id_event (I assume it was NULL before update).
CREATE TRIGGER TR_userSigning
ON user
AFTER INSERT
AS
BEGIN
    DECLARE @idevent int;
    IF (SELECT id_event FROM Inserted) IS NOT NULL --if the id_event is not empty
        BEGIN
        SELECT @idevent=id_event FROM Inserted; --the inserted id_event will be save in a local variable
        UPDATE event SET n_signed_people = n_signed_people+1 WHERE @idevent = id_event;
        END
END
go

A: Good evening,
I did notice some issues with your schema.  I want to list the fixes I made in order.
1 - Do not use reserved words.  Both user and event are reserved.
2 - Name your constraints.  You will be glad they are not some random word when you want to drop one.
3 - I added a foreign key to make sure there is integrity in the relationship.
All this work was done in tempdb.  Now, lets get to the fun stuff, the trigger.

-- Just playing around
use tempdb;
go

-- attendee table
if object_id('attendees') > 0
drop table attendees
go

create table attendees
(
    id int identity (1,1) NOT NULL constraint pk_attendees primary key,
    firstname nvarchar(15) NOT NULL,
    lastname nvarchar(25) NOT NULL,
    email nvarchar(50) NOT NULL constraint uc_email unique,
    phone int NULL constraint uc_phone unique,
    pass nvarchar(50) NOT NULL,
    nick nvarchar(20) NOT NULL constraint uc_nick unique,
    event_id int NOT NULL
)
go

-- events table
if object_id('events') > 0
drop table events
go

create table events
(
    id int identity (1,1) NOT NULL constraint pk_events primary key,
    creator int NOT NULL,
    name nvarchar(50) NOT NULL,
    planed_date datetime NOT NULL constraint uc_planed_date unique,
    street nvarchar(50) NOT NULL,
    city nvarchar(50) NOT NULL,
    zip nvarchar(9) NOT NULL,
    building_num int NOT NULL,
    registered int
        constraint df_registered default (0) NOT NULL
        constraint chk_registered check (registered <= 20),
);
go

-- add some data
insert into events (creator, name, planed_date, street, city, zip, building_num)
values (1, 'new years eve', '20131231 20:00:00', 'Promenade Street', 'Providence', '02908', 99);

-- make sure their is integrity
alter table attendees add constraint [fk_event_id]
foreign key (event_id) references events (id);

I usually add all three options (insert, update, & delete).  You coded for insert in the example above.  But you did not code for delete.
Also, both the inserted and deleted tables can contain multiple rows.  For instance, if two attendees decide to drop out, you want to minus 2 from the table.
-- create the new trigger.
CREATE TRIGGER [dbo].[trg_attendees_cnt] on [dbo].[attendees]
FOR INSERT, UPDATE, DELETE
AS
BEGIN

    -- declare local variable
    DECLARE @MYMSG VARCHAR(250);

    -- nothing to do?
    IF (@@rowcount = 0) RETURN;

    -- do not count rows
    SET NOCOUNT ON;

    -- deleted data
    IF NOT EXISTS (SELECT * FROM inserted)
        BEGIN
            UPDATE e
            SET e.registered = e.registered - c.total
            FROM
                [dbo].[events] e
            INNER JOIN
                (SELECT [event_id], count(*) as total
                         FROM deleted group by [event_id]) c
            ON e.id = c.event_id;
            RETURN;
        END

    -- inserted data
    ELSE IF NOT EXISTS (SELECT * FROM deleted)
       BEGIN
           UPDATE e
            SET e.registered = e.registered + c.total
            FROM
                [dbo].[events] e
            INNER JOIN
                (SELECT [event_id], count(*) as total
                         FROM inserted group by [event_id]) c
            ON e.id = c.event_id;
            RETURN;
       END;

     -- updated data (no counting involved)
END
GO

Like any good programmer, I need to test my work to make sure it is sound.
Lets add 21 new attendees.  The check constraint should fire.  This only works since the error generated by the UPDATE rollback the insert.
-- Add 21 attendees
declare @var_cnt int = 0;
declare @var_num char(2);
while (@var_cnt < 22)
begin
    set @var_num =  str(@var_cnt, 2, 0);
    insert into attendees (firstname, lastname, email, phone, pass, nick, event_id)
    values ('first-' + @var_num,
            'last-' + @var_num,
            'email-'+ @var_num,
            5554400 + (@var_cnt),
            'pass-' +  @var_num,
            'nick-' +  @var_num, 1);
    set @var_cnt = @var_cnt + 1
end
go

Last but not least, we need to test a DELETE action.
-- Delete the last row
delete from [dbo].[attendees] where id = 20;
go


text:
Q: Python "TypeError" when writing to HTML File in "while" Loop I have getting error for TypeError: must be str, not int This function below new_file.write works fine when it outside the while loop.
#write Data
i = 0
j = 0
while i < 10:
    i = i+1
    j = j+1
    news_file.write('
\n' + '' + i + '<\th>' + '\n')
    news_file.write('' + fetch_title[j] + '	' + '\n' +'
')

A: In Python it is not possible to directly concat a string and non-strings. You'll have to use one of the many string interpolation syntaxes, for example:
news_file.write('
\n{}<\th>\n'.format(i)


text:
Q: How to bind XmlDataProvider.Source to MVVM property I've got a treeview bound to an XmlDataProvider following this example. The app I am working on is following the MVVM pattern and the Xml is from a file that the user will open.
When I try to bind the Source property of the XmlDataProvider like so
<XmlDataProvider Source="{Binding Path=XmlFilePath}"/>

I get a "Binding can only be applied to a DependencyProperty of a Dependency object." or somesuch.
So short of cobbling the binding together procedurally is there a way to declaratively bind the XmlDataProvider Source? If I try to forgo the data provider and bind the tree directly to an XmlNode property I get an error about using XPath binding only with Xml objects; which makes absolutely no sense to me but I'm sure it's trying to tell me something important.

A: The answer appears to be: you can't.
I was able to solve my underlying problem (binding a treeview to an Xml document) by removing the XmlDataProvider from the equation and binding the TreeView directly to a ViewModel property that returns an XmlNode.
What had been tripping me up was that I took the binding code that pointed at the XmlDataProvider and pointed it at my property, leaving the XPath argument in place.
<TreeView ItemsSource="{Binding Path=ProjectDocument XPath=.}">

This would result in a runtime error: System.Windows.Data Error: 44 : BindingExpression with XPath cannot bind to non-XML object.; XPath='.'
Which was not the most helpful. What it was really trying to say is that you can't bind to an XmlNode property AND provide an XPath argument in the binding (because it's the XmlDataProvider that knows what to do with that??).
<TreeView ItemsSource="{Binding Path=ProjectDocument}">

A: actually that was rather tough problem for me, cause I needed the app to load treeview from temp file, and assuming application can have different locations, I can't set strict link in the XmlDataProvider Source property;
Add source as resource to the project
the solution I found is adding temp file (markup is created via XAML, see below) to the project with build action set to Content thus, application reloads it every time you call InitializeComponent() on the object containing XmlDataProvider and my treeview updates.
    <XmlDataProvider x:Key="dshPreview"
                     Source="~tmpConstruct.xml"
                     XmlNamespaceManager="{StaticResource argNms}"
                     IsAsynchronous="true"/>

TreeView is bound like this:
  <TreeView  x:Name="PreviewTree"
             ItemsSource="{Binding Source={StaticResource dshPreview},
             XPath=/mns:engine/mns:ws}"
              />

Maybe this will help someone

A: I didn't find how to bind the source straight away, but you can change the XmlDataProvider source in the code behind as following:
var xdp = (XmlDataProvider)this.Resources["key-of-your-XmlDataProvider-in-resources"];
xdp.Source = new Uri("http://url-of-your-xml");

You can use that combined with an event handler to bind.


text:
Q: C++, Gnuplot: Create temporary file in RAM and use it in Gnuplot I am a beginner in C++. Suppose I have a C++ program that outputs a function, for example f(x)=x*x, and I need it evaluated and printed. This can be easily done within the code.
Is it possible to create a temporary file with the result of the evaluation in RAM? As in, it would be an std::vector, most likely, so it would reside in the heap (no?).
Then, would it be possible to use system() (or anything from within the code) to call gnuplot with the file from the memory?
And, as a final whim, can these two be done without an external virtual RAM disk?

A: So in Linux, using pipes, you could do the following as a first example:
cat data.txt | gnuplot -p -e "plot '-' w l"

where data.txt is a two column file. Instead of that file you can have your program produce some data and you could add an extra setting for gnuplot to make it slightly more involved:
./program | gnuplot -p -e "set ylabel 'E'; plot '-' w l"

Now this is all you need. Note that the -p = persistent, -e = interactive(?) and the semicolons (;) between the commands are required. Something similar might work in windows. I hope this helpts.
Extra stuff: If you have a lot of settings you can put them in a file, ex:
$ cat settings.txt
set logs;
set ylabel "hejsan";
set xlabel "energy";
plot '-' w l

and then:
./program | gnuplot -p -e "$(<settings.txt)"

Dont miss any symbols in "$(<filename)"! This might only apply to the Bash shell in Linux though. You can try the cygwin environment. Or just install ubuntu.
EDIT a week later
In case you want to do this to save your SSD, it of course wont hurt, but probably doesn't matter. The SSD's have intelligent management so it wont write to the same physical segment every time. The file would "move around", and they are built to last for hundreds of terabytes worth of cycling.


text:
Q: iPhone will not vibrate while displaying camera view I can programmatically make the phone vibrate, but for some reason it stops working while a live camera view is being displayed. Could it be that the uiimagepicker is intercepting audio playback? Once I dismiss the live view vibrating resumes.

A: I have an app that vibrates while showing a camera view, but I use AVFF, not UIImagePickerController. So it may be something in UIImagePickerController or it might be something unrelated in your code.


text:
Q: Intercept any outgoing network request in V8 ( at core level ) I need to modify the embedded V8 engine in electronjs/nodejs in order to intercept/block any network access request, whether it be through request, http module or even src tag in a html or ajax request, i need to pull this off at the core of V8 so that no one could tamper it using any js code. ( Maybe possibly through C++ addons. )
C++ is not my best thing so if anyone could help me with the solution and implementation I'll appreciate it.

A: V8 does not do any networking requests and has no networking code, so there is nothing to intercept there. You'll have to look at the respective embedder (i.e. Electron/Node).


text:
Q: Fpdf creating new line after new data I changed Cell() to Multicell() in a table to include break lines inside a cell.
I don't know why it is breking the line after each new data. I mean, the header and corresponding data should be all in one line:

Name | Last Name | Exemple of breaking line

but what's happening is:

Name
Last Name
Exemple of breaking line

php:
<?php

$pdf->Multicell(200, 20, 'Motorista',1);
$pdf->Multicell(60, 20, 'Direção',1);
$pdf->Multicell(60, 15, "Espera Pós \nJornada",1,'C');
$pdf->Multicell(60, 15, "Espera em \nJornada",1,'C');
$pdf->Multicell(60, 20, 'Noturnas',1);
$pdf->Multicell(70, 20, 'Extras 50%',1);
$pdf->Multicell(70, 20, 'Extras 100%',1);
$pdf->Multicell(60, 15, "Hrs Tempo \nParado",1,'C');
$pdf->SetFont('Arial', '', 9);
$pdf->Ln(10);

?>

I removed $pdf->Ln(10); but this is just for adding margin from header to data.

A: I solved it based on this answer
<?php

$x = $pdf->GetX();
$y = $pdf->GetY();

$pdf->Multicell(200, 30, 'Motorista',1,'C');
$pdf->SetXY($x + 200, $y);

$pdf->Multicell(60, 30, 'Direção',1,'C');
$pdf->SetXY($x + 260, $y);

$pdf->Multicell(60, 15, "Espera Pós \nJornada",1,'C');
$pdf->SetXY($x + 320, $y);

$pdf->Multicell(60, 15, "Espera em \nJornada",1,'C');
$pdf->SetXY($x + 380, $y);

$pdf->Multicell(60, 30, 'Noturnas',1,'C');
$pdf->SetXY($x + 440, $y);

$pdf->Multicell(60, 30, 'Extras 50%',1,'C');
$pdf->SetXY($x + 500, $y);

$pdf->Multicell(60, 30, 'Extras 100%',1,'C');
$pdf->SetXY($x + 560, $y);

$pdf->Multicell(60, 15, "Hrs Tempo \nParado",1,'C');
$pdf->SetXY($x + 620, $y);

$pdf->SetFont('Arial', '', 9);
$pdf->Ln(30);

?>

So you sum the previous col width to the next one.


text:
Q: How to Skip the first activity under a condition I'm building a group of apps as a package similar to MS Office. Here each app has its own launcher as well as it can be launched from inside the home app. Each app has a login page. I need to display the login page when the app is launched from android launcher and not showing login page while launch from home app, How can i achieve this?
My scenario:
From Launcher----->(App)Login page--->(App)Home screen
From Home app----->(App)Home screen

A: You can do that by launching an empty activity (with no UI) and in its OnCreate method depending on some variable information (You can use SharedPreferences perhaps for that purpose) you can decide which Activity to start (Login or Home Screen app).
PS:
Btw if the login always leads to the same activity (Home Screen and is not used to login somewhere else) you don't even need the empty activity, you can check this in the Oncreate method of the login activity
protected void onCreate(Bundle savedInstanceState)
  {
    super.onCreate(savedInstanceState);

    if (logged_in_check_is_true)
       {
          Intent intent = new Intent(this, HomeScreenActivity.class);
          this.startActivity (intent);
          this.finishActivity (0);
       }

    ...

A: You should always start LoginPageActivity. But if you start it from  your "home app" just pass special extra to activtiy:
public class LoginPageActivity extends Activity {
    onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        boolean needLogin = getIntent().getBooleanExtra("need login extra", true);
        if (!needLogin)
        {
            // start your home screen
        }
        //setup login page
    }
}

In home app just pass "need login extra" as false.

A: Basically similar to what tozka said yet you can also launch the activity you expect to be more often required and onCreate you check if you are in the right activity. If not call startActivity with the other activity without inflating any views etc before. So if your expectation is right then in more than 50% of the cases you are already in the right activity saving your app from two activities being called when it is launched


text:
Q: How to use DaydreamApi in Android Studio? All.
I develop my Daydream app in Android Studio.
I need to get permission(READ & WRITE). so I used permission request dialog.
but Daydream didn't recommend my way so  I want to below flowchart.
Current My Code
Start app -> Permission Check(2D Activity onCreate) -> Permission Popup
-> VR Main start(VR onCreate)
I want to this flowchart
Start app -> VR Main start(VR onCreate) -> Permission Check
-> move 2D Activity & Permission Popup(2D oncreate) -> VR Main (VR onResume)

I found this method(exitFromVr). but I don't know how am i write code.
If you have example code, Please let me know.
My English is not good so I need to your kind help.
Thank you.

A: The basic idea is to launch another Activity that will request the permission for you, then return to the main VR activity.
So from your main activity (in VR), show your transition dialog and call exitFromVr(myPermissionActivity, MY_REQUEST_CODE, MyData).
Removing your phone from the headset will cause the OS to trigger an intent for 'myPermissionActivity' (this activity should be setup with the needed permissions).
Then exit the permission activity, which will fallback to the main VR activity. In code I have seen the permission was activity setup with a close button, which just exits the activity.


text:
Q: TypeORM not using Entity metadata correctly I'm using Typescript + TypeORM on my project. Here's an entity definition:
@Entity({ name: 'city-listing' })
export class CityListing {
  @PrimaryColumn({ type: 'uuid', unique: true, generated: true })
  @Generated('uuid')
  id: string

  @Column('varchar')
  title: string

Whenever I instantiate a repo it looks like this:
const conn = await getConnection()
const repo = await conn.getRepository(CityListing)
const queryResult = await repo.findOne({ id: 'whatever_here' })

The repository defaults to the classname instead of the metadata. SQL Output ends up looking like this:
 'SELECT "CityListing"."id" AS "CityListing_id"...'

instead of
 'SELECT "city-listing"."id" AS "CityListing_id"...'

Any idea why? I'm using "reflect-metadata" as the first import on my app entry point, and migrations output the correct sql output when run from the CLI


text:
Q: MVC, AngularJS, Sortable, keep sort by latest created node I have a solution where I can create a node in a list of nodes. These nodes are then saved in my database. If I create three nodes in same session and then update the site it randomly sort the nodes. Is it possible to make it sort by the latest created node so when I update the page the first created node is in the top and the last created is in the buttom?
I pull every call to the database through angular. This is my js file:
(function () {
var domainName = 'Match';

angular.module('FightCardModule').controller("FightCardController",
    ['$scope', '$modal', '$http', '$routeParams', 'guidGenerator', 'eventBus', domainName + "Service", 'MatchModelFactory',
    function ($scope, $modal, $http, $routeParams, guidGenerator, eventBus, domainService, modelFactory) {

        $scope.eventId = $routeParams.eventId;
        $scope.id = $routeParams.id;

        $scope.refreshList = function (eventId) {
            var serviceUrl = "/api/Match" + (eventId ? "/" + eventId : "");

            $http({
                method: 'GET',
                url: serviceUrl
            }).success(function (data, status, headers, config) {
                $scope.itemsList.nodes = buildHierarchy(data);
            }).error(function (data, status, headers, config) {

            });
        }

        $scope.itemsList = {
            nodes: [],
        };

        $scope.sortableOptions = {
            containment: '#sortable-container',
            accept: function (sourceItemHandleScope, destSortableScope) {
                return sourceItemHandleScope.itemScope.sortableScope.$id === destSortableScope.$id;
            }
        };

        $scope.addNote = function (data) {
            newNode = createNewNode();
            newNode.EventId = $scope.eventId;
            $scope.itemsList.nodes.push(newNode);

            var serviceUrl = "/api/" + "Match";

            var cleanModel = {};
            cleanModel.Id = newNode.Id;
            cleanModel.EventId = newNode.EventId;
            cleanModel.ParentMatchId = newNode.ParentMatchId;
            cleanModel.Player1= newNode.Player1;

            $http({
                method: 'POST',
                url: serviceUrl,
                data: cleanModel
            }).success(function (data, status, headers, config) {
            });
        }

        $scope.alertDelete = function (data) {
            $modal.open({
                templateUrl: 'openAlertBox.html',
                scope: $scope,
                controller: function ($scope) {
                    $scope.ok = function () {

                        var indexToRemove;
                        var Nodes;

                        Nodes = $scope.itemsList.nodes;

                        for (var i = 0; i < Nodes.length; i++) {
                            if (Nodes[i].Id == data.Id) {
                                indexToRemove = i;
                                break;
                            }
                        }
                        Nodes.splice(indexToRemove, 1);
                        eventBus.publish(domainName + ".delete.submit", { model: data });
                        $scope.$dismiss();

                    }
                    $scope.cancel = function () {
                        $scope.$dismiss()
                    }
                }
            })
        }

        function createNewNode(parentNode) {
            var newNodeModel = new modelFactory.DomainModelConstructor();
            if (parentNode) {
                newNodeModel.ParentMatchId = parentNode.Id;
                newNodeModel.EventId = parentNode.EventId;
            }

            var newNode = convertModelToViewModel(newNodeModel);
            newNode.parent = parentNode;
            return newNode;
        }

        function convertModelToViewModel(nodeModel) {
            nodeModel.nodes = [];
            return nodeModel;
        }

        function buildHierarchy(matches) {

            var roots = [], children = {};
            for (var i = 0, len = matches.length; i < len; ++i) {
                var item = convertModelToViewModel(matches[i]);
                if (item.EventId == $scope.eventId){
                roots.push(item);
            }
            }

            return roots;
        }

        $scope.editMatchUsingModal = function (data) {
            $modal.open({
                templateUrl: 'openMatchBox.html',
                scope: $scope,
                controller: function ($scope) {
                    $scope.player1= data.Player1;
                    $scope.ok = function (player1) {
                        $scope.edit(data, player1);

                        $scope.$dismiss();
                    }
                    $scope.cancel = function () {
                        $scope.$dismiss();
                    }
                }
            })
        }

        $scope.edit = function (data, player1) {
            var newNode = {};
            newNode.Player1= player1;

            data.Player1= player1;

            eventBus.publish(domainName + ".edit.submit", { model: newNode });

        };

        $scope.refreshList($scope.eventId);
        $scope.refreshList($scope.id);

    }]);

})();

A: Please take a look at the following link and see how you can sort your list with orderBy.
BTW
you don't have to update your page.. Try to use $watch


text:
Q: String format a double to a maximum number of character in java As stated in the title, I would like to write a double in a string with a maximum number of character, in java.
Well actually to an exact number of character, but I can wrap it in a String.format("%Xs", ...) with given X to fill missing character.
Note that there are many questions related to this on SO and internet, but I couldn't find the exact same as mine for java.
What I think of would be to write

*

*the full double if it fits: for max character n=10, 123.4567 is good

*round decimal and keep the integer part if it fits: for n=10, 123456.789654 would format to 123456.79

*use exponential otherwise: for n=10, 123456789123.321654 would format to 1.23457e11

=> Is there a practical tool to do that or something equivalent?

A: That is what I have for now, not perfect but I spend enough time on it already.
The idea is that Double.toString is doing exactly what I want but for a fixed length (maybe someone knows how to configure that length?). So I use it and remove decimal when necessary
/** write a double to a string of exact given length (but for some extreme cases) */
public static String doubleToString(double x, int length) {
    String str = Double.toString(x);
    if(str.length() <= length){
        return org.apache.commons.lang.StringUtils.repeat(" ", length - str.length()) + str;

    } else if(str.contains("E")){
        String[] split = str.split("E");
        String num = split[0];
        String exp = split[1];
        return removeDecimal(num, length - exp.length()-1) + 'E' + exp;
    } else {
        return removeDecimal(str, length);
    }
}

// remove trailing decimal of a double as string such as xxx.yyyy
private static String removeDecimal(String doubleStr, int length){
    int dotIndex = doubleStr.indexOf('.');
    return doubleStr.substring(0, Math.max(dotIndex+1, length));
}

A: Take a look at BigDecimal (https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/math/BigDecimal.html) I use new DecimalFormat("0.00") if I want to ensure that the two decimal places are always shown, e.g. 1000.5 will display as 1000.50.


text:
Q: Why do all Feynman diagrams with same number of external legs have the same mass dimension? In the Ch.18, book of QFT by Mark Srednicki (p.118), it says the diagram have the same mass dimension with tree diagram with the same external lines, because both of them contribute to the same scattering amplitude. But I am confused of the reason of this argument.

A: This statement is correct.
What is a Feynman diagram? The most naive way to look into it is to say that it's a diagram that dictates all possible ways how a set of initial particles can transform into a set of final particles. The intermediate steps(the loops and internal lines) basically show one of the plausible ways allowed by the theory(these steps may not be possible on-shell, nevertheless are allowed off-shell).
S matrix is the probability amplitude for the whole process taking into consideration all quantum corrections. Therefore classically disallowed intermediate steps are also taken into account. But ultimately all the S-Matrix cares about at the end of the day is the initial and final particles. All the Feynman diagrams(i.e. all possible paths for the process) therefore must be added to get the answer. Since you can only add things that have same dimension, all these diagrams must have same mass dimension. And the dimension for each of these is just sum of dimension of the external states(initial+final).

A: One argument goes as follows:

*

*Recall that the path-integral/partition function $Z[J]$ is the generator of all Feynman diagrams in the source picture. Similarly $W_c[J]$ is the generator of all connected Feynman diagrams in the source picture. All the Feynman diagrams in $Z[J]$ and $W_c[J]$ have mass-dimension zero.
Now we want to find the mass-dimension of an amputated Feynman diagram $D$ with $E_f$ external lines with a field $\phi_f$ of type $f$.
Hence we just have to strip the corresponding dimensionless Feynman diagram $D[J]$ in the source picture of

*

*$E_f$ sources $\tilde{J}_f$ in Fourier momentum space;

*$E_f$ free propagators $\widetilde{G}_{0f}$ in Fourier momentum space for the external legs of type $f$;

*$E_f$ $d$-dimensional momentum integrations;

*an overall $d$-dimensional Dirac delta function imposing total momentum conservation.

This leads to Srednicki's claim that the mass-dimension $[D]$ of the amputated Feynman diagram $D$ only depends on the number of external legs.
In fact, it is not difficult to compute that the mass-dimension of the amputated Feynman diagram $D$ is$^1$
$$\begin{align}[D]~=~&d - \sum_f E_f\left(\underbrace{[\tilde{J}_f]}_{=-[\phi_f]}+\underbrace{[\widetilde{G}_{0f}]+d}_{=[G_{0f}]=2[\phi_f]}\right)\cr
~=~&d-\sum_f E_f[\phi_f].\end{align}$$

*If the amputated Feynman diagram $D$ is 1-particle-irreducible (1PI), there is an even simpler argument: Just functionally differentiate the dimensionless effective action $\Gamma[\phi_{\rm cl}]$ (which is the generator of amputated 1PI diagrams) with the appropriate number of Fourier-transformed fields $\tilde{\phi}_f$ and remove a Dirac delta function imposing total momentum conservation.
--
$^1$ It is implicitly assumed that the coefficients in front of the kinetic terms in the action are dimensionless.


text:
Q: post the rowdata of table using jqueryajax in Django views This is my view
    def endpointdetails(request):
          return HttpResponse("Finally I have redirected.MY values are here)

This is my template
Html:
    <TITLE> Add/Remove dynamic rows in HTML table </TITLE>

<input type="button" value="Add Row" onclick="addRow('dataTable')" />	<input type="button" value="Delete Row" onclick="removeRow()" />

    <form id = "Endpoint" name="myForm" action = '/endpointdetails/' method = "POST">{% csrf_token %}

   <input type="checkbox" name="chk" class="check" >

  <input type='text' class = 'productname' style='display:none;width:150px;'                                      value="Product Name">
  	<input type='text' class = 'endpoint' style='display:none;width:150px;' value="EndPoint Name">
    <input type='text' class = 'ipaddress'  style='display:none;width:150px;' value="IP Address">
    <input type='text' class = 'server' style='display:none;width:150px;' value="ServerName">
     <input type='text' class = 'Hmsg' style='display:none;width:150px;' value="Actual High Message">
     <input type='text' class = 'lmsg' style='display:none;width:150px;' value="Actual Low Message">

    <input type='button' id='edit' value='Edit' onclick='editRow(this);'><input type='button'   id='update' value='Update' onclick='updateRow(this);' style='display:none;'>

        </form>

CSS:

Script:

I have tried the above code and could not redirect to the views.
I have read the document of Django about CSRF but could not understand how to use it.
Can anyone please explain about what is wrong

A: If its CSRF issue... then add one more parameter csrfmiddlewaretoken in your post data like below and your code will be fine.
$.post("/endpointdetails/",
          {'Hmsg':Hmsg, 'lmsg':lmsg, 'csrfmiddlewaretoken':$("input[name='csrfmiddlewaretoken']").val()} ,function(received){
             alert(received); });


text:
Q: Yii check if logged into Facebook every page SOLVED POSTED THE CODE AT THE BOTTOM
I finally got this working, but to be honest i guess i'm doing this totaly wrong.
What i want:
I want to get an check on my site if an user is logged into the site via Facebook. This must be done one every page, cause certain parts of the site need to only be accesable if you are logged in. Also i would like to put the data of Facebook into my Database.
What i got:
At the moment I am able to check on every page if the user has logged via Facebook into my website. I did get this working by altering the init() function in the SiteController.php.
This function now looks like this:
public function init() {
    global $facebookID; // Create global Facebook ID
    global $loginURL;   // Create global URL for login

    $currentURL =  'http://dev03.***.nl/app/facebook-popup.php'; // facebook popup url

    //Get Facebook ID if FacebookID isn't there the result is 0
    $facebookID = Yii::app()->facebook->getUser();

    if(!$facebookID){
        //If there isn't an Facebook ID
        $loginURL = Yii::app()->facebook->getLoginUrl(array(
            'scope' => 'read_insights, publish_actions, manage_pages',
            'display' => 'popup',
            'next' => $currentURL . '?loginsucc=1',
            'cancel_url' => $currentURL . '?cancel=1'
        ));
    }
}

The problem:
The biggest problem is that my site load time expanded, but i don't know how to get this working in an other way. I'm guessing I would be able to put this test into an more load time friendly way.
My question:
How would i be able to decrease the load time, and program this the correct way. Am i able to make this as an function so that if i switch to certain pages there would be an check if the user is logged in via Facebook and show certain pages on the result.
My second question:
At the moment I check in my views/layouts/main.php if the global facebookID is empty or not to show the Facebook profile picture or an login button the following way:
<?php if ($GLOBALS['facebookID']) { ?>
    <img src="https://graph.facebook.com/<?php echo $GLOBALS['facebookID'] ?>/picture"/>
<?php } else{ ?>

        <img src="<?php echo Yii::app()->theme->baseUrl?>/images/buttons/facebook.png" alt="Facebook logo">

login met Facebook

<?php } ?>

If i got an function which checks this for me I guess the load time would also decrease, or is this the only way to put if statements in layouts?
I know this is an big question, but i'm kinda new to Yii and I hope some of you guys would take the time to help me with this.
SOLUTION
With a big thanks to @DarkMukke i was able to solve this question. I changed some things around and maybe did some things that aren't the perfect way. But it works fine for me now.
To start with, i changed my whole thinking about the user authentication, and i removed the globals. At this moment the only first check the webapp does is if we got an facebookID and an user. This is to prevent access when the user deletes the rights in Facebook but is still logged in to the app and got the user status. This is done with the following code:
protected/components/Controller.php
public function init() {
    $facebookID = Yii::app()->facebook->getUser();

    if(!$facebookID && Yii::app()->user->getState('role') == 'user'){
        Yii::app()->user->setState('role', 'guest');
    }
}

So in $facebookID we store the facebookID of the user, if the user has revoked acces then $facebookID is empty. So we check if the user got the role 'user' and if the Facebook id is empty. If so the users needs to get the role 'guest'.
Then the login issue, Instead of using the main Controller for this i decided to make an new controller. I placed this in protected/controllers/FacebookController.php and it looks like this:
class FacebookController extends Controller {

    public function actionLogin() {
        $facebookID = Yii::app()->facebook->getUser();
        $accessToken = Yii::app()->facebook->getAccessToken();
        $loginUrl = Yii::app()->facebook->getLoginUrl(array('scope' => 'read_insights, publish_actions, manage_pages, email', 'display' => 'popup', 'redirect_uri' => 'http://dev03.****.nl/app/facebook-popup.php'));

        if($facebookID == 0) {
            echo '';

        } else {
            $record = Users::model()->findByAttributes(array('FB_id'=>$facebookID));
            if($record===null) {
                $userInfo = Yii::app()->facebook->api('/me');

                $user = new Users;
                $user->firstname = $userInfo['first_name'];
                $user->surname = $userInfo['last_name'];
                $user->city = $userInfo['location']['name'];
                $user->email = $userInfo['email'];
                $user->FB_id = $userInfo['id'];
                $user->save();
            }

            Yii::app()->user->setState('role', 'user');
            Yii::app()->user->setState('FBid', $facebookID);

            echo "";
        }
    }
}

Please note, i am calling this function in an popup via Javascript
So what this does is:
First, get Facebook id, get access token and login url.
Then we check if we got an Facebook id, if not change the location of the popup to the login url for Facebook. This opens the dialog to get access and the permissions described in 'scope' in the getLoginUrl() function.
If we have the permissions it checks if we got the user in the database. if not $record is null. Then we get the info of the user with api('/me') and post this in the database. If this is done we go on.
Then we set the role of the user to user and add an state called FBid with the Facebook id to use this later in the application.
When this all is done we close the window. And the user is logged in.

A: Obviously, you have some ideas on what you are doing. so let me point out some tips.
First of all, if you are overriding the init in your SiteController, you will have to do it in every new controller, so you better overwrite init() in Controller, the class in /protected/components, that every controller is extending from by default, that way it really will be on EVERY page.
Second note, globals are a bad idea. They might seem usefull, but they are a pain to debug. In my opinion, globals should be removed from the next version of PHP.
So the correct way here would be to use CWebuser->setState(), this way you can just check if the user is logged in or not. This gives you another usefull advantage. On first FB login you create a user with his data in your own users table, and for the UserIdentity you just use the FB check, and load the record where the FBid == your record with that FBid set.
So in short,

*

*when people authorize, create a record for them in your users table

*use the native user check, to check if logged in with the native cookie

*if not logged in compare FacebookId against your own records

*if no records, try to authorize them with Facebook popup

*to have the Facebook data everywhere, use CWebuser->setState(), in your UserIdentity, dont use globals


text:
Q: ASP.NET Dynamic Data automatically populating a Drop Down list based on Metadata I am using ASP.NET Dynamic Data and one thing I would like to do is to have a meta class, for example:
    public class CopyTermsHolidaysMetadata
    {
        [Required]
        public int SchoolID { get; set; }

        [Required]
        [UIHint("AcademicYear")]
        public int AcademicYear { get; set; }

        [DisplayName("Recipient School")]
        [Required]
        public int DestinationSchoolID { get; set; }
    }

Now, the two field SchoolID and DestinationSchoolID are drop down lists which come from the "School" table.
Is there any attribute which I can use to automatically populate these as the drop down lists that they are?

A: You should use FilterUIHintAttribute class that allows to replace (or add new filters) default filters on the CopyTermsHolidays entity.
For example:
[Required]
[UIHint("AcademicYear")]
[FilterUIHint("AcademicYearFilter")]
public int AcademicYear { get; set; }

where AcademicYearFilter is custom filter which need to be located in ~\DynamicData\Filters directory (AcademicYearFilter.ascx).
More information at FilterUIHintAttribute Class.
I will take courage to attach to my answer filter template lookup algorithm and some
citation from ASP.NET Dynamic Data UNLEASHED:

Compared to the lookup rules for field templates, lookup rules for
  filter templates are simple. Dynamic Data uses only the FilterUIHint
  associated with the column and has an intrinsic knowledge of several
  column types. If the FilterUIHint is not specified in the data model,
  and the column is Foreign Key (a column that represents the parent
  navigation property of a many-to-one or a one-to-one association in
  the child entity), a Boolean, or an enumeration, Dynamic Data chooses
  a predefined FilterUIHint value, ForeignKey, Boolean, or Enumeration,
  respectively. Having the FilterUIHint value, Dynamic Data tries to
  locate a user control with the matching name in the
  DynamicData\Filters directory of the web application project. If the
  user control does not exist, the lookup process ends, and filtering is
  considered to be unsupported for this column.


text:
Q: How to switch between UI implementations in run-time? I'm developing an application using GWT 2.6.
Now I have a task to implement a functionality to switch between simple/expert modes (of view) at run-time. It means to show a simplified version of view which may contain another widgets.
But the problem is that all the views in most cases are "static" and defined as singletons (using GIN).
Is it possible to implement this using only GWT and what should I use to make it?.

A: There are many ways that this can be done. A couple of ideas that spring to mind:
Option 1.
Instead of using GIN to inject the view, inject a view provider (com.google.inject.Provider). This can be used by the code that builds the view (the activity?) to get the view. The implementation of the view provider can then return an implementation of the view for the relevant mode, simple or expert. For example,
@Inject
public ComposeMessageActivity(Provider<ComposeMessageView> viewProvider, ...) { ... }

@Override
public final void start(final AcceptsOneWidget panel, final EventBus eventBus) {
    view = viewProvider.get();

Option 2.
Use deferred binding. This is not so dynamic but has the advantage a simple implementation will be a smaller download than an expert implementation. There is a project, gwt-seminar, on github that shows this in practice that has mobile and desktop versions.


text:
Q: Tomcat 8.5.31 no puede abrir su propio log Tengo un proyecto en Java y le cambie el contenedor de Servlet Glassfish por Tomcat.
El problema es que no funciona Tomcat, tira el siguiente error:

Starting Tomcat process... Waiting for Tomcat... Starting of Tomcat
  failed.
  /home/educacion/NetBeansProjects/hotelre/nbproject/build-impl.xml:1045:
  Deployment error: Starting of Tomcat failed. See the server log for
  details. BUILD FAILED (total time: 4 seconds)

En otra ventana de log llamada Apache Tomcat or TomEE tira estos errores:

java.io.FileNotFoundException:
  /home/educacion/Descargas/apache-tomcat-8.5.31/logs/catalina.2018-05-09.log
  (Permiso denegado)

Hay un problema en el archivo build-impl.xml que no se como solucionarlo:
<nbdeploy clientUrlPart="${client.urlPart}" debugmode="false" forceRedeploy="${forceRedeploy}"/>

Trate de darle los permisos pero cuando voy a la carpeta no encuentro ningun archivo. La carpeta esta vacia.
Gracias.

A: Trata de darle permisos a la carpeta del tomcat para tu usuario, regularmente la ruta es:
"C:\Program Files\Apache Software Foundation\Tomcat (Tu Version)"


text:
Q: Step by step solution to these derivations I will write test tomorow and I'm stuck at few derivation examples. Unfortunatelly, teacher don't gave me a solution to these examples. I have no problem with simpler derivations.
Calculate first derivation of following functions and specify the domain of derivation:
$f_1(x)=(\arctan\frac{3x}{2x^2-8})^2+\frac{7}{9}$
$f_2(x)=6^{x^{3}}\sqrt[8]{x-x^2}+\arcsin\frac{2x-2}{4}$
$f_3(x)=\cot(4x)+\log_7(2x)$
$f_4(x)=\frac{2x\cos(3x)}{e^{-2x}}+x^{x^{2}}$
I think I just have problem with precedence of operations. I will be very grateful if someone post me straightforward and step by step solution to these examples.
Thank you very much.

A: HINT: you Need the power and the chain rule
$$2\,{1\arctan \left( 3\,{\frac {x}{2\,{x}^{2}-8}} \right)  \left( 3\,
 \left( 2\,{x}^{2}-8 \right) ^{-1}-12\,{\frac {{x}^{2}}{ \left( 2\,{x}
^{2}-8 \right) ^{2}}} \right)  \left( 9\,{\frac {{x}^{2}}{ \left( 2\,{
x}^{2}-8 \right) ^{2}}}+1 \right) ^{-1}}
$$
the first derivative of $$\frac{3x}{2x^2-8}$$ is given by $$3\, \left( 2\,{x}^{2}-8 \right) ^{-1}-12\,{\frac {{x}^{2}}{ \left( 2\,
{x}^{2}-8 \right) ^{2}}}
$$ and the derivative of $$arctan\left(\frac{3x}{2x^2-8}\right)$$ as
$${1 \left( 3\, \left( 2\,{x}^{2}-8 \right) ^{-1}-12\,{\frac {{x}^{2}}{
 \left( 2\,{x}^{2}-8 \right) ^{2}}} \right)  \left( 9\,{\frac {{x}^{2}
}{ \left( 2\,{x}^{2}-8 \right) ^{2}}}+1 \right) ^{-1}}
$$
and the derivative with the power $2$ is given by $$2\,{1\arctan \left( 3\,{\frac {x}{2\,{x}^{2}-8}} \right)  \left( 3\,
 \left( 2\,{x}^{2}-8 \right) ^{-1}-12\,{\frac {{x}^{2}}{ \left( 2\,{x}
^{2}-8 \right) ^{2}}} \right)  \left( 9\,{\frac {{x}^{2}}{ \left( 2\,{
x}^{2}-8 \right) ^{2}}}+1 \right) ^{-1}}
$$
for 2) we need the product, chain and the power rule
$$3\,{6}^{{x}^{3}}{x}^{2}\ln  \left( 6 \right) \sqrt [8]{-{x}^{2}+x}+1/8
\,{{6}^{{x}^{3}} \left( -2\,x+1 \right)  \left( -{x}^{2}+x \right) ^{-
{\frac {7}{8}}}}+{\frac {1}{\sqrt {-{x}^{2}+2\,x+3}}}
$$
for 3) we have $$-4-4\, \left( \cot \left( 4\,x \right)  \right) ^{2}+{\frac {1}{x\ln
 \left( 7 \right) }}
$$
and for the last one we get $$2\,{\frac {\cos \left( 3\,x \right) }{{{\rm e}^{-2\,x}}}}-6\,{\frac {x
\sin \left( 3\,x \right) }{{{\rm e}^{-2\,x}}}}+4\,{\frac {x\cos
 \left( 3\,x \right) }{{{\rm e}^{-2\,x}}}}+{x}^{{x}^{2}} \left( 2\,x
\ln  \left( x \right) +x \right)
$$


text:
Q: Login form does not render at the correct position I want my login form to be like Facebook's, but it's rendered too down, nearly going off the header. I want it in the middle like what Facebook has.
 <!DOCTYPE html>

<link rel="stylesheet" href="stylesheet/5uV6fe9qPff.css" type="text/css">

Morefun logo

<form id="" action="" method="post" onsubmit="">
<input type="hidden" name="lsd" value="AVrMo5Pe" autocomplete="off">

Email or Phone
Password

<input type="text" class="inputtext" name="email" id="email" value="" tabindex="1" placeholder="Email or Phone">
<input type="password" class="inputtext" name="pass" id="pass" tabindex="2" placeholder="Password">
<input value="Log in" tabindex="4" type="submit" id="u_0_4">

<input id="persist_box" type="checkbox" name="persistent" value="1" tabindex="3" class="uiInputLabelCheckbox">
Keep me logged in

<input type="hidden" name="default_persistent" value="0">

<input type="hidden" autocomplete="off" name="timezone" value="0" id="u_0_3">
<input type="hidden" name="lgnrnd" value="110619_A5vh">
<input type="hidden" id="lgnjs" name="lgnjs" value="1364148375"><input type="hidden" autocomplete="off" id="locale" name="locale" value="en_GB">
</form>

here is the css code
    body {
background: url("http://www.sayhellothere.com/images/bg-wrapper.jpg");
color: #c4d6e4;
line-height: 1;
margin: 0;
padding: 0;
text-align: left;
direction: ltr;
unicode-bidi: embed;
}
.loggedout_menubar_container {
background-color: rgba(0,0,0,0.1);
border: 1px solid #556166;
-webkit-box-shadow: 0,0,2px,0,#000;
box-shadow: 0,0,2px,0,#000;
background: url("http://www.sayhellothere.com/images/bg-home.jpg") repeat-x;
height: 82px;
min-width: 980px;
}
.loggedout_menubar {
margin: 0 auto;
padding-top: 13px;
width: 980px;
}
.lfloat {
float: left;
}
a {
color: #3b5998;
cursor: pointer;
text-decoration: none;
}
.loggedout_menubar .morefub_logo {
margin-top: 17px;
}
.sx_df432d {
width: 170px;
height: 36px;
background-position: 0 0;
}
.sp_6jxgq1 {
background-image:url('images/logo.png');
background-size: auto;
background-repeat: no-repeat;
display: inline-block;
height: 9px;
width: 9px;
}
i.img u {
position: absolute;
top: -9999999px;
}
.rfloat {
float: right;
}
form {
margin: 0;
padding: 0;
}
table {
word-wrap: normal;
}
.menu_login_container table tr td {
padding: 0 0 0 14px;
}
td, td.label {
text-align: left;
}
.menu_login_container .html7magic label {
color: #9fafb8;
font-size: 14px;
display: block;
margin: 0 0 6px;
font-weight: bold;
text-shadow: 0px -1px #000;
padding-left: 1px;
}
.menu_login_container .inputtext, .menu_login_container .inputpassword {
width: 138px;
padding: 7px 5px;
background: url("http://www.sayhellothere.com/images/bg-login.png") no-repeat 0 -95px;
overflow: hidden;
margin: 0;
}
.inputtext, .inputpassword {
float: left;
margin: 0;
padding: 0;
width: 138px;
border: 0;
background: none;
color: #fff;
font-size: 14px;
line-height: 17px;
outline: none!important;
}
.uiButtonText, .uiButton input {
float:right;
padding:1px 0 2px;
margin:0;
width:71px;
height:30px;
cursor: pointer;
font-size: 14px;
-webkit-border-radius: 4px;
border-radius: 4px;
background-color: #eaeaea;
background-image: -webkit-linear-gradient(top,#eaeaea,#a8a8a8);
display: inline-block;
font-family: helvetica,arial,sans-serif;
font-weight: bold;
color: #515151;
border: 1px solid #333;
text-shadow: 0 1px 0 rgba(255,255,255,0.5);
}
.uiInputLabel label {
display: inline;
font-size: 12px;
font-weight: normal;
vertical-align: -1px;
color: #9fafb8;
margin: 0 0 6px;
text-shadow: 0px -1px #000;
}

A: If I can understand what you are asking for, is how to make the bar that has the login form larger?
You need to update the height parameter in the .loggedout_menubar_container CSS declaration to being larger, so that the form fits in better.


text:
Q: jpa Hibernate @ElementCollection I have a question which bothers me a bit.
When i use @ElementCollection in my entity hibernate (3.5) generates me a table without any constraints.
Important Edit
My Entity is a subclass of another class. That is maybe the reason why hibernate does not generate the pk and the fk.
Edit End
public MyEntity extends BaseEntity
@ElementCollection(fetch=FetchType.EAGER)
private Set<String> test;

Ends up with (postgres 9):
CREATE TABLE myentity_test
(
  entityid bigint NOT NULL,
  test character varying(255)
)

Is this my mistake that hibernate doesn't set any constraints like foreign keys or unique indexes?
I could set it manually, but i would prefer to annotate the entity correctly that hibernate completely (as much as possible) creates my database.
Best regards,
m
PS: My Bad at all. Mixed up two things which where going around in my mind. i meant @ElementCollection.
PS: The @Column helped to deliver the unique index. Edit: corrected the names to my example.
CREATE TABLE myentity_test
(
  entityid bigint NOT NULL,
  test character varying(255),
  CONSTRAINT itemequipable_test_test_key UNIQUE (test)
)

I would expect something like this (pseudo code):
CREATE TABLE myentity_test
(
  entityid bigint NOT NULL PRIMARY KEY,
  test character varying(255) PRIMARY KEY,
  CONSTRAINT fk_entityid references (myentity) on entityid
)

A: @Column and @JoinColum/@OneToMany annotations are the correct way to handle the foreign keys and unique constraints, even with the @ElementCollection.
In your particular example, there is not going to be a foreign key relationship because String (the type of your Set) is not mapped to another entity.


text:
Q: Does the speed in which a gas through a medium matter? There are two thrusters. They both expel the same volume of gas. The difference is, one has a fine stream of propellant at a higher velocity, and the other a wider stream at a lower velocity. Would both provide the same amount of thrust in Earth's atmosphere? or space?

A: From Newton's second law, the rocket thrust force $$\tag 1F =\frac{\Delta p}{\Delta t} = \dot m v_e+m\dot v_e=\dot m v_e$$ where we assume a constant gas exit velocity or $\dot v_e=0$  and $$\tag 2\dot m=\frac{\Delta m}{\Delta t}=\rho v_e A$$ is the mass flow rate, $p$ is the momentum of the expelled gas, $\rho$ is the density of the expelled gas, $A$ is the gas exit area and $v_e$ is the exit velocity of the gas.
This means that $$F=\rho A v_e^2\tag3$$
We see that if you decrease the gas exit velocity and increase the exit area, and then if you increase the gas exit velocity and decrease the exit area, the gas exit flow rate in equation (2) will be equal in both cases, but the amount of thrust$^1$ given by equation (3) will in general not be the same due to the non-linear dependence of the exit velocity $v_e$
This thrust is independent on the pressure outside of the rocket, so ideally it will not depend all too much on whether or not the thrust is measured in the atmosphere or in space.
$^1$Note that this assumes ideal conditions, and that in each case, the density of the exiting gas stays the same. In real situations though, since parameters like temperature and pressure will vary in each case, the mass flow rates will not usually be the same.
Also note that propulsive efficiency varies slightly with different altitudes due to changing atmospheric pressure. One could conclude from this that the thrust will be slightly different in the atmosphere than in space.


text:
Q: Auto-reload and Search - php page I'm trying add auto-reload a page where I have div in form of a table with only rows that include username.
Using https://github.com/stidges/jquery-searchable to search for username inside div here's the website http://tntdroid.xyz/global.php
If I auto-reload the container the search stops working.
Does anyone know if there's a way to make this work. or an alternative
$(function worker(){
    $("#searchable-container").load('lib/global.php');
    setTimeout(worker, 10*1000);
});

$(function () {
    $( '#searchable-container' ).searchable({
        searchField: '#container-search',
        selector: '.list-group-item',
        childSelector: '.col-md-4',
        show: function( elem ) {
            elem.slideDown(100);
        },
        hide: function( elem ) {
            elem.slideUp( 100 );
        }
    })
});

A: After reloading the content, you need to re-create the searchable.
Do this by re-calling
$( '#searchable-container' ).searchable({
    ...
});

This is needed because the complete element - with all its listeners - gets erased and overwritten.