问:
How to check if an object in Python is a PyCapsule?
I have a C Extension that receives and accepts PyCapsule objects.

In my python wrapper, how can I check if a python object is of the PyCapsule type object?

```<code>>>> # My C extension
>>> foo = Foo()
>>> capsule = foo.to_capsule()  # returns a PyCapsule object from the C extension
>>> capsule
<capsule object "foo" at 0xf707df08>
>>> type(capsule)
<class 'PyCapsule'>
isinstance(capsule, PyCapsule)
NameError: name 'PyCapsule' is not defined
</code>```

What I'm trying to do is write a function like:

```<code>def push_capsule(capsule):
    # check that the `capsule` is of type PyCapsule
    # c_extension.push_capsule(capsule)
</code>```

答:
It's a bit of a mess but you can get it from ctypes:

```<code>def get_capsule_type():
    class PyTypeObject(ctypes.Structure):
        pass  # don't need to define the full structure
    capsuletype = PyTypeObject.in_dll(ctypes.pythonapi, "PyCapsule_Type")
    capsuletypepointer = ctypes.pointer(capsuletype)
    return ctypes.py_object.from_address(ctypes.addressof(capsulepointerpointer)).value
</code>```

Creating a py_object from an address looks to require an address which contains a PyObject*, rather than the PyObject* itself, hence the extra layer of indirection.

Body:
I have a C Extension that receives and accepts PyCapsule objects.

In my python wrapper, how can I check if a python object is of the PyCapsule type object?

>>> # My C extension
>>> foo = Foo()
>>> capsule = foo.to_capsule()  # returns a PyCapsule object from the C extension
>>> capsule
<capsule object "foo" at 0xf707df08>
>>> type(capsule)
<class 'PyCapsule'>
isinstance(capsule, PyCapsule)
NameError: name 'PyCapsule' is not defined

What I'm trying to do is write a function like:

def push_capsule(capsule):
    # check that the `capsule` is of type PyCapsule
    # c_extension.push_capsule(capsule)

Body:
It's a bit of a mess but you can get it from ctypes:

def get_capsule_type():
    class PyTypeObject(ctypes.Structure):
        pass  # don't need to define the full structure
    capsuletype = PyTypeObject.in_dll(ctypes.pythonapi, "PyCapsule_Type")
    capsuletypepointer = ctypes.pointer(capsuletype)
    return ctypes.py_object.from_address(ctypes.addressof(capsulepointerpointer)).value

Creating a py_object from an address looks to require an address which contains a PyObject*, rather than the PyObject* itself, hence the extra layer of indirection.


来源: stackexchange

问:
Room - SELECT doesn't return any data
Can't get where is my mistake - it seems data is inserted (I checked the database file through Device File Explorer) but it doesn't returns.
I wonder whether it's in Adapter or ViewHolder or anywhere else.
Any help is granted!

This the activity where I perform my queries

```<code>public class ShowDatabaseActivity extends AppCompatActivity {
    private List <Contact> contactsList = new ArrayList<>()

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_show_database);
        setupToolbar();
        initRecyclerView();
        Intent intent = getIntent();
        unpack(intent);
    }

    private void setupToolbar() {
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setDisplayShowHomeEnabled(true);
            toolbar.setNavigationOnClickListener(v -> onBackPressed());
        }
    }

    private void initRecyclerView() {
        RecyclerView recyclerView = findViewById(R.id.recycler_view);
        final ContactsListAdapter adapter = new ContactsListAdapter(contactsList);
        adapter.notifyDataSetChanged();
        recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        recyclerView.setAdapter(adapter);
    }

    private void unpack(Intent intent) {
        final Handler handler = new Handler();
        Thread backgroundThread = new Thread(() -> {
            Bundle extras = intent.getExtras();
            String lastName = extras.getString(Constants.LAST_NAME_KEY);
            String firstName = extras.getString(Constants.FIRST_NAME_KEY);
            String middleName = extras.getString(Constants.MIDDLE_NAME_KEY);
            int age = extras.getInt(Constants.AGE_KEY);
            Contact contact = new Contact(lastName, firstName, middleName, age);
            AppDatabase.getINSTANCE(ShowDatabaseActivity.this).contactDao().insert(contact);
            AppDatabase.getINSTANCE(ShowDatabaseActivity.this).contactDao().getAll();
            handler.post(() -> {

            });
        });
        backgroundThread.start();
    }
}
</code>```

If I debug this line shows data sucessfully -

```<code>(ShowDatabaseActivity.this).contactDao().insert(contact);
</code>```

My adapter

```<code>public class ContactsListAdapter extends RecyclerView.Adapter<ContactsListAdapter.ContactViewHolder> {
    private Context context;
    private List<Contact> contacts;

    public ContactsListAdapter(@NonNull List<Contact> contacts) {
        this.contacts = contacts;
    }

    @Override
    public ContactViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        final LayoutInflater inflater = LayoutInflater.from(context);
        View itemView = inflater.inflate(R.layout.recycler_view, parent, false);
        return new ContactViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(@NonNull ContactViewHolder holder, int position) {
            Contact currentContact = contacts.get(position);
            if (currentContact!=null) {
                holder.contactLastNameView.setText(currentContact.getLastName());
                holder.contactFirstNameView.setText(currentContact.getFirstName());
                holder.contactMiddleNameView.setText(currentContact.getMiddleName());
                holder.contactAgeView.setText(Integer.toString(currentContact.getAge()));
            }
            else {
                holder.contactLastNameView.setText("No information");
                holder.contactFirstNameView.setText("No information");
                holder.contactMiddleNameView.setText("No information");
                holder.contactAgeView.setText("No information");
            }
    }

    @Override
    public int getItemCount() {
        return contacts.size();
    }

    class ContactViewHolder extends RecyclerView.ViewHolder {
        private final TextView contactLastNameView;
        private final TextView contactFirstNameView;
        private final TextView contactMiddleNameView;
        private final TextView contactAgeView;

        private ContactViewHolder(View itemView) {
            super(itemView);
            contactLastNameView = itemView.findViewById(R.id.last_name_text_view);
            contactFirstNameView = itemView.findViewById(R.id.first_name_text_view);
            contactMiddleNameView = itemView.findViewById(R.id.middle_name_text_view);
            contactAgeView = itemView.findViewById(R.id.age_text_view);
        }
    }

    @Override
    public int getItemViewType(final int position) {
        return R.layout.recycler_view;
    }
}
</code>```

My DataBase

```<code>@Database(entities = {Contact.class}, version = 1, exportSchema = false)
public abstract class AppDatabase extends RoomDatabase {
    public abstract ContactDao contactDao();

    private List<Contact> allContacts;

    List<Contact> getAllContacts() {
        return allContacts;
    }

    private static AppDatabase INSTANCE;

    public synchronized static AppDatabase getINSTANCE(Context context) {
            INSTANCE = getDatabase(context);
        return INSTANCE;
    }

    private static AppDatabase getDatabase(final Context context) {
        if (INSTANCE == null) {
            synchronized (AppDatabase.class) {
                    INSTANCE = Room.databaseBuilder(context.getApplicationContext(),
                            AppDatabase.class, "table_contacts")
                            .build();
                Log.d("LOG", "Getting the database instance");
            }
        }
        return INSTANCE;
    }
}
</code>```

There is no doubt in my Entity and Dao classes as it worked perfectly with other variant of database so I don't attach them.
Will be very grateful for any help!

答:
Your code is incomplete

You are setting only empty Array inside your adapter, to rectify this make your Adapter's object global

Your handler.post have nothing inside it

you need to create a function inside you adapter like below

```<code>      public void addItem(List<Contacts> list) {

        mList.add(list)

 notifyItemInserted(mList.size - 1)

    }
</code>```

Now you need to call addItem inside your handler.post by using

adapter.addItem(contact)

This will add the content inside your adapter's list and notify the chnages also

ContentLicense: CC BY-SA 4.0

Title: Room - SELECT doesn't return any data

Body:
Can't get where is my mistake - it seems data is inserted (I checked the database file through Device File Explorer) but it doesn't returns.
I wonder whether it's in Adapter or ViewHolder or anywhere else.
Any help is granted!

This the activity where I perform my queries

public class ShowDatabaseActivity extends AppCompatActivity {
    private List <Contact> contactsList = new ArrayList<>()

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_show_database);
        setupToolbar();
        initRecyclerView();
        Intent intent = getIntent();
        unpack(intent);
    }

    private void setupToolbar() {
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setDisplayShowHomeEnabled(true);
            toolbar.setNavigationOnClickListener(v -> onBackPressed());
        }
    }

    private void initRecyclerView() {
        RecyclerView recyclerView = findViewById(R.id.recycler_view);
        final ContactsListAdapter adapter = new ContactsListAdapter(contactsList);
        adapter.notifyDataSetChanged();
        recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        recyclerView.setAdapter(adapter);
    }

    private void unpack(Intent intent) {
        final Handler handler = new Handler();
        Thread backgroundThread = new Thread(() -> {
            Bundle extras = intent.getExtras();
            String lastName = extras.getString(Constants.LAST_NAME_KEY);
            String firstName = extras.getString(Constants.FIRST_NAME_KEY);
            String middleName = extras.getString(Constants.MIDDLE_NAME_KEY);
            int age = extras.getInt(Constants.AGE_KEY);
            Contact contact = new Contact(lastName, firstName, middleName, age);
            AppDatabase.getINSTANCE(ShowDatabaseActivity.this).contactDao().insert(contact);
            AppDatabase.getINSTANCE(ShowDatabaseActivity.this).contactDao().getAll();
            handler.post(() -> {

            });
        });
        backgroundThread.start();
    }
}

If I debug this line shows data sucessfully -

(ShowDatabaseActivity.this).contactDao().insert(contact);

My adapter

public class ContactsListAdapter extends RecyclerView.Adapter<ContactsListAdapter.ContactViewHolder> {
    private Context context;
    private List<Contact> contacts;

    public ContactsListAdapter(@NonNull List<Contact> contacts) {
        this.contacts = contacts;
    }

    @Override
    public ContactViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        final LayoutInflater inflater = LayoutInflater.from(context);
        View itemView = inflater.inflate(R.layout.recycler_view, parent, false);
        return new ContactViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(@NonNull ContactViewHolder holder, int position) {
            Contact currentContact = contacts.get(position);
            if (currentContact!=null) {
                holder.contactLastNameView.setText(currentContact.getLastName());
                holder.contactFirstNameView.setText(currentContact.getFirstName());
                holder.contactMiddleNameView.setText(currentContact.getMiddleName());
                holder.contactAgeView.setText(Integer.toString(currentContact.getAge()));
            }
            else {
                holder.contactLastNameView.setText("No information");
                holder.contactFirstNameView.setText("No information");
                holder.contactMiddleNameView.setText("No information");
                holder.contactAgeView.setText("No information");
            }
    }

    @Override
    public int getItemCount() {
        return contacts.size();
    }

    class ContactViewHolder extends RecyclerView.ViewHolder {
        private final TextView contactLastNameView;
        private final TextView contactFirstNameView;
        private final TextView contactMiddleNameView;
        private final TextView contactAgeView;

        private ContactViewHolder(View itemView) {
            super(itemView);
            contactLastNameView = itemView.findViewById(R.id.last_name_text_view);
            contactFirstNameView = itemView.findViewById(R.id.first_name_text_view);
            contactMiddleNameView = itemView.findViewById(R.id.middle_name_text_view);
            contactAgeView = itemView.findViewById(R.id.age_text_view);
        }
    }

    @Override
    public int getItemViewType(final int position) {
        return R.layout.recycler_view;
    }
}

My DataBase

@Database(entities = {Contact.class}, version = 1, exportSchema = false)
public abstract class AppDatabase extends RoomDatabase {
    public abstract ContactDao contactDao();

    private List<Contact> allContacts;

    List<Contact> getAllContacts() {
        return allContacts;
    }

    private static AppDatabase INSTANCE;

    public synchronized static AppDatabase getINSTANCE(Context context) {
            INSTANCE = getDatabase(context);
        return INSTANCE;
    }

