问:
Angular Custom Directive
I have more than 5 input text field to accept only comm/dot and only numbers.

```<code>[(ngModel)]="company.internetbill"
[(ngModel)]="company.electricitybill"
[(ngModel)]="company.waterbill"
</code>```

etc..

I wrote a custom directive for the above validation.
it works fine,
My requirement is "when user input a -Comma- it must change decimal(dot).

```<code> commtodecimal(ref:any){
        if(ref.includes(",")){
        ref=ref.replace(",",".")
        this.user.internetbill=ref
  }
</code>```

is it possible to change the ngModel value in the same custom directive . so that i can use same directive for both features.

My Custom Directive is--

```<code>private regex: RegExp = new RegExp(/^[+-]?\d*[\.\,]?\d{0,8}$/g);
  private specialKeys: Array<string> = ['Backspace','ArrowLeft','ArrowRight','Delete'];
  constructor(private el:ElementRef) { }
  @HostListener('keydown',['$event'])onKeyDown(event:KeyboardEvent){
    if (this.specialKeys.indexOf(event.key) !== -1) {
      return;
    }
   const inputValue=this.el.nativeElement.value.concat(event.key)
    if(inputValue && !String(inputValue).match(this.regex)){
     event.preventDefault();
   }
   return
  }
</code>```

or please suggest any optimized way. so that can reuse the code

答:
You can achieve this with a custom directive, I made a simple custom directive to achieve that so it becomes reusable for all your inputs across your application.

I would leave this directive only for this work, following single responsibility pattern, leaving out the regex and other logic if not needed.

Open this url to see the example in action and the code: https://stackblitz.com/edit/angular-replacecommabydot-directive-ngmodel?file=src/app/replace-comma-by-dot.directive.ts

Key point for the directive to be able to modify the ngModel is:

```<code>@Directive({
  selector: '[ngModel][replaceCommaByDot]', // use ngModel selector here
})
export class ReplaceCommaByDotDirective {
  @Output() ngModelChange = new EventEmitter(); // emit with the same output name

  @HostListener('input', ['$event.target.value'])
  onInputChange(value: string) {
    value = value.replace(',', '.');
    this.ngModelChange.emit(value); // here we emit and the input with the banana box will receive and set the value
  }
}
</code>```

Title: Angular Custom Directive

Body:
I have more than 5 input text field to accept only comm/dot and only numbers.

[(ngModel)]="company.internetbill"
[(ngModel)]="company.electricitybill"
[(ngModel)]="company.waterbill"

etc..

I wrote a custom directive for the above validation.
it works fine,
My requirement is "when user input a -Comma- it must change decimal(dot).

 commtodecimal(ref:any){
        if(ref.includes(",")){
        ref=ref.replace(",",".")
        this.user.internetbill=ref
  }

is it possible to change the ngModel value in the same custom directive . so that i can use same directive for both features.

My Custom Directive is--

private regex: RegExp = new RegExp(/^[+-]?\d*[\.\,]?\d{0,8}$/g);
  private specialKeys: Array<string> = ['Backspace','ArrowLeft','ArrowRight','Delete'];
  constructor(private el:ElementRef) { }
  @HostListener('keydown',['$event'])onKeyDown(event:KeyboardEvent){
    if (this.specialKeys.indexOf(event.key) !== -1) {
      return;
    }
   const inputValue=this.el.nativeElement.value.concat(event.key)
    if(inputValue && !String(inputValue).match(this.regex)){
     event.preventDefault();
   }
   return
  }

or please suggest any optimized way. so that can reuse the code

Body:
You can achieve this with a custom directive, I made a simple custom directive to achieve that so it becomes reusable for all your inputs across your application.

I would leave this directive only for this work, following single responsibility pattern, leaving out the regex and other logic if not needed.

Open this url to see the example in action and the code: https://stackblitz.com/edit/angular-replacecommabydot-directive-ngmodel?file=src/app/replace-comma-by-dot.directive.ts

Key point for the directive to be able to modify the ngModel is:

@Directive({
  selector: '[ngModel][replaceCommaByDot]', // use ngModel selector here
})
export class ReplaceCommaByDotDirective {
  @Output() ngModelChange = new EventEmitter(); // emit with the same output name

  @HostListener('input', ['$event.target.value'])
  onInputChange(value: string) {
    value = value.replace(',', '.');
    this.ngModelChange.emit(value); // here we emit and the input with the banana box will receive and set the value
  }
}


来源: stackexchange

问:
JWT authentication and the purpose of refresh token
I'm trying to wrap my mind around JWT authentication. I've read a lot of articles and SO questions, but some of them are getting old and I still didn't get satisfactory answers.

I've read this SO question and from José F. Romaniello's answer I understand that:

with refresh token client requests new access token before the old one has expired (it is normal, expected behavior)

on mobile apps tokens never expire

Also on auth0 it says:

You can request new access tokens until the refresh token is on the
DenyList. Applications must store refresh tokens securely because they
essentially allow a user to remain authenticated forever.

So what's the point of having time limited access token if refresh token can request for new access tokens forever?

Then I've read this SO question, which references the SO question from above. In his answer qre0ct says:

...assume that if Bob has compromised the refresh token, he would be
using it to generate an access token (because access token is the only
thing which is authorized to access resources through the APIs). As
soon as Bob (attacker) requests with the newly generated access token
because Alice's (genuine user) access token is still valid, the server
would see this as an anomaly, because for a single refresh token there
can be only one authorized access token at a time.

If we presume that it is normal for a client to request new access token at any moment (every hour, or every time the user opens the web application, as José F. Romaniello said), how will server distinguish if it's Alice or Bob who's making a request for a new access token? And why would this be anomaly?

Also, a lot of people say that the advantage of JWT authentication is that server doesn't make DB calls. But from above quotation from auth0, they mention DenyList. So I guess there must be a DB call on every request to check if the token is not blacklisted? Is the no DB calls thing a myth?

And if I have to keep record of blacklisted tokens, why not just use access tokens and blacklist them if necessary? I cannot understand the advantage of having two tokens, because if either one of them gets stolen, the thief can stay logged in forever (especially in the context of mobile apps where refresh token lasts forever)

Thanks in advance for your patience and time.

答:
After I've slept it over the things got clear(er).

My problem was that I was observing refresh token exclusively from the point of view of security. And from that point of view I still don't understand if/what advantages usage of refresh token brings.

What I've realized is that the purpose of refresh token is to reduce DB calls - instead of checking if access token is blacklisted on every client request, a DB call is made only when new access token is requested (so every access-token-lifetime), to verify if refresh token is blacklisted or the new access token can be issued.

ContentLicense: CC BY-SA 4.0


问:
Can't convert a char to string using standard Linq methods?
I am trying to count the amounts of brackets in a given text using Linq standard methods. This is the code I have written so far.

using System;
using System.Linq;

namespace Exercises
{
    class BracketExercise
    {
        static void Main(string[] args)
        {
            string bracketlist = "a(werawq4rqdcds()()()((((()DAs3";
            string value = "(";
            //string value2 = ")";

            bool result = bracketlist.Contains(value);
            Console.WriteLine($"Does string contain specified substring? {result}");
            if (result == true)
            {
                int freq = bracketlist.Count(f => (f == value));
                Console.WriteLine(freq);
            }
        }

    }

}
```

Am I missing something? This piece gives me compiler error CS0019, Operator 'operator' cannot be applied to operands of type 'char' and 'string'.
I tried changing "Value" to a var type, but that didn't work either.ch

答:
When using LINQ, a string is treated like it's an IEnumerable<char> This means that in the following code:

```<code>int freq = bracketlist.Count(f => (f == value));
</code>```

f is of type char, not string. Since value is of type string, your code is trying to do char == string, which is the source of the error.

In this case, I would suggest you change your value to also be a char:

```<code>char value = '(';
</code>```

Take note of the different ' quotes. "A" is a string, 'A' is a char. The quotes you use are important to the compiler.

Body:
I am trying to count the amounts of brackets in a given text using Linq standard methods. This is the code I have written so far.

using System;
using System.Linq;

namespace Exercises
{
    class BracketExercise
    {
        static void Main(string[] args)
        {
            string bracketlist = "a(werawq4rqdcds()()()((((()DAs3";
            string value = "(";
            //string value2 = ")";

            bool result = bracketlist.Contains(value);
            Console.WriteLine($"Does string contain specified substring? {result}");
            if (result == true)
            {
                int freq = bracketlist.Count(f => (f == value));
                Console.WriteLine(freq);
            }
        }

    }

}

Am I missing something? This piece gives me compiler error CS0019, Operator 'operator' cannot be applied to operands of type 'char' and 'string'.
I tried changing "Value" to a var type, but that didn't work either.ch

Body:
When using LINQ, a string is treated like it's an IEnumerable<char> This means that in the following code:

int freq = bracketlist.Count(f => (f == value));

f is of type char, not string. Since value is of type string, your code is trying to do char == string, which is the source of the error.

In this case, I would suggest you change your value to also be a char:

char value = '(';

Take note of the different ' quotes. "A" is a string, 'A' is a char. The quotes you use are important to the compiler.


问:
Flutter Inkwell does not update right away
I am trying to insert a widget / change height of a widget upon clicking a button. As demonstrated by the video, the InkWell does not update after calling setState(). This only happens with Ink, if changed to Container everything works fine.

market.dart

```<code>class MarketPage extends StatefulWidget {
  const MarketPage({Key? key}) : super(key: key);

  @override
  _MarketPageState createState() => _MarketPageState();
}

class _MarketPageState extends State<MarketPage> {
  List<String> displayedList = [];
  bool isSearchActive = false;

  final TextEditingController _controller = new TextEditingController();

  @override
  void initState() {
    super.initState();
    MarketList marketList = context.read<MarketList>();
    displayedList = marketList.markets.keys.toList();
  }

  @override
  Widget build(BuildContext context) {
    return SingleChildScrollView(
      child: Column(
        mainAxisSize: MainAxisSize.min,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Padding(
            padding: const EdgeInsets.all(25),
            child: Row(
              mainAxisSize: MainAxisSize.max,
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Expanded(
                  child: Text(
                    "Markets",
                    style: TextStyle(fontSize: 30, fontWeight: FontWeight.bold),
                  ),
                ),
                isSearchActive == false
                    ? GestureDetector(
                        onTap: () {
                          print("hello");
                          setState(() {
                            isSearchActive = !isSearchActive;
                          });
                        },
                        child: Icon(
                          Icons.search,
                          size: 30,
                        ),
                      )
                    : GestureDetector(
                        onTap: () {
                          setState(() {
                            isSearchActive = !isSearchActive;
                          });
                        },
                        child: Icon(
                          Icons.arrow_right,
                          size: 30,
                        ),
                      )
              ],
            ),
          ),
          Container(
            height: isSearchActive == true ? 100 : 0,
          ),
          Flexible(
            child: ListView.separated(
              padding: EdgeInsets.all(20),
              separatorBuilder: (BuildContext context, int index) {
                return SizedBox(
                  height: 15,
                );
              },
              shrinkWrap: true,
              physics: BouncingScrollPhysics(),
              scrollDirection: Axis.vertical,
              itemCount: displayedList.length,
              itemBuilder: (BuildContext ctxt, int index) {
                return MarketCard(
                    index, displayedList.length - 1, displayedList[index]);
              },
            ),
          ),
        ],
      ),
    );
  }
