text:
Q: Is there a good general methodology for wrapping swig generated classes in ruby? I have used SWIG to generate wrappers for a C++ library that I am going to be using in ruby.
Since it was a C++ library the method names are not "ruby like", ie they are camelCase for example. I also will need to add some of my own methods, operators for example.
So I was thinking about creating ruby classes to wrap the SWIG classes, but wanted to keep it simple.  Here is what I was thinking of doing, unless someone can point me in a better direction.
I created this "method wrapper" method which I would use to call the corresponding swig generated method from it's corresponding ruby meth in the new ruby class.
I am making use of ruby's scheme of getting the method via
some_method = SomeClass.method(:some_method_name)

and then calling it later on via
some_method.call

Are there any issues with that plan?
Here is my method wrapper method:
def method_wrapper(target_method, hash_keys,  args=[])
 if args.length == 0
    #puts "calling without args"
    return_value = target_method.call
 else
    if args[0].class == Hash
      method_args = Array.new
      hash_args = args[0]
      hash_keys.each do |key|
        arg_value = hash_args[key]
        method_args << arg_value if arg_value
      end
      #puts "calling with hash args #{method_args}"
      return_value = target_method.call(*method_args)
    else
      #puts "calling with args"
      retrun_value = target_method.call(*args)
    end
  end
  return return_value
end

and here is how I would use it to wrap each method in the SWIG generated class
class RubyClassName
  def ruby_method_name(*args)
    return method_wrapper(Swig_module_name::SwigClassName.method(:swigMethodName), [:ruby_hash_key_arg1, :ruby_hash_key_arg2], args)
  end
end

then I can call the methods like such
RubyClassName.ruby_method_name
RubyClassName.ruby_method_name some_value
RubyClassName.ruby_method_name(some_value1, some_value2)
RubyClassName.ruby_method_name :ruby_hash_key_arg1 => some_value
RubyClassName.ruby_method_name :ruby_hash_key_arg2 => some_value2, :ruby_hash_key_arg1 => some_value1

A: You can use %rename directive for renaming C++ classes and functions to something else (for example, rename FooBar to fooBar or foo_bar).
You can use %extend to add your own operators and such.
I believe the above will support all the call examples you had, without needing a second layer of wrapping.


text:
Q: FragmentPagerAdapter - How to handle Orientation Changes? I use a FragmentPagerAdapter containing several Fragments that need to be notified about changes to the database. I  do this by iterating over the fragments, which implement a callback interface, and calling a refreshData() method.
This works just fine until the device changes orientation. After an orientation change, the fragment UI does not visibly refresh even though the method call seems to work.
From what I have read so far this occurs because the FragmentPagerAdapter handles the fragment life-cycle and the fragments that receive the callback are not the ones that are actually displayed.
private class DataPagerAdapter extends FragmentPagerAdapter {

    private DataFragment[] fragments = new DataFragment[] {
                                     new FooDataFragment(), BarDataFragment()};

    public DataPagerAdapter(android.support.v4.app.FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        return fragments[position];
    }

    @Override
    public int getCount() {
        return fragments.length;
    }

    public DataFragment[] getFragments() {
        return fragments;
    }
}

protected void refreshData() {
    for (DataFragment dataFragment : mPagerAdapter.getFragments()) {
     dataFragment.refreshData();
}

I temporarily fixed this issue using a broadcast receiver inside each fragment, but this solution seems to be wasteful and might create memory leaks. How to I fix this properly? I use a different layout and logic in landscape mode so I want to use the newly created fragments after an orientation change.

A: Yes like you said FragmentManager handles fragments after orientation change so getItem in adapter is not called. But you can override method instantiateItem() which is called even after orientation change and cast Object to Fragment and save it in your array.
 @Override
 public Object instantiateItem(ViewGroup container, int position) {
     DataFragment fragment = (DataFragment) super.instantiateItem(container, position);
     fragments[position] = fragment;
     return fragment;
 }

A: Could not you just set the android:configChanges flag on your Activity in AndroidManifest.xml to prevent activity to be recreated?
<activity
    android:name="com.example.test.activity.MainActivity"
    android:configChanges="orientation|screenSize|keyboardHidden"/>

also there you can find more possibilities:
https://android.jlelse.eu/handling-orientation-changes-in-android-7072958c442a

A: I recreated the pager adapter in the onResume method:
override fun onResume() {
    super.onResume()
    val viewPager = findViewById<ViewPager>(R.id.my_view_pager)
    viewPager.adapter = MyPagerAdapter(supportFragmentManager)
}

A: I had similar problem my working solution:
In activity where is an adapter call adapter.notifyDataSetChanged();
override getItemPostion() method in your adapter
@Override
    public int getItemPosition(Object object) {
        MyFragment frag = (MyFragment)object;
        frag.refresh();
        return POSITION_UNCHANGED;
    }

my FragmentStatePagerAdapater (my adapter) contains only one type of fragment, but I am think, that you could use instanceof (for more types of Fragments) and then use cast or every fragment will implement Interface with method refresh()
Then add method refresh() in your Fragment(s) and use this implementation:
public void refresh() {
        LayoutInflater inflater = LayoutInflater.from(getActivity());
        ViewGroup viewGroup = (ViewGroup) getView();
        viewGroup.removeAllViewsInLayout();
        View view = onCreateView(inflater, viewGroup, null);
        viewGroup.addView(view);

    }

This worked for me.
My opinion:
The problem has came, when the device change orientation, adapter is destroyed, but the fragments are still in memory and system try to reuse them after orientation change, but the views which are contains in the fragments are destroyed too and fragments needs to be "recreate" (call onCreateView method ). Maybe I am wrong, so please correct me... .
(Sorry for my english )

redpajama_set_name: RedPajamaStackExchange


text:
Q: Proof of Fixed Point for nonlinear systems in Pazy's Semigroups of linear operators and applications to PDEs book In Theorem 1.2 of Pazy's book called Semigroups of linear operators and applications to PDEs, a fixed point method is used to show that the nonlinear problem has a solution. The map $F:C([t_0,T];X) \to C([t_0, T];X)$ is defined by
$$(Fu)(t)=T(t-t_0)u_0 + \int_{t_0}^t T(t-s) f(s,u(s)) ds, t_0 \leq t\leq T.$$
Using the assumption that
$$\|T(r)v\|_X \leq M\|v\|_X$$
for all $r \in [0,T]$ and the fact that $f$ is continuous in $t$ and uniformly Lipshitz continuous with constant $L$ on $X$, Pazy shows
$$\|(Fu)(t)-(Fv)(t)\| \leq ML(t-t_0)\|u-v\|.$$
This part is understandable to me. He then says using this inequality and the definition of $F$ you can show using induction that
$$||(F^nu)(t)-(F^n)v(t)||\leq \frac{(ML(t-t_0))^n}{n!}||u-v||.$$
To me this part is clear without the factorial, but I am not sure how we get the bound divided by $n!$. I'm assuming it has something to do with the properties of $T(t)$ since $T(t)$ is a $C_0$ semigroup, but I still don't see it. Does anyone have any ideas where this came from?


text:
Q: Codeigniter - Pagination not working correctly I'm having some problems with codeigniter and the pagination. The problem is that I get all the results/posts on all pages.
Here is my code:
<?php

class Posts extends CI_Controller{

function __construct(){
    parent::__construct();
    $this->load->model('post');
}

function index(){
    $data['posts'] = $this->post->get_posts();
    $this->load->library('pagination');
    $config['base_url']= base_url() .'posts/index/';
    $config['total_rows']= $this->post->get_number_of_posts();
    $config['per_page']=1;
    $this->pagination->initialize($config);

    $data['pages']=$this->pagination->create_links();
    $this->load->view('index_blog', $data);

}} ?>

What could possible be wrong ?
Thanks in advance.

A: Add This to Controller start and limit to your model function argument
$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
$data['posts'] = $this->post->get_posts($config["per_page"], $page);

And following to model function get_posts
 $this->db->limit($limit, $start);


text:
Q: Cisco multi switch / multi VLAN monitoring I have a DMZ and a internal LAN with VLANs that I wish to port monitor by means of a NIDS and three switches, if this is possible.

*

*Switch 1 (DMZ) 2950 / VLAN 10 & trunk port to Switch 3

*Switch 2 (LAN) 2950 / VLAN 20 & truck port to switch 3

*Switch 3 (MON) 2960 / trunk ports for both VLAN 10/20 & access port
designated for both VLANs

Now, from what I understand, as long as the trunking between DMZ & LAN switches to the MON switch is correct I should be able to configure SPAN to monitor both those VLANs to a designated port on the MON switch.
Or am I really really off on this?


text:
Q: Installing CodeIgniter I am wanting to install CodeIgnitor on my hosting account, but I'm a little confused.
The documentation says:

"CodeIgniter is installed in four
  steps:
1.Unzip the package.
2.Upload the CodeIgniter folders and files to your server. Normally the
  index.php file will be at your root.
3.Open the application/config/config.php file
  with a text editor and set your base
  URL.   If you intend to use encryption
  or sessions, set your encryption key."

I'm having trouble getting my head around No. 2; It says to chuck everything into the root dir of my server, which is fine, I can do that, BUT, the codeigniter files that I upload also has an index.php page.
And my website files are also located in the root folder. If I upload all the codeigniter files to my root dir, and replace the default index.php file that codeigniter tells me to upload with my own websites index.php file? Is that what you're supposed to do?
Thanks :)

A: If you are using your current website, you may not want to replace the index.php until your new website is ready to go live.  If you are trying to tie the two together, I recommend fully porting your current website in to CodeIgniter if at all possible.
Otherwise, I recommend installing CodeIgniter in a folder under the root directory and modifying its config file to point to it.

A: another way of doing this is to first through your control panel is to create a subdomain like myci.yoursite.com, and select the folder for it as /var/www/myci (which would usually be automatic)
upload unzipped codeigniter files in /var/www/myci.  if any default index.php is created there it is usually safe to overwrite it.  if any default index.html etc is created you may have to delete them.  any cgi-bin etc can be safely left untouched.
you should be able to see your site as http://myci.yoursite.com/
one of the first things you should do is edit your system/application/config/config.php and correct the $config['base_url']