    private static AppDatabase getDatabase(final Context context) {
        if (INSTANCE == null) {
            synchronized (AppDatabase.class) {
                    INSTANCE = Room.databaseBuilder(context.getApplicationContext(),
                            AppDatabase.class, "table_contacts")
                            .build();
                Log.d("LOG", "Getting the database instance");
            }
        }
        return INSTANCE;
    }
}

There is no doubt in my Entity and Dao classes as it worked perfectly with other variant of database so I don't attach them.
Will be very grateful for any help!

Body:
Your code is incomplete

You are setting only empty Array inside your adapter, to rectify this make your Adapter's object global

Your handler.post have nothing inside it

you need to create a function inside you adapter like below

      public void addItem(List<Contacts> list) {

        mList.add(list)

 notifyItemInserted(mList.size - 1)

    }

Now you need to call addItem inside your handler.post by using

adapter.addItem(contact)

This will add the content inside your adapter's list and notify the chnages also


问:
Android Bitmap to Base64 String
How do I convert a large Bitmap (photo taken with the phone's camera) to a Base64 String?</p>

答:
Now that most people use Kotlin instead of Java, here is the code in Kotlin for converting a bitmap into a base64 string.</p>

```<code>import java.io.ByteArrayOutputStream

private fun encodeImage(bm: Bitmap): String? {
        val baos = ByteArrayOutputStream()
        bm.compress(Bitmap.CompressFormat.JPEG, 100, baos)
        val b = baos.toByteArray()
        return Base64.encodeToString(b, Base64.DEFAULT)
    }
</code>```

ContentLicense: CC BY-SA 3.0

Title: Android Bitmap to Base64 String

Body:
Now that most people use Kotlin instead of Java, here is the code in Kotlin for converting a bitmap into a base64 string.

import java.io.ByteArrayOutputStream

private fun encodeImage(bm: Bitmap): String? {
        val baos = ByteArrayOutputStream()
        bm.compress(Bitmap.CompressFormat.JPEG, 100, baos)
        val b = baos.toByteArray()
        return Base64.encodeToString(b, Base64.DEFAULT)
    }


问:
Open target="_blank" links outside of UIWebView in Safari
Inside my iOS Application I have an UIWebView.

Now I want all links that have the attribute target="_blank" not to open inside my WebView but externally in Safari.

How can I do this?

答:
Try this.</p>

```<code>UIApplication *app = [UIApplication sharedApplication];
NSURL         *url = navigationAction.request.URL;

if (!navigationAction.targetFrame) {
    if ([app canOpenURL:url]) {
        [app openURL:url];
        decisionHandler(WKNavigationActionPolicyCancel);
        return;
    }
}
if ([url.scheme isEqualToString:@"mailto"])
{
    if ([app canOpenURL:url])
    {
        [app openURL:url];
        decisionHandler(WKNavigationActionPolicyCancel);
        return;
    }
}

decisionHandler(WKNavigationActionPolicyAllow);
</code>```

Body:
Try this.

UIApplication *app = [UIApplication sharedApplication];
NSURL         *url = navigationAction.request.URL;

if (!navigationAction.targetFrame) {
    if ([app canOpenURL:url]) {
        [app openURL:url];
        decisionHandler(WKNavigationActionPolicyCancel);
        return;
    }
}
if ([url.scheme isEqualToString:@"mailto"])
{
    if ([app canOpenURL:url])
    {
        [app openURL:url];
        decisionHandler(WKNavigationActionPolicyCancel);
        return;
    }
}

decisionHandler(WKNavigationActionPolicyAllow);


问:
IN operator in SQL Statement Does not work?
In SQL Server, I have a table MyTable, with the following 3 columns, P(bigint), F(bigint), D(bigint).

Now what I need to do is to group all records by same P value, then in each group, calculate the following value:

```<code>V = ABS((P & 0xFFFFFFFF) * 256 - F)
</code>```

for each record, and delete all records in the group, except for the one with the minimum value of V.

So I write the SQL statement as follows:

```<code>DELETE FROM MyTable WHERE (P, ABS((P & 0xFFFFFFFF) * 256 - F)) NOT IN (SELECT P, MIN(ABS((P & 0xFFFFFFFF) * 256 - F)) FROM MyTable GROUP BY P HAVING COUNT(*) > 1)
</code>```

But in SQL Server, I will get the following error:

```<code>Msg 4145 SQL Server An expression of non-boolean type specified in a context where a condition is expected,near ','
</code>```

Why? Also whether bitwise and & works in SQL Server 2005? I only have SQL Server 2008 R2 and the online document at https://learn.microsoft.com/en-us/sql/t-sql/language-elements/bitwise-and-transact-sql?view=sql-server-ver15 does not indicate whether it support 2005 & 2008.

Update1

P, F, D are all bigint type.

Update2

With the helps of others, I finally write a query with NOT EXISTS, as follows:

Method 1: DELETE t FROM MyTable t WHERE NOT EXISTS (SELECT 1 FROM (SELECT P, MIN(ABS((P & 0xFFFFFFFF) * 256 - F)) as minpf
  FROM MyTable GROUP BY P) tt WHERE tt.P = t.P AND tt.minpf = ABS((t.P & 0xFFFFFFFF) * 256 - t.F))

Note: I remove the HAVE COUNT(*) > 1, otherwise, the statement will also delete those records who are in a group with only one record.

Though it works, I doubt its performance. Since in most of the groups(group by P), there will only be one record, while calculating the minpf in such a group and then delete the record with the calculated value <> minpf is wasting time(no records are deleted in such a group). So just wonder if there are better way to do the same thing?

Update 3

I test the performance of my method(method 1) with the two methods Gordon provided(with minor revision)

Method 2:

DELETE t
    FROM MyTable t LEFT JOIN
         (SELECT P, MIN(ABS((P & 0xFFFFFFFF) * 256 - F)) as minpf
          FROM MyTable
          GROUP BY P
         ) tt
         ON tt.p = t.p AND tt.minpf = (tt.P & 0xFFFFFFFF) * 256 - tt.F)
    WHERE tt.P IS NULL;

Method 3:

DELETE t FROM (SELECT t.*,
                 ROW_NUMBER() OVER (PARTITION BY P ORDER BY ABS((P & 0xFFFFFFFF) * 256 - F)) as seqnum
          FROM MyTable t
         ) t
     WHERE seqnum > 1;

The performance data are below:

First Test:

(22721 rows affected)
Method 1:16094

(22721 rows affected)
Method 2:17156

(22721 rows affected)
Method 3:12188

Second Test:

(22721 rows affected)
Method 1:26297

(22721 rows affected)
Method 2:27562

(22721 rows affected)
Method 3:11625

3rd Test:

(22721 rows affected)
Method 1:26297

(22721 rows affected)
Method 2:27359

(22721 rows affected)
Method 3:11578

So based on the test, method 3 has the best performance.

答:
In SQL Server, simply use a JOIN:

```<code>DELETE t
    FROM MyTable t LEFT JOIN
         (SELECT P, MIN(ABS((P & 0xFFFFFFFF) * 256 - F)) as minpf
          FROM MyTable
          GROUP BY P
          HAVING COUNT(*) > 1
         ) tt
         ON tt.p = t.p AND tt.minpf = (tt.P & 0xFFFFFFFF) * 256 - tt.F)
    WHERE tt.P IS NULL;
</code>```

Or, more simply use window functions:

```<code>DELETE t
    FROM (SELECT t.*,
                 ROW_NUMBER(*) OVER (PARTITION BY P ORDER BY ABS((P & 0xFFFFFFFF) * 256 - F) as seqnum
          FROM MyTable t
         ) t
     WHERE seqnum > 1;
</code>```

Body:
In SQL Server, I have a table MyTable, with the following 3 columns, P(bigint), F(bigint), D(bigint).

Now what I need to do is to group all records by same P value, then in each group, calculate the following value:

V = ABS((P & 0xFFFFFFFF) * 256 - F)

for each record, and delete all records in the group, except for the one with the minimum value of V.

So I write the SQL statement as follows:

DELETE FROM MyTable WHERE (P, ABS((P & 0xFFFFFFFF) * 256 - F)) NOT IN (SELECT P, MIN(ABS((P & 0xFFFFFFFF) * 256 - F)) FROM MyTable GROUP BY P HAVING COUNT(*) > 1)

But in SQL Server, I will get the following error:

Msg 4145 SQL Server An expression of non-boolean type specified in a context where a condition is expected,near ','

Why? Also whether bitwise and & works in SQL Server 2005? I only have SQL Server 2008 R2 and the online document at https://learn.microsoft.com/en-us/sql/t-sql/language-elements/bitwise-and-transact-sql?view=sql-server-ver15 does not indicate whether it support 2005 & 2008.

Update1

P, F, D are all bigint type.

Update2

With the helps of others, I finally write a query with NOT EXISTS, as follows:

Method 1: DELETE t FROM MyTable t WHERE NOT EXISTS (SELECT 1 FROM (SELECT P, MIN(ABS((P & 0xFFFFFFFF) * 256 - F)) as minpf
  FROM MyTable GROUP BY P) tt WHERE tt.P = t.P AND tt.minpf = ABS((t.P & 0xFFFFFFFF) * 256 - t.F))

Note: I remove the HAVE COUNT(*) > 1, otherwise, the statement will also delete those records who are in a group with only one record.

Though it works, I doubt its performance. Since in most of the groups(group by P), there will only be one record, while calculating the minpf in such a group and then delete the record with the calculated value <> minpf is wasting time(no records are deleted in such a group). So just wonder if there are better way to do the same thing?

Update 3

I test the performance of my method(method 1) with the two methods Gordon provided(with minor revision)

Method 2:

DELETE t
    FROM MyTable t LEFT JOIN
         (SELECT P, MIN(ABS((P & 0xFFFFFFFF) * 256 - F)) as minpf
          FROM MyTable
          GROUP BY P
         ) tt
         ON tt.p = t.p AND tt.minpf = (tt.P & 0xFFFFFFFF) * 256 - tt.F)
    WHERE tt.P IS NULL;

Method 3:

DELETE t FROM (SELECT t.*,
                 ROW_NUMBER() OVER (PARTITION BY P ORDER BY ABS((P & 0xFFFFFFFF) * 256 - F)) as seqnum
          FROM MyTable t
         ) t
     WHERE seqnum > 1;

The performance data are below:

First Test:

(22721 rows affected)
Method 1:16094

(22721 rows affected)
Method 2:17156

(22721 rows affected)
Method 3:12188

Second Test:

(22721 rows affected)
Method 1:26297

(22721 rows affected)
Method 2:27562

(22721 rows affected)
Method 3:11625

3rd Test:

(22721 rows affected)
Method 1:26297

(22721 rows affected)
Method 2:27359

(22721 rows affected)
Method 3:11578

So based on the test, method 3 has the best performance.

Body:
In SQL Server, simply use a JOIN:

DELETE t
    FROM MyTable t LEFT JOIN
         (SELECT P, MIN(ABS((P & 0xFFFFFFFF) * 256 - F)) as minpf
          FROM MyTable
          GROUP BY P
          HAVING COUNT(*) > 1
         ) tt
         ON tt.p = t.p AND tt.minpf = (tt.P & 0xFFFFFFFF) * 256 - tt.F)
    WHERE tt.P IS NULL;

Or, more simply use window functions:

DELETE t
    FROM (SELECT t.*,
                 ROW_NUMBER(*) OVER (PARTITION BY P ORDER BY ABS((P & 0xFFFFFFFF) * 256 - F) as seqnum
          FROM MyTable t
         ) t
     WHERE seqnum > 1;


问:
How does the ViewModel constructor get the required interfaces?
My question based on InventorySampleApp by Microsoft.

The ServiceLocator contains method Configure() that register Services and ViewModels. With method GetService<T>() we can get it. For example, ProductView.cs:

```<code>ViewModel = ServiceLocator.Current.GetService<ProductDetailsViewModel>();
</code>```

Each *ViewModel contains constructor with interface, for example:

```<code>public ProductDetailsViewModel(IProductService productService, IFilePickerService filePickerService, ICommonServices commonServices)
</code>```

I can't understand the magiс that ViewModel uses to get such interfaces into its constructor. So there are no lines like this:

```<code>... = new ProductDetailsViewModel(productService, filePickerService, commonServices)
</code>```

How does the ViewModel constructor get the required interfaces?

ServiceLocator

```<code>public class ServiceLocator : IDisposable
{
    static private readonly ConcurrentDictionary<int, ServiceLocator> _serviceLocators = new ConcurrentDictionary<int, ServiceLocator>();

    static private ServiceProvider _rootServiceProvider = null;

    static public void Configure(IServiceCollection serviceCollection)
    {
        serviceCollection.AddSingleton<ISettingsService, SettingsService>();
        serviceCollection.AddSingleton<IDataServiceFactory, DataServiceFactory>();
        serviceCollection.AddSingleton<ILookupTables, LookupTables>();
        serviceCollection.AddSingleton<ICustomerService, CustomerService>();
        serviceCollection.AddSingleton<IOrderService, OrderService>();
        serviceCollection.AddSingleton<IOrderItemService, OrderItemService>();
        serviceCollection.AddSingleton<IProductService, ProductService>();

        serviceCollection.AddSingleton<IMessageService, MessageService>();
        serviceCollection.AddSingleton<ILogService, LogService>();
        serviceCollection.AddSingleton<IDialogService, DialogService>();
        serviceCollection.AddSingleton<IFilePickerService, FilePickerService>();
        serviceCollection.AddSingleton<ILoginService, LoginService>();

        serviceCollection.AddScoped<IContextService, ContextService>();
        serviceCollection.AddScoped<INavigationService, NavigationService>();
        serviceCollection.AddScoped<ICommonServices, CommonServices>();

        serviceCollection.AddTransient<LoginViewModel>();

        serviceCollection.AddTransient<ShellViewModel>();
        serviceCollection.AddTransient<MainShellViewModel>();

        serviceCollection.AddTransient<DashboardViewModel>();

        serviceCollection.AddTransient<CustomersViewModel>();
        serviceCollection.AddTransient<CustomerDetailsViewModel>();

        serviceCollection.AddTransient<OrdersViewModel>();
        serviceCollection.AddTransient<OrderDetailsViewModel>();
        serviceCollection.AddTransient<OrderDetailsWithItemsViewModel>();

        serviceCollection.AddTransient<OrderItemsViewModel>();
        serviceCollection.AddTransient<OrderItemDetailsViewModel>();

        serviceCollection.AddTransient<ProductsViewModel>();
        serviceCollection.AddTransient<ProductDetailsViewModel>();

        serviceCollection.AddTransient<AppLogsViewModel>();

        serviceCollection.AddTransient<SettingsViewModel>();
        serviceCollection.AddTransient<ValidateConnectionViewModel>();
        serviceCollection.AddTransient<CreateDatabaseViewModel>();

        _rootServiceProvider = serviceCollection.BuildServiceProvider();
    }

    static public ServiceLocator Current
    {
        get
        {
            int currentViewId = ApplicationView.GetForCurrentView().Id;
            return _serviceLocators.GetOrAdd(currentViewId, key => new ServiceLocator());
        }
    }

    static public void DisposeCurrent()
    {
        int currentViewId = ApplicationView.GetForCurrentView().Id;
        if (_serviceLocators.TryRemove(currentViewId, out ServiceLocator current))
        {
            current.Dispose();
        }
    }

    private IServiceScope _serviceScope = null;

    private ServiceLocator()
    {
        _serviceScope = _rootServiceProvider.CreateScope();
    }

    public T GetService<T>()
    {
        return GetService<T>(true);
    }

    public T GetService<T>(bool isRequired)
    {
        if (isRequired)
        {
            return _serviceScope.ServiceProvider.GetRequiredService<T>();
        }
        return _serviceScope.ServiceProvider.GetService<T>();
    }

    #region Dispose
    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    protected virtual void Dispose(bool disposing)
    {
        if (disposing)
        {
            if (_serviceScope != null)
            {
                _serviceScope.Dispose();
            }
        }
    }
    #endregion
</code>```

答:
When using dependency injection, the instantiation of objects is moved to a component called Dependency Injection (DI) Container or Inverse of Control (IoC) Container. This component has some kind of registry that contains all known services that can be instantiated. In your example, the serviceCollection is that registry.

Now, whenever a component A needs an instance from the registry, there are two different options:

Directly ask the container for an instance, e. g. ServiceLocator.Current.GetService<ProductDetailsViewModel>(). This is known as the Service Locator Pattern (I'd recommend to forget this immediately).

Rather than asking the container directly, request the dependency via constructor of A (e. g. public A(ProductDetailsViewModel viewModel)).

The second approach can be pushed more and more upwards until the top of the application hierarchy is reached - the so called composition root.

Anyways, in both ways, the container uses the mechanism of Reflection. It is a way of retrieving metadata of classes, methods, properties, constructors, etc. Whenever the container is asked for a certain type (e. g. ProductDetailsViewModel), he uses reflection to get information about its constructor.

Once the constructor is resolved, its dependencies are known as well (IProductService, IFilePickerService, ICommonServices). Since these dependencies are registered within the container (remember the serviceCollection), instances can be created.

This goes on and on until there are no more dependencies and the container can start instantiating and composing all the objects. Finally, there is an instance of ProductDetailsViewModel.
If there is one dependency within the construction chain that is unknown to the container, the instantiation fails.

So basically, the process of instantiation is moved away from your code into the DI container.

Body:
My question based on InventorySampleApp by Microsoft.

The ServiceLocator contains method Configure() that register Services and ViewModels. With method GetService<T>() we can get it. For example, ProductView.cs:

ViewModel = ServiceLocator.Current.GetService<ProductDetailsViewModel>();

Each *ViewModel contains constructor with interface, for example:

public ProductDetailsViewModel(IProductService productService, IFilePickerService filePickerService, ICommonServices commonServices)

I can't understand the magiс that ViewModel uses to get such interfaces into its constructor. So there are no lines like this:

... = new ProductDetailsViewModel(productService, filePickerService, commonServices)

How does the ViewModel constructor get the required interfaces?

ServiceLocator

public class ServiceLocator : IDisposable
{
    static private readonly ConcurrentDictionary<int, ServiceLocator> _serviceLocators = new ConcurrentDictionary<int, ServiceLocator>();

    static private ServiceProvider _rootServiceProvider = null;

    static public void Configure(IServiceCollection serviceCollection)
    {
        serviceCollection.AddSingleton<ISettingsService, SettingsService>();
        serviceCollection.AddSingleton<IDataServiceFactory, DataServiceFactory>();
        serviceCollection.AddSingleton<ILookupTables, LookupTables>();
        serviceCollection.AddSingleton<ICustomerService, CustomerService>();
        serviceCollection.AddSingleton<IOrderService, OrderService>();
        serviceCollection.AddSingleton<IOrderItemService, OrderItemService>();
        serviceCollection.AddSingleton<IProductService, ProductService>();

        serviceCollection.AddSingleton<IMessageService, MessageService>();
        serviceCollection.AddSingleton<ILogService, LogService>();
        serviceCollection.AddSingleton<IDialogService, DialogService>();
        serviceCollection.AddSingleton<IFilePickerService, FilePickerService>();
        serviceCollection.AddSingleton<ILoginService, LoginService>();

        serviceCollection.AddScoped<IContextService, ContextService>();
        serviceCollection.AddScoped<INavigationService, NavigationService>();
        serviceCollection.AddScoped<ICommonServices, CommonServices>();

        serviceCollection.AddTransient<LoginViewModel>();

        serviceCollection.AddTransient<ShellViewModel>();
        serviceCollection.AddTransient<MainShellViewModel>();

        serviceCollection.AddTransient<DashboardViewModel>();

        serviceCollection.AddTransient<CustomersViewModel>();
        serviceCollection.AddTransient<CustomerDetailsViewModel>();

        serviceCollection.AddTransient<OrdersViewModel>();
        serviceCollection.AddTransient<OrderDetailsViewModel>();
        serviceCollection.AddTransient<OrderDetailsWithItemsViewModel>();

        serviceCollection.AddTransient<OrderItemsViewModel>();
        serviceCollection.AddTransient<OrderItemDetailsViewModel>();

        serviceCollection.AddTransient<ProductsViewModel>();
        serviceCollection.AddTransient<ProductDetailsViewModel>();

        serviceCollection.AddTransient<AppLogsViewModel>();

        serviceCollection.AddTransient<SettingsViewModel>();
        serviceCollection.AddTransient<ValidateConnectionViewModel>();
        serviceCollection.AddTransient<CreateDatabaseViewModel>();

        _rootServiceProvider = serviceCollection.BuildServiceProvider();
    }

    static public ServiceLocator Current
    {
        get
        {
            int currentViewId = ApplicationView.GetForCurrentView().Id;
            return _serviceLocators.GetOrAdd(currentViewId, key => new ServiceLocator());
        }
    }

    static public void DisposeCurrent()
    {
        int currentViewId = ApplicationView.GetForCurrentView().Id;
        if (_serviceLocators.TryRemove(currentViewId, out ServiceLocator current))
        {
            current.Dispose();
        }
    }

    private IServiceScope _serviceScope = null;

    private ServiceLocator()
    {
        _serviceScope = _rootServiceProvider.CreateScope();
    }

    public T GetService<T>()
    {
        return GetService<T>(true);
    }

    public T GetService<T>(bool isRequired)
    {
        if (isRequired)
        {
            return _serviceScope.ServiceProvider.GetRequiredService<T>();
        }
        return _serviceScope.ServiceProvider.GetService<T>();
    }

    #region Dispose
    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    protected virtual void Dispose(bool disposing)
    {
        if (disposing)
        {
            if (_serviceScope != null)
            {
                _serviceScope.Dispose();
            }
        }
    }
    #endregion


问:
Informatica File date string convert into timestamp
I  have a column in file Delivery_date - '02/09/2020  15:30:00 PM' in string format . It can AM OR PM both.
I need to convert it on TIMESTAMP format of oracle in informatica power center.

I have tried like below-
TO_DATE(Delivery_date,'MM-DD-YYYY HH24:MI:SS')

But its not working for AM an PM. Kindly suggest

答:
You can remove the AM or PM using reg_replace in your mapping transformation then add TO_DATE if the column is in date/time format

```<code>REG_REPLACE('02/09/2020 15:30:00 PM', '( AM| PM)', '')
</code>```

Since data is coming in as string and going out as time, your output epression i believe will be in date/time

Then you can add to_date to work.

```<code>TO_DATE(REG_REPLACE('02/09/2020 15:30:00 PM', '( AM| PM)', ''), 'MM-DD-YYYY HH24:MI:SS')
</code>```

And if you want to force to the format --another way

```<code>TO_DATE(TO_CHAR(TO_DATE(REG_REPLACE('02/09/2020 15:30:00 PM', '( AM| PM)', '')), 'MM-DD-YYYY HH24:MI:SS'))

 #EXPLANATION
 /*REMOVE THE AM/PM: REG_REPLACE('02/09/2020 15:30:00 PM', '( AM| PM)', '')*/
 /*CONVERT IT TO DATE: TO_DATE(REG_REPLACE('02/09/2020 15:30:00 PM', '( AM| PM)', ''))*/
 /*CHANGE THE FORMAT: TO_CHAR(TO_DATE(REG_REPLACE('02/09/2020 15:30:00 PM', '( AM| PM)', '')), 'MM-DD-YYYY HH24:MI:SS')*/
 /*THEN RETURN TO DATE: TO_CHAR(TO_DATE(REG_REPLACE('02/09/2020 15:30:00 PM', '( AM| PM)', '')), 'MM-DD-YYYY HH24:MI:SS')*/
</code>```

Body:
You can remove the AM or PM using reg_replace in your mapping transformation then add TO_DATE if the column is in date/time format

REG_REPLACE('02/09/2020 15:30:00 PM', '( AM| PM)', '')

Since data is coming in as string and going out as time, your output epression i believe will be in date/time

Then you can add to_date to work.

TO_DATE(REG_REPLACE('02/09/2020 15:30:00 PM', '( AM| PM)', ''), 'MM-DD-YYYY HH24:MI:SS')

And if you want to force to the format --another way

TO_DATE(TO_CHAR(TO_DATE(REG_REPLACE('02/09/2020 15:30:00 PM', '( AM| PM)', '')), 'MM-DD-YYYY HH24:MI:SS'))

 #EXPLANATION
 /*REMOVE THE AM/PM: REG_REPLACE('02/09/2020 15:30:00 PM', '( AM| PM)', '')*/
 /*CONVERT IT TO DATE: TO_DATE(REG_REPLACE('02/09/2020 15:30:00 PM', '( AM| PM)', ''))*/
 /*CHANGE THE FORMAT: TO_CHAR(TO_DATE(REG_REPLACE('02/09/2020 15:30:00 PM', '( AM| PM)', '')), 'MM-DD-YYYY HH24:MI:SS')*/
 /*THEN RETURN TO DATE: TO_CHAR(TO_DATE(REG_REPLACE('02/09/2020 15:30:00 PM', '( AM| PM)', '')), 'MM-DD-YYYY HH24:MI:SS')*/


问:
React Native IOS build clang: error: linker command failed with exit code 1 (use -v to see invocation)
While I'm trying to run the react-native ios application with command react-native run-ios. The Build goes failed and showing me error following:-

ld: warning: directory not found for option
  '-L/Users/User/Documents/react-test-app/ios/build/Build/Products/Debug-iphonesimulator/React'
  ld: library not found for -lRNSVG clang: error: linker command failed
  with exit code 1 (use -v to see invocation)

** BUILD FAILED **

The following build commands failed:
         Ld build/Build/Products/Debug-iphonesimulator/react-test-app.app/react-test-app
  normal x86_64 (1 failure)

Installing
  build/Build/Products/Debug-iphonesimulator/react-test-app.app An error
  was encountered processing the command (domain=NSPOSIXErrorDomain,
  code=22): Failed to install the requested application The bundle
  identifier of the application could not be determined. Ensure that the
  application's Info.plist contains a value for CFBundleIdentifier.
  Print: Entry, ":CFBundleIdentifier", Does Not Exist

Command failed: /usr/libexec/PlistBuddy -c Print:CFBundleIdentifier
  build/Build/Products/Debug-iphonesimulator/oldapollo.app/Info.plist
  Print: Entry, ":CFBundleIdentifier", Does Not Exist.

Please Help Me Out To resolve this problem.
Thank you in advance

答: Open Melkana.xcworkspace instead of Melkana.xcodeproj in Xcode


问:
Scala convert tuple of types to tuple of generic of types
Say I have type a defined as a tuple of types

type a = (Int, String, Int)
```

<p>and I define generic class <code>Foo</code> as</p>

<pre class="lang-scala prettyprint-override"><code>class Foo[A]{}
</code>```

is there any method is Scala (preferably native Scala) that can convert a to b, a tuple of generic of types?

type b = (Foo[Int], Foo[String], Foo[Int])
```

答:
As previously mentioned, there is no way to do it with Scala 2.x without using some sophisticated type-level magic (in this case Shapeless). My implementation uses a generic representation and contains some comments to label some auxillary things.

In order to fully understand how generic representations work, though, you have to read at least the first couple of chapters of The Shapeless Guide.

object Demo extends App {

  import shapeless._
  import syntax.std.tuple._
  import poly._

  // Generic representation of the input type
  val tupleGen = Generic[(Int, String, Int)]

  // Generic representation of the output type
  val tupleFooGen = Generic[(Foo[Int], Foo[String], Foo[Int])]

  // The type we want to lift all tuple members into
  class Foo[A] {}

  // The instance of the input type
  val input = (42, "four two", 43)

  // The "natural transformation" thing
  object liftFoo extends (Id ~> Foo) {
    def apply[T](t: T): Foo[T] = new Foo[T] {}
  }

  // Having done all the prep work, the conversion is really easy
  val result: (Foo[Int], Foo[String], Foo[Int]) =
    tupleFooGen.from(tupleGen.to(input).map(liftFoo))

  println(result)
}
```

Body:
Say I have type a defined as a tuple of types

type a = (Int, String, Int)

and I define generic class Foo as

class Foo[A]{}

is there any method is Scala (preferably native Scala) that can convert a to b, a tuple of generic of types?

type b = (Foo[Int], Foo[String], Foo[Int])


问:
Regular expression to extract all sentences that start and end with the same word
Given a string of sentences, I need to extract a list of all of the sentences which start and end with the same word.

e.g.

# sample text
text = "This is a sample sentence. well, I'll check that things are going well. another sentence starting with another. ..."

# required result
[
 "well, I'll check that things are going well",
 "another sentence starting with another"
]
```
<p>How can I make the match using back references and also capture the full sentence?</p>
<p>I have tried the following regex but it's not working.</p>
<pre class="lang-py prettyprint-override"><code>re.findall("^[a-zA-Z](.*[a-zA-Z])?$", text)
</code>```

答:
```<code>text = "This is a sample sentence. going to checking whether it is well going. another
sentence starting with another."

sentences = re.split('[.!?]+', text)
result = []

for s in sentences:
    words = s.split()
    if len(words) > 0 and words[0] == words[-1]:
        result.append(s.strip())

print(result)
</code>```

Body:
Given a string of sentences, I need to extract a list of all of the sentences which start and end with the same word.

e.g.

# sample text
text = "This is a sample sentence. well, I'll check that things are going well. another sentence starting with another. ..."

# required result
[
 "well, I'll check that things are going well",
 "another sentence starting with another"
]

How can I make the match using back references and also capture the full sentence?

I have tried the following regex but it's not working.

re.findall("^[a-zA-Z](.*[a-zA-Z])?$", text)


问:
Why android program doesnt work on my phone( it work on virtual phone fine)
```<code> try {
        val adresstext= findViewById(R.id.editText3)as TextView

        fusedLocationClient = LocationServices.getFusedLocationProviderClient(this)
        fusedLocationClient.lastLocation.addOnSuccessListener {
                location -> location

            var locationx=location.longitude
            var locationy=location.latitude

            val name = findViewById(R.id.textView) as TextView
            name.text=(locationx.toString()+" "+locationy.toString())
            var geocoder: Geocoder
            var listadress :List<Address>

            geocoder = Geocoder(this, Locale.getDefault());
            listadress =geocoder.getFromLocation(locationy,locationx,1)
            var adress=listadress[0].getAddressLine(0)
            var city =listadress[0].locality.get(0)
            var state = listadress[0].adminArea.get(0)
            var country = listadress[0].getCountryName()
            var postalCode = listadress[0].getPostalCode()
            var knownName = listadress[0].getFeatureName()
            adresstext.text=(adress+city+state+country+postalCode+knownName)

        }

    }
    catch (e: java.lang.Exception)
    {
        Toast.makeText(this,e.toString(),Toast.LENGTH_LONG).show()
    }
</code>```

That is my code,
when ı run it in the emulator it works fine with no error
But when i run it with my phone( ı connect it to my pc) the button not working and it says :

```<code>V/AudioManager: querySoundEffectsEnabled...
D/AwareBitmapCacher: handleInit switch not opened pid=19134
</code>```

Before that when the program opens in my phone the run seciton is like :

```<code>E/: APS:IFLoad:importExternalFunctions, search function createNewHwApsUtils failed, dlsym err:undefined symbol: createNewHwApsUtils

E/AwareLog: AtomicFileUtils: readFileLines file not exist: android.util.AtomicFile@6c8edde
E/AwareLog: AtomicFileUtils: readFileLines file not exist: android.util.AtomicFile@3bb1bbf
</code>```

this 3 are red How can i solve that problem?

答: You should go to phone settings and find your application. Check location service is allowed. If not allowed. Accept that.</p>

Body:
 try {
        val adresstext= findViewById(R.id.editText3)as TextView

        fusedLocationClient = LocationServices.getFusedLocationProviderClient(this)
        fusedLocationClient.lastLocation.addOnSuccessListener {
                location -> location

            var locationx=location.longitude
            var locationy=location.latitude

            val name = findViewById(R.id.textView) as TextView
            name.text=(locationx.toString()+" "+locationy.toString())
            var geocoder: Geocoder
            var listadress :List<Address>

            geocoder = Geocoder(this, Locale.getDefault());
            listadress =geocoder.getFromLocation(locationy,locationx,1)
            var adress=listadress[0].getAddressLine(0)
            var city =listadress[0].locality.get(0)
            var state = listadress[0].adminArea.get(0)
            var country = listadress[0].getCountryName()
            var postalCode = listadress[0].getPostalCode()
            var knownName = listadress[0].getFeatureName()
            adresstext.text=(adress+city+state+country+postalCode+knownName)

        }

    }
    catch (e: java.lang.Exception)
    {
        Toast.makeText(this,e.toString(),Toast.LENGTH_LONG).show()
    }

That is my code,
when ı run it in the emulator it works fine with no error
But when i run it with my phone( ı connect it to my pc) the button not working and it says :

V/AudioManager: querySoundEffectsEnabled...
D/AwareBitmapCacher: handleInit switch not opened pid=19134

Before that when the program opens in my phone the run seciton is like :

E/: APS:IFLoad:importExternalFunctions, search function createNewHwApsUtils failed, dlsym err:undefined symbol: createNewHwApsUtils

E/AwareLog: AtomicFileUtils: readFileLines file not exist: android.util.AtomicFile@6c8edde
E/AwareLog: AtomicFileUtils: readFileLines file not exist: android.util.AtomicFile@3bb1bbf

this 3 are red How can i solve that problem?


问:
TortoiseHg: No visual diff tools were detected (Mac)
I installed meld in my Mac and i want to use this as a visual diff tool in TortoiseHg. (Note that I am using a Mac. )

I have the following configuration in my .hgrc file. But when I double clicked on a file, I got this "No visual diff tools were detected". Am I missing something in the file ?

This is getting a little bit frustrating because I have spent hours on this and still wasn't able to get a solution. Need some help here please .

```<code>[ui]
merge = /opt/local/bin/meld

[tortoisehg]
vdiff = /opt/local/bin/meld
</code>```

答:
I have TortoiseHg locally installed in my home directory (since Ubuntu PPA was abandoned). My .hgrc starts with following line:

```<code>%include PATH_TO_THG_REPO/contrib/mergetools.rc
</code>```

This file contains description of various merge and diff tools. Without it TortoiseHg doesn't detect any.

Once path to this file changed (when I copied .hgrc to another machine) and I got the same error message.

P.S.
Don't forget to replace PATH_TO_THG with your specific path.

Body:
I installed meld in my Mac and i want to use this as a visual diff tool in TortoiseHg. (Note that I am using a Mac. )

I have the following configuration in my .hgrc file. But when I double clicked on a file, I got this "No visual diff tools were detected". Am I missing something in the file ?

This is getting a little bit frustrating because I have spent hours on this and still wasn't able to get a solution. Need some help here please .

[ui]
merge = /opt/local/bin/meld

[tortoisehg]
vdiff = /opt/local/bin/meld

Body:
I have TortoiseHg locally installed in my home directory (since Ubuntu PPA was abandoned). My .hgrc starts with following line:

%include PATH_TO_THG_REPO/contrib/mergetools.rc

This file contains description of various merge and diff tools. Without it TortoiseHg doesn't detect any.

Once path to this file changed (when I copied .hgrc to another machine) and I got the same error message.

P.S.
Don't forget to replace PATH_TO_THG with your specific path.


问:
How to fix Scrolling issue of horizontal ViewPager2 and RecyclerView that are inside a vertical RecyclerView?
I have a RecyclerView (say, rootRecyclerView) that can have different kinds of rows depending on some API response. I implemented one of them is a horizontal ViewPager2 and another one is implemented with horizontal  RecyclerView (say, childRecyclerView).

The rootRecyclerView swipes vertically whereas the viewPager2 and childRecyclerView swipes horizontally.

The Problem:

When I swipe on the screen, if the swipe is on the the viewPager2 or childRecyclerView, the swipe MUST go perfectly straight horizontally. Otherwise, they won't scroll horizontally; the swipe is taken by the rootRecyclerView and so the you would see vertical movement.

So, this happens because your thumb would move in a curved/circular direction creating movement in both the X axis and Y axis, and the so the rootRecyclerView intercepts the swipe creating this unpleasant user experience.

I did try to solve the issue, such as adding an OnItemTouchListener to the childRecyclerView like this:

```<code>    private float Y_BUFFER = ViewConfiguration.get(getContext())
                                     .getScaledPagingTouchSlop(); // 10;
    private float preX = 0f;
    private float preY = 0f;
childRecyclerView.addOnItemTouchListener(new RecyclerView.OnItemTouchListener() {
            @Override
            public boolean onInterceptTouchEvent(@NonNull RecyclerView rv, @NonNull MotionEvent e) {
                if(e.getAction()==MotionEvent.ACTION_DOWN){
                    childRecyclerView.getParent().requestDisallowInterceptTouchEvent(true);
                }
                if(e.getAction() == MotionEvent.ACTION_MOVE){
                    if (Math.abs(e.getX() - preX) > Math.abs(e.getY() - preY)) {
                        childRecyclerView.getParent().requestDisallowInterceptTouchEvent(true);
                    } else if (Math.abs(e.getY() - preY) > Y_BUFFER) {
                        childRecyclerView.getParent().requestDisallowInterceptTouchEvent(false);
                    }
                }
                preX = e.getX();
                preY = e.getY();
                return false;
            }
// ... rest of the code
</code>```

It solves the problem only for the childRecyclerView, but I could not solve it for the ViewPager2.

I have also tried to use GestureDetector as described in this answer link, and some other combinations of code, but I could not make it work.

Could anyone help me?

答:
Okay, so after some research, I came to the conclusion of substituting my ViewPager2 with a recyclerView that will 'behave like' a viewPager :/ .

First I replaced my viewPager2 with a horizontal recyclerView. To make it behave like a viewpager, use SnapHelper.

RecyclerView childRecyclerView2 = findViewById(R.id.previously_viewPager);
// other init like setup layout manager, adapter etc
SnapHelper snapHelper = new PagerSnapHelper();
snapHelper.attachToRecyclerView(replacedRecyclerView); // <-- this makes out rv behave like a viewPager
```
<p>After that, you have to add an <code>OnItemTouchListener</code> and override <code>onInterceptTouchEvent</code> just like the code segment in my question:</p>
<pre class="lang-java prettyprint-override"><code>childRecyclerView2.addOnItemTouchListener(new RecyclerView.OnItemTouchListener() {
            @Override
            public boolean onInterceptTouchEvent(@NonNull RecyclerView rv, @NonNull MotionEvent e) {
// same as the code segment in the question,
//so skipping this part.
//just copy it from my question
          }
// ...
}
</code>```

Optional:

In viewPager2, you can get the current focus with getCurrentItem(), but since we have replaced out viewpager2 with recyclerview, we don't have that method. So, we need to implement our own equivalent version. If you are a Kotlin guy, you can directly jump to the reference 2 and skip this part. Here is the java version if you need, I'll skip the explanation though.
Create SnapHelperExt.java

public class SnapHelperExt {

    public SnapHelperExt(){}

    public int getSnapPosition(RecyclerView recyclerView, SnapHelper snapHelper){
        RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
        View snapView =  snapHelper.findSnapView(layoutManager);
        if (snapView != null) {
            return layoutManager.getPosition(snapView);
        }else{
            return -1;
        }
    }
}
```
<p>Next create an interface <code>OnSnapPositionChangeListener</code> as our listener :</p>
<pre class="lang-java prettyprint-override"><code>public interface OnSnapPositionChangeListener {
    void onSnapPositionChange(int position);
}
</code>```

After that, create SnapOnScrollListener.java:

public class SnapOnScrollListener extends RecyclerView.OnScrollListener {

    public enum Behavior {
        NOTIFY_ON_SCROLL,
        NOTIFY_ON_SCROLL_STATE_IDLE
    }

    private SnapHelperExt snapHelperExt;
    private SnapHelper snapHelper;
    private Behavior behavior;
    private OnSnapPositionChangeListener onSnapPositionChangeListener;
    private int snapPosition = RecyclerView.NO_POSITION;

    public SnapOnScrollListener(SnapHelper snapHelper, Behavior behavior, OnSnapPositionChangeListener onSnapPositionChangeListener){
        this.snapHelper = snapHelper;
        this.behavior = behavior;
        this.onSnapPositionChangeListener = onSnapPositionChangeListener;
        this.snapHelperExt = new SnapHelperExt();
    }

    @Override
    public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
        super.onScrolled(recyclerView, dx, dy);
        if (behavior == Behavior.NOTIFY_ON_SCROLL) {
            maybeNotifySnapPositionChange(recyclerView);
        }
    }

    @Override
    public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
        super.onScrollStateChanged(recyclerView, newState);
        if (behavior == Behavior.NOTIFY_ON_SCROLL_STATE_IDLE
                && newState == RecyclerView.SCROLL_STATE_IDLE) {
            maybeNotifySnapPositionChange(recyclerView);
        }
    }

    private void maybeNotifySnapPositionChange(RecyclerView recyclerView){
        int prevPosition = this.snapHelperExt.getSnapPosition(recyclerView, snapHelper);
        boolean snapPositionIsChanged = (this.snapPosition!=prevPosition);

        if(snapPositionIsChanged){
            onSnapPositionChangeListener.onSnapPositionChange(prevPosition);
            this.snapPosition = prevPosition;
        }
    }
}
```
<p>Finally, use it in this way:</p>
<pre class="lang-java prettyprint-override"><code>            SnapOnScrollListener snapOnScrollListener = new SnapOnScrollListener(
                    snapHelper,
                    SnapOnScrollListener.Behavior.NOTIFY_ON_SCROLL,
                    position -> {
Log.e(TAG, "currently focused page no = "+position);
// your code here, do whatever you want
}
            );

            childRecyclerView2.addOnScrollListener(snapOnScrollListener);
</code>```

References:

create-viewpager-using-recyclerview

detecting-snap-changes-with-androids-recyclerview

Body:
I have a RecyclerView (say, rootRecyclerView) that can have different kinds of rows depending on some API response. I implemented one of them is a horizontal ViewPager2 and another one is implemented with horizontal  RecyclerView (say, childRecyclerView).

The rootRecyclerView swipes vertically whereas the viewPager2 and childRecyclerView swipes horizontally.

The Problem:

When I swipe on the screen, if the swipe is on the the viewPager2 or childRecyclerView, the swipe MUST go perfectly straight horizontally. Otherwise, they won't scroll horizontally; the swipe is taken by the rootRecyclerView and so the you would see vertical movement.

So, this happens because your thumb would move in a curved/circular direction creating movement in both the X axis and Y axis, and the so the rootRecyclerView intercepts the swipe creating this unpleasant user experience.

I did try to solve the issue, such as adding an OnItemTouchListener to the childRecyclerView like this:

    private float Y_BUFFER = ViewConfiguration.get(getContext())
                                     .getScaledPagingTouchSlop(); // 10;
    private float preX = 0f;
    private float preY = 0f;
childRecyclerView.addOnItemTouchListener(new RecyclerView.OnItemTouchListener() {
            @Override
            public boolean onInterceptTouchEvent(@NonNull RecyclerView rv, @NonNull MotionEvent e) {
                if(e.getAction()==MotionEvent.ACTION_DOWN){
                    childRecyclerView.getParent().requestDisallowInterceptTouchEvent(true);
                }
                if(e.getAction() == MotionEvent.ACTION_MOVE){
                    if (Math.abs(e.getX() - preX) > Math.abs(e.getY() - preY)) {
                        childRecyclerView.getParent().requestDisallowInterceptTouchEvent(true);
                    } else if (Math.abs(e.getY() - preY) > Y_BUFFER) {
                        childRecyclerView.getParent().requestDisallowInterceptTouchEvent(false);
                    }
                }
                preX = e.getX();
                preY = e.getY();
                return false;
            }
// ... rest of the code

It solves the problem only for the childRecyclerView, but I could not solve it for the ViewPager2.

I have also tried to use GestureDetector as described in this answer link, and some other combinations of code, but I could not make it work.

Could anyone help me?

Body:
Okay, so after some research, I came to the conclusion of substituting my ViewPager2 with a recyclerView that will 'behave like' a viewPager :/ .

First I replaced my viewPager2 with a horizontal recyclerView. To make it behave like a viewpager, use SnapHelper.

RecyclerView childRecyclerView2 = findViewById(R.id.previously_viewPager);
// other init like setup layout manager, adapter etc
SnapHelper snapHelper = new PagerSnapHelper();
snapHelper.attachToRecyclerView(replacedRecyclerView); // <-- this makes out rv behave like a viewPager

After that, you have to add an OnItemTouchListener and override onInterceptTouchEvent just like the code segment in my question:

childRecyclerView2.addOnItemTouchListener(new RecyclerView.OnItemTouchListener() {
            @Override
            public boolean onInterceptTouchEvent(@NonNull RecyclerView rv, @NonNull MotionEvent e) {
// same as the code segment in the question,
//so skipping this part.
//just copy it from my question
          }
// ...
}

Optional:

In viewPager2, you can get the current focus with getCurrentItem(), but since we have replaced out viewpager2 with recyclerview, we don't have that method. So, we need to implement our own equivalent version. If you are a Kotlin guy, you can directly jump to the reference 2 and skip this part. Here is the java version if you need, I'll skip the explanation though.
Create SnapHelperExt.java

public class SnapHelperExt {

    public SnapHelperExt(){}

    public int getSnapPosition(RecyclerView recyclerView, SnapHelper snapHelper){
        RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
        View snapView =  snapHelper.findSnapView(layoutManager);
        if (snapView != null) {
            return layoutManager.getPosition(snapView);
        }else{
            return -1;
        }
    }
}

Next create an interface OnSnapPositionChangeListener as our listener :

public interface OnSnapPositionChangeListener {
    void onSnapPositionChange(int position);
}

After that, create SnapOnScrollListener.java:

public class SnapOnScrollListener extends RecyclerView.OnScrollListener {

    public enum Behavior {
        NOTIFY_ON_SCROLL,
        NOTIFY_ON_SCROLL_STATE_IDLE
    }

    private SnapHelperExt snapHelperExt;
    private SnapHelper snapHelper;
    private Behavior behavior;
    private OnSnapPositionChangeListener onSnapPositionChangeListener;
    private int snapPosition = RecyclerView.NO_POSITION;

    public SnapOnScrollListener(SnapHelper snapHelper, Behavior behavior, OnSnapPositionChangeListener onSnapPositionChangeListener){
        this.snapHelper = snapHelper;
        this.behavior = behavior;
        this.onSnapPositionChangeListener = onSnapPositionChangeListener;
        this.snapHelperExt = new SnapHelperExt();
    }

    @Override
    public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
        super.onScrolled(recyclerView, dx, dy);
        if (behavior == Behavior.NOTIFY_ON_SCROLL) {
            maybeNotifySnapPositionChange(recyclerView);
        }
    }

    @Override
    public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
        super.onScrollStateChanged(recyclerView, newState);
        if (behavior == Behavior.NOTIFY_ON_SCROLL_STATE_IDLE
                && newState == RecyclerView.SCROLL_STATE_IDLE) {
            maybeNotifySnapPositionChange(recyclerView);
        }
    }

    private void maybeNotifySnapPositionChange(RecyclerView recyclerView){
        int prevPosition = this.snapHelperExt.getSnapPosition(recyclerView, snapHelper);
        boolean snapPositionIsChanged = (this.snapPosition!=prevPosition);

        if(snapPositionIsChanged){
            onSnapPositionChangeListener.onSnapPositionChange(prevPosition);
            this.snapPosition = prevPosition;
        }
    }
}

Finally, use it in this way:

            SnapOnScrollListener snapOnScrollListener = new SnapOnScrollListener(
                    snapHelper,
                    SnapOnScrollListener.Behavior.NOTIFY_ON_SCROLL,
                    position -> {
Log.e(TAG, "currently focused page no = "+position);
// your code here, do whatever you want
}
            );

            childRecyclerView2.addOnScrollListener(snapOnScrollListener);

References:

create-viewpager-using-recyclerview

detecting-snap-changes-with-androids-recyclerview


问:
Govendor as type error
Getting an error:  cannot use *company/model as type *vendor/company/model

Flat Vendor structure : vendor/company/model

The files import "company/model"

答: Follow GarMan's explaination, running command govendor add +e works.

Title: Govendor as type error


问:
datepicker JQuery Validations and Format
I am using the following for datepicker in Jquery to format the date display in dd/mm/yy format and also I want the user not to select future date.Only one thing is working at a time.

```<code><script type="text/javascript" language ="javascript" >
            $(function () {
                var date = new Date();
                var currentDate = date.getDate();
                var currentMonth = date.getMonth();
                var currentYear = date.getFullYear();
               $(".datepicker").datepicker({ dateFormat: 'dd/mm/yy' });
                $(".datepicker").datepicker({ maxDate: new Date(currentYear, currentMonth, currentDate) });

            });
</script>
</code>```

How do make, both the dateformat and disable the future dates to work simultaneously. I am missing single bit, I don't know how to club this two validations or requirements togather.

Any answers Please?

Thank you.

答:
I had a similar requirement for my code with a hire date.  Here's how I did it:</p>

```<code>$('#hireDate').datepicker({
    dateFormat: 'dd/mm/yy',
    maxDate: new Date(currentYear, currentMonth, currentDay)
});
</code>```

Body:
I am using the following for datepicker in Jquery to format the date display in dd/mm/yy format and also I want the user not to select future date.Only one thing is working at a time.

How do make, both the dateformat and disable the future dates to work simultaneously. I am missing single bit, I don't know how to club this two validations or requirements togather.

Any answers Please?

Thank you.

Body:
I had a similar requirement for my code with a hire date.  Here's how I did it:

$('#hireDate').datepicker({
    dateFormat: 'dd/mm/yy',
    maxDate: new Date(currentYear, currentMonth, currentDay)
});


问:
Tensorflow OMP: Error #15 when training
I am training my neural network using tensorflow on CentOS HPC. However I got this error at start of the training process:

 OMP: Error #15: Initializing libiomp5.so, but found libiomp5.so already initialized.
OMP: Hint: This means that multiple copies of the OpenMP runtime have been linked into the program. That is dangerous, since it can degrade performance or cause incorrect results. The best thing to do is to ensure that only a single OpenMP runtime is linked into the process, e.g. by avoiding static linking of the OpenMP runtime in any library. As an unsafe, unsupported, undocumented workaround you can set the environment variable KMP_DUPLICATE_LIB_OK=TRUE to allow the program to continue to execute, but that may cause crashes or silently produce incorrect results. For more information, please see http://www.intel.com/software/products/support/.

The code is for instance segmentation and it worked fine for many people, but failed in my case.

Why it occurs? How to solve it?

答:
I had a similar issue on macOS with the same error message (see this question) and found the following reasons:

Problem:

I had a conda environment where Numpy, SciPy and TensorFlow were installed.

Conda is using Intel(R) MKL Optimizations, see docs:

Anaconda has packaged MKL-powered binary versions of some of the most popular numerical/scientific Python libraries into MKL Optimizations for improved performance.

The Intel MKL functions (e.g. FFT, LAPACK, BLAS) are threaded with the OpenMP technology.

But on macOS you do not need MKL, because the Accelerate Framework comes with its own optimization algorithms and already uses OpenMP. That is the reason for the error message: OMP Error #15: ...

Workaround:

You should install all packages without MKL support:

conda install nomkl

and then use

conda install numpy scipy pandas tensorflow

followed by

conda remove mkl mkl-service

For more information see conda MKL Optimizations.

Title: Tensorflow OMP: Error #15 when training


问:
Wrong number of arguments to IF
With the formula below, I keep receiving the error "Wrong number of arguments to IF. Expected between 2 and 3 arguments, but received 5 arguments."

Where have I gone wrong? It works up until a certain point and then the code throw up the above error... Am i missing a comma or bracket somewhere?

Any help greatly appreciated :)

```<code>=arrayformula(If(G5 <> "",if(H5 = "Y",if(C6 = "Sub-Total", ttime($M$3,vlookup(B5,Lookup!$A:$I,3,0)),if(AND(C7 = "Sub-Total",B6 <>"",B5 <>""),ttime($M$3,vlookup(B6,Lookup!$A:$I,3,0),vlookup(B5,Lookup!$A:$I,3,0)),if(AND(C8 = "Sub-Total",B7 <> "", B6 <> "",B5 <>""),ttime($M$3,vlookup(B7,Lookup!$A:$I,3,0),vlookup(B6,Lookup!$A:$I,3,0),vlookup(B5,Lookup!$A:$I,3,0)),if(AND(C9 = "Sub-Total",B8 <> "", B7 <> "",B6 <>"",B5 <> ""),ttime($M$3,vlookup(B8,Lookup!$A:$I,3,0),vlookup(B7,Lookup!$A:$I,3,0),vlookup(B6,Lookup!$A:$I,3,0)),vlookup(B5,Lookup!$A:$I,3,0)),if(AND(C10 = "Sub-Total",B9 <> "", B8 <> "",B7 <>"",B6 <> "",B5 <> ""),ttime($M$3,vlookup(B9,Lookup!$A:$I,3,0),vlookup(B8,Lookup!$A:$I,3,0),vlookup(B7,Lookup!$A:$I,3,0)),vlookup(B6,Lookup!$A:$I,3,0)),vlookup(B5,Lookup!$A:$I,3,0))))+IF(C6 = "sub-total","",if(B5 <> "", G6 * 3,""))+IF(C6 = "sub-total","",if(B5 <> "", "15","")),"Not Despatched"),""))
</code>```

Title: Wrong number of arguments to IF

Body:
With the formula below, I keep receiving the error "Wrong number of arguments to IF. Expected between 2 and 3 arguments, but received 5 arguments."

Where have I gone wrong? It works up until a certain point and then the code throw up the above error... Am i missing a comma or bracket somewhere?

Any help greatly appreciated :)