</code>```

market_card.dart

```<code>class MarketCard extends StatefulWidget {
  final int myIndex;
  final int lastIndex;
  final String name;

  MarketCard(this.myIndex, this.lastIndex, this.name);

  @override
  State<MarketCard> createState() => _MarketCardState();
}

class _MarketCardState extends State<MarketCard> {
  @override
  initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Consumer<MarketList>(
      builder: (context, value, child) => InkWell(
        onTap: () {
          FocusManager.instance.primaryFocus?.unfocus();
          Navigator.push(
            context,
            MaterialPageRoute(
              builder: (context) => MarketDetailsPage(widget.name),
            ),
          );
        },
        borderRadius: BorderRadius.vertical(
          top: widget.myIndex == 0 ? Radius.circular(10) : Radius.circular(0),
          bottom: widget.myIndex == widget.lastIndex
              ? Radius.circular(10)
              : Radius.circular(0),
        ),
        child: card(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.start,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Row(
                    children: [
                      ClipOval(
                        child: SizedBox(
                          width: 50,
                          height: 50,
                          child:
                              Image.asset(value.markets[widget.name]!.iconURL),
                        ),
                      ),
                      SizedBox(width: 15),
                      Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            value.markets[widget.name]!.name,
                            style: TextStyle(
                                fontWeight: FontWeight.bold, fontSize: 18),
                          ),
                          SizedBox(height: 10),
                          Text(
                            "\$${value.markets[widget.name]!.currentPrice.toString()}",
                            style: TextStyle(
                                fontWeight: FontWeight.bold,
                                color: value.markets[widget.name]!
                                            .priceChangePercent >
                                        0
                                    ? Colors.green
                                    : Colors.red),
                          ),
                        ],
                      ),
                    ],
                  ),
                  Icon(Icons.keyboard_arrow_right),
                ],
              )
            ],
          ),
        ),
      ),
    );
  }

  @override
  void dispose() {
    super.dispose();
  }
}
</code>```

答:
Try with the below code.</p>
```<code>return SingleChildScrollView(
      child: Column(
        mainAxisSize: MainAxisSize.min,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Padding(
            padding: const EdgeInsets.all(25),
            child: Row(
              mainAxisSize: MainAxisSize.max,
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Expanded(
                  child: Text(
                    "Markets",
                    style: TextStyle(fontSize: 30, fontWeight: FontWeight.bold),
                  ),
                ),
                GestureDetector(
                  onTap: () {
                    setState(() {
                      isSearchActive = !isSearchActive;
                    });
                  },
                  child: Icon(isSearchActive ? Icons.arrow_right : Icons.search, size: 30),
                ),
              ],
            ),
          ),
          if (isSearchActive) Container(height: 100, color: Colors.blue),
          ListView.separated(
            shrinkWrap: true,
            primary: false,
            padding: EdgeInsets.all(20),
            separatorBuilder: (BuildContext context, int index) {
              return SizedBox(height: 15);
            },
            physics: BouncingScrollPhysics(),
            scrollDirection: Axis.vertical,
            itemCount: displayedList.length,
            itemBuilder: (BuildContext ctxt, int index) {
              return MarketCard(index, displayedList.length - 1, displayedList[index]);
            },
          ),
        ],
      ),
    );
</code>```

Body:
I am trying to insert a widget / change height of a widget upon clicking a button. As demonstrated by the video, the InkWell does not update after calling setState(). This only happens with Ink, if changed to Container everything works fine.

market.dart

class MarketPage extends StatefulWidget {
  const MarketPage({Key? key}) : super(key: key);

  @override
  _MarketPageState createState() => _MarketPageState();
}

class _MarketPageState extends State<MarketPage> {
  List<String> displayedList = [];
  bool isSearchActive = false;

  final TextEditingController _controller = new TextEditingController();

  @override
  void initState() {
    super.initState();
    MarketList marketList = context.read<MarketList>();
    displayedList = marketList.markets.keys.toList();
  }

  @override
  Widget build(BuildContext context) {
    return SingleChildScrollView(
      child: Column(
        mainAxisSize: MainAxisSize.min,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Padding(
            padding: const EdgeInsets.all(25),
            child: Row(
              mainAxisSize: MainAxisSize.max,
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Expanded(
                  child: Text(
                    "Markets",
                    style: TextStyle(fontSize: 30, fontWeight: FontWeight.bold),
                  ),
                ),
                isSearchActive == false
                    ? GestureDetector(
                        onTap: () {
                          print("hello");
                          setState(() {
                            isSearchActive = !isSearchActive;
                          });
                        },
                        child: Icon(
                          Icons.search,
                          size: 30,
                        ),
                      )
                    : GestureDetector(
                        onTap: () {
                          setState(() {
                            isSearchActive = !isSearchActive;
                          });
                        },
                        child: Icon(
                          Icons.arrow_right,
                          size: 30,
                        ),
                      )
              ],
            ),
          ),
          Container(
            height: isSearchActive == true ? 100 : 0,
          ),
          Flexible(
            child: ListView.separated(
              padding: EdgeInsets.all(20),
              separatorBuilder: (BuildContext context, int index) {
                return SizedBox(
                  height: 15,
                );
              },
              shrinkWrap: true,
              physics: BouncingScrollPhysics(),
              scrollDirection: Axis.vertical,
              itemCount: displayedList.length,
              itemBuilder: (BuildContext ctxt, int index) {
                return MarketCard(
                    index, displayedList.length - 1, displayedList[index]);
              },
            ),
          ),
        ],
      ),
    );
  }

market_card.dart

class MarketCard extends StatefulWidget {
  final int myIndex;
  final int lastIndex;
  final String name;

  MarketCard(this.myIndex, this.lastIndex, this.name);

  @override
  State<MarketCard> createState() => _MarketCardState();
}

class _MarketCardState extends State<MarketCard> {
  @override
  initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Consumer<MarketList>(
      builder: (context, value, child) => InkWell(
        onTap: () {
          FocusManager.instance.primaryFocus?.unfocus();
          Navigator.push(
            context,
            MaterialPageRoute(
              builder: (context) => MarketDetailsPage(widget.name),
            ),
          );
        },
        borderRadius: BorderRadius.vertical(
          top: widget.myIndex == 0 ? Radius.circular(10) : Radius.circular(0),
          bottom: widget.myIndex == widget.lastIndex
              ? Radius.circular(10)
              : Radius.circular(0),
        ),
        child: card(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.start,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Row(
                    children: [
                      ClipOval(
                        child: SizedBox(
                          width: 50,
                          height: 50,
                          child:
                              Image.asset(value.markets[widget.name]!.iconURL),
                        ),
                      ),
                      SizedBox(width: 15),
                      Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            value.markets[widget.name]!.name,
                            style: TextStyle(
                                fontWeight: FontWeight.bold, fontSize: 18),
                          ),
                          SizedBox(height: 10),
                          Text(
                            "\$${value.markets[widget.name]!.currentPrice.toString()}",
                            style: TextStyle(
                                fontWeight: FontWeight.bold,
                                color: value.markets[widget.name]!
                                            .priceChangePercent >
                                        0
                                    ? Colors.green
                                    : Colors.red),
                          ),
                        ],
                      ),
                    ],
                  ),
                  Icon(Icons.keyboard_arrow_right),
                ],
              )
            ],
          ),
        ),
      ),
    );
  }

  @override
  void dispose() {
    super.dispose();
  }
}

Body:
Try with the below code.

return SingleChildScrollView(
      child: Column(
        mainAxisSize: MainAxisSize.min,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Padding(
            padding: const EdgeInsets.all(25),
            child: Row(
              mainAxisSize: MainAxisSize.max,
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Expanded(
                  child: Text(
                    "Markets",
                    style: TextStyle(fontSize: 30, fontWeight: FontWeight.bold),
                  ),
                ),
                GestureDetector(
                  onTap: () {
                    setState(() {
                      isSearchActive = !isSearchActive;
                    });
                  },
                  child: Icon(isSearchActive ? Icons.arrow_right : Icons.search, size: 30),
                ),
              ],
            ),
          ),
          if (isSearchActive) Container(height: 100, color: Colors.blue),
          ListView.separated(
            shrinkWrap: true,
            primary: false,
            padding: EdgeInsets.all(20),
            separatorBuilder: (BuildContext context, int index) {
              return SizedBox(height: 15);
            },
            physics: BouncingScrollPhysics(),
            scrollDirection: Axis.vertical,
            itemCount: displayedList.length,
            itemBuilder: (BuildContext ctxt, int index) {
              return MarketCard(index, displayedList.length - 1, displayedList[index]);
            },
          ),
        ],
      ),
    );


问:
service crash with "Context.startForegroundService() did not then call Service.startForeground()"
Hello friends. I use this code inside the service for the pedometer service and I will
encounter the following error. Thank you for your help.

*error
android.app.RemoteServiceException: Context.startForegroundService() did not then call
Service.startForeground()
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2220)
at android.os.Handler.dispatchMessage(Handler.java:109)
at android.os.Looper.loop(Looper.java:166)
at android.app.ActivityThread.main(ActivityThread.java:7555)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:469)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:963)

```<code>class MyService : Service(), SensorEventListener {
private var sensorManager: SensorManager? = null
private var running = false
private var totalStep = 0f
private var previousTotalStep = 0f

override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
    try {
        running = true
        val stepSensor = sensorManager?.getDefaultSensor(Sensor.TYPE_STEP_COUNTER)
        sensorManager?.registerListener(this, stepSensor, SensorManager.SENSOR_DELAY_UI)
    } catch (e: Exception) {

    }
    return START_STICKY

}

