text:
Q: PyAudio install error after updated to Xcode 12 I have been updated to Xcode 12, but when I trying to install PyAudio, I always got an error like this:
(I also tried to install with sudo, with and without venv, which got same error like this...)

*

*OS: macOS 10.15.6 (19G2021)

*Python: 3.8

*Xcode version: 12

Collecting pyaudio
  Using cached PyAudio-0.2.11.tar.gz (37 kB)
Using legacy 'setup.py install' for pyaudio, since package 'wheel' is not installed.
Installing collected packages: pyaudio
    Running setup.py install for pyaudio ... error
    ERROR: Command errored out with exit status 1:
     command: /Users/userid/Desktop/Workspace/Projects/hello-world/env/bin/python3 -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/dg/ppgz73fs3ml5zs4mxqtw_z_c0000gn/T/pip-install-qfayqnx7/pyaudio/setup.py'"'"'; __file__='"'"'/private/var/folders/dg/ppgz73fs3ml5zs4mxqtw_z_c0000gn/T/pip-install-qfayqnx7/pyaudio/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record /private/var/folders/dg/ppgz73fs3ml5zs4mxqtw_z_c0000gn/T/pip-record-8ls2_tdo/install-record.txt --single-version-externally-managed --compile --install-headers /Users/userid/Desktop/Workspace/Projects/hello-world/env/include/site/python3.8/pyaudio
         cwd: /private/var/folders/dg/ppgz73fs3ml5zs4mxqtw_z_c0000gn/T/pip-install-qfayqnx7/pyaudio/
    Complete output (104 lines):
    running install
    running build
    running build_py
    creating build
    creating build/lib.macosx-10.14.6-x86_64-3.8
    copying src/pyaudio.py -> build/lib.macosx-10.14.6-x86_64-3.8
    running build_ext
    building '_portaudio' extension
    creating build/temp.macosx-10.14.6-x86_64-3.8
    creating build/temp.macosx-10.14.6-x86_64-3.8/src
    xcrun -sdk macosx clang -Wno-unused-result -Wsign-compare -Wunreachable-code -fno-common -dynamic -DNDEBUG -g -fwrapv -O3 -Wall -iwithsysroot/System/Library/Frameworks/System.framework/PrivateHeaders -iwithsysroot/Applications/Xcode.app/Contents/Developer/Library/Frameworks/Python3.framework/Versions/3.8/Headers -arch arm64 -arch x86_64 -DMACOSX=1 -I/Users/userid/Desktop/Workspace/Projects/hello-world/env/include -I/Applications/Xcode.app/Contents/Developer/Library/Frameworks/Python3.framework/Versions/3.8/include/python3.8 -c src/_portaudiomodule.c -o build/temp.macosx-10.14.6-x86_64-3.8/src/_portaudiomodule.o
    In file included from src/_portaudiomodule.c:27:
    In file included from /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/include/stdio.h:64:
    In file included from /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/include/_stdio.h:68:
    /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/include/sys/cdefs.h:807:2: error: Unsupported architecture
    #error Unsupported architecture
     ^
    In file included from src/_portaudiomodule.c:27:
    In file included from /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/include/stdio.h:64:
    In file included from /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/include/_stdio.h:71:
    In file included from /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/include/_types.h:27:
    In file included from /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/include/sys/_types.h:33:
    /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/include/machine/_types.h:34:2: error: architecture not supported
    #error architecture not supported
     ^
    In file included from src/_portaudiomodule.c:27:
    In file included from /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/include/stdio.h:64:
    In file included from /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/include/_stdio.h:71:
    In file included from /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/include/_types.h:27:
    /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/include/sys/_types.h:55:9: error: unknown type name '__int64_t'
    typedef __int64_t       __darwin_blkcnt_t;      /* total blocks */
            ^
    /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/include/sys/_types.h:56:9: error: unknown type name '__int32_t'; did you mean '__int128_t'?
    typedef __int32_t       __darwin_blksize_t;     /* preferred block size */
            ^
    note: '__int128_t' declared here
    /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/include/sys/_types.h:57:9: error: unknown type name '__int32_t'; did you mean '__int128_t'?
    typedef __int32_t       __darwin_dev_t;         /* dev_t */
            ^
    note: '__int128_t' declared here
    /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/include/sys/_types.h:60:9: error: unknown type name '__uint32_t'; did you mean '__uint128_t'?
    typedef __uint32_t      __darwin_gid_t;         /* [???] process and group IDs */
            ^
    note: '__uint128_t' declared here
    /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/include/sys/_types.h:61:9: error: unknown type name '__uint32_t'; did you mean '__uint128_t'?
    typedef __uint32_t      __darwin_id_t;          /* [XSI] pid_t, uid_t, or gid_t*/
            ^
    note: '__uint128_t' declared here
    /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/include/sys/_types.h:62:9: error: unknown type name '__uint64_t'
    typedef __uint64_t      __darwin_ino64_t;       /* [???] Used for 64 bit inodes */
            ^
    /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/include/sys/_types.h:68:9: error: unknown type name '__darwin_natural_t'
    typedef __darwin_natural_t __darwin_mach_port_name_t; /* Used by mach */
            ^
    /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/include/sys/_types.h:70:9: error: unknown type name '__uint16_t'; did you mean '__uint128_t'?
    typedef __uint16_t      __darwin_mode_t;        /* [???] Some file attributes */
            ^
    note: '__uint128_t' declared here
    /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/include/sys/_types.h:71:9: error: unknown type name '__int64_t'
    typedef __int64_t       __darwin_off_t;         /* [???] Used for file sizes */
            ^
    /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/include/sys/_types.h:72:9: error: unknown type name '__int32_t'; did you mean '__int128_t'?
    typedef __int32_t       __darwin_pid_t;         /* [???] process and group IDs */
            ^
    note: '__int128_t' declared here
    /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/include/sys/_types.h:73:9: error: unknown type name '__uint32_t'; did you mean '__uint128_t'?
    typedef __uint32_t      __darwin_sigset_t;      /* [???] signal set */
            ^
    note: '__uint128_t' declared here
    /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/include/sys/_types.h:74:9: error: unknown type name '__int32_t'; did you mean '__int128_t'?
    typedef __int32_t       __darwin_suseconds_t;   /* [???] microseconds */
            ^
    note: '__int128_t' declared here
    /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/include/sys/_types.h:75:9: error: unknown type name '__uint32_t'; did you mean '__uint128_t'?
    typedef __uint32_t      __darwin_uid_t;         /* [???] user IDs */
            ^
    note: '__uint128_t' declared here
    /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/include/sys/_types.h:76:9: error: unknown type name '__uint32_t'; did you mean '__uint128_t'?
    typedef __uint32_t      __darwin_useconds_t;    /* [???] microseconds */
            ^
    note: '__uint128_t' declared here
    In file included from src/_portaudiomodule.c:27:
    In file included from /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/include/stdio.h:64:
    In file included from /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/include/_stdio.h:71:
    /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/include/_types.h:43:9: error: unknown type name '__uint32_t'; did you mean '__uint128_t'?
    typedef __uint32_t      __darwin_wctype_t;
            ^
    note: '__uint128_t' declared here
    In file included from src/_portaudiomodule.c:27:
    In file included from /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/include/stdio.h:64:
    In file included from /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/include/_stdio.h:75:
    In file included from /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/include/sys/_types/_va_list.h:31:
    /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/include/machine/types.h:37:2: error: architecture not supported
    #error architecture not supported
     ^
    In file included from src/_portaudiomodule.c:27:
    In file included from /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/include/stdio.h:64:
    In file included from /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/include/_stdio.h:75:
    /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk/usr/include/sys/_types/_va_list.h:32:9: error: unknown type name '__darwin_va_list'
    typedef __darwin_va_list va_list;
            ^
    fatal error: too many errors emitted, stopping now [-ferror-limit=]
    20 errors generated.
    error: command 'xcrun' failed with exit status 1
    ----------------------------------------
ERROR: Command errored out with exit status 1: /Users/userid/Desktop/Workspace/Projects/hello-world/env/bin/python3 -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/dg/ppgz73fs3ml5zs4mxqtw_z_c0000gn/T/pip-install-qfayqnx7/pyaudio/setup.py'"'"'; __file__='"'"'/private/var/folders/dg/ppgz73fs3ml5zs4mxqtw_z_c0000gn/T/pip-install-qfayqnx7/pyaudio/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record /private/var/folders/dg/ppgz73fs3ml5zs4mxqtw_z_c0000gn/T/pip-record-8ls2_tdo/install-record.txt --single-version-externally-managed --compile --install-headers /Users/userid/Desktop/Workspace/Projects/hello-world/env/include/site/python3.8/pyaudio Check the logs for full command output.

Anyone can help? thanks!

A: I was able to work around this by exporting an environment variable
export ARCHFLAGS="-arch x86_64"


text:
Q: Interrupt a postdelayed from a handler inside a OnCompletionListener I have several different Activitys each with a MediaPlayer and a OnCompletionListener to start other activities after the current file has stopped playing. There also is a delay built in the OnCompletion Listener which i achieve through a Handler with postDelayed and it looks like this:
public void onCompletion(MediaPlayer mp) {

        Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                try {
                    Intent stopplay;
                    stopplay = new Intent(actualActivity, Class
                            .forName(nextView));
                    actualActivity.startActivity(stopplay);
                } catch (ClassNotFoundException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }, stopTime);

}

The problem with this is, when i call my SettingsActivity, sometimes it just switches to the Activity that would have come next. So i assume it's hanging in the postDelayd's wait...
How could i get around this?
I also do this in the onStop, onPause and onDestroy of these Activities:
if (mPlayer != null) {
        mPlayer.stop();
        mPlayer.release();
        mPlayer = null;
    }

A: You have to cancel your handler's callback when you don't want it to be executed.
Define your handler at your activity scope(because you have to reach it). Something like this:
public class MainActivity extends Activity {

    Handler handler = new Handler();
    Runnable myRunnable;
        ...
}

