text:
Q: Android drawing in loop This is the class i use for animated drawing, it takes starting and final point of a curve and the number of curves to render.
public class DrawIt extends View {
    Context context;
    int[] z;
    int[] k;
    Path[] patharr;
    Path[] drawarr;
    Paint paint = new Paint();
    Paint paint2 = new Paint();
    Paint paint3 = new Paint();
    Random r = new Random();
    float x1;
    float y1;
    float x3;
    float y3;
    float x2;
    float y2;
    int ref;
    public boolean finito = false;

    public DrawIt(Context context, int a, int b, int c, int d,
            final int num) {

        super(context);
        this.context = context;
        setBackgroundResource(com.example.test.R.drawable.endturn);

        this.ref = num;
        x1 = a;
        y1 = b;
        x3 = c;
        y3 = d;
        if (x1 < x3) {
            x2 = (x1 + x3) / 2 - 50;
        } else {
            x2 = (x1 + x3) / 2 + 50;
        }

        y2 = (y1 + y3) / 2 - 350;

        paint.setAntiAlias(true);
        paint.setAlpha(255);
        paint.setStrokeWidth(2);
        paint.setColor(Color.WHITE);
        paint.setStyle(Style.STROKE);
        paint.setPathEffect(new DashPathEffect(new float[] { 2, 4 }, 50));

        paint2.setAntiAlias(true);
        paint2.setAlpha(55);
        paint2.setStrokeWidth(1);
        paint2.setColor(Color.WHITE);
        paint2.setStyle(Style.FILL);

        paint3.setAntiAlias(true);
        paint3.setAlpha(255);
        paint3.setStrokeWidth(2);
        paint3.setColor(Color.RED);
        paint3.setStyle(Style.STROKE);

        drawarr = new Path[num];
        patharr = new Path[num];
        z = new int[num];
        k = new int[num];
        for (int p = 0; p < num; p++) {
            k[p] = r.nextInt(50 - 1) - 1;
            z[p] = r.nextInt(50 - 1) - 1;
            patharr[p] = new Path();
            patharr[p].moveTo(x1, y1);
            patharr[p].quadTo(x2, y2, x3 + k[p], y3 + z[p]);

        }

        final long DRAW_TIME = 800;
        CountDownTimer timer = new CountDownTimer(DRAW_TIME, 100) {
            PathMeasure[] measarr = new PathMeasure[num];
            Path[] segmarr = new Path[num];
            float[] startarr = new float[num];
            float[] lengtharr = new float[num];

            @Override
            public void onTick(long millisUntilFinished) {

                for (int p = 0; p < num; p++) {
                    measarr[p] = new PathMeasure();
                    segmarr[p] = new Path();
                    measarr[p].setPath(patharr[p], false);
                    startarr[p] = 0;
                }
                float percent = ((float) (DRAW_TIME - millisUntilFinished))
                        / (float) DRAW_TIME;

                for (int p = 0; p < num; p++) {
                    lengtharr[p] = measarr[p].getLength() * percent;
                }

                for (int p = 0; p < num; p++) {
                    measarr[p].getSegment(startarr[p], lengtharr[p],
                            segmarr[p], true);
                }

                for (int p = 0; p < num; p++) {
                    startarr[p] = lengtharr[p];
                }

                for (int p = 0; p < num; p++) {
                    drawarr[p] = new Path();
                    drawarr[p].addPath(segmarr[p]);
                }

                invalidate();
            }

            @Override
            public void onFinish() {
                for (int p = 0; p < num; p++) {
                    measarr[p].getSegment(startarr[p], measarr[p].getLength(),
                            segmarr[p], true);
                }
                for (int p = 0; p < num; p++) {
                    drawarr[p].addPath(segmarr[p]);
                }
                if (measarr[0].getSegment(startarr[0], measarr[0].getLength(),
                        segmarr[0], false)) {
                    finito = true;
                }
                invalidate();
            }
        };
        timer.start();

    }

    @Override
    public void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        Log.d("Costruttore", "" + drawarr[0]);

        for (int p = 0; p < drawarr.length; p++) {
            canvas.drawPath(drawarr[p], paint);
        }

        if (finito == true) {
            for (int m = 0; m < drawarr.length; m++) {
                canvas.drawCircle(x3 + k[m], y3 + z[m], 10, paint2);
                canvas.drawCircle(x3 + k[m], y3 + z[m], 10, paint3);
            }

        }

    }
}

DrawIt is called in this way, inside a CountDownTimer, after doing end turn calculations for a game:
@Override
            public void onTick(long millisUntilFinished) {
                if (l < players.length) {
                    while (l < players.length && players[l].mess.equals(".")) {
                        l++;
                        }
                    if (l >= players.length) {
                        this.cancel();
                    } else {
                        azioni.setText(players[l].mess);
                        players[l].vista = new DrawIt(TurnActivity.this, x1,y1,x2,y2);
                        addContentView(players[l].vista, layout);
                        l++;

                    }
                }
            }

This is resulting in a NullPointerException on the Ondraw. I can't understand why. I'm Android novice, maybe this could be the chance to understand more about View and this kind of animations made with CountDownTimer.
Here's Logcat:
04-23 16:00:26.175: W/dalvikvm(1135): threadid=1: thread exiting with uncaught exception (group=0xa4dcab20)
04-23 16:00:26.179: E/AndroidRuntime(1135): FATAL EXCEPTION: main
04-23 16:00:26.179: E/AndroidRuntime(1135): Process: com.example.test, PID: 1135
04-23 16:00:26.179: E/AndroidRuntime(1135): java.lang.NullPointerException
04-23 16:00:26.179: E/AndroidRuntime(1135):     at android.view.GLES20Canvas.drawPath(GLES20Canvas.java:1059)
04-23 16:00:26.179: E/AndroidRuntime(1135):     at com.example.test.DrawIt.onDraw(DrawIt.java:154)
04-23 16:00:26.179: E/AndroidRuntime(1135):     at android.view.View.draw(View.java:14465)
04-23 16:00:26.179: E/AndroidRuntime(1135):     at android.view.View.getDisplayList(View.java:13362)
04-23 16:00:26.179: E/AndroidRuntime(1135):     at android.view.View.getDisplayList(View.java:13404)
04-23 16:00:26.179: E/AndroidRuntime(1135):     at android.view.View.draw(View.java:14182)
04-23 16:00:26.179: E/AndroidRuntime(1135):     at android.view.ViewGroup.drawChild(ViewGroup.java:3103)
04-23 16:00:26.179: E/AndroidRuntime(1135):     at android.view.ViewGroup.dispatchDraw(ViewGroup.java:2940)
04-23 16:00:26.179: E/AndroidRuntime(1135):     at android.view.View.getDisplayList(View.java:13357)
04-23 16:00:26.179: E/AndroidRuntime(1135):     at android.view.View.getDisplayList(View.java:13404)
04-23 16:00:26.179: E/AndroidRuntime(1135):     at android.view.View.draw(View.java:14182)
04-23 16:00:26.179: E/AndroidRuntime(1135):     at android.view.ViewGroup.drawChild(ViewGroup.java:3103)
04-23 16:00:26.179: E/AndroidRuntime(1135):     at android.view.ViewGroup.dispatchDraw(ViewGroup.java:2940)
04-23 16:00:26.179: E/AndroidRuntime(1135):     at android.view.View.getDisplayList(View.java:13357)
04-23 16:00:26.179: E/AndroidRuntime(1135):     at android.view.View.getDisplayList(View.java:13404)
04-23 16:00:26.179: E/AndroidRuntime(1135):     at android.view.View.draw(View.java:14182)
04-23 16:00:26.179: E/AndroidRuntime(1135):     at android.view.ViewGroup.drawChild(ViewGroup.java:3103)
04-23 16:00:26.179: E/AndroidRuntime(1135):     at android.view.ViewGroup.dispatchDraw(ViewGroup.java:2940)
04-23 16:00:26.179: E/AndroidRuntime(1135):     at android.view.View.draw(View.java:14468)
04-23 16:00:26.179: E/AndroidRuntime(1135):     at android.widget.FrameLayout.draw(FrameLayout.java:472)
04-23 16:00:26.179: E/AndroidRuntime(1135):     at com.android.internal.policy.impl.PhoneWindow$DecorView.draw(PhoneWindow.java:2326)
04-23 16:00:26.179: E/AndroidRuntime(1135):     at android.view.View.getDisplayList(View.java:13362)
04-23 16:00:26.179: E/AndroidRuntime(1135):     at android.view.View.getDisplayList(View.java:13404)
04-23 16:00:26.179: E/AndroidRuntime(1135):     at android.view.HardwareRenderer$GlRenderer.buildDisplayList(HardwareRenderer.java:1570)
04-23 16:00:26.179: E/AndroidRuntime(1135):     at android.view.HardwareRenderer$GlRenderer.draw(HardwareRenderer.java:1449)
04-23 16:00:26.179: E/AndroidRuntime(1135):     at android.view.ViewRootImpl.draw(ViewRootImpl.java:2381)
04-23 16:00:26.179: E/AndroidRuntime(1135):     at android.view.ViewRootImpl.performDraw(ViewRootImpl.java:2253)
04-23 16:00:26.179: E/AndroidRuntime(1135):     at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1883)
04-23 16:00:26.179: E/AndroidRuntime(1135):     at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1000)
04-23 16:00:26.179: E/AndroidRuntime(1135):     at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5670)
04-23 16:00:26.179: E/AndroidRuntime(1135):     at android.view.Choreographer$CallbackRecord.run(Choreographer.java:761)
04-23 16:00:26.179: E/AndroidRuntime(1135):     at android.view.Choreographer.doCallbacks(Choreographer.java:574)
04-23 16:00:26.179: E/AndroidRuntime(1135):     at android.view.Choreographer.doFrame(Choreographer.java:544)
04-23 16:00:26.179: E/AndroidRuntime(1135):     at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:747)
04-23 16:00:26.179: E/AndroidRuntime(1135):     at android.os.Handler.handleCallback(Handler.java:733)
04-23 16:00:26.179: E/AndroidRuntime(1135):     at android.os.Handler.dispatchMessage(Handler.java:95)
04-23 16:00:26.179: E/AndroidRuntime(1135):     at android.os.Looper.loop(Looper.java:136)
04-23 16:00:26.179: E/AndroidRuntime(1135):     at android.app.ActivityThread.main(ActivityThread.java:5017)
04-23 16:00:26.179: E/AndroidRuntime(1135):     at java.lang.reflect.Method.invokeNative(Native Method)
04-23 16:00:26.179: E/AndroidRuntime(1135):     at java.lang.reflect.Method.invoke(Method.java:515)
04-23 16:00:26.179: E/AndroidRuntime(1135):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
04-23 16:00:26.179: E/AndroidRuntime(1135):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
04-23 16:00:26.179: E/AndroidRuntime(1135):     at dalvik.system.NativeStart.main(Native Method)
04-23 16:00:27.983: I/Process(1135): Sending signal. PID: 1135 SIG: 9