override fun onBind(p0: Intent?): IBinder? {
    return null
}

override fun onSensorChanged(event: SensorEvent?) {
    if (running) {
        totalStep = event!!.values[0]
        val currentSteps = totalStep.toInt() - previousTotalStep.toInt()
        Constant.editor(this).putFloat(STEPNUMBER, previousTotalStep).apply()
    }
}

override fun onAccuracyChanged(p0: Sensor?, p1: Int) {

}

override fun stopService(name: Intent?): Boolean {
    return super.stopService(name)
}

override fun onDestroy() {
    val intent = Intent(this, MyPhoneReciver::class.java)
    sendBroadcast(intent)
    super.onDestroy()
}
</code>```

}

```<code></code>```

答:
The reason for this crash is :

-> From Android 9 Pie if your service does not call startForeground within 5 seconds after it has been started with the command startForegroundService ... then it produces an ANR + Crash.

Solution : After starting the service with startForegroundService, call startForeground() in the service’s onCreate method.

Body:
Hello friends. I use this code inside the service for the pedometer service and I will
encounter the following error. Thank you for your help.

*error
android.app.RemoteServiceException: Context.startForegroundService() did not then call
Service.startForeground()
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2220)
at android.os.Handler.dispatchMessage(Handler.java:109)
at android.os.Looper.loop(Looper.java:166)
at android.app.ActivityThread.main(ActivityThread.java:7555)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:469)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:963)

class MyService : Service(), SensorEventListener {
private var sensorManager: SensorManager? = null
private var running = false
private var totalStep = 0f
private var previousTotalStep = 0f

override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
    try {
        running = true
        val stepSensor = sensorManager?.getDefaultSensor(Sensor.TYPE_STEP_COUNTER)
        sensorManager?.registerListener(this, stepSensor, SensorManager.SENSOR_DELAY_UI)
    } catch (e: Exception) {

    }
    return START_STICKY

}

override fun onBind(p0: Intent?): IBinder? {
    return null
}

override fun onSensorChanged(event: SensorEvent?) {
    if (running) {
        totalStep = event!!.values[0]
        val currentSteps = totalStep.toInt() - previousTotalStep.toInt()
        Constant.editor(this).putFloat(STEPNUMBER, previousTotalStep).apply()
    }
}

override fun onAccuracyChanged(p0: Sensor?, p1: Int) {

}

override fun stopService(name: Intent?): Boolean {
    return super.stopService(name)
}

override fun onDestroy() {
    val intent = Intent(this, MyPhoneReciver::class.java)
    sendBroadcast(intent)
    super.onDestroy()
}

}


问:
Unbuffered character input for python on a windows machine
What I am trying to do

I am trying to design a stopwatch with lap timing. When you press "L" then a lap is completed and when you press "S" all laps are completed and the timings are displayed in order.

While in C++ I can do this with the function _getch() from conio.h and it would be quite easy. I want to write this program in python as it would be a lot more easier and also the time handling in C++ proved to be hard.

Still I did write a program (which was for cube timing) on this link:
 Cube timer

Problem

There is no function like _getch(). And this is a problem because at the end of a lap you can't press a key and an enter key because it would be time taking and irritating for the user.

things I read

I read about the curses library but alas it has no windows port.

I tried a program that was supposed to work according to the website. This was from the link

 Link to getch recipe

But it did not work.

What I tried:

 msvcrt.getch()

```

    >>> import msvcrt
    >>> msvcrt.getch()
    '\xff'

```

I believe that FF is the hexadecimal equivalent of 255.

I did not understand why this is happenning.

 readch()  as sugggested in @martineau

import msvcrt

def readch(echo=True):
    "Get a single character on Windows."
    while msvcrt.kbhit():  # clear out keyboard buffer
        msvcrt.getch()
    ch = msvcrt.getch()
    while ch in '\x00\xe0':  # arrow or function key prefix?
        msvcrt.getch()
        ch = msvcrt.getch()  # second call returns the actual key code
    if echo:
        msvcrt.putch(ch)
    return ch.decode()

a = []

for i in range(10):
    a.append(readch())

The error that i got:

```<code>>>>

Traceback (most recent call last):
  File "C:/Python25/1.py", line 30, in <module>
    a.append(readch())
  File "C:/Python25/1.py", line 25, in readch
    return ch.decode()