and define your runnable inside your activity(maybe inside you onCreate method)
myRunnable = new Runnable() {
    @Override
    public void run() {
        try {
            Intent stopplay;
            stopplay = new Intent(actualActivity, Class
                    .forName(nextView));
            actualActivity.startActivity(stopplay);
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
};

Change your code:
handler.removeCallbacks(myRunnable);
handler.postDelayed(myRunnable, stopTime);

And if you want to cancel it try this:
handler.removeCallbacks(myRunnable);

redpajama_set_name: RedPajamaStackExchange


text:
Q: hosted on aws, still page not available I have registered a domain www.techsteroid.com with godaddy and hosted on aws ec2 instance with public dns ec2-52-8-152-90.us-west-1.compute.amazonaws.com . I have installed wordpress and associated elastic ip address and updated it in godaddy. Then, my website was redirecting to correct page like this
http://www.techsteroid.com/

but on clicking on any link, address bar will show public dns ie
http://ec2-52-8-152-90.us-west-1.compute.amazonaws.com/2016/06/11/hello-world/

instead of
http://techsteroid.com/2016/06/11/hello-world/

To fix it I created a hosted zone, imported zone file, and updated nameservers in godaddy. But since then website is not even opening. It says www...com can't ebe reached. Niether of company's support are able to resolve this problem.
The ss's are

The problem now is how should I be able to connect to the site by its domain on my network.  In permalinks setting, I am seeing this

A: OK, first, the DNS changes you made are working. I can pull up the site without issue.
Your NS servers point to Route53 as expected:
$ whois techsteroid.com | grep "Name Server"
   Name Server: NS-1129.AWSDNS-13.ORG
   Name Server: NS-159.AWSDNS-19.COM
   Name Server: NS-1846.AWSDNS-38.CO.UK
   Name Server: NS-635.AWSDNS-15.NET

Furthermore, the DNS records themselves look good:
$ dig +short www.techsteroid.com
techsteroid.com.
52.8.152.90

Here's the site screenshot:

So, any issue you're seeing locally are likely due to cache issues. Either your browser is caching old data, or something between your browser and the server is caching old data. Try a different browser, or connecting from a network different than the one you're currently using.


text:
Q: Android out of memory on Galaxy S3, but not on HTC Desire S I just bought Samsung Galaxy S3, and I also have HTC Desire S. I am almost done with my application and it works great on HTC Desire S. Problem is with my S3 - I get out of memory error when executing my task. It goes through for the first time, but every next execution crashes application(Could not allocate cursorWindow (Databases/baza....) of size 2097152 due to error -12)
My thread:
  private class nalozi_statistiko_igralca extends AsyncTask<Void, Integer, Void> {

  protected Void doInBackground( Void... ignoredParams ) {

      publishProgress();
      vpisi_statistiko_igralca_update();
        cursor_statistika_igralca_tocke = baza5.rawQuery("SELECT * FROM player_stats" +
                " WHERE id_seznam_iger LIKE "+id_seznam_iger+ " AND id_ekipe LIKE "+ id_izbrane_ekipe_domaci_kopija+ " ORDER BY tocke DESC", null);

        cursor_statistika_igralca_tocke_gosti = baza5.rawQuery("SELECT * FROM player_stats" +
                " WHERE id_seznam_iger LIKE "+id_seznam_iger+ " AND id_ekipe LIKE "+ id_izbrane_ekipe_gosti_kopija+" ORDER BY tocke DESC", null);

        cursor_statistika_igralca_asistence = baza5.rawQuery("SELECT * FROM player_stats" +
                " WHERE id_seznam_iger LIKE "+id_seznam_iger+ " AND id_ekipe LIKE "+ id_izbrane_ekipe_domaci_kopija+ " ORDER BY asistence DESC", null);

        cursor_statistika_igralca_asistence_gosti = baza5.rawQuery("SELECT * FROM player_stats" +
                " WHERE id_seznam_iger LIKE "+id_seznam_iger+ " AND id_ekipe LIKE "+ id_izbrane_ekipe_gosti_kopija+ " ORDER BY asistence DESC", null);

        cursor_statistika_igralca_obrambni_skoki = baza5.rawQuery("SELECT * FROM player_stats" +
                " WHERE id_seznam_iger LIKE "+id_seznam_iger+ " AND id_ekipe LIKE "+ id_izbrane_ekipe_domaci_kopija+ " ORDER BY defensive_rebounds DESC", null);

        cursor_statistika_igralca_obrambni_skoki_gosti = baza5.rawQuery("SELECT * FROM player_stats" +
                " WHERE id_seznam_iger LIKE "+id_seznam_iger+ " AND id_ekipe LIKE "+ id_izbrane_ekipe_gosti_kopija+ " ORDER BY defensive_rebounds DESC", null);

        cursor_statistika_igralca_napadalni_skoki = baza5.rawQuery("SELECT * FROM player_stats" +
                " WHERE id_seznam_iger LIKE "+id_seznam_iger+ " AND id_ekipe LIKE "+ id_izbrane_ekipe_domaci_kopija+ " ORDER BY offensive_rebounds DESC", null);

        cursor_statistika_igralca_napadalni_skoki_gosti = baza5.rawQuery("SELECT * FROM player_stats" +
                " WHERE id_seznam_iger LIKE "+id_seznam_iger+ " AND id_ekipe LIKE "+ id_izbrane_ekipe_gosti_kopija+ " ORDER BY offensive_rebounds DESC", null);

        cursor_statistika_igralca_ukradene_zoge = baza5.rawQuery("SELECT * FROM player_stats" +
                " WHERE id_seznam_iger LIKE "+id_seznam_iger+ " AND id_ekipe LIKE "+ id_izbrane_ekipe_domaci_kopija+ " ORDER BY steals DESC", null);

        cursor_statistika_igralca_ukradene_zoge_gosti = baza5.rawQuery("SELECT * FROM player_stats" +
                " WHERE id_seznam_iger LIKE "+id_seznam_iger+ " AND id_ekipe LIKE "+ id_izbrane_ekipe_gosti_kopija+ " ORDER BY steals DESC", null);

        cursor_statistika_igralca_blokade = baza5.rawQuery("SELECT * FROM player_stats" +
                " WHERE id_seznam_iger LIKE "+id_seznam_iger+ " AND id_ekipe LIKE "+ id_izbrane_ekipe_domaci_kopija+ " ORDER BY blocks DESC", null);

        cursor_statistika_igralca_blokade_gosti = baza5.rawQuery("SELECT * FROM player_stats" +
                " WHERE id_seznam_iger LIKE "+id_seznam_iger+ " AND id_ekipe LIKE "+ id_izbrane_ekipe_gosti_kopija+ " ORDER BY blocks DESC", null);

        cursor_statistika_igralca_izgubljene_zoge = baza5.rawQuery("SELECT * FROM player_stats" +
                " WHERE id_seznam_iger LIKE "+id_seznam_iger+ " AND id_ekipe LIKE "+ id_izbrane_ekipe_domaci_kopija+ " ORDER BY turnovers DESC", null);

        cursor_statistika_igralca_izgubljene_zoge_gosti = baza5.rawQuery("SELECT * FROM player_stats" +
                " WHERE id_seznam_iger LIKE "+id_seznam_iger+ " AND id_ekipe LIKE "+ id_izbrane_ekipe_gosti_kopija+ " ORDER BY turnovers DESC", null);

        cursor_statistika_igralca_osebne = baza5.rawQuery("SELECT * FROM player_stats" +
                " WHERE id_seznam_iger LIKE "+id_seznam_iger+ " AND id_ekipe LIKE "+ id_izbrane_ekipe_domaci_kopija+ " ORDER BY fouls DESC", null);

        cursor_statistika_igralca_osebne_gosti = baza5.rawQuery("SELECT * FROM player_stats" +
                " WHERE id_seznam_iger LIKE "+id_seznam_iger+ " AND id_ekipe LIKE "+ id_izbrane_ekipe_gosti_kopija+ " ORDER BY fouls DESC", null);

             return null;
  }

  protected void onPostExecute( Void array )
  {
    if(nalozi_statistiko_igralca_ali_upload==0)
    {
      pokazi_statistiko_igralca(view);
      pokazi_statistiko_igralca_tocke2(view);
    }
    if(nalozi_statistiko_igralca_ali_upload==1)
    {
        naredi_pdf_izvrsi(view);
    }
    if(nalozi_statistiko_igralca_ali_upload==2)
    {
        pokazi_mvp_domaci(domaci_top_efficiency_id);
    }
    if(nalozi_statistiko_igralca_ali_upload==3)
    {
        pokazi_mvp_gosti(gosti_top_efficiency_id);
    }
  }

  protected void onProgressUpdate(Integer... values)
  {
      Context context = getApplicationContext();
      int duration = Toast.LENGTH_SHORT;
      Toast toast = Toast.makeText(context,  getString(R.string.toast_loading), duration);
      toast.show();

    }

}

public void vpisi_statistiko_igralca_update()
{
    Cursor cursor_ekipa_domaci;

    //list_home = (ListView) findViewById (R.id.list_home);
    //cursor2 = baza5.query("igralci", null, null, null, null, null,"_id" + " ASC");
    cursor_ekipa_domaci = baza5.query("igralci_kopija",null,
            "id_ekipe like " + id_izbrane_ekipe_domaci_kopija,
            null, null, null, null);

    while (cursor_ekipa_domaci.moveToNext())
    {
        String a=cursor_ekipa_domaci.getString(0);
        update_statistiko_igralca((Integer.valueOf(a)),
                cursor_ekipa_domaci.getString(1),
                cursor_ekipa_domaci.getString(2));
    }

    Cursor cursor_ekipa_gosti;

    //list_home = (ListView) findViewById (R.id.list_home);
    //cursor2 = baza5.query("igralci", null, null, null, null, null,"_id" + " ASC");
    cursor_ekipa_gosti = baza5.query("igralci_kopija",null,
            "id_ekipe like " + id_izbrane_ekipe_gosti_kopija,
            null, null, null, null);
    while (cursor_ekipa_gosti.moveToNext())
    {
        String a=cursor_ekipa_gosti.getString(0);
        update_statistiko_igralca((Integer.valueOf(a)),
                cursor_ekipa_gosti.getString(1),
                cursor_ekipa_gosti.getString(2));
    }
}

The heavy work is done in function "vpisi_statistiko_igralca_update". I wonder if Galaxy S3 keeps data in memory, but HTC Desire S dont...

A: I figure it out!!
I needed to close my Cursors, when i was not needing them anymore. (I needed to close about 100 different cursors).
(cursor.close());


text:
Q: Check whether a tuple of variables cannot be constrained any further, in Mozart/Oz Greetings,
The idea can be best given with an example:
Suppose we have a vector vec(a:{FD.int 1#100} b:{FD.int 1#100} c:{FD.int 1#100}).
I want to be able to add constraints to this vector, until the point that every additional constraint I add
to it does not add any more information, e.g. does not constraint vec.a, vec.b and vec.c any further.
Is it possible to do it in Mozart/Oz?
I'd like to think it that way.
In a loop:

*

*Access the constraint store,

*Check whether it is changed

*Terminate if there is no change.

A: You can check the state of a finite domain variable with the functions in the FD.reflect module. The FD.reflect.dom function seems especially useful in this context.
To get the current domain of every field in a record, you can map this function over records:
declare

fun {GetDomains Vec}
   {Record.map Vec FD.reflect.dom}
end

The initial result in your example would be:
vec(a:[1#100] b:[1#100] c:[1#100])

Now you can compare the result of this function before and after adding constraints, to see if anything happens.
Two limitations:

*

*This will only work with constraints which actually change the domain of at least one variable. Some constraints change the constraint store but do not change any domains, for example an equality constraint with an unbound variable.

*Using reflection like this does not work well with concurrency, i.e. if constraints are added from multiple threads, this will introduce race conditions.

If you need an example on how to use the GetDomains function in a loop, let me know...
EDIT: With a hint from an old mailing list message, I came up with this general solution which should work with all types of constraints. It works by speculatively executing a constraint in a subordinate computation space.
declare

Vec = vec(a:{FD.int 1#100} b:{FD.int 1#100} c:{FD.int 1#100})

%% A number of constraints as a list of procedures
Constraints =
[proc {$} Vec.a <: 50 end
 proc {$} Vec.b =: Vec.a end
 proc {$} Vec.b <: 50 end
 proc {$} Vec.a =: Vec.b end
]

%% Tentatively executes a constraint C (represented as a procedure).
%% If it is already entailed by the current constraint store, returns false.
%% Otherwise merges the space (and thereby finally executes the constraint)
%% and returns true.
fun {ExecuteConstraint C}
   %% create a compuation space which tentatively executes C
   S = {Space.new
        proc {$ Root}
           {C}
           Root = unit
        end
       }
in
   %% check whether the computation space is entailed
   case {Space.askVerbose S}
   of succeeded(entailed) then false
   else
      {Wait {Space.merge S}}
      true
   end
end

for C in Constraints I in 1..4 break:Break do
   {System.showInfo "Trying constraint "#I#" ..."}
   if {Not {ExecuteConstraint C}} then
      {System.showInfo "Constraint "#I#" is already entailed. Stopping."}
      {Break}
   end
   {Show Vec}
end

{Show Vec}


text:
Q: Formatting number as thousand using only Javascript Console.log is showing the correct result, but how can I add the same formatting to the input type while typing.
Input type is reset after every comma to zero.
1000 to 1,000
Please Help.
This code is working here

function numberWithCommas(number) {
    if (isNaN(number)) {
        return '';
    }

    var asString = '' + Math.abs(number),
        numberOfUpToThreeCharSubstrings = Math.ceil(asString.length / 3),
        startingLength = asString.length % 3,
        substrings = [],
        isNegative = (number < 0),
        formattedNumber,
        i;

    if (startingLength > 0) {
        substrings.push(asString.substring(0, startingLength));
    }

    for (i=startingLength; i < asString.length; i += 3) {
        substrings.push(asString.substr(i, 3));
    }

    formattedNumber = substrings.join(',');

    if (isNegative) {
        formattedNumber = '-' + formattedNumber;
    }

    document.getElementById('test').value = formattedNumber;
}
<input type="number" id="test" class="test" onkeypress="numberWithCommas(this.value)">

A: Check out my fiddle here http://jsfiddle.net/6cqn3uLf/
You'd need another regex to limit to numbers but this will format based on the user's locale - which may be advantageous here.
<input id="mytext" type="text">

$(function () {
    $('#btnformat').on('input propertychange paste', function () {
        var x = $('#btnformat').val();
 $('#btnformat').val(Number(x.replace(/,/g,'')).toLocaleString());
    });
});

A: function numberWithCommas(x) {
    var real_num =  x.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,");
    console.log(real_num);
    document.getElementById('test').value = real_num;
}

<input type="number" id="test" onkeypress="numberWithCommas(this.value)">

A: Some notes:

*

*Because you want commas, the type is not a number, it's a string

*Because you want to work on the input after you type, it's onkeyup not onkeypressed

I have a solution that does a regex replace for 3 characters with 3 characters PLUS a comma:
var x = "1234567";
x.replace(/.../g, function(e) { return e + ","; } );
// Gives: 123,456,7

i.e. almost the right answer, but the commas aren't in the right spot. So let's fix it up with a String.prototype.reverse() function:

String.prototype.reverse = function() {
    return this.split("").reverse().join("");
}

function reformatText() {
    var x = document.getElementById('test').value;
    x = x.replace(/,/g, ""); // Strip out all commas
    x = x.reverse();
    x = x.replace(/.../g, function(e) { return e + ","; } ); // Insert new commas
    x = x.reverse();
    x = x.replace(/^,/, ""); // Remove leading comma
    document.getElementById('test').value = x;
}
<input id="test" class="test" onkeyup="reformatText()">

A: if jquery is not overhead for your application then you can use
https://code.google.com/p/jquery-numberformatter/


text:
Q: Unable to resolve rxjs dependency issue While trying to install latest version of angular/core, I am facing issue with unmet dependency of rxjs.
I am not sure which version of rxjs is currently installed here!!

A: That's not how you check what package version you have installed. That 3.10.10 is your npm version not rxjs version. Also, using just npm show rxjs version will show you the latest version in npm repository, not the installed version.
To see what version of rxjs you have use npm ls --depth=0 that will show you all dependencies defined in your composer.json and their version.
I guess your problem is that you don't have rxjs in package.json and that's why it's complaining about the peer dependency.


text:
Q: Bootstrap 4 Layout not working as expected when used with forms I am working with Bootstrap 4 on a form. Now, when using the form along with the grid classes, it does not actually work like its supposed to. The output can be seen here http://www.henryspike.tk/testform
What I had expected was to see the whole 12 columns divided into 4-4-4 each containing an input field but it stacks up.

                            <form class="form">

                                        Name
                                        <input class="form-control" type="text" name="name" id="name" placeholder="eg. John Doe" required>

                                        Name
                                        <input class="form-control" type="email" name="email" id="email" placeholder="someone@example.com" required>

                                        Name
                                        <input class="form-control" type="text" name="username" id="username" placeholder="eg. JDoe12" required>

                            </form>

A: col- should always be the immediate child of row..
http://www.codeply.com/go/moFmNMMuPs

        <form class="row form">

                    Name
                    <input class="form-control" type="text" name="name" id="name" placeholder="eg. John Doe" required="">

                    Name
                    <input class="form-control" type="email" name="email" id="email" placeholder="someone@example.com" required="">

                    Name
                    <input class="form-control" type="text" name="username" id="username" placeholder="eg. JDoe12" required="">

        </form>


text:
Q: How do I plot the 'inverse' of a survival function? I am trying to plot the inverse of a survival function, as the data I'm is actually an increase in proportion of an event over time. I can produce Kaplan-Meier survival plots, but I want to produce the 'opposite' of these. I can kind of get what I want using the following fun="cloglog":
plot(survfit(Surv(Days_until_workers,Workers)~Queen_Number+Treatment,data=xdata),
     fun="cloglog", lty=c(1:4), lwd=2, ylab="Colonies with Workers",
     xlab="Days", las=1, font.lab=2, bty="n")

But I don't understand quite what this has done to the time (i.e. doesn't start at 0 and distance decreases?), and why the survival lines extend above the y axis.
Would really appreciate some help with this!
Cheers

A: Use fun="event" to get the desired output
fit <- survfit(Surv(time, status) ~ x, data = aml)
par(mfrow=1:2, las=1)
plot(fit, col=2:3)
plot(fit, col=2:3, fun="event")

The reason for fun="cloglog" screwing up the axes is that it does not plot a fraction at all. It is instead plotting this according to ?plot.survfit:

"cloglog" creates a complimentary log-log survival plot (f(y) = log(-log(y)) along with log scale for the x-axis)

Moreover, the fun argument is not limited to predefined functions like "event" or "cloglog", so you can easily give it your own custom function.
plot(fit, col=2:3, fun=function(y) 3*sqrt(1-y))


text:
Q: Linker error when using standard library in C++ I have been struggling with this compilation problem for hours and I haven't been able to find any solution:
I am working on a medium size application written in "C with classes" style and using cmake. I am trying to add a std::multimap to a part which I am extending. I have included <map> and <utility> in the corresponding header file, and this code is my minimal example:
std::pair<int,int> y(5,10);
cout << y.first << ", " << y.second << endl;

std::map<int,int> x;
//x.insert(y);
//x[2] = 4;
cout << x.empty() << endl;

This works as expected unless I enable either of the commented lines, in which case I get the following error from the linker:
In function `std::_Rb_tree<int, std::pair<int const, int>, std::_Select1st<std::pair<int const, int> >, std::less<int>, std::allocator<std::pair<int const, int> > >::_M_insert_(std::_Rb_tree_node_base const*, std::_Rb_tree_node_base const*, std::pair<int const, int> const&)':
/usr/lib/gcc/x86_64-redhat-linux/4.7.2/../../../../include/c++/4.7.2/bits/stl_tree.h:981: undefined reference to `std::_Rb_tree_insert_and_rebalance(int, std::_Rb_tree_node_base*, std::_Rb_tree_node_base*, std::_Rb_tree_node_base&)'
collect2: error: ld returned 1 exit status

Things I have tried

*

*Some research pointed towards this being something to do with libc++ vs libstdc++, but I think not, seeing as removing the insert() does work. (I also dion't really understand the distinction)

*The above code works fine in a standalone program, compiled with g++ (no options) or gcc -lstdc++.

*I have tried adding -lstdc++ to the cmake CMAKE_CXX_FLAGS, but this didn't seem to make any difference.

*Setting set(CMAKE_CXX_COMPILER "g++") in CMakeLists.txt doesn't seem to make any difference.

It must be something to do with the libraries or project setup I suppose, but I would be very grateful for some advice on where to begin looking.


text:
Q: Is it possible to mount CIFS onto Solaris 10 server I want to mount a SAN CIFS share on a solaris 10 u11 server.
I found and info doc from Oracle saying its not supported until Solaris 11.
Are there any 3rd party / Freeware tools for Solaris 10 that will enable the mounting of a CIFS share on Solaris 10 ?

A: smbfs/cifs is not supported on Solaris 10.
however, you can use smbclient to access the share from Solaris 10 (this is what we do), with something like :
/usr/sfw/bin/smbclient -m SMB2 -W DOMAIN -U USER%PASSWORD //HOST.DOMAIN/Yoursharename

you can also pass commands to it, with e.g:
/usr/sfw/bin/smbclient -m SMB2 -W DOMAIN -U USER%PASSWORD //HOST.DOMAIN/Yoursharename -c 'cd /folder; dir; exit;'

hope that helps
regards,


text:
Q: R Shiny theme colors do not like call to an html page I have a Shiny app using R code which attempts to use a bootstrap theme bootstrap_united.css:
# ui.R
library(shiny)
#
shinyUI(
    fluidPage(
        theme = "bootstrap_united.css",
        navbarPage("",
            tabPanel("Input and display your text",
                fluidRow(
                    column(width = 6,
                        wellPanel(
                            h5("Your input ="),
                            tags$style(type="text/css", "textarea {width:100%}"),
                            tags$textarea(id = "myText", rows = 22, "")
                        )
                    ),
                    column(width = 6,
                        wellPanel(
                            h5("Our output ="),
                            verbatimTextOutput("myText")
                        )
                    )
                )
            ),
            tabPanel("Help page",
                fluidRow(
                    includeHTML("help.html")
                    # h5("This works!")
                )
            )
        )
    )
)

and
# server.R
library(shiny)
#
shinyServer(
    function(input, output) {
        output$myText <- renderText({input$myText})
    }
)

The second tabPanel attempts to call an html file which is saved in the same folder as the ui.R and server.R files. The call is successful, and the page is displayed, but the presence of this page causes the theme colors from the CSS file to not be shown, and so everything in the R Shiny app is displayed in monochrome shades of gray.
However, if the second tabPanel just displays some text {e.g. shown as # h5("Our output =") in the R code} instead of an html page, then the theme is used/displayed correctly, and the app is displayed in color.
How can I adapt the R code in the shiny app so that the html page will be displayed, and the theme will be displayed correctly too?


text:
Q: Sending multiple responses with the same response object in nodejs I have a long running process which needs to send data back at multiple reponse. Is there some way to send back multiple responses with express.js
I want have "test" after 3 seconde a new reponse "bar"
app.get('/api', (req, res) =>
{
    res.write("test");
    setTimeout(function(){
        res.write("bar");
        res.end();
    }, 3000);
});

with res.write a wait a 3050 of have a on response

A: Yes, you can do it. What you need to know is actually chunked transfer encoding.
This is one of the old technics used a decade ago, since Websockets, I haven't seen anyone using this.
Obviously you only need to send responses in different times maybe up to some events will be fired later in chunks. This is actually the default response type of express.js.
But there is a catch. When you try to test this, assuming you are using a modern browser or curl which all of them buffer chunks, so you won't be seeing expected result. Trick is filling up chunk buffers before sending consecutive response chunks. See the example below:
const express = require('express'),
app = express(),
port = 3011;

app.get('/', (req, res) => {

    // res.write("Hello\n");
    res.write("Hello" + " ".repeat(1024) + "\n");

    setTimeout(() => {
        res.write("World");
        res.end();
    }, 2000);

});

app.listen(port, () => console.log(`Listening on port ${port}!`));

First res.write with additional 1024 spaces forces browser to render chunk. Then you second res.write behaves as you expected. You can see difference with uncommenting the first res.write.
On network level there is no difference. Actually even in browser you can achieve this by XHR Object (first AJAX implementation) Here is the related answer

A: An HTTP request response has one to one mapping. You can return HTTP response once, however long it may be. There are 2 common techniques:

*

*Comet responses - Since Response is a writable stream, you can write data to it from time to time before ending it. Ensure the connection read timeout is properly configured on the client that would be receiving this data.

*Simply use web sockets - These are persistent connection that allow 2 way messaging between server and client.


text:
Q: Yii2 fixtures + Codeception functional (rest) tests As I understand reading Yii2 docs, fixtures used for unit tests only, but what I have to do if i need to test api?
If I extend cest from TestCase (yii\codeception), codeception assumes inherited methods as tests and ofc fails it.
There's a discussion about some FixtureHelper which I couldn't find at Yii2 repo.


text:
Q: How to expand/collapse a specific heading by selecting an option from a ComboBox I have created a few headings that should stay collapsed until a specific text is selected from a comboxbox dropdown list.
So far I can only find options to expand all for collapse all.
here's what I have... and I'm sure I'm way off base
Private Sub ComboBox1_DropButtonClick()

ComboBox1.List = Array("Tetra Pak T50", "Tetra Pak T100", "Tetra Pak T125")

  If ComboBox1.Value = "Tetra Pak T50" Then
    ActiveDocument.ActiveWindow.View.ExpandAllHeadings
    Else
    ActiveDocument.ActiveWindow.View.CollapseAllHeadings
  End If

End Sub

A: The Paragraph.CollapsedState property is used to collapse/expand an individual paragraph. (Note that this is Word 2013 or later - not available in earlier versions.)
Set to False in order to expand a paragraph.
I don't know how you're planning to identify specific paragraphs, but assuming you use a bookmark:
ActiveDocument.Bookmarks("TetraPak100").Range.Paragraphs(1).CollapsedState = False

to expand the paragraph.


text:
Q: Laravel join query with two column in same table My code
$result=DB::table('receipts')
      ->join('dealer_m','receipts.ToDealerID','dealer_m.DealerID')
      ->join('dealer_m','receipts.FromDealerID','dealer_m.DealerID')
      ->join('product_m','receipts.ProductID','product_m.ProductID')->get();

table receipts
Id | FromDealerId  | ToDealerId  |  ProductId
---+---------------+-------------+------------
1         1              2            1

2         1              3            1

3         3              1            1

Table dealer_m
DealerId | DealerName
---------+-----------
  1         Dealer One
  2         Dealer Two
  3         Dealer Three

Table product_m
ProductId | ProductName
----------+-----------
    1       Product One
    2       Product Two

Expected Output
Id | FromDealerId  | ToDealerId  |  ProductId | FromDealerName | ToDealerName | ProductName
---+---------------+-------------+------------+----------------+--------------+------------

 1         1              2            1         Dealer One      Dealer Two  Product One

 2         1              3            1         Dealer One      Dealer Three  Product One

 3         3              1            1         Dealer Three    Dealer One   Product One

When I run my code it gets an error

SQLSTATE[42000]: Syntax error or access violation: 1066 Not unique
  table/alias: 'dealer_m' (SQL: select '' from 'receipts' inner join
  'dealer_m' on 'receipts'.'ToDealerID' = `dealer_m'.'DealerID' inner
  join 'dealer_m' on 'receipts'.'FromDealerID' = 'dealer_m'.'DealerID'
  inner join 'product_m' on 'receipts'.'ProductID' =
  'product_m'.'ProductID')

How to solve this ???
Thank You

A: Try This:
$results=DB::table('receipts')
      ->select('receipts.*','dealer_m1.DealerName as ToDealer','dealer_m2.DealerName as FromDealer','product_m.ProductName')
      ->join('dealer_m as dealer1','receipts.ToDealerID','dealer_m.DealerID')
      ->join('dealer_m as dealer2','receipts.FromDealerID','dealer_m.DealerID')
      ->join('product_m','receipts.ProductID','product_m.ProductID')->get();

You just need to give each joined table an alias
Now in your blade:
@foreach ($results as $result)

    {{$result->Id}}
    {{$result->FromDealerId}}
    {{$result->ToDealerId}}
    {{$result->ProductId}}
    {{$result->FromDealer}}
    {{$result->ToDealer}}
    {{$result->ProductName}}

@endforeach

Of course if you ever get stuck on what to call in your blade, just print our the collection to find the key => values or do dd($results); in the controller to inspect it before it gets to the view.

A: You should try this:
$result=DB::table('receipts')
      ->join('dealer_m as dealer_id','receipts.ToDealerID','dealer_m.DealerID')
      ->join('dealer_m as dealer_f_id','receipts.FromDealerID','dealer_m.DealerID')
      ->join('dealer_m as product_p_id','receipts.ProductID','product_m.ProductID')->get();


text: Q: Como trabalhar elementos de uma pagina web em python Estudo python a algum tempo e criei uma aplicação, agora gostaria apenas de criar uma pagina onde os dados que são armazenados em uma variável fossem exibidos naquele elemento html, mais ou menos como o DOM no JS, só que toda explicação que procuro é terrivelmente confusa pra mim, cheguei a pesquisar sobre django mas nunca acho uma aula simples sobre isso, alguém poderia me dar uma luz?


text:
Q: Adding in an array after message.content discord bot so I'm trying to make my discord bot filter specific words out which I have set in my Array:

let Blacklist = ['bad1', 'bad2', 'bad3']

But the problem is that I don't really know how to have this in the Message.content, I've looked it up all over the internet but couldn't find it.
The code I have right now:

 else if (message.content.toLowerCase().includes(Blacklist))
  message.delete() && message.author.send("Keep the use of Profanity out of our server!");

How would I go by entering the array into the message's content?

A: We could very simply use a forEach() function in order to scroll through every element in the array, and check if the message's content includes that element.
This could be done by typing:
const blacklist = ['bad word 1', 'bad word 2', 'bad word 3']
    blacklist.forEach(word => {
        // 'word' represents an element inside of the array.
        // Everytime the client is finished walking through an element, the value of 'word' changes to the next one!
        if (message.content.toLowerCase().includes(word)) message.delete() && message.author.send("Keep the use of Profanity out of our server!")
    })

A: you can use Array.prototype.some() to see if message content has atleast one blacklist word
const blacklist = ['bad word 1', 'bad word 2', 'bad word 3']
const containsProfanity =  blacklist.some(word => message.content.includes(word))
if(containsProfanity){
  message.delete() && message.author.send("Keep the use of Profanity out of our server!")
}

A: You could loop through the blacklist and check for each individual word like so:
let Blacklist=["bad","dumb"]
for(let word of Blacklist){
  if(message.content.includes(word)){
    message.delete()
    message.author.send("warning")
    break;
    }
}

I would break out of the loop if there was a bad word in the text so that the user isn't warned multiple times


text:
Q: How does one create a new R environment from C? I wasn't able to find documentation for this. It looks like the R source code uses NewEnvironment and R_NewHashedEnv, but neither of those are in the public headers, so it looks like they aren't available for me as a user. What function (or what lines of code) should I be using to generate a new ENVSXP?

A: You want allocSExp:
/* C code in foo.c */
#include "Rinternals.h"
SEXP foo() {
  SEXP res = allocSExp(ENVSXP);
  return res;
}

> # R code (after running R CMD SHLIB foo.c)
> dyn.load("foo.dll")
> .Call("foo")
<environment: 0x016a4084>

A: As of R 4.1.0, you can now use the C function R_NewEnv(), which has a signature of:
SEXP R_NewEnv(SEXP enclos, int hash, int size);

Where you provide:

*

*enclos: The parent environment

*hash: Either 1 or 0 depending on if you want a hashed environment

*size: The initial size of the environment (if <= 0, it will use an internal default size, which is currently set to 29)

This takes the same arguments as the R level new.env(), but will be a bit faster because you don't need a callback to R.
Here is the commit that introduced it:
https://github.com/wch/r-source/commit/8a322e786068ec2e23324e61821ff666d0b6e329


text:
Q: Detect resources loading in Angular I have an issue with a directive that I created in Angular.
In this directive, I want to execute some code after the window.onload event to be sure that all the page resources have been loaded (because I want to know the page top offset of some elements in the directive and if the images are not loaded, this offset is not correct)
If I refresh the page, it works because of the window.onload event is fired but when using the angular navigation to reach my component, this event is not fired anymore.
I tried to use the lifecycle of angular like AfterViewInit but most of the time the AfterViewInit method is executed before the images are loaded.
UPDATE
This is the code of my directive :
export class ParallaxDirective implements OnInit, OnDestroy {
    @Input() coef = 1;

    start = 0;
    path = 0;
    initialTranslate = 0;
    intersectObserver: IntersectionObserver;
    inView: boolean;

    constructor(
      private element: ElementRef
    ) {

    }

    ngOnInit(): void {
      window.addEventListener('load', () => this.initParallax());
    }

    ngOnDestroy(): void {
      this.intersectObserver.unobserve(this.element.nativeElement);
      window.removeEventListener('scroll', () =>this.setTransform());
    }

    initParallax(): void {
      this.intersectObserver = new IntersectionObserver(this.intersect.bind(this));
      this.intersectObserver.observe(this.element.nativeElement);

      const initialY = new DOMMatrixReadOnly(window.getComputedStyle(this.element.nativeElement).getPropertyValue('transform')).m42;
      this.start = this.element.nativeElement.offsetTop + initialY;
      this.path = this.element.nativeElement.clientHeight;
      this.initialTranslate = (initialY /
this.element.nativeElement.clientHeight) * 100;
      if (window.pageYOffset > 0) {
        this.setTransform(true);
      }
      window.addEventListener('scroll', () => this.setTransform());
  }

  setTransform(force = false): void {
    if (!this.inView && !force) {
      return;
    }
    const offset = window.pageYOffset + window.innerHeight - this.start;
    const t = (offset * 10) / this.path;
    const i = t * this.coef + this.initialTranslate;
    this.element.nativeElement.style.setProperty('transform', `translate3d(0, ${i}%, 0)`);
  }

  intersect(entries: IntersectionObserverEntry[], observer: IntersectionObserver): void {
    entries.forEach(entry => {
      this.inView = entry.isIntersecting || entry.intersectionRatio > 0;
    });
  }

}

As you can see, I need to retrieve some offsets and dom elements height. The problem is that these offsets and heights are not the same after resources in the page (like images) are completely loaded that's why I need to have an event like window.onload to be sure that everything is loaded. And I didn't find any Angular lifecycle that should be triggered after resources load.
I hope someone can help me with this.
Thanks.

A: After a long long exchange of comments, I finally understood your problem, Romain, and here's what I came up with.
My solution involves adding a directive and a service. The directive will be attached to all <img> tags, and will subscribe to their load events, and the service will coordinate all the load events firing and maintain a running list of images that are still being loaded.
Here's the directive:
@Directive({
  selector: 'img'
})
export class MyImgDirective {
  constructor(private el: ElementRef, private imageService: ImageService) {
    imageService.imageLoading(el.nativeElement);
  }

  @HostListener('load')
  onLoad() {
    this.imageService.imageLoadedOrError(this.el.nativeElement);
  }

  @HostListener('error')
  onError() {
    this.imageService.imageLoadedOrError(this.el.nativeElement);
  }
}

Here's the service:
@Injectable({
  providedIn: 'root'
})
export class ImageService {
  private _imagesLoading = new Subject<number>();
  private images: Map<HTMLElement, boolean> = new Map();
  private imagesLoading = 0;

  imagesLoading$ = this._imagesLoading.asObservable();

  imageLoading(img: HTMLElement) {
    if (!this.images.has(img) || this.images.get(img)) {
      this.images.set(img, false);
      this.imagesLoading++;
      console.log('images loading', this.imagesLoading);
      this._imagesLoading.next(this.imagesLoading);
    }
  }

  imageLoadedOrError(img: HTMLElement) {
    if (this.images.has(img) && !this.images.get(img)) {
      this.images.set(img, true);
      this.imagesLoading--;
      console.log('images loading', this.imagesLoading);
      this._imagesLoading.next(this.imagesLoading);
    }
  }
}

And here's how I would use it in your parallax directive:
  constructor(private imageService: ImageService) {}

  ngOnInit() {
    this.sub = imageService.imagesLoading$.pipe(filter(r => r === 0)).subscribe(_ => {
      this.initParallax()
    });
  }

  ngOnDestroy() {
    this.sub.unsubscribe();
  }

How does this work? The image directive gets attached to all images regardless of how deep they are in your component tree, registers the image with the service, and then tracks the loading progress by listening to the load event. Every time a new directive is created it means a new image is created, so a counter is incremented, and every time load fires, it means an image has finished loading, so the counter is decremented. We emit this counter in an observable, and so we can detect when all images are ready by waiting for the observable to emit the value 0.
Stackblitz demo
EDIT Added error handling in case an image points to a broken link

A: You can use HostListener
import { HostListener, Component } from "@angular/core";

@Component({
  selector: 'app',
  template: `<h1>{{message}}</h1>`
})
class AppComponent {
  message = "Window not loaded";

  @HostListener('load', ['$event'])
  windowLoadedEvent(event) {
    this.message = "Window loaded";
  }
}

Note: It will work only if the component is initialized before window is loaded. Otherwise it will not work


text:
Q: Estimating the parameters of a beta distribution with zeroes and ones in the sample I have a list of values in [0,1] that I want to fit to a Beta distribution in order to get the corresponding  alpha parameter.
I can't use a beta fitting function because my values might be 0's and 1's.
On wikipedia I found this formula for the method-of-moments estimation of alpha given the sample mean and sample variance:

I don't need any exact fitting, just a good approximation. By using sample mean and variance, I should get rid of all the problems arising with 0s and 1s in my sample, right? Will this still be acceptable?


text:
Q: What is the Binder class in System.Reflection for? I notice that there is a Binder class resided in the System.Reflection namespace of .NET. I read through the documentation on MSDN, but I am still not very what it does and how I can use it.
I did a search on Google but the word binding is alluded to "Data binding". By binding, does it mean "Data Binding"? If so, how can I use it for data binding then? I am hoping to find a simple or easy-to-understand example on its usage.
Thanks!

A: Binder selects a member from a list of candidates, and performs type conversion from actual argument type to formal argument type (MSDN).
You are also able to create your own binder.
Also quoted from this page

A System.Reflection.Binder object, which controls such things as type coercion and appropriate overloaded method selection. In most cases you'll be able to pass null and use the default binder.


text:
Q: SQL 3 AND PROBLEMS I want to update my data in my db but I run the my script Toad says that 0 rows updated even if my conditions are excatly true. What is the problem?
update CCB.CCB_PRICE_CAT_BALANCE_CAT set end_date =  (
    select  min(start_date)
    from CCB.CCB_PRICE_CAT_BALANCE_CAT
    where price_code ='XBG93MCM'
        and balance_id = 'HS-XSOTHER' group by price_code),
upd_user='caktas',
upd_date=sysdate
where  (price_code ='XBG93MCM' and balance_id = 'HS-XSOTHER')
    and start_date = (
        select  min(start_date)
        from CCB.CCB_PRICE_CAT_BALANCE_CAT
        where price_code ='XBG93MCM'
            and balance_id = 'HS-XSOTHER'
        group by price_code);

A: Isn't your query currently the same as:
update CCB.CCB_PRICE_CAT_BALANCE_CAT
set
    end_date = start_date
    , upd_user='caktas'
    , upd_date=sysdate
where price_code ='XBG93MCM'
and balance_id = 'HS-XSOTHER'
and start_date = (
    select
        min(start_date)
    from CCB.CCB_PRICE_CAT_BALANCE_CAT
    where price_code ='XBG93MCM'
    and balance_id = 'HS-XSOTHER'

);

If so, can you check the value of min(start_date)?


text:
Q: Статические переменные и методы класса Как в современном (c++11 и более позднем) объявлять статические переменные в классе и можно ли вообще это делать?
#include <iostream>
#include <string>

using namespace std;

int main()
{
    class Class
    {
        static const short unsigned id = 1;
        static const string name = "Заголовок 1";

        public:
        static short unsigned getId()
        {
            return id;
        }

        static string getName()
        {
            return name;
        }
    };

    cout<<Class::getId()<<' '<<Class::getName()<<endl;
    return 0;
}

Я уже понял, что инициализировать статические переменные класса можно только либо из вне, или только если это константы, но не получается вообще никак.
g++ -Wall -march=native -msse3 -O3 -fomit-frame-pointer -pipe -o "oop" "oop.cpp" (в каталоге: /home/ilya/Downloads/Qt)
oop.cpp: В функции «int main()»:
oop.cpp:10:36: ошибка: локальный класс «class main()::Class» не должен иметь статический элемент данных «const short unsigned int main()::Class::id» [-fpermissive]
   static const short unsigned id = 1;
                                    ^
oop.cpp:11:30: ошибка: локальный класс «class main()::Class» не должен иметь статический элемент данных «const string main()::Class::name» [-fpermissive]
   static const string name = "Заголовок 1";
                              ^~~~~~~~~~~~~~~~~~~~~~
oop.cpp:11:23: ошибка: инициализация внутри класса статического элемента данных «const string main()::Class::name» нелитерального типа
   static const string name = "Заголовок 1";
                       ^~~~
oop.cpp:11:30: ошибка: вызов non-constexpr функции «std::__cxx11::basic_string<_CharT, _Traits, _Alloc>::basic_string(const _CharT*, const _Alloc&) [с _CharT = char; _Traits = std::char_traits<char>; _Alloc = std::allocator<char>]»
   static const string name = "Заголовок 1";
                              ^~~~~~~~~~~~~~~~~~~~~~
Сборка завершилась с ошибкой.

И если определять из вне.
#include <iostream>
#include <string>

using namespace std;

int main()
{
    class Class
    {
        public:
        static short unsigned id;
        static string name;
    };

    Class::id = 1;
    Class::name = "Заголовок 1";
    cout<<Class::id<<' '<<Class::name<<endl;
    return 0;
}

То всё равно не получается.
g++ -Wall -march=native -msse3 -O3 -fomit-frame-pointer -pipe -o "oop" "oop.cpp" (в каталоге: /home/ilya/Downloads/Qt)
oop.cpp: В функции «int main()»:
oop.cpp:11:25: ошибка: локальный класс «class main()::Class» не должен иметь статический элемент данных «short unsigned int main()::Class::id» [-fpermissive]
   static short unsigned id;
                         ^~
oop.cpp:12:17: ошибка: локальный класс «class main()::Class» не должен иметь статический элемент данных «std::__cxx11::string main()::Class::name» [-fpermissive]
   static string name;
                 ^~~~
Сборка завершилась с ошибкой.

Почему так происходит и что я делаю не так?

A: Обратите внимание на ошибку. Там упоминается, что класс локальный.
#include <iostream>
#include <string>

class Class
{
public:
    static const int id; // можно инициализировать тут
    static const std::string name; // нельзя инициализировать тут
};

const int         Class::id{111};
const std::string Class::name = "rectangle";

int main()
{
    std::cout << Class::id << ' ' << Class::name << std::endl;
    return 0;
}

Можно убрать константность, инициализация от этого не пострадает
#include <iostream>
#include <string>

class Class
{
public:
    static int id;
    static std::string name;
};

int         Class::id{111};
std::string Class::name = "rectangle";

int main()
{
    Class c;
    std::cout << c.id << ' ' << c.name << std::endl;
    return 0;
}

Во втором примере можно обращаться по имени класса и далее через ::, я просто привел для примера через экземпляр и .  Также рекомендую обратить внимание на фигурную инициализацию, через {}, как сделал для id, она имеет ряд преимуществ, но иногда стоит быть осторожнее, потому что из нее получается объект std::initializer_list. Что касается инициализации внутри класса, то это возможно, если мы имеем статическую константу и интегральный тип:
class Curious
{
    static const int c1 = 7;     // правильно, но помните об определении
    static int c2 = 11;          // ошибка: не константа
    const int c3 = 13;           // ошибка: не статическая константа
    static const int c4 = f(17); // ошибка: инициализатор не константа
    static const float c5 = 7.0; // ошибка: не интегральный тип
    // ...
};

Если (и только если) Вы используете инициализированный член таким образом, что требуется хранить его в памяти, как объект, член должен быть где-нибудь (один раз) определен. Инициализатор не может повторяться:
const int Curious::c1;       // это определение, но не повторяйте здесь инициализатор
const int *p = &Curious::c1; // правильно: Curious::c1 был определен


text:
Q: How to get database connection through websphere ORB call? i've got a websphere 6.1 cluster environment which is composed of two nodes with 2 appservers each. Let's call NodeA including Server1(2809) & Server2(2810), NodeB including Server3(2811) & Server4(2812). Meanwhile, i created a cluster-scope datasource with JNDI local_db.
Right now i want to get database connection in a java client through WAS ORB call from above environment. The specific part of java code would look like this:
        Hashtable env = new Hashtable();
        env.put(Context.INITIAL_CONTEXT_FACTORY,"com.ibm.websphere.naming.WsnInitialContextFactory");
        env.put(Context.PROVIDER_URL,"iiop://localhost:2809");

        javax.sql.DataSource ds = (DataSource)initialContext.lookup("local_db");

        Connection cn = ds.getConnection();

*

*If above java client code gets run, will the database connection retrieve request follow load-balancing rule among the four connection pools of all application servers?

*Moreover, if my java client gets one database connection successfully and then run a big SQL Query with large result return, as for the memory space occupation, which WAS application server would take care? only server1 due to port 2809 used above or the target server who returns the database connection?

*BTW, if i put two server members for that PROVIDER_URL, such as iiop://localhost:2809, localhost:2810, does it mean load-balancing or failover?
Please help explain and correct me if i'm understanding wrongly!
Thanks

A: Let me start with the easy ones and proceed to the rest

*

*Having two provider URLs' implies failover. If you can't connect to the first naming server, it connects to the second naming server and continues till the end of that list. Notice the Fail over is for connection to the naming server (not to the resource itself)

The look up is done on the server that you connect to. THe local_db represents a datasource (and its connection pool) on that server. You will one work with the server1 (as you are connecting to that NS) and will get connection from the datasource hosted on that server.
You will never get any connection from the other servers. In others words there is no load balancing (one request uses connection from server1, another uses a connection from server 2 etc). I believe this is what you mean by load balancing in your question above.
HTH

A: A DataSource is neither remotable nor serializable. Therefore, if you look up local_db from the server, it will return a javax.naming.Reference that the client uses to create a new DataSource instance with the same configuration as the one on the server. That also means that once the lookup has been performed, no JDBC method will ever send requests to the WebSphere server.


text:
Q: sylow subgroups of GL(n,q) Dear all
I am interested to know about the r-sylow subgroups of GL(n,q), is there any work about the structure of this subgroups?

A: Quillen's "On the cohomology and $K$-theory of the general linear groups over a finite field".


text:
Q: Upload Image to google cloud storage using iOS? i need a help to upload image to google cloud storage using iOS ?
Please help.

A: This is a link for demo. You can use google console. First, you need to enable JSON API from above console.


text:
Q: Populating a combo box with values from an enum I've got the enum like so.
enum Beep {A, B, C }

Now, I wish to populate my combo box with these values as follows (the idea is to follow other's example).
<ComboBox x:Name="comboBox1"
          ...
          ItemsSource="Binding Source={StaticResource Beep}" />

However, the binding gets a little bit too static and gives me literally the exact string I'm putting in. What did I do wrong and how do I resolve it?

I've also tried following the hint I got to add something like this. To no avail, though.
public List<Beep> Beepies
{
  get
  {
    return new List<Beep>{ Beep.A }
  }
}

What more can be done about it? I can get the values into the box if I bind in the code behind by the below. But that's not the point - I wish to XAMLize the approach.
comboBox1.ItemsSource = Enum.GetValues(typeof(Beep));

A: You have to bind using a collection. Try creating a List<Beep>.
OR
Create a converter that enumerates the enum:
public class EnumConverter : IValueConverter
{
  public object Convert(object value, ...)
  {
    return Enum.GetValues(value.GetType());
  }
}

You can then use this converter in the binding to XAMLise the approach:
<!-- Put this in resources somewhere -->
<Converters:EnumConverter x:Key="MyEnumConverter"/>

<!-- Change your binding to include the new converter -->
<ComboBox x:Name="comboBox1"
          ...
          ItemsSource="Binding Source={StaticResource Beep},
                       Converter={StaticResource MyEnumConverter}" />


text:
Q: Adding percent value in cell to a dollar amount in Excel I have a column of currency formatted cells (C8:C15) and a markup rate of 15% which is entered into B19. I want to have the markup rate applied to C8:C15. Starting with C8 I entered the formula =B8 + $B$19 but this merely gave me $24.15.
I know I can write *1.15 to get the correct result but this is for a school assignment and the teacher wants me to use "absolute cell referencing". Basically I have to refer to the cell C8 as the formula, not just write *1.15.
Here's a picture with the project that might help explain:

A: What's the matter with using
=B8 * (1 + $B$19)

?


text:
Q: External files not loading into HTML I have a problem loading external files into my index.html. My stylesheet as well as my JS files do not show up at all (Error 404 - Not Found). My directory structure is as follows.

My index.html is:
<!DOCTYPE html>
<html ng-app="myApp">
<head>
    <title>Orders and Customers</title>
    <link rel="stylesheet" type="text/css" href="./assets/css/stylesheet.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.5/angular.min.js"></script>
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.5/angular-route.min.js"></script>
    <script src="./../app/app.js" type="text/javascript"></script>
    <script src="./../app/controllers/customer/CustomerController.js"></script>
    <script src="./../app/controllers/order/OrderController.js"></script>
    <script src="./../app/services/customer/CustomerService.js"></script>
    <script src="./../app/services/order/OrderService.js"></script>
</head>
<body>
    <div ng-view></div>
</body>
</html>

This is what Chrome shows:

My server.js is:
var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');

var app = express();

app.use(bodyParser.json());

require('./server/config/mongoose.js');
require('./server/config/routes.js')(app);

app.use(express.static(path.join(__dirname, './views')));

app.listen(8000, function() {
console.log('Listening on Port 8000');
})

Any help is greatly appreciated!

A: Try this
in server.js
var router = express.Router();
router.use(express.static(path.resolve(__dirname, "../app")));

in index.html
<script src="/app.js" type="text/javascript"></script>
<script src="/controllers/customer/CustomerController.js"></script>
<script src="/controllers/order/OrderController.js"></script>
<script src="/services/customer/CustomerService.js"></script>
<script src="/services/order/OrderService.js"></script>

Router is middle-ware for capture * path.
For example, /service/* matches all requests under service path.
so I changed your code as to handle all resources under "/app" folder. (eg: /app/app.js, etc)
path.resolve changes path from relative to absolute.
it means that you can add another current working directory.
path.resolve(__dirname, "../app") add "/app" from current working directory (views). it parsed from "views/../app" to "/app"

(Reference) Path.resolve

A: The relative paths
<script src="./../app/app.js" type="text/javascript"></script>

etc, are pointing to the wrong directory.
Use the Network tab in your browser developer tools, to check what exact requests are going out.
If the whole app directory is public (Which, in my opinion, should not be the case), "./../" will refer to the views directory.
Single . refers to the current directory, which in this case is, the one containing your index.html. Double .. refers to the directory above it, which here is views.

A: Rather than
<script src="./../app/app.js" type="text/javascript"></script>

Try using the full path:
<script src="/app/app.js" type="text/javascript"></script>
<script src="/app/controllers/order/OrderController.js"></script>

A: Try this
app.use(express.static(path.join(__dirname, 'views')));

and just use
<link rel="stylesheet" type="text/css" href="assets/css/stylesheet.css">

A: Thanks to SeongHyeon, I was able to figure out the solution to my problem. I really appreciate your guys' help. I'd like to elaborate more on this just for my own reference.
When declaring your static path in express, you don't need to reference anything relative to the file that you're trying to import from. Instead, you simply reference the file from the static path that you've declared.


text:
Q: Delete functionality similar to iOS delete messages I have a list of items in UITableView which I want to delete, is there a way to reuse similar delete functionality as of delete messages in iPhone?

A: You will need to implement some of the UITableViewDelegate methods such as:
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath

To provide the default functionality for editing and deleting cells, you will need to include the edit button in the navigation bar, a la:
[[self navigationItem] setLeftBarButtonItem:[self editButtonItem]];

This should cater for most of the "default" implementation you're looking for, with some amendments to wrap around your code of course :)


text:
Q: Grails 2.0.3 error starting from command line in Windows7 Hoping a kindred soul can assist with this odd windows problem
I am attempting to run a grails app on windows and am unable to get grails to start.
I have both downloaded the 2.0.3 distro from grails.org and pulled and built the source off of github.
The error I receive is as follows:
Error: Could not find or load main class
       org.codehaus.groovy.grails.cli.support.GrailsStarter

The searching I've done to find solutions to this problem (which some people have had) have yielded no help: All I've found is suggestions that my environment variables are improperly set up. (e.g. here)
I felt I was quite careful in setting up my variables though. I have the following configured, all under System Variables:
JAVA_HOME C:\java\jdk7
GRAILS_HOME C:\grails\2.0.3  // also set it to C:\grails\source\grails-core when dlded from source
GROOVY_HOME C:\groovy\1.8.6
PATH %JAVA_HOME%\bin;%GRAILS_HOME%\bin;%GROOVY_HOME%\bin;$PATH

I've tried things both before and after downloading groovy and setting that environment variable, and I'm afraid I'm quite lost at this point. Groovy starts just fine, java starts just fine, but grails is unable to start.
Is anyone else in Windows having this issue with the latest grails version?

A: I ran into this error message in the DOS CMD shell. Turned out, I had my GRAILS_HOME set to 2.2.0 but my PATH was pointed to Grails-2.2.1\bin. Once I fixed this mismatch, the error went away and things worked fine. Suggest using "set" in your CMD shell to see what your environment is actually set to.

A: I faced the same issue in the msysgit console and could solve this by setting the environment variable $GRAILS_HOME to the unix format:
export GRAILS_HOME=/c/grails/2.0.3

This fixed the above error but leads to a new one when executing "grails run-app":
$ grails run-app
Error opening zip file or JAR manifest missing : /d/Programme/grails-2.2.4/lib/org.springsource.springloaded/springloaded-core/jars/springloaded-core-1.1.3.jar
Error occurred during initialization of VM
agent library failed to init: instrument

The jar can be found under logged path, so i dont know why it doesnt work. I'm still trying to solve this error.
I hope the above solution could help anybody.

A: Grails 2.3.7, Win7, Java7, msysgit:
By default grails is failed to start from msysgit.
To fix copy cygpath.exe from cygwin to msysgit/bin. And modify startGrails
In the section # For Cygwin, ensure paths are in UNIX format before anything is touched
Replace
    if $cygwin ; then

with
    if [ $cygwin -o $mingw ] ; then

or just set GRAILS_HOME in grails/bin/startGrails in unix style, for example
$GRAILS_HOME=/c/program/grails-2.3.7

ps
useful link about cygpath.exe

A: I feel like a fool for not trying this, but...
Grails is working as a command from the Windows DOS prompt (cmd). It is NOT working from the bash I've been using on windows (git bash, out of convenience and familiarity with the linux cmds).
For those of you that find yourselves in this situation, Make SURE you try this in the Windows cmd prompt as well. (Those with any insight into why this is working in the DOS prompt but not in a custom linux-like bash please weigh in, I will update this answer with any findings I come across!)

A: Your set up should work as-is afaict. I would verify that my grails installation is not corrupt.

A: I had this problem and I realized that I had groovy 2.1.7 in the path.  I removed this groovy from path and Grails worked.

A: As user 'sfitts' pointed out in his comments (which I cannot yet append to), the problem was addressed/fixed at http://jira.grails.org/browse/GRAILS-8271 . This fix was already incorporated in my Grails 2.3.11 installation.
However I additionally had to undefine my GRAILS_HOME environment variable in Windows for this to work (the startup script automatically detects and sets this variable).


text:
Q: Convert Buffer (image) to file I'm looking for the best way to send image files to my server using Apollo Express, and Node.
Getting the information there doesn't seem to be an issue, I convert the object into a string but can't find out how to convert it back to a regular file object to store away.
What I have so far;
JS - let buffer = await toBase64(file);

Through Apollo server..
Node - let buffer = Buffer.from(args.image, 'base64');

This gives me a Buffer. I'm unsure how to proceed with NodeJS to convert this back to a file object.
Thanks

A: I hope this will be helpfull for you
const file = new File([
      new Blob(["decoded_base64_String"])
    ], "output_file_name");

A: You can use one of the various write or writeFile methods which accept a Buffer.
const fs = require("fs");

let buffer = Buffer.from(
  "iVBORw0KGgoAAAANSUhEUgAAAAgAAAAGCAIAAABxZ0isAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAQSURBVBhXY/iPAwygxP//AAjcj3EdtT3BAAAAAElFTkSuQmCC",
  "base64"
);

fs.writeFile("pic.png", buffer, (err) => {
  if (err) throw err;
  console.log("The file has been saved!");
});


text:
Q: Are aggregate extensions the best way to solve this issue or should I try to do something with grouping? I a working with a stock data feed and I want to build minute bars (candlesticks) out of the data. I think that I have a pretty good query that will give me the data that I need but I am not sure that it is the best way to go about it. Please give any comments or critisisms that you have, I am open to any input you want to give.
Input on the left and output on the right
class StockTick
{
    public DateTime Timestamp { get; set; }

    public int Id { get; set; }

    public decimal LastPrice { get; set; }
}

class FirstUda : CepAggregate<decimal, decimal>
{
    public override decimal GenerateOutput(IEnumerable<decimal> payloads)
    {
        return payloads.First();
    }
}

class LastUda : CepAggregate<decimal, decimal>
{
    public override decimal GenerateOutput(IEnumerable<decimal> payloads)
    {
        return payloads.Last();
    }
}

public static class CepExtensions
{
    [CepUserDefinedAggregate(typeof(FirstUda))]
    public static decimal First<InputT>(this CepWindow<InputT> window, Expression<Func<InputT, decimal>> map)
    {
        throw CepUtility.DoNotCall();
    }

    [CepUserDefinedAggregate(typeof(LastUda))]
    public static decimal Last<InputT>(this CepWindow<InputT> window, Expression<Func<InputT, decimal>> map)
    {
        throw CepUtility.DoNotCall();
    }
}

class Program
{
    static void Main(string[] args)
    {
        using (var server = Server.Create("Default"))
        {
            var app = server.CreateApplication("app");

            var source = GetStockTick();

            var input = source.ToPointStream(
                app,
                t => PointEvent.CreateInsert(t.Timestamp, t),
                AdvanceTimeSettings.IncreasingStartTime);

            var minuteWindows = input.AlterEventDuration(e => TimeSpan.FromTicks(TimeSpan.TicksPerMinute - (e.StartTime.Ticks % TimeSpan.TicksPerMinute)));

            var highLowTicks = from e in minuteWindows
                               group e by e.Id into g
                               from win in g.SnapshotWindow(SnapshotWindowOutputPolicy.Clip)
                               select new
                               {
                                   Id = g.Key,
                                   Timestamp = win.Max(e => e.Timestamp.AddSeconds(e.Timestamp.Second * -1)),
                                   OpenPrice = win.First(e => e.LastPrice),
                                   HighPrice = win.Max(t => t.LastPrice),
                                   LowPrice = win.Min(t => t.LastPrice),
                                   ClosePrice = win.Last(e => e.LastPrice)
                               };

            foreach (var hl in highLowTicks.ToEnumerable())
            {
                Console.WriteLine(hl);
            }

            Console.ReadKey();
        }
    }

    private static IEnumerable<StockTick> GetStockTick()
    {
        var ticks = new List<StockTick>();

        var baseTime = new DateTime(2010, 1, 1, 12, 0, 0);

        ticks.Add(new StockTick() { Id = 1, Timestamp = baseTime.AddSeconds(1), LastPrice = 10 });
        ticks.Add(new StockTick() { Id = 1, Timestamp = baseTime.AddSeconds(15), LastPrice = 8 });
        ticks.Add(new StockTick() { Id = 1, Timestamp = baseTime.AddSeconds(30), LastPrice = 12 });
        ticks.Add(new StockTick() { Id = 1, Timestamp = baseTime.AddSeconds(45), LastPrice = 11 });
        ticks.Add(new StockTick() { Id = 1, Timestamp = baseTime.AddSeconds(65), LastPrice = 13 });

        ticks.Add(new StockTick() { Id = 2, Timestamp = baseTime.AddSeconds(11), LastPrice = 35 });
        ticks.Add(new StockTick() { Id = 2, Timestamp = baseTime.AddSeconds(13), LastPrice = 37 });
        ticks.Add(new StockTick() { Id = 2, Timestamp = baseTime.AddSeconds(50), LastPrice = 22 });
        ticks.Add(new StockTick() { Id = 2, Timestamp = baseTime.AddSeconds(55), LastPrice = 32 });
        ticks.Add(new StockTick() { Id = 2, Timestamp = baseTime.AddSeconds(61), LastPrice = 36 });

        return ticks.OrderBy(t => t.Timestamp);
    }
}

A: Ryan,
Looks good - just checking whether this is the intended semantics:
You will get several results within each minute. For every input event, you will get a result event with the same start time, containing the first (in this minute) and the current price, as well as the min and max occurred in this minute so far. So only the very last result event within each minute will contain the first, last, min, max of the entire minute. Correct? You don't want just one event for each entire minute?
Roman


text:
Q: C++ preprocessor: avoid code repetition of member variable list I have a multiple classes each with different member variables that are initialized trivially in a constructor.  Here is an example:
struct Person
{
    Person(const char *name, int age)
        :
        name(name),
        age(age)
    {
    }
private:
    const char *name;
    int age;
};

Each has an associated print<>() function.
template <>
void print<Person>(const Person &person)
{
    std::cout << "name=" << name << "\n";
    std::cout << "age=" << age << "\n";
}

This code is error prone since the parameter list is replicated in four places.  How can I rewrite the code to avoid this duplication?  I'd like to use the preprocessor and/or templates.
For example, could I use the X-args preprocessor technique -- something like this?
#define ARGUMENTS \
    ARG(const char *, name) \
    ARG(int, age)

struct Person
{
    Person(LIST_TYPE_NAME_COMMA(ARGUMENTS))
       :
       LIST_NAME_INIT(ARGUMENTS)
    {
    }
private:
    LIST_TYPE_NAME_SEMICOLON(ARGUMENTS)
};

template <>
void print<Person>(const Person &person)
{
   LIST_COUT_LINE(ARGUMENTS)
}

#undef ARGUMENTS

Or better, a template-based approach?
Please don't question why I want to do this, there are reasoned design decisions that have resulted in multiple similar objects with named parameters.  The parameters need to be named member variables for performance reasons.  I'm just exploring whether it's possible to list the parameters and their types only once.

A: I have solved the same problem with my generic struct to JSON code.
Define a macro:  REFLECT( CLASS_NAME, MEMBER_SEQUENCE )
where MEMBER_SEQUENCE is (name)(age)(other)(...)
Have REFLECT expand to something similar to:
template<>
struct reflector<CLASS_NAME> {
  template<typename Visitor>
  void visit( Visitor&& v ) {
     v( "name" , &CLASS_NAME::name );
     v( "age",   &CLASS_NAME::age  );
     ...
  }
}

You can use BOOST_PP_SEQ_FOREACH to expand the SEQ into the visitors.
Then define your print visitor:
template<typename T>
struct print_visitor {
  print_visitor( T& s ):self(s){}

  template<typename R>
  void operator( const char* name, R (T::*member) )const {
     std::cout<<name<<"= "<<self.*member<<std::endl;
  }
  T& self;
}

template<typename T>
void print( const T& val ) {
   reflector<T>::visit( print_visitor<T>(val) );
}

http://bytemaster.github.com/mace/group_mace_reflect__typeinfo.html
https://github.com/bytemaster/mace/blob/master/libs/reflect/include/mace/reflect/reflect.hpp

A: I am afraid that your solution is pretty optimal for this reduced usecase. Where we can help is if you have additional functions besides print that would benefit from iterating over the fields.
This is a perfect example for Boost.Fusion Fusion Sequences; they can be used to introduce compile-time reflection. On top of it you can then generate more generic runtime behavior.
So, you can for example declare your elements using a Fusion.Map (which restricts you to a single occurrence of each type) or other such fantasies.
If your type does not conform to a Fusion Sequence (or you don't want to meddle with its internals), there are adapters in the adapted section such as BOOST_FUSION_ADAPT_STRUCT. And of course, since not everything is a struct (or has public members), there is also a more generic version for classes, it just gets ugly soon: BOOST_FUSION_ADAPT_ADT.
Stealing from the quick start:
struct print_xml {
    template <typename T>
    void operator()(T const& x) const {
        std::cout
            << '<' << typeid(x).name() << '>'
            << x
            << "</" << typeid(x).name() << '>'
            ;
    }
};

int main() {
    vector<int, char, std::string> stuff(1, 'x', "howdy");
    int i = at_c<0>(stuff);
    char ch = at_c<1>(stuff);
    std::string s = at_c<2>(stuff);

    for_each(stuff, print_xml());
}

The adapters will let you "adapt" a type, so you would get:
struct Foo { int bar; char const* buzz; };

BOOST_FUSION_ADAPT_STRUCT(
    Foo,
    (int, bar)
    (char const*, buzz)
)

And then:
int main() {
    Foo foo{1, "Hello");
    for_each(foo, print_xml());
}

It's a pretty impressive library :)

A: What you need to do is have the preprocessor generate reflection data about the fields. This data can be stored as nested classes.
First, to make it easier and cleaner to write it in the preprocessor we will use typed expression. A typed expression is just an expression that puts the type in parenthesis. So instead of writing int x you will write (int) x. Here are some handy macros to help with typed expressions:
#define REM(...) __VA_ARGS__
#define EAT(...)

// Retrieve the type
#define TYPEOF(x) DETAIL_TYPEOF(DETAIL_TYPEOF_PROBE x,)
#define DETAIL_TYPEOF(...) DETAIL_TYPEOF_HEAD(__VA_ARGS__)
#define DETAIL_TYPEOF_HEAD(x, ...) REM x
#define DETAIL_TYPEOF_PROBE(...) (__VA_ARGS__),
// Strip off the type
#define STRIP(x) EAT x
// Show the type without parenthesis
#define PAIR(x) REM x

Next, we define a REFLECTABLE macro to generate the data about each field(plus the field itself). This macro will be called like this:
REFLECTABLE
(
    (const char *) name,
    (int) age
)

So using Boost.PP we iterate over each argument and generate the data like this:
// A helper metafunction for adding const to a type
template<class M, class T>
struct make_const
{
    typedef T type;
};

template<class M, class T>
struct make_const<const M, T>
{
    typedef typename boost::add_const<T>::type type;
};

#define REFLECTABLE(...) \
static const int fields_n = BOOST_PP_VARIADIC_SIZE(__VA_ARGS__); \
friend struct reflector; \
template<int N, class Self> \
struct field_data {}; \
BOOST_PP_SEQ_FOR_EACH_I(REFLECT_EACH, data, BOOST_PP_VARIADIC_TO_SEQ(__VA_ARGS__))

#define REFLECT_EACH(r, data, i, x) \
PAIR(x); \
template<class Self> \
struct field_data<i, Self> \
{ \
    Self & self; \
    field_data(Self & self) : self(self) {} \
    \
    typename make_const<Self, TYPEOF(x)>::type & get() \
    { \
        return self.STRIP(x); \
    }\
    typename boost::add_const<TYPEOF(x)>::type & get() const \
    { \
        return self.STRIP(x); \
    }\
    const char * name() const \
    {\
        return BOOST_PP_STRINGIZE(STRIP(x)); \
    } \
}; \

What this does is generate a constant fields_n that is number of reflectable fields in the class. Then it specializes the field_data for each field. It also friends the reflector class, this is so it can access the fields even when they are private:
struct reflector
{
    //Get field_data at index N
    template<int N, class T>
    static typename T::template field_data<N, T> get_field_data(T& x)
    {
        return typename T::template field_data<N, T>(x);
    }

    // Get the number of fields
    template<class T>
    struct fields
    {
        static const int n = T::fields_n;
    };
};

Now to iterate over the fields we use the visitor pattern. We create an MPL range from 0 to the number of fields, and access the field data at that index. Then it passes the field data on to the user-provided visitor:
struct field_visitor
{
    template<class C, class Visitor, class T>
    void operator()(C& c, Visitor v, T)
    {
        v(reflector::get_field_data<T::value>(c));
    }
};

template<class C, class Visitor>
void visit_each(C & c, Visitor v)
{
    typedef boost::mpl::range_c<int,0,reflector::fields<C>::n> range;
    boost::mpl::for_each<range>(boost::bind<void>(field_visitor(), boost::ref(c), v, _1));
}

Now for the moment of truth we put it all together. Here is how we can define the Person class:
struct Person
{
    Person(const char *name, int age)
        :
        name(name),
        age(age)
    {
    }
private:
    REFLECTABLE
    (
        (const char *) name,
        (int) age
    )
};

Here is the generalized print_fields function:
struct print_visitor
{
    template<class FieldData>
    void operator()(FieldData f)
    {
        std::cout << f.name() << "=" << f.get() << std::endl;
    }
};

template<class T>
void print_fields(T & x)
{
    visit_each(x, print_visitor());
}

An example:
int main()
{
    Person p("Tom", 82);
    print_fields(p);
    return 0;
}

Which outputs:
name=Tom
age=82

And voila, we have just implemented reflection in C++, in under 100 lines of code.

A: Why do you need to use preprocessor? Introduction to boost.fusion library has an example somewhat similar to your use-case.

A: Here are my 2 cents as an addition to the great REFLECTABLE macro of Paul. I had a need to have an empty list of fields, i.e. REFLECTABLE(), to handle an inheritance hierarchy properly. The following modification handles this case:
// http://stackoverflow.com/a/2831966/2725810
#define REFLECTABLE_0(...)                                                     \
    static const int fields_n = BOOST_PP_VARIADIC_SIZE(__VA_ARGS__);           \
    friend struct reflector;                                                   \
    template <int N, class Self> struct field_data {};                         \
    BOOST_PP_SEQ_FOR_EACH_I(REFLECT_EACH, data,                                \
                            BOOST_PP_VARIADIC_TO_SEQ(__VA_ARGS__))

#define REFLECTABLE_1(...)                                                     \
    static const int fields_n = 0;

#define REFLECTABLE_CONST2(b, ...) REFLECTABLE_##b(__VA_ARGS__)

#define REFLECTABLE_CONST(b, ...) REFLECTABLE_CONST2(b,__VA_ARGS__)

#define REFLECTABLE(...)                                                      \
    REFLECTABLE_CONST(BOOST_PP_IS_EMPTY(__VA_ARGS__), __VA_ARGS__)

A: You need a tuple, not a class. This would easily solve all of your problems without having to resort to preprocessor hackery.


text:
Q: Baby talk function I want to construct a function where the input is a normal sentence and the output is that sentence translated to "child language". Child language means to only say the first syllable in every word but saying it 3 times.
So "hello world" would be "hehehe wowowo".
My idea is to first split the sentence into a list of words. Then for every word we should have a counter that starts at 0. If consonant the counter adds 0 - if vowel the counter adds 1. When the counter 1 one we stop, return the consonants and the vowel and go to the next word. But I am having trouble "accessing" going through every word in the list. How can I set my idea in to practice?

A: Don't use a 0-1 counter; that's called a Boolean flag.  When you find the vowel, just continue to the next step.
vowel_list = 'aeiou'
sentence = "hello world"

# split the sentence into a list of words.
word_list = sentence.split()
for word in word_list:
    # Find the minimal pronounceable prefix and print it 3 times
    # Find the first vowel
    for i in range(len(word)):
        if word[i] in vowel_list:
            # Grab the consonants and vowel, and stop
            syllable = word[:i+1]
            break
    # Report the syllable in triplicate
    print syllable*3

The output from this is
hehehe
wowowo

That should get you through the immediate questions.  You still get to cobble this into a function the way you described, and then put the individual baby words into a baby sentence.  I'll also leave it to you to handle problem cases, such as
each
school
rhythm

If this doesn't solve anything for you, then please edit the question with a clearer description.

A: Here's baby talk generated based on word pronunciations and written using arpabet:
#!/usr/bin/env python3
from nltk.corpus import cmudict  # $ pip install nltk
# >>> nltk.download('cmudict')

def baby_talk(word, repeat=3, phone_sep=u'\N{NO-BREAK SPACE}',
              pronunciations=cmudict.dict()):
    for phones in pronunciations.get(word.casefold(), []):
        for i, ph in enumerate(phones):
            if ph[-1] in '012':  # found vowel sound
                return phone_sep.join((phones[:i] + [ph[:-1]]) * repeat)
    return naive_baby_talk(word, repeat, phone_sep)  # no pronunciations

def naive_baby_talk(word, repeat, phone_sep, vowels="aeiouAEIOU"):
    i = None
    for i, char in enumerate(word, start=1):
        if char in vowels:
            break  # found vowel
    return phone_sep.join([word[:i]] * repeat)

Example:
import re

sentences = ["hello world",
             "Quiet European rhythms.",
             "My nth happy hour.",
             "Herb unit -- a dynasty heir."]
for sentence in sentences:
    sesese = " ".join(["".join(
        [w if i & 1 or not w else baby_talk(w)  # keep non-words as is
         for i, w in enumerate(re.split("(\W+)", non_whitespace))])
        for non_whitespace in sentence.split()])
    print(u'"{}" → "{}"'.format(sentence, sesese))

Output
"hello world" → "HH AH HH AH HH AH W ER W ER W ER"
"Quiet European rhythms." → "K W AY K W AY K W AY Y UH Y UH Y UH R IH R IH R IH."
"My nth happy hour." → "M AY M AY M AY EH EH EH HH AE HH AE HH AE AW AW AW."
"Herb unit -- a dynasty heir." → "ER ER ER Y UW Y UW Y UW -- AH AH AH D AY D AY D AY EH EH EH."
Note:

*

*nth, hour, herb, heir start with a vowel

*European, unit start with a consonant

*y in "rhythms", "dynasty" is a vowel

See:

*

*Pig Latin Translator

*Python: How to prepend the string 'ub' to every pronounced vowel in a string?

A: def end_at_vowel(string):
    vowels = ["a","e","i","o","u"] # A list of vowels
    letters = []
    for l in string:
        letters += l
        if l in vowels:
            break
    return "".join(letters)
def bbt(string):
    string = string.split() #Split the string into a list
    return " ".join([end_at_vowel(w) * 3 for w in string])

This should handle mostly what you described. Take a look at the comments and the two functions and see if you can decipher what is happening.

A: This is one of the few times I'd recommend regular expressions:
import re

FIRST_SYLLABLE = re.compile(r'.*?[aeiou]', re.IGNORECASE)

def baby_talk(sentence):
    words = []
    for word in sentence.split():
        match = FIRST_SYLLABLE.match(word)
        if match:
            words.append(match.group(0) * 3)
    return ' '.join(words)

print baby_talk('hello world')

Line by line:
import re

FIRST_SYLLABLE = re.compile(r'.*?[aeiou]', re.IGNORECASE)

This makes a compiled pattern that matches anything up to and including the first vowel.
def baby_talk(sentence):
    words = []
    for word in sentence.split():
        match = FIRST_SYLLABLE.match(word)

This attempts to match the word against our compiled pattern.
        if match:
            words.append(match.group(0) * 3)

If it works, match.group(0) contains the matching portion. Given 'hello', match.group(0) will be 'he'. Make three copies of it and add it to the output word list.
    return ' '.join(words)

Return the output word list joined together by spaces.
print baby_talk('hello world')


text:
Q: R mutate last row of group I have a dataframe where the first column represents the date and it covers the span of a few months. I then duplicate the last row of each month using How to duplicate last row by group (ID)?
What I'm hoping to achieve now is to modify a certain column of that duplicated row. I'll explain it better with a snippet of my data (attached at the bottom):
# A tibble: 11 × 3
   date        file value
   <date>     <int> <dbl>
 1 2021-07-26     1   858
 2 2021-07-27     1   880
 3 2021-07-28     1   904
 4 2021-07-29     1   933
 5 2021-07-30     1   970
 6 2021-07-31     1  1010
 7 2021-07-31     1  1010
 8 2021-08-01     2  1048
 9 2021-08-02     2  1078
10 2021-08-03     2  1096
11 2021-08-04     2  1107

As you can see, rows 6 and 7 are the same. Row 7 is the duplicate of 6 and I would like to change the "file" column from "1" to "2" so I can then get that row as the first row of the group "file==2".
Expected output (for clarification):
# A tibble: 11 × 3
   date        file value
   <date>     <int> <dbl>
 1 2021-07-26     1   858
 2 2021-07-27     1   880
 3 2021-07-28     1   904
 4 2021-07-29     1   933
 5 2021-07-30     1   970
 6 2021-07-31     1  1010
 7 2021-07-31     2  1010  # file changed from 1 to 2 as desired
 8 2021-08-01     2  1048
 9 2021-08-02     2  1078
10 2021-08-03     2  1096
11 2021-08-04     2  1107

Data:
df <- structure(list(date = structure(c(18834, 18835, 18836, 18837,
18838, 18839, 18839, 18840, 18841, 18842, 18843), class = "Date"),
    file = c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L), value = c(858,
    880, 904, 933, 970, 1010, 1010, 1048, 1078, 1096, 1107)), row.names = c(NA,
-11L), class = c("tbl_df", "tbl", "data.frame"))

A: One possible way to solve your probelm:
df %>%
  mutate(file = file + duplicated(.))

# A tibble: 11 x 3
   date        file value
   <date>     <int> <dbl>
 1 2021-07-26     1   858
 2 2021-07-27     1   880
 3 2021-07-28     1   904
 4 2021-07-29     1   933
 5 2021-07-30     1   970
 6 2021-07-31     1  1010
 7 2021-07-31     2  1010
 8 2021-08-01     2  1048
 9 2021-08-02     2  1078
10 2021-08-03     2  1096
11 2021-08-04     2  1107

A: A possible solution:
library(dplyr)

df %>%
  mutate(file = file + data.table::rowid(.$date) - 1)

#> # A tibble: 11 × 3
#>    date        file value
#>    <date>     <dbl> <dbl>
#>  1 2021-07-26     1   858
#>  2 2021-07-27     1   880
#>  3 2021-07-28     1   904
#>  4 2021-07-29     1   933
#>  5 2021-07-30     1   970
#>  6 2021-07-31     1  1010
#>  7 2021-07-31     2  1010
#>  8 2021-08-01     2  1048
#>  9 2021-08-02     2  1078
#> 10 2021-08-03     2  1096
#> 11 2021-08-04     2  1107

Another possible solution:
library(dplyr)

df %>%
  group_by(date) %>%
  mutate(file = first(file):(first(file)+n()-1)) %>%
  ungroup

#> # A tibble: 11 × 3
#>    date        file value
#>    <date>     <int> <dbl>
#>  1 2021-07-26     1   858
#>  2 2021-07-27     1   880
#>  3 2021-07-28     1   904
#>  4 2021-07-29     1   933
#>  5 2021-07-30     1   970
#>  6 2021-07-31     1  1010
#>  7 2021-07-31     2  1010
#>  8 2021-08-01     2  1048
#>  9 2021-08-02     2  1078
#> 10 2021-08-03     2  1096
#> 11 2021-08-04     2  1107


text:
Q: How to superscript in a link

.project-link {
font-family:Arial;
display:inline-block;
color:#FFF;
font-size:5vw;
white-space:nowrap;
text-decoration:underline;
margin-right: 3%;
line-height:120%;
}
body {
  background-color: black;
}
Maru Speaker Design  (1)
 span { vertical-align:super; }

body {
  background-color: black;
}
Maru Speaker Design  (1)
<