text:
Q: how to discover all WiFi networks on my Ubuntu 15.10 and choose one of them? how to discover all WiFi networks on my Ubuntu 15.10 and choose one of them? is this possible?

A: Use iwlist. The man page (actually http://manpages.ubuntu.com/manpages/wily/en/man8/iwlist.8.html) says:
wlist.8.gz
Provided by: wireless-tools_30~pre9-8ubuntu1_i386

NAME

       iwlist  -  Get  more  detailed  wireless  information  from  a wireless
       interface

SYNOPSIS

       iwlist [interface] scanning

snip...
PARAMETERS

       scan[ning]
              Give the list of Access Points and Ad-Hoc cells  in  range,  and
              optionally  a  whole  bunch  of  information  about them (ESSID,
              Quality, Frequency, Mode...). The type of  information  returned
              depends on what the card supports.
              Triggering  scanning  is  a privileged operation (root only) and
              normal users can only read left-over scan results.  By  default,
              the way scanning is done (the scope of the scan) is dependant on
              the card and card settings.
              This command takes optional arguments, however most drivers will
              ignore  those.  The  option essid is used to specify a scan on a
              specific ESSID. With  some  card/driver,  this  enables  to  see
              hidden  networks.  The  option  last does not trigger a scan and
              read left-over scan results.

"How do I connect to a wireless..." is a second question that should be asked by itself, in a different Question post.

A: If you have a graphical environment installed, there should be a network indicator icon somewhere on the desktop, (most of the time in a bar on the top of the screen), and you should be able to find your network there in its dropdown menu. Click on the network indicator icon and check Enable Wi-Fi to show all available Wi-Fi networks. Click your network, fill in the password, and it should connect.


text:
Q: Flutter - How to make a custom TabBar
This is the output that I want. I am still new in flutter so can anyone let me know if there is already a widget for this kind of switch or how should I make one ??
Also, I want the data shown below this button to change if I choose the other button but I guess that's obvious.
Thanks in advance.

A: You can use the TabBar widget to achieve this. I added a full example demonstrating how you can create this using the TabBar widget:
CODE
class StackOver extends StatefulWidget {
  @override
  _StackOverState createState() => _StackOverState();
}

class _StackOverState extends State<StackOver>
    with SingleTickerProviderStateMixin {
  TabController _tabController;

  @override
  void initState() {
    _tabController = TabController(length: 2, vsync: this);
    super.initState();
  }

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(
          'Tab bar',
        ),
      ),
      body: Padding(
        padding: const EdgeInsets.all(8.0),
        child: Column(
          children: [
            // give the tab bar a height [can change hheight to preferred height]
            Container(
              height: 45,
              decoration: BoxDecoration(
                color: Colors.grey[300],
                borderRadius: BorderRadius.circular(
                  25.0,
                ),
              ),
              child: TabBar(
                controller: _tabController,
                // give the indicator a decoration (color and border radius)
                indicator: BoxDecoration(
                  borderRadius: BorderRadius.circular(
                    25.0,
                  ),
                  color: Colors.green,
                ),
                labelColor: Colors.white,
                unselectedLabelColor: Colors.black,
                tabs: [
                  // first tab [you can add an icon using the icon property]
                  Tab(
                    text: 'Place Bid',
                  ),

                  // second tab [you can add an icon using the icon property]
                  Tab(
                    text: 'Buy Now',
                  ),
                ],
              ),
            ),
            // tab bar view here
            Expanded(
              child: TabBarView(
                controller: _tabController,
                children: [
                  // first tab bar view widget
                  Center(
                    child: Text(
                      'Place Bid',
                      style: TextStyle(
                        fontSize: 25,
                        fontWeight: FontWeight.w600,
                      ),
                    ),
                  ),

                  // second tab bar view widget
                  Center(
                    child: Text(
                      'Buy Now',
                      style: TextStyle(
                        fontSize: 25,
                        fontWeight: FontWeight.w600,
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}

OUTPUT

A: Try out this you have to change some colour and font:-
import 'package:flutter/material.dart';

typedef SwitchOnChange = Function(int);

class CustomSwitch extends StatefulWidget {
  SwitchOnChange onChange;

  CustomSwitch({this.onChange});

  @override
  State<StatefulWidget> createState() {
    return CustomSwitchState();
  }
}

class CustomSwitchState extends State<CustomSwitch>
    with TickerProviderStateMixin {
  AnimationController controller;
  Animation animation;

  GlobalKey key = GlobalKey();
  @override
  void initState() {
    Future.delayed(Duration(milliseconds: 100)).then((v) {
      controller = AnimationController(
          vsync: this, duration: Duration(milliseconds: 300));

      tabWidth = key.currentContext.size.width / 2;
      // var width = (media.size.width - (2 * media.padding.left)) / 2;
      animation = Tween<double>(begin: 0, end: tabWidth).animate(controller);

      setState(() {});

      controller.addListener(() {
        setState(() {});
      });
    });
    super.initState();
  }

  var selectedValue = 0;
  double tabWidth = 0;
  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () {
        selectedValue == 0 ? this.controller.forward() : controller.reverse();
        selectedValue = selectedValue == 0 ? 1 : 0;
      },
      child: Container(
        key: key,
        height: 44,
        decoration: BoxDecoration(
            color: Colors.grey, borderRadius: BorderRadius.circular(22)),
        child: Stack(
          children: <Widget>[
            Row(
              children: <Widget>[
                Transform.translate(
                  offset: Offset(animation?.value ?? 0, 0),
                  child: Container(
                    height: 44,
                    width: tabWidth,
                    decoration: BoxDecoration(
                        color: Colors.white,
                        borderRadius: BorderRadius.circular(22),
                        boxShadow: [
                          BoxShadow(color: Colors.grey, blurRadius: 3),
                        ]),
                  ),
                ),
              ],
            ),
            Center(
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: <Widget>[
                  Container(
                    width: tabWidth,
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: <Widget>[
                        Icon(Icons.directions_walk),
                        SizedBox(width: 5),
                        Text("Place Bid")
                      ],
                    ),
                  ),
                  Container(
                    width: tabWidth,
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: <Widget>[
                        Icon(Icons.directions_walk),
                        SizedBox(width: 5),
                        Text("Buy now")
                      ],
                    ),
                  )
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}

A: The following is my workaround, which I believe to be the best method.
import 'package:flutter/material.dart';

class SettingsScreen extends StatelessWidget {

  const SettingsScreen({
    super.key,
  });

  @override
  Widget build(BuildContext context) {
    return DefaultTabController(
      length: 2,
      child: Scaffold(
        appBar: AppBar(
          title: const Text('Settings'),
          bottom: PreferredSize(
            preferredSize: Size.fromHeight(AppBar().preferredSize.height),
            child: Container(
              height: 50,
              padding: const EdgeInsets.symmetric(
                horizontal: 20,
                vertical: 5,
              ),
              child: Container(
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(
                    10,
                  ),
                  color: Colors.grey[200],
                ),
                child: TabBar(
                  labelColor: Colors.white,
                  unselectedLabelColor: Colors.black,
                  indicator: BoxDecoration(
                    borderRadius: BorderRadius.circular(
                      10,
                    ),
                    color: Colors.pink,
                  ),
                  tabs: const [
                    Tab(
                      text: 'Basic',
                    ),
                    Tab(
                      text: 'Advanced',
                    )
                  ],
                ),
              ),
            ),
          ),
        ),
        body: const TabBarView(
          children: [
            Center(
              child: Text(
                'Basic Settings',
                style: TextStyle(
                  fontSize: 30,
                ),
              ),
            ),
            Center(
              child: Text(
                'Advanced Settings',
                style: TextStyle(
                  fontSize: 30,
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

A: You can use also PageView widget.
const double borderRadius = 25.0;

class CustomSwitchState extends StatefulWidget {
  @override
  _CustomSwitchStateState createState() => _CustomSwitchStateState();
}

class _CustomSwitchStateState extends State<CustomSwitchState> with SingleTickerProviderStateMixin {

  PageController _pageController;
  int activePageIndex = 0;

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

  @override
  void initState() {
    super.initState();
    _pageController = PageController();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: SingleChildScrollView(
          physics: const ClampingScrollPhysics(),
          child: GestureDetector(
            onTap: () {
              FocusScope.of(context).requestFocus(FocusNode());
            },
            child: Container(
              width: MediaQuery.of(context).size.width,
              height: MediaQuery.of(context).size.height,
              child: Column(
                mainAxisSize: MainAxisSize.max,
                children: <Widget>[
                  Padding(
                    padding: const EdgeInsets.only(top: 20.0),
                    child: _menuBar(context),
                  ),
                  Expanded(
                    flex: 2,
                    child: PageView(
                      controller: _pageController,
                      physics: const ClampingScrollPhysics(),
                      onPageChanged: (int i) {
                        FocusScope.of(context).requestFocus(FocusNode());
                        setState(() {
                          activePageIndex = i;
                        });
                      },
                      children: <Widget>[
                        ConstrainedBox(
                          constraints: const BoxConstraints.expand(),
                          child: Center(child: Text("Place Bid"),),
                        ),
                        ConstrainedBox(
                          constraints: const BoxConstraints.expand(),
                          child: Center(child: Text("Buy Now"),),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            ),
          ),
        ));
  }

  Widget _menuBar(BuildContext context) {
    return Container(
      width: 300.0,
      height: 50.0,
      decoration: const BoxDecoration(
        color: Color(0XFFE0E0E0),
        borderRadius: BorderRadius.all(Radius.circular(borderRadius)),
      ),
      child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          children: <Widget>[
            Expanded(
              child: InkWell(
                borderRadius: BorderRadius.all(Radius.circular(borderRadius)),
                onTap: _onPlaceBidButtonPress,
                child: Container(
                  width: MediaQuery.of(context).size.width,
                  padding: EdgeInsets.symmetric(vertical: 15),
                  alignment: Alignment.center,
                  decoration: (activePageIndex == 0) ? const BoxDecoration(
                    color: Colors.green,
                    borderRadius: BorderRadius.all(Radius.circular(borderRadius)),
                  ) : null,
                  child: Text(
                    "Place Bid",
                    style: (activePageIndex == 0) ? TextStyle(color: Colors.white) : TextStyle(color: Colors.black),
                  ),
                ),
              ),
            ),
            Expanded(
              child: InkWell(
                borderRadius: BorderRadius.all(Radius.circular(borderRadius)),
                onTap: _onBuyNowButtonPress,
                child: Container(
                  width: MediaQuery.of(context).size.width,
                  padding: EdgeInsets.symmetric(vertical: 15),
                  alignment: Alignment.center,
                  decoration: (activePageIndex == 1) ? const BoxDecoration(
                    color: Colors.green,
                    borderRadius: BorderRadius.all(Radius.circular(borderRadius)),
                  ) : null,
                  child: Text(
                    "Buy Now",
                    style: (activePageIndex == 1) ? TextStyle(color: Colors.white, fontWeight: FontWeight.bold) : TextStyle(color: Colors.black, fontWeight: FontWeight.bold),
                  ),
                ),
              ),
            ),
          ],
        ),
    );
  }

  void _onPlaceBidButtonPress() {
    _pageController.animateToPage(0,
        duration: const Duration(milliseconds: 500), curve: Curves.decelerate);
  }

  void _onBuyNowButtonPress() {
    _pageController.animateToPage(1,
        duration: const Duration(milliseconds: 500), curve: Curves.decelerate);
  }

}

OUTPUT

A: If you want tab layout like this you can use this
Output:

import 'package:flutter/material.dart';
import 'package:icons_helper/icons_helper.dart';

class DetailScreen extends StatefulWidget {
  var body;
  String title = "";

  DetailScreen(this.body, this.title);

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

class _MainPageState extends State<DetailScreen> with TickerProviderStateMixin {
  late int _startingTabCount;

  List<Tab> _tabs = <Tab>[];
  List<Widget> _generalWidgets = <Widget>[];
  late TabController _tabController;

  @override
  void initState() {
    _startingTabCount = widget.body["related_modules"].length;
    _tabs = getTabs(_startingTabCount);
    _tabController = getTabController();
    super.initState();
  }

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
        bottom: TabBar(
          isScrollable: true,
          tabs: _tabs,
          controller: _tabController,
        ),
        flexibleSpace: Container(
          decoration: BoxDecoration(
            gradient: LinearGradient(
              colors: [
                Colors.grey,
                Colors.blue,
              ],
              stops: [0.3, 1.0],
            ),
          ),
        ),
        leading: IconButton(
          icon: Icon(Icons.arrow_back_ios),
          color: Colors.white,
          onPressed: () {
            Navigator.of(context, rootNavigator: true).pop(context);
          },
        ),
        actions: <Widget>[
          IconButton(
            icon: Icon(Icons.skip_previous),
            color: Colors.white,
            onPressed: () {
              goToPreviousPage();
            },
          ),
          Container(
            margin: EdgeInsets.only(right: 15),
            child: IconButton(
              icon: Icon(Icons.skip_next),
              color: Colors.white,
              onPressed: () {
                goToNextPage();
              },
            ),
          )
        ],
      ),
      body: Column(
        children: <Widget>[
          Expanded(
            child: TabBarView(
              physics: NeverScrollableScrollPhysics(),
              controller: _tabController,
              children: getWidgets(),
            ),
          ),
        ],
      ),
    );
  }

  TabController getTabController() {
    return TabController(length: _tabs.length, vsync: this)
      ..addListener(_updatePage);
  }

  Tab getTab(int widgetNumber) {
    return Tab(
      icon: Column(
        children: [
          if (widget.body["related_modules"][widgetNumber]["icon"].toString() ==
              "fa-comments-o") ...[
            Icon(
              Icons.comment_outlined,
            ),
          ] else if (widget.body["related_modules"][widgetNumber]["icon"]
                  .toString() ==
              "fa-map-marker") ...[
            Icon(
              Icons.location_on_rounded,
            ),
          ] else if (widget.body["related_modules"][widgetNumber]["icon"]
                  .toString() ==
              "fa-address-card") ...[
            Icon(
              Icons.contact_page_sharp,
            ),
          ] else ...[
            Icon(
              getIconUsingPrefix(
                name: widget.body["related_modules"][widgetNumber]["icon"]
                    .toString()
                    .substring(3),
              ),
            )
          ]
        ],
      ),
      text: widget.body["related_modules"][widgetNumber]["label"].toString(),
    );
  }

  Widget getWidget(int widgetNumber) {
    return Center(
      child: Text("Widget nr: $widgetNumber"),
    );
  }

  List<Tab> getTabs(int count) {
    _tabs.clear();
    for (int i = 0; i < count; i++) {
      _tabs.add(getTab(i));
    }
    return _tabs;
  }

  List<Widget> getWidgets() {
    _generalWidgets.clear();
    for (int i = 0; i < _tabs.length; i++) {
      _generalWidgets.add(getWidget(i));
    }
    return _generalWidgets;
  }

  void _updatePage() {
    setState(() {});
  }

  //Tab helpers

  bool isFirstPage() {
    return _tabController.index == 0;
  }

  bool isLastPage() {
    return _tabController.index == _tabController.length - 1;
  }

  void goToPreviousPage() {
    _tabController.animateTo(_tabController.index - 1);
  }

  void goToNextPage() {
    isLastPage()
        ? showDialog(
            context: context,
            builder: (context) => AlertDialog(
                title: Text("End reached"),
                content: Text("This is the last page.")))
        : _tabController.animateTo(_tabController.index + 1);
  }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Bootstrap class for not invalid-feedback Is there a class which I can use for representing !invalid-feedback? What I am trying to do is, I want to have a placeholder under my form input and tell the user that this field needs to only have 3 characters and if the validation fails, I will add a a div with a class of invalid-feedback. I want them to be mutually exclusive so it's either the placeholder or the invalid-feedback.
So for example,
<form:input path="ac" required="required"
    class="form-control text-uppercase" maxlength="3" />
Only three characters are allowed

AC is required

in the following block, if the user is either entering the data or if the value is valid, I want to show what's in the  tag, if the form is submitted and if there is a validation error, I want to show what's in the invalid-feedback div.
So, is there a class in Bootstrap which is basically !invalid-feedback? Is it valid-feedback? isValid? Can this be done with just using styles and not Javascript/jQuery?

A: There are Bootstrap classes to indicate a field has an error but since you're asking to display errors in a non-Bootstrap way (i.e. by hiding and showing different tags) you'll have to roll your own validation using Javascript.
Here is one way that monitors the status of the input field and hides/shows the  and div.invalid-feedback elements. (Note that this is just a proof-of-concept, and doesn't deal well with all possible ways of the user interacting with the input field.)

$('input').on('input', function() {
    if ($(this).val().length == 3) {
        $('.invalid-feedback').hide()
        $('small').show()
    } else {
        $('.invalid-feedback').show()
        $('small').hide()
    }
})

<form>
<input path="ac" required="required"
    class="form-control text-uppercase" maxlength="3" />
Only three characters are allowed

AC is required

</form>


text:
Q: Three columns layout - set left and right div's heigth according to center div
*

*I need to make a three columns css layout (without setting the height and width).

*The left and right div height need to set automatically according to the center div (center div height depends on its content)

I tried with position, height 100%, overflow, but something wrong, so I cleared my code and so for now here I'm standing:

.container {
  background-color: blue;
  overflow: hidden;
}

.left {
   background-color: green;
   float: left;
}

.right {
   background-color: yellow;
   float: left;
}

.center {
   background-color: red;
   float: left;
}

 < left

Holisticly underwhelm process-centric architectures via functionalized quality vectors. Collaboratively transform turnkey total linkage rather than value-added technologies.

Holisticly underwhelm process-centric architectures via functionalized quality vectors. Collaboratively transform turnkey total linkage rather than value-added technologies.

right >

thank you

A: Try this.
.container
   Display: inline-flex;
   Flex-direction: row;
If you want to center
  Justify-content: center.

A: An alternative to display:flex is display:table

.container {
  background-color: blue;
  display: table;
  width: 100%; /*optional*/
}
.container > div {
  display: table-cell;
  vertical-align: top;
}
.left {
  background-color: green;
  width: 75px; /*optional*/
}
.right {
  background-color: yellow;
  width: 75px; /*optional*/
  text-align:right;
}
.center {
  background-color: red;
}

< left

Holisticly underwhelm process-centric architectures via functionalized quality vectors. Collaboratively transform turnkey total linkage rather than value-added technologies.

Holisticly underwhelm process-centric architectures via functionalized quality vectors. Collaboratively transform turnkey total linkage rather than value-added technologies.

right >


text:
Q: Geolocation plugin permission alert on iPhone with PhoneGap Two time alert show first alert is correct but second alert generate with string with would like to use your current location.
How do you change the string on the alert saying:
/var/mobile/Applications/157EB70D-4AA7-826E-690F0CBE0F/appname.app/www/index.html
Someone having an idea?

A: Try to use following code on device ready:
document.addEventListener('deviceready', onDeviceReady, false);

function onDeviceReady() {
   navigator.geolocation.getCurrentPosition(onSuccess, onError);
}

function onSuccess(position) {
   //Retrieve latitude as: alert(position.coords.latitude);
   //Retrieve longitude as: alert(position.coords.longitude);
}

function onError(error) {
   console.log('code: ' + error.code + '\n' + 'message: ' + error.message + '\n');
}


text:
Q: java.sql.SQLException: Io exception: NL Exception was generated I am using spark-sql 2.4.1 while I am trying to connect the oracle db using my spark program

Spark Program

val o_url =//"jdbc:oracle:thin: etc ... it is correct and working
val query  ="( SELECT 1 FROM DUAL ) T";
val dfReader   = spark.read.format("jdbc")
       .option("url", o_url)
       .option("driver", "oracle.jdbc.OracleDriver")
       .option("user", "ABC")
       .option("password", "ZYX")
       .option("fetchsize","10000")

val ss = dfReader
                .option("inferSchema", true)
                .option("schema","LDF")
                .option("dbtable", query)
                .load();

println(" Table Count : "+ ss.count());
spark.close();

Ofcource I added the "ojdbc14.jar" jar in my class path.

I am getting below error
Error
java.sql.SQLException: Io exception: NL Exception was generated
  at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:112)
  at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:146)
  at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:255)
  at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:387)
  at oracle.jdbc.driver.PhysicalConnection.<init>(PhysicalConnection.java:414)
  at oracle.jdbc.driver.T4CConnection.<init>(T4CConnection.java:165)
  at oracle.jdbc.driver.T4CDriverExtension.getConnection(T4CDriverExtension.java:35)
  at oracle.jdbc.driver.OracleDriver.connect(OracleDriver.java:801)
  at org.apache.spark.sql.execution.datasources.jdbc.DriverWrapper.connect(DriverWrapper.scala:45)
  at org.apache.spark.sql.execution.datasources.jdbc.JdbcUtils$$anonfun$createConnectionFactory$1.apply(JdbcUtils.scala:63)
  at org.apache.spark.sql.execution.datasources.jdbc.JdbcUtils$$anonfun$createConnectionFactory$1.apply(JdbcUtils.scala:54)
  at org.apache.spark.sql.execution.datasources.jdbc.JDBCRDD$.resolveTable(JDBCRDD.scala:56)
  at org.apache.spark.sql.execution.datasources.jdbc.JDBCRelation.<init>(JDBCRelation.scala:115)
  at org.apache.spark.sql.execution.datasources.jdbc.JdbcRelationProvider.createRelation(JdbcRelationProvider.scala:52)
  at org.apache.spark.sql.execution.datasources.DataSource.resolveRelation(DataSource.scala:340)
  at org.apache.spark.sql.DataFrameReader.loadV1Source(DataFrameReader.scala:239)
  at org.apache.spark.sql.DataFrameReader.load(DataFrameReader.scala:227)
  at org.apache.spark.sql.DataFrameReader.load(DataFrameReader.scala:164)

what is wrong here ? How to fix this issue ?

A: It was with
val o_url =//"jdbc:oracle:thin: etc ... it is correct and working
It was earlier

val o_url ="jdbc:oracle:thin:@(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)...
  ; ";

I corrected it as below by removing ";" inside quotes.

val o_url ="jdbc:oracle:thin:@(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)...
  ";


text:
Q: How get access to hidden ItemView in a RecyclerView Hey thanks to stop by !
So there is my issue I got a RecyclerView that can have as much as item i want. And in this when I select on item it grows to show that he is selected. And when I select it I need to unselect my previous selected. But if he is not in view I can't access the view.
I try to put logic to know if it as to be selected or not when he is bind again, but some of the item arn't accessable and don't redraw them self when you swipe so they stay stuck as selected...
Does any one see a workaround?
Thanks for your time, I know there is no code here. But I don't know what I can show you because is more a need of idea then implementing solution.

A: It sounds like you're storing the selected state of items in the RecyclerViewHolders themselves and you shouldn't do that.  The state data that shows up in RecyclerViewHolders should be stored outside of the ViewHolders themselves and passed in as needed during update events.  When you ViewHolders go into and out of view, they will be reset and recreated outside of you control, so a ViewHolder needs to be able to go from it's initial state to a viewable state at any time and you can't rely on the state of a ViewHolder to be maintained.


text:
Q: How Many Prime Number exist? Something is wrong with my code that i can't figure it out, will you help me to find my mistake? Thank you!
/// Calculate Prime
private static int countPrimes(int number){
    int count =0;
    for(int i=1; i<=MAX_PRIME; i++) {
        if(isPrime(i)){
        count++;
        }
    }
    System.out.println("Exactly "+  count + " prime numbers exist between "+number + " and 1000.");
return number;
}

here is my result:
Exactly 180 prime numbers exist between 1 and 1000. Which is wrong and has to be 168!!!

A: It seems that your implicit parameter, int number, is never used in your program.
Try this code:
private static int countPrimes(int number){
    int count =0;
    int countPrimes=0;
    if(number<2)
       return 0;
    for(int i=2; i<=number; i++) { //start i=2, because you know that 1 is not a prime number.
       for(int j=1; j<=i; j++){
            if(i%j==0)
                count++;
        }
        if(count ==2)
            countPrimes++;
        count=0;
    }
    return number;
}

Then, in your runner method, call:
int numOfPrimes = countPrimes(10000);

In this, you can vary what number you want to count up to. In this example it counts the primes up to 10000.
int numOfPrimes = countPrimes(100);

This will count primes up to 100. If you want to keep track of the primes, in your program you could add:
ArrayList<Integer> listOfPrimes = new ArrayList<Integer>();
private static int countPrimes(int number){
    int count =0;
    int countPrimes=0;
    if(number<2)
       return 0;
    for(int i=2; i<=number; i++) { //start i=2, because you know that 1 is not a prime number.
       for(int j=1; j<=i; j++){
            if(i%j==0)
                count++;
        }
        if(count ==2){
            countPrimes++;
            listOfPrimes.add(i);
        }
        count=0;
    }
    return number;
}

In order to retrieve your numbers you could do something like this:
System.out.println("Exactly "+  countPrimes(number) + " prime numbers exist between "+ "1" + " and " + number + ".");
System.out.println("These numbers are: ");
for(int i =0; i<listOfPrimes.size();i++){
    System.out.println(listOfPrimes.get(i));
}

A: The prime count can be found using "Sieve of Eratosthenes".
http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
Following program will count the no. of primes given the limit.
I am taking the limit = 1000.
public class CountPrime {

public static void main(String[] args) {

boolean[] isPrime     = null;
int       Tprimes     = 0;
final int UPPER_BOUND = Integer.parseInt("1000");

/*------------------------------------------------------+
| Assuming all to prime                                 |
+------------------------------------------------------*/
isPrime = new boolean[UPPER_BOUND + 1];
for (int Tindex = 2; Tindex <= UPPER_BOUND; Tindex++) {
  isPrime[Tindex] = true;
} /*end for*/

/*------------------------------------------------------+
| Mark Non-Primes given the Upper Bound                 |
+------------------------------------------------------*/
for (int Tindex = 2; Tindex*Tindex <= UPPER_BOUND; Tindex++) {
  /*------------------------------------------------------+
  | For any prime all the multiples are non-prime         |
  +------------------------------------------------------*/
  if (isPrime[Tindex]) {
    for (int Tver = Tindex; Tindex*Tver <= UPPER_BOUND; Tver++) {
      isPrime[Tindex*Tver] = false;
    } /*end for*/
  } /*end if*/
} /*end for*/

/*------------------------------------------------------+
| Now, as we are done count the total primes            |
+------------------------------------------------------*/
for (int Tindex = 2; Tindex <= UPPER_BOUND; Tindex++) {
  if (isPrime[Tindex]) {
    Tprimes++;
  } /*end if*/
} /*end for*/
System.out.println("Total No. of Primes[" + Tprimes +
                   "], given the limit[" + UPPER_BOUND + "]");
} /*END OF main*/

} /*END OF CountPrime*/

Output:
Total No. of Primes[168], given the limit[1000]

A: What the function isPrice()? is it a function to check that a integer number is prime number or not? I think that if you have it, you just need to do like this:
 for(int i=1; i<=MAX_PRIME; i++) {
     if(isPrime(i)){
        count++
     }
 }
 return count;

A: I think you return a wrong variable instead of count, and if countPrimes means to calc the  count of primes between nunber and MaxPrime, then you should count from number, like this:
for (int i = number; i<=MAX_PRIME;i++)


text:
Q: Convert Image to ASCII Art I have used a tutorial to program this Image to ASCII Art converter, but it gives me an error. Here is the code:
import PIL.Image
from tkinter import filedialog

# Ascii characters
ASCII_CHARS = ["@", "#" ,"S" ,"%" ,"?" ,"*" ,"+" , ";", ":", "," "."]

def resize_image(image,new_width=100):
    width,height =image.size
    ratio = height / width / 1.65
    new_height = int(new_width*ratio)
    resized_image = image.resize((new_width,new_height))
    return(resized_image)

# convert each pixel to grayscale
def grayscaler(image):
    grayscale_image = image.convert("L")
    return(grayscale_image)

#convert pixels to a string of ASCII characters
def pixels_to_ascii(image):
    pixels = image.getdata()
    characters = "".join([ASCII_CHARS[pixel // 25]for pixel in pixels])
    return(characters)

def main(new_width=100):
    # Get image path
    path = filedialog.askopenfilename(title="Select an image", filetypes=(("Image File", "*.png"),("all files", "*.*")))
    try:
        image = PIL.Image.open(path)
    except:
        print(path, "is not a valid pathname to an image")

    # convert image to ascii
    new_image_data = pixels_to_ascii(grayscaler(resize_image(image)))

    # format
    pixel_count = len(new_image_data)
    ascii_image = "\n".join(new_image_data[i:(i+new_width)] for i in range(0, pixel_count, new_width))

    # print result
    print(ascii_image)

    # save result to "ascii_image.txt"
    with open("ascii_image.txt", "w") as f:
        f.write(ascii_image)

main()

It is suposed to be printing and saving the ascii art. Instead of that, it gives me this error ay line 34, and 22:
Traceback (most recent call last):
  File "c:\Users\Forna\Documents\PYTHON\Image to Ascii\main.py", line 47, in <module>
    main()
  File "c:\Users\Forna\Documents\PYTHON\Image to Ascii\main.py", line 34, in main
    new_image_data = pixels_to_ascii(grayscaler(resize_image(image)))
  File "c:\Users\Forna\Documents\PYTHON\Image to Ascii\main.py", line 22, in pixels_to_ascii
    characters = "".join([ASCII_CHARS[pixel // 25]for pixel in pixels])
  File "c:\Users\Forna\Documents\PYTHON\Image to Ascii\main.py", line 22, in <listcomp>
    characters = "".join([ASCII_CHARS[pixel // 25]for pixel in pixels])
IndexError: list index out of range

It would be very nice if someone could help me.

A: The error was in
ASCII_CHARS = ["@", "#" ,"S" ,"%" ,"?" ,"*" ,"+" , ";", ":", "," "."]
There wasn't a , after "," my bad


text:
Q: How to install Helm 3 Chart on Air Gapped System I am trying to install a helm chart on an air gapped system. The chart should be pulling an image from a private docker registry and deploy to the kubernetes cluster (both also on the air gapped system). My chart passed linting but when I try to install it, I keep seeing the error:
$ helm install my-mongodb . --debug
install.go:172: [debug] Original chart version: ""
install.go:189: [debug] CHART PATH: /opt/helm-charts/my-mongodb

Error: unable to build kubernetes objects from release manifest: the server could not find the requested resource
helm.go:94: [debug] the server could not find the requested resource
unable to build kubernetes objects from release manifest
helm.sh/helm/v3/pkg/action.(*Install).Run
    /home/circleci/helm.sh/helm/pkg/action/install.go:257
main.runInstall
    /home/circleci/helm.sh/helm/cmd/helm/install.go:242
main.newInstallCmd.func2
    /home/circleci/helm.sh/helm/cmd/helm/install.go:120
github.com/spf13/cobra.(*Command).execute
    /go/pkg/mod/github.com/spf13/cobra@v1.0.0/command.go:842
github.com/spf13/cobra.(*Command).ExecuteC
    /go/pkg/mod/github.com/spf13/cobra@v1.0.0/command.go:950
github.com/spf13/cobra.(*Command).Execute
    /go/pkg/mod/github.com/spf13/cobra@v1.0.0/command.go:887
main.main
    /home/circleci/helm.sh/helm/cmd/helm/helm.go:93
runtime.main
    /usr/local/go/src/runtime/proc.go:203
runtime.goexit
    /usr/local/go/src/runtime/asm_amd64.s:1373

Helm is installed:
$ helm version
version.BuildInfo{Version:"v3.3.4", GitCommit:"a61ce5633af99708171414353ed49547cf05013d", GitTreeState:"clean", GoVersion:"go1.14.9"}

So is Kubernetes:
$ kubectl version
Client Version: version.Info{Major:"1", Minor:"5", GitVersion:"v1.5.2", GitCommit:"269f928217957e7126dc87e6adfa82242bfe5b1e", GitTreeState:"clean", BuildDate:"2017-06-06T13:19:52Z", GoVersion:"go1.7.6", Compiler:"gc", Platform:"linux/amd64"}
Server Version: version.Info{Major:"1", Minor:"5", GitVersion:"v1.5.2", GitCommit:"269f928217957e7126dc87e6adfa82242bfe5b1e", GitTreeState:"clean", BuildDate:"2017-06-06T13:19:52Z", GoVersion:"go1.7.6", Compiler:"gc", Platform:"linux/amd64"}

$ kubectl config get-clusters
NAME
dev-cluster

$ kubectl get node -n kube-system
NAME          STATUS    AGE
kube-node01   Ready     14d
kube-node02   Ready     14d
kube01        Ready     14d

Here is my Helm Chart.yaml:
apiVersion: v2
name: my-mongodb
description: A Helm chart for My MongoDB Kubernetes
type: application
version: 0.1.0
appVersion: 5.0.0-1
annotations:
  category: Database

And my values.yaml
replicaCount: 1

image:
  repository: docker01.dev.local:5000/my-mongodb
  pullPolicy: Always
  pullSecrets:
     - name: regcred

serviceAccount:
  create: true
  annotations: {}
  name: ""

podAnnotations: {}

podSecurityContext: {}

securityContext: {}

service:
  type: ClusterIP
  port: 80

ingress:
  enabled: false
  annotations: {}
  hosts:
    - host: chart-example.local
      paths: []
  tls: []

resources: {}

autoscaling:
  enabled: false
  minReplicas: 1
  maxReplicas: 100
  targetCPUUtilizationPercentage: 80

nodeSelector: {}

tolerations: []

affinity: {}

My docker image successfully runs in a docker container, so I'm fairly confident the image isn't the issue. What am I doing wrong?
EDIT: I am running the helm install command at: /opt/helm-charts/my-mongodb
This is the location of the Charts.yaml file. The file structure is:
my-mongodb
 - Chart.yaml
 - values.schema.json
 - values.yaml
 - charts
 - templates
   - deployment.yaml
   - _helpers.tpl
   - hpa.yaml
   - ingress.yaml
   - NOTES.txt
   - serviceaccount.yaml
   - service.yaml
   - tests
     - test-connection.yaml

This chart was created with the command: helm create my-mongodb and then I edited the Charts.yaml, values.yaml and deployment.yaml files
Here is the deployment.yaml file as well:
apiVersion: apps/v1
kind: Deployment
metadata:
  name: {{ include "my-mongodb.fullname" . }}
  labels:
    {{- include "my-mongodb.labels" . | nindent 4 }}
spec:
{{- if not .Values.autoscaling.enabled }}
  replicas: {{ .Values.replicaCount }}
{{- end }}
  selector:
    matchLabels:
      {{- include "my-mongodb.selectorLabels" . | nindent 6 }}
  template:
    metadata:
    {{- with .Values.podAnnotations }}
      annotations:
        {{- toYaml . | nindent 8 }}
    {{- end }}
      labels:
        {{- include "my-mongodb.selectorLabels" . | nindent 8 }}
    spec:
      {{- with .Values.imagePullSecrets }}
      imagePullSecrets:
        {{- toYaml . | nindent 8 }}
      {{- end }}
      serviceAccountName: {{ include "my-mongodb.serviceAccountName" . }}
      securityContext:
        {{- toYaml .Values.podSecurityContext | nindent 8 }}
      containers:
        - name: {{ .Chart.Name }}
          securityContext:
            {{- toYaml .Values.securityContext | nindent 12 }}
          image: "{{ .Values.image.repository }}:{{ .Values.image.tag | default .Chart.AppVersion }}"
          imagePullPolicy: {{ .Values.image.pullPolicy }}
          ports:
            - name: http
              containerPort: 8080
              protocol: TCP
            - name: mongoDB
              containerPort: 27017
              protocol: TCP
            - name: mongoDBShardSvr
              containerPort: 27018
              protocol: TCP
            - name: mongoDBConfigSvr
              containerPort: 27019
              protocol: TCP
          livenessProbe:
            httpGet:
              path: /
              port: http
          readinessProbe:
            httpGet:
              path: /
              port: http
          resources:
            {{- toYaml .Values.resources | nindent 12 }}
      {{- with .Values.nodeSelector }}
      nodeSelector:
        {{- toYaml . | nindent 8 }}
      {{- end }}
      {{- with .Values.affinity }}
      affinity:
        {{- toYaml . | nindent 8 }}
      {{- end }}
      {{- with .Values.tolerations }}
      tolerations:
        {{- toYaml . | nindent 8 }}
      {{- end }}

A: It is probably a version compatibility issue. Helm v3.3.x is not compatible with Kubernetes v1.5.2.
As per Supported Version Skew:

When a new version of Helm is released, it is compiled against a
particular minor version of Kubernetes. For example, Helm 3.0.0
interacts with Kubernetes using the Kubernetes 1.16.2 client, so it is
compatible with Kubernetes 1.16.
|---------------------|--------------------------------------|
|      Helm Version   |     Supported Kubernetes Versions    |
|---------------------|--------------------------------------|
|         3.4.x       |           1.19.x - 1.16.x            |
|         3.3.x       |           1.18.x - 1.15.x            |
|         3.2.x       |           1.18.x - 1.15.x            |
|---------------------|--------------------------------------|

More than that, you are using apiVersion: apps/v1 for your Deployment version. This API version was introduced on Kubernetes v1.9.0.


text:
Q: Process responding freezing application I'm trying to detect if process is responding, and I'm doing it with System.Diagnostics
But the problem is when the process is not responding my form freezes, it should show message box with No in it but it just freezes while if the process is active it displays Yes as it should.
This is what I've done so far:
private void timer1_Tick(object sender, EventArgs e)
{
    Process[] processes = Process.GetProcessesByName("Anticheat");

    foreach (Process p in processes)
    {
        if (p.Responding)
        {
            MessageBox.Show("Yes");
        }
        else
        {
            MessageBox.Show("No");
        }
    }
}

And yeah I'm checking it with a timer that runs every 5 seconds.

A: A workaround will be to use task with a max wait timeout for getting the response
    private void timer1_Tick(object sender, EventArgs e)
    {
        var processes = Process.GetProcessesByName("Anticheat");
        foreach (var p in processes)
        {

            var task = Task.Factory.StartNew(() => p.Responding);

            const int maxWaitForResponse = 1000; //ms
            var processResponding = task.Wait(maxWaitForResponse) && task.Result;

            MessageBox.Show(processResponding ? "Yes" : "No");
        }
    }


text:
Q: InvalidPDFException when viewing the Chinese content PDF using Primeface DefaultStreamedContent Using Primefaces 6.0 and
JAVA 1.8
Using below code to view the PDF document using DefaultStreamedContent.
<pe:documentViewer locale="en"  height="600" value="#{documentMBean.pdfFile}" id="pdfDocViewer" >

Below code to get the Stream as pdfFile.
byte[] documentData = null;
setPdfFile(new DefaultStreamedContent());
documentData =//Getting the byte array from DB
getPdfFile().setStream(new ByteArrayInputStream(documentData));
getPdfFile().setContentType("application/pdf");
getPdfFile().setContentEncoding("UTF-8");

When I upload and store a PDF file which contents Chineese charactes getting below exception in PDF Viewer.

PDF.js v1.0.21 (build: f954cde) Message: InvalidPDFException

Note: Plain text PDF which contents English characters working fine and able to view the PDF.
I have tried to set different character-encoding such as UTF-8,UTF-16
Please assist me how to resolve above exception. Where I can find PDF.js for further analysis ?


text:
Q: Process.kill does not seem to work The following code hangs in the call to WaitForExit at the end. It terminates cleanly if I remove the 1 second long sleep. Could someone please tell me what to do so the process would die shortly after I call Kill() on it? Many thanks.
    let processStartInfo = System.Diagnostics.ProcessStartInfo("c:/cygwin/bin/bash.exe", "-c yes")
    processStartInfo.CreateNoWindow <- true
    processStartInfo.UseShellExecute <- false
    processStartInfo.RedirectStandardOutput <- true
    processStartInfo.RedirectStandardInput <- false
    processStartInfo.RedirectStandardError <- true

    use proc = new System.Diagnostics.Process ()
    proc.StartInfo <- processStartInfo

    let f _ = ()
    proc.OutputDataReceived.Add f
    proc.ErrorDataReceived.Add f

    if not (proc.Start()) then
        failwithf "Could not start"

    proc.BeginErrorReadLine ()
    proc.BeginOutputReadLine ()

    // the process terminates fine without this
    System.Threading.Thread.Sleep (1000)

    printf "Waiting to die"

    proc.Kill ()              // this does not seem to work
    proc.CancelOutputRead ()
    proc.CancelErrorRead ()
    proc.WaitForExit()        // execution gets stuck here, apparently forever

A: I don't know F#, but this code has a few very strange things; Process.Read() is a blocking call, so you either have to make them asynchronous or call .ReadToEnd() instead if you want to wait until the thing redirected to finishes. I would use proc.Dispose() or put it in a using block in C# instead of calling proc.kill(), which should be done after WaitForExit().
Check out my answer to Opening a DOS Console.
Also check out this reply saying that if you redirect both stdOut and stdErr, you must make at least one asynchronous.


text:
Q: How can I test an application for thread safety? I have a working C++ application, using the same variables and objects in different threads without thinking about the consequences. I want to improve the application to be thread-safe (using mutex, atomic, etc...) - how can I test that the things I want to implement actually work?
My point is, that my application is already working fine without this - but I'm pretty sure it's just working because a possible error has not happend yet, and not because I have done something to prevent an error.

A: The same way that you can test for any undefined behaviour. Write comprehensive tests, run them with sanitisers, and hope for the best.
For the case of thread safety in particular, you'll want to write tests that operate on shared data in parallel and use a thread sanitiser.
Always keep in mind that no test is sufficient to prove that there is no undefined behaviour in the program.


text:
Q: Run tests in Azure DevOps Build Pipeline I would like to make a build pipeline in Azure DevOps including tests/code coverage.
For that, I created a very basic Java project:
package main:
    - main class
    - Calculator class
          - add method
package test:
    - CalculatorTest class
        - addTest method

It's very basic, just for me to understand how test in pipeline work. I don't use maven or things like that. For the tests, I'm using JUnit framework.
In Azure DevOps pipeline, I imported my project from Github, and started to create the pipeline. I start from the starter template, which contains:
trigger:
- master

pool:
  vmImage: 'Ubuntu-16.04'

steps:
- script: echo Hello, world!
  displayName: 'Run a one-line script'

- script: |
    echo Add other tasks to build, test, and deploy your project.
    echo See https://aka.ms/yaml
  displayName: 'Run a multi-line script'

My question is:
What do I have to do to run my tests automatically ?
I've seen several examples on the Microsoft documentation but it was always for "complex" projects (like with maven etc.). And ass I'm new with Azure DevOps and YAML file/syntax, I'm lost.
I want to run my tests after each commit, and see the results (test + code coverage) in the pipeline summary, like it is described here : https://learn.microsoft.com/en-us/azure/devops/pipelines/test/review-continuous-test-results-after-build?view=azure-devops#view-test-results-in-build
Thanks a lot.
PS: For the moment I'm just focusing on tests but once it will be done I also would like to publish build artefacts. I would like the confirmation of that:
- task: PublishBuildArtifacts@1

Is that line correct ?
EDIT
The line - task: PublishBuildArtifacts@1 seems to work correclty but I have the following warning:
Directory '/home/vsts/work/1/a' is empty. Nothing will be added to build artifact 'drop'.

What does it mean ?

A: Finally I used the visual designer (like explained here: https://learn.microsoft.com/en-US/azure/iot-edge/how-to-ci-cd) and I added the Maven task.
I upgraded my project to use Maven, which is well integrated in Azure Devops.


text:
Q: Submitting comments with PHP (cURL) <?php
$mycurl = curl_init();
curl_setopt_array($mycurl,
    [
        CURLOPT_URL => "https://example.com",
        CURLOPT_RETURNTRANSFER => TRUE,
        CURLOPT_TIMEOUT => 4,
        CURLOPT_FOLLOWLOCATION => TRUE,
        CURLOPT_POST => TRUE,
        CURLOPT_POSTFIELDS => ["Name" => "Example", "Email" => "Example@gmail.com", "Comment" => "Example"]
    ]
);
$result = curl_exec($mycurl);
curl_close($mycurl); ?>

My code is wrong I know, I just want learn PHP.
How can I fix my code?
I want really simple thing.
I just want to comment on the website with the information I sent.

A: https://example.org does not support comments. maybe try curling a service that actually support comments instead, like Discord.


text:
Q: Dealing with commas in csv files csv-river plugin I am trying to index data present in csv file to elasticsearch server. The problem is the string itself contain multiple "," so during indexing it is giving indexoutofbound exception.
How to handle commas using csv-river plugin.
Edit:
The example file would be:
MESSAGE_ID,PARENT_MESSAGE_ID,THREAD_ID,FORUM_ID,FORUMINDEX,USER_ID,SUBJECT,BODY,MODVALUE,FORUM_NAME,CATEGORY_NAME,LIKES,DISLIKES,IS_ROOT_MESSAGE,IS_QUESTION
244,195,103,4,3,341,Re: The most stupidest program I've ever seen--Amazon,"I know nothing of your case, but I do know that throwing around terms like ""stupid idiot"" doesn't exactly help your side any.",1,"Order Management, Shipping, Feedback & Returns",Sell on Amazon,,,no,no

A: you need to enclose your fields in quotes. If the field contains a quote, you need to escape it with a preceding quote.
For example:
"field1","field2","field3 with, commas","field4","field ""5"" with quotes","field6"


text:
Q: How do I create a native Debian package for static files? I have a need to Debianize some static resources for a software project but am confused by the available information and could use some guidance in doing so. Here are the materials I've been reading:

*

*Rolling your own Debian packages

*Debian New Maintainer's Guide

*Debian Library Packaging Guide

*Debian Mentors FAQ
The Debian New Maintainer's Guide seems the most apropos, especially this chapter, but it's didactic presentation is not effective for me; it reads more as a re-learning reference than a guide for the unknowing. Much of the information I've found is likewise geared to getting packages included in a public repository which I do not need. To make it that some kindly folk might show me the way, I've created a small project statrec which exemplifies the type of package I need to create. It's source tree looks like so:
statrec/
├── LICENSE
├── README.md
├── share
│   ├── gilgamesh.txt
│   └── thoreau.txt
└── VERSION

I need to but am unable to deduce how to:

*

*install statrec/share to /usr/share/statrec/VERSION/,

*create or modify a symlink from /usr/share/statrec/current/ to /usr/share/statrec/VERSION/ and then

*uninstall previous versions of statrec.

I understand how to accomplish some of this, maybe which tools to use but feel rather paralized by the surfeit of information.

A: I would say easiest thing would be to:

*

*Create a makefile, that will install the files as you want them honoring any DESTDIR setting and do nothing for default target. Something along the lines of:
all: # nothing to build

install:
    cp -r share/* $(DESTDIR)/usr/share/statrec/$(VERSION)

The DESTDIR thing is important; it will not be installing to the system, but instead to a temporary directory that dpkg will than pack up. All symlinks must point to the final destinations (without $(DESTDIR) prefix).

*Let dh_make --native do it's business (it will create another makefile debian/rules that will call the first makefile).

*Look at the files under debian. Especially debian/changelog may need editing (it's where debuild /dpkg-buildpackage get the version number from, so it must be filled in).
I believe debuild uses fakeroot automatically, for dpkg-buildpackage you have to specify it manually. Don't even think about running it as real root.

*Use debuild or dpkg-buildpackage -rfakeroot to build it
No need to care for uninstalling as dpkg is going to handle that.
Update: I suggest dh_make --native, because I understood the question is for simply installing a handful of data files on a handful of debian systems. If it should be distributed, I suggest simply going to ask on the irc.debian.org#debian IRC channel and probably leaving it up to Debian Developer (only Debian Developers may upload to Debian archive and they usually want to handle the packaging themselves).
Also if it's part of software rather than stand-alone bunch of data files, the installation should be part of the general installation of the software using one common makefile, there should be just one Debian source package and just the debian/control and debian/*.files should specify which files go to the application package (which is "Architecture: any") and which files go to the data package (which is "Architecure: all" and usually gets suffix -data).

A: I found saurik's (of cydia/jailbreak fame) "Hosting a Cydia Repository" guide useful for creating your own .deb files. Have a look at it here: http://www.saurik.com/id/7

A: You should read section 15.2.2 in the debian-handbook.
I found it helpfull to just create a .install file and skip that Makefile part, for my own project


text:
Q: Horizontal scroll View not scroll? i am working with a react native project but i have a problem that is my horizontal scroll view dont want to scroll it working with ios but android no, i am working with native base tabs so i have two screens the first with vertical scrolling works fine but the second with horizontal dont work do you have any idea ? i tried to add nestedScrollEnabled props but not working
tabs code
 <Tabs
   tabBarUnderlineStyle={tabBarUnderlineStyle}
   tabContainerStyle={tabContainerStyle}>
   <Tab
     heading={strings.info}
     tabStyle={tabStyle}
     activeTabStyle={tabStyle}
     textStyle={textStyle}
     activeTextStyle={activeTextStyle}>
     <Info />
   </Tab>
   <Tab
     heading={strings.state}
     tabStyle={tabStyle}
     activeTabStyle={tabStyle}
     textStyle={textStyle}
     activeTextStyle={activeTextStyle}>
     <State />
   </Tab>
 </Tabs>

and here is the screen that i have problem with
 <View style={container}>
   <View style={itemsContainer}>
     <View>
       <ScrollView horizontal nestedScrollEnabled={true}>
         <HeaderItem label={Strings.ca} />
         <HeaderItem label={Strings.packs} />
         <HeaderItem label={Strings.terme} />
         <HeaderItem label={Strings.sinistre} />
         <HeaderItem label={Strings.attestation} />
       </ScrollView>
     </View>
   </View>
 </View>

A: import React, { Component } from 'react';
import { View, StyleSheet } from 'react-native';
import { TabViewAnimated, TabViewPage, TabBarTop } from 'react-native-tab-view';

export default class TabViewExample extends Component {
  state = {
    index: 0,
    routes: [
      { key: '1', title: 'First' },
      { key: '2', title: 'Second' },
    ],
  };

  _renderScene = ({ route }) => {
    switch (route.key) {
    case '1':
      return <View style={{ flex: 1, backgroundColor: '#ff4081' }} />;
    case '2':
      return <View style={{ flex: 1, backgroundColor: '#673ab7' }} />;
    default:
      return null;
    }
  };

  _renderPage = (props) => <TabViewPage {...props} renderScene={this._renderScene} />;

  render() {
    return (
      <TabViewAnimated
        style={{ flex: 1 }}
        navigationState={this.state.navigation}
        renderScene={this._renderPage}
        renderHeader={this._renderHeader}
        onRequestChangeTab={index => this.setState({ index })}
      />
    );
  }
}


text:
Q: Save a table in ascending order in order to avoid overlapping proportional circles (QGIS) Is there a quick way to sort an attribute table in QGIS in ascending order permanently and save it? When you make a map with proportional circles in QGIS the circles overlaps between each other according to their sorting order. I want the smaller circle above the bigger which is why I think sorting can solve this issue.
Note: If I click on the header, the table will be sorted in ascending order using the clicked column. However, if I save it that way and I open it again nothing has changed about row order.

A: Finally, that is a very easy treatment with the MMQGIS plugin (Quantum GIS Plugin Repository). It allows to rewrite on another table using selected column and chosen order.

It also works for the circles problem


text:
Q: Some seconds delay on starting sending Voip with Android.net.rtp I implemented an Android app that uses Voip by Android.net.rtp library.
It simply gets voice from device microphone and sends it in Voip (to another Android or to a PC receiver).
The problem is that on some devices the voip trasmission start after 2–3 seconds. I don't mean that there is a delay of 2–3 seconds in delivering packets, I mean that the first 2–3 seconds of voice are not sended. After those 2–3 seconds everything works properly.
The strange thing is that it happens only on some android device, and it is not a problem of device performance or Android version. For example it happens on a very old device and in a new one, while it doesn't happen in another very old device and in another new one…
I thought to some Android service/functionality that delays mic capture, but I didn't find out anything at the moment…
In the following, the code I use to send Voip, it is a classical code:
myAudioStream = new AudioStream(myIPAddress);
myAudioStream.setCodec(AudioCodec.PCMU);
myAudioGroup = new AudioGroup();
myAudioManager = (AudioManager) myContext.getSystemService(Context.AUDIO_SERVICE);

myAudioGroup.setMode(RtpStream.MODE_SEND_ONLY);
myAudioStream.join(null);
myAudioStream.setMode(RtpStream.MODE_SEND_ONLY);
myAudioStream.associate(ipAddress_Receiver, port_Receiver);
myAudioStream.join(myAudioGroup);
myAudioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);
myAudioManager.setSpeakerphoneOn(false);
myAudioManager.setMicrophoneMute(false);

A: Check if you can disable ICE and/or STUN in Android.net.rtp. These are usually responsible for the delay at media setup.

A: after some debugging I discovered that the AudioManager is introducing the delay in the setMode call:
myAudioManager.setMode(AudioManager.MODE_IN_COMMUNICATION))

The strange thing is that it depends from the device. With some devices it can introduce also 2-3 seconds, with other devices no delay is introduced.
See similar answer in:
Is there any significant delay in initializing AudioTrack on Android?
Finally I found out this solution, setting:
myAudioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);

in the costructor of my class, then only once. I invoke the costructor on starting of my App, when I didn't start the voice TX yet.
In this way, when I have to speak I don't have to loose those seconds...
Hope to be usefull for somobedy else.


text:
Q: TypeORM makes strange query I just want to modify data value to "qwer".
But TypeORM makes query like:
{
    "sql": "UPDATE table SET data = 0 = 'q', 1 = 'w', 2 = 'e', 3 = 'r' WHERE id IN (1)",

    "code": "ER_BAD_FIELD_ERROR",
    "errno": 1054,
    "sqlMessage": "Unknown column '1' in 'field list'"
}

const repository = await connection.getRepository(Table);
const result = await repository.findOne({ where: { id: 1 } });
result.data = "qwer";
await repository.save(result);


text:
Q: How do I modify Docusaurus appearances of the blog from a component library? Creating Modified Blog Entries
I am new to React, and very much to Docusaurus, however, I've managed to get a decent looking DS site going. I am trying to capture some simple snippets to as "blog entries", just small factual snippets, etc. simple project summaries. I've hit the limit of the Docusaurus.config options and not sure how to expand the out of box components.
How do I begin to alter and edit Docusaurus to change the Blog page to be like "Cards" in component-speak? Ive seen some example in Infima, but not sure how to bridge that gap?
How can I easily replicate the Announcement Bar to also be at the bottom, like a Banner?
Thank You!

A: One possible arena for you to use is Bootstrap — specifically React-Bootstrap. They have a card component you could use where you link individual blog entries to that card. If you're comfortable with JavaScript, there's probably an automation you can build there, but hand-coded text is somewhat part and parcel with static-site generators.
If you want a different solution with the CSS code in your src file outright, CSSCodeLab has a React Card layout entry with an attached source code file. Some hand-coded text required, and not automatically integrated with a separate blog setup, but YMMV.
Otherwise Docusaurus' Showcase page does provide the card formatting. The source code for the page (coded at index.tsx) as well as the components are available.


text:
Q: Calculate probability of a state after depolarization Let's say I have a particle in the quantum state $|+\rangle = \frac{1}{\sqrt{2}}(|0\rangle + |1\rangle)$, represented as a density operator (1st matrix) that went through a depolarizing chanel (2nd matrix). Let's call the depolarized matrix $D_p$.
$$
\begin{bmatrix}
.5 & .5 \\
.5 & .5
\end{bmatrix}
\rightarrow
\begin{bmatrix}
.5 & .43 \\
.43 & .5
\end{bmatrix}
$$
Now, I have two of these $D_p$, and their resulting product state is:
$$
D_p^{\otimes 2} = \begin{bmatrix}
.5 & .43 \\
.43 & .5
\end{bmatrix}
\otimes
\begin{bmatrix}
.5 & .43 \\
.43 & .5
\end{bmatrix}.
$$
Now, if I want want to calculate the probability of finding some state $|\psi\rangle = |0\rangle \otimes |0\rangle$ in the above mentioned product system, then this is what I do:
$$
p(|\psi\rangle | D_p^{\otimes 2}) = trace(\psi\rangle\langle \psi | D_p^{\otimes 2}).
$$
As you can see, calculating this trace is a $O(N^3)$ complexity operation and becomes very slow for even a small number of particles, i.e. for $D_p^{\otimes 10}$ or higher. Is there a principled way to calculate these probabilities? Without using any matrix multiplication? TIA.

Cross-Posted on quantumcomputing.SE

A: As long as your final state is a product state, everything is a product, and the probabilities for the individual qubits will just multiply. So compute the probabilities for each qubit to be in the respective state and just multiply them.
But even if this is not the case, you can compute $\langle \psi\vert D_p^{\otimes k}\vert\psi\rangle$ rather than the trace, then it only scales as $O(N^2)$, $N=2^k$.
Finally, you could use that $D_p^{\otimes k}$ is a tensor product and multiply $\vert\psi\rangle$ with one $D_p$ at a time.  Then, it is easy to see that each of these operations only sums over one index with $2$ settings, which takes $2N$ operations, so the total number of operations is $2kN = O(kN) = O(N\log(N))$.


text:
Q: Como ler uma quantidade aleatória de inteiros em C? Eu preciso criar uma forma de ler inteiros em um mesmo input, sendo que a quantidade de inteiros inseridos é aleatória toda vez que se executa o programa.
Eu tentei realizar o seguinte algoritmo:
#include <stdio.h>
#include <stdlib.h>

int main()
{
    long int numero, i, vetor[100000];

    i = 0;
    while(scanf("%li", &numero) != EOF)
        vetor[i++] = numero;

    while(i > 0)
        printf("%li ", vetor[i--]);

    return 0;
}

Entretanto, em uma máquina, o 1º while nunca termina. E em outra máquina, obtenho um segmentation fault. O que pode estar acontecendo?

A: O teu problema e no uso do scanf()
while(scanf("%li", &numero) != EOF)

O valor que o scanf() devolve normalmente corresponde ao numero de atribuicoes efectuadas (no teu caso esse valor e 1 porque so ha uma atribuicao a variavel numero).
Nota que um scanf() com mais que uma atribuicao pode devolver um numero inferior sem ser erro
chk = scanf("%d%d%d", &um, &dois, &tres);
if (chk == 3) /* 3 atribuicoes */;
if (chk == 2) /* 2 atribuicoes: `tres` nao foi atribuido */;
if (chk == 1) /* 1 atribuicao: apenas `um` foi atribuido */;
if (chk == 0) /* nenhuma atribuicao */;
if (chk == EOF) /* erro de leitura */;

No teu exemplo acima nao deves testar o valor devolvido pelo scanf() com EOF, mas sim com 1
while(scanf("%li", &numero) == 1)

A: Fiz algumas alterações pequenas no seu código e testei utilizando CTRL+Z para parar a leitura dos inteiros, funcionou perfeitamente:
#include <stdio.h>
#include <stdlib.h>

int main()
{
    long int numero, i = 0, vetor[100000];

    while(scanf("%li", &numero) != EOF)
    {
        if (i == 99999)     //caso o vetor chegue ao seu limite a leitura encerra.
        {
            printf("Limite do vetor atingido!\n");
            break;
        }
        else
        {
            vetor[i++] = numero;
        }
    }

    while(i > 0)
        printf("%li ", vetor[--i]);

    return 0;
}

Faça o teste utilizando esse código, se der algum problema me avise nos comentários que vou buscar resolve-lo. Espero ter ajudado.


text:
Q: How to use date DatePipe with ngx-translate I have this translation defined:
"...has created {{param1}} ({{param2}}) on {{ param3 | date:'mediumDate' }}, {{ param3| date:'shortTime' }}"
param1 and param2 get replaced but param3 is not ({{ param3 | date:'mediumDate' }}, {{ param3| date:'shortTime' }} is printed)...how can I use the datepipe inside a translation?

A: When you define your translation like that, ngx-translate expects
{{param3 | date:'mediumDate' }} as is.
Instead just try following
"...has created {{param1}} ({{param2}}) on {{ param3 }}, {{ param4}}"

When you want to get your message, use it as follows
{{'path.to.your.message' | translate: {param3: yourDateVariable| date: 'mediumDate'}}}


text:
Q: Handling same variable in traits If I write something like this:
trait foo {
    val a: Int
}

trait bar extends foo{
    val a:Int
}

case class baz(fish:Int) extends bar {
   val a = 3
 }

why does not it throw any compilation error? I assume if there are two variables of the same name, an error should get thrown but the code works smoothly. And which value of 'a' gets updated?

A: val a: Int in both trait foo and bar are the same. When bar extends foo, you must define a value for a or leave it abstract.
In your example, you are explicitly leaving a as abstract. This would have the same effect:
trait foo {
    val a: Int
}

trait bar extends foo

case class baz(fish:Int) extends bar {
    val a = 3
}


text:
Q: Finding the derivative of $\log_ax$ $\log_ax$
I know there is a formula for this, but I am trying to understand the logic behind the formula.
I know that $$\log_ax = \frac{\ln x}{\ln a} = \ln x \cdot \ln a ^{-1}$$
Because this is in the form $f(x)g(x)$, I have to use $f'(x)g(x)+f(x)g'(x)$ to solve this, and so I have:
$$f(x) = \ln x \\ f'(x) = \frac{1}{x} \\ g(x) = \ln a ^{-1} \\ g'(x) = -\frac{1}{a\ln^2 a}$$
So I did:
$$\frac{1}{x} \cdot \ln a ^{-1} + \ln x \cdot  -\frac{1}{a\ln^2 a} = \frac{1}{x \ln a} - \frac{\ln x}{a\ln^2 a} = \frac{a \ln^2(a)-\ln(x)x\ln(a)}{ax \ln^3(a)}= \frac{a \ln(a) - \ln (x)x}{ax\ln^2(a)} = \text{???}$$
I think this is wrong. I put it on Wolfram Alpha http://www.wolframalpha.com/input/?i=(aln(a)-ln(x)x)%2F(axln(a)%5E2) and it doesn't seem to simplify to $\frac{1}{\ln(a)x}$, which is the correct answer.
What did I do wrong?

A: You simply treat $(\ln a)^{-1}$ as a constant. That is $\frac{d}{dx} ((\ln a)^{-1} \ln x )= (\ln a)^{-1}  \frac{d}{dx} \ln x  =  (\ln a)^{-1} \cdot \frac{1}{x}$

A: Since $\log_a{x}=\frac{\ln{x}}{\ln{a}}$, and $a$ is just a constant, not a variable, you do not need to use the product rule.
Therefore:
$$\frac{d}{dx}(\log_a{x})=\frac{d}{dx}\left(\frac{1}{\ln{a}}\cdot \ln{x}\right)=\frac{1}{\ln{a}}\cdot \frac{d}{dx}(\ln{x})=\frac{1}{\ln{a}}\cdot \frac{1}{x}=\frac{1}{x\ln{a}}$$


text:
Q: Search with a varable after https link im trying to make a search button that sets the searched article in a link.
example.com/zoeken?query=
after the = needs to be set the searched article.(so needs to be 'zoeken?query=article')
but when i try it it wil set a lot of random characters.
example.com/zoeken?query=&article=zena
<form action="https://pyroworks-demo.webshop.kei.io/zoeken?query=" method="get" target="_blank">
    <input type="hidden" name="query">
    <input type="text" name="article" placeholder="article">
    <input type="submit" value="send">
</form>

Can someone help me with this?

<!doctype html>
<html lang="nl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Home</title>
</head>
<body>
<div class="">
    <form action="https://pyroworks-demo.webshop.kei.io/zoeken?query=" method="get">
        <input type="hidden" name="query">
        <input type="text" name="article" placeholder="article">
        <input type="submit" value="send">
    </form>
</div>
</body>
</html>

A: You don't need query= in your action.
The form submit will automatically append all input name attributes, as query parameters, as long as the method is get
So simply do like this:

<form action="https://pyroworks-demo.webshop.kei.io/zoeken" method="get">
   <input type="text" name="query" placeholder="article">
   <input type="submit" value="send">
</form>


text:
Q: failed to solve: rpc error: code = Unknown desc = failed commit on ref I have a django application and I'm trying to run it using docker. But when I run docker-compose build the following error shows up:
> [ 1/15] FROM docker.io/library/python:3.9@sha256:d084f55e2bfeb86ae8e1f3fbac55aad813c7c343c7cbacc91ee11a2d07c32d25:
------
failed to solve: rpc error: code = Unknown desc = failed commit on ref "layer-sha256:bf48494000001a037b72870d2a6a2536f9da8bc5d1ceddd72d79f4a51fe7a60e": "layer-sha256:bf48494000001a037b72870d2a6a2536f9da8bc5d1ceddd72d79f4a51fe7a60e" failed size validation: 2623870 != 10876505: failed precondition

here is my Dockerfile:
FROM python:3.9
ENV PYTHONUNBUFFERED 1

RUN mkdir /code
WORKDIR /code
COPY requirements.txt /code/
RUN apt update && apt install -y lsb-release && apt clean all
RUN pip install --upgrade pip
RUN pip install -r requirements.txt
RUN apt -y update && apt -y install gettext
RUN wget -O - https://www.postgresql.org/media/keys/ACCC4CF8.asc
RUN sudo apt-key add ACCC4CF8.asc
RUN echo "deb http://apt.postgresql.org/pub/repos/apt/ `lsb_release -cs`-pgdg main" | tee  /etc/apt/sources.list.d/pgdg.list
RUN echo "deb http://apt.postgresql.org/pub/repos/apt/ `lsb_release -cs`-pgdg-testing main 13" | tee  /etc/apt/sources.list.d/pgdg-testing.list
RUN apt -y update && apt -y install postgresql-client-13

COPY . /code/
RUN chmod +x /code/entrypoint.sh1
ENTRYPOINT ["sh", "/code/entrypoint.sh"]

here is my docker-compose.yml:
version: '3'

services:
  db:
    image: postgres
    environment:
      - POSTGRES_DB=${POSTGRES_DB}
      - POSTGRES_USER=${POSTGRES_USER}
      - POSTGRES_PASSWORD=${POSTGRES_PASSWORD}
      - POSTGRES_PORT=${POSTGRES_PORT}
    volumes:
      - postgres-data:/var/lib/postgresql/data
  web:
    build: .
    command: bash -c "python manage.py runserver 0.0.0.0:8000"
    volumes:
      - .:/code
      - ./static:/static
      - ./media:/media
    ports:
      - ${PORT}:8000
    depends_on:
      - db

volumes:
  postgres-data:

I'm on Windows and my docker-compose version is v2.2.3 and my docker version is 20.10.12, build e91ed57.
Any idea how I can get rid of this error?
Update: I believe it was due to network issues. If you have restricted access to the internet and face this problem, you might want to use a VPN.


text:
Q: Real-time grab the audio stream. Linux I have a task. Real-time grab the audio stream and process it (remove noise, adjust the frequency) and send back.

*

*Which protocol is better to work for a high stream of data?

*What libraries should I use?


text:
Q: Issues with mail sending in php So I have been working on a project and I have a function that will send emails out to employees whose employer is chosen.  Now this is working except the mail function (I am using winhost and we need to include Mail.php in order for the mailing function to work) It will sometimes send 3 emails out instead of 2 and sometimes 1 email instead of 2.
The code :
if (isset($_POST['openemailmem'])){
    $memberuser = $_POST['openemailmemusername'];
    $sql = "SELECT email, username, password, status FROM csvdata WHERE memberview =:user ";
    $getinfo=$DBH->prepare($sql);
    $getinfo->execute(array(':user' => $memberuser));

    while ($row = $getinfo->fetch(PDO::FETCH_ASSOC)) {
        $check = $row;
        $newEmployeeEmail = $check['email'];
        $csvusername = $check['username'];
        $password = $check['password'];
        $status = $check['status'];

        if ($status == "Open"){
            echo "tesing";
            $from = "the email of where it is coming from is here but i removed";
            $to = $newEmployeeEmail;
            if (!empty($_POST['cc'])){
                $cc = $_POST['cc'];
            }
            if (!empty($_POST['ccsend'])){
                $cc = $_POST['ccsend'];
                $to .= ", $cc";
            }
            $subject = "removed msg";
            $body = "removed msg";
            $host = "i removed";
            $username = "i removed";
            $password = "i removed";
            $headers = array ('From' => $from, 'To' => $to,'Cc' => $cc, 'Subject' => $subject);
            $smtp = Mail::factory('smtp', array ('host' => $host, 'auth' => true, 'username' => $username, 'password' => $password));
            $mail = $smtp->send($to, $headers, $body);
        }
    }

    header("Location: I removed this.php?getmsg=12");
    exit;

}

Thank you for all your time!!!

A: Your solution is most likely in your logs. If exceptions are thrown, you can find them in there.
Additionally a suggestion:
Add logging before and after the loop. So your example becomes:
if (isset($_POST['openemailmem']))
{
    $memberuser = $_POST['openemailmemusername'];
    $sql        = "SELECT email, username, password, status "
                . "FROM csvdata WHERE memberview =:user ";
    $getinfo    = $DBH->prepare($sql);
    $getinfo->execute(array(':user' => $memberuser));

    $log_file = "/home/my/transaction.log";
    $now      = "[" . date("Ymd-His") . "] ";

    $message = $now . "Starting loop...";
    error_log($message, 3, $log_file);

    while ($row = $getinfo->fetch(PDO::FETCH_ASSOC))
    {

        $check            = $row;
        $newEmployeeEmail = $check['email'];
        $csvusername      = $check['username'];
        $password         = $check['password'];
        $status           = $check['status'];

        if ($status == "Open")
        {
            echo "tesing";
            $from = "the email of where it is coming from is here but i removed";
            $to   = $newEmployeeEmail;
            if (!empty($_POST['cc']))
            {
                $cc = $_POST['cc'];
            }
            if (!empty($_POST['ccsend']))
            {
                $cc = $_POST['ccsend'];
                $to .= ", $cc";
            }
            $subject  = "removed msg";
            $body     = "removed msg";
            $host     = "i removed";
            $username = "i removed";
            $password = "i removed";
            $headers = array(
                           'From'    => $from,
                           'To'      => $to,
                           'Cc'      => $cc,
                           'Subject' => $subject,
                       );

            $now     = "[" . date("Ymd-His") . "] ";
            $message = $now . "Before connecting to server - " . $to;
            error_log($message, 3, $log_file);

            $smtp = Mail::factory(
                'smtp',
                 array(
                     'host'     => $host,
                     'auth'     => true,
                     'username' => $username,
                     'password' => $password,
                 )
            );

            $now     = "[" . date("Ymd-His") . "] ";
            $message = $now . "After connecting to server - " . $to;
            error_log($message, 3, $log_file);

            $now     = "[" . date("Ymd-His") . "] ";
            $message = $now . "Before sending email - " . $to;
            error_log($message, 3, $log_file);

            $mail = $smtp->send($to, $headers, $body);

            $now     = "[" . date("Ymd-His") . "] ";
            $message = $now . "After sending email - " . $to;
            error_log($message, 3, $log_file);
        }
    }

    $now     = "[" . date("Ymd-His") . "] ";
    $message = $now . "End of loop";
    error_log($message, 3, $log_file);

    header("Location: I removed this.php?getmsg=12");
   exit;

}

You might find that your function times out, depending of how long it takes the mailer to dispatch the email to the relevant host.
From what I see for every user there is a (potentially) unique connection to a mail server and then the email is sent. If for whatever reason there is a delay in establishing that connection then your script could very well time out.
You can adjust the error logging method above to use microtime so that you can see the real time between each iteration of your code - of course you will need to add more logging in between blocks of code.
If you find out that it is indeed a delay in the mail server connection etc. you could (if your requirements allow you to) connect once to one server and send your emails from there.
HTH


text:
Q: C# vs VB6: How to get IME Unicode Char assosiated with an ANSI Window (UC or PictureBox) In VB6,UserControl or Form or PictureBox is ANSI window in locale English 1033 (configurable in Region and Language settings). I see wParam is always 63 (Char '?') in WM_IME_CHAR or WM_UNICHAR or WM_CHAR when I am typing Unicode via MS IME or Baidu input.
For Comparison, I creates a SDK TextBox, used by CreateWindowExW API, IsWindowUnicode API shows it is Unicode window, Since it is Unicode Window, I can see wParam is Unicode Keycode When I subclass WM_IME_CHAR and WM_UNICHAR and WM_CHAR. So I can get Unicode Char easily.
I guess OS deal with ANSI window and Unicode Window is different. What is the work-around to get IME Unicode Char?
The same code in C# works with whatever locale either 1033 (English USA) or 2052 (Chinese PRC), since C# window is always Unicode.

protected override void WndProc(ref Message m)
    int msg = m.Msg;
    if (msg == WM_IME_SETCONTEXT) //associated IME with our UserControl
       {
         if (!m.WParam.Equals(IntPtr.Zero))
          {
           bool flag = ImmAssociateContextEx(m.HWnd, IntPtr.Zero, 16);
           IntPtr hIMC = ImmGetContext(m.HWnd);
           flag = ImmSetOpenStatus(hIMC, true);
           flag = ImmReleaseContext(m.HWnd, hIMC);
          }
        }
    }
    else
    if (msg == WM_IME_CHAR) //Intercept Message to get Unicode Char
      {
        KeyPress(this, new KeyPressEventArgs(Strings.ChrW(m.WParam.ToInt32())));
        return;
      }
    }
   base.WndProc(ref m);
}

In VB6 UserControl:
Private Function WindowProcUserControl(ByVal hWnd As Long, ByVal wMsg As Long, ByVal wParam As Long, ByVal lParam As Long) As Long
   Select Case wMsg
    Case WM_IME_SETCONTEXT '//associated IME with our UserControl
         If Not wParam = 0 Then
            Dim flag As Boolean
            flag = ImmAssociateContextEx(hWnd, 0, 16)
            If flag Then
               Dim hIMC As Long
               hIMC = ImmGetContext(hWnd)
               flag = ImmSetOpenStatus(hIMC, True)
               flag = ImmReleaseContext(hWnd, hIMC)
            End If
         End If
     Case WM_IME_CHAR '//Intercept Message to get Unicode Char
         Call KeyPress(ChW$(wParam And &HFFFF&))
         Exit Function
  End Select
End Function

A: I think the root problem is that VB6 windows are ANSI, When an IME window attach to them, VB6 just handle by ANSI APIs (may say "VB's ANSI pump will eat it"). Since this problem is beyond mine and most of programmers capability, I let this thread 'solved' falsely.


text:
Q: Permutation Notations In a permutation consisting of numbers {1, 2, 3}
What's the difference between the permutation notations
$(x_1, x_2, x_3)$ where it's a specific/particular permutation
and
$(X_1, X_2, X_3)$ where it's a random permutation.
$(x_1, x_2, x_3)$ could be the permutations (1, 2, 3), (1, 3, 2), ..., (3, 2, 1)
but
$(X_1, X_2, X_3)$ also could also the permutations be (1, 2, 3), (1, 3, 2), ..., (3, 2, 1)?

A: Calling $\langle X_1,X_2,X_3\rangle$ a random permutation we implicitly assume the existence of an underlying probability space $(\Omega,\mathcal A,\mathsf{P})$.
The $X_i$ are looked at as functions $\Omega\to\mathbb R$, and the probability space can be constructed in such a way that function $\langle X_1,X_2,X_3\rangle:\Omega\to\mathbb R^3$ only takes values in the set: $$S=\{\langle x_1,x_2,x_3\rangle\mid\{x_1,x_2,x_3\}=\{1,2,3\}\}$$
Then element $\langle x_1,x_2,x_3\rangle\in S$ induces the event: $\{\langle X_1,X_2,X_3\rangle=\langle x_1,x_2,x_3\rangle\}$ which is actually the preimage of $\{\langle x_1,x_2,x_3\rangle\}$ under function $\langle X_1,X_2,X_3\rangle:\Omega\to\mathbb R^3$: $$\langle X_1,X_2,X_3\rangle^{-1}(\{\langle x_1,x_2,x_3\rangle\})=\{\omega\in\Omega\mid \langle X_1(\omega),X_2(\omega),X_3(\omega)\rangle=\langle x_1,x_2,x_3\rangle\}$$
In this situation we can choose for $\Omega=S$ and we can prescribe $X_i:\Omega=S\to\mathbb R$ by: $$\langle x_1,x_2,x_3\rangle\mapsto x_i$$
Then we can take $\mathcal A=\wp(S)$ and - if we want equiprobability for all outcomes - we can determine $\mathsf{P}$ by stating that $\mathsf{P}(\{s\})=\frac16$ for every $s\in S$ (note that $S$ has $6$ elements).

I hope that this gives some clarity. My main point is that the $X_i$ are functions and the $x_i$ are not. Quite often in situations like this not much attention goes to the underlying probability space, and in fact it is a good thing that that is not really needed. It is enough to know that we can model the situation, but how that could be done is irrelevant in most situations. A nice question on that subject you can find here.


text:
Q: Как осуществить последовательность выполнения скрипта в jquery? Есть функция showItems, которая получает все товары из БД вставляет их на страницу покупок в виде последовательных картинок с описанием, есть вторая функция checkMyItems, которая получает из бд id товаров, которые выбрал пользователь. Товары предчтавляют собой div-элемент с каринкой на background. Проблема в том, что раз через раз выполянется вторая функция быстрее первой и все начинает визуально ломаться. Как сделать так чтобы мы были уверены, что первый скрипт полностью отработан и подгрузил все картинки?
Пробывал так, но проблема осталась:
$.when(showItems()).then(checkMyItems());

function showItems(){
        $.ajax({
            url: "shop.php",
            data: {
                Action: "getItems"
            },
            type: 'post',
            success: function(data) {
                $.each(data.items, function(i, items) {
                //вставляем items
...
});
}

A: $.ajax возвращает deffered объект, у которого есть функция then. Поэтому в данном случае не нужен when, достаточно вернуть из функции showItems результат выполнения $.ajax.
function showItems(){ return $.ajax(...) }

Далее добавить обработчик через функцию then
showItems().then(checkMyItems);


text:
Q: Atmega328p datasheet mistake "OCRA" I was reading the atmega328p datasheet, and suddenly, i saw that a register is mentioned called "OCRA", on page 108 and page 160, which normally, should be register "OCR0A", which is widely mentioned on this datasheet. "OCRA" is only mentioned on those two pages, inside tables, which is suspicious.
OCR0A is normally responsible for the TOP value of compare register for the timer interrups.
Is this a mistake of the datasheet?


text:
Q: Redirecting to login page if user enters root path I've got a VB.net web app, and its start page is http:\\<myServer>\<myApp>\webforms\login.aspx
I'd rather they didn't have to enter this whole address. Is there a simple way to redirect my users to this page if they just enter the root i.e.  http:\\<myServer>\<myApp>\ ?

A: Assuming you have not changed the default pages in IIS, just setup a default.aspx on the root that redirects to the login.aspx page.

A: Another thought is to use URL Routing if you are using ASP.Net 3.5 or 4.0.  Here is a link - https://web.archive.org/web/20201205221404/https://www.4guysfromrolla.com/articles/051309-1.aspx  The page is specific to 3.5 SP 1, but there is another link on the page for 4.0.  So you might use  http:\\\login and it will route to http:\\\webforms\login.aspx.  HTH


text:
Q: Standard represention of $S_3$ I am wondering how to extract the standard representation from the permutation representation? I want to obtain the permutation rep matrices $\Gamma((1,2)), \Gamma((1,3))$ and $\Gamma((1,3,2))$ in the standard representation in a basis where $\underline{e}_1 = \sqrt{\frac{2}{3}} (1, -\frac{1}{2}, -\frac{1}{2})$, $\underline{e}_2 = \sqrt{\frac{1}{2}}(0,1,-1)$ and $\underline{e}_3 = \frac{1}{\sqrt{3}}(1,1,1)$
I can obtain the corresponding transformation matrix and then compute $\Gamma' = T^{\dagger}\Gamma T = T^T \Gamma T$, but when I have this $\Gamma'$ I don't know how to then extract the standard representation as per the question requirements.
Many thanks.

A: I won't calculate the exact result but let me give you some ingredients:
You should know how to transform a matrix to another via a change of basis. This way we can work with a preferred one. Mine is the standard basis. Since you used $e_i$ already lets call them $v_1,v_2,v_3$.
You hopefully know how the permutation matrices that you called $\Gamma((1,2)),\dots$ look like. (e.g. $\begin{pmatrix}0&1&0\\1&0&0\\0&0&1\end{pmatrix}$)
Now the part that you probably had trouble with. The standard representation lives on the vector space usually defined by $\mathbb C^3/ \langle(1,1,1)\rangle$ (assuming you work over $\mathbb C$ although every field would work here). This vector space is two-dimensional and one can see that the images of $v_1$ and $v_2$ are again form a basis. Let us call them $\bar v_1, \bar v_2$.
Now we only need to know what happens on these two vectors. Note that the image of $v_1+v_2+v_3$ is zero, so whenever we get $\bar v_3$ we replace it by $-\bar v_1-\bar v_2$.
Example: $\Gamma((1,2,3))$
$v_1$ is sent to $v_2$ and $v_2$ is sent to $v_3$, hence $\bar v_1$ gets sent to $\bar v_2$ and $\bar v_2$ gets sent to $\bar v_3 = -\bar v_1-\bar v_2$. Thus the matrix is $\begin{pmatrix}0&1\\-1&-1\end{pmatrix}$.
Now you only have to work out what the images $\bar e_1, \bar e_2$ of $e_1,e_2$ are in terms of $\bar v_1, \bar v_2$ and do the base change.


text:
Q: MongoDB how to do multiple aggregations in one query with C# driver? My data model looks something like this:
{
    "ListingId": 1,
    "Status": "Current",
    "Category": "Rental"
}

I have around 5 million documents, and would like to run aggregations on both the "status" and "category" fields, so i can produce an output like this:
{
   "Statuses":
   {
      "Current": 100, // count of all documents with 'Status' = 'Current'
      "Sold": 12 // count of all documents with 'Status' = 'Sold'
      // etc
   },
   "Categories":
   {
      "Sale": 120,
      "Rental": 12
      // etc
   }
}

Basically, i want to return data to power a 'faceted search' UI, so i need the count's of all facets, and I want to do it in one trip to MongoDB.
I've been reading up about Aggregations and Facets for a day or so now, and i'm still confused.
Questions:

*

*Given my scenario and collection size, what should i be using here? Facets or Aggregations?

*How do i do it in the latest C# driver?

Related questions (which i haven't been able to convert to my situation / code):

*

*Using Facets in the Aggregation Framework C#

*Using Facets in the Aggregation Framework C# with Multiple Facet, Unwind and sortByCount

A: You can get these data in a little bit different way with aggregation like below. Try facet code like below in my screenshot. Let me know if more help is required.

You can export the same pipeline and put it in your c# code.


text:
Q: sistema de favoritos sin base datos Quiero hacer un botón de favoritos,como un corazón o algo así...el tema es que no quería utilizar base de datos y he encontrado un código que funciona y me gusta pero al salir y volver a entrar se reinicia y borra los datos:

var likes =0;
     function like(){
     document.getElementById("show").innerHTML=likes;
     likes=likes+1;
}
#button {
    background-color: #4CAF50;
    border: none;
    color: white;
    padding: 15px 32px;
    text-align: center;
    text-decoration: none;
    display: inline-block;
    font-size: 16px;
    margin: 4px 2px;
    cursor: pointer;
}
    <!DOCTYPE html>

    <title>me gusta</title>

    <button id="button" onClick="like()">LIKE</button>

LIKES

¿Cómo lo puedo hacer para que se guarde sin usar base datos?

A: Puedes usar localStorage para guardar
var likes =0;
     function like(){
     document.getElementById("show").innerHTML=likes;
     likes=likes+1;
localStorage.setItem('likes', likes);

}

proba que se guarda:
console.log(localStorage.getItem('likes'));


text:
Q: Nustache.Mvc - Is it possible to create a custom helper I use The Nustach.MVC assembly https://www.nuget.org/packages/Nustache.Mvc3/1.13.8.22 so I can share templates betwixt back end and front.
Is there a way to write a custom handlebars helper that I can use in the back end?

A: Maybe this Project could help you nustache-helpers


text:
Q: Deserializing multiple objects from a single file I have a number of objects (of the same class) serialized into a file.
But while deserializing it, only the first serialized object is deserialized.
Code for serializing:
public void save() {
File f = new File("vehicule.txt");
try {
    if(!f.exists()) f.createNewFile();
} catch(IOException e) {
}
try {
    ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(f,true));
oos.writeObject(this);
} catch(IOException e) {
}

}
I think the problem is with:
Vehicule v;
while( (v = (Vehicule)ois.readObject()) != null )

Is there a better way to check for the end of the file?

A: It's probably better to write the number of Vehicules that are in the file at the beginning, and let that control how many you read.
If you want to do it the way you are doing it, then you will have to try/catch an IOException
[also btw, this isn't a txt file]

A: If you are going to use multiple appended ObjectOutputStreams, then I believe this might help (along with making sure you delete the file each time you run your test!):

Why can't a file that contains multiple appended ObjectOutputStreams be deserialized by one ObjectInputStream?
Using the default implementation of serialization, there must be a
  one-to-one mapping between ObjectOutputStream construction and
  ObjectInputStream construction. ObjectOutputStream constructor
  writes a stream header and ObjectInputStream reads this stream
  header. A workaround is to subclass ObjectOutputStream and override
  writeStreamHeader(). The overriding writeStreamHeader() should
  call the super writeStreamHeader method if it is the first write to
  the file and it should call ObjectOutputStream.reset() if it is
  appending to a pre-existing ObjectOutputStream within the file.

Otherwise I would suggest you add the objects to a List and then serialize it with a single ObjectOutputStream.
For example:
    Vehicule v1 = new Vehicule();
    Vehicule v2 = new Vehicule();
    List<Vehicule> vehicules = Arrays.asList(v1, v2);

    // serialize the list of Vehicules
    File f = new File("vehicule.txt");
    try {
        ObjectOutputStream oos = new ObjectOutputStream(
                new FileOutputStream(f));
        oos.writeObject(vehicules);
        oos.close();
    } catch (Exception e) {
        e.printStackTrace(); // handle this appropriately
    }

    // deserialize the list of Vehicules
    try {
        ObjectInputStream ois = new ObjectInputStream(
                new FileInputStream(f));
        List<Vehicule> deserializedVehicles = (List<Vehicule>) ois.readObject();
        ois.close();
        System.out.println("list size = " + deserializedVehicles.size());
    } catch (Exception e) {
        e.printStackTrace(); // handle this appropriately
    }

For me, this outputs:
list size = 2

A: try {
    if(!f.exists()) f.createNewFile();
} catch(IOException e) {
}

You don't need any of that. new FileOutputStream() will create the file.
new ObjectOutputStream(new FileOutputStream(f,true))

You can't append to an ObjectOutputStream. There are headers in there that ObjectInputStream won't understand if it encounters them in the middle of a stream.
while( (v = (Vehicule)ois.readObject()) != null )

Is there a better way to check for the end of the file?

There's nothing in the Javadoc about readobject() returning null at EOS. readObject() returns null if and only if you wrote a null.
The correct technique is to catch EOFException, close the stream, and break out of the loop.

A: Just serialize/deserlialize an ArrayList<Vehicle> (rather than trying to stuff multiple object into a single file).

A: Ok this is how it finally worked.
I deserialized everything in the file to an ArrayList; added the new object and while serializing, I added each element of the ArrayList to the file [erasing the previous entries by using (new FileOutputStream(new File("Vehicule.txt"),false) ].
Finally I added a null explicitly to the file so as to help with the deserializing.
Also while creating the file for the first time with createNewFile, I added a null to the file.


text:
Q: Android: White View shown when keyboard shown on Pie and Oreo Version I am facing a strange problem when keyboarad shown in fragment it white overlay view shown above the layout and disapper when keyboard hide
this picture when keyboard hide

this picture when keyboard shown

A: I think its not hard problem
Then
In AndroidManifest.xml file try to set windowSoftInputMode attribute to adjustNothing.
Like this :
android:windowSoftInputMode="adjustNothing"

I hope that it works.


text:
Q: Remove HTML-tags on Lucene.net Indexe update/build Is it possible to make Lucene.net remove all html-tags from strings that I store in the lucene.net fields?

A: I'm not aware of any built in HTML Analyzer for Lucene.net, but it should be simple enough to code your own Analyzer/Tokenizer using a parser like HTMLAgilityPack.


text:
Q: How to convert a camel-case string to dashes in JavaScript? I want to convert these strings:
fooBar
FooBar

into:
foo-bar
-foo-bar

How would I do this in JavaScript the most elegant and performant way for any given string?

A: For those who do not need the preceding hyphen:

console.log ("CamelCase".replace(/[A-Z]/g, (match, offset) => (offset > 0 ? '-' : '') + match.toLowerCase()))

A: You can use replace with a regex like:
let dashed = camel.replace(/[A-Z]/g, m => "-" + m.toLowerCase());

which matches all uppercased letters and replace them with their lowercased versions preceded by "-".
Example:

console.log("fooBar".replace(/[A-Z]/g, m => "-" + m.toLowerCase()));
console.log("FooBar".replace(/[A-Z]/g, m => "-" + m.toLowerCase()));

A: You can use replace() with regex. Then use toLowerCase()

let camel = (s) => s.replace(/[A-Z]/g, '-$&').toLowerCase()

console.log(camel('fooBar'))
console.log(camel('FooBar'))

`

A: You can use https://github.com/epeli/underscore.string#dasherizestring--string from underscore.string library.

A: Maybe you could use kebabCase from lodash: https://lodash.com/docs/4.17.15#kebabCase

A: EDIT
Simple case:
"fooBar".replace( /([a-z])([A-Z])/g, '$1-$2' ).toLowerCase();
"FooBar".replace( /([a-z])([A-Z])/g, '$1-$2' ).toLowerCase();

Edge case: this can get an extreme case where you have a single char.
"FooBarAFooBar".replace(/([A-Z])/g, (g) => `-${g[0].toLowerCase()}`)

A: You can use
const makeItDashed = camelCased => {
   let dashed = ``
   camelCased.split(``).map(ch => {{dashed += ch.toUpperCase() == ch ? `-${ch.toLowerCase()}` : ch}})
   return dashed
}

console.log(makeItDashed(`fooBar`))
console.log(makeItDashed(`FooBar`))