UnicodeDecodeError: 'ascii' codec can't decode byte 0xff in position 0: ordinal not in range(128)
</code>```

What I need help with

A function that works like _getch() or something equivalent that works on a windows machine.

Machine specs

Python IDLE 2.5.4 or 2.6 or 2.7

Windows XP SP3

答: You can't use msvcrt library in IDLE. Try your code in Windows command line.</p>

ContentLicense: CC BY-SA 3.0

Body:
What I am trying to do

I am trying to design a stopwatch with lap timing. When you press "L" then a lap is completed and when you press "S" all laps are completed and the timings are displayed in order.

While in C++ I can do this with the function _getch() from conio.h and it would be quite easy. I want to write this program in python as it would be a lot more easier and also the time handling in C++ proved to be hard.

Still I did write a program (which was for cube timing) on this link:
 Cube timer

Problem

There is no function like _getch(). And this is a problem because at the end of a lap you can't press a key and an enter key because it would be time taking and irritating for the user.

things I read

I read about the curses library but alas it has no windows port.

I tried a program that was supposed to work according to the website. This was from the link

 Link to getch recipe

But it did not work.

What I tried:

 msvcrt.getch()

    >>> import msvcrt
    >>> msvcrt.getch()
    '\xff'

I believe that FF is the hexadecimal equivalent of 255.

I did not understand why this is happenning.

 readch()  as sugggested in @martineau

import msvcrt

def readch(echo=True):
    "Get a single character on Windows."
    while msvcrt.kbhit():  # clear out keyboard buffer
        msvcrt.getch()
    ch = msvcrt.getch()
    while ch in '\x00\xe0':  # arrow or function key prefix?
        msvcrt.getch()
        ch = msvcrt.getch()  # second call returns the actual key code
    if echo:
        msvcrt.putch(ch)
    return ch.decode()

a = []

for i in range(10):
    a.append(readch())

The error that i got:

>>>

Traceback (most recent call last):
  File "C:/Python25/1.py", line 30, in <module>
    a.append(readch())
  File "C:/Python25/1.py", line 25, in readch
    return ch.decode()
UnicodeDecodeError: 'ascii' codec can't decode byte 0xff in position 0: ordinal not in range(128)

What I need help with

A function that works like _getch() or something equivalent that works on a windows machine.

Machine specs

Python IDLE 2.5.4 or 2.6 or 2.7

Windows XP SP3


问:
We made it reliable. What's next? Usability?
I'm working in a small development group. We are building and improving our product.

Half a year ago we couldn't think about higher characteristics, such as usability, because we had so many problems with our product. Many bugs, high technical debt, low performance and other problems kept us from being able to focus on usability.

With time we've improved our process substantially. What we've done:

Real Agile iterations

Continuous integration

Testing(unit-tests, functional Smoke tests, performance)

Code quality is 'good'

Painless deployment process

So we are now producing stable, reliable releases. The following quote (paraphrased) describes our current situation:

first - make it work; after that, make it reliable; after that, make it usable

We are geeks, so we can't 'make' a great UI by ourselves.
So what should we do? What direction can you recommend?
Maybe we should hire Usability experts part-time or full-time?
How can we explain the importance of Usability to our stakeholders?
How do we convince them that this is useful?

答:
I'm in the same boat as you are - I basically live on the command line, and I'm completely out of touch with the modern UI (both web and desktop application).

The solution for me was using a real UI developer for all my GUIs, and I just live in the back-end as it were.

There are quite a few benefits of this arrangement:

You don't have to debug your own crappy UIs anymore :) that's their job, and they're better at it than you, so no worries.

Your code will naturally gravitate to a MVC or at least tiered API approach, which is easier to code against for all parties involved.

Good UI people know what questions to ask end users, and know when those users don't know what they're talking about. I certainly don't have that skill.

You can do what you do best, and they do what they do best, making a stronger team overall.

The cons are obvious - you need to not only find the money for a talented UI dev, but you need to find a talented UI dev!

Now, I can't speak for you and your company's position in your market etc etc (I also don't do buisnessspeak :) ) but if you can afford another hire, it will give back more to the team than the cost of the position. It did for me!

OwnerDisplayName: Fedyashev Nikita

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Gortok

OwnerDisplayName: Mike


问:
Codeigniter dynamic configuration
How do I let users set the database configuration for a new CI install?

My intention is to have a form that allows them to enter the data then either generate a new config file or to set the options in the database.php file.

Is this possible?

答:
Let's say you want to create a database config file. Here's how I do it:

Create a "dummy" config file by copying  a real one, and use values that look something like this:

```<code>$db['default']['hostname'] = '__HOSTNAME__';
$db['default']['username'] = '__USERNAME__';
$db['default']['password'] = '__PASSWORD__';
$db['default']['database'] = '__DATABASE__';
</code>```

Have the user complete the installation form, and verify all the data by testing a database connection. Next, use file_get_contents() to grab the content of the "dummy" config file, use a simple str_replace() to rewrite the values with the ones the user provided, then write the new content to your real config file overwriting the entire thing.

Here's part of the actual code I'm using for creating the file, just to get an idea. Bear in mind that I'm running this on a totally separate CI installation (the "installer"), and this is not a copy/paste example:

```<code>// Write the database configuration file
$config = array(
    'hostname',
    'username',
    'password',
    'database',
);

$data = file_get_contents(APPPATH.'config/dummy_database.php');
$file = '../private/config/database.php';

// Oops! Just caught this after posting: str_replace() accepts arrays.
// TODO: Use the array method instead of a loop!
foreach ($config as $item)
{
    $data = str_replace('____'.strtoupper($item).'____', mysql_escape_string($this->data[$item]), $data);
}
if (write_file($file, $data))
{
    $this->message('Database configuration file was written!', 'success');
    @chmod($file, 0644);
    {
        if (is_really_writable($file))
        {
            $this->message('The database configuration is still writable, make sure to set permissions to <code>0644</code>!', 'notice');
        }
    }
}
else
{
    $this->message('Could not write the database configuration file!');
    redirect('step_4');
}
</code>```

This retains the original copy of the "dummy" config file. You could use the same logic for editing, just read the current config values for anything the user has not changed and do the same string replacement technique.

Title: Codeigniter dynamic configuration

Body:
Let's say you want to create a database config file. Here's how I do it:

Create a "dummy" config file by copying  a real one, and use values that look something like this:

$db['default']['hostname'] = '__HOSTNAME__';
$db['default']['username'] = '__USERNAME__';
$db['default']['password'] = '__PASSWORD__';
$db['default']['database'] = '__DATABASE__';

Have the user complete the installation form, and verify all the data by testing a database connection. Next, use file_get_contents() to grab the content of the "dummy" config file, use a simple str_replace() to rewrite the values with the ones the user provided, then write the new content to your real config file overwriting the entire thing.

Here's part of the actual code I'm using for creating the file, just to get an idea. Bear in mind that I'm running this on a totally separate CI installation (the "installer"), and this is not a copy/paste example:

// Write the database configuration file
$config = array(
    'hostname',
    'username',
    'password',
    'database',
);

$data = file_get_contents(APPPATH.'config/dummy_database.php');
$file = '../private/config/database.php';

// Oops! Just caught this after posting: str_replace() accepts arrays.
// TODO: Use the array method instead of a loop!
foreach ($config as $item)
{
    $data = str_replace('____'.strtoupper($item).'____', mysql_escape_string($this->data[$item]), $data);
}
if (write_file($file, $data))
{
    $this->message('Database configuration file was written!', 'success');
    @chmod($file, 0644);
    {
        if (is_really_writable($file))
        {
            $this->message('The database configuration is still writable, make sure to set permissions to <code>0644</code>!', 'notice');
        }
    }
}
else
{
    $this->message('Could not write the database configuration file!');
    redirect('step_4');
}

This retains the original copy of the "dummy" config file. You could use the same logic for editing, just read the current config values for anything the user has not changed and do the same string replacement technique.


问:
How to pass data from nodejs to inside html script tags
I'm using expressjs as a server on 8000 port. I want to send a string value from expressjs file to html script tags and use this string value in script tags.
name variable is coming as a empty string now.
How can i console.log name variable's value?

static-pages-server.js:

```<code> app.get('/index', function(req, res) {
        var name = "hello";
        res.render(__dirname + "/static-pages/journey-analize-report/index.html", {name:name});
    });
</code>```

index.html:

```<code> <script type="text/javascript">
        console.log(name);
 </script>
</code>```

Edit : I used ejs and now problem is how should i describe name attribute in script tags? Below code is giving syntax error.

```<code><script type="text/javascript">
        console.log(<%=name%>);
 </script>
</code>```

答:
here is the answer How do I use HTML as the view engine in Express?

what you will need is a view engine package in your app. there are many view engines currently available.

then set that view engine in express app.  Trigger the view render via a call from your route’s response like you have done above.

Then in  your view render the html output using the view variables and if these variables are outputted into html you can use them in your in browser JavaScript. You can also call a service in your html sending the dynamic data as well.

check out esj or pug (ps pug is my personal favourite )

Body:
I'm using expressjs as a server on 8000 port. I want to send a string value from expressjs file to html script tags and use this string value in script tags.
name variable is coming as a empty string now.
How can i console.log name variable's value?

static-pages-server.js:

 app.get('/index', function(req, res) {
        var name = "hello";
        res.render(__dirname + "/static-pages/journey-analize-report/index.html", {name:name});
    });

index.html:

Edit : I used ejs and now problem is how should i describe name attribute in script tags? Below code is giving syntax error.


问:
Unable to import key vault certificate to app service - Failed to get App Service Service principal details
I have a SSL cert in my Azure key vault that I am trying to import to the correct App Service.

I am the owner of the Azure subscription and I have given the App Service GET and LIST permissions for certificates on the vault.

On my App Service I click TLS/SSL settings > Private Key Certificates (.pfx) > Import Key Vault Certificate

This is the message I receive

Another owner on the subscription is able to complete this process successfully. So I am not sure why I am not able to when we both have owner roles on the subscription?

Is anyone able to offer any suggestions please?

答:
When you are trying the operation from Azure Portal and you are a Owner of the Subscription, then Azure by default adds a access policy for the Azure APP Service Resource Provider and you do not further require to add the any access policies for the Web App.

Example:

I created a Web App with system managed identity and a Key vault with the below added Access Policies. I am an Owner of the Subscription and a User in the Azure Active Directory.

When , I perform the import certificate operation in the TLS/SSL Settings, the access policy get automatically updated with the Azure App Service Service Principal Credential.

In your case its not able to find the details of the Resource Provider Service Principal. As a Solution you can try adding Microsoft.Azure.CertificateRegistration (i.e. ObjectId : ed47c2a1-bd23-4341-b39c-f4fd69138dd3) , Microsoft Azure App Service (Internal) (i.e. ObjectId : 505e3754-d8a9-4f8b-97b6-c3e48ac7a543) & Microsoft Azure App Service (i.e. ObjectId : f8daea97-62e7-4026-becf-13c2ea98e8b4) in access policy for key vault.

Note: If the Issue is still not resolved , Please reach out to Azure Support for better assistance.


答: On the line int freq = bracketlist.Count(f => (f == value)); f is of type char (because the enumeration on a string works on char). You are comparing it to value, which is of type string. Change string value = "("; to char value = '(';. Note the single quotes used to declare a char (as opposed to using double quotes, which declares a string).

Title: Can't convert a char to string using standard Linq methods?


问:
Property in type is not assignable to the same property in base type - Typescript bug?
Typescript complains because somehow the type of the abstract property is lost when extending. Is this a bug or am I doing something wrong?

```<code>type A = {
    bar: number,
    krass: Array<string>,
}