=arrayformula(If(G5 <> "",if(H5 = "Y",if(C6 = "Sub-Total", ttime($M$3,vlookup(B5,Lookup!$A:$I,3,0)),if(AND(C7 = "Sub-Total",B6 <>"",B5 <>""),ttime($M$3,vlookup(B6,Lookup!$A:$I,3,0),vlookup(B5,Lookup!$A:$I,3,0)),if(AND(C8 = "Sub-Total",B7 <> "", B6 <> "",B5 <>""),ttime($M$3,vlookup(B7,Lookup!$A:$I,3,0),vlookup(B6,Lookup!$A:$I,3,0),vlookup(B5,Lookup!$A:$I,3,0)),if(AND(C9 = "Sub-Total",B8 <> "", B7 <> "",B6 <>"",B5 <> ""),ttime($M$3,vlookup(B8,Lookup!$A:$I,3,0),vlookup(B7,Lookup!$A:$I,3,0),vlookup(B6,Lookup!$A:$I,3,0)),vlookup(B5,Lookup!$A:$I,3,0)),if(AND(C10 = "Sub-Total",B9 <> "", B8 <> "",B7 <>"",B6 <> "",B5 <> ""),ttime($M$3,vlookup(B9,Lookup!$A:$I,3,0),vlookup(B8,Lookup!$A:$I,3,0),vlookup(B7,Lookup!$A:$I,3,0)),vlookup(B6,Lookup!$A:$I,3,0)),vlookup(B5,Lookup!$A:$I,3,0))))+IF(C6 = "sub-total","",if(B5 <> "", G6 * 3,""))+IF(C6 = "sub-total","",if(B5 <> "", "15","")),"Not Despatched"),""))