A: Please note that the CI index page is a config page, not a welcome page.  Your "real" index page is NOT the index page that you are thinking it is.
Your site address should be like this
www.sitename.com/index.php/main
main is simply the controller name that calls the opening page.(I use main, you can use any name you want)
if Main is your controller that points to the opening page,m you would name youre first function in the main controller "index"
Class Main extends controller{
function index(){
$this->load->view('main page name');
}
}

All pages views in CI are called by a controller, there are no free floating pages

A: First of all back up all your existing files in your root folder, Install Codeigniter following the guide which is located at
https://ellislab.com/codeigniter/user-guide/installation/.
Your index.php file is different when compared with Codeigniter index.php file, Codeigniter uses index.php file as a config file to set the required paths and to load different classes including Router, this way the default Welcome page is loaded indicating proper installation of Codeigniter.
You can later place the application and system folder out of your public directory, while changing the settings in Codeigniter's index.php  file


text:
Q: Gulp within Visual Studio 2015 does not run angular2-template-loader I'm trying to get a basic webpack-powered build working in VS2015 for an Angular 2 app. I'm using Gulp to trigger the webpack process (VS2015 has hooks that work well with gulp - webpack does all the heavy lifting in my case)
Here's the problem - when I use the VS2015 build process to trigger gulp (via 'after build' hook), the angular2-template-loader does not run. I'm expecting to see the templateUrl replaced with in-line mark-up, but it still references my template files. When I run gulp via command line, the angular2-template-loader seems to run and do its work.
Here's what I've tried:

*

*Running webpack straight from the command line gives me the desired result - which leads me to believe my webpack config is correct

*Running gulp straight from the command line gives me the desired result

*I've researched to see if there are any 'hidden' parameters VS uses that would cause different results as well as if VS was tied to a particular version of gulp. As far as I can tell, there are no hidden params or version dependencies.
For reference, here are my gulp and webpack configs as well as the bad output and expected output:
https://gist.github.com/scotmeiste/b9b91dcda13a896e771be0da5d89255c
On the output files, look at the templateUrl/template properties towards the bottom.

A: tldr: VS2015 auto compiles TypeScript files by default, and this caused undesired results with the Gulp typescript build. Adding the following to the first <PropretyGroup> node in the project file corrected the issue:
<TypeScriptCompileBlocked>true</TypeScriptCompileBlocked>
Details
By default, Visual Studio will compile your TypeScript files, but only when you do a full rebuild. This explains why some of my changes in my TS file were not being propagated. The result of this was that my app directory would get filled with the output from the Visual Studio TS build, but not every time i would make a change.
When gulp would trigger the 2nd TypeScript build, I believe it would see the [bad] out put from the VS-triggered build and use those files, even though they were potentially out-of-date. They also didn't have the benefit of the angular2-template-loader process since VS only cares about running the TypeScript build.
Solutions

*

*First solution is mentioned in the tldr - add the option to stop TypeScript Compilation.

*Use another editor that will play nicer with gulp and webpack.

*(untested) set the output in the TS config to match the output destination in your gulp file - not sure if this would resolve the issue with the angular2-template-loader not working.


text:
Q: Is Ubuntu 12.04 still stable today? I installed Ubuntu 14.04 in my HP Pavilion g6-1030se laptop, but I have a problem in developing java games. My laptop became slow. Is it ok if i go back to Ubuntu 12.04? Is it still stable today?

A: Ubuntu 12.04 is still stable, and will be fully supported and updated until April 2017


text:
Q: iBeacon - Disconnecting I'm trying to configure some iBeacons. I have the Locate app by Radius and the LightBlue. But in both apps, the Beacons keeps disconnecting. On LightBlue it disconnects a few seconds after I connect.
On Locate it connects (or no?) but my distance range keeps ranging from excellent to not detected.
What configs should I do?
Thanks

A: The issue may be that your beacon is not transmitting frequently enough.  Beacons transmit at different frequencies from 10 Hz (good) down to 0.2 Hz or less (bad).  Some manufacturers of battery powered beacons make them transmit infrequently so the battery lasts longer.  This has serious impacts on ranging and distance estimates because so few samples of signal strength are available.


text:
Q: how to create Definition via REST API with Send Classification of type = Commercial? I am trying to use an existing send classification and use it for the creation of a Send definition.
But getting the following error:
{
"message": "MCMS_UTM_Validation_InvalidValue_classification_IncorrectType: Classification must have type of transactional",
"errorcode": 10000,
"documentation": ""
}

How do I create a Definition via REST API with Send Classification of type Commercial?

A: Check this documentation, you can see the existing types in the sample code. I would try "Marketing" as the type.
https://developer.salesforce.com/docs/atlas.en-us.noversion.mc-apis.meta/mc-apis/creating_a_send_classification.htm


text:
Q: In eslint hide errors with variables which are not used at this moment In my @vue/cli 4.1.1 app on installation in file .eslintrc.js I have options
module.exports = {
  root: true,
  env: {
    node: true
  },
  'extends': [
    'plugin:vue/essential',
    'eslint:recommended'
  ],
  rules: {
    'no-console': process.env.NODE_ENV === 'production' ? 'off' : 'off',
    'no-debugger': process.env.NODE_ENV === 'production' ? 'off' : 'off'
  },
  parserOptions: {
    parser: 'babel-eslint'
  }
}

and it works ok for me, expect it shows error with variables which are not used at this moment
If there is a way to remove only this option, leaving the rest of options ?
Thanks!

A: You can add this line : 'vue/no-unused-vars': process.env.NODE_ENV === 'production' ? 'error' : 'off'
This will disable the rule when developing but throw an error when you try to build for production.
If you to disable the rule anytime put this instead : 'vue/no-unused-vars': 'off'
module.exports = {
  root: true,
  env: {
    node: true
  },
  'extends': [
    'plugin:vue/essential',
    'eslint:recommended'
  ],
  rules: {
    'no-console': process.env.NODE_ENV === 'production' ? 'off' : 'off',
    'no-debugger': process.env.NODE_ENV === 'production' ? 'off' : 'off',
    'vue/no-unused-vars': process.env.NODE_ENV === 'production' ? 'error' : 'off'
  },
  parserOptions: {
    parser: 'babel-eslint'
  }
}


text:
Q: Make oneboxing work for comments in chat
Possible Duplicate:
Add chat oneboxing support for comment links

As the title says, now that comments are linkable, I would like them to be oneboxed to appear similar to this one, when they are linked in the chat.


text:
Q: How do you show an alert view for push notifications if the app is not in the foreground or background in iOS? I know how to show a push notifications UIAlertView if the app is in the background or foreground using the following code:
(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
    NSString *message = [ [userInfo objectForKey:@"aps"]
                         objectForKey:@"alert"];
    UIAlertView *alert = [ [UIAlertView alloc]
                            initWithTitle:@""
                            message:message
                            delegate:nil
                            cancelButtonTitle:@"OK"
                            otherButtonTitles:nil];
    [alert show];
}

However, I also want to show an alert view if the app was completely closed and the user wants to open the app via the push notifications.
How can I achieve this?
Thanks

A: When application launches as a result of a push notification, in other words, when the app was not running, you need to handle that case in [AppDelegate application:didFinishLaunchingWithOptions:] method.
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    NSDictionary *notification = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];

    if (notification) {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Push Notification" message:notification[@"aps"][@"alert"] delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [alertView show];
    }
}

If the app is in background or foreground (active) state, you need to handle that case in [AppDelegate application:didReceiveRemoteNotification:fetchCompletionHandler:] method.
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult result))handler
{
    if (application.applicationState == UIApplicationStateActive) {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Push Notification" message:userInfo[@"aps"][@"alert"] delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];

        [alertView show];
    }
    else if (application.applicationState == UIApplicationStateBackground || application.applicationState == UIApplicationStateInactive) {
        // Do something else rather than showing an alert view, because it won't be displayed.
    }
}

For more information, you can take a look at Local and Remote Notification Programming Guide from Apple.


text:
Q: Why isn't my SwiftUI transition animating? I have a view based on a few state variables. These states are set by the completion block of an API call. The bookings are displayed as a ForEach list and I want them to appear with the slide transition.
The slide transition worked perfectly. Since I added the !isLoading check, these animations no longer display. All the animations that appear now are the fade in/out of the ProgressView. When removing the !isLoading check, the staggered slide animation comes back, but I want to keep this check so I can properly handle loading states.
Here is a standalone code to reproduce the issue:
import SwiftUI

struct RoomView: View {

    @State private var room: String?
    @State private var bookings: [String]?
    @State private var isLoading: Bool = false

    var body: some View {
        VStack(spacing: 0) {
            if /* This is the problematic condition !isLoading, */ let room = self.room {
                ScrollView {
                    LazyVStack(alignment: .leading) {
                        Text(room)

                        if let bookings = bookings {
                            ForEach(bookings.indices) { (index) in
                                let booking = bookings[index]
                                VStack(alignment: .leading) {
                                    Text(booking)
                                    Divider()
                                }
                                .transition(.slide)
                                // Stagger the animations when displaying the list
                                .animation(Animation.spring().delay(0.04 * Double(index)))
                            }
                        }
                    }
                    .padding()
                }
            } else {
                // If we're loading
                ProgressView("Loading Room")
            }
        }
        .transition(.opacity)
        .animation(.easeInOut)
        .onAppear {
            self.isLoading = true
            DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
                self.room = "Demo room"
                DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
                    withAnimation {
                        self.bookings = ["Booking 1", "Booking 2", "Booking 3", "Booking 4", "Booking 5"]
                        self.isLoading = false
                    }
                }
            }
        }
    }
}

struct RoomView_Previews: PreviewProvider {
    static var previews: some View {
        RoomView()
    }
}

Is there a known issue with SwiftUI animations where having multiple conditions could cause transitions to not appear? How can I fix this so I keep my staggered animation & fade of the ProgressView transitions without removing the !isLoading check?

A: Here is possible solution - make views independent. Tested with Xcode 12 / iOS 14.

struct RoomView: View {

    @State private var room: String?
    @State private var bookings: [String]?
    @State private var isLoading: Bool = false