abstract class Foo<T> {
    protected abstract arr: (keyof T & string)[];
}

class Bar extends Foo<A> {
    arr = ["bar", "krass"];
}
</code>```

Error msg:

```<code>Property 'arr' in type 'Bar' is not assignable to the same property in base type 'Foo<A>'.
  Type 'string[]' is not assignable to type '("bar" | "krass")[]'.
    Type 'string' is not assignable to type '"bar" | "krass"'.
</code>```

答:
Three possible solutions: if you don't mind (or actually prefer) the array being read-only, you can declare it as readonly and as const:

```<code>abstract class Foo<T> {
    protected abstract arr: readonly (keyof T & string)[];
}

class Bar extends Foo<A> {
    arr = ["bar", "krass"] as const;
}
</code>```

Otherwise you need a type annotation in the subclass:

```<code>abstract class Foo<T> {
    protected abstract arr: (keyof T & string)[];
}

class Bar extends Foo<A> {
    arr: (keyof A & string)[] = ["bar", "krass"];
}
</code>```

Or you could set this value in the base class's constructor, so that it's contextually typed by the super call:

```<code>abstract class Foo<T> {
    constructor(
        protected arr: (keyof T & string)[]
    ) {}
}

class Bar extends Foo<A> {
    constructor() {
        super(["bar", "krass"]);
    }
}
</code>```

Body:
Typescript complains because somehow the type of the abstract property is lost when extending. Is this a bug or am I doing something wrong?

type A = {
    bar: number,
    krass: Array<string>,
}

abstract class Foo<T> {
    protected abstract arr: (keyof T & string)[];
}

class Bar extends Foo {
    arr = ["bar", "krass"];
}

Error msg:

Property 'arr' in type 'Bar' is not assignable to the same property in base type 'Foo'.
  Type 'string[]' is not assignable to type '("bar" | "krass")[]'.
    Type 'string' is not assignable to type '"bar" | "krass"'.

Body:
Three possible solutions: if you don't mind (or actually prefer) the array being read-only, you can declare it as readonly and as const:

abstract class Foo<T> {
    protected abstract arr: readonly (keyof T & string)[];
}

class Bar extends Foo<A> {
    arr = ["bar", "krass"] as const;
}

Otherwise you need a type annotation in the subclass:

abstract class Foo<T> {
    protected abstract arr: (keyof T & string)[];
}

class Bar extends Foo<A> {
    arr: (keyof A & string)[] = ["bar", "krass"];
}

Or you could set this value in the base class's constructor, so that it's contextually typed by the super call:

abstract class Foo<T> {
    constructor(
        protected arr: (keyof T & string)[]
    ) {}
}

class Bar extends Foo<A> {
    constructor() {
        super(["bar", "krass"]);
    }
}


问:
Transparent or Invisible
I'm trying to use an ImageView without any background. I know that I can use

```<code>imageView.setVisibility(INVISIBLE);
</code>```

and

```<code>imageView.setBackgroundColor(Color.TRANSPARENT);
</code>```

I was wondering which one is more efficient? or any extra solution?

答:
The two lines don't have the same purpose, so you don't really have to compare their efficiency.

The first one changes the view visibility, so the entire view is still drawn, takes the space in the layout, but is not visible at the moment.

On the other hand, an ImageView with an invisible background can still be visible if it has an android:src that is not null.

Here is a random example that uses the two together: it's an imageview with a transparent background, but with a source image, for which the visibility changes based on a certain condition, so it can be INVISIBLE or VISIBLE:

```<code> <ImageView
      android:layout_width="50dp"
      android:layout_height="50dp"
      android:visibility="@{!obj.mealbox}"
      android:background="@android:color/transparent"
      android:src="@drawable/ic_list_sorting_close"
      app:tint="@color/dish_icon_color" />
</code>```

Since your purpose is to

use an ImageView without any background.

only the second option will work.

Title: Transparent or Invisible

Body:
I'm trying to use an ImageView without any background. I know that I can use

imageView.setVisibility(INVISIBLE);

and

imageView.setBackgroundColor(Color.TRANSPARENT);

I was wondering which one is more efficient? or any extra solution?

Body:
The two lines don't have the same purpose, so you don't really have to compare their efficiency.

The first one changes the view visibility, so the entire view is still drawn, takes the space in the layout, but is not visible at the moment.

On the other hand, an ImageView with an invisible background can still be visible if it has an android:src that is not null.

Here is a random example that uses the two together: it's an imageview with a transparent background, but with a source image, for which the visibility changes based on a certain condition, so it can be INVISIBLE or VISIBLE:

 <ImageView
      android:layout_width="50dp"
      android:layout_height="50dp"
      android:visibility="@{!obj.mealbox}"
      android:background="@android:color/transparent"
      android:src="@drawable/ic_list_sorting_close"
      app:tint="@color/dish_icon_color" />

Since your purpose is to

use an ImageView without any background.

only the second option will work.


问:
Query with column named "name"
I am trying to join a few tables but it is failing on my join statement. I believe it is because the column name in the second join is "name" and perhaps MySQL thinks i am trying to access an attribute? how can i get around this?

```<code>SELECT surgery_city.*, s.surgeon_type, st.abbrev
FROM surgery_city
LEFT JOIN surgery_key as s ON s.surg_id = treatment_id
LEFT JOIN states as st ON st.name = surgery_city.state
WHERE treatment_id='10001'
</code>```

The issue is the second left join where i reference st.name - any ideas on how i can reference that column properly? changing the column name in the table is not an option at this point unfortunately :(..

Thanks,

Silver Tiger

UPDATE:

The error I get on the query above is:

[Err] 1267 - Illegal mix of collations (utf8_unicode_ci,IMPLICIT) and (utf8_general_ci,IMPLICIT) for operation '='

when i surround the field by back ticks i get the following:

```<code>LEFT JOIN states as st ON `st.name` = seo_surgery_city.state
</code>```

I get the following instead:

[Err] 1054 - Unknown column 'st.name' in 'on clause'

It also fails on

```<code>LEFT JOIN states as st ON st.`name` = seo_surgery_city.state
</code>```

(single quotes = back ticks there, but it wont display properly here)

[Err] 1267 - Illegal mix of collations (utf8_unicode_ci,IMPLICIT) and (utf8_general_ci,IMPLICIT) for operation '='

Also fails on

```<code>LEFT JOIN states as st ON `st`.`name` = seo_surgery_city.state
</code>```

[Err] 1267 - Illegal mix of collations (utf8_unicode_ci,IMPLICIT) and (utf8_general_ci,IMPLICIT) for operation '='

答:
Update 2022:

The keyword "name" is now listed on the "keywords and reserved words" list of the official MySQL documentation. You can find all the reserved words there.

Reference: https://dev.mysql.com/doc/refman/8.0/en/keywords.html#keywords-8-0-detailed-N

Title: Query with column named "name"

Body:
I am trying to join a few tables but it is failing on my join statement. I believe it is because the column name in the second join is "name" and perhaps MySQL thinks i am trying to access an attribute? how can i get around this?

SELECT surgery_city.*, s.surgeon_type, st.abbrev
FROM surgery_city
LEFT JOIN surgery_key as s ON s.surg_id = treatment_id
LEFT JOIN states as st ON st.name = surgery_city.state
WHERE treatment_id='10001'

The issue is the second left join where i reference st.name - any ideas on how i can reference that column properly? changing the column name in the table is not an option at this point unfortunately :(..

Thanks,

Silver Tiger

UPDATE:

The error I get on the query above is:

[Err] 1267 - Illegal mix of collations (utf8_unicode_ci,IMPLICIT) and (utf8_general_ci,IMPLICIT) for operation '='

when i surround the field by back ticks i get the following:

LEFT JOIN states as st ON `st.name` = seo_surgery_city.state

I get the following instead:

[Err] 1054 - Unknown column 'st.name' in 'on clause'

It also fails on

LEFT JOIN states as st ON st.`name` = seo_surgery_city.state

(single quotes = back ticks there, but it wont display properly here)

[Err] 1267 - Illegal mix of collations (utf8_unicode_ci,IMPLICIT) and (utf8_general_ci,IMPLICIT) for operation '='

Also fails on

LEFT JOIN states as st ON `st`.`name` = seo_surgery_city.state

[Err] 1267 - Illegal mix of collations (utf8_unicode_ci,IMPLICIT) and (utf8_general_ci,IMPLICIT) for operation '='


问:
PhysicalPath Web Api .net 6 is null
I am using RCL with Blazor Wasm and net 6-rc1

My images in the RCL (CommonComponents) project are in the wwwroot / lib / bootstrap-icons / icons folder.

In Net 5, all images are received from the Controller and web api with the following code:

```<code>var rootPath = _webHostEnverioment.WebRootFileProvider.GetDirectoryContents ("/ _ Content / CommonComponents"). FirstOrDefault (x => x.Name == "lib"). Physical path;
</code>```

But when projects are updated from .net5 to .net6, PhysicalPath is empty
In version 6, webHostEnvironment. WebRootPath also returns null

Has access to folders and their contents changed in .NET 6?

答:
I had same issue. In .net 5.0 WebRootFileProvider is simple PhysicalFileProvider, but in .net 6.0 CompositeFileProvider is used with 2 providers under the hood: ManifestStaticWebAssetFileProvider and PhysicalFileProvider

ManifestStaticWebAssetFileProvider returns null for PhysicalPath property for directories. I could not google any info about ManifestStaticWebAssetFileProvider and why we need it. To revert old behavior you can do in startup class:

```<code>_webHostEnverioment.WebRootFileProvider = new PhysicalFileProvider(_webHostEnverioment.WebRootPath);
</code>```

Title: PhysicalPath Web Api .net 6 is null

Body:
I am using RCL with Blazor Wasm and net 6-rc1

My images in the RCL (CommonComponents) project are in the wwwroot / lib / bootstrap-icons / icons folder.

In Net 5, all images are received from the Controller and web api with the following code:

var rootPath = _webHostEnverioment.WebRootFileProvider.GetDirectoryContents ("/ _ Content / CommonComponents"). FirstOrDefault (x => x.Name == "lib"). Physical path;

But when projects are updated from .net5 to .net6, PhysicalPath is empty
In version 6, webHostEnvironment. WebRootPath also returns null

Has access to folders and their contents changed in .NET 6?

Body:
I had same issue. In .net 5.0 WebRootFileProvider is simple PhysicalFileProvider, but in .net 6.0 CompositeFileProvider is used with 2 providers under the hood: ManifestStaticWebAssetFileProvider and PhysicalFileProvider

ManifestStaticWebAssetFileProvider returns null for PhysicalPath property for directories. I could not google any info about ManifestStaticWebAssetFileProvider and why we need it. To revert old behavior you can do in startup class:

_webHostEnverioment.WebRootFileProvider = new PhysicalFileProvider(_webHostEnverioment.WebRootPath);


问:
DebounceTime after first value in RxJS
I need a specific behavior that I can't get with the RxJS operators. The closest would be to use DebounceTime only for values entered after the first one, but I can't find a way to do it. I have also tried with ThrottleTime but it is not exactly what I am looking for, since it launches intermediate calls, and I only want one at the beginning that is instantaneous, and another at the end, nothing else.

ThrottleTime

```<code>throttleTime(12 ticks, { leading: true, trailing: true })