Body:
try:

=ARRAYFORMULA(
 IF(G5<>"",
 IF(H5="Y",
 IF(C6="Sub-Total",                                               TTIME($M$3, VLOOKUP(B5, Lookup!$A:$I, 3, 0)),
 IF(AND(C7="Sub-Total", B6<>"", B5<>""),                          TTIME($M$3, VLOOKUP(B6, Lookup!$A:$I, 3, 0),
                                                                              VLOOKUP(B5, Lookup!$A:$I, 3, 0)),
 IF(AND(C8="Sub-Total", B7<>"", B6<>"", B5<>""),                  TTIME($M$3, VLOOKUP(B7, Lookup!$A:$I, 3, 0),
                                                                              VLOOKUP(B6, Lookup!$A:$I, 3, 0),
                                                                              VLOOKUP(B5, Lookup!$A:$I, 3, 0)),
 IF(AND(C9="Sub-Total", B8<>"", B7<>"", B6<>"", B5<>""),          TTIME($M$3, VLOOKUP(B8, Lookup!$A:$I, 3, 0),
                                                                              VLOOKUP(B7, Lookup!$A:$I, 3, 0),
                                                                              VLOOKUP(B6, Lookup!$A:$I, 3, 0),
                                                                              VLOOKUP(B5, Lookup!$A:$I, 3, 0)),
 IF(AND(C10="Sub-Total", B9<>"", B8<>"", B7<>"", B6<>"", B5<>""), TTIME($M$3, VLOOKUP(B9, Lookup!$A:$I, 3, 0),
                                                                              VLOOKUP(B8, Lookup!$A:$I, 3, 0),
                                                                              VLOOKUP(B7, Lookup!$A:$I, 3, 0),
                                                                              VLOOKUP(B6, Lookup!$A:$I, 3, 0),
                                                                              VLOOKUP(B5, Lookup!$A:$I, 3, 0)))))))+
 IF(C6="sub-total",,
 IF(B5<>"", G6*3, ))+
 IF(C6="sub-total",,
 IF(B5<>"", "15", )), "Not Despatched"), ))