    var body: some View {
        ZStack {
            if isLoading {
                // If we're loading
                ProgressView("Loading Room")
            }
            if let room = self.room {
                ScrollView {
                    LazyVStack(alignment: .leading) {
                        Text(room)

                        if let bookings = bookings {
                            ForEach(bookings.indices) { (index) in
                                let booking = bookings[index]
                                VStack(alignment: .leading) {
                                    Text(booking)
                                    Divider()
                                }
                                .transition(.slide)
                                // Stagger the animations when displaying the list
                                .animation(Animation.spring().delay(0.04 * Double(index)))
                            }
                        }
                    }
                    .padding()
                }
            }
        }
        .transition(.opacity)
        .animation(.easeInOut)
        .onAppear {
            self.isLoading = true
            DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
                self.room = "Demo room"
                DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
                    withAnimation {
                        self.bookings = ["Booking 1", "Booking 2", "Booking 3", "Booking 4", "Booking 5"]
                        self.isLoading = false
                    }
                }
            }
        }
    }
}


text:
Q: XML Schema - multiple child elements are possible, but have unique values So I have a "hotel" root element which contains an element "rooms".
Inside the rooms element, there must be a list of present rooms:
<?xml version="1.0"?>
<h:hotel xmlns:h="hotel">
    <existingRooms>
        <room>101</room>
        <room>102</room>
        <room>201</room>
    </existingRooms>
</h:hotel>

multiple rooms with the same roomnumber should be illegal:
<?xml version="1.0"?>
<h:hotel xmlns:h="hotel">
    <existingRooms>
        <room>101</room>
        <room>102</room>
        <room>201</room>
        <room>201</room>
    </existingRooms>
</h:hotel>

When I try to do this with , the validator only accepts one room, which is obviously not my goal:
<?xml version="1.0"?>
<schema xmlns="http://www.w3.org/2001/XMLSchema"
    xmlns:h="hotel"
    targetNamespace="hotel">
    <element name="hotel">
        <complexType>
            <sequence>
                <element name="existingRooms">
                    <complexType>
                        <sequence>
                            <element name="room" type="integer" maxOccurs="unbounded"/>
                        </sequence>
                    </complexType>
                </element>
            </sequence>
        </complexType>
        <unique name="inuqueRoomNumber">
            <selector xpath="existingRooms"/>
            <field xpath="room"/>
        </unique>
    </element>
</schema>

What can be the solution for this issue?

A: Change
    <unique name="inuqueRoomNumber">
        <selector xpath="existingRooms"/>
        <field xpath="room"/>
    </unique>

to
    <unique name="inuqueRoomNumber">
        <selector xpath="existingRooms/room"/>
        <field xpath="."/>
    </unique>


text:
Q: How do I figure out all the global imports and from where are those imported? when I add the following line at the beginning of app.ts
const crypto = require('crypto');

I get the following error,

Cannot redeclare block-scoped variable 'crypto'

Seems like it has been globally imported from somewhere else,
this is how my tsconfig.json looks like
{
  "compilerOptions": {
    "allowJs": true,
    "outDir": "./dist",
    "target": "ES6",
    "module": "commonjs",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "removeComments": true,
    "noImplicitAny": false,
    "strictNullChecks": true,
    "noUnusedLocals": true,
    "types": [
      "node"
    ],
    "typeRoots": [
      "./node_modules/@types"
    ],
    "lib": ["es2015", "dom"]
  },
  "include": [
    "./src/"
  ]
}

PS:
The above error is when I try to transpile it from terminal.
I am using VisualStdioCode, in VisualStdioCode it doesn't show any error as it points to,

/path/to/VisualStdioCode/Visual Studio
  Code.app/Contents/Resources/app/extensions/typescript/node_modules/typescript/lib/lib.dom.d.ts

EDIT(solved):
The problem here was slightly different than cannot redeclare block scoped variable (typescript)
The aim of this question was to detect duplicate import source than use ES6 non explicit assignment to atomatically solve it for us.
The solution here was to import either from libs or node_modules and not to scope it unlike mentioned in answers there.

A: crypto is already a global read-only property in the browser, so TypeScript is keeping you from trying to overwrite it.
https://developer.mozilla.org/en-US/docs/Web/API/Window/crypto
But since you're using commonJS, you may be building for Node and maybe you didn't mean to include the "dom" typings in "lib"?


text:
Q: Get the full http response in case of an error In angular documentation they stated that you have to specify observe: "response" on the provided options to get the full http response, which I did here:
constructor(private service: new () => T,
  private http: HttpClient,
  private httpErrorHandler: HttpErrorHandlerService,
){
    this._handleError = this.httpErrorHandler.createHandleError(this.service.name);
}
private _handleError: HandleError;
//...other code
delete(resourceNameOrId: number | string): Observable<HttpErrorResponse>{
    return this.http.delete<T>(this._url + resourceNameOrId, {
      observe: "response"
    }).pipe(
      catchError(this._handleError(`delete`, null))
    );
  }

The handleError function is defined in this service:
export type HandleError = <T> (operation?: string, result?: T) => (error: HttpErrorResponse) => Observable<T>;

@Injectable({
  providedIn: 'root'
})
export class HttpErrorHandlerService {

  constructor(private errorService: ErrorService, private modalService: NzModalService) { }

  createHandleError = (serviceName = '') => <T> (operation = 'operation', result = {} as T) => this.handleError(serviceName, operation, result);

  handleError<T> (serviceName = '', operation = 'operation', result = {} as T ){
    return (error: HttpErrorResponse): Observable<T> => {
      const message = (error.error instanceof ErrorEvent) ? error.error.message: `{error code: ${error.status}, body: "${error.message}"}`;
      this.errorService.errorMessage = `${serviceName} -> ${operation} failed.\n Message: ${message}`;
      console.error(this.errorService.errorMessage);
      return of(result);
    }
  }
}

And this is an example of how I call my service delete function in a component:
this.service.delete(nom).subscribe(data => {
  if(!this.errorService.errorMessage){
    this.notificationService.success("Suppression", "L'enregistrement a été supprimée !");
  }
});

But specifying the observe: "response" didn't work in my case, and the error: HttpErrorResponse only returns the error message and not the full response :

I have tried solutions in this thread : Angular 4.3.3 HttpClient : How get value from the header of a response? which didn't work for me, and the provided solution was to define the observe option.
How can I solve this ?
Update:
The the observe option only works when the delete http request returns a 200 code as shown in screenshot below, but when there is a 404 response status the response object in this case is null, and in the handleError function the response body is the only thing I can access to.

A: If you want the HttpErrorResponse object inside your catchError, try to get it inside the block after the api call is completed, something like this:
delete(resourceNameOrId: number | string): Observable<HttpErrorResponse>{
    return this.http.delete<T>(this._url + resourceNameOrId)
 .pipe(
      catchError((error:any)=>{
           console.log(error);//error is the HttpErrorResponse object returned
           return this._handleError(`delete`, null)
      })
    );
  }

A: Is it fit to you to intercept the HttpClient hook via Interceptor?
Try something Like this:
Create an Interceptor:
@Injectable()
export class FinalInterceptor implements HttpInterceptor {

constructor(private errorHandlerService: HttpErrorHandlerService) {}

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
      return next.handle(req).pipe(
        tap((event: HttpEvent<any>) => {
            if (event instanceof  HttpErrorResponse) {
              this.errorHandlerService.handleError(event);
            }
        }));
  }
}

AppModule:
providers: [
    ...
    { provide: HTTP_INTERCEPTORS, useClass: FinalInterceptor, multi: true },
  ],

so in my handler service on http errors i've got
next console.log.
i suppose this is exactly what you looking for


text:
Q: Why is this jni error occuring when running a jar file, packaged by sbt? I have a project that runs fine inside the IDE, but for some reason I can't run the packaged jar from the command line.
This is what my build.sbt looks like:
import sbt.io.Using

name := "bigdata-mx-2"

version := "0.1"

scalaVersion := "2.12.7"

libraryDependencies ++=Seq(
  "junit" % "junit" % "4.10" % Test,
  "org.scalatest" %% "scalatest" % "3.2.0-SNAP10" % Test,
  "org.apache.parquet" % "parquet-avro" % "1.10.0",
  "org.apache.hadoop" % "hadoop-common" % "3.1.1"
)

packageOptions in (Compile, packageBin) +=  {
  val file = new java.io.File("META-INF/MANIFEST.MF")
  val manifest = Using.fileInputStream(file)( in => new java.util.jar.Manifest(in) )
  Package.JarManifest( manifest )
}

I do sbt compile, package and get a jar file. when I run it by doing java -jar myjar.jarI get:
Error: A JNI error has occurred, please check your installation and try again
Exception in thread "main" java.lang.NoClassDefFoundError: scala/Function0
        at java.lang.Class.getDeclaredMethods0(Native Method)
        at java.lang.Class.privateGetDeclaredMethods(Unknown Source)
        at java.lang.Class.privateGetMethodRecursive(Unknown Source)
        at java.lang.Class.getMethod0(Unknown Source)
        at java.lang.Class.getMethod(Unknown Source)
        at sun.launcher.LauncherHelper.validateMainClass(Unknown Source)
        at sun.launcher.LauncherHelper.checkAndLoadMain(Unknown Source)
Caused by: java.lang.ClassNotFoundException: scala.Function0
        at java.net.URLClassLoader.findClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        ... 7 more

Why is this happenig and how can I resolve this problem?


text:
Q: How to make vi redraw screen? When I use
git commit --amend

It will enter into a vi window to let me input comments for commit, the problem is the vi windows will show some dirty characters from former shell background. So I wonder how can I let vi to reload or redraw the screen to make the screen normal.
So far, I try reset terminal and Ctrl+L, it works, but I wonder is there best answer for such situation?

A: In Vi both of these are redraw:

*

*^R ( does not work with VT100 type terminals )

*^L ( does not work with Televideo terminals )

From http://www.cs.rit.edu/~cslab/vi.html#A1.4 (dead link; see archive)
As noted in the comments Vim now uses ^R for redo and ^L alone for redraw.

A: To force a screen refresh
:redraw!

A: If your terminal supports it, ctrl+L is a common shortcut for this.