source:             --0--1-----2--3----4--5-6---7------------8-------9---------
throttle interval:  --[~~~~~~~~~~~I~~~~~~~~~~~I~~~~~~~~~~~I~~~~~~~~~~~]--------
output:             --0-----------3-----------6-----------7-----------9--------

source_2:           --0--------1------------------2--------------3---4---------
throttle interval:  --[~~~~~~~~~~~I~~~~~~~~~~~]---[~~~~~~~~~~~]--[~~~~~~~~~~~I~
output_2:           --0-----------1---------------2--------------3-----------4-
</code>```

DebounceTime

```<code>debounceTime(500)

source:             --0--1--------3------------4-5-6-7-8-9-10-11--13----------------
debounce_interval:  -----[~~~~~]--[~~~~~]--------------------------[~~~~~]----------
output:             -----------1--------3--------------------------------13---------
</code>```

What I want

```<code>debounceTimeAfterFirst(500) (?)

source:             --0--1--------3------------4-5-6-7-8-9-10-11--13----------------
debounce_interval:  -----[~~~~~]--[~~~~~]--------------------------[~~~~~]----------
output:             --0--------1--3------------4-------------------------13---------
</code>```

As you see, the debounce time is activated when a new value is entered. If the debounce time passes and any new value has been entered, it stops the listening the debounceTime action and waits to start a new one.

Edit: I forgot to comment that this must be integrated with NgRx’s Effects, so it must be a continuous stream that mustn't be completed. Terminating it would probably cause it to stop listening for dispatched actions.

答:
I think you could do it like the following, even though I can't think of any easier solution right now (I'm assuming you're using RxJS 7+ with connect() operator):

```<code>connect(shared$ => shared$.pipe(
  exhaustMap(value => merge(
    of(value),
    shared$.pipe(debounceTime(1000)),
  ).pipe(
    take(2),
  )),
)),
</code>```

Live demo: https://stackblitz.com/edit/rxjs-qwoesj?devtoolsheight=60&file=index.ts

connect() will share the source Observable and lets you reuse it in its project function multiple times. I'm using it only to use the source Observable inside another chain.

exhaustMap() will ignore all next notifications until its inner Observable completes. In this case the inner Observable will immediately reemit the current value (of(value)) and then use debounceTime(). Any subsequent emission from source is ignored by exhaustMap() because the inner Observable hasn't completed yet but is also passed to debounceTime(). Then take(2) is used to complete the chain after debounceTime() emits and the whole process can repeat when source emits because exhaustMap() won't ignore the next notification (its inner Observable has completed).

Title: DebounceTime after first value in RxJS

Body:
I need a specific behavior that I can't get with the RxJS operators. The closest would be to use DebounceTime only for values entered after the first one, but I can't find a way to do it. I have also tried with ThrottleTime but it is not exactly what I am looking for, since it launches intermediate calls, and I only want one at the beginning that is instantaneous, and another at the end, nothing else.

ThrottleTime

throttleTime(12 ticks, { leading: true, trailing: true })

source:             --0--1-----2--3----4--5-6---7------------8-------9---------
throttle interval:  --[~~~~~~~~~~~I~~~~~~~~~~~I~~~~~~~~~~~I~~~~~~~~~~~]--------
output:             --0-----------3-----------6-----------7-----------9--------

source_2:           --0--------1------------------2--------------3---4---------
throttle interval:  --[~~~~~~~~~~~I~~~~~~~~~~~]---[~~~~~~~~~~~]--[~~~~~~~~~~~I~
output_2:           --0-----------1---------------2--------------3-----------4-

DebounceTime

debounceTime(500)

source:             --0--1--------3------------4-5-6-7-8-9-10-11--13----------------
debounce_interval:  -----[~~~~~]--[~~~~~]--------------------------[~~~~~]----------
output:             -----------1--------3--------------------------------13---------

What I want

debounceTimeAfterFirst(500) (?)

source:             --0--1--------3------------4-5-6-7-8-9-10-11--13----------------
debounce_interval:  -----[~~~~~]--[~~~~~]--------------------------[~~~~~]----------
output:             --0--------1--3------------4-------------------------13---------

As you see, the debounce time is activated when a new value is entered. If the debounce time passes and any new value has been entered, it stops the listening the debounceTime action and waits to start a new one.

Edit: I forgot to comment that this must be integrated with NgRx’s Effects, so it must be a continuous stream that mustn't be completed. Terminating it would probably cause it to stop listening for dispatched actions.

Body:
I think you could do it like the following, even though I can't think of any easier solution right now (I'm assuming you're using RxJS 7+ with connect() operator):

connect(shared$ => shared$.pipe(
  exhaustMap(value => merge(
    of(value),
    shared$.pipe(debounceTime(1000)),
  ).pipe(
    take(2),
  )),
)),

Live demo: https://stackblitz.com/edit/rxjs-qwoesj?devtoolsheight=60&file=index.ts

connect() will share the source Observable and lets you reuse it in its project function multiple times. I'm using it only to use the source Observable inside another chain.

exhaustMap() will ignore all next notifications until its inner Observable completes. In this case the inner Observable will immediately reemit the current value (of(value)) and then use debounceTime(). Any subsequent emission from source is ignored by exhaustMap() because the inner Observable hasn't completed yet but is also passed to debounceTime(). Then take(2) is used to complete the chain after debounceTime() emits and the whole process can repeat when source emits because exhaustMap() won't ignore the next notification (its inner Observable has completed).


问:
Change the text cursor/caret in Visual Studio 2010
I've accidentally changed the text cursor/caret in Visual Studio 2010 from the line to the one with the box that highlights the entire character and cannot find out how to change it back.
Can anyone tell me how?
Thanks!</p>

答: I stuggled finding the insert key on my Mac book air because i'm running visual studio under bootcamp however i got it right by pressing fn + enter which i understand is equivalent to insert key on mac.


问:
I am trying to recreate the flutter docs app but something won't work
this is the code:

```<code>import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      home: ListViewTests(),
    );
  }
}

class _ListViewTestsState extends State<ListViewTests> {
  Widget listViewTest() {
    return ListView.builder(
        padding: const EdgeInsets.all(8),
        itemBuilder: (context, item) {
          item += 1;
          if (item.isOdd) return const Divider();
          return listTileTest(item);
        });
  }

  Widget listTileTest(int item) {
    return const ListTile(
      title: Text('hello'),
    );
  }

  @override
  Widget build(BuildContext context) {
    return const Scaffold(
      body: ListViewTests(),
    );
  }
}

class ListViewTests extends StatefulWidget {
  const ListViewTests({Key? key}) : super(key: key);