问:
SQL alchemy prefixes table name to columns
I am using delcarative base in sql-alchemy to query data:

```<code>from sqlalchemy.ext.declarative import declarative_base
OdsBase = declarative_base(metadata=sql.MetaData(schema='ods'))

class BagImport(OdsBase):
    __tablename__ = 'bag_stg_import'
    __table_args__ = {'extend_existing': True}
    PAN = sql.Column(sql.String(50), primary_key = True)
    GEM = sql.Column(sql.String(50))
    def __repr__(self):
        return "<{0} Pan: {1} - Gem: {2}>".format(self.__class__.__name__, self.PAN, self.GEM)
</code>```

If I do, I get a proper result:

```<code>my_session.query(BagImport).first()
</code>```

But if I want to see the query and I do:

```<code>the_query = my_session.query(BagImport)
print(the_query)
</code>```

I get the output query as:

```<code>SELECT ods.bag_stg_import."PAN" AS "ods_bag_stg_import_PAN_1", ods.bag_stg_import."GEM" AS "ods_bag_stg_import_GEM_2"
FROM ods.bag_stg_import
</code>```

Why is SQL-Alchemy prefixing the table name in the alias e.g. SELECT ods.bag_stg_import."PAN" AS "ods_bag_stg_import_PAN_1"?

How can I make it AS SELECT ods.bag_stg_import."PAN" AS "PAN"?

答:
just mention below meta property in your model

```<code>__tablename__ = 'Users'
</code>```

them sqlaclchemy will take the  proper table name

Body:
I am using delcarative base in sql-alchemy to query data:

from sqlalchemy.ext.declarative import declarative_base
OdsBase = declarative_base(metadata=sql.MetaData(schema='ods'))

class BagImport(OdsBase):
    __tablename__ = 'bag_stg_import'
    __table_args__ = {'extend_existing': True}
    PAN = sql.Column(sql.String(50), primary_key = True)
    GEM = sql.Column(sql.String(50))
    def __repr__(self):
        return "<{0} Pan: {1} - Gem: {2}>".format(self.__class__.__name__, self.PAN, self.GEM)

If I do, I get a proper result:

my_session.query(BagImport).first()

But if I want to see the query and I do:

the_query = my_session.query(BagImport)
print(the_query)

I get the output query as:

SELECT ods.bag_stg_import."PAN" AS "ods_bag_stg_import_PAN_1", ods.bag_stg_import."GEM" AS "ods_bag_stg_import_GEM_2"
FROM ods.bag_stg_import

Why is SQL-Alchemy prefixing the table name in the alias e.g. SELECT ods.bag_stg_import."PAN" AS "ods_bag_stg_import_PAN_1"?

How can I make it AS SELECT ods.bag_stg_import."PAN" AS "PAN"?

Body:
just mention below meta property in your model

__tablename__ = 'Users'

them sqlaclchemy will take the  proper table name


问:
Use of multiple <router-outlet> under Angular Material (8) is not working
Attempting to redefine the problem since I have some more information.

I am working with Angular Material (8) - along with the MDBootstrap package.
I have 2 areas. One is an area that deals with logins/authorizations (AUTH) and the other is a "dashboard" area (that is to be accessed after login) (DASHBOARD).

Here is the code that is working with AUTH and MYDASHBOARD - AUTH is being interpreted by Angular as being the primary. I named the second router-outlet definition mydashboard

app.component.html

```<code><router-outlet></router-outlet>
<router-outlet name="mydashboard"></router-outlet>
</code>```

app-routing.module.ts

```<code>const routes: Routes = [
  { path: 'auth', loadChildren: './kdc/authorization/authorization.module#AuthorizationModule' },
  { path: 'dashboard', loadChildren: './kdc/dashboard/dashboard.module#DashboardModule'  },
  { path: '**' , component: PageNotFoundComponent }

];
</code>```

authorization-routing.module.ts

```<code>export const routesAuth : Routes = [
    { path: 'login' , component: LoginComponent },
    { path: 'register' , component: RegisterComponent },
    { path: 'forgot-pass' , component: ForgotPasswordComponent },
];
</code>```

NOTE: EVERYTHING FOR (AUTH) IS WORKING - THERE IS NOTHING WRONG WITH THIS PART. THE PROBLEM IS WITH (DASHBOARD)

After logging in, the processing goes to the dashboard. I used the code below to send it to the dashboard

login.component.ts

```<code>onLoginSubmit() {
[... snip ...]
        if (this.in_results.count == 0)
          this.errorMsg = 'EMail/Login ID not found';
        else
          // go ahead and navigate to the HOME page
          this.router.navigate(['/dashboard']);
[... snip ...]
}
</code>```

dashboard-routing.module.ts

```<code>const dashboardroutes: Routes = [
    { path: 'clients', component: ClientsComponent, outlet: 'contentarea'  },
    { path: '', component: HomeComponent, outlet:'mydashboard' },
];
</code>```

NOTE: EVERYTHING EXECUTES FINE HERE, THE DASHBOARD DOES COME UP AND IT IS STORED IN <router-outlet name="mydashboard"></router-outlet> THE PROBLEM COMES WITH USING THE MENU.

When clicking on the "Clients" area, my expectation is that the "Client Information" will be placed into <router-outlet name="contentarea"> </router-outlet>  because of how home.component.html was defined.

home.component.html

```<code>[... snip ...]
                       <!-- Collapsible link -->
                            <mdb-accordion-item-body>
                                <ul>
                                    <li>  <a [routerLink]="[{ outlets: { primary: 'mydashboard', contentarea : 'clients' }}]" mdbWavesEffect> Press for clients</a></li>
                                    <li><a href="#" mdbWavesEffect>Link 2</a></li>
                                </ul>
                            </mdb-accordion-item-body>
                        </mdb-accordion-item>

[... snip ...]
<!--Main Layout-->
<main>
    <div class="container-fluid mt-5">
        <router-outlet name="contentarea"> </router-outlet>
    </div>
</main>
<!--/Main layout-->

[... snip ...]
</code>```

NOTE:
The processing does not go to: <router-outlet name="contentarea"> </router-outlet>

INSTEAD

It goes to: <router-outlet></router-outlet> located on page: app.component.html

QUESTION: Why does it do this? Am I doing it properly? Is there a better way?

I have looked at the following pieces of documentation

```<code>https://stackoverflow.com/questions/53702674/children-routing-not-working-and-application-redirects-to-the-404-page
https://www.tektutorialshub.com/angular/angular-child-routes-nested-routes/
https://stackoverflow.com/questions/52824639/nested-router-outlet-with-name-not-working
https://www.techiediaries.com/angular-router-multiple-outlets/
https://angular.io/guide/router
</code>```

but have not found anything as of yet.

Any information or ideas would be greatly appreciated.

TIA

答:
After research (I am new to Angular pretty much), I found that I needed to the following to resolve my problem:

Since I am working with "Lazy Loading", I made sure that the Routes defined in the xxx-routing.ts files were properly imported into the xxx-module.ts files (I missed this for the Dashboard setup)

I changed the Dashboard setup so that Children were used:

app-routing.module.ts

```<code>const routes: Routes = [
  { path: 'auth', loadChildren: './kdc/authorization/authorization.module#AuthorizationModule' },

  { path: 'dashboard', loadChildren: './kdc/dashboard/dashboard.module#DashboardModule'  },
  { path: '**' , component: PageNotFoundComponent }
];
</code>```

dashboard.routing.module.ts

```<code>export const dashboardroutes: Routes = [

    { path: 'landing/:id', component: HomeComponent,
        children: [
            { path: 'clients', component: ClientsComponent, outlet: 'contentarea'  },
        ]},
];
</code>```

I played around with different ways to see if the routers were working. It was during the "playaround time", that I found an answer that worked for me.

```<code><!-- WORKS : http://localhost:4200/dashboard/landing/(contentarea:clients) -->

<!-- NOTES: GOES TO BASE HOME PAGE FOR DASHBOARD: http://localhost:4200/dashboard/landing -->

<!-- 404 RESULT: http://localhost:4200/dashboard/landing/landing
    <li>  <a [routerLink]="['landing',  { outlets: { contentarea : ['clients']}}] " mdbWavesEffect> Press for clients</a></li> -->

<!-- the one below WORKED:  http://localhost:4200/dashboard/landing/(contentarea:clients) -->
        <li>  <a [routerLink]="[{ outlets: { contentarea : ['clients']}}] " mdbWavesEffect> Press for clients</a></li>
</code>```

I got rid of the <router-outlet name="mydashboard"><router-outlet> since it did not seem to be needed. I thought that the routers could work in a "sibling" relationship. Have learned that the relationship between different router-outlet definitions is more of a "parent-child" relationship.

Body:
Attempting to redefine the problem since I have some more information.

I am working with Angular Material (8) - along with the MDBootstrap package.
I have 2 areas. One is an area that deals with logins/authorizations (AUTH) and the other is a "dashboard" area (that is to be accessed after login) (DASHBOARD).

Here is the code that is working with AUTH and MYDASHBOARD - AUTH is being interpreted by Angular as being the primary. I named the second router-outlet definition mydashboard

app.component.html

<router-outlet></router-outlet>
<router-outlet name="mydashboard"></router-outlet>

app-routing.module.ts

const routes: Routes = [
  { path: 'auth', loadChildren: './kdc/authorization/authorization.module#AuthorizationModule' },
  { path: 'dashboard', loadChildren: './kdc/dashboard/dashboard.module#DashboardModule'  },
  { path: '**' , component: PageNotFoundComponent }

];

authorization-routing.module.ts

export const routesAuth : Routes = [
    { path: 'login' , component: LoginComponent },
    { path: 'register' , component: RegisterComponent },
    { path: 'forgot-pass' , component: ForgotPasswordComponent },
];

NOTE: EVERYTHING FOR (AUTH) IS WORKING - THERE IS NOTHING WRONG WITH THIS PART. THE PROBLEM IS WITH (DASHBOARD)

After logging in, the processing goes to the dashboard. I used the code below to send it to the dashboard

login.component.ts

onLoginSubmit() {
[... snip ...]
        if (this.in_results.count == 0)
          this.errorMsg = 'EMail/Login ID not found';
        else
          // go ahead and navigate to the HOME page
          this.router.navigate(['/dashboard']);
[... snip ...]
}

dashboard-routing.module.ts

const dashboardroutes: Routes = [
    { path: 'clients', component: ClientsComponent, outlet: 'contentarea'  },
    { path: '', component: HomeComponent, outlet:'mydashboard' },
];

NOTE: EVERYTHING EXECUTES FINE HERE, THE DASHBOARD DOES COME UP AND IT IS STORED IN <router-outlet name="mydashboard"></router-outlet> THE PROBLEM COMES WITH USING THE MENU.

When clicking on the "Clients" area, my expectation is that the "Client Information" will be placed into <router-outlet name="contentarea"> </router-outlet>  because of how home.component.html was defined.

home.component.html

[... snip ...]

                            <mdb-accordion-item-body>

   Press for clients

Link 2

                            </mdb-accordion-item-body>
                        </mdb-accordion-item>

[... snip ...]

        <router-outlet name="contentarea"> </router-outlet>

[... snip ...]

NOTE:
The processing does not go to: <router-outlet name="contentarea"> </router-outlet>

INSTEAD

It goes to: <router-outlet></router-outlet> located on page: app.component.html

QUESTION: Why does it do this? Am I doing it properly? Is there a better way?

I have looked at the following pieces of documentation

https://stackoverflow.com/questions/53702674/children-routing-not-working-and-application-redirects-to-the-404-page
https://www.tektutorialshub.com/angular/angular-child-routes-nested-routes/
https://stackoverflow.com/questions/52824639/nested-router-outlet-with-name-not-working
https://www.techiediaries.com/angular-router-multiple-outlets/
https://angular.io/guide/router

but have not found anything as of yet.

Any information or ideas would be greatly appreciated.

TIA

Body:
After research (I am new to Angular pretty much), I found that I needed to the following to resolve my problem:

Since I am working with "Lazy Loading", I made sure that the Routes defined in the xxx-routing.ts files were properly imported into the xxx-module.ts files (I missed this for the Dashboard setup)

I changed the Dashboard setup so that Children were used:

app-routing.module.ts

const routes: Routes = [
  { path: 'auth', loadChildren: './kdc/authorization/authorization.module#AuthorizationModule' },

  { path: 'dashboard', loadChildren: './kdc/dashboard/dashboard.module#DashboardModule'  },
  { path: '**' , component: PageNotFoundComponent }
];

dashboard.routing.module.ts

export const dashboardroutes: Routes = [

    { path: 'landing/:id', component: HomeComponent,
        children: [
            { path: 'clients', component: ClientsComponent, outlet: 'contentarea'  },
        ]},
];

I played around with different ways to see if the routers were working. It was during the "playaround time", that I found an answer that worked for me.

<!-- WORKS : http://localhost:4200/dashboard/landing/(contentarea:clients) -->

<!-- NOTES: GOES TO BASE HOME PAGE FOR DASHBOARD: http://localhost:4200/dashboard/landing -->

<!-- 404 RESULT: http://localhost:4200/dashboard/landing/landing
    <li>  <a [routerLink]="['landing',  { outlets: { contentarea : ['clients']}}] " mdbWavesEffect> Press for clients</a></li> -->

<!-- the one below WORKED:  http://localhost:4200/dashboard/landing/(contentarea:clients) -->
        <li>  <a [routerLink]="[{ outlets: { contentarea : ['clients']}}] " mdbWavesEffect> Press for clients</a></li>

I got rid of the <router-outlet name="mydashboard"><router-outlet> since it did not seem to be needed. I thought that the routers could work in a "sibling" relationship. Have learned that the relationship between different router-outlet definitions is more of a "parent-child" relationship.


问:
What can I use as a XACML PDP?
I have an API REST made in node js, and now I'd like to implement some XACML policy. I have been searching and I found that I can use ALFA to make the XACML rules. But I need a PDP for applying the rules. What can I use / how can I implement it?