text:
Q: Interchanging $\limsup$ and $\sup$ Let $f_n: \mathcal{X} \to [0,1]$ be a sequence of functions and $\alpha \in (0,1)$.
I want to show that
$$
\limsup_{n \to \infty} \sup_{x \in \mathcal{X}} f_n(x) \leq \alpha
$$
implies
$$
\sup_{x \in \mathcal{X}} \limsup_{n \to \infty} f_n(x) \leq \alpha
$$
but my $\limsup$'s are a little rusty. Any tips?

A: Suppose $$\sup_{x\in X}\limsup_{n\to \infty }f_n(x)>\alpha .$$
Then, there is $y\in X$ s.t. $$\limsup_{n\to \infty }f_n(y)>\alpha ,$$
i.e. there is $N$ s.t. $$\sup_{k\geq n}f_k(y)>\alpha.$$ for all $n\geq N$.
But $$f_k(y)\leq \sup_{x\in X}f_k(y),$$ i.e., if $n\geq N$ $$\alpha <\sup_{k\geq n}f_k(y)\leq \sup_{k\geq n}\sup_{x\in X}f_k(x).$$
Therefore $$\limsup_{n\to \infty }\sup_{x\in X}f_n(x)>\alpha .$$
Contradiction.

A: Consider, for each $n$, $$m_n=\sup_{x \in \mathcal{X}} f_n(x)$$ Then, for every $x$ in $\mathcal X$ and every $n$, $$f_n(x)\leqslant m_n$$ hence, for each given $x$ in $\mathcal X$, $$\limsup\limits_{n\to\infty}f_n(x)\leqslant\limsup\limits_{n\to\infty}m_n$$ This inequality holds for every $x$ in $\mathcal X$, hence, as desired, $$\sup_{x\in\mathcal X}\limsup\limits_{n\to\infty}f_n(x)\leqslant\limsup\limits_{n\to\infty}m_n$$


text:
Q: regex to find acronyms inside parentheses I am trying to develop a regex to match acronyms inside parentheses.
regex = r"\(\b[A-Z][a-zA-Z\.]*[A-Z]\b\.?\)"

This is what I have so far, it works for almost but not all cases. The case where an acronym is on its own line (not preceded or proceeded by any other characters) is also getting matched by this regex even if it is not surrounded by parentheses.
input it should match:
Any acronym in parentheses IE:
(ADF)
Input it shouldn't match but it is:
An acronym on it's own line IE:
ADF
Any idea what I have done wrong?

A: here's what I have so far.  I'm using an "extension notation" to capture the acronym.  The pattern is basically r"\([A-Z]\w*[A-Z]\)" otherwise.
tst1="this is (ADF) a test"
tst2 = "This is is ADF a test, too."

# Newline tests
tst3 = "\n(ADF)\n"
tst4 = "\nADF\n"

# Upper/lowercase test.
tst5 = "This is (AdF) a test."
tst6 = "This is (Adf) a test."

def retest(testcase):
    res = re.search(r"(?P<acronym>\([A-Z]\w*[A-Z]\))", testcase)
    if res:
        print(res.group("acronym"))

retest(tst1) # (ADF)
retest(tst2) # None

retest(tst3) # (ADF)
retest(tst4) # None

retest(tst5) # (ADF)
retest(tst6) # None


text:
Q: Transformer/BERT token prediction vocabulary (filtering the special tokens out of the set of possible tokens) With the Transformer model, especially with the BERT, does it make sense (and would it be statistically correct) to programmatically forbid the model to result with the special tokens as predictions?
How is that in the original implementations? During convergence the models have to learn not to predict these but would this intervention help (or the opposite)?

*

*I would consider the [MASK], [CLS] tokens mainly

*[PAD] token could have some sense as well (but that not in all situations)

A: If I understand your question, you're asking how BERT (or other transformer based models) handle special characters. This is less relevant to the model architecture (i.e. this answer is relevant to auto-regressive models, or even non-neural models) than it is to the pre-processing steps.
In particular, BERT tokenizers use a Byte-Pair Encoding tokenizer to split the text and tokens into subwords. Should the tokenizer not recognize a sequence of characters, it will replace the sequence of characters with an UNK meta-token, very much like the MASK or CLS tokens. Google will have many answers should you want to see more specifics, for example, from a blog article:

There is an important point to note when we use a pre-trained model. Since the model is pre-trained on a certain corpus, the vocabulary was also fixed. In other words, when we apply a pre-trained model to some other data, it is possible that some tokens in the new data might not appear in the fixed vocabulary of the pre-trained model. This is commonly known as the out-of-vocabulary (OOV) problem.
For tokens not appearing in the original vocabulary, it is designed that they should be replaced with a special token [UNK], which stands for unknown token.


text:
Q: Mutual inclusion with singleton I currently have a problem with mutual inclusion in a project of mine (C++).
Normally, if I had a mutual inclusion problem, I'd easily solve it by either forward declaration or redesigning the classes a bit. But this time, I'm stuck:
I have a class called Game, which creates and launches core game systems, where one of these is called GraphicsSystem.
In the Game constructor, a GraphicsSystem object is dynamically created and stored in a GraphicsSystem* pointer. Looks like this:
Game::Game ()
{
    gfxSys = new GraphicsSystem(80, new Camera());
}

Now my GraphicsSystem class needs to access a Game class's method at one point to get the player object, which is stored within the Game object. The respective part looks like this (Game is btw a singleton!):
void GraphicsSystem::handleFrame ()
{
    ElementList elements = Game::instance()->getPlayer()->getEnvironment()->getElements();
}

Now I tried forward declaration in both directions already, but that wouldn't satisfy the compiler. I could of course also just put the player pointer into the graphics system, but I really don't want to do that, since he doesn't belong there.
Is there any way to resolve this without me having to change the design too much? I'm really stumped right now, so I hope you guys can help me.
I'm using Visual Studio 2010 (Visual C++).
Thank you in advance!
Chris

A: There are two main ways to break circular dependencies in C++.
1) Create a 'interface' class which lists the methods implemented by your real class and which your real class inherits from. Then you can include that instead of the declaration of the real class.
2) Pimpl - a class holds an opaque pointer to its real data, solving the problem of having to include declarations for the types of member variables.

A: Forward declare GraphicsSystem in Game.h.  Include Game.h in GraphicsSystem.h if it needs it.  Include Game.h and GraphicsSystem.h in Game.cpp.  Include Game.h and GraphicsSystem.h in GraphicsSystem.cpp.
That should work based off the code you posted.

A: I know this is going to sound dodgy, but have you considered holding a global reference to the initialized Game class?
I know globals are evil and so on and so forth, and I'm sure lots of people are going to rage, but in my personal experience I have succumb to Singletonitis with the Game class (among others) and found that sometimes it just simply isn't necessary.
The biggest question you need to ask yourself is "Who are you trying to protect your Game object from? and is there any reason why you need to request an instance each time you need the game class? I'm pretty sure that if your Game object wasn't initialized, you wouldn't be doing much else in your engine anyway.
Hope this might help you think about things in a different way, even though it's not answering your question directly.


text:
Q: Hibernate does not work in the app console There was a problem after I connected the hibernate dependency to my project via the maven. Everything works in IntelliJ Idea, but if I run the jar from the console, then it throws me an error.
Exception in thread "main" java.lang.ExceptionInInitializerError
    at org.hibernate.boot.registry.BootstrapServiceRegistryBuilder.build(BootstrapServiceRegistryBuilder.java:218)
    at org.hibernate.boot.registry.StandardServiceRegistryBuilder.<init>(StandardServiceRegistryBuilder.java:87)
Caused by: java.lang.IllegalArgumentException: Invalid logger interface org.hibernate.internal.CoreMessageLogger (implementation not found in sun.misc.Launcher$AppClassLoader@7f31245a)

I can't understand what the reason for this behavior is. Here is the version I'm using
<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-core</artifactId>
    <version>5.5.7.Final</version>
</dependency>


text:
Q: Can I use join instead of a subquery which returns 1 row? Here is my query:
SELECT p1.*,
       (select guid
        from wp_posts p2
        where p2.post_parent = p1.id
        ORDER by p2.id DESC
        LIMIT 1) as post_image
from wp_posts p1
where p1.post_status = 'publish' and
      p1.post_type = 'post'
order by p1.id DESC limit 4

I want to make the same query but using join (instead of subquery). Is it possible ?

A: We can try rewriting using a series of extra joins:
SELECT
    p1.*,
    COALESCE(t2.guid, 'NA') AS post_image
FROM wp_posts p1
LEFT JOIN
(
    SELECT post_parent, MAX(id) AS max_id
    FROM wp_posts
    GROUP BY post_parent
) t1
    ON p1.id = t2.post_parent
LEFT JOIN wp_posts t2
    ON t1.max_id = t2.id
WHERE p1.post_status = 'publish' AND p1.post_type = 'post'
ORDER BY p1.id DESC
LIMIT 4;

The logic behind the above refactor is, by observation, that your current subquery is returning the record, for each value of post_parent, having the max value of id.  So, we can join to a subquery which finds the max id value for each post_parent group.  Then, we need to join again to wp_posts to bring in the guid value for that max id row.

A: You can use
SELECT p1.*, p2.guid FROM
wp_posts as p1
JOIN wp_post AS p2 ON  p2.post_parent = p1.id
AND p1.post_status = 'publish' AND p1.post_type = 'post'
ORDER by p1.id DESC limit 1

A: Try this
SELECT p1.*
from wp_posts p1
left outer join(select guid
        from wp_posts
        where p2.post_parent = p1.id
        ORDER by p2.id DESC
        LIMIT 1) as post_image
where p1.post_status = 'publish' and
      p1.post_type = 'post'
order by p1.id DESC limit 4


text:
Q: How do I implement a loss function (Intersection over Union) for a Sequential model in Keras? The IoU is a loss function that needs to be maximised and not minimised. Here is what I tried but I couldn't access the values of the parameters in the max functions:
def bb_intersection_over_union(boxA, boxB):

    # determine the (x, y)-coordinates of the intersection rectangle
    xA = max(boxA[0], boxB[0])       #error in THESE lines
    yA = max(boxA[1], boxB[1])
    xB = min(boxA[2], boxB[2])
    yB = min(boxA[3], boxB[3])

    # compute the area of intersection rectangle
    interArea = max(0, xB - xA + 1) * max(0, yB - yA + 1)

    # compute the area of both the prediction and ground-truth
    # rectangles
    boxAArea = (boxA[2] - boxA[0] + 1) * (boxA[3] - boxA[1] + 1)
    boxBArea = (boxB[2] - boxB[0] + 1) * (boxB[3] - boxB[1] + 1)

    # compute the intersection over union by taking the intersection
    # area and dividing it by the sum of prediction + ground-truth
    # areas - the interesection area
    iou = interArea / float(boxAArea + boxBArea - interArea)

    # return the intersection over union value
    return iou