  @override
  _ListViewTestsState createState() => _ListViewTestsState();
}
</code>```

What I want it to do is make a list of numbers that generate as the user scrolls. This code does basically nothing.

答:
Try this....</p>
```<code>class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: ListView.separated(
          itemBuilder: (context, index) {
            return ListTile(
              title: Text("Here is Item $index"),
            );
          },
          separatorBuilder: (context, index) => Divider(),
          itemCount: 10),
    );
  }
}
</code>```

Body:
this is the code:

import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      home: ListViewTests(),
    );
  }
}

class _ListViewTestsState extends State<ListViewTests> {
  Widget listViewTest() {
    return ListView.builder(
        padding: const EdgeInsets.all(8),
        itemBuilder: (context, item) {
          item += 1;
          if (item.isOdd) return const Divider();
          return listTileTest(item);
        });
  }

  Widget listTileTest(int item) {
    return const ListTile(
      title: Text('hello'),
    );
  }

  @override
  Widget build(BuildContext context) {
    return const Scaffold(
      body: ListViewTests(),
    );
  }
}

class ListViewTests extends StatefulWidget {
  const ListViewTests({Key? key}) : super(key: key);

  @override
  _ListViewTestsState createState() => _ListViewTestsState();
}

What I want it to do is make a list of numbers that generate as the user scrolls. This code does basically nothing.

Body:
Try this....

class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: ListView.separated(
          itemBuilder: (context, index) {
            return ListTile(
              title: Text("Here is Item $index"),
            );
          },
          separatorBuilder: (context, index) => Divider(),
          itemCount: 10),
    );
  }
}


答:
```<code>import pandas as pd

df = pd.DataFrame(['96.22872386(2015-03-28)', 'None(2014-03-31)', '96.22872386(2015-03-30)', 'None(2017-03-31)'], columns=['col'])

def sort_by_date(df):
    df['date'] = df['col'].str.extract("(\(.*\))", expand=True)
    df = df.sort_values(by='date').drop(columns=['date'])
    return df

sorted_df = sort_by_date(df)
</code>```

Title: Sort date in list of strings in pandas column

Body:
I have data in this format

['96.22872386(2015-03-28)', 'None(2014-03-31)', '96.22872386(2015-03-30)', 'None(2017-03-31)']

['None(2015-10-01)', '1400(2021-11-23)', '1281(2019-07-26)', '690.854(2016-12-13)', '530(2021-08-21)']

Expected result:

['None(2014-03-31)', '96.22872386(2015-03-28)', '96.22872386(2015-03-30)', 'None(2017-03-31)']

['None(2015-10-01)', '690.854(2016-12-13)', '1281(2019-07-26)', '530(2021-08-21)', '1400(2021-11-23)']

Basically I want to sort the column values with respect to date.


问:
Is jQuery image lazy load still solution for optimizing web load speed
For sometime ago, I notice that few big design blog like SmashingMagazine, Noupe and other implement lazy loading on their image. I suppose this helps in optimizing their load time and save server resource.

Then I come to this jQuery lazyload for image, but the plugin is broke and not working for new browser. Would like to know is lazyload still recommended for optimizing website?

答:
That depends on how many images you have and how important they are, there are many solutions to improving your performance ( you can find a presentation about the topic here) and most of them depend on how your website is organized and what are our needs.

So, if your website has a lot of small icons that are reused in many different places ( like amazon does ), you can use CSS sprites, you can use images encoded directly on the HTML, like google has been doing a lot and you can do lazy-load, so it all depends on your situation.

But going back to the lazy load plugin, look for javascript errors or things like that, if it doesn't work you can even build a lazy loader for yourself, should not be that complicated. Here's a hack that could possibly work (I did not run it, so I can't be sure):

```<code><img lazy_loaded_src="/some_image.jpeg" class="lazy_loaded"/>
</code>```

And then in JavaScript:

```<code>jQuery( "img.lazy_loaded" ).each( function () {
  var image = jQuery( this );
  image.attr( "src", image.attr("lazy_loaded_src") );
} );
</code>```

This should have the same lazy-load behavior as long as you do it after the page has loaded.

Body:
That depends on how many images you have and how important they are, there are many solutions to improving your performance ( you can find a presentation about the topic here) and most of them depend on how your website is organized and what are our needs.

So, if your website has a lot of small icons that are reused in many different places ( like amazon does ), you can use CSS sprites, you can use images encoded directly on the HTML, like google has been doing a lot and you can do lazy-load, so it all depends on your situation.

But going back to the lazy load plugin, look for javascript errors or things like that, if it doesn't work you can even build a lazy loader for yourself, should not be that complicated. Here's a hack that could possibly work (I did not run it, so I can't be sure):

<img lazy_loaded_src="/some_image.jpeg" class="lazy_loaded"/>

And then in JavaScript:

jQuery( "img.lazy_loaded" ).each( function () {
  var image = jQuery( this );
  image.attr( "src", image.attr("lazy_loaded_src") );
} );

This should have the same lazy-load behavior as long as you do it after the page has loaded.


问:
How to change the size of Image.network in Flutter
I use Image.network("image_url") to display images from the web in my flutter app,

I tried changing the height of the image as such: Image.network("image_url", height: 45)

But it doesn't work,

If anyone knows how to change the size of an image using this widget, thanks for helping.

答: Actually, I was wrapping my image in container with a fixed height, my bad.</p>


问:
Could not instantiate EventHubSourceProvider for Azure Databricks
Using the steps documented in structured streaming pyspark, I'm unable to create a dataframe in pyspark from the Azure Event Hub I have set up in order to read the stream data.

Error message is:
java.util.ServiceConfigurationError: org.apache.spark.sql.sources.DataSourceRegister: Provider org.apache.spark.sql.eventhubs.EventHubsSourceProvider could not be instantiated

I have installed the Maven libraries (com.microsoft.azure:azure-eventhubs-spark_2.11:2.3.12 is unavailable) but none appear to work:
com.microsoft.azure:azure-eventhubs-spark_2.11:2.3.15
com.microsoft.azure:azure-eventhubs-spark_2.11:2.3.6

As well as ehConf['eventhubs.connectionString'] = sc._jvm.org.apache.spark.eventhubs.EventHubsUtils.encrypt(connectionString) but the error message returned is:

java.lang.NoSuchMethodError: org.apache.spark.internal.Logging.$init$(Lorg/apache/spark/internal/Logging;)V

The connection string is correct as it is also used in a console application that writes to the Azure Event Hub and that works.

Can someone point me in the right direction, please. Code in use is as follows:

```<code>from pyspark.sql.functions import *
from pyspark.sql.types import *

# Event Hub Namespace Name
NAMESPACE_NAME = "*myEventHub*"
KEY_NAME = "*MyPolicyName*"
KEY_VALUE = "*MySharedAccessKey*"

# The connection string to your Event Hubs Namespace
connectionString = "Endpoint=sb://{0}.servicebus.windows.net/;SharedAccessKeyName={1};SharedAccessKey={2};EntityPath=ingestion".format(NAMESPACE_NAME, KEY_NAME, KEY_VALUE)

ehConf = {}
ehConf['eventhubs.connectionString'] = connectionString

# For 2.3.15 version and above, the configuration dictionary requires that connection string be encrypted.
# ehConf['eventhubs.connectionString'] = sc._jvm.org.apache.spark.eventhubs.EventHubsUtils.encrypt(connectionString)

df = spark \
  .readStream \
  .format("eventhubs") \
  .options(**ehConf) \
  .load()
</code>```

答:
check the cluster scala version and the library version
Unisntall the older libraries and install :
com.microsoft.azure:azure-eventhubs-spark_2.12:2.3.17
in the shared workspace(right click and install library) and also in the cluster</p>

Body:
Using the steps documented in structured streaming pyspark, I'm unable to create a dataframe in pyspark from the Azure Event Hub I have set up in order to read the stream data.

Error message is:
java.util.ServiceConfigurationError: org.apache.spark.sql.sources.DataSourceRegister: Provider org.apache.spark.sql.eventhubs.EventHubsSourceProvider could not be instantiated

I have installed the Maven libraries (com.microsoft.azure:azure-eventhubs-spark_2.11:2.3.12 is unavailable) but none appear to work:
com.microsoft.azure:azure-eventhubs-spark_2.11:2.3.15
com.microsoft.azure:azure-eventhubs-spark_2.11:2.3.6

As well as ehConf['eventhubs.connectionString'] = sc._jvm.org.apache.spark.eventhubs.EventHubsUtils.encrypt(connectionString) but the error message returned is:

java.lang.NoSuchMethodError: org.apache.spark.internal.Logging.$init$(Lorg/apache/spark/internal/Logging;)V

The connection string is correct as it is also used in a console application that writes to the Azure Event Hub and that works.

Can someone point me in the right direction, please. Code in use is as follows:

from pyspark.sql.functions import *
from pyspark.sql.types import *

# Event Hub Namespace Name
NAMESPACE_NAME = "*myEventHub*"
KEY_NAME = "*MyPolicyName*"
KEY_VALUE = "*MySharedAccessKey*"

# The connection string to your Event Hubs Namespace
connectionString = "Endpoint=sb://{0}.servicebus.windows.net/;SharedAccessKeyName={1};SharedAccessKey={2};EntityPath=ingestion".format(NAMESPACE_NAME, KEY_NAME, KEY_VALUE)

ehConf = {}
ehConf['eventhubs.connectionString'] = connectionString

# For 2.3.15 version and above, the configuration dictionary requires that connection string be encrypted.
# ehConf['eventhubs.connectionString'] = sc._jvm.org.apache.spark.eventhubs.EventHubsUtils.encrypt(connectionString)

df = spark \
  .readStream \
  .format("eventhubs") \
  .options(**ehConf) \
  .load()


问:
Factor shebangs
According to Hyperpolyglot, Factor should accept shebangs. But on my system Factor can't handle shebangs.

Specs: Factor v0.94, Mac OS X 10.7

```<code>$ cat hello.factor