I have read about WSO2 Identity Server (which I think I can use as a PDP? I'm not sure). It is probably too much for a little project. Any other suggestions? Or is WSO2 IS adecuate?

答: Adding to Buddhima Udaranga reply, If you think IS too much for a little project, then you can directly use balana, which is the entitlement engine used inside IS. You can refer to this for more details. But balana have only java API.</p>

Title: What can I use as a XACML PDP?


问:
SQL set column names from another query
I'm am using MS Reporting Services to graph some data from an Oracle database. I want to name the columns in my select statement with values from another select statement. Is this possible?

Like instead of

```<code>Select Column1 As 'Test' From Table1
</code>```

could I do something like

```<code>Select Column1 As (Select column2 from Table2 where Value = 1) From Table1
</code>```

?

答: I would think you'd have to query out separately, then form the query dynamically. Interested to see if there is a different answer.</p>

OwnerDisplayName: MaxGeek

Title: SQL set column names from another query

Body:
I'm am using MS Reporting Services to graph some data from an Oracle database. I want to name the columns in my select statement with values from another select statement. Is this possible?

Like instead of

Select Column1 As 'Test' From Table1

could I do something like

Select Column1 As (Select column2 from Table2 where Value = 1) From Table1

?

OwnerDisplayName: sfossen

ContentLicense: CC BY-SA 2.5


问:
upload a image and insert directly into CKEditor
I'd like to create the same kind of function tumblr has for uploading images and then inserting them directly into the WYSIWYG editor.

I was planning on using uploadify to upload the image, then I am not sure of the method for inserting into the CKEditor.

Has anyone done anything similar or know of a plugin that could do this? Ideally I'd like it to insert the image wherever the text cursor was last placed.

Upload an image and directly insert it into a text area http://www.freeimagehosting.net/uploads/06217dcebb.png

Thanks in advance,

Tim

答: I'm using nice plugin for CKeditor http://www.ckuploader.com</p>


问:
Python: How to compare two 2-dimension lists, process its values and store it in a new one?
I have the following lists:

```<code>TAKEOFF LIST:  [['EHAM', 55], ['EGLL', 46], ['LOWW', 44], ['LFPG', 43], ['LTBA', 38], ['EDDF', 37], ['LEMD', 34], ['EKCH', 33], ['EGKK', 31], ['LFPO', 30], ['LEBL', 28], ['LEPA', 28], ['LIRF', 25], ['EBBR', 25], ['ENGM', 23]]

LANDING LIST:  [['LEMD', 38], ['EDDM', 35], ['LEBL', 34], ['LFPO', 33], ['LFPG', 32], ['EKCH', 29], ['LTBA', 27], ['ENGM', 25], ['LSZH', 25], ['LTFJ', 24], ['LOWW', 23], ['EHAM', 23], ['EGKK', 22], ['EDDL', 22], ['ESSA', 21]]
</code>```

I want to compare both lists, if the first item for every row exist in both lists, then add it  to a new lists with both values and the sum of it.

Example output top 3 by the sum of its values:

```<code>OUTPUT_LIST: [['EHAM', 78, 55, 23], ['LFPG', 75, 43, 32], ['LOWW', 67, 44, 23]]
</code>```

Constraints: The final structure must be a lists of lists and this is just a simplified part of the original code. Actually the lists are composed from reading a file with thousands of lines (up to 500000).

答:
Lists are not really ideal for that kind of data. You should consider storing the data in e.g. dicts in the first place. However given input and output lists as above, we could first convert to dicts (using dict comprehensions) and then back to a double list using a list comprehension:

```<code>takeoffs = {k: v for k, v in takeoff_list}
landings = {k: v for k, v in landing_list}
output = [[k, v1+landings[k], v1, landings[k]] for k, v1 in takeoffs.items() if k in landings]
</code>```

Note that this code does not check for errors, e.g. for duplicate items in either list.

Body:
I have the following lists:

TAKEOFF LIST:  [['EHAM', 55], ['EGLL', 46], ['LOWW', 44], ['LFPG', 43], ['LTBA', 38], ['EDDF', 37], ['LEMD', 34], ['EKCH', 33], ['EGKK', 31], ['LFPO', 30], ['LEBL', 28], ['LEPA', 28], ['LIRF', 25], ['EBBR', 25], ['ENGM', 23]]

LANDING LIST:  [['LEMD', 38], ['EDDM', 35], ['LEBL', 34], ['LFPO', 33], ['LFPG', 32], ['EKCH', 29], ['LTBA', 27], ['ENGM', 25], ['LSZH', 25], ['LTFJ', 24], ['LOWW', 23], ['EHAM', 23], ['EGKK', 22], ['EDDL', 22], ['ESSA', 21]]

I want to compare both lists, if the first item for every row exist in both lists, then add it  to a new lists with both values and the sum of it.

Example output top 3 by the sum of its values:

OUTPUT_LIST: [['EHAM', 78, 55, 23], ['LFPG', 75, 43, 32], ['LOWW', 67, 44, 23]]

Constraints: The final structure must be a lists of lists and this is just a simplified part of the original code. Actually the lists are composed from reading a file with thousands of lines (up to 500000).

Body:
Lists are not really ideal for that kind of data. You should consider storing the data in e.g. dicts in the first place. However given input and output lists as above, we could first convert to dicts (using dict comprehensions) and then back to a double list using a list comprehension:

takeoffs = {k: v for k, v in takeoff_list}
landings = {k: v for k, v in landing_list}
output = [[k, v1+landings[k], v1, landings[k]] for k, v1 in takeoffs.items() if k in landings]

Note that this code does not check for errors, e.g. for duplicate items in either list.


问:
JAXB A cycle is detected in the object graph
I want to convert my pojo to json with JAXB, my pojo have one to many relation, and when i convert my pojo to json, JAXB generate error "A cycle is detected in the object graph. This will cause infinitely deep XML".

I read from web that, this problem can be solved with help from @XmlID and @XmlIDREF, but there is one problem, my Id attribute is not String type but Long. and as far as i know @XmlID can be used only with String property.

Other web suggest using eclipselink MOXy, but MOXy cannot generate json.

答:
I faced similar problem when I wanted to convert my POJO to JSON with JaxRS. The MoxyJsonProvider is the default option of eclipselink but it fails to parse the JSOG (where cycles exists in the JSON structure). Jackson Jaxb Provider does this better with ObjectMapper.

I have elaborated in this answer below, about how to invoke Jackson Provider instead of Moxy. You will need jackson packages in your pom xml.

https://stackoverflow.com/a/60319306/5076414


问:
Postgres group by having at least 1 row with status='started'
I need to perform a group by and only including if at least one observation matches the constraint. Like I have tried to describe below.

```<code>SELECT {some variables}
FROM my_table
GROUP BY A
HAVING {at least 1 row with status='started'}
</code>```

My initial guess to replace was "at least 1 row with status='started'" was "bool_or(status='started')". Which doesn't work.

Do any of you have a sugestion?

EDIT:

```<code>SELECT {some variables}
FROM my_table
GROUP BY A
HAVING bool_or(status='started');
</code>```

Works fine. The reason it not work for me, was that I used the wrong quotation mark. Thanks for your help and sorry for the inconvenience.

答:
having bool_or(status = 'started') is a nice option in Postgres, and probably your best pick here.

It is actually equivalent to:

```<code>having max( (status = 'started')::int ) = 1
</code>```

For the sake of completness: in standard SQL, you would phrase this with a case expression:

```<code>having max(case when status = 'started' then 1 end) = 1
</code>```

Body:
I need to perform a group by and only including if at least one observation matches the constraint. Like I have tried to describe below.

SELECT {some variables}
FROM my_table
GROUP BY A
HAVING {at least 1 row with status='started'}

My initial guess to replace was "at least 1 row with status='started'" was "bool_or(status='started')". Which doesn't work.

Do any of you have a sugestion?

EDIT:

SELECT {some variables}
FROM my_table
GROUP BY A
HAVING bool_or(status='started');

Works fine. The reason it not work for me, was that I used the wrong quotation mark. Thanks for your help and sorry for the inconvenience.

Body:
having bool_or(status = 'started') is a nice option in Postgres, and probably your best pick here.

It is actually equivalent to:

having max( (status = 'started')::int ) = 1

For the sake of completness: in standard SQL, you would phrase this with a case expression:

having max(case when status = 'started' then 1 end) = 1


问:
Absolute/outer and inner namespace confusion in C#
```<code>using Foo.Uber;

namespace MyStuff.Foo
{
    class SomeClass{
        void DoStuff(){
            // I want to reference the outer "absolute" Foo.Uber
            // but the compiler thinks I'm refering to MyStuff.Foo.Uber
            var x = Foo.Uber.Bar();
        }
    }
}
</code>```

How could I solve this? Just moving the using statement inside my namespace doesn't help.

答:
You can use using alias directives</p>

```<code>using Outer = Foo.Uber;

namespace MyStuff.Foo
{
    class SomeClass{
        void DoStuff(){
            var x = new Outer.Bar(); //outer class
        }
    }
}
</code>```

Body:
using Foo.Uber;

namespace MyStuff.Foo
{
    class SomeClass{
        void DoStuff(){
            // I want to reference the outer "absolute" Foo.Uber
            // but the compiler thinks I'm refering to MyStuff.Foo.Uber
            var x = Foo.Uber.Bar();
        }
    }
}

How could I solve this? Just moving the using statement inside my namespace doesn't help.

Body:
You can use using alias directives

using Outer = Foo.Uber;

namespace MyStuff.Foo
{
    class SomeClass{
        void DoStuff(){
            var x = new Outer.Bar(); //outer class
        }
    }
}


问:
Wordpress returns incorrect image URL for downsized images
I'm experiencing an error regarding in relation to wp_get_attachment_image_src, where I'm not receiving the image size I need to.

I'm setting the following sizes in my functions.php-file:

```<code>// Image Sizes
add_image_size('wide', 1344, 378, true);
add_image_size('mobile', 480, 360, true);
</code>```

However, the frontend isn't giving me the correct URL for mobile or array('480','360'):

```<code>print_r(wp_get_attachment_image_src($id));
> Array ( [0] => http://localhost:8888/wp-content/uploads/stockmann-150x150.jpg [1] => 150 [2] => 150 [3] => 1 )

print_r(wp_get_attachment_image_src($id, 'mobile'));
> Array ( [0] => http://localhost:8888/wp-content/uploads/stockmann.jpg [1] => 480 [2] => 290 [3] => )

print_r(wp_get_attachment_image_src($id, array('480','360')));
> Array ( [0] => http://localhost:8888/wp-content/uploads/stockmann.jpg [1] => 480 [2] => 290 [3] => )

print_r(wp_get_attachment_image_src($id, 'wide'));
> Array ( [0] => http://localhost:8888/wp-content/uploads/stockmann-1344x378.jpg [1] => 1344 [2] => 378 [3] => 1 )
</code>```

I've set $content_width = 1344; in functions.php before I declare my image sizes.

Also, I checked to see that the image exists which it does:

I have absolutely no idea how to solve this.

答: I had WPML translations installed and therefore needed to regenerate thumbnails for all the different languages, not only for english.</p>

Body:
I'm experiencing an error regarding in relation to wp_get_attachment_image_src, where I'm not receiving the image size I need to.

I'm setting the following sizes in my functions.php-file:

// Image Sizes
add_image_size('wide', 1344, 378, true);
add_image_size('mobile', 480, 360, true);

However, the frontend isn't giving me the correct URL for mobile or array('480','360'):

print_r(wp_get_attachment_image_src($id));
> Array ( [0] => http://localhost:8888/wp-content/uploads/stockmann-150x150.jpg [1] => 150 [2] => 150 [3] => 1 )

print_r(wp_get_attachment_image_src($id, 'mobile'));
> Array ( [0] => http://localhost:8888/wp-content/uploads/stockmann.jpg [1] => 480 [2] => 290 [3] => )

print_r(wp_get_attachment_image_src($id, array('480','360')));
> Array ( [0] => http://localhost:8888/wp-content/uploads/stockmann.jpg [1] => 480 [2] => 290 [3] => )

print_r(wp_get_attachment_image_src($id, 'wide'));
> Array ( [0] => http://localhost:8888/wp-content/uploads/stockmann-1344x378.jpg [1] => 1344 [2] => 378 [3] => 1 )

I've set $content_width = 1344; in functions.php before I declare my image sizes.

Also, I checked to see that the image exists which it does:

I have absolutely no idea how to solve this.