Here is a code that I found on the Internet: (Will this work? It doesn;t look like IoU.
import numpy as np
def computeIoU(y_pred_batch, y_true_batch):
    return np.mean(np.asarray([pixelAccuracy(y_pred_batch[i], y_true_batch[i])
for i in range(len(y_true_batch))]))

def pixelAccuracy(y_pred, y_true):
    y_pred = np.argmax(np.reshape(y_pred,
    [N_CLASSES_PASCAL,img_rows,img_cols]),axis=0)
    y_true = np.argmax(np.reshape(y_true,
   [N_CLASSES_PASCAL,img_rows,img_cols]),axis=0)
        y_pred = y_pred * (y_true>0)

        return 1.0 * np.sum((y_pred==y_true)*(y_true>0)) /  np.sum(y_true>0)

A: If you have predictions for pixels (not boxes), and values between 0 and 1. (For single class, presence/absence)
def iou(true, pred):

    intersection = true * pred

    notTrue = 1 - true
    union = true + (notTrue * pred)

    return K.sum(intersection)/K.sum(union)

Your function adapted (I don't know if it works properly, there is a risk or having None as gradients because of the intersection = constant 0)
def iou(boxA,boxB):

    xA = K.stack([boxA[:,0], boxB[:,0]], axis=-1)
    yA = K.stack([boxA[:,1], boxB[:,1]], axis=-1)
    xB = K.stack([boxA[:,2], boxB[:,2]], axis=-1)
    yB = K.stack([boxA[:,3], boxB[:,3]], axis=-1)

    xA = K.max(xA, axis=-1)
    yA = K.max(yA, axis=-1)
    xB = K.min(xB, axis=-1)
    yB = K.min(yB, axis=-1)

    interX = K.zeros_like(xB)
    interY = K.zeros_like(yB)

    interX = K.stack([interX, xB-xA + 1], axis=-1)
    interY = K.stack([interY, yB-yA + 1], axis=-1)

    #because of these "max", interArea may be constant 0, without gradients, and you may have problems with no gradients.
    interX = K.max(interX, axis=-1)
    interY = K.max(interY, axis=-1)
    interArea = interX * interY

    boxAArea = (boxA[:,2] - boxA[:,0] + 1) * (boxA[:,3] - boxA[:,1] + 1)
    boxBArea = (boxB[:,2] - boxB[:,0] + 1) * (boxB[:,3] - boxB[:,1] + 1)

    iou = interArea / (boxAArea + boxBArea - interArea)

    return iou


text:
Q: Universal App roaming data not synchronized between devices I'm writing out a data file into the RoamingFolder that is not larger than 10KB after the app is closed (suspended). The app runs on the dev desktop and the Surface 2, both of which are signed on to the same Microsoft Account. But the roaming data is not synchronized no matter how long I wait (I even left for lunch and came back 40 minutes later to no avail).
Both apps are verified to be closed, so there are no active file handles. Both devices will write the data into the Roaming Folder themselves if the app is opened/closed on each. And both devices sync data of other apps from the Windows Store.
The guidelines (http://msdn.microsoft.com/en-us/library/windows/apps/xaml/hh465094.aspx) state that sync is triggered by locking the device. This does not seem to trigger the sync either.

A: I had the same problem,
make sure your app is associated with the store.
For other details check out this blog.


text:
Q: change edittext text color in older platform version I am using a dark background for my app. The text color of edittext is set as white. It is working fine in latest versions. But in older versions since the edittext itself is displaying as white color i am not able to see the entered text in edittext. how can i handle this?

A: Make new xml file in res/drawable name it rounded_edit_text then paste this:
<?xml version="1.0" encoding="utf-8"?>
<shape  xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle" android:padding="10dp">
    <solid android:color="#F9966B" />
    <corners
        android:bottomRightRadius="15dp"
        android:bottomLeftRadius="15dp"
        android:topLeftRadius="15dp"
        android:topRightRadius="15dp" />
</shape>

In res/layout copy and past following code (code of EditText) :
<EditText
    android:id="@+id/txtdoctor"
    android:layout_width="match_parent"
    android:layout_height="30dp"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true"
    android:background="@drawable/rounded_edit_text"
    android:ems="10" >
    <requestFocus />
</EditText>

A: You can use this thing as it included in API level 1:
editText.setTextColor(getResources().getColor(R.id.your_color));
editText.setBackgroundColor(getResources().getColor(R.id.your_color));

A: You are setting the background as color white in your style.xml. In older version it will also set as background color of editttext,dialog like views;  please check this answer. It is about setting android:windowBackground and android:colorBackground . Hope it will help you.


text:
Q: EditText crashing on clearing text I want to clear the text from an EditText.
I tried:

*

*editText.setText("")

*editText.text.clear()

*editText.editableText.clear()
and it works.But sometimes there's an exception.
2018-12-11 16:23:44.367 13388-13388/com.example.helios.myapplication E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.helios.myapplication, PID: 13388
    java.lang.IndexOutOfBoundsException: setSpan (0 ... 6) ends beyond length 0
        at android.text.SpannableStringBuilder.checkRange(SpannableStringBuilder.java:1265)
        at android.text.SpannableStringBuilder.setSpan(SpannableStringBuilder.java:684)
        at android.text.SpannableStringBuilder.setSpan(SpannableStringBuilder.java:677)
        at android.widget.Editor$SuggestionsPopupWindow.updateSuggestions(Editor.java:3608)
        at android.widget.Editor$SuggestionsPopupWindow.show(Editor.java:3480)
        at android.widget.Editor.replace(Editor.java:359)
        at android.widget.Editor$3.run(Editor.java:2129)
        at android.os.Handler.handleCallback(Handler.java:751)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:154)
        at android.app.ActivityThread.main(ActivityThread.java:6119)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776

I execute that code from an overridden performClick() (I'm creating a subclass of EditText).
It seems that EditText doesn't realize it should cancel/forget the suggestion mechanism and it fails.
Do you know if there's anything special I should do to cancel/prevent suggestions to fail?
I noticed that the exception happens if I make the popup window to appear, then click twice at X (first one dismiss the popup, second one executes the clearing code).
Update:
Relevant parts of the code. The actual code has a plugin system to add different drawings and actions, but the relevant code is this one:
    class MyEditText(..): EditText(context) {
    ...
        override fun onTouchEvent(event: MotionEvent?): Boolean {
            event!!
            ensureDrawingInfo()
            when (event.actionMasked) {
                MotionEvent.ACTION_DOWN, MotionEvent.ACTION_CANCEL, MotionEvent.ACTION_UP -> {
                    lastTouchArea = pluginAreaFromMotionEvent(event)
                }
            }
            return super.onTouchEvent(event)
        }

        override fun performClick(): Boolean {
            lastTouchArea?.let {
                plugins[it.pluginIndex].onClick(this, it.rightSide, ::invalidateDrawingInfo)
                return true
            }
            return super.performClick()
        }

    class MyPlugin(val drawableLeft: Drawable, val drawableRight: Drawable) : Plugin {
        ....

        override fun onClick(editText: MyEditText, rightSide: Boolean, redraw: () -> Unit) {
            if (rightSide) {
                // X
                editText.text.clearSpans()
                editText.text.clear()
            }
        }
    }

A: Problem is "updateSuggestions" try to setSpan after you change text in EditText.
So you need make text change after editor modify EditText. Just put your code in view.post
Kotlin
mEditText.post {
   mEditText.setText("your text")
}

Java
mEditText.post(new Runnable() {
        @Override
        void run() {
            mEditText.setText("your text");
        }
    });

A: I found a way to avoid the problem: consuming the touch events I'm interested in.
I want to react to clicks on certain corner of the edit box (think of a clear text button, or a view password one).
I first tried to use only onTouchEvent because I needed the coordinates. But the IDE warned me about not overriding performClick too for accessibility reasons. The idea is if you add extra behavior on touch, it should be available also to accessibility tools that call performClick.
But it's not the case. The extra buttons are extra functionality that doesn't need to be available. Or, if it is available, it won't be available as a normal/general click on the edit box. Maybe as an accessibility action implemented somewhere else.
So, conclusion: I can use only onTouchEvent and consume the events.
Solution
override fun onTouchEvent(event: MotionEvent?): Boolean {
        event!!
        ensureDrawingInfo()
        val touchArea = pluginAreaFromMotionEvent(event)
        if (touchArea != null) {
          // it's the special place, I will handle this
          when (event.actionMasked) {
              MotionEvent.ACTION_DOWN -> lastTouchArea = touchArea
              MotionEvent.ACTION_CANCEL -> lastTouchArea = null
              MotionEvent.ACTION_UP -> {
                if (lastTouchArea == touchArea) { // proper click on place
                  // call the plugin
                  plugins[touchArea.pluginIndex].onClick(this, it.rightSide, ::invalidateDrawingInfo)
              }
          }
          // consume touch events that happen on MY area
          return true
        }
        return super.onTouchEvent(event)
    }

Why
The EditText editor opens sometimes a suggestion window in response to touch events. And it wants to replace text in certain position. But it doesn't replace it right away. It enqueues a message to be processed later, using a looper) so when the replace takes place the text might have been changed by me. I even tried to enqueue my clearing code in the hope that it happens later, but I was unlucky.
The cleanest solution is to consume the events relative to the areas I'm handling so the editor doesn't provoke any problems.
In fact, running this on an API 27 emulator I couldn't reproduce the error. I guess the editor code changed to be aware that the text could have been changed in between.


text:
Q: Adding a new column with data from a join What is the best approach to add a column to an existing table with values from a join...For example:
If I join Table A to Table B...
Select
A.Column1,
A.Column2,
B.Column1,
B.Column2,
B.Column3
FROM A
INNER JOIN B
ON A.Column1 = B.Column2

Basically I just want to copy the column that exists in Table B over to Table A, how can I add new A.Column3 to Table A to match B.Column3 based on the join?

A: Try this:
alter table A add column3 datatype

update A
set column3 = B.column3
from A inner join B on A.Column1 = B.Column2

A: Note that this is probably not most efficient method
alter table A add column3 [yourdatatype];

update A set column3 = (select column3 from B where A.Column1 = B.Column2)
  where exists (select column3 from B where A.Column1 = B.Column2)

A: First use an alter table command to add the new column.
Afterwords use update command to put the values of B in column created in A.

A: You can do this:
alter A add column3 datatype;

update A
inner join (select column2 ,column3, count(*) as cnt from B group by column2) b
on A.column1 = b.column2 set
A.column3 = b.column3;

A: You can make a new table using INSERT statement:
INSERT INTO
   NEW_A
SELECT
   A.*,
   B.Column3
FROM A
   INNER JOIN B
   ON A.Column1 = B.Column2


text:
Q: CSS fixing an element besides another just a simple question i am stuck with. i am playing around with some html and css, i would like to create a page with content box in the centre of the page and two images of arrows on either side of the content box. now thats not hard at all, the issue is i am using position: absolute; so if i change the window size the elements go nuts..
my html:

something

more something

and my css looks like this:
#left_side {
  border: black solid 1px;
  position: absolute;
  left: 0;
  width: 10em;
  text-align: center;
  margin: 65px;
  border-radius: 8px 8px 8px 8px;
  }

#right_side {
  border: black solid 1px;
  position: absolute;
  right: 0;
  width: 10em;
  text-align: center;
  margin: 65px 210px 0px 0px ;
  border-radius: 8px 8px 8px 8px;
  }

#content {
  background-color: white;
  width: 500px;
  margin: 15px 320px 15px 320px;
  padding: 30px;
  border:5px;
  border-radius: 8px 8px 8px 8px;
  }

what can i change so that the side images/buttons are relative to the content box at all times no matter what the screen size. i was thinking of nesting them in a bigger box but is that the best practice or am i going off on the wrong foot all together. sorry for the simple question, i am new to this and positioning always kills me.
thanks in advance

A: I normally use two wrapper divs to center anything inside them (no absolute style). CSS:
.couter
{
    position: relative;
    left: 50%;
    float: left;
}
.cinner
{
    position: relative;
    left: -50%;
}

And use like:

something

more something

A: I have created a jsfiddle for you with a possible solution.
http://jsfiddle.net/simonweston/MuTEn/
HTML:

LEFT

something

more something

  RIGHT

CSS:
#left_side {
  border: black solid 1px;
  float: left;
  width: 10em;
  text-align: center;
  border-radius: 8px 8px 8px 8px;
  }

#right_side {
  border: black solid 1px;
  float: left;
  width: 10em;
  text-align: center;
  border-radius: 8px 8px 8px 8px;
  }

