text:
Q: radio button check doesnt work with jquery hello I am testing radio buttons on my page but it doesn't work correctly else why not go into else if block?
uncheck works but not when you select a radio button
JQuery Code

$("#s1").click(function () {
      if ($("input[name=test]").prop("checked", false)) {
        alert("Lütfen Seçin");
      } else if ($("input[name=test]:checked").val() == "dunya") {
        var x = parseInt($("#testt").text());
        $.ajax({
          url: "test.php",
          data: { get_data: x },
          type: "post",
          success: function (e) {
            alert("Tebrikler Doğru cevapladınız ve +10 puan kazandınız");
            $("#testt").text(e);
          },
        });
      } else {
        alert("Yanlış Cevap Verdiniz Tekrar Kontrol Edin");
      }
    });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="radio" id="a" name="test" value="dunya">
<input type="radio" id="b" name="test" value="print">
<input type="radio" id="c" name="test" value="sayi">
<input type="button" value="Kontrol Et" class="first_btn" id="s1">

A: You are checking for the wrong values in the first if statement, and it will always come true what you should be checking for is the checked radio button of test input, not the props of the whole radio button set:
$("input[name=test]:checked").val()

This is how it should look like:

$("#s1").click(function () {
  if ($("input[name=test]:checked").val() === "sayi") {
    console.log("INSIDE sayi check statement");
    alert("Lütfen Seçin");
  } else if ($("input[name=test]:checked").val() === "dunya") {
    console.log("INSIDE dunya check statement");
    var x = parseInt($("#testt").text());
    $.ajax({
      url: "test.php",
      data: { get_data: x },
      type: "post",
      success: function (e) {
        alert("Tebrikler Doğru cevapladınız ve +10 puan kazandınız");
        $("#testt").text(e);
      },
    });
  } else {
    console.log("INSIDE print check statement");
    alert("Yanlış Cevap Verdiniz Tekrar Kontrol Edin");
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="radio" id="a" name="test" value="dunya">
<input type="radio" id="b" name="test" value="print">
<input type="radio" id="c" name="test" value="sayi">
<input type="button" value="Kontrol Et" class="first_btn" id="s1">

for validation and checking if user selected one input, you can do something like this:

$("#s1").click(function () {
  // Here we are checkinig if any radio button is selected.
  if($("input[name=test]:checked").val() === undefined) {
    alert('PLEASE SELECT A VALUE');
    return ;
  }

  if ($("input[name=test]:checked").val() === "sayi") {
    console.log("INSIDE sayi check statement");
    alert("Lütfen Seçin");
  } else if ($("input[name=test]:checked").val() === "dunya") {
    console.log("INSIDE dunya check statement");
    var x = parseInt($("#testt").text());
    $.ajax({
      url: "test.php",
      data: { get_data: x },
      type: "post",
      success: function (e) {
        alert("Tebrikler Doğru cevapladınız ve +10 puan kazandınız");
        $("#testt").text(e);
      },
    });
  } else {
    console.log("INSIDE print check statement");
    alert("Yanlış Cevap Verdiniz Tekrar Kontrol Edin");
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="radio" id="a" name="test" value="dunya">
<input type="radio" id="b" name="test" value="print">
<input type="radio" id="c" name="test" value="sayi">
<input type="button" value="Kontrol Et" class="first_btn" id="s1">


text:
Q: How can I sort a FirebaseListObservable list in Angularfire2 Angular2? I want to get all users from a Firebase realtime database and sort them by a score property. I've got this to work using the variable
users: FirebaseListObservable<any[]>;
but I get the errors:
Type 'Observable<any[]>' is not assignable to type 'FirebaseListObservable<any[]>'.
Property '_ref' is missing in type 'Observable<any[]>'.

If I change the variable to
users: Observable<any[]>;
then the errors go away, but then I can't use the Angularfire methods like .push() and .update().
My fetching and sorting code (which works) looks like:
this.users = this.af.database.list('/users')
  .map(items => items.sort((a, b) => b.score - a.score));

I would appreciate any advice on how this should be done to avoid the errors, or any preferred way, thank you!

A: You need this example. To watch other opts see Query interface.

this.items = angularFire.database.list('/users', {
  query: {
    orderByChild: 'childPropertyName'
  }
});

export interface Query {
    [key: string]: any;
    orderByKey?: boolean | Observable<boolean>;
    orderByPriority?: boolean | Observable<boolean>;
    orderByChild?: string | Observable<string>;
    orderByValue?: boolean | Observable<boolean>;
    equalTo?: any | Observable<any>;
    startAt?: any | Observable<any>;
    endAt?: any | Observable<any>;
    limitToFirst?: number | Observable<number>;
    limitToLast?: number | Observable<number>;
}

A: The FirebaseListObservable implements lift, so RxJS operators - like map - will return a FirebaseListObservable instance.
It's just that - when using TypeScript - the RxJS operators are statically typed to return Observable, so you have to cast to FirebaseListObservable. (Using RxJS does not have to involve TypeScript and if you look at the guidance for adding operators you will see that types are not mentioned.)
You can verify that a FirebaseListObservable instance is returned by looking for the push and update functions you mentioned in your question:
this.users = this.af.database
  .list('/users')
  .map(items => items.sort((a, b) => b.score - a.score)) as FirebaseListObservable<any[]>;
console.log(this.users.push.toString());
console.log(this.users.update.toString());

Note, however, that this will not work for FirebaseListObservable instances that are created as queries. There is an as-yet-unanswered question regarding such instances.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Foreign Key between Django application In Django, I would like to link foreign key from another app. Bellow is the method for same application, but in my case, they are two different applications on same project.
App Client Model :

name = models.CharField(max_length=64)
App Invoice Model :
client = models.ForeignKey('Client', on_delete=models.CASCADE)
thanks

A: Updated Answer
First you need to import model into application.
from some_other_app.models import client

class Invoice(models.Model):
       user = models.ForeignKey(client,on_delete=models.CASCADE,related_name="userpostchallenge")

You are putting quotes around the model name don't do that.
I misunderstood, now i realized what you want to that so here is updated answer.


text:
Q: setting location.href twice in chrome I'm using
location.href=document.getElementById("link1").href;
location.href=document.getElementById("link2").href;

to run the scripts associated to the links:

The code works fine in Firefox, but in Chrome only the last location.href command (and so only the second piece of javascript code) is executed. How can I force it to execute both the first time and the second one?

A: I had a similar situation. I solved it by using setTimeout function to delay the second one a bit and it works  fine.

A: Try putting your javascript code into functions.
You can then call those functions from the links when they are clicked, as well as anywhere else you need them.
This is a much more stable way of running code rather than with urls.


text:
Q: how to restore deleted records in MDB is it possible to restore deleted records in MDB?

A: I had a near catastrophic loss of data in an MDB file once and I researched this a lot. I ended up purchasing a product named Advanced Access Repair. The free trial allowed me to preview the data available for restore so I was sure that it was worth the $300 price tag.
I tried finding documentation on how to get the data back with code, but that didn't lead anywhere (for me at least).


text:
Q: Phonegap / Cordova include external src without http / https So here it is, I'm starting a Phonegap app and would like to use a given library. In the library code it tries to reach some URL with this form :
//img.site.com/given_img.png

without http or https at the beginning so it will adapt nicely. But when launching the app on my phone I see it tries to reach :
file://img.site.com/given_img.png

Not http or https... But file protocol. Obviously it fails to load...
Anyone knows how to deal with this ?
Thanks ahead !

A: As far as I can tell, after researching this for some time... Currently there is no solution out of the box. You have to check the code with JS and force add the wanted protocol into it before execution. I simply changed the way I wanted to do things and avoided that kind of situation.

A: The idea behind having src="//domain.com/some/pic" is so that the browser will request those assets with the protocol matching your website, meaning, if your website is running on http - it will request the picture over http, vs if your website is running on https it will request the image with https://.
@Jeremy is right, there's no option at the moment.
But you can take the protocol matching your website with var protocol = window.location.protocol and use that in your src={{ protocol + image }}
This is to prevent from writing hard-coded http / https and mix secure with non-secure content in your website which causes errors to jump like "This Page Contains Both Secure and Non-Secure Items"


text:
Q: ValueError: could not convert string to float: '15ML' When I used to run this code I have this error. I have tried to solve it by others method but they are not sophisticated.
The dataset looks like this:
[]
And my code:
from sklearn.ensemble import RandomForestRegressor

regressor = RandomForestRegressor(n_estimators = 10, random_state = 0)
regressor.fit(df_train, y_train)

Error trace:

File "C:\Users\Acer
  15\Anaconda3\lib\site-packages\sklearn\utils\validation.py", line 433,
  in check_array array = np.array(array, dtype=dtype, order=order,
  copy=copy) ValueError: could not convert string to float: '15ML'

A: To replace 15ML to 15 in pandas dataframe,
df['Quantity'].replace('15ML','15')

I have assumed the column name for 15ML column is Quantity. You should replace with the actual column name that you've. If you want to access by location, you can also use
df.ix[:,4].replace('15ML','15')

I have counted including the index column in the image. Actual location may vary according to how you load the data.


text:
Q: How to create a circle icon button in Flutter? How can I create something similar to a FloatingActionButton?

A: RawMaterialButton(
  onPressed: () {},
  constraints: BoxConstraints(),
  elevation: 2.0,
  fillColor: Colors.white,
  child: Icon(
    Icons.pause,
    size: 35.0,
  ),
  padding: EdgeInsets.all(15.0),
  shape: CircleBorder(),
)

note down constraints: BoxConstraints(),  it's for not allowing padding in left.
Happy fluttering!!

A: There actually is an example how to create a circle IconButton similar to the FloatingActionButton.
Ink(
    decoration: const ShapeDecoration(
        color: Colors.lightBlue,
        shape: CircleBorder(),
    ),
    child: IconButton(
        icon: Icon(Icons.home),
        onPressed: () {},
    ),
)

To create a local project with this code sample, run:
flutter create --sample=material.IconButton.2 mysample

A: Using ElevatedButton:
          ElevatedButton(
            onPressed: () {},
            child: Icon(
              Icons.add,
              color: Colors.white,
              size: 60.0,
            ),
            style: ElevatedButton.styleFrom(
                shape: CircleBorder(), primary: Colors.green),
          )

A: You just need to use the shape: CircleBorder()
MaterialButton(
  onPressed: () {},
  color: Colors.blue,
  textColor: Colors.white,
  child: Icon(
    Icons.camera_alt,
    size: 24,
  ),
  padding: EdgeInsets.all(16),
  shape: CircleBorder(),
)

A: 2021
If you need it flat (no elevation) as FlatButton is now deprecated.
TextButton(
      onPressed: (){},
      child: Icon(Icons.arrow_back),
      style: ButtonStyle(
          backgroundColor: MaterialStateProperty.all(Colors.black26),
          shape: MaterialStateProperty.all(const CircleBorder())),
    );

A: I created a version with correct clipping, elevation and border. Feel free to customize it.
Material(
    elevation: 2.0,
    clipBehavior: Clip.hardEdge,
    borderRadius: BorderRadius.circular(50),
    color: Colors.white,
    child: InkWell(
        onTap: () => null,
        child: Container(
            padding: EdgeInsets.all(9.0),
            decoration: BoxDecoration(
                shape: BoxShape.circle,
                border: Border.all(color: Colors.blue, width: 1.4)),
           child: Icon(
                Icons.menu,
                size: 22,
                color: Colors.red,
            ),
        ),
    ),
)),

A: This code will help you to add button without any unwanted padding,
RawMaterialButton(
      elevation: 0.0,
      child: Icon(Icons.add),
      onPressed: (){},
      constraints: BoxConstraints.tightFor(
        width: 56.0,
        height: 56.0,
      ),
      shape: CircleBorder(),
      fillColor: Color(0xFF4C4F5E),
    ),

A: I used this one because I like the customisation of the border-radius and size.
  Material( // pause button (round)
    borderRadius: BorderRadius.circular(50), // change radius size
    color: Colors.blue, //button colour
    child: InkWell(
      splashColor: Colors.blue[900], // inkwell onPress colour
      child: SizedBox(
        width: 35,height: 35, //customisable size of 'button'
        child: Icon(Icons.pause,color: Colors.white,size: 16,),
      ),
      onTap: () {}, // or use onPressed: () {}
    ),
  ),

  Material( // eye button (customised radius)
    borderRadius: BorderRadius.only(
        topRight: Radius.circular(10.0),
        bottomLeft: Radius.circular(50.0),),
    color: Colors.blue,
    child: InkWell(
      splashColor: Colors.blue[900], // inkwell onPress colour
      child: SizedBox(
        width: 40, height: 40, //customisable size of 'button'
        child: Icon(Icons.remove_red_eye,color: Colors.white,size: 16,),),
      onTap: () {}, // or use onPressed: () {}
    ),
  ),

A: There are many ways to create the circle icon button in Flutter. Each of the examples below will use a different method.

*

*Using ElevatedButton + Icon (recommended)

*Using MaterialButton

*ClipOval + Material + InkWell + Padding + Icon

*IconButton + CircleAvatar

*Ink + IconButton

Using ElevatedButton + Icon
ElevatedButton(
      style: ElevatedButton.styleFrom(
          shape: const CircleBorder(),
          padding: const EdgeInsets.all(30)
      ),
      child: const Icon(
        Icons.add,
        size: 50,
      ),
      onPressed: () {},

),
Output:

Using MaterialButton
MaterialButton(
    shape: const CircleBorder(),
    color: Colors.red,
    padding: const EdgeInsets.all(20),
    onPressed: () {},
    child: const Icon(
      Icons.star,
      size: 50,
      color: Colors.yellow,
    ),

)
Output:

ClipOval + Material + InkWell + Padding + Icon
ClipOval(
    child: Material(
      color: Colors.blue,
      child: InkWell(
        onTap: () {},
        child: const Padding(
          padding: EdgeInsets.all(20),
          child: Icon(
            Icons.plus_one,
            size: 50,
            color: Colors.white,
          ),
        ),
      ),
    ),

)
Output:

IconButton + CircleAvatar
CircleAvatar(
      radius: 50,
      backgroundColor: Colors.amber,
      child: IconButton(
          color: Colors.black,
          padding: const EdgeInsets.all(20),
          iconSize: 50,
          icon: const Icon(Icons.shop),
          onPressed: () {
          // do something
          }),

),
Output:

Ink + IconButton
Ink(
    decoration:
        const ShapeDecoration(
            shape: CircleBorder(),
            color: Colors.purple
        ),
    child: IconButton(
      icon: const Icon(Icons.arrow_back),
      iconSize: 30,
      color: Colors.white,
      onPressed: () {},
    ),

)
Output:

A: You can use InkWell to do that:

A rectangular area of a Material that responds to touch.

Below example demonstrate how to use InkWell. Notice: you don't need StatefulWidget to do that. I used it to change the state of the count.
Example:
import 'package:flutter/material.dart';

class SettingPage extends StatefulWidget {
  @override
  _SettingPageState createState() => new _SettingPageState();
}

class _SettingPageState extends State<SettingPage> {
  int _count = 0;
  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      body: new Center(
        child: new InkWell(// this is the one you are looking for..........
        onTap: () => setState(() => _count++),
        child: new Container(
          //width: 50.0,
          //height: 50.0,
          padding: const EdgeInsets.all(20.0),//I used some padding without fixed width and height
          decoration: new BoxDecoration(
            shape: BoxShape.circle,// You can use like this way or like the below line
            //borderRadius: new BorderRadius.circular(30.0),
            color: Colors.green,
          ),
          child: new Text(_count.toString(), style: new TextStyle(color: Colors.white, fontSize: 50.0)),// You can add a Icon instead of text also, like below.
          //child: new Icon(Icons.arrow_forward, size: 50.0, color: Colors.black38)),
        ),//............
      ),
      ),
    );
  }
}

If you want to get benefit of splashColor, highlightColor, wrap InkWell widget using a Material widget with material type circle. And then remove decoration in Container widget.
Outcome:

A: My contribution:
import 'package:flutter/material.dart';

///
/// Create a circle button with an icon.
///
/// The [icon] argument must not be null.
///
class CircleButton extends StatelessWidget {
  const CircleButton({
    Key key,
    @required this.icon,
    this.padding = const EdgeInsets.all(8.0),
    this.color,
    this.onPressed,
    this.splashColor,
  })  : assert(icon != null),
        super(key: key);

  /// The [Icon] contained ny the circle button.
  final Icon icon;

  /// Empty space to inscribe inside the circle button. The [icon] is
  /// placed inside this padding.
  final EdgeInsetsGeometry padding;

  /// The color to fill in the background of the circle button.
  ///
  /// The [color] is drawn under the [icon].
  final Color color;

  /// The callback that is called when the button is tapped or otherwise activated.
  ///
  /// If this callback is null, then the button will be disabled.
  final void Function() onPressed;

  /// The splash color of the button's [InkWell].
  ///
  /// The ink splash indicates that the button has been touched. It
  /// appears on top of the button's child and spreads in an expanding
  /// circle beginning where the touch occurred.
  ///
  /// The default splash color is the current theme's splash color,
  /// [ThemeData.splashColor].
  final Color splashColor;

  @override
  Widget build(BuildContext context) {
    final ThemeData theme = Theme.of(context);

    return ClipOval(
      child: Material(
        type: MaterialType.button,
        color: color ?? theme.buttonColor,
        child: InkWell(
          splashColor: splashColor ?? theme.splashColor,
          child: Padding(
            padding: padding,
            child: icon,
          ),
          onTap: onPressed,
        ),
      ),
    );
  }
}

A: RawMaterialButton is better suited I think.
RawMaterialButton(
  onPressed: () {},
  elevation: 2.0,
  fillColor: Colors.white,
  child: Icon(
    Icons.pause,
    size: 35.0,
  ),
  padding: EdgeInsets.all(15.0),
  shape: CircleBorder(),
)

A: If you need a background image, you can use CircleAvatar with IconButton. Set the backgroundImage property.
CircleAvatar(
  backgroundImage: NetworkImage(userAvatarUrl),
)

Example with button:
        CircleAvatar(
          backgroundColor: Colors.blue,
          radius: 20,
          child: IconButton(
            padding: EdgeInsets.zero,
            icon: Icon(Icons.add),
            color: Colors.white,
            onPressed: () {},
          ),
        ),

A: Update (use new ElevatedButton)

*

*ElevatedButton (with less customizations)
ElevatedButton(
  onPressed: () {},
  child: Icon(Icons.menu, color: Colors.white),
  style: ElevatedButton.styleFrom(
    shape: CircleBorder(),
    padding: EdgeInsets.all(20),
    backgroundColor: Colors.blue, // <-- Button color
    foregroundColor: Colors.red, // <-- Splash color
  ),
)

*ElevatedButton (with more customizations)
ElevatedButton(
  onPressed: () {},
  child: Icon(Icons.menu),
  style: ButtonStyle(
    shape: MaterialStateProperty.all(CircleBorder()),
    padding: MaterialStateProperty.all(EdgeInsets.all(20)),
    backgroundColor: MaterialStateProperty.all(Colors.blue), // <-- Button color
    overlayColor: MaterialStateProperty.resolveWith<Color?>((states) {
      if (states.contains(MaterialState.pressed)) return Colors.red; // <-- Splash color
    }),
  ),
)

*Using InkWell
ClipOval(
  child: Material(
    color: Colors.blue, // Button color
    child: InkWell(
      splashColor: Colors.red, // Splash color
      onTap: () {},
      child: SizedBox(width: 56, height: 56, child: Icon(Icons.menu)),
    ),
  ),
)

Output (same for the last two):

A: Not Material solution:
final double floatingButtonSize = 60;
final IconData floatingButtonIcon;

TouchableOpacity(
  onTap: () {
     /// Do something...
  },
  activeOpacity: 0.7,
  child: Container(
    height: floatingButtonSize,
    width: floatingButtonSize,
    decoration: BoxDecoration(
      borderRadius: BorderRadius.circular(floatingButtonSize / 2),
      color: Theme.of(context).primaryColor,
      boxShadow: [
        BoxShadow(
          blurRadius: 25,
          color: Colors.black.withOpacity(0.2),
          offset: Offset(0, 10),
        )
      ],
    ),
    child: Icon(
      floatingButtonIcon ?? Icons.add,
      color: Colors.white,
    ),
  ),
)

You can use GestureDetector instead of TouchableOpacity library.

A: You can easily do the following:
FlatButton(
      onPressed: () {

       },
      child: new Icon(
        Icons.arrow_forward,
        color: Colors.white,
        size: 20.0,
      ),
      shape: new CircleBorder(),
      color: Colors.black12,
    )

The result is

A: RaisedButton is depricated,
now you can create this by ElevatedButton.
ElevatedButton(
      onPressed: () {},
      child: Icon(Icons.add, color: Colors.white),
      style: ElevatedButton.styleFrom(
        shape: CircleBorder(),
        padding: EdgeInsets.all(20),
        primary: Colors.blue,
        onPrimary: Colors.black,
      ),
    )

A: You can also use a RaisedButton with an image inside (for example for social login) like this (sizedbox with fittebox is needed to contraint the image on the specified size):
FittedBox(
    fit: BoxFit.scaleDown,
    child: SizedBox(
        height: 60,
        width: 60,
        child: RaisedButton(
             child: Image.asset(
                 'assets/images/google_logo.png'),
                 shape: StadiumBorder(),
                 color: Colors.white,
                     onPressed: () {},
                 ),
             ),
         ),

A: ClipOval(
      child: MaterialButton(
      color: Colors.purple,
      padding: EdgeInsets.all(25.0),
      onPressed: () {},
      shape: RoundedRectangleBorder(
      borderRadius: BorderRadius.circular(30.0)),
            child: Text(
                      '1',
                      style: TextStyle(fontSize: 30.0),
                    ),
                  ),
                ),

A: Below code will create a Circle of radius 25 and will have white color add icon in it. and If user also want to have click method that can be simply achieved by wrapping a Container widget into GestureDetector() or InkWell().
Container(
height: 50,
width: 50,
decoration: BoxDecoration(
color: Colors.blue,
borderRadius: BorderRadius.circular(50 / 2),
),
child: Center(
child: Icon(
Icons.add,
color: Colors.white,
),
),
),

A: Just use the circle shape

MaterialButton(
  onPressed: () {
print("Circle button pressed");
  },
  color: Colors.blue,
  textColor: Colors.white,
  child: Icon(
    Icons.favorite,
    size: 20,
  ),
  padding: EdgeInsets.all(16),
//use this class Circleborder() for circle shape.
  shape: const CircleBorder(),
)

A: Material 3 / Flutter 3.7.0-
Here is a CircleIconButton widget supporting standard, filled, filled tonal and outlined types from Material 3, as described in https://m3.material.io/components/icon-buttons/overview. The widget supports also toggle feature and enabled/disabled states.
import 'package:flutter/material.dart';

enum CircleIconButtonStyle {
  standard,
  filled,
  filledTonal,
  outlined,
}

class CircleIconButton extends StatelessWidget {
  const CircleIconButton({
    super.key,
    required this.icon,
    this.circleIconButtonStyle = CircleIconButtonStyle.filled,
    required this.onPressed,
    this.isSelected,
    this.selectedIcon,
  });

  final IconData icon;
  final CircleIconButtonStyle circleIconButtonStyle;
  final VoidCallback? onPressed;

  /// For toggle buttons
  final bool? isSelected;
  final Widget? selectedIcon;

  @override
  Widget build(BuildContext context) {
    final ColorScheme colors = Theme.of(context).colorScheme;
    return IconButton(
      onPressed: onPressed,
      icon: Icon(icon),
      isSelected: isSelected,
      selectedIcon: selectedIcon,
      style: _CircleIconButtonStyleProvider.getStyle(
          circleIconButtonStyle: circleIconButtonStyle,
          isEnabled: onPressed != null,
          isSelected: isSelected == true,
          colors: colors),
    );
  }
}

// adapted from samples at https://api.flutter.dev/flutter/material/IconButton-class.html
class _CircleIconButtonStyleProvider {
  static ButtonStyle? getStyle({
    required CircleIconButtonStyle circleIconButtonStyle,
    required bool isEnabled,
    required bool isSelected,
    required ColorScheme colors,
  }) {
    switch (circleIconButtonStyle) {
      case CircleIconButtonStyle.standard:
        return null;
      case CircleIconButtonStyle.filled:
        return isEnabled
            ? _enabledFilledButtonStyle(isSelected, colors)
            : _disabledFilledButtonStyle(isSelected, colors);
      case CircleIconButtonStyle.filledTonal:
        return isEnabled
            ? _enabledFilledTonalButtonStyle(isSelected, colors)
            : _disabledFilledTonalButtonStyle(isSelected, colors);
      case CircleIconButtonStyle.outlined:
        return isEnabled
            ? _enabledOutlinedButtonStyle(isSelected, colors)
            : _disabledOutlinedButtonStyle(isSelected, colors);
    }
  }

  static ButtonStyle _enabledFilledButtonStyle(
    bool selected,
    ColorScheme colors,
  ) {
    return IconButton.styleFrom(
      foregroundColor: selected ? colors.onPrimary : colors.primary,
      backgroundColor: selected ? colors.primary : colors.surfaceVariant,
      disabledForegroundColor: colors.onSurface.withOpacity(0.38),
      disabledBackgroundColor: colors.onSurface.withOpacity(0.12),
      hoverColor: selected
          ? colors.onPrimary.withOpacity(0.08)
          : colors.primary.withOpacity(0.08),
      focusColor: selected
          ? colors.onPrimary.withOpacity(0.12)
          : colors.primary.withOpacity(0.12),
      highlightColor: selected
          ? colors.onPrimary.withOpacity(0.12)
          : colors.primary.withOpacity(0.12),
    );
  }

  static ButtonStyle _disabledFilledButtonStyle(
    bool selected,
    ColorScheme colors,
  ) {
    return IconButton.styleFrom(
      disabledForegroundColor: colors.onSurface.withOpacity(0.38),
      disabledBackgroundColor: colors.onSurface.withOpacity(0.12),
    );
  }

  static ButtonStyle _enabledFilledTonalButtonStyle(
    bool selected,
    ColorScheme colors,
  ) {
    return IconButton.styleFrom(
      foregroundColor:
          selected ? colors.onSecondaryContainer : colors.onSurfaceVariant,
      backgroundColor:
          selected ? colors.secondaryContainer : colors.surfaceVariant,
      hoverColor: selected
          ? colors.onSecondaryContainer.withOpacity(0.08)
          : colors.onSurfaceVariant.withOpacity(0.08),
      focusColor: selected
          ? colors.onSecondaryContainer.withOpacity(0.12)
          : colors.onSurfaceVariant.withOpacity(0.12),
      highlightColor: selected
          ? colors.onSecondaryContainer.withOpacity(0.12)
          : colors.onSurfaceVariant.withOpacity(0.12),
    );
  }

  static ButtonStyle _disabledFilledTonalButtonStyle(
    bool selected,
    ColorScheme colors,
  ) {
    return IconButton.styleFrom(
      disabledForegroundColor: colors.onSurface.withOpacity(0.38),
      disabledBackgroundColor: colors.onSurface.withOpacity(0.12),
    );
  }

  static ButtonStyle _enabledOutlinedButtonStyle(
    bool selected,
    ColorScheme colors,
  ) {
    return IconButton.styleFrom(
      backgroundColor: selected ? colors.inverseSurface : null,
      hoverColor: selected
          ? colors.onInverseSurface.withOpacity(0.08)
          : colors.onSurfaceVariant.withOpacity(0.08),
      focusColor: selected
          ? colors.onInverseSurface.withOpacity(0.12)
          : colors.onSurfaceVariant.withOpacity(0.12),
      highlightColor: selected
          ? colors.onInverseSurface.withOpacity(0.12)
          : colors.onSurface.withOpacity(0.12),
      side: BorderSide(color: colors.outline),
    ).copyWith(
      foregroundColor:
          MaterialStateProperty.resolveWith((Set<MaterialState> states) {
        if (states.contains(MaterialState.selected)) {
          return colors.onInverseSurface;
        }
        if (states.contains(MaterialState.pressed)) {
          return colors.onSurface;
        }
        return null;
      }),
    );
  }

  static ButtonStyle _disabledOutlinedButtonStyle(
    bool selected,
    ColorScheme colors,
  ) {
    return IconButton.styleFrom(
      disabledForegroundColor: colors.onSurface.withOpacity(0.38),
      disabledBackgroundColor:
          selected ? colors.onSurface.withOpacity(0.12) : null,
      side:
          selected ? null : BorderSide(color: colors.outline.withOpacity(0.12)),
    );
  }
}

A: Container(
  width: 70.w,
  height: 70.h,
  alignment: AlignmentDirectional.topCenter,
  child: MaterialButton(
    onPressed: () {},
    color: Color(0xff022C43),
    textColor: Colors.white,
    child: Icon(
      Icons.arrow_forward,
      size: 24,
    ),
    padding: EdgeInsets.all(16),
    shape: CircleBorder(),
  )
)

A: Try out this Card
Card(
    elevation: 10,
    shape: RoundedRectangleBorder(
      borderRadius: BorderRadius.circular(25.0), // half of height and width of Image
      ),
    child: Image.asset(
      "assets/images/home.png",
      width: 50,
      height: 50,
    ),
  )

A: Card(
        elevation: 4.0,
        margin: EdgeInsets.zero,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(150),
        ),
        child: InkWell(
          onTap: (){},
          child: Container(
              width: 40,
              height: 40,
              padding: const EdgeInsets.all(3.0),
              decoration: const BoxDecoration(
                  shape: BoxShape.circle, color: backGroundColor),
              child: Image.asset(imageUrl)),
        )),


text:
Q: Prevent git from automatically generating user email if missing Is there a way to globally configure git to not automatically generate user's email, if none is set and abort the commit instead?
$ git commit -m "test"
[master (root-commit) 71c3e2e] test
Committer: unknown <my.user@my.very.own.hostname>
Your name and email address were configured automatically based
on your username and hostname. Please check that they are accurate.

This can cause serious privacy leaks if the committer is not careful enough to check git warnings.

A: Set git config --global user.useConfigOnly true

user.useConfigOnly
Instruct Git to avoid trying to guess defaults for user.email and user.name, and instead retrieve the values only from the
  configuration. For example, if you have multiple email addresses and
  would like to use a different one for each repository, then with this
  configuration option set to true in the global config along with a
  name, Git will prompt you to set up an email before making new commits
  in a newly cloned repository. Defaults to false.

A: This can be done with git pre-commit hook, following the suggestion by @cupcake.

*

*Create file named pre-commit like so:
#!/bin/sh

git config user.name >/dev/null 2>&1

if [[ $? != 0 ]]; then
    echo "Error: user.name is undefined. Use 'git config user.name \"Your Name\"' to set it."
    exit 1
fi

git config user.email >/dev/null 2>&1

if [[ $? != 0 ]]; then
    echo "Error: user.email is undefined. Use 'git config user.email you@example.com' to set it."
    exit 1
fi

*If necessary, make it executable with chmod +x pre-commit

*Throw this file to global git hook templates:

*

*On *nix systems this is located at
 /usr/share/git-core/templates/hooks

*On Windows this can be typically found in
 %ProgramFiles%\Git\share\git-core\templates\hooks

*Re-initialize your existing git repos with git init.


text:
Q: Calabash-android - how to delay the start of the test scenarios to wait for the app to start? Once I follow the correct procedure for installing the calabash framework on the App under test, and after writing the test scenarios with the relevant definition step, if I run via console:
$ calabash-android console C:\..\app-unaligned.apk
$ start_test_server_in_background

The App starts without problems on my device (connected to the pc).
Instead when I run in command prompt:
$ calabash-android run C:\..\app-unaligned.apk

The App starts after about 40 seconds, which it is obviously too, because in this time range the first two test scenarios have already left, without being able to actually starts in the App. When then the App start (after about 40 seconds) the remaining scenarios (not yet started) are properly executed on App. So the first scenarios fails and the remaining pass.
    C:\..\MyApp>calabash-android run C:\..\app-unaligned.apk
    *** WARNING: You must use ANSICON 1.31 or higher (https://github.com/adoxa/ansicon/) to get coloured output on Windows
    Feature: Testing MyApp

    6278 KB/s (585926 bytes in 0.091s)
    6759 KB/s (5721923 bytes in 0.826s)
      Background:                                    # features/my_first.feature:3
      App did not start (RuntimeError)
      ./features/support/app_life_cycle_hooks.rb:5:in `Before'
        Given I wait                                 # calabash-android-0.7.3/lib/calabash-android/steps/progress_steps.rb:5
        Then I press on the tutorial screen          # features/step_definitions/calabash_steps.rb:3
    .
    .
    Scenario: Test One      # features/my_first.feature:14
    .
    .
    Scenario: Test two    # features/my_first.feature:25
    .
    .
    Scenario: Test three     # features/my_first.feature:60
    .
    .
    Failing Scenarios:
    cucumber features/my_first.feature:14 # Scenario: Test one
    cucumber features/my_first.feature:25 # Scenario: Test two

    3 scenarios (2 failed, 1 passed)
    56 steps (44 skipped, 12 passed)
    1m12.056s

So I wonder if I can delay the start of the test scenarios until real start of the App on mobile, So that all the test scenarios are effectively executed.

A: Use this empty step.
feature:
Given App is running

step_definition:
Given(/^App is running$/) do
end

For me this work.


text:
Q: Magento 2.2.7 error when using bulk attribute update when item is enabled When trying to use the bulk update attributes I get the following error:

Exception message: Required parameter 'theme_dir' was not passed

I've been chasing this error for the last 2 weeks.  At one point the function worked fine but now it doesn't.
I finally found out when you disable the item you can use the bulk attribute update and it works fine.
Any ideas what might be causing this?
Rich


text:
Q: how to extract html code for website using iframe and silverlight I need to load a specific webpage from a site that has multiple images on the site. I need to extract these images but I can't do this manually because the names of each image have no pattern and there will be hundreds of sites. I have a silverlight application to load the webpage in an iframe and I intended on extracting the html for this webpage and then retrieving the image source for each image from the extracted code and then populating a listbox.
I can load the web page in iframe with no problem, but I don't know how to retrieve the html code for the webpage.
public Page()
    {
        InitializeComponent();

        System.Windows.Browser.HtmlElement myFrame = System.Windows.Browser.HtmlPage.Document.GetElementById("ifHtmlContent");
        if (myFrame != null)
        {
            myFrame.SetStyleAttribute("width", "1024");
            myFrame.SetStyleAttribute("height", "768");
            myFrame.SetAttribute("src", txtURI.Text);
            myFrame.SetStyleAttribute("left", "0");
            myFrame.SetStyleAttribute("top", "50");
            myFrame.SetStyleAttribute("visibility", "visible");
        }
    }

    private void UserControl_Loaded(object sender, RoutedEventArgs e)
    {
        this.Button_Click(sender, e);
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        System.Windows.Browser.HtmlElement myFrame = System.Windows.Browser.HtmlPage.Document.GetElementById("ifHtmlContent");
        if (myFrame != null) myFrame.SetAttribute("src", txtURI.Text);
    }

    private void txtURI_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.Key == Key.Enter)
            this.Button_Click(sender, e);
    }

A: The following article may offer some help:
http://jesseliberty.com/2010/05/03/screen-scraping-when-all-you-have-is-a-hammer/


text:
Q: Only administrator allow to access wp-admin and login? I would like to do that only administrator(role) allow to login with wp-admin not any other role, other uses like(editor,author) are login from front end and it's working fine but i would like only administrator can login through  wp-admin.
I have used ultimate member plug in for front end login.
Ultimate Plugin link
also i have used below code for access wp-admin only for administrator(role) but it's not working.
<?php
function restrict_admin(){
//if not administrator, kill WordPress execution and provide a message
   if( !current_user_can('administrator') ) {
        wp_die( __('You are not allowed to access this part of the site') );
    }
}
add_action( 'admin_init', 'restrict_admin', 1 );
?>

A: Thank you guys for your help, I am answering my own question hope this will help others too.
I have referred this link https://developer.wordpress.org/reference/functions/wp_authenticate/
I have solved this with hook wp_authenticate
 add_action( 'wp_authenticate' , 'check_custom_authentication' );
  function check_custom_authentication ( $username ) {

    $username;
     $user = new WP_User($username);
     $user_role_member=$user->roles[0];

    if($user_role_member == 'author' || $user_role_member == 'editor'){
        session_destroy();
        wp_redirect( home_url() );
        exit;
    }

 }

A: add_action( 'admin_init', 'redirect_none_admin' );

function redirect_none_admin(){

 if(is_admin() && current_user_can(activate_plugins)){
    //...
 }else{
     wp_redirect(home_url());
 }
}

i tested this one and it worked i think it is simple and easy
you can find Roles and Capabilities here

A: If anyone will need the same here is code that allows only administrators, authors and editors to login using /wp-login.php
//------------- This website is read only - so only staff can log in  -------------
add_filter( 'authenticate', 'myplugin_auth_signon', 30, 3 );
function myplugin_auth_signon( $user, $username, $password ) {
    $user_role_member=$user->roles[0];
    if(!in_array($user_role_member,array('administrator','author','editor'))){
         wp_logout();
         return new WP_Error( 'broke', __( "This website is read only for regular users", "your_wp_domain_name" ) );
        exit;
    }else{
        return $user;
    }
}
//------------- this website is read only - so staff can log in  ------------------

You can add\remove roles in the array above array('administrator','author','editor')

A: Try this
add_action( 'admin_init', 'redirect_non_admin_users' );
/**
 * Redirect non-admin users to home page
 *
 * This function is attached to the 'admin_init' action hook.
 */
function redirect_non_admin_users() {
    if ( is_admin() !== false) {
        wp_redirect( home_url() );
        exit;
    }
}


text:
Q: Minimum edge in a set of edges which connects a graph The following is an example from my graph theory and algorithm course:
Let A be a minimal subset of edges of a weighted undirected graph G (distinct weight), such that if we remove A from G then G becomes disconnected.  The lightest edge in A must be in any MST.
Why this is a correct fact? I couldn't understand it.

A: According to the definition of minimal edge cut:

A minimal edge cut is an edge cut such that if any edge is put back in the graph, the graph will be reconnected.

In the following figure:

The set, A = {a, b, c, d} is a minimal edge cut.
If A is removed from G, the graph becomes disconnected.
Now, the property: "lightest edge in A must be in any MST" can be explained by the Cut Property:

Therefore the statement is true, because,
The lightest edge of the set A  = e = min(a, min(b, min(c,d))) will be the part of MST.

A: Here's how I think of it.  It's given that A is a set of edges that when removed disconnects G.  We could say that A connects (at least) two subsets of nodes in G, G1 and G2.  There can be no edges linking G1 and G2 that don't go through A, because otherwise the connection of G1 and G2 would not depend on A.  Also denote m as the minimum edge within A (not necessarily the minimum of G, although it could be!).
So the question is, can you make the minimum path from G1 to G2 through A without taking its minimum edge m?  Well think of another subgraph which is all of the nodes which contain an edge within A.  So at least one node from G1 and one node from G2 (such that they are connected through A).  The MST of this subgraph must include m, because a MST must include the smallest edge weight.  And the MST of G must include the MST of A, else we would be getting from G1 to G2 in a suboptimal way.


text:
Q: adding a conditions in for loop I have the following two functions in VBA. And my excel would look like this.
OddsId  Agt      Ma   Sma     Result
1       Agt1    Ma1   Sma1     x

My intentions is to calculate the value of x. And i want to add a condition like, User can provide only one value at a time among Agt, ma and Sma. If any of these 2 fields are non-zero then my result should read "Error". I am not sure where to add this condition in these functions.
I am also not pretty sure what would If NOT function would actually return !!
Kindly help me on this.
Function fcComm1(oddsId As Integer, agt As String, ma As String, sma As String, fcOption1 As Integer)
If Not setFcType(agt, ma, sma) Then
    fcComm1 = "Invalid2"
    Return
End If
For i = 1 To bets.ListRows.Count
    currOddsId = bets.ListColumns("OddsId").DataBodyRange(i)
    currTransId = bets.ListColumns("TransId").DataBodyRange(i)
    currPlayer = bets.ListColumns("Account").DataBodyRange(i)

    If (currOddsId = oddsId) Then
        If FcType = "agt" Then
            currAgt = Application.WorksheetFunction.VLookup(currPlayer, accounts.DataBodyRange, 9, False)
            If (agt <> currAgt) Then
                fcComm1 = ""
                GoTo NextIteration
            End If
        ElseIf FcType = "ma" Then
            currMa = Application.WorksheetFunction.VLookup(currPlayer, accounts.DataBodyRange, 10, False)
            If (ma <> currMa) Then
            fcComm1 = ""
                GoTo NextIteration
            End If
        ElseIf FcType = "sma" Then
            currSma = Application.WorksheetFunction.VLookup(currPlayer, accounts.DataBodyRange, 11, False)
            If (sma <> currSma) Then
            fcComm1 = ""
                GoTo NextIteration
            End If
        End If

        exchangeRate = Application.WorksheetFunction.VLookup(currPlayer, accounts.DataBodyRange, 4, False)
        blindRisk = Application.WorksheetFunction.VLookup(currPlayer, accounts.DataBodyRange, 6, False) / 100#
        fcComm1 = fcComm1 + ForecastBet(currTransId, exchangeRate, blindRisk)

NextIteration:

    End If
Next
End Function

Function setFcType(agt As String, ma As String, sma As String)
setFcType = True

If Len(agt) + Len(ma) + Len(sma) = 0 Then
    FcType = "company"
ElseIf agt <> "" And agt <> "0" Then
    FcType = "agt"
ElseIf ma <> "" And ma <> "0" Then
    FcType = "ma"
ElseIf sma <> "" And sma <> "0" Then
    FcType = "sma"
End If

End Function

A: Here you have a corrected version of your setFcType function returning false in case of having more than one variable different than "".
Function setFcType(agt As String, ma As String, sma As String)
setFcType = True

If ((Len(Trim(agt)) > 0 And (Len(Trim(ma)) > 0 Or Len(Trim(sma)) > 0)) Or (Len(Trim(ma)) > 0 And (Len(Trim(agt)) > 0 Or Len(Trim(sma)) > 0))) Then
    setFcType = False
    Exit Function
End If

If Len(agt) + Len(ma) + Len(sma) = 0 Then
    FcType = "company"
ElseIf agt <> "" And agt <> "0" Then
    FcType = "agt"
ElseIf ma <> "" And ma <> "0" Then
    FcType = "ma"
ElseIf sma <> "" And sma <> "0" Then
    FcType = "sma"
End If

End Function


text:
Q: How do you sync a ListView and List model using MVVM? I am attempting to use the MVVM pattern to display a List of objects that can be updated in the UI.  I would also like some basic operations like Add/Remove.  Right now I have a simple Customer model that is just a first and last name.  I have the DataContext assigned to the ViewModel.  In the ViewModel class I have the "model" (which is just a List of Customers) that will be injected at a later point.   To keep the underlying List model up to date, I wrap the List with an ObservableCollection each time it's accessed.  In doing this, it doesn't seem to keep the SelectedValue active because when you remove the SelectedValue, it sets it to null and clears out the selection in the ListView.  This means that I would need some manual tracking (which I am hoping to avoid).
I have tried to keep an ObservableCollection as a member variable to the ViewModel class, but this only copies the underlying list of data and doesn't keep it synced if you add/remove objects from it.
I also want to avoid using ObservableCollection as the model, since this seems more geared toward ViewModel data binding support (reference; see Using it in the model).
Has anyone done this before and found a good way to keep the List model in sync but also data bind to the ListView using ObservableCollection?
MainWindow.xaml
<Window x:Class="TestCollectionAndSelectedItem.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:TestCollectionAndSelectedItem"
        Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <local:IndexConverter x:Key="IndexConverter" />
    </Window.Resources>
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="35*" />
            <RowDefinition Height="276*" />
        </Grid.RowDefinitions>
        <Button Content="Add" Command="{Binding Path=AddCustomer}"  Width="95" Margin="22,11,0,231" Grid.Row="1" HorizontalAlignment="Left" />
        <Label Content="First" Height="26" Width="80" HorizontalAlignment="Left" Margin="263,95,0,155" Grid.Row="1" />
        <TextBox Text="{Binding SelectedCustomer.FirstName, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Height="31" Width="133" IsEnabled="True" Margin="345,93,25,152" Name="textBox1" Grid.Row="1" />
        <Label Content="Last" Height="26" Width="80" HorizontalAlignment="Left" Margin="263,139,0,111" Grid.Row="1" />
        <TextBox Text="{Binding SelectedCustomer.LastName, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Width="133" Height="31" IsEnabled="True" Margin="345,137,25,108" Name="textBox2" Grid.Row="1" />
        <ListView SelectionMode="Single" ItemsSource="{Binding Customers}" SelectedValue="{Binding SelectedCustomer, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Name="listviewNames" Margin="22,56,258,77" Grid.Row="1">
            <ListView.View>
                <GridView>
                    <GridView.Columns>
                        <GridViewColumn Header="Number"
                            DisplayMemberBinding="{Binding RelativeSource={RelativeSource FindAncestor,
                            AncestorType={x:Type ListViewItem}},
                            Converter={StaticResource IndexConverter}}" />
                        <GridViewColumn Header="Last" DisplayMemberBinding="{Binding Path=LastName}" Width="80"/>
                        <GridViewColumn Header="First" DisplayMemberBinding="{Binding Path=FirstName}" Width="80"/>
                    </GridView.Columns>
                </GridView>
            </ListView.View>
        </ListView>
        <Button Command="{Binding Path=RemoveCustomer}" CommandParameter="{Binding ElementName=listviewNames, Path=SelectedIndex}" Content="Remove" HorizontalAlignment="Left" Margin="150,11,0,231" Width="95" Grid.Row="1" />
    </Grid>
</Window>

MainWindow.xaml.cs
public partial class MainWindow : Window
{
   // wont go here, just example
   List<Customer> customers = new List<Customer>() {
      new Customer() { LastName = "Anderson", FirstName = "John" },
      new Customer() { LastName = "NoName", FirstName = "" } };

   public MainWindow()
   {
      InitializeComponent();
      DataContext = new ViewModel(customers);
   }
}

ViewModel.cs
public class ViewModel : INotifyPropertyChanged
{
   public event PropertyChangedEventHandler PropertyChanged;

   private List<Customer> _customersModel;
   private Customer _selectedCustomer;

   public DelegateCommand<object> AddCustomer { get; private set; }
   public DelegateCommand<int> RemoveCustomer { get; private set; }

   public ViewModel(List<Customer> listOfCustomers)
   {
      _customersModel = listOfCustomers;
      AddCustomer = new DelegateCommand<object>((a) => Add(), (a) => CanAdd());
      RemoveCustomer =
         new DelegateCommand<int>((a) => Remove(a), (a) => CanRemove());
   }

   public ObservableCollection<Customer> Customers
   {
      get
      {
         return new ObservableCollection<Customer>(_customersModel);
      }
      set
      {
         _customersModel = new List<Customer>(value);
         OnPropertyChanged("Customers");
      }
   }

   public Customer SelectedCustomer
   {
      get { return _selectedCustomer; }
      set
      {
         if (_selectedCustomer != value)
         {
            _selectedCustomer = value;
            UpdateCommands();
            OnPropertyChanged("SelectedCustomer");
         }
      }
   }

   public void Add()
   {
      _customersModel.Add(new Customer() { FirstName = "", LastName = "" });
      UpdateCommands();
      OnPropertyChanged("Customers");
   }

   public Boolean CanAdd()
   {
      return _customersModel.Count < 8;
   }

   public void Remove(int selectedIndex)
   {
      _customersModel.Remove(_selectedCustomer);
      UpdateCommands();
      OnPropertyChanged("Customers");
   }

   public Boolean CanRemove()
   {
      return (_selectedCustomer != null) &&
             (_customersModel != null) &&
             (_customersModel.Count > 0);
   }

   public void UpdateCommands()
   {
      RemoveCustomer.RaiseCanExecuteChanged();
      AddCustomer.RaiseCanExecuteChanged();
   }

   protected void OnPropertyChanged(string name)
   {
      PropertyChangedEventHandler handler = PropertyChanged;
      if (handler != null)
      {
         handler(this, new PropertyChangedEventArgs(name));
      }
   }
}

IndexConverter.cs
public class IndexConverter : IValueConverter
{
   public object Convert(object value, Type TargetType, object parameter, CultureInfo culture)
   {
      ListViewItem item = (ListViewItem)value;
      ListView listView =
         ItemsControl.ItemsControlFromItemContainer(item) as ListView;
      int index =
         listView.ItemContainerGenerator.IndexFromContainer(item) + 1;
      return index.ToString();
   }

   public object ConvertBack(object value,
      Type targetType, object parameter, CultureInfo culture)
   {
      throw new NotImplementedException();
   }
}

Customer.cs
public class Customer
{
   public String FirstName { get; set; }
   public String LastName { get; set; }
}

A: I wouldn't recommend exposing your domain model directly on your view models. If you're able to, it's probably a sign that you have an anemic domain model. This is very popular, but it doesn't necessarily mean it's correct.
You could expose an ObservableCollection of a CustomerViewModel. The CustomerViewModel would be a DTO for the purposes of binding to your view (as well as having properties that may augment the underlying model).
The point at which you need to run appropriate domain logic to reflect the actions of the user will depend on your UI. For example, the user may make all the changes to list and signify all of the changes at once, or you may need to run domain logic on every list change. Either way, this should be driven by your domain, and then the UI updated to reflect those changes depending on success or failure within the domain.
So it's likely that when the view model is activated, you wish to retrieve all of the customers from a data store either via an injected application service, or directly through a repository. These customers would then be mapped to your DTO (CustomerViewModel) and presented to the user. Then, when a save option is selected in your UI, the verb that sits on your view model would map those DTOs back to your domain objects, and you would persist those changes via the application service or repository.


text:
Q: Magento 2 : Ui form element enable/disable on store switcher In Magento 2.3.1, I want to do like :
If all store view, then input text should be enable. Othervise, input text should be disable.
I follow this answer : click here
But, still I'm not getting output.
How to do that?
Any help would be appreciated.
Thanks.

A: your form element should be like:
   <field name="sort_order" formElement="input">
        <argument name="data" xsi:type="array">
            <item name="config" xsi:type="array">
                <item name="source" xsi:type="string">page</item>
            </item>
        </argument>
        <settings>
            <validation>
                <rule name="required-entry" xsi:type="boolean">true</rule>
            </validation>
            <dataType>text</dataType>
            <label translate="true">Sort Order</label>
            <dataScope>sort_order</dataScope>
             <imports>
                <link name="disabled">${ $.provider}:data.do_we_hide_it</link>
            </imports>
        </settings>
    </field>

   **And you Dataprovider condition should be like below:**

        if ($storeId && $storeId != 0) {
        $this->loadedData[$banner->getBannerId()]['do_we_hide_it'] = true;
        } else {
        $this->loadedData[$banner->getBannerId()]['do_we_hide_it'] = false;
        }


text:
Q: Как создать эффект смешивания изображений при прокрутке с помощью CSS? Я видел этот классный эффект прокрутки онлайн ...

Когда одно изображение совмещается с последующим изображением при прокрутке по секциям.
Я пытался воспроизвести этот эффект, но не могу понять, как сделать это?
Вот ссылка, где я видел этот эффект: http://readingbuddysoftware.com/how-it-works/
Я пробовал использовать position: fixed на скриншотах с z-index в разделе выше, чем изображение, но последний снимок экрана всегда находится вверху.
Update:
 по разным причинам (включая размещение, используя наклон ...), я не могу использовать background-image css. Мне нужно решение для использования элемента .

A: Это можно сделать, используя background-attachement: fixed и два похожих по размерам изображения.
Вот простой пример:

body {
  min-height:150vh;
  margin:0;
  background:url(https://lorempixel.com/g/100/100/) 50px 50px/auto no-repeat;
  background-attachment:fixed;
}

.box {
  margin-top:200px;
  height:200px;
  background:url(https://lorempixel.com/100/100/) 50px 50px/auto no-repeat,
  grey;
  background-attachment:fixed;
}

Так же вы можете легко масштабировать смешивая большее количество изображений:

body {
  min-height:250vh;
  margin:0;
  background:url(https://lorempixel.com/g/100/100/) 50px 50px/auto no-repeat;
  background-attachment:fixed;
}

.box {
  height:200px;
  background:url(https://lorempixel.com/100/100/) 50px 50px/auto no-repeat,
  grey;
  background-attachment:fixed;
}
.box:first-child {
  margin-top:200px;
}

UPDATE
Если вам не нравится решение с  background-image, то вам будет необходимо  использовать некоторое количество кода JS для того, чтобы переместить IMG тег.

window.onscroll = function() {
  var scroll = window.scrollY || window.scrollTop || document.getElementsByTagName("html")[0].scrollTop;
  document.documentElement.style.setProperty('--scroll-var', scroll+"px");
}
:root {
  --scroll-var: 0px;
}

body {
  min-height: 150vh;
  margin: 0;
}

img {
  position: fixed;
  top: 50px;
  left: 50px;
}

.box {
  margin-top: 200px;
  height: 200px;
  background: grey;
  position: relative;
  overflow: hidden;
}

.box img {
  top: calc(-200px + 50px + var(--scroll-var));
  /* margin of box + top of the other image + scroll*/
  position: absolute;
}

С несколькими изображениями:

window.onscroll = function() {
  var scroll = window.scrollY || window.scrollTop || document.getElementsByTagName("html")[0].scrollTop;
  document.documentElement.style.setProperty('--scroll-var', scroll+"px");
}
:root {
  --scroll-var: 0px;
}

body {
  min-height: 250vh;
  margin: 0;
  padding-top:200px;
}

img {
  position: fixed;
  top: 50px;
  left: 50px;
}

.box {
  height: 200px;
  background: grey;
  position: relative;
  overflow: hidden;
}
img.f1 {
  top: calc(-200px + 50px + var(--scroll-var));
  position: absolute;
}
img.f2 {
  top: calc(-400px + 50px + var(--scroll-var));
  position: absolute;
}
img.f3 {
  top: calc(-600px + 50px + var(--scroll-var));
  position: absolute;
}

Источник ответа


text:
Q: CATransform3DRotate rotate for 360 degrees I've started using CATransform3D lately and it seems very nice. I just have 1 issue with the rotation though. I'm trying to rotate my view for 360˚ degrees to the right but if I just put pass 360 to CATransform3DRotate it doesn't work (It just doesn't move at all.)
Here's my code:
      CALayer *layer = dock.layer;
      CATransform3D r = CATransform3DIdentity;
      r.m34 = 1.0 / -500;
      r = CATransform3DRotate(r, DegreesToRadians(360.0f), 100.0f, 1.0f, 100.0f);
      layer.transform = r;

Does anyone know how to fix this issue? Thanks in advance! :)

A: You can animate a layer through one (or more) full rotations around its Z axis by animating the layer's transform.rotation key path, like this:
CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"transform.rotation"];
animation.duration = .25;
animation.fromValue = [NSNumber numberWithFloat:0];
animation.toValue = [NSNumber numberWithFloat:2 * M_PI];
[layer addAnimation:animation forKey:animation.keyPath];

You can animate around the X or Y axes using the key paths transform.rotation.x and transform.rotation.y.  (The transform.rotation.z key path has the same effect as the transform.rotation key path.)  You can apply multiple rotations, on separate axes, simultaneously.
Another way to do it, which probably works better if you want to rotate around an off-axis vector, is using a keyframe animation, like this:
CALayer *layer = [sender layer];
CATransform3D transform = CATransform3DIdentity;
transform.m34 = 1.0 / -50;
layer.transform = transform;

CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:@"transform"];
animation.values = [NSArray arrayWithObjects:
    [NSValue valueWithCATransform3D:CATransform3DRotate(transform, 0 * M_PI / 2, 100, 1, 100)],
    [NSValue valueWithCATransform3D:CATransform3DRotate(transform, 1 * M_PI / 2, 100, 1, 100)],
    [NSValue valueWithCATransform3D:CATransform3DRotate(transform, 2 * M_PI / 2, 100, 1, 100)],
    [NSValue valueWithCATransform3D:CATransform3DRotate(transform, 3 * M_PI / 2, 100, 1, 100)],
    [NSValue valueWithCATransform3D:CATransform3DRotate(transform, 4 * M_PI / 2, 100, 1, 100)],
    nil];
animation.duration = 2;
[layer addAnimation:animation forKey:animation.keyPath];


text:
Q: Working with Year , week and Leap year in SQL Server I'm trying to work with Year and Week in combination and would like to include leap years when they occur.
In my code I'm only adding year + week and I'm not getting what I desire. I would like to have '202101' if I change my code to '+3' because this year there are 53 weeks and the 54 week should 01.
(SELECT
     LEFT(CONVERT(VARCHAR(10), GETDATE(), 120), 4)  +
         CAST((DATEPART(ISOWK, GETDATE()) + 3) AS NVARCHAR(2)))

I would like to be able to change my code like this

*

*...GETDATE()) + 2) in my code should return 202053

*...GETDATE()) + 3) in my code should return 202001

*...GETDATE()) + 4) in my code should return 202002
etc...

Might it be that i should change my code and not have it as a 2 part YYYY and WW but rather combine it as a date? I would believe its a string now.


text:
Q: Django group by jalali week number I'm working on django api using a PostgreSQL database. The model has a date field representing a travel time (in jalali format) and an integer field representing number of passengers for that travel.
I'm using django_jalali to handle jalali date queries.
from django_jalali.db import models as jmodels

class TravelReport( models.Model ):

   travel_date = jmodels.jDateField(verbose_name="تاریخ سفر")
   passengers = models.IntegerField()

I want to aggregate sum of passengers for each week number in a jalali year. This is the query I'm using:
queryset= TravelReport.objects.annotate(week=F("travel_date__week")).values("week").annotate(total_passengers=Sum("passengers"))

Here is my problem: Django lookup __week is returning Georgian week number not jalali week number. For example week number for a travel date with jdatetime.date(1390, 5, 12) should be 19 but my query is returning 31.
What are my options to fix this?

A: Ok. Lets work out options:

*

*override the lookup method to work using the jalali calender format.

*convert your dates to gregorian format and store in another field, and call a function taht takes as input jalali format date, and sends the reciprocating gregorian format date to the lookup field.

*Keep the number of passengers for a week stored in a separate field, with key as jalali calender weekname and value will be the number of passengers for that week.


text:
Q: What does "sidle around" mean? In the following text I don't understand what "sidle around" means, I know what sidle means, but I can't imagine in my head how to "sidle around" something, I can certainly understand what walking around something means, but I can't get into my head how would someone sidle around something. Could anyone please explain?

You could see the garage, too: a long gray intestine, its doors wide
open. The trucks were parked on the paved lot next to it. He was right
about the trucks—his brains were functioning. God forbid you should
stick your head between two trucks. You have to sidle around them.

A: Think about how you would slip through a narrow space: you'd turn your body sidewise and move crablike, moving the front foot forward, and then pulling the other one up to it.
(I once parked my car too close to a pillar in the parking structure of a supermarket.  After loading my groceries into the back, I pressed the button to close the hatch and attempted to sidle between the quarter-panel of the car and the pillar, resting my hands on the car body — incautious leaving one hand in the path of the electrically closing hatch.  It nearly broke three of my fingers and did succeed in tearing the nail off my index finger.)


text:
Q: How to build a property grid in Angular 2+ I am building an IDE type application in Angular 6 specific to my domain where I need to allow the user to edit properties of C# objects. Think of the Visual Studio property grid for a Windows Forms or Web Forms project where you can click on a button on the form and in the property grid you can change the properties of the button (e.g. color,size,text,etc).
I had the idea of sending a json string to the client that includes the properties of the object with their current values. Something like this:
{
"id":1,
"name":"Volume",
"type":"VolumeCalculator",
"properties":
[
  {
    "name":"NumberOfLevels",
    "type":"int",
    "value":2
  },
  {
    "name":"Period",
    "type":"object",
    "properties":
    [
      {
        "name":"From",
        "type":"DateTime",
        "properties":
        [
          {
            "name":"FromDate",
            "type":"Date",
            "value":"01/01/2018"
          },
          {
            "name":"FromTime",
            "type":"Time",
            "value":"12:00:00"
          }
        ]
      },
      {
        "name":"Until",
        "type":"DateTime",
        "value":"02/01/2018 12:00:00"
      }
    ]
  },
  {
    "name":"TreeType",
    "type":"enum",
    "value":2,
    "options":["Path Graph","Star Like"]
  }
]
}

With this json string I have all the information I need to build a grid. Different data types will present different editors. A DateTime type would allow the user to click a calendar icon to bring up a calendar and choose a value. An Enum type would present a drop down where the user would pick from the provided values.
Where I am struggling is I am relatively new to Angular 6 development. I have built some simpler applications so I am familiar with beginner level Angular concepts. I think this problem requires a bit more advanced concepts that I am just unfamiliar with so am looking for pointers. Perhaps this should be a directive? Perhaps it is just a component itself and no directive is necessary.
I am not asking for a complete solution (however, if someone wants to provide one I won't complain), just some direction from the Angular experts.
I am even interested in just buying a library that already provides the functionality, but so far I have been unable to find one that supports Angular 6. If anyone knows of one, I am happy to review it to see if it will work for me.


text:
Q: How to get labels from GitHub using Swift3 I would like to know how to get labels from user setting. I know how to post selected labels to a user's repository.
 let authToken = GithubAPIManager.sharedInstance.OAuthToken
    let repo = newIssue.repo!.name!
    let repoOwner = newIssue.repo!.ownerLogin!

    let URL = Foundation.URL(string: "https://api.github.com/repos/\(repoOwner)/\(repo)/labels")!

    print("Issue URL ---->", URL)

    Alamofire.request(URL, method: .get, parameters: getParameters, encoding: JSONEncoding.default).responseJSON {

        (response) in

        guard let object = response.result.value else {
            print(response.result.error!)
            completionHandler(.failed)
            return
        }

        completionHandler(.success)
        print(object)

    }


text:
Q: Why does R source() sometimes work and sometimes gives an error I have the API credentials in one separate R script to keep it out of Git. I want to run this script in the beginning of the scripts that actually interact with the different servers. I have successfully used the same strategy for all my global functions.
setwd("G:/script")
source("API_credentials.R")  # gives always an error

# > source("API_credentials.R")
# Error: '\s' is an unrecognized escape in character string starting ""g:\s"

source("ProVeg_functions.R") # runs fine

Problem:
Why does the first source() not work, while the second one does?  The error message does not make any sense to me.
Solutions tried:

*

*I have tried different escape chars \.

*I have tried writing full path & file names.

*I have tried putting the file name in as a variable, which gets its
content from a dir() search, to make sure that the file exists and
the name is correctly written.

*Order of source() does not change situation.

*Isolating the piece of code with error, and restarting R.

*upgraded all my packages and R to version 4.0.2.

*The API_credentials.r script works fine when run on its own. the Sys.setenv() works fine and I can read the API keys with Sys.getenv().

*I am not sure if it is related to my problem, but if I do usethis::edit_r_environ() I can not see my API keys.

Setup
Windows 10, R-Studio 1.3.1093, R version 4.0.2 (2020-06-22)

A: I mistakenly assumed that the error message was related to the script calling the API_credentials.R, but it actually was an error message indicating an error in the API_credentials.R script.  Fixed a typo and all is good.


text:
Q: Check if application was started through Toast Notification panel click Is it possible to check whether the application was started when the user received the Toast Notification and clicked it?

A: In the page URL (which opens when the Toast is tapped), add a query string. For example:
"<wp:Param>/ToastPage.xaml?NavigatedFrom=FromToast</wp:Param>"

Then, in your ToastPage.xaml's OnNavigatedTo method, you can check for the query string
string navFrom= "";

NavigationContext.QueryString.TryGetValue("NavigatedFrom", out navFrom);

Here, navFrom will store the value FromToast if it came from toast, otherwise it will either store something else if you have other query string values or remain as "".


text:
Q: running multiple regression models using tidymodels I've recently been using tidymodels to run models and select parameters that best satisfy some objective function. For example using a hypothetical regression on mtcars data (using the regression examples from the bottom answer of this question as an example)
library(tidymodels)
library(tidyverse)

#some regression model
cars_recipe <- recipe(mpg ~ disp + drat, data = mtcars)

wf <- workflow() %>%
  add_recipe(cars_recipe)

(roughly using syntax from this blog post for comparison; I'm not doing various steps like splitting test/train just for clarity in this example)
I can then run many models and get the metrics from those models (in this case for various penalties for some elastic nets) thusly
#run over a parameter space and find metrics as an objective
mtcars_bootstrap <- bootstraps(mtcars)

tune_spec <- linear_reg(penalty = tune(), mixture = 1) %>%
  set_engine("glmnet")

lambda_grid <- grid_regular(penalty(), levels = 50)

lasso_grid <- tune_grid(
  wf %>% add_model(tune_spec),
  resamples = mtcars_bootstrap,
  grid = lambda_grid
)

but lets say I have good reason to think there are two separate models which may best capture the effect on (e.g.) mpg of a car so I create a second model as a recipe
cars_recipe2 <- recipe(mpg ~ I(disp + drat), data = mtcars)

now I could just also run this recipe through the above pipeline using lapply or the purrr family of functions, however, I wondered if there is some built-in way to run multiple recipes through tidymodels?
It seems like there should be though I also thought it might be precluded by design to prevent p-hacking

A: There is an experimental package we are developing to do just this called workflowsets. You can install it from GitHub for now, if you are up for trying out a new, still-developing package:
devtools::install_github("tidymodels/workflowsets")

Then you can set up an analysis like this:
library(tidymodels)
library(workflowsets)

mtcars_boot <- bootstraps(mtcars)

rec1 <- recipe(mpg ~ disp + drat, data = mtcars)
rec2 <- recipe(mpg ~ disp + drat, data = mtcars) %>%
  step_log(disp) %>%
  step_normalize(disp, drat)

lasso_spec <- linear_reg(penalty = tune(), mixture = 1) %>%
  set_engine("glmnet")

# put it all together in a "workflow set"
car_models <-
  workflow_set(
    preproc = list(simple = rec1, preproc = rec2),
    models = list(lasso = lasso_spec),
    cross = TRUE
  )
car_models
#> # A workflow set/tibble: 2 x 4
#>   wflow_id      info             option    result
#>   <chr>         <list>           <list>    <list>
#> 1 simple_lasso  <tibble [1 × 4]> <opts[0]> <list [0]>
#> 2 preproc_lasso <tibble [1 × 4]> <opts[0]> <list [0]>

Now that you have a workflow set, you can "map" over it using, in this case tune_grid() and the other arguments you want to use like the resamples and grid.
lambda_grid <- grid_regular(penalty(range = c(-2, 0)), levels = 10)

car_res <- car_models %>%
  workflow_map("tune_grid", resamples = mtcars_boot,
               grid = lambda_grid, verbose = TRUE)
#> i 1 of 2 tuning:     simple_lasso
#> ✓ 1 of 2 tuning:     simple_lasso (7.7s)
#> i 2 of 2 tuning:     preproc_lasso
#> ✓ 2 of 2 tuning:     preproc_lasso (8.4s)

## some autoplot methods are available
autoplot(car_res)

Created on 2021-02-09 by the reprex package (v1.0.0)
This is in process so if you have high stability needs, I would wait a few months to use it. We are excited about how it will be able to fit people's needs, though!


text:
Q: How to index select keys in Postgres jsonb data? I use jsonb type in Postgres for storing key-value documents. And I use GIN indexes on top of these documents for fast look-ups. All of it works well, although GIN indexes by default tend to be verbose, i.e. they index every key in the jsonb structure. I'd like to have more selective indexing.
Is it possible to do these with GIN indexes?

*

*Have GIN only index the top-level keys, and leave the nested structures unindexed? OR

*Have GIN only index specific keywords (I'm aware that I could create separate btree indexes for each keyword that needs to be indexed. I'm interested in knowing if I can get it done via GIN)

Thank you.

A: It can be done using auxiliary function that takes a JSONB document as input and array of keys and returns a new document with keys filtered, that you can then index with GIN:
create function jsonb_filter(doc jsonb, variadic keys text[])
returns jsonb
as 'select jsonb_object_agg(key, doc->key) from unnest(keys) key'
language sql
immutable;

create index filtered_index on jsonb_table
using gin (jsonb_filter(data, 'a', 'b'));

select data->'a'
from jsonb_table
where jsonb_filter(data, 'a', 'b') @> '{"a":1}';

You may want to hardcode the set of keys you want to filter inside the function to avoid repeating them in queries.
If you want to just index the presence of some keys, then:
create function jsonb_keys(doc jsonb)
returns text[]
as 'select array_agg(key) from jsonb_object_keys(doc) key'
language sql
immutable;

create index keys_index on jsonb_table
using gin (jsonb_keys(data));

select data->'b'
FROM jsonb_table
where jsonb_keys(data) @> ARRAY['a'];

The function jsonb_keys can be modified to include only the keys you want to index.
Here is the relevant SqlFiddle http://sqlfiddle.com/#!17/b7935/6


text:
Q: Trying to get the specific information from the array I need to convert this array:
arr=("aa:" "info" "{" "bb:" "name" "value" "50;" "bb:" "surname" "oth_value" "50;" "bb:" "age" "number" "3;" "bb:" "about" "text" "void;" "}")

to something like this:
arr=(("aa:" "info" "{") ("bb:" "name" "value" "50;") ("bb:" "surname" "oth_value" "50;") ("bb:" "age" "number" "3;") ("bb:" "about" "text" "void;") ("}"))

the goal is to loop through the multidimensional array to be able to perform actions with each array that is inside. For example:
for i in "${!arr[@]}"; do
   echo "${arr[i][0]}"
   # prints out the first value of each element
   echo "${arr[i][1]}"
   # prints out the second value of each element
done

What I need is to be able to separate the information between bb: and ; and use each of it's elements. For example to echo it out. The only idea I came up with is to put separate the needed information in the arrays inside of the main array (to create multidimensional) and when looping through it, to use the values I need. Basically there will be only three values between bb: and ;. But the number of this bb: and ; sections is unlimited. The aa: info { and the } should be cutted of. I don't need them.

A: arr=("aa:" "info" "{" "bb:" "name" "value" "50;" "bb:" "surname" "oth_value" "50;" "bb:" "age" "number" "3;" "bb:" "about" "text" "void;" "}")
for ((i=3; i + 4 < ${#arr[@]}; i+=4))
do
    echo "${arr[i]}"
    echo "${arr[i + 1]}"
    echo "${arr[i + 2]}"
    echo "${arr[i + 3]}"
done

This is a straightforward C-style for loop. You can ignore any of the fields you don't want to care about, and change the numbers.

Wherever this array originally came from, you'd almost certainly be better off in general using a proper parser on the source text, but this does satisfy the scenario you've described adequately. As soon as it gets more complicated it's going to get much harder, though — it's only because it happens to be purely stepping by four that this works out simply.


text:
Q: Approach in migrating Access rows to existing SQL tables I have used SSMA 5.2 to migrate an Access 2010 database to SQL 2005 (SP3). The SQL database is part of an ASP.NET application and is currently in production. However, users have also been inserting new records into the tables of the original Access file and now I need to insert these new rows into the SQL tables. There are around 100+ tables.
Unfortunately, If I try to run SSMA again, it requires that I overwrite the SQL tables. If I do this I will loose the new rows that have been added, into the SQL tables, after the system went live. I only need to insert the new rows that are in Access.
Are there any other tools available that I can use?
Appreciate if someone could help me resolve this.
Thanks!

A: Why not use SSMA to migrate the Access DB to a sencond SQL2005, using exactly the same procedure.
Afterwards, you can write a script that merges each table from each db.


text:
Q: Windows phone - Counting number of times phone has been turned on/off Just checking if its possible on WinPhone 8.1, to log a daily count of power on/off and screen locked/unlocked events. Ideally I'd like to maintain a log with timestamps but counts will do too. Thanks!

A: Sorry, this is not possible in Windows Phone.


text:
Q: Probability of Adjacent Birthdays Recall the birthday problem, where only 23 people are required for a >50% chance that at least two share the same birthday.
What is the new probability if we want at least two people out of twenty-three to share the same birthday or have adjacent birthdays? January 1 and December 31 are considered adjacent, and we don't consider February 29.
Similar to the birthday problem, I thought it would be easier to consider the probability that nobody has matching or adjacent birthdays, but as I was setting up the products, I realized that there are different amounts of available dates, depending on when the birthdays are. For ease of writing, let the dates be represented as 1, 2, 3, 4, ..., 365. Say the first person's birthday is 1. If the second person's birthday is 3 or 364, then there are 360 remaining choices for the third birthday, but if the second person's birthday is not in (364, 365, 1, 2, 3), then there are 359 remaining choices for the third person's birthday. Considering all these possibilities for 23 people is tedious, however.
I also tried approaching this from a stars and bars perspective. Arrange 23 bars in a circle, put one star automatically between each bar, leaving 339 possible dates to be inserted. However, this also is difficult because there's an ordering. If three bars are Mar 1, Mar 14, and Mar 20, you can't stick Aug 5 in there. So, I was at a loss to figure it out intuitively.
On the other hand, I generated a pattern by starting small (5 days and 2 people, for example), and finding a function out of OEIS. The answer to the problem with 365 days and 23 people is
$$1 - \frac{23!}{365^{23}} \left( \binom{343}{23} - \binom{341}{21} \right) \approx 0.8879096$$
Let $r(n,k)$ be the rising factorial, $n(n+1)(n+2)...(n+k-1)$. The answer can also be written as
$$1 - \frac{23!}{365^{23}} \left( r(321, 23) - r(321, 21) \right) \approx 0.8879096$$
The $321$ comes from $365 - 2(23-1)$, which is due to the pattern I found.
My question is, what's the intuitive way to approach this problem, or how do I actually derive the formula to get my answer?

A: Without loss of generality break the circle of days at the first person's birthday, leaving a row of $364$ days. We want to count the number of ways $n-1$ other, different birthdays ($n$ people total) can be filled into those slots so no two birthdays are adjacent to each other or the row's ends.
The $n-1$ other people may be viewed as bars dividing the row into $n$ necessarily nonempty parts and the $365-n$ unfilled days as stars; there are thus $364-n$ places the bars can go into and the desired number is $\binom{364-n}{n-1}(n-1)!$ when the people's order matters. The number of ways to assign birthdays in order without restrictions, keeping the first person's birthday fixed, is $365^{n-1}$. The probability of no birthdays adjacent is therefore
$$\frac{(364-n)!}{365^{n-1}(365-2n)!}$$
which is $0.11209035633\dots$ for $n=23$ (agreeing with your result) and first less than $\frac12$ for $n=14$.

A: The problem may be elegantly attacked by re-construing the original Birthday problem to be a Stars and Bars problem, and then regarding this problem as a refinement of the original problem.
For Stars and Bars theory, see
this article and
this article.

Thank goodness that you made the simplifying assumptions that Dec 31 is right-next-to Jan 1, and that Feb 29 does not exist.
First consider the original problem by regarding the dates of the $(23)$ people as
$$D_1, D_2, \cdots, D_{23}.$$
Then, in the original problem, the probability may be regarded as $$\frac{N}{D} ~: ~D = 365^{23}.$$
In the original problem, you would then consider the number of non-negative integer solutions to
$$x_1 + x_2 + \cdots + x_{24} = (365 - 23). \tag1 $$
In (1) above, the $(24)$ variables may be regarded as the gaps before and after the $(23)$ dates, $D_1, D_2,\cdots, D_{23},$ which are required to be distinct dates in strictly ascending order.
Per Stars and Bars theory, the enumeration of the number of solutions is
$$\binom{[365 - 23] + [24 - 1]}{[24 - 1]} = \binom{365}{23}. \tag2 $$
Note that (2) above gives the perfect enumeration of the numerator in the original problem, except that the enumeration is lacking the $(23!)$ factor, which represents that the $(23)$ people can be assigned the dates $D_1, \cdots, D_{23}$ in $(23)!$ ways.

The only necessary alteration to the Stars and Bars approach of the original problem is that:

*

*Each of $~\displaystyle \left(x_2, x_3, \cdots, x_{23}\right)~$ must be $\geq 1 ~~~$ and

*Either $~x_1 \geq 1, ~~x_{24} \geq 1,~$ or both.
The two bullet-pointed complications above are handled as follows:
$y_i = x_i - 1 ~: ~2 \leq i \leq 23.$
This implies that you want the number of non-negative integer solutions to
$$~\color{red}{x_1} + y_2 + \cdots + y_{23} + \color{red}{x_{24}} = [365 - 23] ~\color{red}{- 22}. \tag3 $$
The enumeration to (3) above, which may be construed to be $N_1,$ which will represent a partial computation in the numerator of the refined problem, is calculated as
$$\binom{[\langle 365 - 23\rangle - 22] + [24 - 1]}{[24 - 1]} = \binom{343}{23}. \tag4 $$
So, you have that
$$N_1 = \binom{343}{23},$$
which represents the enumeration when $x_2, \cdots, x_{23}$ are all forced to be $\geq 1$, and represents that there must be at least one day between each of $D_1,D_2$ and $D_2,D_3$ and ... and $D_{22},D_{23}.$
What I need is to use $N_1$ as a baseline computation, and deduct from that all of the situations where $x_1$ and $x_{24}$ are both equal to $(0)$.
The number of solutions to deduct will be the number of non-negative integer solutions to
$$0 + y_2 + \cdots + y_{23} + 0 = [365 - 23] - 22.$$
This computation will be
$$N_2 = \binom{[\langle 365 - 23\rangle - 22] + [22 - 1]}{[22 - 1]} = \binom{341}{21}. \tag4 $$
So, the final enumeration of the numerator will be
$$N = N_1 - N_2 = \binom{343}{23} - \binom{341}{21}. \tag5 $$
Then, using (5) above, the final computation will be
$$\frac{(23)!}{(365)^{(23)}} \times N.$$

A: *

*Make $23$ blocks of birthday - nonbirthday, $(365-23) =342$ entities result

*Place the $23$ blocks in  $\binom{342 }{23}$ ways

*Multiply by $\frac{365}{342}$ as you allowed birthdays only $342$ starts

*Finally multiply by $23!$ to assign people to birthdays and divide by all possible assignations, $365^{23}$

*P(some birthdays shared or
adjacent) $ = 1 -  \Large\dfrac{23!\cdot\frac{
365}{342}\cdot\binom{342}{23}}{365^{23}}$

Added Explanation
The total possible birthdays of $365^{23}$, and the final use of the complement are yours, I shall explain the numerator.

*

*Form blocks of birthday-nonbirthday, $\;\boxed{BN}....\boxed{BN}\,$ (clockwise,say) to ensure that no two birthdays are adjacent in the circle

*The placing of the blocks in $\dbinom{365-23}{23} = \dbinom{342}{23}\;$ ways,
and $23!$ for who occupies which of the $23$ birthdays should be obvious

*The unusual feature in the approach is to circumvent stars and bars by forming blocks, and correcting for the reduced starting points now available for birthdays by the multiplier $\Large\frac{365}{342}$


text:
Q: kubernetes development environment to reduce development time I'm new to devops and kubernetes and was setting up the local development environment.
For having hurdle-free deployment, I wanted to keep the development environment as similar as possible to the deployment environment. So, for that, I'm using minikube for single node cluster, and that solves a lot of my problems but right now, according to my  knowledge, a developer need to do following to see the changes:

*

*write a code locally,

*create a container image and then push it to container register

*apply the kubernetes configuration with updated container image

But the major issue with this approach is the high development time, Can you suggest some better approach by which I can see the changes in real-time?

A: The official Kubernetes blog lists a couple of CI/CD dev tools for building Kubernetes based applications: https://kubernetes.io/blog/2018/05/01/developing-on-kubernetes/
However, as others have mentioned, dev cycles can become a lot slower with CI/CD approaches for development. Therefore, a colleague and I started the DevSpace CLI. It lets you create a DevSpace inside Kubernetes which allows you a direct terminal access and real-time file synchronization. That means you can use it with any IDE and even use hot reloading tools such as nodemon for nodejs.
DevSpace CLI on GitHub: https://github.com/covexo/devspace

A: I am afraid that the first two steps are practically mandatory if you want to have a proper CI/CD environment in Kubernetes. Because of the ephemeral nature of containers, it is strongly discouraged to perform hotfixes in containers, as they could disappear at any moment.
There are tools like helm or kubecfg that can help you with the third step

apply the kubernetes configuration with updated container image

They allow versioning and deployment upgrades. You would still need to learn how to use but they have innumerable advantages.
Another option that comes to mind (that without Kubernetes) would be to use development containers with Docker. In this kind of containers your code is in a volume, so it is easier to test changes. In the worst case you would only have to restart the container.
Examples of development containers (by Bitnami) (https://bitnami.com/containers):

*

*https://github.com/bitnami/bitnami-docker-express

*https://github.com/bitnami/bitnami-docker-laravel

*https://github.com/bitnami/bitnami-docker-rails

*https://github.com/bitnami/bitnami-docker-symfony

*https://github.com/bitnami/bitnami-docker-codeigniter

*https://github.com/bitnami/bitnami-docker-java-play

*https://github.com/bitnami/bitnami-docker-swift

*https://github.com/bitnami/bitnami-docker-tomcat

*https://github.com/bitnami/bitnami-docker-python

*https://github.com/bitnami/bitnami-docker-node

A: I think using Docker / Kubernetes already during development of a component is the wrong approach, exactly because of this slow development cycles. I would just develop as I'm used to do (e.g. running the component in the IDE, or a local app server), and only build images and start testing it in a production like environment once I have something ready to deploy. I only use local Docker containers, or our Kubernetes development environment, for running components on which the currently developed component depends: that might be a database, or other microservices, or whatever.

A: On the Jenkins X project we're big fans of using DevPods for fast development - which basically mean you compile/test/run your code inside a pod inside the exact same kubernetes cluster as your CI/CD runs using the exact same tools (maven, git, kubectl, helm etc).
This lets you use your desktop IDE of your choice while all your developers get to work using the exact same operating system, containers and images for development tools.
I do like minikube but developers often hit issues trying to get it running (usually related to docker or virtualisation issues). Plus many developers laptops are not big enough to run lots of services inside minikube and its always going to behave differently to your real cluster - plus then the developers tools and operating system are often very different to whats running in your CI/CD and cluster.
Here's a demo of how to automate your CI/CD on Kubernetes with live development with DevPods to show how it all works

A: It's not been so long for me to get involved in Kubernetes and Docker, but to my knowledge, I think it's the first step to learn whether it is possible and how to dockerize your application.
Kubernetes is not a tool for creating docker image and it is simply pulling pre-built image by Docker.
There are quite a few useful courses in the Udemy including this one.
https://www.udemy.com/docker-and-kubernetes-the-complete-guide/


text:
Q: Cycle list of colors and set them as cell background color | UITableView | Objective-C Say I have a list of hex colors: {#5375ab, #D673DD, #fca565, #4f70a6, #f86cb5, #b9f3cd, #eff8a5, #f4adf9, #fe502e, #5375ab}.
In my UITableView, is there a way to cycle through the list of colors and set each cell as one of the colors?
For example the background colors would be as such:
Cell 1 - backgroundColor: #5375ab
Cell 2 - backgroundColor: #D673DD
Cell 3 - backgroundColor: #fca565

...and so on

A: Yes, use the % modulo operator on the indexPath.row. In your cellForRowAtIndexPath implementation do something like:
NSArray *colors = @[yourColor1, yourColor2, yourColor3];
int colorIndex = indexPath.row % colors.count;

cell.backgroundColor = colors[colorIndex];


text:
Q: website layout issue & best practice when designing the main template I want to have a website layout with

*

*Header section full width

*Content Area Center with 870px width with Content bar & widget bar

*Footer section with 100%

*Copyright bar at bottom with 100%

Sample design is setup at fiddle http://jsfiddle.net/7zavu4f4/
For some reason Footer section is not showing up and i want to know if this design temple is flexible to adjust contents in content area of varying height.
Has this been design in a good way or i need to make any changes to make it clean.

Search control will be on right

Logo Will Be here

Home

Products

Company

Contact

I don't need a responsive version for this as we have a separate mobile version of this website based on Mobile jQuery.. So please only take desktop version into consideration

A: Have you tested your design out different browsers and different screen sizes? PCs and Macs? Android? iOS?
Rather than having a specific mobile version, it is much better to make your standard website look good at all screen sizes. Not everyone has a browser window of 870px width -- you have to consider how the page will look on a 1920x1080 screen or a 1440x900 screen as well as a narrow phone viewport. Some things to consider might be whether you want to make your main content wider on large screens and put the widgets outside the central coloured content area.
If you want to improve your markup (i.e. the html), have a look at the html5 specs, and particularly at the semantic tags such as
,
, , and  -- it is more semantically appropriate to use those elements than a load of
s . There is an excellent list of html5 resources at HTML5 Rocks.

A: Footer & copyright sections are not showing up because you have a floated element above them in the page. So they are actually just sitting behind all the floats.
So a simple clear: both will bring out these two footer elements. Either add some height eg height:10px or some text so you can see them.


text:
Q: Tuxguitar - no sound on 22.10 I have always this type of issue when installing a new version of Ubuntu from scratch.
I typically solve by adding some plugins, however I read that 22.10 sports with Pipewire as a new audio server.
Not being an expert my concern is to mess things, is there a clear procedure to make audio working on Tuxguitar?


text:
Q: TypeScript ignores optional parameter of type never I don't want a specific function to be passed as a parameter to another function however according to TypeScript it is valid, but is it? and why?
Here's the code example:
function spoken(nope?: never): void {
    console.log("He has spoken.");
}

function speak(toSay: string, spoken: (arg1: string) => void): void {
    console.log("He says: " + toSay);
    spoken("He has spoken.");
}

speak("Hello world.", spoken);

Because basically, TypeScript says type string is assignable to type never, because if nope were of lets say type number, TypeScript would complain because type string isn't compatible to type number.

A: Short Answer

...according to TypeScript it is valid, but is it? and why?

Yes, it is valid, because TypeScript says that type never is assignable to type string. Here is some code in typescript/play to demonstrate.
Details on never
The Basic Types documentation says:

The never type is a subtype of, and assignable to, every type; however, no type is a subtype of, or assignable to, never (except never itself).

That means we can assign never to string but cannot assign string to never.
let arg1: string = (null as never); // works
let arg2: never = (null as string); // fails

Details on Your Situation
Your speak function has a parameter named spoken, which is a function that has an arg1 parameter of type string. Here is the spoken parameter on its own.
let spokenParam: (arg1: string) => void;

Since arg1 is a string and string is a super-type of never, the following assignment is valid.
function spoken(nope?: never): void {
    console.log("He has spoken.");
}

spokenParam = spoken;


text:
Q: Why the program hangs after pressing the connect button? I want to start a server that will run regardless of whether there are clients or not, but when I press the connect button it(the GUI) hangs even if I started a new thread for function runServer().
Thanks in advance, and help is appreciated.
 class HandleAClient implements Runnable {
    private Socket socket;

    public HandleAClient(Socket socket){
        this.socket = socket;
    }

    @Override
    public void run() {
        try{
            DataInputStream inputFromClient = new DataInputStream(socket.getInputStream());
            DataOutputStream outputToClient = new DataOutputStream(socket.getOutputStream());
        }catch(IOException ioex){
            System.err.println(ioex);
        }
    }

}
//==========================================================================
//==========================================================================
private void runServer()
{
    try{

        while(true){
           Socket socket = server.accept();
            HandleAClient task = new HandleAClient(socket);
            new Thread(task).start();
        }
    }catch(IOException ioex){
        ioex.printStackTrace();
    }

}//end method runServer
  //=====================================================================
 //=====================================================================

   private void Connect_BtnActionPerformed(java.awt.event.ActionEvent evt) {
    // TODO add your handling code here:
    username = UserName_TF.getText();
    passwordtext = Password_TF.getText();

    try {
        conn = DriverManager.getConnection(url, username, passwordtext);
        if(conn.isValid(0))
            connected = true;

        jButton3.setEnabled(true);
        jLabel4.setText("Connected");
        UserName_TF.setEnabled(false);
        Password_TF.setEnabled(false);

        //java.awt.EventQueue.invokeLater(() -> {
            runServer();
        //});

    } catch (SQLException e) {
        //System.err.println(e);
        JOptionPane.showMessageDialog(null, e);
    }
}

A: I changed my code to the following (Thanks to Vince recommendations)
public class MyThread extends Thread {

//private int var;

public MyThread() {
    //this.var = var;
}

@Override
public void run() {
    try {
        while (true) {
        Socket socket = server.accept();
        DataInputStream inputFromClient = new DataInputStream(socket.getInputStream());
        DataOutputStream outputToClient = new DataOutputStream(socket.getOutputStream());
        }
    } catch (IOException ex) {
        Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
    }
}
}

//=========================================================================
private void Connect_BtnActionPerformed(java.awt.event.ActionEvent evt) {
    // TODO add your handling code here:
    username = UserName_TF.getText();
    passwordtext = Password_TF.getText();

    try {
        conn = DriverManager.getConnection(url, username, passwordtext);
        if(conn.isValid(0))
            connected = true;

        jButton3.setEnabled(true);
        jLabel4.setText("Connected");
        UserName_TF.setEnabled(false);
        Password_TF.setEnabled(false);
            //JOptionPane.showMessageDialog(null, "Connection Established");

            new Login.MyThread().start();

    } catch (SQLException e) {
        //System.err.println(e);
        JOptionPane.showMessageDialog(null, e);
    }
}