text:
Q: force:recordData redirect to created record on Salesforce mobile app I created an overwrite for the "new"-button on a custom object via a Lightning Component.
On the desktop everything works fine but the Salesforce mobile app causes some issues.
The component contains the following:
    <force:recordData aura:id="forceRecord"
                      recordId="{!v.recordId}"
                      targetFields="{!v.record}"
                      fields="Id, Name, Street__c, PostalCode__c, City__c, Country__c"
                      mode="EDIT" />

   <lightning:button variant="brand" label="Submit" onclick="{!c.saveRecord}" />

Within the controller I execute a redirect to the created record with the following snippet:
    var tempRec = component.find("forceRecord");
    tempRec.saveRecord($A.getCallback(function(result) {
    if (result.state === "SUCCESS") {
        var navEvt = $A.get("e.force:navigateToSObject");
        navEvt.setParams({
          "recordId": result.recordId
        });
        navEvt.fire();
    }

This works on desktop but not on Salesforce mobile app.
I also tried window.location.href = '/' + result.recordId; without success.
Any ideas how I can make it work on mobile as well?
Thanks
Chris

A: Seems not to be possible - therefore I wrote the method by my own.
This solved the problem.

redpajama_set_name: RedPajamaStackExchange


text:
Q: WP8 MvvmLight namespace missing and EventToCommand doesn't exist I am using MVVM Light libraries only (from Nuget package) in my Windows Phone 8 project and I want to use EventToCommand in ToggleSwitch. I have these lines of codes:
<toolkit:ToggleSwitch x:Name="LockSwitch"
        IsChecked="{Binding IsLock, Mode=TwoWay}">
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="Toggled">
            <Command:EventToCommand
                Command="{Binding DataContext.NavigateToArticleCommand, ElementName=LayoutRoot}"
                CommandParameter="{Binding}" />
        </i:EventTrigger>
    </i:Interaction.Triggers>
</toolkit:ToggleSwitch>

The problem is that VS shows errors:

Error 1   The name "EventToCommand" does not exist in the namespace
  "clr-namespace:GalaSoft.MvvmLight.Command;assembly=GalaSoft.MvvmLight.Extras.WP8".
Error 2   The type 'Command:EventToCommand' was not found. Verify that
  you are not missing an assembly reference and that all referenced
  assemblies have been built.
Error 3   The tag 'EventToCommand' does not exist in XML namespace
  'clr-namespace:GalaSoft.MvvmLight.Command;assembly=GalaSoft.MvvmLight.Extras.WP8'.

I have lines above in file Styles.xaml which is a ResourceDictionary and ToggleSwitch is part of a DataTemplate. I am including MvvmLight library using this line:
xmlns:Command="clr-namespace:GalaSoft.MvvmLight.Command;assembly=GalaSoft.MvvmLight.Extras.WP8"

What's wrong? Why I get that error? I was trying to use google but I couldn't find a solution.

A: The reference that you use to include the command is wrong. The correct reference is
xmlns:Command="clr-namespace:GalaSoft.MvvmLight.Command;assembly=GalaSoft.MvvmLight.Platform"

There's a trick to obtain this reference without writing a single line of code.
After you have downloaded the MvvmLight nuget package, compile your project and then open your xaml file in Expression Blend.
Then click the Assets icon on the left toolbar (the bottom one) and start typing "eventtocommand" (see picture below).

Once you see EventToCommand appear in the Assets panel, drag and drop it on top of your ToggleSwitch. That's it! The reference will be added into your xaml automatically as well as the actual command code.

A: Why not use Microsoft.Behaviors SDK ? (references, add reference, extensions, behavior sdk) Not sure but I think EventTrigger and mvvm light EventToCommand is deprecated now (because of behaviors sdk).
Code sample with Behaviors.SDK:
xmlns:interactivity="using:Microsoft.Xaml.Interactivity"
xmlns:core="using:Microsoft.Xaml.Interactions.Core"

<toolkit:ToggleSwitch x:Name="LockSwitch"
        IsChecked="{Binding IsLock, Mode=TwoWay}">
            <interactivity:Interaction.Behaviors>
                <core:EventTriggerBehavior EventName="Toggled">
                    <core:InvokeCommandAction Command="{Binding command}" CommandParameter="{Binding param}"/>
                </core:EventTriggerBehavior>
            </interactivity:Interaction.Behaviors>
</toolkit:ToggleSwitch>


text:
Q: Reject rabbitMQ message with pre-message TTL I have added ttl (30seconds) in the queue during the auto-creation of the queue in the RabbitConfig class. I would like to extended/reduced ttl(10seconds) for certain message and reject them, when necessary, inside the @RabbitListener method (listenToMain()).
I have managed to figure out that I am able to include the ttl(10seconds) in every message, which I have done it in the MyService.call(), but when the message goes back to the main-queue, the ttl will go back to the ttl (30seconds) I have set in the queue. How can I code it in a way that, the ttl will always be indicated in the MyService.call()?
Here are my codes:
RabbitConfig.java
@Configuration
public class RabbitConfig{

    /*Setup all the RabbitTemplate etc code*/

    //Auto creation of queue
    String mainQueue = "main-queue";
    String subQueue = "sub-queue";

    String mainExchange = "main-exchange";
    String subExchange = "sub-exchange";

    String mainRouting = "mainroute";
    String subRouting = "subroute";

    @Bean
    Queue mainQueue(){
        Map<String, Object> args = new HashMap();
        args.put("x-dead-letter-exchange", subExchange);
        args.put("x-dead-letter-routing-key", subRouting);

        return ....to build this queue with the args values.....
    }

    @Bean
    Queue subQueue(){
        Map<String, Object> args = new HashMap();
        args.put("x-dead-letter-exchange", mainExchange);
        args.put("x-dead-letter-routing-key", mainRouting);
        args.put("x-message-ttl", 30000);

        return ....to build this queue with the args values.....
    }

    @Bean
    Exchange mainExchange(){
        return ......to build the main exchange......
    }

    @Bean
    Exchange subExchange(){
        return ......to build the sub exchange......
    }

    @Bean
    Binding mainBinding(){
        return ...tobind the mainExchange() and mainQueue().......
    }

    @Bean
    Binding subBinding(){
        return ...tobind the subExchange() and subQueue().......
    }
}

MyMessagePostProcessor.java
public class MyMessagePostProcessor implements MessagePostProcessor {

    private final Integer ttl;

    public MyMessagePostProcessor(final Integer ttl) {
        this.ttl = ttl;
    }

    @Override
    public Message postProcessMessage(final Message message) throws AmqpException {
        message.getMessageProperties().getHeaders().put("expiration", ttl.toString());
        return message;
    }
}

MyService.java
@Service
public class MyService{
    public void call(){
        final String message = "message";
        final MessagePostProcessor messagePostProcessor = new MyMessagePostProcessor(10000);
        rabbitTemplate.convertAndSend("sub-exchange", "subroute", message, messagePostProcessor);
    }
}

RabbitConsume.java
@Service
public class RabbitConsume{
    @RabbitListener(queue="main-queue")
    public void listenToMain(String msg, Channel channel,
        @Header(AmqpHeaders.DELIVERY_TAG) long tag
    ){
        channel.basicReject(tag, false)
    }
}


text:
Q: How to fetch phone numbers from string? I have string whom fetch from database but all having different format so how can i fetch phone numbers from that strings
String Examples
user name;foo@foo.com;0373XXXXXX;fooo;ccc
user name;foo@foo.com;fooo;0373XXXXXX;ccc
user name;0373XXXXXX;foo@foo.com;fooo;ccc

and here 0373XXXXXX is 10 digit phone number of user

A: Use below code :
<?php

$string = "user name;foo@foo.com;0373123456;fooo;ccc";

preg_match_all('!\d+!', $string, $matches);
print_r($matches);

?>

Hope it will help you :)


text:
Q: Python 3.5 setup.py egg_info failed with error code 1 [Linux] Me and a friend are trying to setup a discord bot through DigitalOcean. However, when we run the command "sudo -H pip3.5 install --upgrade -r requirements.txt" or something along those lines it always ends up with the same error.
We have tried installing python, it's already up to date.
Here are the logs.
You may need to use sudo to install dependencies.

root@discord-bot:~/RadioOP# sudo -H pip3.5 install --upgrade -r requirements.txt
Collecting https://github.com/Rapptz/discord.py/archive/async.zip (from -r requirements.txt (line 1))
  Downloading https://github.com/Rapptz/discord.py/archive/async.zip (442kB)
    100% |████████████████████████████████| 450kB 2.5MB/s
Collecting youtube_dl>=2016.4.24 (from -r requirements.txt (line 2))
  Using cached youtube_dl-2016.6.3-py2.py3-none-any.whl
Collecting aiohttp<0.22.0,>=0.21.0 (from discord.py==0.10.0a0->-r requirements.txt (line 1))
  Using cached aiohttp-0.21.6.tar.gz
Collecting websockets==3.1 (from discord.py==0.10.0a0->-r requirements.txt (line 1))
  Using cached websockets-3.1.tar.gz
Collecting PyNaCl==1.0.1 (from discord.py==0.10.0a0->-r requirements.txt (line 1))
  Using cached PyNaCl-1.0.1.tar.gz
    Complete output from command python setup.py egg_info:
    No working compiler found, or bogus compiler options
    passed to the compiler from Python's distutils module.
    See the error messages above.
    (If they are about -mno-fused-madd and you are on OS/X 10.8,
    see http://stackoverflow.com/questions/22313407/ .)
Traceback (most recent call last):
  File "/usr/local/lib/python3.5/dist-packages/setuptools/sandbox.py", line 154, in save_modules
    yield saved
  File "/usr/local/lib/python3.5/dist-packages/setuptools/sandbox.py", line 195, in setup_context
    yield
  File "/usr/local/lib/python3.5/dist-packages/setuptools/sandbox.py", line 243, in run_setup
    DirectorySandbox(setup_dir).run(runner)
  File "/usr/local/lib/python3.5/dist-packages/setuptools/sandbox.py", line 273, in run
    return func()
  File "/usr/local/lib/python3.5/dist-packages/setuptools/sandbox.py", line 242, in runner
    _execfile(setup_script, ns)
  File "/usr/local/lib/python3.5/dist-packages/setuptools/sandbox.py", line 46, in _execfile
    exec(code, globals, locals)
  File "/tmp/easy_install-7oxtbavt/cffi-1.6.0/setup.py", line 111, in <module>

  File "/tmp/easy_install-7oxtbavt/cffi-1.6.0/setup.py", line 65, in ask_supports_thread

  File "/tmp/easy_install-7oxtbavt/cffi-1.6.0/setup.py", line 52, in no_working_compiler_found

SystemExit: 1

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/usr/local/lib/python3.5/dist-packages/setuptools/command/easy_install.py", line 1101, in run_setup
    run_setup(setup_script, args)
  File "/usr/local/lib/python3.5/dist-packages/setuptools/sandbox.py", line 246, in run_setup
    raise
  File "/usr/lib/python3.5/contextlib.py", line 77, in __exit__
    self.gen.throw(type, value, traceback)
  File "/usr/local/lib/python3.5/dist-packages/setuptools/sandbox.py", line 195, in setup_context
    yield
  File "/usr/lib/python3.5/contextlib.py", line 77, in __exit__
    self.gen.throw(type, value, traceback)
  File "/usr/local/lib/python3.5/dist-packages/setuptools/sandbox.py", line 166, in save_modules
    saved_exc.resume()
  File "/usr/local/lib/python3.5/dist-packages/setuptools/sandbox.py", line 141, in resume
    six.reraise(type, exc, self._tb)
  File "/usr/local/lib/python3.5/dist-packages/pkg_resources/_vendor/six.py", line 685, in reraise
    raise value.with_traceback(tb)
  File "/usr/local/lib/python3.5/dist-packages/setuptools/sandbox.py", line 154, in save_modules
    yield saved
  File "/usr/local/lib/python3.5/dist-packages/setuptools/sandbox.py", line 195, in setup_context
    yield
  File "/usr/local/lib/python3.5/dist-packages/setuptools/sandbox.py", line 243, in run_setup
    DirectorySandbox(setup_dir).run(runner)
  File "/usr/local/lib/python3.5/dist-packages/setuptools/sandbox.py", line 273, in run
    return func()
  File "/usr/local/lib/python3.5/dist-packages/setuptools/sandbox.py", line 242, in runner
    _execfile(setup_script, ns)
  File "/usr/local/lib/python3.5/dist-packages/setuptools/sandbox.py", line 46, in _execfile
    exec(code, globals, locals)
  File "/tmp/easy_install-7oxtbavt/cffi-1.6.0/setup.py", line 111, in <module>

  File "/tmp/easy_install-7oxtbavt/cffi-1.6.0/setup.py", line 65, in ask_supports_thread

  File "/tmp/easy_install-7oxtbavt/cffi-1.6.0/setup.py", line 52, in no_working_compiler_found

SystemExit: 1

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "/tmp/pip-build-qb7qi39t/PyNaCl/setup.py", line 259, in <module>
    "Programming Language :: Python :: 3.5",
  File "/usr/lib/python3.5/distutils/core.py", line 108, in setup
    _setup_distribution = dist = klass(attrs)
  File "/usr/local/lib/python3.5/dist-packages/setuptools/dist.py", line 269, in __init__
    self.fetch_build_eggs(attrs['setup_requires'])
  File "/usr/local/lib/python3.5/dist-packages/setuptools/dist.py", line 313, in fetch_build_eggs
    replace_conflicting=True,
  File "/usr/local/lib/python3.5/dist-packages/pkg_resources/__init__.py", line 826, in resolve
    dist = best[req.key] = env.best_match(req, ws, installer)
  File "/usr/local/lib/python3.5/dist-packages/pkg_resources/__init__.py", line 1092, in best_match
    return self.obtain(req, installer)
  File "/usr/local/lib/python3.5/dist-packages/pkg_resources/__init__.py", line 1104, in obtain
    return installer(requirement)
  File "/usr/local/lib/python3.5/dist-packages/setuptools/dist.py", line 380, in fetch_build_egg
    return cmd.easy_install(req)
  File "/usr/local/lib/python3.5/dist-packages/setuptools/command/easy_install.py", line 665, in easy_install
    return self.install_item(spec, dist.location, tmpdir, deps)
  File "/usr/local/lib/python3.5/dist-packages/setuptools/command/easy_install.py", line 695, in install_item
    dists = self.install_eggs(spec, download, tmpdir)
  File "/usr/local/lib/python3.5/dist-packages/setuptools/command/easy_install.py", line 876, in install_eggs
    return self.build_and_install(setup_script, setup_base)
  File "/usr/local/lib/python3.5/dist-packages/setuptools/command/easy_install.py", line 1115, in build_and_install
    self.run_setup(setup_script, setup_base, args)
  File "/usr/local/lib/python3.5/dist-packages/setuptools/command/easy_install.py", line 1103, in run_setup
    raise DistutilsError("Setup script exited with %s" % (v.args[0],))
distutils.errors.DistutilsError: Setup script exited with 1

----------------------------------------

Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-qb7qi39t/PyNaCl/
Thanks in advance for help.

A: Well, I fixed the problem by asking the "Discord API."
Heres how I fixed it:

sudo apt install build-essential

and then

sudo apt install build-essential libffi-dev python3.5-dev

and then I ran my command

A: Pip tried to download PyNaCL which needs to compile a python extension module from source. For that you need to have the right development libraries installed and ofc a working compiler setup. Hence the message no_working_compiler_found. You can try to find a complete binary wheel for PyNaCL, install that manually and afterwards run your original install command again.


text:
Q: How to Retrieve a File's "Product Version" in VBScript I have a VBScript that checks for the existence of a file in a directory on a remote machine.  I am looking to retrieve the "Product Version" for said file (NOT "File Version"), but I can't seem to figure out how to do that in VBScript.
I'm currently using Scripting.FileSystemObject to check for the existence of the file.
Thanks.

A: You can use the Shell.Namespace to get the extended properties on a file, one of which is the Product Version. The GetDetailsOf function should work. You can test with the following code to get an idea:
Dim fillAttributes(300)

Set shell = CreateObject("Shell.Application")
Set folder = shell.Namespace("C:\Windows")

Set file = folder.ParseName("notepad.exe")

For i = 0 to 299
    Wscript.Echo i & vbtab & fillAttributes(i) _
        & ": " & folder.GetDetailsOf(file, i)
Next

One thing to be aware of:
The extended properties of a file differs between versions of Windows. Hence, the product version index numbers changes based on the version of Windows you are using. You can use the code above to determine what they are. From my testing, I believe they are as follows:

*

*Window XP - 39

*Windows Vista - 252

*Windows 7 - 268

*Windows 2008 R2 SP1 - 271

*Windows 2012 R2 - 285

You may also find the following post helpful.

A: The product version can be retrieved directly with the ExtendedProperty method.
function GetProductVersion(Path)
    dim shell, file
    set shell = CreateObject("Shell.Application")
    const ssfDesktop = 0
    set file = shell.Namespace(ssfDesktop).ParseName(Path)
    if not (file is nothing) then
        GetProductVersion = _
            file.ExtendedProperty("System.Software.ProductVersion")
    end if
end function

By contrast with a couple of older answers,

*

*This does not require looping over an unknown or arbitrary number of columns with GetDetailsOf.

*This uses the canonical name of the property, not the display name. One can also use the FMTID and PID: "{0CEF7D53-FA64-11D1-A203-0000F81FEDEE} 8".

*This avoids the need to split the path into directory and name, by starting at the root (desktop) namespace.

A: I use a function that is slightly modified from the previous example.  The function takes the path and file name and returns the "Product Version"
Function GetProductVersion (sFilePath, sProgram)
Dim FSO,objShell, objFolder, objFolderItem, i
Set FSO = CreateObject("Scripting.FileSystemObject")
If FSO.FileExists(sFilePath & "\" & sProgram) Then
    Set objShell = CreateObject("Shell.Application")
    Set objFolder = objShell.Namespace(sFilePath)
    Set objFolderItem = objFolder.ParseName(sProgram)
    Dim arrHeaders(300)
    For i = 0 To 300
        arrHeaders(i) = objFolder.GetDetailsOf(objFolder.Items, i)
        'WScript.Echo i &"- " & arrHeaders(i) & ": " & objFolder.GetDetailsOf(objFolderItem, i)
        If lcase(arrHeaders(i))= "product version" Then
            GetProductVersion= objFolder.GetDetailsOf(objFolderItem, i)
            Exit For
        End If
    Next
End If
End Function

I've found that the position of the attributes has occasionally changes (not sure why) in XP and Vista so I look for the "product version" attribute and exit the loop once it's found.  The commented out line will show all the attributes and a value if available

A: ' must explicitly declare all variables
Option Explicit
' declare global variables
Dim aFileFullPath, aDetail
' set global variables
aFileFullPath = "C:\Windows\Notepad.exe"
aDetail = "Product Version"
' display a message with file location and file detail
WScript.Echo ("File location: " & vbTab & aFileFullPath & vbNewLine & _
aDetail & ": " & vbTab & fGetFileDetail(aFileFullPath, aDetail))
' make global variable happy. set them free
Set aFileFullPath = Nothing
Set aDetail = Nothing
' get file detail function. created by Stefan Arhip on 20111026 1000
Function fGetFileDetail(aFileFullPath, aDetail)
' declare local variables
Dim pvShell, pvFileSystemObject, pvFolderName, pvFileName, pvFolder, pvFile, i
' set object to work with files
Set pvFileSystemObject = CreateObject("Scripting.FileSystemObject")
' check if aFileFullPath provided exists
If pvFileSystemObject.FileExists(aFileFullPath) Then
' extract only folder & file from aFileFullPath
pvFolderName = pvFileSystemObject.GetFile(aFileFullPath).ParentFolder
pvFileName = pvFileSystemObject.GetFile(aFileFullPath).Name
' set object to work with file details
Set pvShell = CreateObject("Shell.Application")
Set pvFolder = pvShell.Namespace(pvFolderName)
Set pvFile = pvFolder.ParseName(pvFileName)
' in case detail is not detected...
fGetFileDetail = "Detail not detected"
' parse 400 details for given file
For i = 0 To 399
' if desired detail name is found, set function result to detail value
If uCase(pvFolder.GetDetailsOf(pvFolder.Items, i)) = uCase(aDetail) Then
fGetFileDetail = pvFolder.GetDetailsOf(pvFile, i)
End If
Next
' if aFileFullPath provided do not exists
Else
fGetFileDetail = "File not found"
End If
' make local variable happy. set them free
Set pvShell = Nothing
Set pvFileSystemObject = Nothing
Set pvFolderName = Nothing
Set pvFileName = Nothing
Set pvFolder = Nothing
Set pvFile = Nothing
Set i = Nothing
End Function

A: Wscript.Echo CreateObject("Scripting.FileSystemObject").GetFileVersion("C:\Windows\notepad.exe")


text:
Q: Powering 17 meters of RGB LED strip - Worried about voltage drop and wire size I'm modifying an IKEA Ramvik coffee table by mounting lengths of individually addressable RGB LED strip under the glass controlled by a Raspberry Pi. The LED strip is pretty standard; running at 5v with 32 RGB LEDs per meter, each one has an WS2801 which talk to each other via SPI. It's identical to this one: https://www.sparkfun.com/products/11272
In total there's going to be just under 17m of strip: 16 rows split into 106cm sections. I'm going to be wiring the rows up snake style and dual feeding to keep brightness consistent across the array.
At full brightness, with all LEDs on, each row of strip will draw just under 2 amps, multiplied by my 16 rows, that's 32 amps in total. With this much ampage running I'm concerned I'm going to need some hefty wires to handle the load without dropping voltage. Unfortunately the design of the table means that there's only around 3mm space underneath the glass so the diameter of the wire is important.
The 5v power supply is going to be mounted inside the table, around 0.5m from the start of the LED strips. I've been running some calculations which says even if I use 16awg wire I'm still going to see a drop of ~0.5v.
Is there any way I can negate this or do something to prevent it?

A: I'm going to be wiring the rows up snake style and dual feeding to keep brightness consistent across the array.
If Dual Feeding is what I think it means, you already know what to do.
Feed the 5v to each 106cm section individually or in pairs. Don't chain the power through the entire 17m length. Sure, this means 8 or 16 sets of 5v and Gnd cables, but with each only carrying 2A or 4A over a small length, heat/current/resistance issues go away. Same reason you only see 18 AWG wire in ATX Power Supplies. Instead of a single 10AWG 12v Cable, it uses 8 or 12 18AWG wires to carry the same current.
You would keep the data cable the same. Just make sure to tie the grounds together.
Actually, pretty much how the datasheet for the Sparkfun item you linked to already has it, for a snake layout.

For 1M strips (106cm = 1.06M) the voltage drop would be insignificant.

A: You have some things you can work with here:
1) Raise the 5V supply voltage a bit to accommodate the voltage drop of the wiring.
2) Gang up several runs of smaller gauge wire instead of trying to use one larger fat wire.
3) Let there be some drop in the cable if it does not interfere with the operation of the LED light strings and controllers.
Another thing I want to caution about. You indicate that you'll hide the 5V supply inside the table. A 5V supply that can provide 32A of load current is a unit that can deliver 160W of power. If one makes an estimate that the supply is a switcher at 70% efficiency that means the input power is ~228W with some 68W being dissipated as heat in the power supply. An enclosed space without airflow can get quite hot and so it is encouraged that you provide for some airflow vents and mount a fan to force air through. (A power supply with an in-built fan may be adequate if you arrange the venting in such way that the intake air comes from outside the table and exhausts in a way as to not recirculate back to the input side.


text:
Q: Writing a regex in perl to compare a method definition in java I want to compare method definition like :
1. static void main(String[] args){

2. static void main(String[] args)
{
3. int sum()
4. int abc(int a,int b){

I just have the method's name and I'm reading the file one line at a time.
The regex shouldn't compare method calls such as :
sum();
OBJ.abc(1,2);

I wrote a regex which is not working :
$srcLine =~ m/$methodName[\([A-Z]*[a-z]*[0-9]*\s*[,]*\(*\)*\)]*/)

I'm getting a compilation error at this line.
EDIT
$srcLine =~ m/$methodName\((?!~)+\)/

This is another regex where I am comparing it with the
"methodName('anything other than ~')"

A: I am not sure how restrictive your pattern should be, but I can explain you the problems in your regexes.

*

*$srcLine =~ m/$methodName[\([A-Z]*[a-z]*[0-9]*\s*[,]*\(*\)*\)]*/)
With the square brackets you are creating a character class and you can't mix them. So I assume you wanted a group there, so
$srcLine =~ m/$methodName(?:\([A-Z]*[a-z]*[0-9]*\s*[,]*\(*\)*\))*/)

would be a bit closer at your requirements. I am not sure about the [,]* part, that means match a literal "," 0 or more times, this is probably not what you want.

*$srcLine =~ m/$methodName\((?!~)+\)/
You can't repeat a zero width assertion (the (?!~)+ part). If you want to say match anything but a certain character, use a negated character class.
$srcLine =~ m/$methodName\([^~]+\)/

Be aware that this will match till the last found closing bracket.


text:
Q: Design Pattern for getting data from optional services In my project there are two different modules (A and B). Also module B is optional. However there is a functionality in module A to get data from module B, only if module B is installed.
Is there any design pattern for this scenario rather than disabling the functionality by looking at the existence of module B ??

A: You could introduce an API for Module B with an actual implementation and a null pattern implementation. While wiring your application you can choose which one to use, depending on availability of Module B.
The Null pattern implementation should behave so that module A is unaware whether Module B is there or not.

A: Yes, the design pattern is polymorphism. Make module A abstract and create two subclasses.

*

*A1 always uses B.

*A2 never uses B.

Common logic remains in A. At runtime, check once for the existence of B and then inject the appropriate subclass of A.


text:
Q: Will not open Project My solution in in c# has two projects. Each in their own seperate folder. I can change the first folder name containing the first project and it does not affect the program. I can open and run it with no complains. However, when I change the second project folder name it gives the following warning:
One or more projects in the solution could not be loaded for the following reason(s):
The project file or web has been moved, renamed or is not on your computer.
These projects will be labled as unavailable in Solution Explorer. Expand the node to show the reason the project could not be loaded.
When I expand the node it says:
The project file or web cannot be found.
I have just renamed the folder. Where can I access the path to change this?
I have tried making a new project with the correct name. This seems to work but I now encounter another problem. Since this is a Windows Mobile application, when I debug I get the deploy box asking which mobile device I would like to run my solution on. I pick the Windows Mobile 6 Professional Emulator. The emulator comes up but after about 4 seconds I get another deploy box coming up asking me the same thing. I pick the same device and my program runs on the second emulator with no problems. I have no clue why Inow get a second deploy box. When all I done was make a new project and copy the classes from the old one to the new one.
Can someone please tell me what happend and what I can do in both cases.
Thank you in advance.

A: Either remove the project from the solution and re-add it, or open up the solution file in a text editor and change the path there.

A: You may want to check the path information in the solution file and verify that path information against the real path on the file system?


text:
Q: Jasper report excel export output I have total 5 reports in 5 different files and i want to make only single excel file which contains these five reports and five different sheets how it will be possible with jasper report?
Please help
Thanks in advance

A: Instead of creating 5 reports just use one report and set the property net.sf.jasperreports.export.xls.one.page.per.sheet to true.
Then just rename them with net.sf.jasperreports.export.xls.sheet.name
and use the Page Break element
Search on the internet for more information if needed. There are actually a lot of examples for this.

A: First you have to create JasperPrint objects for each sheet as you normally would.
JasperPrint firstSheet = ...;
JasperPrint secondSheet = ...;
JasperPrint thirdSheet = ...;
JasperPrint fourthSheet = ...;
JasperPrint fifthSheet = ...;

Now JasperPrint already have the datasource at this point. Use the Arraylist to add the JasperPrint object and the exporter will use each object to create a sheet
JRXlsxExporter exporter = new JRXlsxExporter();

ArrayList<JasperPrint> list = new  ArrayList<JasperPrint>();
list.add(firstSheet);
list.add(secondSheet);
list.add(thirdSheet);
list.add(fourthSheet);
list.add(fifthSheet);
exporter.setExporterInput(SimpleExporterInput.getInstance(list));
exporter.setExporterOutput(new SimpleOutputStreamExporterOutput(outputFile));
exporter.exportReport();

And you need to use net.sf.jasperreports.engine.export.ooxml.JRXlsxExporter as import


text:
Q: Codeigniter Model returning empty data I have a problem with my model. It's returning empty data.
Here is the controller.
public function getReport() {
  $data = array();

  $id = $this->input->post('id');

  $this->auth->setId($id);

  $data['instant_main']=$this->auth->getReportData();

  $this->load->view('auth/report-item', $data);
}

and this is my Model
class Auth_model extends CI_Model {
    // Declaration of a variables
    private $_id;

    public function setId($id) {
        $this->_id = $id;
    }

    function getReportData()
    {

        $this->db->select('*');
        $this->db->from('inbound_main');
        $this->db->join('inbound_item', 'inbound_main.id = inbound_item.report_id');
        $this->db->where('inbound_item.report_id', $this->_id);

        $query = $this->db->get();

        return $query->result();
    }

}

If I have removed the WHERE condition from the query, everything was fine.

A: Your $this_id is empty..
You have folow the code like this
Controller
$data['instant_main']=$this->auth->getReportData($id);
Model
function getReportData($id)
{
    $this->db->select('*');
    $this->db->from('inbound_main');
    $this->db->join('inbound_item', 'inbound_main.id = inbound_item.report_id');
    $this->db->where('inbound_item.report_id', $id);

    $query = $this->db->get();

    return $query->result();
}


text:
Q: changes in models.py not reflecting on website even after running successful makemigrations and migrate commands my models.py looks like this
from django.db import models
from django.urls import reverse

class Product(models.Model):
    PRODUCTS_CATEGORY = [
        ('None', 'None'),
        ('Sterilisation', 'Sterilisation'),
        ('Cleaning Chemistry', 'Cleaning Chemistry'),
        ('Bacterial Barrier', 'Bacterial Barrier'),
        ('Waste Management', 'Waste Management'),
        ('Instrument Tracking', 'Instrument Tracking'),
        ('Validation', 'Validation')
    ]
    prod_id = models.AutoField
    prod_name = models.CharField(max_length=100)
    prod_category = models.CharField(
        max_length=100, choices=PRODUCTS_CATEGORY, default='None')
    prod_desc = models.TextField()
    prod_img = models.ImageField(upload_to='product_images')
    slug = models.SlugField(null=True, blank=True)

    def __str__(self):
        return self.prod_name

i changed the spelling of Sterilisation to Sterilization (replacing the 's' with 'z')
i ran python manage.py makemigrations and it returned  Migrations for 'website': website/migrations/0003_auto_20210407_1842.py - Alter field prod_category on product
 i then ran python manage.py migrate and it returned Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions, website Running migrations: Applying website.0003_auto_20210407_1842... OK
but i dont see the changes reflected on the website. the spelling still remains to be Sterilisation! What can be the reason for this?
 PS:  I am using sqlite3 and the website is on Ubuntu 20.04x64 which is a VPS.

A: The easiest solution for this was given by @azundo.
Step 1: Get into your python django shell by using the command python manage.py shell
Step 2: Import the desired model where you want to make the changes by using the command from <app_name>.models import <model_name>
Step 3: Use the below command
<model_name>.objects.filter(<column_name>='<old_spelling>').update(<column_name>='<new_spelling>')

In my case the above command was Product.objects.filter(prod_category='Sterilisation').update(prod_category='Sterilization')


text:
Q: Python pandas: Weird index value I have posted a similar thread but have now another angle to explore: After doing a covariance analysis between X and Z groupby 2 different levels, I get a DF like
index       X      Z

(1,1,'X')  2.3     0

...
'1' and '1' are the 2 different levels (I could have chosen '1' and '2'; there are 5 and 10 different levels)
Now I would like to extract each 'element' of the index and have something
 index       X      Z     H1      H2     H3

(1,1,'X')  2.3     0      1       1      X

...
I read few posts on slice and dice things - but this is not a normal string is it?
Cheers

A: (1,1,'X') isn't a string here, It's a tuple.
So you need to split the tuple into multiple columns. You can achieve this
by using apply(pandas.Series)
say your dataframe was df in this case.
df.apply(pandas.series)
In [10]: df['index'].apply(pd.Series)
Out[10]:
0  1  2  3
0  1  1 'X'

You need to add the columns back to original data frame so
df[['H1', 'H2','H3']] = df.apply(pandas.Series)


text:
Q: Nginx rewrites taking precedence over redirects? I have some redirects set up in an include file for our nginx config. I noticed the other day that some redirects aren't working, and they seem to just be the ones that are impacted by rewrite rules.
Can anyone take a look and see what I've done wrong? Here are the relevant snippets:
/etc/nginx/sites-available/MySite.conf:
server {
    listen 443 ssl http2 default_server;
    server_name www.example.com ;
    include /etc/nginx/sites-available/includes/Redirects.conf;
    include /etc/nginx/sites-available/includes/Rewrites.conf;
    ...
}

/etc/nginx/sites-available/includes/Redirects.conf:
#This redirect works:
location ~ ^/images/products/1234.jpg { return 301 /images/products/5678.jpg$is_args$args ; }
#This redirect does NOT work
location ~ ^/p/1234 { return 301 /p/5678$is_args$args ; }

/etc/nginx/sites-available/includes/Rewrites.conf:
#This rewrites the short URL /p/<ProductCode> to our ecommerce system's default URL
#I think this is what is conflicting with the redirect above
rewrite ^/p/(.*) /mm5/merchant.mvc?Screen=PROD&Product_Code=$1 break;

A: It may not be clear from the documentation, but rewrite directives in the server block are evaluated sequentially before the search for a location to process the URI.
So the "rewrite ^/p/(.*) ..." statement will be evaluated before the "location ~ ^/p/1234 ..." statement, irrespective of the order of these two statements.
You could convert your rewrite statements into location blocks or vice versa.
For example:
rewrite ^/p/1234 /p/5678 permanent;
rewrite ^/p/(.*) /mm5/merchant.mvc?Screen=PROD&Product_Code=$1 break;


text:
Q: Kruskal-Wallis Test on R with ajusted p-value I am performing a Kruskal-Wallis test on my dataset and I am trying to adjust the p-value but it does not seem to work, here is my code:
> kruskal.test(df$Folate_biosynthesis, df$Group, p.adj="holm")

        Kruskal-Wallis rank sum test

data:  df$Folate_biosynthesis and df$Group Kruskal-Wallis chi-squared
= 8.5144, df = 5, p-value = 0.1301

> kruskal.test(df$Folate_biosynthesis, df$Group, p.adj="none")

        Kruskal-Wallis rank sum test

data:  df$Folate_biosynthesis and df$Group Kruskal-Wallis chi-squared
= 8.5144, df = 5, p-value = 0.1301

As you can see if I put p.adjust = "none" I obtained exactly the same result. How is it possible?
Thanks in advance to everyone willing to help.
Andrea

A: P-value adjustments usually are done when you have multiple p-values. You only have a single p-value so I'm wondering what you expect the adjustment to do here.
With that said it also doesn't appear there is a p.adj parameter for kruskal.test.  The function has a dots parameter but as far as I can tell it doesn't use or pass those along to any further functions so any input that isn't a named parameter will essentially be ignored.
If you wanted to adjust the p-values from multiple outputs from kruskal.test you could collect the p-values in a vector and pass them directly to p.adjust with the appropriate method.
But with all that said it's not clear what you're hoping to achieve - but it is clear that trying to use a p.adj parameter in kruskal.test is not the way to achieve your goal.


text:
Q: Azure Data Factory - Multiple activities in Pipeline execution order I have 2 blob files to copy to Azure SQL tables. My pipeline with two activities:
{
    "name": "NutrientDataBlobToAzureSqlPipeline",
    "properties": {
        "description": "Copy nutrient data from Azure BLOB to Azure SQL",
        "activities": [
            {
                "type": "Copy",
                "typeProperties": {
                    "source": {
                        "type": "BlobSource"
                    },
                    "sink": {
                        "type": "SqlSink",
                        "writeBatchSize": 10000,
                        "writeBatchTimeout": "60.00:00:00"
                    }
                },
                "inputs": [
                    {
                        "name": "FoodGroupDescriptionsAzureBlob"
                    }
                ],
                "outputs": [
                    {
                        "name": "FoodGroupDescriptionsSQLAzure"
                    }
                ],
                "policy": {
                    "timeout": "01:00:00",
                    "concurrency": 1,
                    "executionPriorityOrder": "NewestFirst"
                },
                "scheduler": {
                    "frequency": "Minute",
                    "interval": 15
                },
                "name": "FoodGroupDescriptions",
                "description": "#1 Bulk Import FoodGroupDescriptions"
            },
            {
                "type": "Copy",
                "typeProperties": {
                    "source": {
                        "type": "BlobSource"
                    },
                    "sink": {
                        "type": "SqlSink",
                        "writeBatchSize": 10000,
                        "writeBatchTimeout": "60.00:00:00"
                    }
                },
                "inputs": [
                    {
                        "name": "FoodDescriptionsAzureBlob"
                    }
                ],
                "outputs": [
                    {
                        "name": "FoodDescriptionsSQLAzure"
                    }
                ],
                "policy": {
                    "timeout": "01:00:00",
                    "concurrency": 1,
                    "executionPriorityOrder": "NewestFirst"
                },
                "scheduler": {
                    "frequency": "Minute",
                    "interval": 15
                },
                "name": "FoodDescriptions",
                "description": "#2 Bulk Import FoodDescriptions"
            }
        ],
        "start": "2015-07-14T00:00:00Z",
        "end": "2015-07-14T00:00:00Z",
        "isPaused": false,
        "hubName": "gymappdatafactory_hub",
        "pipelineMode": "Scheduled"
    }
}

As I understand, once first activity is done, second starts. How do you then execute this pipeline, instead of going to Dataset slices and run manually? Also pipelineMode how can I set up to OneTime only, instead of Scheduled?

A: In order to have activities run synchronously (ordered) the output of the first pipeline will need to be an input of the second pipeline.
{
"name": "NutrientDataBlobToAzureSqlPipeline",
"properties": {
    "description": "Copy nutrient data from Azure BLOB to Azure SQL",
    "activities": [
        {
            "type": "Copy",
            "typeProperties": {
                "source": {
                    "type": "BlobSource"
                },
                "sink": {
                    "type": "SqlSink",
                    "writeBatchSize": 10000,
                    "writeBatchTimeout": "60.00:00:00"
                }
            },
            "inputs": [
                {
                    "name": "FoodGroupDescriptionsAzureBlob"
                }
            ],
            "outputs": [
                {
                    "name": "FoodGroupDescriptionsSQLAzureFirst"
                }
            ],
            "policy": {
                "timeout": "01:00:00",
                "concurrency": 1,
                "executionPriorityOrder": "NewestFirst"
            },
            "scheduler": {
                "frequency": "Minute",
                "interval": 15
            },
            "name": "FoodGroupDescriptions",
            "description": "#1 Bulk Import FoodGroupDescriptions"
        },
        {
            "type": "Copy",
            "typeProperties": {
                "source": {
                    "type": "BlobSource"
                },
                "sink": {
                    "type": "SqlSink",
                    "writeBatchSize": 10000,
                    "writeBatchTimeout": "60.00:00:00"
                }
            },
            "inputs": [
                {
                    "name": "FoodGroupDescriptionsSQLAzureFirst",
                    "name": "FoodDescriptionsAzureBlob"
                }
            ],
            "outputs": [
                {
                    "name": "FoodDescriptionsSQLAzureSecond"
                }
            ],
            "policy": {
                "timeout": "01:00:00",
                "concurrency": 1,
                "executionPriorityOrder": "NewestFirst"
            },
            "scheduler": {
                "frequency": "Minute",
                "interval": 15
            },
            "name": "FoodDescriptions",
            "description": "#2 Bulk Import FoodDescriptions"
        }
    ],
    "start": "2015-07-14T00:00:00Z",
    "end": "2015-07-14T00:00:00Z",
    "isPaused": false,
    "hubName": "gymappdatafactory_hub",
    "pipelineMode": "Scheduled"
}

If you notice the output of the first activity "FoodGroupDescriptionsSQLAzureFirst" becomes an input in the second activity.

A: If I understand correctly you want to execute both the activities without manually executing the dataset slices.
You can do that simply by defining the dataset as external.
As an example
{
    "name": "FoodGroupDescriptionsAzureBlob",
    "properties": {
        "type": "AzureBlob",
        "linkedServiceName": "AzureBlobStore",
        "typeProperties": {
            "folderPath": "mycontainer/folder",
            "format": {
                "type": "TextFormat",
                "rowDelimiter": "\n",
                "columnDelimiter": "|"
            }
        },
        "external": true,
        "availability": {
            "frequency": "Day",
            "interval": 1
        }
    }
}

Observe that the property external is marked as true. This will move the data set in a ready state automatically.
Sadly there is no was to mark the pipeline as run once. After running the pipeline once you have an option of setting the isPaused property to true to prevent further executions.
Note: external property can be set to true only for input data sets.
All the activities which have input data set which is marked as external will be executed in parallel.


text:
Q: Convert a Scala list to a tuple? How can I convert a list with (say) 3 elements into a tuple of size 3?
For example, let's say I have val x = List(1, 2, 3) and I want to convert this into (1, 2, 3). How can I do this?

A: If you are very sure that your list.size<23 use it:
def listToTuple[A <: Object](list:List[A]):Product = {
  val class = Class.forName("scala.Tuple" + list.size)
  class.getConstructors.apply(0).newInstance(list:_*).asInstanceOf[Product]
}
listToTuple: [A <: java.lang.Object](list: List[A])Product

scala> listToTuple(List("Scala", "Smart"))
res15: Product = (Scala,Smart)

A: You can't do this in a type-safe way. In Scala, lists are arbitrary-length sequences of elements of some type. As far as the type system knows, x could be a list of arbitrary length.
In contrast, the arity of a tuple must be known at compile time. It would violate the safety guarantees of the type system to allow assigning x to a tuple type.
In fact, for technical reasons, Scala tuples were limited to 22 elements, but the limit no longer exists in 2.11 The case class limit has been lifted in 2.11 https://github.com/scala/scala/pull/2305
It would be possible to manually code a function that converts lists of up to 22 elements, and throws an exception for larger lists. Scala's template support, an upcoming feature, would make this more concise. But this would be an ugly hack.

A: You can do it using scala extractors and pattern matching (link):
val x = List(1, 2, 3)

val t = x match {
  case List(a, b, c) => (a, b, c)
}

Which returns a tuple
t: (Int, Int, Int) = (1,2,3)

Also, you can use a wildcard operator if not sure about a size of the List
val t = x match {
  case List(a, b, c, _*) => (a, b, c)
}

A: You can't do this in a typesafe way. Why? Because in general we can't know the length of a list until runtime. But the "length" of a tuple must be encoded in its type, and hence known at compile time. For example, (1,'a',true) has the type (Int, Char, Boolean), which is sugar for Tuple3[Int, Char, Boolean]. The reason tuples have this restriction is that they need to be able to handle a non-homogeneous types.

A: This can also be done in shapeless with less boilerplate using Sized:
scala> import shapeless._
scala> import shapeless.syntax.sized._

scala> val x = List(1, 2, 3)
x: List[Int] = List(1, 2, 3)

scala> x.sized(3).map(_.tupled)
res1: Option[(Int, Int, Int)] = Some((1,2,3))

It's type-safe: you get None, if the tuple size is incorrect, but the tuple size must be a literal or final val (to be convertible to shapeless.Nat).

A: Using Pattern Matching:
val intTuple = List(1,2,3) match {case List(a, b, c) => (a, b, c)}

A: an example using shapeless :
import shapeless._
import syntax.std.traversable._
val x = List(1, 2, 3)
val xHList = x.toHList[Int::Int::Int::HNil]
val t = xHList.get.tupled

Note: the compiler need some type informations to convert the List in the HList that the reason why you need to pass type informations to the toHList method

A: 2015 post.
For the Tom Crockett's answer  to be more clarifying, here is a real example.
At first, I got confused about it. Because I come from Python, where you can just do tuple(list(1,2,3)).
Is it short of Scala language ? (the answer is -- it's not about Scala or Python, it's about static-type and dynamic-type.)
That's causes me trying to find the crux why Scala can't do this .

The following code example implements a toTuple method, which has type-safe toTupleN and type-unsafe toTuple.
The toTuple method get the type-length information at run-time, i.e no type-length information at compile-time, so the return type is Product which is very like the Python's tuple indeed (no type at each position, and no length of types).
That way is proned to runtime error like type-mismatch or IndexOutOfBoundException. (so Python's convenient list-to-tuple  is not free lunch. )
Contrarily , it is the length information user provided that makes toTupleN compile-time safe.
implicit class EnrichedWithToTuple[A](elements: Seq[A]) {
  def toTuple: Product = elements.length match {
    case 2 => toTuple2
    case 3 => toTuple3
  }
  def toTuple2 = elements match {case Seq(a, b) => (a, b) }
  def toTuple3 = elements match {case Seq(a, b, c) => (a, b, c) }
}

val product = List(1, 2, 3).toTuple
product.productElement(5) //runtime IndexOutOfBoundException, Bad !

val tuple = List(1, 2, 3).toTuple3
tuple._5 //compiler error, Good!

A: you can do this either

*

*via pattern-matching (what you do not want) or

*by iterating through the list and applying each element one by one.
val xs: Seq[Any] = List(1:Int, 2.0:Double, "3":String)
val t: (Int,Double,String) = xs.foldLeft((Tuple3[Int,Double,String] _).curried:Any)({
  case (f,x) => f.asInstanceOf[Any=>Any](x)
}).asInstanceOf[(Int,Double,String)]

A: Shapeless 2.0 changed some syntax. Here's the updated solution using shapeless.
import shapeless._
import HList._
import syntax.std.traversable._

val x = List(1, 2, 3)
val y = x.toHList[Int::Int::Int::HNil]
val z = y.get.tupled

The main issue being that the type for .toHList has to be specified ahead of time. More generally, since tuples are limited in their arity, the design of your software might be better served by a different solution.
Still, if you are creating a list statically, consider a solution like this one, also using shapeless. Here, we create an HList directly and the type is available at compile time. Remember that an HList has features from both List and Tuple types. i.e. it can have elements with different types like a Tuple and can be mapped over among other operations like standard collections. HLists take a little while to get used to though so tread slowly if you are new.
scala> import shapeless._
import shapeless._

scala> import HList._
import HList._

scala>   val hlist = "z" :: 6 :: "b" :: true :: HNil
hlist: shapeless.::[String,shapeless.::[Int,shapeless.::[String,shapeless.::[Boolean,shapeless.HNil]]]] = z :: 6 :: b :: true :: HNil

scala>   val tup = hlist.tupled
tup: (String, Int, String, Boolean) = (z,6,b,true)

scala> tup
res0: (String, Int, String, Boolean) = (z,6,b,true)

A: Despite the simplicity and being not for lists of any length, it is type-safe and the answer in most cases:
val list = List('a','b')
val tuple = list(0) -> list(1)

val list = List('a','b','c')
val tuple = (list(0), list(1), list(2))

Another possibility, when you don't want to name the list nor to repeat it (I hope someone can show a way to avoid the Seq/head parts):
val tuple = Seq(List('a','b')).map(tup => tup(0) -> tup(1)).head
val tuple = Seq(List('a','b','c')).map(tup => (tup(0), tup(1), tup(2))).head

A: FWIW, I wanted a tuple to initalise a number of fields and wanted to use the syntactic sugar of tuple assignment.
EG:
val (c1, c2, c3) = listToTuple(myList)

It turns out that there is syntactic sugar for assigning the contents of a list too...
val c1 :: c2 :: c3 :: Nil = myList

So no need for tuples if you've got the same problem.

A: In scala 3, you can do something like this:
    def totuple[A](as: List[A]): Tuple = as match
        case Nil => EmptyTuple
        case h :: t => h *: totuple(t)

but as has been said already, without giving the compiler any more hard-coded type information, you aren't going to know the length of the tuple or the types of its elements, so this is likely hardly any better than the original list.

A: as far as you have the type:
val x: List[Int] = List(1, 2, 3)

def doSomething(a:Int *)

doSomething(x:_*)


text:
Q: Collections Referencing in MongoDb and fetching data Issue with Creating Relations in Collection in MongoDB to fetch Data through REST API
I am new to NodeJs and MongoDB, I am trying to develop a REST API that fetched data for categories and products. I am trying to create a relation b/w the categories and product such that when queried for a particular category, only those products should be fetched from the DB
I have tried fetching data from categories and then passed the _id into products to fetch the related products.
Categories.js Schema
const mongoose = require('mongoose')
const uniqueValidator = require('mongoose-unique-validator')

const categoriesSchema = mongoose.Schema({
    name: {
        type: String,
        unique: true,
    }
})
categoriesSchema.plugin(uniqueValidator)
module.exports = mongoose.model('Categories', categoriesSchema)

Prodcuts.js Schema
const mongoose = require('mongoose');

const  ProductSchema =  mongoose.Schema({
    category:{
    type: String
    },
    name:{
        type: String,
        required: true,
        trim: true,
        lowercase: true
    } ,
    description: {
        type: String,
        required: true,
        trim: true,
        lowercase: true
    } ,
    quantity: {
        type: Number,
        required: true,
        trim: true,
        default:0
    } ,
    color: {
        type: String,
        required: true,
        trim: true,
        lowercase: true
    } ,
    price: {
        type: Number,
        required: true,
        trim: true,
        default:0
    }
});
module.exports = mongoose.model('Product', ProductSchema);

Home.js Route
const express = require('express')
const router = express.Router()

const productModel = require('../models/products')
const categoriesModel = require('../models/categories')

router.get('', async (req, res) => {
    categroyFetched = []
    productsFecthed =[]
    await categoriesModel.find({})
        .then(categories => {
            categroyFetched = categories.map(category => {
                return{
                    name: category.name,
                    id: category._id
                }
            })

            return category = {
                count: categroyFetched.length,
                name: categroyFetched
            }
        })
       .then(async()=>{
        await productModel.find({category: categroyFetched.id})
        .then(products => {

            productsFecthed = products.map(product => {
                return product
            })

        })

       })
       .catch(err => {
        console.log('err', err)
    })

    res.status(200).json({
        category, productsFecthed
    })

})

module.exports = router

I need help in establishing the relation in Category and Products Schema and later how I can use it in Home.js Route to extract Data. and Also while creating the Products, what format of Json Data need to be sent to incorporate reference to Category Collection.

A: In order to establish relationship between Category and Product define your Product schema as follows:
const  ProductSchema =  mongoose.Schema({
    category:{ type: mongoose.Types.ObjectId, ref: "Categories" },
 // other fields...

Now in order to insert record in product, category will take ObjectId (in other words, _id of Category) of Category.
Now you can query and do whatever you want.
await Product.find().populate('category') // This will also populate category along with product

await Product.find({category: catId}).populate('category'); //conditional find statement

A: For your flow,
We will start with creating categories and saving them in DB, then when creating products we will fetch all categories from DB and show in UI for selection of category to create products. Every created product would have a category as string in the DB(as you described in schema).
Now If we want to fetch products of a specific category, try productModel.find({category: specificCategory}) if category is saved as string in the product. Here specific category is what you sent to the server. In your query, if you are planning to store both name and id of a category in product. Then you should have to change the category from string to object in the product schema. When saving product you should send object containing name and id to the product.
If you want to fetch all categories with the related products for each category at the same time, try $lookup aggregations queries in mongodb. They are very useful to perform operations on multiple collections in a single query.

A: Since you are using category id to make a relation. In product schema update categoryId key from string to mongoose.Types.ObjectId. This will be useful when performing aggregations based on category id relation. Now after creation of category and product, the documents in DB will have same key which can be used as a relation between the related documents.
If you are choosing $lookup to perform the query in you question, then in the Home.js
categoriesModel.aggregate([
   {
     $lookup:
       {
         from: "product",
         localField: "_id",
         foreignField: "categoryId",
         as: "products"
       }
  }
])

Expected Result will be array of all categories with products as key for every element. products are the array of products of the respective category
[{name:'category1', products:[{p1 Object},{p2 Object}, ...{}]}, {name:'category2', products:[{p6 Object},{p7 Object}, ...{}]}]. Try this.


text:
Q: Can anyone please explain why output of the following is such?      String str1 = "abc:5";
     String str2 = "abc:" + str1.length();
     String str3 = "abc:" + 5;

     System.out.println(str1==str2);
     System.out.println(str1==str3);

Output of the program is :
false
true
But I don't understand why?

A: == operator will compare reference only
.equals() will compare the values.
in your case
str1==str2 // compares the two references, which are different.
had it been, str1.equals(str2), it would have compared the values, which will return true
The "==" operator
In Java, when the "==" operator is used to compare 2 objects, it checks to see if the objects refer to the same place in memory. In other words, it checks to see if the 2 object names are basically references to the same memory location.The "==" operator compares the objects' location(s) in memory
The "equals" method
The Java String class actually overrides the default equals() implementation in the Object class – and it overrides the method so that it checks only the values of the strings, not their locations in memory.

A: Here str1 = "abc:5"; is located in constant pool of string and str2 is concatenated with 2 different object with new operator. So both str1 and str2 are referring to different object. That's the reason it is showing false.

A: The == operator is used for only reference variables in java. For example if you are comparing characters a1 and a2 you can use the == operator because the char type is highlighted in most IDEs in Java. To check if two Strings are equal to each other you can use .equals()or .equalsIgnoreCase() to compare the Strings. This is because Strings are objects, not primitives, and require their own method in the class to test if Strings are the same.
For the first System.out.println(); statement, you would use System.out.println(str1.equals(str2)); or System.out.println(str1.equalsIgnoreCase(str2));.
For the second System.out.println(); statement, you would use System.out.println(str1.equals(str3)); or System.out.println(str1.equalsIgnoreCase(str3));.


text:
Q: Get max and min date of java.sql.date I see everywhere that for get the minimum and the maximum of a date i have to use  :
Date dateModificationMin = new Date( Long.MIN_VALUE );
Date dateModificationMax = new Date( Long.MAX_VALUE );

But i do it on my java.sql.date it's return :
055-12-02 for the min date
994-08-17 for the max date
How can i do for get the maximum and minimum of a java.sql.date?

A: Database-specific
The answer is database-specific, not to be found in Java or JDBC or java.sql types. The limits on possible date-time values differs enormously between databases.
For example:

*

*Postgres 9.5 TIMESTAMP WITH TIME ZONE has a range of 4713 BC  to 294276 AD.

*MySQL 5.7 TIMESTAMP type has a range of '1970-01-01 00:00:01.000000' to '2038-01-19 03:14:07.999999' UTC. The range for DATETIME values is '1000-01-01 00:00:00.000000' to '9999-12-31 23:59:59.999999',

*SQLite has no data types as such, and stores date-time values as ISO 8601 strings ("YYYY-MM-DD HH:MM:SS.SSS"). So presumably limited to year 9999 if it tracks only 4 digits for year (I do not know).

*Firebird seems to have a TIMESTAMP from January 1, 1753, to December 31, 9999, with an accuracy of three-hundredths of a second, or 3.33 milliseconds. I could not find their main reference page, nor update for version 3 just announced.

*Microsoft SQL Server datetime2 type has a range of 0001-01-01 through 9999-12-31 through January 1,1 CE through December 31, 9999 CE, times from 00:00:00 through 23:59:59.9999999 (note the 7 digits of fraction, finer than microseconds but more coarse than nanoseconds). Also has datetime with range of January 1, 1753, through December 31, 9999, and time-of-day 00:00:00 through 23:59:59.997.

Instead of determining the absolute limit, I suggest you choose arbitrary points in the future and in the past, and use those as your limits. Far enough out to go beyond value to be encountered during the lifetime of your software and apps, but not so far out as to exceed the limits of most databases. Hard-code the limits as constants in your app, as enums in Java for example.
Other postings on Stack Overflow have shown that there is no clean simple answer to this question of finding date-time values to use as placeholders for unknown or yet-to-be-determined values (which I assume is the purpose behind the question).

A: If you do the code to the java.util.Date, you will gain
dateModificationMin = Sun Dec 02 17:47:04 CET 292269055
dateModificationMax = Sun Aug 17 08:12:55 CET 292278994

i guess, the date with negative long timestamp works wrong, so the minimum date is
new Date(0)==  Thu Jan 01 01:00:00 CET 1970

Since java.sql.date extends the java.util.Date, the problem there is probably same
with
        long timestamp = -10;

    for (int i = 0; i < 20; i++) {

        System.out.println("timestamp = " + timestamp + " date = " + (new Date(timestamp)));
        timestamp*=10;
    }

you get :
timestamp = -10 date = Thu Jan 01 00:59:59 CET 1970
timestamp = -100 date = Thu Jan 01 00:59:59 CET 1970
timestamp = -1000 date = Thu Jan 01 00:59:59 CET 1970
timestamp = -10000 date = Thu Jan 01 00:59:50 CET 1970
timestamp = -100000 date = Thu Jan 01 00:58:20 CET 1970
timestamp = -1000000 date = Thu Jan 01 00:43:20 CET 1970
timestamp = -10000000 date = Wed Dec 31 22:13:20 CET 1969
timestamp = -100000000 date = Tue Dec 30 21:13:20 CET 1969
timestamp = -1000000000 date = Sat Dec 20 11:13:20 CET 1969
timestamp = -10000000000 date = Sun Sep 07 07:13:20 CET 1969
timestamp = -100000000000 date = Mon Oct 31 15:13:20 CET 1966
timestamp = -1000000000000 date = Sun Apr 24 23:13:20 CET 1938
timestamp = -10000000000000 date = Mon Feb 10 07:13:20 CET 1653
timestamp = -100000000000000 date = Thu Feb 26 15:13:20 CET 1200
timestamp = -1000000000000000 date = Tue Nov 16 23:13:20 CET 29720
timestamp = -10000000000000000 date = Sun Feb 01 07:13:20 CET 314912
timestamp = -100000000000000000 date = Mon Mar 08 15:13:20 CET 3166840
timestamp = -1000000000000000000 date = Sun Feb 24 23:13:20 CET 31686119

see how dates go crasy after -1 * 10^15
also with java.sql.Date :
timestamp = -10000000000000 date = 1653-02-10
timestamp = -100000000000000 date = 1200-02-26
timestamp = -1000000000000000 date = 720-11-16
timestamp = -10000000000000000 date = 912-02-01
timestamp = -100000000000000000 date = 840-03-08
timestamp = -1000000000000000000 date = 119-02-24
timestamp = 8446744073709551616 date = 634-03-09
timestamp = -7766279631452241920 date = 582-01-06

so wrong here !! :D


text:
Q: unselected gridview items? i have a game project that has a problem.in my game has a grid with 20 item. user should selected multi item that == main Number (6+2+4+8 == 20)

when click on items that it's position above 9 (two digits), both itself and the first item is selected. for exam: for item by position 14: item 14 & item 1 is selected when click on item 14.
it's my java code:
1. grid.onItemClickListener :
if(Integer.parseInt(string.charAt(position)+"")+sum_main < Integer.parseInt(tv.getText().toString())){
            // define action when: sum_main < Number
            sum_main  += Integer.parseInt(string.charAt(position)+"");
            String sm = position+"";
            if(sm.length() > 1){
                Log.d("11","Ok");
                sbVars.append(slash);
                sbVars.append(string.charAt(position));
                sbPoss.append(slash);
                sbPoss.append(position);
                Log.d("12","Ok");
            }else{ Log.d("13","Ok");
                sbVars.append(string.charAt(position));
                sbPoss.append(position); Log.d("14","Ok");
            }
            view.setEnabled(false);
            Log.d("15","Ok");
            n = 1;
            Toast.makeText(MplusN_Game.this, sbPoss+"", Toast.LENGTH_LONG).show();
        }else if(Integer.parseInt(string.charAt(position)+"")+sum_main == Integer.parseInt(tv.getText().toString())){
            // define action when: sum_main = Number
            sum_main = 0;
            String sm = position+"";
            if(sm.length() > 1){
                sbVars.append("/");
                sbVars.append(string.charAt(position));
                sbPoss.append("/");
                sbPoss.append(position);
            }else{
                sbVars.append(string.charAt(position));
                sbPoss.append(position);
            }
            tv.setText(setNumber()+"");
            n = 2;
            deleteVarsOfString();
        }else{
            // define action when: sum_main > Number
            sum_main = 0;
            n = 3;
        }
        setStatesGridItems(n);// method for change bg of selected items
        }
    });

*this is setStateGridItems() method

for(int i=0; i<sbPoss.length(); i++){
                String s = sbPoss.charAt(i)+"";
                if(s.equals(slash)){
                    String ss = sbPoss.charAt(i+1)+""+sbPoss.charAt(i+2);
                    int t1 = Integer.parseInt(ss);
                    grid.getChildAt(t1).setBackgroundResource(R.drawable.bg_grid_items_bloo100);
                    Log.w("1","OK");
                }
                else{
                    Log.w("2","OK");
                    if(i > 1){
                        Log.w("21","OK");
                        String s2 = sbPoss.charAt(i-1)+"";
                        String s3 = sbPoss.charAt(i-2)+"";
                        if(s2.equals(slash))
                            if(s3.equals(slash)){
                                Log.w("211","OK");
                                continue;
                            }
                        else{
                            int t = Integer.parseInt(sbPoss.charAt(i)+"");
                            grid.getChildAt(t).setBackgroundResource(R.drawable.bg_grid_items_bloo100);
                            grid.getChildAt(t).setEnabled(false);
                                Log.w("212","OK");
                        }
                    }else{
                        Log.w("22","OK");
                        if(i==0){
                            int t = Integer.parseInt(sbPoss.charAt(0)+"");
                            grid.getChildAt(t).setBackgroundResource(R.drawable.bg_grid_items_bloo100);
                            grid.getChildAt(t).setEnabled(false);
                            Log.w("221","OK");
                        }else{
                            Log.w("222","OK");
                            String s2 = sbPoss.charAt(i-1)+"";
                            if(s2.equals(slash)){
                                Log.w("2221","OK");
                                continue;
                            }
                            else{
                                Log.w("2222","OK");
                                int t = Integer.parseInt(sbPoss.charAt(i)+"");
                                grid.getChildAt(t).setBackgroundResource(R.drawable.bg_grid_items_bloo100);
                                grid.getChildAt(t).setEnabled(false);
                            }
                        }
                    }
                }
            }

please solve this problem.thank you


text:
Q: ReactJS: Open only selected modal popup of map items I am trying to add react-modal to the items of the mapped array. When
I click on the onClick event on the mapped items it opens all the modals at once. What I want is top open selected modal at a time.
Here I am mapping through the employee's array and adding a button to each of them with onClick modal.

const employeeInfo = this.props.employees.map(employee => (

        {employee.name}

            <button className="edit" onClick={this.toggleEditEmployeeModal}>

            </button>

            //This is the modal component
            <Modal
              open={this.state.openEditEmployeeModal}
              onClose={this.toggleEditEmployeeModal}
              center
            >
              <EditEmployeeModal />
            </Modal>

    ));
return (

            Name
            Employee Id
            Job Title
            Date Of Joining
            Employee Info
            Actions

{employeeInfo}

    );
  }

here is the state for toggling the model

state = {
  openEditEmployeeModal: false
};

toggleEditEmployeeModal = () => {
  this.setState({
    openEditEmployeeModal: !this.state.openEditEmployeeModal
  });
};

Now If I click the button it will open all the modal but I want to open a selected modal only. Any help will be appreciated.

A: Three ways:

*

*Render a map of "Employee" components with they own states so the modal is proper to each employee.

*Render your current map with modal on the parent component and, from an employee click, set the modal state with that employee context.

*Have a key based state with each employee index as a key (state[employeeId]) so you can mutate each separately.

A: I usually separate them into components
const employeeInfo = this.props.employees.map(employee => (
    <Employee employee=employee />
    ));

class Employee extends PureComponent {
   render(){
      constructor(props){
      super(props);
      this.state={visible:false}
     }
 toggleEditEmployeeModal(){
   this.setState({
   visible = !this.state.visible
      })
   }
  var employee = this.props.employee

    return(

        {employee.name}

            <button className="edit" onClick={this.toggleEditEmployeeModal}>

            </button>

            //This is the modal component
            <Modal
              open={this.state.visible}
              onClose={this.toggleEditEmployeeModal}
              center
            >
              <EditEmployeeModal />
            </Modal>

)
    }

}

let me know if you have further problems


text:
Q: MvvmCross Popup Window I would like to have a popup window.  Even though I am using MvvmCross, it will strictly run on Android.  In Windows Store, you can do the following with xaml:
    <Popup VerticalOffset="300" HorizontalOffset="200" x:Name="SigPopup" >
        <Border BorderBrush="{StaticResource ApplicationForegroundThemeBrush}"
            Background="{StaticResource ApplicationPageBackgroundThemeBrush}"
            BorderThickness="1">
            <StackPanel>
                <StackPanel Orientation="Horizontal" >
                    <Button x:Name="btnAccept" Content="Accept" Click="btnAccept_Click"/>
                    <Button x:Name="btnCancel" Grid.Column="1" Content="Cancel" Click="btnCancel_Click"/>
                    <TextBlock x:Name="txtSigner" Text="Shipper" Style="{StaticResource SubheaderTextBlockStyle}" Margin="25,3,0,0" />
                </StackPanel>
                <!-- Inking area -->
                <Border BorderBrush="{StaticResource ApplicationForegroundThemeBrush}"
                    Background="{StaticResource ApplicationPageBackgroundThemeBrush}"
                    BorderThickness="2" Width="750" Height="175">
                    <Grid x:Name="inkPanel" Margin="5">
                        <!-- Inking area -->
                        <Canvas x:Name="InkCanvas" Background="White" Margin="5" />
                    </Grid>
                </Border>
            </StackPanel>
        </Border>
    </Popup>

You can use this to popup a window to collect a Signature.  There is an accept and cancel button you can wire up accordingly.  Is there any way to do this using MvvmCross?  I have watched the ViewModel demo and saw where you could draw rectangles and put data in them and it was bound, but it didn't show how to make them go away once you were done.  I had this vision of being able to popup some sort of child ViewModel with a SignatureWidget in it and collect a signature then close the popup.  Can this be done using MvvmCross?

A: there is a Xamarin Component available.
Is this something that fits your need?
http://components.xamarin.com/view/signature-pad
Regards,
Benjamin


text:
Q: How can I maintain multiple versions of an applications on playstore? I want to maintain multiple versions of an application ,so that EMM admin has a control where he can silently push different version to different devices using android management api.
Google play doesn't allow to maintain multiple versions of an application.

A: It depends what you mean and what you want for different versions. There are a bunch of important questions:

*

*would you ever want a user to change version from one version to another (and back again)?

*would you ever want a user to have two versions installed at once?

If the answer to both of the above is yes, then you will need to use different package names for the versions. If the answer is no, then Google Play lets you have different versions using test channels.
But in general you are right. Google Play requires all users of an app to get the latest version.


text:
Q: Using PHP and MySQL, how do you send a variable into a WHERE... IN clause? The following SELECT statement works just fine:
try {
  $sql = $db->prepare('SELECT *
                       FROM classes
                       WHERE classes.id IN (65,70,80)');
  $sql->execute();
  $sublist = $sql->fetchAll(PDO::FETCH_ASSOC);
} catch(Exception $e) {
  echo $e->getMessage();
  die();
}

BUT when I try to send a variable into the WHERE clause, I only get one row back.
In this case $ids is a string that looks like '65,70,80'.
try {
  $sql = $db->prepare('SELECT *
                       FROM classes
                       WHERE classes.id IN (?)');
  $sql->bindParam(1, $ids);
  $sql->execute();
  $sublist = $sql->fetchAll(PDO::FETCH_ASSOC);
} catch(Exception $e) {
  echo $e->getMessage();
  die();
}

Do I need to change the way I'm fetching the data, or is my syntax wrong?

A-HA!   Thanks for that link Mihai.  Here's the code that works:
First:  instead of passing in a string, put ids into an $ids array.
// Figure out how many ? marks have to be in your query as parameter placeholders.
$count = count($ids);
$arrayOfQuestions = array_fill(0, $count, '?');
$queryPlaceholders = implode(',', $arrayOfQuestions);

try {
  $sql = $db->prepare('SELECT *
                       FROM classes
                       WHERE classes.id IN (' . $queryPlaceholders . ')');
  $sql->execute($ids);
  $sublist = $sql->fetchAll(PDO::FETCH_ASSOC);
} catch(Exception $e) {
  echo $e->getMessage();
  die();
}

A: Try this:
try {
  $sql = $db->prepare('SELECT *
                       FROM classes
                       WHERE classes.id IN (?)');
  $sql->bindParam(1, explode(',', $ids));
  $sql->execute();
  $sublist = $sql->fetchAll(PDO::FETCH_ASSOC);
} catch(Exception $e) {
  echo $e->getMessage();
  die();
}


text:
Q: EditText PasswordtransformationMethod and spans I am trying to adapt the PasswordTransformationMethod (https://github.com/android/platform_frameworks_base/blob/master/core/java/android/text/method/PasswordTransformationMethod.java) so that it can work with Editable instance of charsequence which contains spans. What i want is the transformed string also contains the spans present in the source string e.g. styling spans. The reason for doing this is that i need only part of the input to be transformed as a password. e.g input ABCDEF would get transformed as AB...F during text input and retain any styling spans as well.
Looking at the PasswordTransformationMethod above, it looks as though PasswordCharSequence  only implements Charsequence and GetChars thereby losing any spans on the source string.
From the android source code link above, i tried to change the PasswordCharSequence so that it extends SpannableStringBuilder however that gives following exception :
08-25 19:41:29.162: E/AndroidRuntime(998): java.lang.IndexOutOfBoundsException
08-25 19:41:29.162: E/AndroidRuntime(998):  at android.graphics.Paint.getTextRunAdvances(Paint.java:1734)
08-25 19:41:29.162: E/AndroidRuntime(998):  at android.graphics.Paint.getTextRunAdvances(Paint.java:1711)
08-25 19:41:29.162: E/AndroidRuntime(998):  at android.text.TextLine.handleText(TextLine.java:749)
08-25 19:41:29.162: E/AndroidRuntime(998):  at android.text.TextLine.handleRun(TextLine.java:1017)
08-25 19:41:29.162: E/AndroidRuntime(998):  at android.text.TextLine.measureRun(TextLine.java:416)
08-25 19:41:29.162: E/AndroidRuntime(998):  at android.text.TextLine.measure(TextLine.java:295)
08-25 19:41:29.162: E/AndroidRuntime(998):  at android.text.Layout.getHorizontal(Layout.java:1145)
08-25 19:41:29.162: E/AndroidRuntime(998):  at android.text.Layout.getHorizontal(Layout.java:1123)
08-25 19:41:29.162: E/AndroidRuntime(998):  at android.text.Layout.getPrimaryHorizontal(Layout.java:1107)
08-25 19:41:29.162: E/AndroidRuntime(998):  at android.widget.TextView.bringPointIntoView(TextView.java:7224)
08-25 19:41:29.162: E/AndroidRuntime(998):  at android.widget.TextView.updateAfterEdit(TextView.java:6343)
08-25 19:41:29.162: E/AndroidRuntime(998):  at android.widget.TextView.finishBatchEdit(TextView.java:6324)
08-25 19:41:29.162: E/AndroidRuntime(998):  at android.widget.TextView.endBatchEdit(TextView.java:6307)
08-25 19:41:29.162: E/AndroidRuntime(998):  at com.android.internal.widget.EditableInputConnection.endBatchEdit(EditableInputConnection.java:60)
08-25 19:41:29.162: E/AndroidRuntime(998):  at com.android.internal.view.IInputConnectionWrapper.executeMessage(IInputConnectionWrapper.java:436)
08-25 19:41:29.162: E/AndroidRuntime(998):  at com.android.internal.view.IInputConnectionWrapper$MyHandler.handleMessage(IInputConnectionWrapper.java:85)
08-25 19:41:29.162: E/AndroidRuntime(998):  at android.os.Handler.dispatchMessage(Handler.java:99)
08-25 19:41:29.162: E/AndroidRuntime(998):  at android.os.Looper.loop(Looper.java:154)
08-25 19:41:29.162: E/AndroidRuntime(998):  at android.app.ActivityThread.main(ActivityThread.java:4945)
08-25 19:41:29.162: E/AndroidRuntime(998):  at java.lang.reflect.Method.invokeNative(Native Method)
08-25 19:41:29.162: E/AndroidRuntime(998):  at java.lang.reflect.Method.invoke(Method.java:511)
08-25 19:41:29.162: E/AndroidRuntime(998):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
08-25 19:41:29.162: E/AndroidRuntime(998):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
08-25 19:41:29.162: E/AndroidRuntime(998):  at dalvik.system.NativeStart.main(Native Method)

Any hints/pointers appreciated since this is an area where documentation is very sparse.

A: I manged to fix this myself by getting PasswordCharSequence to also implement Spannable in addition to Charsequnce and GetChars and implemented all spannable methods by delegating those onto mSource e.g. mSource.getSpans(...). The spans are now nicely applied onto the transformed text thus serving my purpose very well!


text: Q: Is it possible to scale QGraphicsItem geometry but not pen width? Is it possible to scale QGraphicsItem geometry but not pen width? I mean scaling with QGraphicsView::scale(). I.e. I want scale of graphics view to work as usual but for some items I want to have QPen width untouchable.


text:
Q: How do I share data between 3 separate authenticated users in Firestore? Each of the 3 users will need to read and write the data.
I've looked at other stackoverflow posts, but none seem to answer this question.
For this sharing scheme, I'm also wondering what the Firestore security rules should look like.

A: You can store an array in that document containing UIDs of those 3 users. For example lets call it "authorized_users".
{
  ...otherDocumentFields,
  authorized_users: ["uid1", "uid2", "uid3"]
}

You can use the following security rules so only those 3 users can read/write on that document:
match /collection/{docID} {
    allow read, write: if request.auth != null && request.auth.uid in resource.data.authorized_users;
}


text:
Q: multiple fields grouping in storm I have two Bolt class BoltX and BoltY. BoltY receives tuples from BoltX. BoltX declares output with multiple fields, each tuple contains 4 strings:
class BoltX implements IBasicBolt {
    ...
    public void declareOutputFields(OutputFieldsDeclarer declarer) {
        declarer.declare(new Fields("A","B","C","D"));
    }
}

In BoltY:
class BoltX implements IBasicBolt {
    boolean hasReceive = false;
    String A = null;
    String B = null;
    ...
    public void execute(Tuple input, BasicOutputCollector collector) {
        if (!hasReceive) {
            hasReceive = true;
            A = input.getString(0);
            B = input.getString(1);
        }

        if (!input.getString(0).equals(A) || !input.getString(1).equals(B)) {
            LOG.error("group error");
            return;
        }
        ...
    }
    ...
}

In Topology:
...
builder.setBolt("x", new BoltX(), 3);
builder.setBolt("y", new Bolty(), 3).fieldsGrouping("x", new Fields("A", "B"));
...

I think that the output from x with same fields "A" and "B" will go to the same task of BoltY.
However, the log of topology shows lots of "group error".
So how to group outputs with same fields  "A" and "B" to the same task of BoltY?

A: Seeing a lot of group errors in log file is expected. From http://storm.apache.org/documentation/Concepts.html the description of Field Grouping says
Fields grouping: The stream is partitioned by the fields specified in the grouping. For example, if the stream is grouped by the "user-id" field, tuples with the same "user-id" will always go to the same task, but tuples with different "user-id"'s may go to different tasks.
It means the tuples with same values for field A and B will always go to the same task but it does not mean that tuples with other vales for field A and B cannot go to the same task. For e.g. If your input data has following tuples
1, 2, 3, 4
1, 2, 5, 6
3, 4, 5, 6
In the above scenario the first two tuples are guaranteed to go to the same task but the third tuple can also go to the same task, specially when parallelism hint is set to 1 for BoltY. There is no other task. Think about it like hashcode method in java. Equal objects always have same hash codes but two different objects can have the same hashcode.


text:
Q: How can we make a Work Item Creator automatically a Follower? I am running Azure DevOps 2019 RC1 with an Inheritance Collection and a new Agile project.
I have a requirement that when a user creates a work item (task/issue), they must automatically be added as a follower of this work item.  How can I achieve this?  I have look in the rules for the work item under process customisation but it doesn't appear to be possible this way.
We are using the tickets to track issues.  Whoever discovers the issue raises the ticket.  The basic requirement is that anyone who raises a ticket should be automatically notified of its progress, even though they are not responsible for the development or testing.
Currently the work around is telling the user that when they create an issue they must click the Follow button, but it is easy for them to forget and then lose their updates.  It seems like a very simple customisation so maybe I'm missing the obvious.
Thanks

A: I think you can't auto follow things currently, but you can add notification setting that will send automatically emails when work item is updated. To do this, go to Project Settings > Notifications page and create new subscription. Select "Work/A work item is changed" and put "Members of ... team by role" in Deliver to selection. Set roles to "Created by" and untick the "Skip initiator".

A: Your problem would be addressed precisely with the feature requested in the official Azure DevOps' feedback platform here:
479189 - Automatically follow work items I interact with
(That page also mentions workarounds, including per-team one answered here, and a per-person alternative. See this comment. The shortcoming of both is that they don't allow to you to unsubscribe for selected tickets.)