#content {
  background-color: red;
    float: left;
    width: 100px;
  border:5px;
  border-radius: 8px 8px 8px 8px;
  }

A: If you want the content to expand when the page expands, this is how you could do that:
http://jsfiddle.net/VKBTy/
Also, I would use a container box with position:relative.

A: The layout which you need can be brought in a very simpler way..
I have modified your css as
#left_side {float:left;width:100px;padding:10px;}
#right_side {float:left;width:100px;padding:10px;}
#content {width:500px;float:left;background:blue;}
.clear{clear:both;}

and your HTML as

something

more something

Please use this code to check whether you got your requirement right..


text:
Q: use groovy to activate remote ssh command with parameters I am trying to activate a command on a remote server using a groovy script.
I already copied my ssh key to the remote server it worked.
ssh root@remote_server '/usr/local/bin/activate.pl'

when I tried to add parameters to the remote script I got failures:
ssh root@remote_server '/usr/local/bin/activate.pl android linux'

The errros are: No such file or directory.
Since I know the script is there and it worked before adding the parameters I guess the problem is adding the parameters.
when I activate the remote shell from the shell without the groovy the remote script works. How can I pass them to the remote script with groovy?
thanks

A: I was running it as Jenkins user.
I found out that it is not possible to pass parameters to a remote script with groovy.
I created a local script that executes the ssh command and I activating the local script from Jenkins groovy


text:
Q: Send email with attachments - changes between ICS and JB? I'm using the following code to send emails with multiple attachments using M4A (should be easily transferable to Java):
                Intent intent = new Intent(Intent.ActionSendMultiple);
                intent.SetType("text/plain");
                intent.PutExtra(Intent.ExtraText, "Mail body");
                intent.PutExtra(Intent.ExtraSubject, "Mail subject");

                DirectoryInfo di = new DirectoryInfo(Android.App.Application.Context.FilesDir.AbsolutePath);
                List<Android.Net.Uri> fileList = new List<Android.Net.Uri>();
                foreach (FileInfo file in di.GetFiles("MyAppLogFile*"))
                {
                    Java.IO.File myFile = new Java.IO.File(file.FullName);
                    var uri = Android.Net.Uri.FromFile(myFile);
                    fileList.Add(uri);
                }
                if (fileList.Count > 0)
                    intent.PutParcelableArrayListExtra(Intent.ExtraStream, fileList.ToArray());

                StartActivity(Intent.CreateChooser(intent, "Send email"));

This worked fine on ICS devices, but on Jelly Bean, the mail programm still shows the attachments, but they are not being sent. Since the files come from within the protected part of the file system belonging to the app, I suspect that something may have changed with the permission system from ICS (tried on a Galaxy S3) and JB (tried on a Galaxy S3 and Galaxy Nexus - the latter running JB 4.2).
Has anybody successfully managed to send emails with attachments on JB where the files to be sent are located in the application directory or a subdirectory thereof?
Thanks
Stephan


text:
Q: Convert factor that includes "." to numeric I'm using a dataset that has periods (.) in place of NAs. Right now, the column I'm looking at is a factor with levels 1, 2, and .. I'm trying to take a mean, and obviously, na.rm isn't working. I went back and cleaned the data by changing the periods to NAs (pe94[pe94 == "."] <- NA), and that appeared to work. However, mean can't take the mean of a factor, and when I convert the factor to a numeric, the NAs become 3s. How can I get rid of this problem?

A: I also had similar issues (and other issues) converting factors into numbers for mathematical analysis.  However, I found a fairly simple solution that seems to work.  Hope this helps ...
#Script to convert factor data to numeric data without loss or alterations of values

#Samlpe data frame with factor variables represented by numbers
factor.vector1<-factor(x=c(111,222,333,444,555))
thousands<-c("1,000","2,000","3,000","4,000","5,000")
factor.vector2<-factor(x=thousands)
df<-data.frame(factor.vector1, factor.vector2)

#Numbers as factors without comma place holders
#1st convert dataset to character data type
df[,1]<-as.character(df[,1])
#2nd convert dataset to numeric data type
df[,1]<-as.numeric(df[,1])

#Numbers as factors WITH comma place holders
#If data contains commas in the numbers (e.g. 2,000) use gsub to remove commas
#If commas are not removed before conversion, the value containing commas will become NA
df[,2]<-gsub(",", "", df[,2])
#1st convert dataset to character data type
df[,2]<-as.character(df[,2])
#2nd convert dataset to numeric data type
df[,2]<-as.numeric(df[,2])


text:
Q: How to do a rtrim() to a Android Cursor query? I have the following query:
Cursor c = sd.query(itemsTable.Table_Name, columns, itemsTable.ItemNumber + "= ?", selectionArgs, null, null, null);

I need to be able to do this:
'SQL Query I am running on the database using for testing
select * from items where rtrim(itemnumber) = '292664'

Where itemnumber is my selectionArgs.
The SQL query returns the correct results but the cursor query returns null.
I would rather not change the way I am running queries and would like to know if there is a way to convert my existing query to work the same as the SQL query.

A: Try the following:
String selection = "RTRIM(" + itemsTable.ItemNumber + ") = ?";
String[] selectionArgs = new String[] {"292664"}; // or whatever
Cursor c = sd.query(itemsTable.Table_Name, columns, selection, selectionArgs, null, null, null);


text:
Q: Weird Glitch in program with arrow keys So my program here takes wasd or arrow keys from user otherwise it is supposed to give an error:
import termios
import tty, sys
def getVal():
    old = termios.tcgetattr(sys.stdin)
    tty.setcbreak(sys.stdin.fileno())
    try:
        key = ord(sys.stdin.read(1))
        while key not in [119, 97, 115, 100, 65, 66, 67, 68]:
            print("Please enter w, a, s, or d OR arrow keys only.")
            key = ord(sys.stdin.read(1))

        if key == 119 or key == 65:
            print('up')
        elif key == 97 or key == 68:
            print('left')
        elif key == 115 or key == 66:
            print('down')
        elif key == 100 or key == 67:
            print('right')
    finally:
        termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old)
while True:
    getVal()

The wasd commands work fine but when I try to do any arrow keys(in this case the down one) this happens:
Please enter w, a, s, or d OR arrow keys only.
Please enter w, a, s, or d OR arrow keys only.
down

It is giving me 2 error messages and a down even though it should only give the down message. Why is this happening?

A: When you press an arrow key (as opposed to a literal key), three values are generated: 27 ("escape"), 91, and the actual arrow key (say, 68). If the first value you read is 27, then you should read the next two and decipher only the last one. You should replace this line:
key = ord(sys.stdin.read(1))

with:
key = ord(sys.stdin.read(1))
if key == 27:
    sys.stdin.read(1) # Skip the next character, must be 91
    key = ord(sys.stdin.read(1))


text:
Q: makeSceneTransitionAnimation when opening an activity from an intent from a button within a fragment I am opening the activity screen from on-click of a fragment button. I am trying to make the button move from my fragment screen to activity screen via makeSceneTransitionAnimation. But its not animating . How can I open an activity from intent from a fragment and have the animation going. I really appreciate any help.
public class ListFragment extends Fragment {

    FloatingActionButton fab;
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