\#!/usr/bin/env factor

USE: io
IN: hello

: hello ( -- ) "Hello World!" print ;

MAIN: hello

$ ./hello.factor

./hello.factor

1: #!/usr/bin/env factor
                 ^
No word named “#!/usr/bin/env” found in current vocabulary search path
</code>```

答:
Just a guess, but the web page shows a space after the #!:

```<code>#! /usr/bin/env factor
</code>```

If that doesn't work, it's likely that Hyperpolyglot got this wrong (or perhaps it refers to a different version or implementation of factor).

Amusingly, when I try the example on my system (Ubuntu), I get:

```<code>/usr/bin/factor: `./hello.factor' is not a valid positive integer
</code>```

but that's because /usr/bin/factor is the GNU coreutils utility that factors numbers into primes.  8-)}

Title: Factor shebangs

Body:
According to Hyperpolyglot, Factor should accept shebangs. But on my system Factor can't handle shebangs.

Specs: Factor v0.94, Mac OS X 10.7

$ cat hello.factor

\#!/usr/bin/env factor

USE: io
IN: hello

: hello ( -- ) "Hello World!" print ;

MAIN: hello

$ ./hello.factor

./hello.factor

1: #!/usr/bin/env factor
                 ^
No word named “#!/usr/bin/env” found in current vocabulary search path

Body:
Just a guess, but the web page shows a space after the #!:

#! /usr/bin/env factor

If that doesn't work, it's likely that Hyperpolyglot got this wrong (or perhaps it refers to a different version or implementation of factor).

Amusingly, when I try the example on my system (Ubuntu), I get:

/usr/bin/factor: `./hello.factor' is not a valid positive integer

but that's because /usr/bin/factor is the GNU coreutils utility that factors numbers into primes.  8-)}


问:
how to turn speaker on/off programmatically in android Pie and UP
Same as this question and many others from a few years ago:
how to turn speaker on/off programmatically in android 4.0

It seems that Android has changed the way it handles this.

here are the things I tried to make an Outgoing call to have a speakerphone programmatically.  None of these solutions worked for me on Android Pie.
while they seem to work well on Android Nougat and Oreo

Solution 1.

```<code>final static int FOR_MEDIA = 1;
final static int FORCE_NONE = 0;
final static int FORCE_SPEAKER = 1;

Class audioSystemClass = Class.forName("android.media.AudioSystem");
Method setForceUse = audioSystemClass.getMethod("setForceUse", int.class, int.class);
setForceUse.invoke(null, FOR_MEDIA, FORCE_SPEAKER);
</code>```

2.

```<code>AudioManager audioManager = (AudioManager)getApplicationContext().getSystemService(Context.AUDIO_SERVICE);
if (audioManager != null) {
   audioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);
   audioManager.setSpeakerphoneOn(true);
</code>```

3.

```<code>AudioManager audioManager = (AudioManager)getApplicationContext().getSystemService(Context.AUDIO_SERVICE);
if (audioManager != null) {
   audioManager.setMode(AudioManager.MODE_IN_CALL);
   audioManager.setSpeakerphoneOn(true);
</code>```

4.

```<code>Thread thread = new Thread() {
    @Override
    public void run() {
        try {
            while(true) {
                sleep(1000);
                audioManager.setMode(AudioManager.MODE_IN_CALL);
                if (!audioManager.isSpeakerphoneOn())
                    audioManager.setSpeakerphoneOn(true);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
};
thread.start();
</code>```

the app has the following permissions granted among many others:

```<code><uses-permission android:name="android.permission.CALL_PHONE"/>
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS"/>
<uses-permission android:name="android.permission.MODIFY_PHONE_STATE" />
</code>```

I have also tried the following solution only for outgoing calls. and it also didn't work.

```<code>Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.putExtra("speaker", true);
callIntent.setData(Uri.parse("tel:" + number));
context.startActivity(callIntent);
</code>```

答:
in my self managed voice calling app I managed by changing connection service audio route like below beside using audioManager,

```<code> public void setSpeakerphoneOn(final boolean enabled) {
            if (enabled != audioManager.isSpeakerphoneOn()) {
                Log.d(TAG, "setSpeakerphoneOn(): " + enabled);
                audioManager.setSpeakerphoneOn(enabled);
            }
    }
</code>```

and in my connectionservice class,

```<code>   public void speakerOnOff(String uuid,boolean on) {
        Log.d(TAG,"SPEAKER  is" + String.valueOf(on));

        Connection connection = VoipConnectionService.getConnection(uuid);

        if (on) {
            connection.setAudioRoute(CallAudioState.ROUTE_SPEAKER);

        } else {
            connection.setAudioRoute(CallAudioState.ROUTE_EARPIECE);
        }

    }
</code>```

or you can change route according to your audio device for output

```<code>public void speakerOnOff(String uuid,String device) {
     Log.d(TAG,"Device to  route  is" + device);

        Connection connection = VoipConnectionService.getConnection(uuid);

            int state =  CallAudioState.ROUTE_EARPIECE ;
            switch (device){
                case   "SPEAKER_PHONE":
                  state  = CallAudioState.ROUTE_SPEAKER ;
                  break;
                case "WIRED_HEADSET":
                    state  = CallAudioState.ROUTE_WIRED_HEADSET ;
                    break;
                case "EARPIECE" :
                case "NONE" :
                    state  = CallAudioState.ROUTE_EARPIECE ;
                    break;
                case "BLUETOOTH" :
                    state  = CallAudioState.ROUTE_BLUETOOTH ;
                    break;
            }
            connection.setAudioRoute(state);
        }
</code>```

Body:
Same as this question and many others from a few years ago:
how to turn speaker on/off programmatically in android 4.0

It seems that Android has changed the way it handles this.

here are the things I tried to make an Outgoing call to have a speakerphone programmatically.  None of these solutions worked for me on Android Pie.
while they seem to work well on Android Nougat and Oreo

Solution 1.

final static int FOR_MEDIA = 1;
final static int FORCE_NONE = 0;
final static int FORCE_SPEAKER = 1;

Class audioSystemClass = Class.forName("android.media.AudioSystem");
Method setForceUse = audioSystemClass.getMethod("setForceUse", int.class, int.class);
setForceUse.invoke(null, FOR_MEDIA, FORCE_SPEAKER);

2.

AudioManager audioManager = (AudioManager)getApplicationContext().getSystemService(Context.AUDIO_SERVICE);
if (audioManager != null) {
   audioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);
   audioManager.setSpeakerphoneOn(true);

3.

AudioManager audioManager = (AudioManager)getApplicationContext().getSystemService(Context.AUDIO_SERVICE);
if (audioManager != null) {
   audioManager.setMode(AudioManager.MODE_IN_CALL);
   audioManager.setSpeakerphoneOn(true);

4.

Thread thread = new Thread() {
    @Override
    public void run() {
        try {
            while(true) {
                sleep(1000);
                audioManager.setMode(AudioManager.MODE_IN_CALL);
                if (!audioManager.isSpeakerphoneOn())
                    audioManager.setSpeakerphoneOn(true);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
};
thread.start();

the app has the following permissions granted among many others:

<uses-permission android:name="android.permission.CALL_PHONE"/>
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS"/>
<uses-permission android:name="android.permission.MODIFY_PHONE_STATE" />

I have also tried the following solution only for outgoing calls. and it also didn't work.

Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.putExtra("speaker", true);
callIntent.setData(Uri.parse("tel:" + number));
context.startActivity(callIntent);

Body:
in my self managed voice calling app I managed by changing connection service audio route like below beside using audioManager,

 public void setSpeakerphoneOn(final boolean enabled) {
            if (enabled != audioManager.isSpeakerphoneOn()) {
                Log.d(TAG, "setSpeakerphoneOn(): " + enabled);
                audioManager.setSpeakerphoneOn(enabled);
            }
    }

and in my connectionservice class,

   public void speakerOnOff(String uuid,boolean on) {
        Log.d(TAG,"SPEAKER  is" + String.valueOf(on));

        Connection connection = VoipConnectionService.getConnection(uuid);

        if (on) {
            connection.setAudioRoute(CallAudioState.ROUTE_SPEAKER);

        } else {
            connection.setAudioRoute(CallAudioState.ROUTE_EARPIECE);
        }

    }

or you can change route according to your audio device for output

public void speakerOnOff(String uuid,String device) {
     Log.d(TAG,"Device to  route  is" + device);

        Connection connection = VoipConnectionService.getConnection(uuid);

            int state =  CallAudioState.ROUTE_EARPIECE ;
            switch (device){
                case   "SPEAKER_PHONE":
                  state  = CallAudioState.ROUTE_SPEAKER ;
                  break;
                case "WIRED_HEADSET":
                    state  = CallAudioState.ROUTE_WIRED_HEADSET ;
                    break;
                case "EARPIECE" :
                case "NONE" :
                    state  = CallAudioState.ROUTE_EARPIECE ;
                    break;
                case "BLUETOOTH" :
                    state  = CallAudioState.ROUTE_BLUETOOTH ;
                    break;
            }
            connection.setAudioRoute(state);
        }