                R.layout.fragment, container, false);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

 fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                Intent i = new Intent(getActivity(), MainActivity.class);
             i.putExtra("title",  "title");

                ActivityOptionsCompat options = ActivityOptionsCompat.makeSceneTransitionAnimation(getActivity(), fab, "image");
                ActivityCompat.startActivity(getActivity(), i, options.toBundle());

    } }); }

A: If you see the documentation:
/**
 * Create an ActivityOptions to transition between Activities using cross-Activity scene
 * animations. This method carries the position of multiple shared elements to the started
 * Activity. The position of the first element in sharedElements
 * will be used as the epicenter for the exit Transition. The position of the associated
 * shared element in the launched Activity will be the epicenter of its entering Transition.
 *
 *
This requires {@link android.view.Window#FEATURE_CONTENT_TRANSITIONS} to be
 * enabled on the calling Activity to cause an exit transition. The same must be in
 * the called Activity to get an entering transition.

 * @param activity The Activity whose window contains the shared elements.
 * @param sharedElements The names of the shared elements to transfer to the called
 *                       Activity and their associated Views. The Views must each have
 *                       a unique shared element name.
 * @return Returns a new ActivityOptions object that you can use to
 *         supply these options as the options Bundle when starting an activity.
 */
public static ActivityOptionsCompat makeSceneTransitionAnimation(Activity activity,
        Pair<View, String>... sharedElements) {

So probably you have to do
ActivityOptionsCompat options = ActivityOptionsCompat.makeSceneTransitionAnimation(getActivity(), new Pair<>(fav, "image"));
ActivityCompat.startActivity(getActivity(), i, options.toBundle());

A: @jason,
Add below code in styles.xml file

and in manfiest.xml, go to the activity and use the theme like below;
<activity
        android:name=".YourActivityName"
        android:theme="@style/TransitionTheme"/>


text:
Q: database structure for facebook wall type requirement I am working on a social networking site and it has a wall like facebook where user can post status, pics and stuff. Building a wall just for a user is not hard thing. I have structure like this.
Wall
  {
     Id,
     ToUserId (BigInt) (Owner of wall)
     ByUserId (The person who is posting)
     Content  (message, pic or something else)
     more fields....
  }

This wall is just for a user, I cant reuse it, For example, I am thinking site will have
other objects too like Pages, Groups etc. so all the objects will have Wall for them. I dont want to create separate table for each wall.
Then I thought, I can have ObjectId instead of ToUserId and my structure will be like this.
  Wall
  {
     Id,
     ObjectId (BigInt)(PageId/UserId/GroupId (one of them))
     ByUserId (The person who is posting)
     Content  (message, pic or something else)
     more fields....
  }

As I am using Increment field in my tables, A page can have same Id which a user has. so that is again a problem.
Next, I thought, my object should be string type
Wall
  {
     Id,
     ObjectId (string(10))(PageId/UserId/GroupId (one of them))
     ByUserId (The person who is posting)
     Content  (message, pic or something else)
     more fields....
  }

Now for a User, I will append "U" to the number so Object Id's will be "1U","2U" and for pages they will be "1P","2P" and for a group "1G", "2G".
But I am still not convince, Would like to hear to expert advice on this.
Update
Thanks guys, The problem, I am having is, how can I keep one table for all types of walls.
A wall for a User
A Wall for a Page
A Wall for a Group

If you look at facebook, its one wall or atleast, I want to build it, so it should be attached to any object (to a user, to a page or to a group or to anything).
I hope this makes more sense now.

A: I'd go for separate nullable fields for each possible reference. This will also allow you to use foreign keys and if you want you can even make check contraint so all rows must have exactly one reference defined. I'd definitely NOT recommend going for that string id idea - it would be ineffective to do joins on that.
create table [Posts]
(
    [ID] int not null identity(1, 1),
    [ID_FromUser] int not null,
    [ID_ToUser] int null,
    [ID_ToPage] int null,
    [ID_ToGroup] int null,
    [Content] nvarchar(max) not null,
    -- more stuff

    constraint [FK_Posts_FromUser] foreign key ([ID_FromUser]) references [Users]([ID]),
    constraint [FK_Posts_ToUser] foreign key ([ID_ToUser]) references [Users]([ID]),
    constraint [FK_Posts_ToPage] foreign key ([ID_ToPage]) references [Pages]([ID]),
    constraint [FK_Posts_ToGroup] foreign key ([ID_ToGroup]) references [Groups]([ID]),
    constraint [PK_Posts] primary key ([ID])
)

A: I don't understand why you're trying to create some kind of "string" reference structure. That doesn't seem "relational".
How about this.

A User has many Posts.
A User has one Wall.
A Post has one Wall.
A Post has one User.
A Wall has many Posts.
A Wall has one User.

POCO's (because i can't be bothered writing SQL)
public class User
{
   public int UserId { get; set; }
   public ICollection<Post> Posts { get; set; } // the Posts this user has written. Could be against different Wall's
   public Wall Wall { get; set; } // the User's wall.
}

public class Post
{
   public int PostId { get; set; }
   public User User { get; set; } // the User who wrote the post.
   public Wall Wall { get; set; } // the Wall this Post belongs to.
}

public class Wall
{
   public int WallId { get; set; }
   public ICollection<Post> Posts { get; set; } // all the posts on this Wall.
}

Assumptions:

*

*A Post can only be done against one Wall.


text:
Q: ASP.Net Page Method exceptions not bubbling up? I can't figure out why the exception from a static ASP.Net Page method isn't bubbling up to the Application_Error event to be handled in the global.asax file. I'm not really expecting any errors, but I would like to be safe and know about them if they do happen to occur and would rather not wrap every static method in a try...catch.
Does anyone know how to catch these exceptions or at least why they aren't bubbling?

A: Exceptions bubble to the error handler in Application_Error if they are not being handled in the lower layers. If you already have a TRY/CATCH block where you think the exception is occurring, it will be trapped at that point.
Please post the code of your static method and your Application_Error. It will make it easier to provide you with an accurate answer instead of a generalized one.

A: If developing in Visual Studio, you should debug your code and then step through the source to find the exception and see what is catching it before bubbling up to your Application_Error method.


text:
Q: Powershell script to find a folder and copy to another folder I have a long directory path. The nested folder values keep changing as per project name. but last directory PackageTmp does not change, Looking forward to copy files from PackageTmp to another directory. I want to copy all subfolder and files from C:\unzip\Content\D_C\a\1\s\src\prj\obj\Release\Package\PackageTmp to C:\deploy. My code is copying to C:\deploy\PackageTmp.
Source Dir :- C:\unzip\Content\D_C\a\1\s\src\prj\obj\Release\Package\PackageTmp
Inconsistent Path :- \D_C\a\1\s\src\prj\obj\Release\Package\
Target Dir :- C:\deploy\
Non working code :- Get-ChildItem C:\unzip\ -Filter PackageTmp -Recurse | where {($_.psiscontainer)}| Copy-Item -Destination C:\deploy\ -Recurse -filter * -Force

A: Analysis
Looks like you're almost there.  Your script is just finding the PackageTmp directory and then passing it down the pipeline where it's eventually copied to the destination, directory and contents all included. The trick is, once you find the PackageTmp directory, you then can use a wildcard to get everything that's IN the PackageTmp directory and copy that to your destination.
Code
I tweaked your non-working code, so hopefully this works for you.
# Get the PackageTmp directory
$PackageTmp = Get-ChildItem C:\unzip\ -Filter PackageTmp -Recurse | Where-Object {($_.psiscontainer)}

# Print the FullName of the PackageTmp directory
Write-Host "PackageTmp: $($PackageTmp.FullName)"

# Recursively copy everything in the PackageTmp directory to our destination directory
Copy-Item -Path "$($PackageTmp.FullName)\*" -Destination C:\deploy\ -Recurse -filter * -Force

Explanation
I store the PackageTmp location in a variable.  I can then specify that I want to copy everything INSIDE the PackageTmp directory by using the -Path "$($PackageTmp.FullName)\*" parameter, note the use of the wildcard \*.  This doesn't copy the PackageTmp directory, like you requested.
So effectively instead of doing this:
Copy C:\unzip\Content\D_C\a\1\s\src\prj\obj\Release\Package\PackageTmp -> C:\deploy\

We're just doing this:
Copy C:\unzip\Content\D_C\a\1\s\src\prj\obj\Release\Package\PackageTmp\* to C:\deploy\


text:
Q: Square API: Extracting Client Details for Historic Transactions I am completely new to Square API, and I am not sure the data I'd like to extract is stored every time a transaction is processed.
I read the documentation and I can't find a clear reference on how long can one go into historical transactions for the clients that paid for them, or if their data is automatically stored when payment is processed, which is the key to my question.
I see it is possible to extract all historical transactions of a location. https://docs.connect.squareup.com/api/connect/v2#endpoint-listtransactions
Do I understand correctly, it is possible to extract the customer details for each transaction? https://docs.connect.squareup.com/api/connect/v2#endpoint-listcustomers
My end goal will be to discover customer details such as:
"id": "icard-card_id",
"card_brand": "VISA",
"last_4": "1111",
"cardholder_name": "Amelia Earhart",
"billing_address": {
  "address_line_1": "500 Electric Ave",
  "address_line_2": "Suite 600",
  "locality": "New York",
  "administrative_district_level_1": "NY",
  "postal_code": "10003",
  "country": "US"
}

A: You only have access to the customer information that is in the merchant's account. So if I am a merchant and I create a customer profile for one of my customers I can attach that customer to transactions that are created online and via Point of Sale, and then see the linked customer_id when I pull my transaction info. If no customer entity has been created by the merchant, or the customer is not linked to the transaction, you will not be able to see the info.
In general you never have any info that the merchant hasn't added to their customer directory (like email addresses linked to cards for receipts)


text:
Q: Smooth Interpolation between two points i am trying to interpolate in a mesh between points. I did some research and found few solutions, but all of them produce weird results for me. I tried Cosinus and Cubic interpolation, but whole mesh gets tiny waves in it instead of being smooth.
I tried this
 mu2 = mu*mu;
   a0 = y3 - y2 - y0 + y1;
   a1 = y0 - y1 - a0;
   a2 = y2 - y0;
   a3 = y1;

   return(a0*mu*mu2+a1*mu2+a2*mu+a3);

from here : http://paulbourke.net/miscellaneous/interpolation/
i got all the points i need and all should be working, but it isnt. I spent a lot of time debugging it and only thing i found to be a problem is that it seems that mu ( regular t from 0.0 - 1.0 in interpolation ) starts at 0.0 at P1 as it should, but at 1.0 it is at P3, while it should be at P2 ( points P0, P1, P2, P3, where interpolation should happen between P1 and P2 )
If there is any other better simple way how to do interpolation between two points, please let me know. I dont want to do bezier curves or anything like that with controls points. I just have two points and i can use one more point on each side like in the example above.
Thanks for any help
Luke

A: It appears that a Catmull-Rom spline would be suitable for your data.
As an example of implementing it in VB.NET:
Module Module1

    ''' <summary>
    ''' A class for a 2-D point and operations on it.
    ''' </summary>
    Class PointD
        Property X As Double
        Property Y As Double

        Public Shared Operator +(p1 As PointD, p2 As PointD) As PointD
            Return New PointD(p1.X + p2.X, p1.Y + p2.Y)
        End Operator

        Public Shared Operator -(p As PointD) As PointD
            Return New PointD(-p.X, -p.Y)
        End Operator

        Public Shared Operator -(p1 As PointD, p2 As PointD) As PointD
            Return New PointD(p1.X - p2.X, p1.Y - p2.Y)
        End Operator

        Public Shared Operator *(a As Double, p As PointD) As PointD
            Return New PointD(a * p.X, a * p.Y)
        End Operator

        Public Shared Operator *(p As PointD, a As Double) As PointD
            Return New PointD(a * p.X, a * p.Y)
        End Operator

        'TODO: (Optional) Add methods for magnitude, cross product and dot product.

        Public Sub New()
            ' empty contructor
        End Sub

        Public Sub New(x As Double, y As Double)
            Me.X = x
            Me.Y = y
        End Sub

        Public Overrides Function ToString() As String
            ' use the N3 format string for tidiness in this example
            Return $"({X:N3}, {Y:N3})"
        End Function

    End Class

    ''' <summary>
    ''' Ordinary Catmull-Rom interpolation.
    ''' </summary>
    ''' <param name="t">Vary from 0.0 to 1.0 to get an interpolated point between data points p1 and p2.</param>
    ''' <param name="p0">The first control point.</param>
    ''' <param name="p1">The first data point.</param>
    ''' <param name="p2">The second data point.</param>
    ''' <param name="p3">The second control point.</param>
    ''' <returns>The interpolated point.</returns>
    Function CatmullRomInterpolate(t As Double, p0 As PointD, p1 As PointD, p2 As PointD, p3 As PointD) As PointD
        ' this is the regular Catmull-Rom spline
        ' other ways of treating it can be found at:
        ' https://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-And-no-self-intersections
        Return 0.5 * ((2 * p1) +
            t * (p2 - p0) +
            Math.Pow(t, 2) * (2 * p0 - 5 * p1 + 4 * p2 - p3) +
            Math.Pow(t, 3) * (3 * (p1 - p2) + p3 - p0))

    End Function

    Sub Main()
        ' some sample data which will produce a symmetrical wave shape...
        Dim p0 As New PointD(-1, 1)
        Dim p1 As New PointD(0, 0)
        Dim p2 As New PointD(1, 0)
        Dim p3 As New PointD(2, -1)

        For t = 0.0 To 1.0 Step 0.1
            Console.WriteLine(CatmullRomInterpolate(t, p0, p1, p2, p3))
        Next

        Console.ReadLine()

    End Sub

End Module

Depending on what you need, you might find Catmull-rom curve with no cusps and no self-intersections useful.


text:
Q: This device type does not match the module profile. Error while Deploying HAP I've set up HUAWEI DevEco Studio with HarmonyOS SDK, but fail to launch a newly created project:

I'd suppose, that this might be a phone module, but I have tablet hardware.
How I can change that - or which modules are suitable for a "large screen"?

A: I've found it myself; the relevant configuration file is: entry/src/main/config.json.
"deviceType": ["phone"] should be "deviceType": ["tablet"]. One can even combine them: "deviceType": ["phone", "tablet"] (there seem to be Phone, Tablet, TV, Wearable, Car). Then it fails with INSTALL_FAILED_NO_BUNDLE_SIGNATURE, but this wasn't the question.


text:
Q: Mysql Getting zero values when counting I'm trying to count the number of sales orders has been canceled in a time period. But I run into the problem that it doesn't return results that are zero
My table
+---------------+------------+------------------+
| metrausername | signupdate | cancellationdate |
+---------------+------------+------------------+
| GLO00026      | 2017-06-22 | 2017-03-20       |
| GLO00055      | 2017-06-22 | 2017-04-18       |
| GLO00022      | 2017-06-27 | NULL             |
| GLO00044      | 2017-06-24 | NULL             |
| GLO00005      | 2017-06-26 | NULL             |
+---------------+------------+------------------+

The statment i'm trying to count with
SELECT metrausername, COUNT(*) AS count FROM salesdata2
WHERE cancellationdate IS NOT NULL
AND signupDate >= '2017-6-21' AND signupDate <= '2017-7-20'
GROUP BY metrausername;

Let me know if any additional information would help

A: If the metrausername is filtered out by the where, it won't appear. Left join to the aggregation to get round this:
select distinct a1.metrausername, coalesce(a2.counted,0) as counted -- coalesce replaces null with a value
from salesdata2  a1
left join
(
SELECT metrausername, COUNT(*) AS counted
FROM salesdata2
WHERE cancellationdate IS NOT NULL
AND signupDate >= '2017-6-21' AND signupDate <= '2017-7-20'
GROUP BY metrausername
) a2
on a1.metrausername = a2.metrausername

A: I would just do this by moving the filtering clause to the select.  Assuming you really do want the date range (as opposed to having users outside the range), then:
SELECT metrausername, COUNT(cancellationdate ) AS count
FROM salesdata2
WHERE signupDate >= '2017-06-21' AND signupDate <= '2017-07-20'
GROUP BY metrausername;

COUNT(<colname>) counts the non-NULL values, so this seems like the simplest approach.


text:
Q: COM: If I change the parent of an Interface do I need to create a new Interface? I have been adding new functionality to a COM Interface, and from what I have read the only way to do it( and keep it backwards compatible ) is to create a new interface that inherits the old interface and add the new methods. I have tried doing this but my hierarchy is already quite complex.
Say this is how my interfaces currently are:

IBaseInterface
    |
IDerivedInterface

and I want to add some functionality to the Base Interface, and it now looks like this:

IBaseOldInterface
    |
IBaseInterface
    |
IDerivedInterface

because I have added this new functionality do i need to create a new IDerivedInterface? I have tried it the way it is at the moment and it doesn't seem to work properly for all cases.
I just want some confirmation really, and an explanation why if possible
I need to further explain what my ideal situation would be and why:
I want to add some methods to the IBaseInterface class that then all of the derived classes can use. What I thought might be possible is this:

                   IBaseOldInterface
                  /                 \
IDerivedOldInterface               IBaseNewInterface
                   \               /
                  IDerivedNewInterface

I understand that Diamond Inheritance should be avoided but they are only interfaces so I think that will be alright.
having this new structure, when a user requests one of the INewDerivedInterfaces. The query interface will return the correct Interface for that IID, whether that is the INewDerivedInterface or the IOldDerivedInterface.

A: That does not work. As you have said, to maintain compatibility, you cannot modify an already published interface. But by changing the inheritance you are modifying the interface.
So, you could add the new methods to a new subclass and then you would have this structure:

IBaseInterface
    |
IDerivedInterface
    |
IDerivedInterface2

Or perhaps what you should do is add a new interface which the implementing objects support. So, instead of using inheritance, you simply declare that you implementing class supports multiple interfaces.
In that case you would leave the existing inheritance structure alone, and have something like this:

IBaseInterface         INewInterface
    |
IDerivedInterface

and then implement the class like this:
class TMyObject: public TInterfacedObject, IDerivedInterface, INewInterface

A: There are three ways you can add new functionality to your IBaseInterface, IDerivedInterface interfaces:

*

*You add new methods to the bottom of IDerivedInterface. The newly built apps aware of these new methods will be able to use them. Earlier built apps will keep safely using old methods. You cannot add methods to IBaseInterface or reinherit it from another interface because this will shift dependent methods.
From the context of your original question I have a feeling that you are changing public interfaces used by a range of external software items, and you don't want your change to cause any issues. If so, you perhaps would want to restrain from going this path, even though it looks simple and doing the job (see below why).

*You can derive new interface from either IBaseInterface or IDerivedInterface and newly built apps will use it. Beware of necessity to assign new IID to the new interface.

*You define new interface (such as INewInterface in @DavidHeffernan's above) and your COM objects implements just more interfaces. Newly built apps can query new interface and call its methods.

Item 3 above is perhaps the typical, easy and convenient way to extend the object. Item 2 makes sense only if you need to keep methods on "main" interface, e.g. for legacy clients such as VB6. Item 1 is a way to quick add stuff without modifying code too much, it does work too - the only catch is that client won't be able to safely detect whether the server is implementing old methods only, or new ones as well.

A: Adding methods to the base interface (or replacing it by another that extends it) changes the vtable layout of all derived interfaces, so indeed you need to create new derived interfaces with new IIDs.

A: To add new functionality to IBaseInterface, you need to create a new interface, but DO NOT change your existing hierarchy at all.  What you can do instead is have the class that implements IBaseInterface also implement the new interface as well, eg:
type
  IBaseInterface = interface
    ...
  end;

  IBaseInterface2 = interface(IBaseInterface)
    ...
  end;

  IDerivedInterface = interface(IBaseInterface)
    ...
  end;

  TBaseClass = class(TInterfacedObject, IBaseInterface, IBaseInterface2)
    ...
  end;

  TDerivedClass = class(TBaseClass, IDerivedInterface)
    ...
  end;

That way, any code that wants to use the new IBaseInterface2 functionality can query any IBaseInterface for that interface, and if successful then use the new functionality, eg:
var
  Base2: IBaseInterface2;
begin
  if Supports(AnyBaseOrDerivedInterfacePtr, IBaseInterface2, Base2) then
  begin
    // use Base2 as needed...
  end;
end;