What do * (single star) and / (slash) do as independent parameters?

Question: In the following function definition, what do the * and / account for?
def func(self, param1, param2, /, param3, *, param4, param5):
     print(param1, param2, param3, param4, param5)

NOTE: Not to mistake with the single|double asterisks in *args | **kwargs (solved here)
Comment: `/` is for [positional-only arguments](https://www.python.org/dev/peps/pep-0570/), while `*` is for [keyword-only arguments](https://www.python.org/dev/peps/pep-3102/).
Comment: Please refer to this: [Python Positional-Only Parameters](https://www.python.org/dev/peps/pep-0570/#syntax-and-semantics)
Answer: The function parameter syntax(/) is to indicate that some function parameters must be specified positionally and cannot be used as keyword arguments.(This is new in Python 3.8)
Documentation specifies some of the use cases/benefits of positional-only parameters

It allows pure Python functions to fully emulate behaviors of
existing C coded functions. For example, the built-in pow()
function does not accept keyword arguments:
def pow(x, y, z=None, /):
    "Emulate the built in pow() function"
    r = x ** y
    return r if z is None else r%z

Another use case is to preclude keyword arguments when the parameter
name is not helpful. For example, the builtin len() function has
the signature len(obj, /). This precludes awkward calls such as:
len(obj='hello')  # The "obj" keyword argument impairs readability

A further benefit of marking a parameter as positional-only is that
it allows the parameter name to be changed in the future without
risk of breaking client code. For example, in the statistics module,
the parameter name dist may be changed in the future. This was made
possible with the following function specification:
def quantiles(dist, /, *, n=4, method='exclusive')
    ...

Where as * is used to force the caller to use named arguments. Django documentation contains a section which clearly explains a  usecase of named arguments.

Form fields no longer accept optional arguments as positional
arguments
To help prevent runtime errors due to incorrect ordering of
form field arguments, optional arguments of built-in form fields are
no longer accepted as positional arguments. For example:
forms.IntegerField(25, 10)
raises an exception and should be replaced
with:
forms.IntegerField(max_value=25, min_value=10)

Suppose we have a method called func:
def func(self, param1, param2, /, param3, *, param4, param5):
     print(param1, param2, param3, param4, param5)

It must called with
obj.func(10, 20, 30, param4=50, param5=60)

OR
obj.func(10, 20, param3=30, param4=50, param5=60)

ie,

param1, param2 must be specified positionally.
param3 can be called either with positional or keyword argument.
param4 and param5 must be called with keyword argument.

DEMO:
>>> class MyClass(object):
...     def func(self, param1, param2, /, param3, *, param4, param5):
...         return param1, param2, param3, param4, param5
...
>>> obj = MyClass()
>>>
>>> assert obj.func(10, 20, 30, param4=40, param5=50), obj.func(
...     10, 20, param3=30, param4=40, param5=50
... )

Comment: @GammaGames: Yes.  The order of arguments is always positional-only `/` positional-or-keyword `*` keyword-only.
Comment: @Charanor See https://www.python.org/dev/peps/pep-0570/#rationale for the reasons considered by the people who designed and implemented this feature.  Whether you find these to be convincing reasons is up to you; I can argue either way, personally.
Comment: Does the `/` operator only apply to the left parameters? Your descriptions don't seem to make that clear to me, but I might be reading it wrong.
Comment: Nice; do you have any idea what the point is? Why restrict user freedom like this?
Comment: another form of dan04's comment: `/` have no effect on arguments listed right to it, and `*` have no effect on arguments listed left to it.
Answer: As mentioned in the docs, the slash is for positional-only arguments, as the docs says:

There is a new function parameter syntax / to indicate that some function parameters must be specified positionally and cannot be used as keyword arguments. This is the same notation shown by help() for C functions annotated with Larry Hastings' Argument Clinic tool.

And for the asterisk, it's mentioned here in the docs:

For a parameter with a default value, the corresponding argument may be omitted from a call, in which case the parameter's default value is substituted. If a parameter has a default value, all following parameters up until the "*" must also have a default value — this is a syntactic restriction that is not expressed by the grammar.

def func(self, param1, param2, /, param3, *, param4, param5):
     print(param1, param2, param3, param4, param5)

So the ways to call this would be:
obj.func(10, 20, 30, param4=50, param5=60)

And:
obj.func(10, 20, param3=30, param4=50, param5=60)


Parse Json Data into Existing Flutter Widget

Question: hello i am learning flutter now and i am trying to get json data and display it on a carousel widget , below is the full code just so you get an idea of what is going on
import 'package:flutter/material.dart';
import 'package:mares/components/drawer.dart';
import 'package:carousel_pro/carousel_pro.dart';
import 'package:mares/components/homecards.dart';
import 'package:mares/pages/contactus.dart';
import 'package:mares/pages/profile.dart';
import 'dart:async';
import 'dart:convert';
import 'package:http/http.dart' as http;

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Elaph Training',
      theme: ThemeData(fontFamily: 'Roboto'),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {

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

class _MyHomePageState extends State<MyHomePage> {

  Future<List> getSlides() async {
    final response = await http.get("http://igh-eg.com/mares/json/slides.php");
    return json.decode(response.body);
  }

  @override
  Widget build(BuildContext context) {
    Widget imagecarousel = new Container(
      height: 200.0,
      child: new Carousel(
        boxFit: BoxFit.cover,
        images: [
          AssetImage('assets/slide1.jpg'),
          AssetImage('assets/slide2.jpg'),
          AssetImage('assets/slide3.jpg'),
        ],
        autoplay: true,
        animationCurve: Curves.fastOutSlowIn,
        animationDuration: Duration(milliseconds: 2000),
        dotSize: 5.0,
        dotColor: const Color.fromRGBO(234, 91, 12, 1),
      ),
    );

    return Scaffold(
      appBar: new AppBar(
        backgroundColor: const Color.fromRGBO(32, 102, 174, 1),
        title: Text('Elaph Training Center'),
        actions: <Widget>[
          new IconButton(icon: Icon(Icons.phone_in_talk, color: Colors.white,), onPressed: (){Navigator.of(context).push(new MaterialPageRoute(builder: (context) => new ContactUsPage()));}),//search button
          new IconButton(icon: Icon(Icons.supervised_user_circle, color: Colors.white,), onPressed: (){Navigator.of(context).push(new MaterialPageRoute(builder: (context) => new Profilepage()));}),//cart button
        ],
      ),
      //--the end of the app bar--//
      //---start of the drawer---//
      drawer: NavDrawer(),
      body: new ListView(
        children: <Widget>[
          new FutureBuilder<List>(
            future: getSlides(),
            builder: (context, snapshot) {
              if (snapshot.hasError) print(snapshot.error);

              return snapshot.hasData
                  ? new ItemList(
                list: snapshot.data,
              )
                  : new Center(
                child: new CircularProgressIndicator(),
              );
            },
          ),
          imagecarousel,
          SizedBox(height: 10.0,),
          HomeCards(),
        ],
      ),
    );
  }
}

class ItemList extends StatelessWidget {
  final List list;
  ItemList({this.list});

  @override
  Widget build(BuildContext context) {
    return new ListView.builder(
      itemCount: list == null ? 0 : list.length,
      itemBuilder: (context, i) {
        return new Container(
          padding: const EdgeInsets.all(10.0),
          child: new Card(

              child: new ListTile(
                title: new Text(list[i]['name']),
                leading: new Image.network("http://igh-eg.com/mares/img/${list[i]['photo']}"),
                subtitle: new Text("Description : ${list[i]['desc']}"),
              ),
            ),
        );
      },
    );
  }
}

currently the data is code is working fine with the listitem class defined above however i want the data to be displayed on the carousel part shown below
  Widget imagecarousel = new Container(
      height: 200.0,
      child: new Carousel(
        boxFit: BoxFit.cover,
        images: [
          AssetImage('assets/slide1.jpg'),
          AssetImage('assets/slide2.jpg'),
          AssetImage('assets/slide3.jpg'),
        ],
        autoplay: true,
        animationCurve: Curves.fastOutSlowIn,
        animationDuration: Duration(milliseconds: 2000),
        dotSize: 5.0,
        dotColor: const Color.fromRGBO(234, 91, 12, 1),
      ),
    );

any help please? i searched the internet alot and i cannot see what i am missing
Answer: I have implemented similar code with carousel_slider: ^2.2.1 & cached_network_image: ^2.1.0+1 package.
You can try the code like below:
class _HomeScreenState extends State<HomeScreen> {
  Future<List<Product>> carouselProducts;
  ...
  // method to fecth data from URL
  Future<List<Product>> getSlides() async {
    return await apiController.carouselDataFetch();
  }

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      carouselProducts = getSlides();
    });
  }

Widget in build method:
FutureBuilder<List<Product>>(
    future: carouselProducts,
    builder: (BuildContext cont, AsyncSnapshot snapshot) {
      if (snapshot.connectionState != ConnectionState.done) {
        return Center(child: CircularProgressIndicator());
      }
      if (snapshot.connectionState == ConnectionState.none) {
        return Center(
            child: Text("Turn-On Mobile Data / WiFi Please!",));
      }
      if (snapshot.hasError) {
        return Center(
            child: Text("Something went wrong!",));
      }
      return CarouselSlider.builder(
        options: CarouselOptions(
          height: 250,
          autoPlay: true,
          enableInfiniteScroll: false,
          enlargeCenterPage: true,
          scrollDirection: Axis.horizontal,
          scrollPhysics: const BouncingScrollPhysics(),
          enlargeStrategy: CenterPageEnlargeStrategy.height,
          autoPlayCurve: Curves.fastLinearToSlowEaseIn,
        ),
        itemCount: snapshot.data.length,
        itemBuilder: (BuildContext context, int index) {
          Product prod = snapshot.data[index];
          return CachedNetworkImage(
            imageUrl: prod.productImage,
            fit: BoxFit.fill,
            useOldImageOnUrlChange: true,
            fadeInCurve: Curves.linearToEaseOut,
            placeholder: (context, url) => Center(
                child: CircularProgressIndicator()),
            errorWidget: (context, url, error) =>
                Icon(Icons.error),
          );
        },
      );
    },
  )

Output:

FYI:
Change this exemplary code as per your API response data.
Answer: Thank you guys but i found the problem is with the version of the widget i am using so i simply followed the below steps
Step 1: i added the version (carousel_pro: ^0.0.13) to pubspec.yaml
Step 2: Created the below dart file
import 'package:carousel_pro/carousel_pro.dart';
import 'package:flutter/material.dart';

Widget CarouselSlider(items) => SizedBox(
  height: 200,
  child: Carousel(
    boxFit: BoxFit.cover,
    images: items,
    autoplay: true,
    animationCurve: Curves.fastOutSlowIn,
    animationDuration: Duration(milliseconds: 1500),
  ),
);

then retrieved the data using http,get while initiating the state inside the main.dart as follows
class _MyHomePageState extends State<MyHomePage> {

  var items = [];
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    //get json data function//
    getSlides();
  }

  Future<List> getSlides() async {
    final response = await http.get("http://igh-eg.com/mares/json/slides.php");
    var result = json.decode(response.body);
    result['data'].forEach((data){
      setState(() {
        items.add(NetworkImage("http://igh-eg.com/mares/img/${data['photo']}"));
      });
    });
    print(json.decode(response.body));
    return json.decode(response.body);
  }

  @override
  Widget build(BuildContext context) {

    return Scaffold(
      appBar: new AppBar(
        backgroundColor: const Color.fromRGBO(32, 102, 174, 1),
        title: Text('Elaph Training Center'),
        actions: <Widget>[
          new IconButton(icon: Icon(Icons.phone_in_talk, color: Colors.white,), onPressed: (){Navigator.of(context).push(new MaterialPageRoute(builder: (context) => new ContactUsPage()));}),//search button
          new IconButton(icon: Icon(Icons.supervised_user_circle, color: Colors.white,), onPressed: (){Navigator.of(context).push(new MaterialPageRoute(builder: (context) => new Profilepage()));}),//cart button
        ],
      ),
      //--the end of the app bar--//
      //---start of the drawer---//
      drawer: NavDrawer(),
      body: new ListView(
        children: <Widget>[
          CarouselSlider(items),
          SizedBox(height: 10.0,),
          HomeCards(),
        ],
      ),
    );
  }
}

and it worked like a chart , and a better way is to use the networkcachedimage widget from pub.dev website if you are working with huge data and images
Thank you all and special thanks to @Sanket Vekariya for his help


Sql query: no rows selected

Question: I tried different variations of the sql statement but I am still getting "no rows selected". I don't know where I am going wrong!.
Here is the question:
I have to list titles of conferences organized by the employees whose manager is 'Green'.
The tables associated with the query are:
Employee_C table:
EID  NAME   SALARY           MID
---    -------------------- -----
e01   Wilson    53000
e02   Smith      48000       e01
e03   Jones      38000       e01
e04   Loftus     41000
e05   Fox        54000       e04
e06   Smith      45000       e04
e07   Green      48000
e08   Fox        49000       e04
e09   Wolf       41000       e04
e10   Wang        32000      e01
e11   Phillips    33000      e07
e12   Liu         27000      e07

Conference_C table:
CONFID              TITLE                     LOCATION          SDATE
------        --------------------       -------------------- ---------
c00001    Hydroinformatics                  Singapore          15-JUN-12
c00002    Ecological_modeling               Berlin             15-JUL-12
c00003    Computational_M                   London             25-MAY-12
c00004    Ecoinformatics                    Boston             22-AUG-12
c00005    Uncertainty_analysis              Athens             10-OCT-12
c00006    Large_databases                   Toronto            13-APR-12
c00007    Systems_analysis                  Boston             23-MAR-12
c00008    Systems_integration               Tokyo              24-FEB-12
c00009    Aquatic_biology                   Helsinki           12-MAY-12
c00010    Information_systems               Paris               08-JAN-12
c00011    Simulation_modeling               Rome                01-SEP-12
c00012    DSS                               Melbourne          18-DEC-12

Deals_C table:
EID   CONFID
---    ------
e02   c00001
e03   c00001
e05   c00001
e06   c00001
e03   c00002
e08   c00002
e09   c00002
e10   c00002
e03   c00003
e05   c00003
e06   c00004
e08   c00005
e09   c00005
e10   c00005
e06   c00005
e11   c00006
e12   c00006
e05   c00007
e06   c00007
e08   c00007
e09   c00008
e10   c00008
e11   c00008
e02   c00009
e12   c00009
e10   c00010
e02   c00011
e03   c00011
e05   c00011
e12   c00012
e06   c00012

The sql statement that I have is:
select C.Title
from Conference_C C
where C.ConfID in (select D.ConfID
                   from  Deals_C D
                   where D.eid in (select E.eid
                                   from Employee_C E
                                   where E.Name = 'Green'));

I got "no rows selected"
Comment: You don't have and deals with eid = 07.
Comment: Green's EID is e07 and you don't have any row with e07 EID in Deals_C table.
Comment: check my answer why its not returning record
Answer: The problem with your query is you are checking the wrong employee data. Your WHERE clause is checking the EID to the EID when it really should be checking the Deals_C.EID to the Employees.MID:
select C.Title
from Conference_C C
inner join
(
  select D.ConfID, e.eid
  from Deals_C D
  inner join Employee_C e
    on d.EID= e.EID
  where exists (select *
                from Employee_C e2
                where E2.Name = 'Green'
                  and e.mid = e2.eid)
) d
  on c.CONFID = d.CONFID

See SQL Fiddle with Demo.
The EXISTS query is returning the rows that have the last name of Green but you need to check the Employee_C.MID to the subqueries EID.
This can also be written:
select C.Title
from Conference_C C
where C.ConfID in (select D.ConfID
                   from Deals_C D
                   inner join Employee_C e
                     on d.EID= e.EID
                   where exists (select *
                                 from Employee_C e2
                                 where E2.Name = 'Green'
                                   and e.mid = e2.eid));

See SQL Fiddle with Demo
Answer: I just had this problem. The reason I had "no row selected" was simply because my sqlcase was set to UPPER and I was querying in lower case.
i.e. WHERE empName LIKE '_a%';
I set the sqlcase to mixed and solved my problem. Seems that string between quotes is case sensitive. Hope it helps.

Sql query: no rows selected


VMWare slowly freezing whole system

Question: Background:
I'm running Kubuntu 18.04 LTS and running Win 10 as guest for random MS specific apps OS on VMWare Workstation 15 Player. Everything appears to work really smooth and nice... for a while. After system has been up for a week or two, weird things start to happen.
At some point, I see various desktop features freezing/unresponsive, and by digging what's going on, it always seems to somehow point to vmware-vmx process. I.e. when I run simple ps aux at terminal, it gets frozen when printing details fof vmware-vmx. By doing strace ps aux I can see that it always gets stuck when reading from /proc/vmware-vmx-PID/cmdline file. The ps aux is frozen so hard that it can't be killed.

Also killing the vmware-vmx process doesn't seem to fix the problem. After killing the process, system continues to behave weird and cause lots of lock-ups with many apps. Only reboot seems to recover from it (or actually hard-reset, because reboot also gets stuck waiting to shutdown snapd daemon forever).
What is most terrifying is that doing the system reboot at that state has tendency to corrupt files that I assume some apps are trying to write when closing. On next boot I see some files being empty (i.e. thunderbird passwords were once lost, another time eclipse workspace settings were lost because it contained an empty file, vmware disk image was crapped also once).
Any idea what's going on here?
OR any positive experiences with vmware with long uptimes?
Thanks for sharing your thoughts!
Sys specs:

VMWare Workstation 15 Player 15.0.2
64 bit kernel 4.15.0-44
Core i5-6600
24 GB RAM, memtest86 pass
Geforce 1060 with NVidia drivers 410.78 (390.xx also tried, no difference)
KDE 5
Ubuntu updates up to date
System should be stable, it's been used for 3 years on Win7 without stability issues (uptime several months between boots & active use, no problems)
Comment: As an experiment I have ran VMWare without 3D acceleration enabled and no stability issue occurred during 24 day uptime. Perhaps the freezing is related to VMware's 3D support OR nvidia drivers. Next test is to try with other display drivers/GPU.
Answer: Try rolling back the kernel to 4.15.0-43 (or -42). There's known issues around external displays (though I've had the same lock-up symptoms you described the last two days). My kernel updated to 4.15.0-44 yesterday (check with grep 4.15.0-44 /var/log/dpkg.log). I suggest installing ukuu to manage kernels.
I'm also running Kubuntu 18.04 LTS, 64 bit on an i7-8850h, 32 GB RAM.
Links:

Redit link about the kernel bug
Ukuu Kernal Manager - FOSS Mint
Comment: Thanks for hint! However I'm not certain that these kernel version would solve this. The lockups have been haunting me since I installed Ubuntu, over two months ago, and it has gone thru few kernel versions on that time. All of them had same issue.

VMWare slowly freezing whole system


How to install Citrix receiver xubuntu 13.04 64-bit

Question: Anyone have a walkthrough on installing Citrix receiver on Xubuntu 13.04 64-bit?

Update
<code>$ sudo apt-get install libmotif4 nspluginwrapper

 ... snip ...
Setting up libmotif4:amd64 (2.3.3-7ubuntu1) ...
Setting up nspluginviewer (1.4.4-0ubuntu5) ...
Setting up nspluginwrapper (1.4.4-0ubuntu5) ...
plugin dirs: nspluginwrapper: no appropriate viewer found for /usr/lib/flashplugin-installer/libflashplayer.so
Auto-update plugins from /usr/lib/mozilla/plugins
Looking for plugins in /usr/lib/mozilla/plugins
Segmentation fault (core dumped) Processing triggers for libc-bin ...
ldconfig deferred processing now taking place

sudo dpkg --install Downloads/icaclient_12.1.0_amd64.deb
Selecting previously unselected package icaclient.
(Reading database ... 155808 files and directories currently installed.)
Unpacking icaclient (from .../icaclient_12.1.0_amd64.deb) ...
dpkg: dependency problems prevent configuration of icaclient:
icaclient depends on libc6-i386 (>= 2.7-1);
however: Package libc6-i386 is not installed. icaclient depends on ia32-libs;
however: Package ia32-libs is not installed.
icaclient depends on lib32z1;
however: Package lib32z1 is not installed. icaclient depends on lib32asound2;
however: Package lib32asound2 is not installed. dpkg:
error processing icaclient (--install): dependency problems -
leaving unconfigured Errors were encountered while processing: icaclient
</code>
Comment: Take a look at [Citrix ICA Client How To](https://help.ubuntu.com/community/CitrixICAClientHowTo).
Comment: $ sudo apt-get install libmotif4 nspluginwrapper
... snip ...
Setting up libmotif4:amd64 (2.3.3-7ubuntu1) ...
Setting up nspluginviewer (1.4.4-0ubuntu5) ...
Setting up nspluginwrapper (1.4.4-0ubuntu5) ...
plugin dirs:
nspluginwrapper: no appropriate viewer found for /usr/lib/flashplugin-installer/libflashplayer.so
Auto-update plugins from /usr/lib/mozilla/plugins
Looking for plugins in /usr/lib/mozilla/plugins
Segmentation fault (core dumped)
Processing triggers for libc-bin ...
ldconfig deferred processing now taking place
$

(puny 29 chars left. see next comment)
Comment: Tried to continue in spite of error above:

sudo dpkg --install Downloads/icaclient_12.1.0_amd64.deb
Selecting previously unselected package icaclient.
(Reading database ... 155808 files and directories currently installed.)
Unpacking icaclient (from .../icaclient_12.1.0_amd64.deb) ...
dpkg: dependency problems prevent configuration of icaclient:
 icaclient depends on libc6-i386 (>= 2.7-1); however:
  Package libc6-i386 is not installed.
 icaclient depends on ia32-libs; however:
  Package ia32-libs is not installed.
Comment: icaclient depends on lib32z1; however:
  Package lib32z1 is not installed.
 icaclient depends on lib32asound2; however:
  Package lib32asound2 is not installed.

dpkg: error processing icaclient (--install):
 dependency problems - leaving unconfigured
Errors were encountered while processing:
 icaclient
$
Comment: See if [this](http://techcell.chaseorigina.l.com/technotes/install-citrix-receiver-on-64bit-ubuntu/) helps you
Answer: Step 1.  Open a terminal and enter:  sudo apt-get install libmotif4 nspluginwrapper
Step 2.  Download and install the receiver. See the following video to understand what to download and what to expect when installing the receiver:  http://www.youtube.com/watch?v=JZVxNH76kj0
(Link to the official Citrix Receiver 12.1 .deb:  https://www.citrix.com/downloads/citrix-receiver/receivers-by-platform/receiver-for-linux-121.html)
Step 3.  When complete copy the certificates to the proper directory:
sudo cp /usr/share/ca-certificates/mozilla/* /opt/Citrix/ICAClient/keystore/cacerts
Step 4.  When accessing the Citrix environment tell the browser to open launch.ica (or launch.jsp) by using the following as the default app:  /opt/Citrix/ICAClient/wfica.sh
Good luck!


How to read an Internal ConfigurationSection from Web.Config in ASP.NET

Question: I am trying to read a Microsoft defined ConfigurationSection:

Microsoft.ApplicationServer.Caching.DataCacheClientSection

but the type is internal so I cannot access it in the conventional way.
i.e.
var dataCacheClientSection = (DataCacheClientSection)ConfigurationManager.GetSection("dataCacheClient");

I know I can use reflection but do I have any other options?
Answer: You can open the configuration file as XmlDocument and read whatever you want there using XPath.
Something like:
var xmlDoc = new XmlDocument();
xmlDoc.Load(Assembly.GetExecutingAssembly().Location + ".config");
XmlNode setting = xmlDoc.SelectSingleNode("configuration/...");

Use the correct XPath in SelectSingleNode
Comment: Thanks. Was afraid that it might come down to that.


How to bind DataGridComboBoxColumn to List

Question: I've wanted to create a ComboBoxColumn with specific options for each row
e.g.
List string
public List<string> Types
        {
            get
            {
                if (PropertyType == typeof(bool))
                {
                    return FilterCharacters.BoolList;
                }

                if (PropertyType == typeof(string))
                {
                    return FilterCharacters.TextList;
                }
                if (PropertyType == typeof(int) || PropertyType == typeof(double) ||
                    PropertyType == typeof(float))
                {
                    return FilterCharacters.NumberList;
                }
                return new List<string>();
            }
        }

Lists itself
public static class FilterCharacters
    {
        public static Dictionary<FilterTypes, string> FilterCharactersList => new Dictionary<FilterTypes, string>()
                {
                    {FilterTypes.Equals, "=" },
                    {FilterTypes.NotEquals, "!=" },
                    {FilterTypes.Greater, ">" },
                    {FilterTypes.GreaterOrEqual, ">=" },
                    {FilterTypes.Less, "<" },
                    {FilterTypes.LessOrEqual, "<=" },
                    {FilterTypes.Contains, "contains" },
                    {FilterTypes.NotContains, "does not contain" },
                    {FilterTypes.True, "True" },
                    {FilterTypes.False, "False" }
                };

        public static List<string> NumberList => new List<string>()
        {
            FilterCharactersList[FilterTypes.Greater],
            FilterCharactersList[FilterTypes.GreaterOrEqual],
            FilterCharactersList[FilterTypes.Less],
            FilterCharactersList[FilterTypes.LessOrEqual],
            FilterCharactersList[FilterTypes.Equals],
            FilterCharactersList[FilterTypes.NotEquals]
        };

        public static List<string> TextList => new List<string>()
        {
            FilterCharactersList[FilterTypes.Contains],
            FilterCharactersList[FilterTypes.NotContains],
            FilterCharactersList[FilterTypes.Equals],
            FilterCharactersList[FilterTypes.NotEquals]
        };

        public static List<string> BoolList => new List<string>()
        {
            FilterCharactersList[FilterTypes.True],
            FilterCharactersList[FilterTypes.False]
        };
    }

and xaml
<DataGrid ItemsSource="{Binding}"  Grid.Row="0" Grid.Column="0" x:Name="FiltersList1" AutoGenerateColumns="False">
            <DataGrid.Columns>
...
<DataGridComboBoxColumn Width="120" ItemsSource="{Binding Path=Types}"/>

I've tried binding to FiltersList1 DataContext, ItemsSource, i've also tried specifying the SelectedItemBinding, ComboBoxStyles but it all ended in either nothing at all (an empty combobox) or an error in the output saying

System.Windows.Data Error: 2 : Cannot find governing FrameworkElement
or FrameworkContentElement for target element.
BindingExpression:Path=DataContext.Types; DataItem=null; target
element is 'DataGridComboBoxColumn' (HashCode=15167431); target
property is 'ItemsSource' (type 'IEnumerable')

I've ran out of ideas and could not match any found answer on the internet to this problem
Answer: The trick is to use an ElementStyle and an EditingElementStyle to set the ItemsSource:
<DataGridComboBoxColumn Width="120">
    <DataGridComboBoxColumn.ElementStyle>

    </DataGridComboBoxColumn.ElementStyle>
    <DataGridComboBoxColumn.EditingElementStyle>

    </DataGridComboBoxColumn.EditingElementStyle>
</DataGridComboBoxColumn>

Comment: Thanks for the answer, it did show the items as expected but now i stumbled upon an issue with selecting items. When i change the selection from blank to any element and change cell the selection goes back to the blank one. Do you maybe know how to prevent that?
Comment: Please ask a new question if you have another issue. Your original question has already been answered.


TCL Script Error Issue: [dim]GetAttrib: Missing current element

Question: Problem with this script is that I can't get any info on the internet.
Can someone help to identify where is the issue?
This is a working script, but since last week, a new Account was added, and after that this script does not run properly anymore.
I manually added the newly added Account into my OLAP cube, and try to run the script agian, but to no avail.
What is GetAttrib: Missing current element?
#backup the OLAP and test&check FORECAST cleaning act. month and copy from FORECAST
###run transfer to Jan script !!!!
###manually backup MIS/R&D!!!! before because of changed IMD

#New Accounts & Update the Account name!
#OPEN ISSUES:   ORDERPOS
#               new parents 612x and 615x for exceptional accounts, if parents not already available (manually added/configured)

set sFilePath "d:\\PM10\\import Log files\\ACCOUNT_History.txt"
if {[file exists $sFilePath]==1} {
  set iFileID [open $sFilePath "a"]

  OLAP2 SelectDimension "ACCOUNT" dim

  RDB1 NewCursor "VIIPER.ACCOUNT" curs

  curs Open

  set iElement 0
  set iParent 0
  set iUpdateACCOUNT 0

  while {[curs Next]==1} {
   set sOrderpos "99999"
   if {[dim SelectElement $curs(ACCOUNT_ID)] == 0} {

     #1:ASSIGN
     set PL1 "6"
     set PL2 "7"
     if { [string compare [string range $curs(ACCOUNT_ID) 0 0] $PL1] == 0 || [string compare [string range $curs(ACCOUNT_ID) 0 0] $PL2] == 0} {
       set sAssign "1"
      } else {
       set sAssign "2"
     }

     #Parent
     set sParent [string range $curs(ACCOUNT_ID) 0 2]

     #1:ORDERPOS
     set sElementOrderpos3 [string range $sParent 0 2]
     append sElementOrderpos3 "00000"

     set sElementOrderpos2 [string range $sParent 0 1]
     append sElementOrderpos2 "000000"

     set sElementBefore [expr $curs(ACCOUNT_ID) - 1]

     #backwards check to get the latest available account element to use the orderpos+1 - does not work for Orderpos! but needed for account check!!!!
     while {$sElementBefore >= $sElementOrderpos3} {
      if {[dim SelectElement $sElementBefore] == 1} {
       set sOrderpos [expr [dim GetAttrib "1:ORDERPOS"] + 1]
       break
      }
      set sElementBefore [expr $sElementBefore - 1]
     }

     #parent "###" is needed/to be created, if not available
     if {([string compare $sElementOrderpos3 "612"] != 0 && [string compare $sElementOrderpos3 "615"] != 0)} {

      if {[string compare $sOrderpos "99999"] == 0} {
       puts "--> ISSUE in ACCOUNT: $curs(ACCOUNT_ID) - check if parents (XX/XXX) are available!"
###########################################################################################
###########################################################################################
#delete next lines  "###" after check
###       if {$sElementBefore < $sElementOrderpos2} {
###        set sElementOrderpos2 [expr [string range $sParent 0 1] -1]
###        append sElementOrderpos2 "000000"
###        while {$sElementBefore > $sElementOrderpos2} {
###         if {[dim SelectElement $sElementBefore] == 1} {
###          set sOrderpos [expr [dim GetAttrib "1:ORDERPOS"] + 1]
###
###          dim NewNElement $sParent
###          dim PutAttrib "1:NAME" $curs(ACCOUNT_NAME)
###          dim PutAttrib "2:ENGLISH" $curs(ACCOUNT_NAME)
###          dim PutAttrib "2:GERMAN" $curs(ACCOUNT_NAME)
###          dim PutAttrib "1:ASSIGN" $sAssign
###          set sNewCParent [string range $sParent 0 1]
###          dim PutAttrib "1:ORDERPOS" $sOrderpos
###          dim MemberOf $sNewCParent
###
###          puts "Created New Parent: $sNewCParent, Account: $sElementOrderpos3 -->please check Element and Attributes"
###          fputs $iFileID "$act_date  NewParent   $sNewCParent    $sAssign    $curs(ACCOUNT_NAME)"
###
###          set sOrderpos [expr $sOrderpos + 1]
###          set iParent [expr $iParent + 1]
###          break
###         }
###         set sElementBefore [expr $sElementBefore - 1]
###        }
###########################################################################################
###########################################################################################
          }
       } else {

        while {$sElementBefore > $sElementOrderpos2} {
         if {[dim SelectElement $sElementBefore] == 1 && [dim SelectElement $sParent] == 0} {

          set sOrderpos [expr [dim GetAttrib "1:ORDERPOS"] + 1]

          dim NewNElement $sParent
          dim PutAttrib "1:NAME" $curs(ACCOUNT_NAME)
          dim PutAttrib "2:ENGLISH" $curs(ACCOUNT_NAME)
          dim PutAttrib "2:GERMAN" $curs(ACCOUNT_NAME)
          dim PutAttrib "1:ASSIGN" $sAssign
          set sNewCParent [string range $sParent 0 1]
          dim PutAttrib "1:ORDERPOS" $sOrderpos
          dim MemberOf $sNewCParent

          puts "Created New Parent Account and Account: $sElementOrderpos3 -->please check Element and Attributes"
          fputs $iFileID "$act_date NewParent   $sNewCParent    $sParent    $sAssign    $curs(ACCOUNT_NAME)"

          set iParent [expr $iParent + 1]
          set sOrderpos [expr $sOrderpos + 1]
          break
         }
         set sElementBefore [expr $sElementBefore - 1]
        }
      }
      CloseDimension dim
      OLAP2 SelectDimension "ACCOUNT" dim
     }

     dim NewNElement $curs(ACCOUNT_ID)
     dim PutAttrib "1:NAME" $curs(ACCOUNT_NAME)
     dim PutAttrib "2:ENGLISH" $curs(ACCOUNT_NAME)
     dim PutAttrib "2:GERMAN" $curs(ACCOUNT_NAME)
     dim PutAttrib "1:ORDERPOS" $sOrderpos
     dim PutAttrib "1:ASSIGN" $sAssign

     #exception in level logic XXXX instead of XXX AND Exception for 612x which is not 6120 then fix to 6122
     if {([string compare $sElementOrderpos3 "612"] == 0 || [string compare $sElementOrderpos3 "615"] == 0)} {
      "--> PARENT Exception for 612x or 615x"
      if {[string compare [string range $curs(ACCOUNT_ID) 0 3] "6120"] == 0 || [string compare $sElementOrderpos3 "615"] == 0} {
        set sParent [string range $curs(ACCOUNT_ID) 0 3]
       } else {
        puts "--> PARENT exception fix to '6122'"
        set sParent "6122"
      }
     }

     dim MemberOf $sParent
     puts "New ACCOUNT: $curs(ACCOUNT_ID), Parent $sParent, $curs(ACCOUNT_NAME), Orderpos: $sOrderpos, Assign: $sAssign"
     fputs $iFileID "$act_date  NewAccount  $sParent    $curs(ACCOUNT_ID)   $sAssign    $curs(ACCOUNT_NAME)"
     set iElement [expr $iElement + 1]
     CloseDimension dim
     OLAP2 SelectDimension "ACCOUNT" dim
    } else {

     #update name
     dim SelectElement $curs(ACCOUNT_ID)
     set oldACCOUNTname [dim GetAttrib "1:NAME"]
     set sOrderpos [dim GetAttrib "1:ORDERPOS"]
     if {[string compare $curs(ACCOUNT_NAME) $oldACCOUNTname] != 0} {
      dim PutAttrib "1:NAME" $curs(ACCOUNT_NAME)
      dim PutAttrib "2:ENGLISH" $curs(ACCOUNT_NAME)
      dim PutAttrib "2:GERMAN" $curs(ACCOUNT_NAME)
      #dim PutAttrib "1:ORDERPOS" $sOrderpos
      puts "Updated ACCOUNT: $curs(ACCOUNT_ID); new Name: $curs(ACCOUNT_NAME); old Name: $oldACCOUNTname"
      fputs $iFileID "$act_date Update  $curs(ACCOUNT_ID)   $curs(ACCOUNT_NAME) old: $oldACCOUNTname"
      set iUpdateACCOUNT [expr $iUpdateACCOUNT + 1]
     }
   }
  }

  dim Sort -type CN -name ASC NOCASE -recursive
  #-attrib "1:ORDERPOS" ASC NOCASE -recursive

  DeleteCursor curs

  CloseDimension dim

  close $iFileID

 } else {
    puts "File do not exit"
}

puts "New ACCOUNT Parents #: $iParent"
puts "New ACCOUNT Elements #: $iElement"
puts "Updated ACCOUNT Elements #: $iUpdateACCOUNT"

this is the output is generated.
Import started at 18 Feb 2021 02:21:32.
---------------------------------------------------
Loading Script DLL
C:\Program Files (x86)\Common Files\Cubeware\cwscript85.dll
MMM-2020
---------------------------------------------------
ACCOUNT structure: Starting jobs at 18 Feb 2021 02:21:32
Execute script: ACCOUNT structure - Started at 18 Feb 2021 02:21:32
Driver 'C:\Program Files (x86)\Common Files\Cubeware\cwiopmolap.dll' loaded. Version: 220.127.116.11
OLAP2: Infor PM OLAP on mis/MIS connected.
Driver 'C:\Program Files (x86)\Common Files\Cubeware\cwiroledb.dll' loaded. Version: 188.8.131.52
RDB1: OLE DB (OraOLEDB.Oracle): misdb user: melexis_pm connected.
Error in script 'ACCOUNT structure', Line: 10
[dim]GetAttrib: Missing current element.
---------------------------------------------------
Freeing resources
Error in import
Import finished at 18 Feb 2021 02:21:37

Comment: I can't tell where the problem is; the `GetAttrib` call is hidden somewhere. We need a proper traceback, and my answer should say how to get one.
Answer: I just love how that script is not printing where the problem was encountered! (Standard tclsh is scrupulous about printing error traces because it helps so much with tracking down problems.) Fortunately, we can add code to the script to make this much easier to track. Note that this is not really an answer, but rather information that might help you debug what's going wrong (but it's too long and structured for a comment).
Put this at the top:
package require Tcl 8.5
proc PrintTraceOnError {script} {
    set code [catch {uplevel 1 $script} msg opt]
    if {$code == 1} {
        puts "ERROR: $msg"
        puts "EXCEPTION CODE: [dict get $opt -errorcode]"
        puts "TRACEBACK: [dict get $opt -errorinfo]"
    }
    # Re-raise the error or send on the normal result
    return -options $opt $msg
}

Then wrap the rest of your script in PrintTraceOnError { and } to get better information about what actually went wrong. Hopefully that will be enough for you to figure out what information is missing or what schema change you have to adapt to.


Why do my LED strip lights only work if I reverse the connection polarity?

Question: Hi I have installed a small run of LEDs but they do not work at all unless I reverse the connection that goes directly on to the stip so that it's not lining up with 12v symbol. I tested everything before cutting the strip to length and it worked fine but now it will not switch on with remote. I have changed the controller and remote with different ones but still no go.
I would be very greatful for any help.
Thanks
Comment: Hello, and welcome to Stack Exchange. A manufacturer/model number might help, as would a picture or two.
Comment: I'm confused, you can get it to work if you swap the wires?
If so, that is the correct orientation, and possibly your supply or the markings are incorrect.  LEDs will only work one way, and if they're working at all, that's the way they need to be.   If you have a test meter, check the polarity at the strip and the supply.
Answer: I just received some LED tape from a supplier in the US  from ebay.  The polarity marked on the tape was incorrect and the factory ends had the red wire to the negative mark.   The markings on your strips may also be incorrect.
Answer: Look very closely on the cut LED strips and make sure you did not short the + and - sides to each other somewhere, such as where you cut it... if the strip is shorted, the power supply will sense that and shut it down.
Also keep in mind, polarity matters on LEDs - if you hook the wires to the strip backwards, it will refuse to light.  Won't do it any damage, just reverse polarity and it should light.
Comment: An LED hooked up backwards can let the magic smoke out if the supply curent is avaiable, many of the strings do not have reverse polarity protection.


Terarria Ore Map Reference

Question: Does anyone have or know of a decent reference for ore color (and possibly typical depths) on the minimap? I am on a console (no mods); I see a lot of images full screen map discovery (from PCs), but none calling out all the ores (or basic ones... specifically I have no idea what lead/tin/iron/titanium look like on my map) and I get lost running around looking all over the place x_x
Comment: I don't know how this would work on console, if it does at all, but on PC you can hover the cursor over an ore patch on the map to have a tooltip pop up naming what kind of ore it is.
Answer: I couldn't find one so I made my own. Note I made this on PC so I'm not sure if console has the exact same colors.

Row 1: copper, iron, silver, gold, demonite, meteorite, hellstone
Row 2: tin, lead, tungsten, platinum, crimtane, chlorophyte
Row 3: cobalt, mythril, adamantium
Row 4: palladium, orichalcum, titanium

Terarria Ore Map Reference


Is there a way to get clues about each blade favorite items?

Question: To unlock new orbs you often have to put items of a specific category in the pouch. Some other time you have to put the blade's favorite item.
Spoiler :

 I did notice that at some point in a cinematic near chapter 2 or 3 while in an inn you can see Pyra having a cup of tea and saying that she enjoys it a lot or something like that which made me think that tea would be her favorite item.

Other than that I didn't see any hints for the other blades (I might have missed it). But still for blades you don't see in cinematics aside from trying everything single category and then every single item of that category I don't see how you can achieve that.
So is there any way to know which specific item (or even category for that matter) is their favorite ?
Comment: You can always check the spreadsheet to just get the answers.
Answer: The Rare Blade Boreas gives clues to the favorite pouch items of party members and their personal blades when his affinity chart is filled out.
For other Blades, some of them have clues to their favorite items in their respective affinity charts when nodes are filled in.
Answer: There are many dialogue clues like the one you mentioned.  The wide majority come from speaking with <code>*</code> dialogue NPCs, but some come from cutscenes as well.
Minor spoiler, example:

One early example that springs to mind is when someone jokes to Nia that she might devour some meat, and she replies that she actually loves fish.


Auto add  tag in Wordpress post after 300 words

Question: How can I automatically add nextpage tag in Wordpress posts? I have blog with long texts and want to show them like a book, divided in pages.
I use this in my single.php but there is no second page of post:

        <?php echo wp_trim_words(get_the_content(), 250 ,''); ?>
        <?php wp_link_pages(); ?>

In my theme pagination was single and I change it
<?php the_content(); ?>

 '' . esc_html__( 'Pages:', 'author' ), 'after' => '', ) ); ?>

It's not an option manually to add nextpage tag or more, because some of texts are with 1000 pages
Answer: wp_trim_words This function trims text to a certain number of words and returns the trimmed text.
EX:-
wp_trim_words(get_the_content,500,'');

it will put the  tag after 500 words..
Comment: you want to put  tag after certain words.. this is for that thing. if you want to create the whole new page then show some code of what have you done? at which stage you are facing problems..  no one will write the complete code for you. show some of your efforts..
Comment: I know that no one will write my code but I'm stuck with that for 3 days. Yes, I want to put  tag after certain words and split my post into couple of pages - 2, 3 or more, depends of how long is post. I will find a way. Thank you again!
Comment: if you have done something then update your question so that  we can have better idea.


Android app package name

Question: When creating an Android application using Java, you place your classes into packages such as com.example.appName
However, in the Android XML manifest file, you also specify the package there.
It is my understanding that the Google Play Store, where Android apps are uploaded, uses the package name as a unique identifier for your app.
So, which package name actually identifies your app/APK file? And can the package names in your code be different to the package name in the manifest?
Answer: Only the package name in AndroidManifest.xml counts and must not change. The package you put your Java classes in can be anything.
Comment: @LiamFlaherty They are not ignored. Your manifest must for example state the full (java) package name of your Activities. As long as they are the same you can write something short like ".MainActivity" and it will assume that you mean "[package name].MainActivity", if they are different you'll have to write down the full path. Java package name: to organize your code as you like. Manifest package name: Play Store App identifier.
Comment: So the package names in code and the manifest are completely independent of each other? And the package names in code are basically ignored?
Answer: The Play store picks up the package as the identifier from the manifest file.
It really doesn't matter if your source files go into the same package or something else.
So, you can manage/arrange your source files into any arbitrary packages you want.
Generally, it's easier to have your source files in the same package/sub-package as your manifest file, so that referencing them from the manifest file is easier, as you will not have to specify the fully qualified class names for your activities/services etc.
Answer: which package name actually identifies your app/APK file?

play store will take only Android manifest package. like package="com.example.appName"
 can the package names in your code be different to the package name in the manifest?

yes, you can use different package for your code but need to give the absolute package name when declaring in manifest.xml
android:name="org.demo.MyFile"

Comment: So the package name in the manifest can't be completely different to any package names in the code?
Answer: Android XML manifest file package is understanding by the Google Play Store because  Google Play Store only read this file , when you upload android application in google play store.
so, if you src package and manifest is different then it do not make any problem.
Thanks
Answer: I just want to add couple more observation:
* the field package from AndroidManifest is also used for package of generated classes (e.g. R class)
* and something  important if you are using google map v2 in your project pay attention of the package used in authorization because need to be the same. if you don't do that it will just not fetch the map but with no error message in logcat. (just hit this issue today and yesterday)
googlemap v2 version 8.1.1
google play services 4.4.52
Answer: The answers here seem a little out from my experience.
In Android Studio the applicationId in your Build.Gradle is the important attribute and should not change.
Our Manifest package name was different from our applicationId, I changed them to be the same and was able to upload the APK to Google Play without error.

Android app package name


Android app crashing due to null pointer exception.Getting error in Recyclerview adapter

Question: I am using Recyclerview and Recyclerview adapter generate the null pointer exception .I had tried many things,but i cannot understand the reason.The error say The function  getitem count () in Recylcerview adapter is returning null value.
Following is My activity code.
package com.example.builderpro;

public class   project_list extends AppCompatActivity  {
MyViewModel myViewModel;
 List<Dproject>  myprojectlist;
Toolbar toolbar;
RecyclerView recyclerView;

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if(keyCode== KeyEvent.KEYCODE_BACK) {
        return false;
    }
    return super.onKeyDown(keyCode, event);
}
@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_project_list);

        toolbar=(Toolbar)findViewById(R.id.custom_toolbar);
        recyclerView=(RecyclerView)findViewById(R.id.recycler_view);

    setSupportActionBar(toolbar);

    RecyclerView.LayoutManager layoutManager= new LinearLayoutManager(getApplicationContext());
    recyclerView.setLayoutManager(layoutManager);

    final MyAdaptor myAdaptor=new MyAdaptor();
    recyclerView.setAdapter(myAdaptor);
    final   int sid= getIntent().getIntExtra("supervisor_id",0);

    myViewModel= ViewModelProviders.of(this).get(MyViewModel.class);
    myViewModel.GetAllProject().observe(this, new Observer<List<Dproject>>() {
        @Override
        public void onChanged(List<Dproject> dprojects) {

            myAdaptor.setproject(dprojects);

         }
     });

    }
     @Override
     public boolean onCreateOptionsMenu(Menu menu) {

     getMenuInflater().inflate(R.menu.logout_menu,menu);

      return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
    if(item.getItemId()==R.id.logout)
    {
        SharedPreferences preferences= getSharedPreferences("checkbox",MODE_PRIVATE);
        SharedPreferences.Editor editor= preferences.edit();
        editor.putString("remember","false");
        editor.apply();
        finish();

    }
    return super.onOptionsItemSelected(item);
    }
    }

Following is my Adapter code
package com.example.builderpro;

public class MyAdaptor extends RecyclerView.Adapter<MyAdaptor.projectViewHolder>{
private Context context;
private List<Dproject>  myprojectlist;
int Position;

public MyAdaptor() {
}

public MyAdaptor(Context context, List<Dproject> myprojectlist) {
    this.context = context;
    this.myprojectlist = myprojectlist;

}

class   projectViewHolder extends RecyclerView.ViewHolder
{
    ImageView imageView,imageView2;
    TextView title,discription,address;
    Button Button1,Button2;

    public projectViewHolder(View itemView) {
        super(itemView);
        imageView=itemView.findViewById(R.id.Project_Image);
        title=itemView.findViewById(R.id.Project_Title);
        address=itemView.findViewById(R.id.project_address);
        discription=itemView.findViewById(R.id.project_dis);
        Button1=itemView.findViewById(R.id.activity_button);
        Button2=itemView.findViewById(R.id.labour_button);
        imageView2=itemView.findViewById(R.id.card_back);

    }
    }

    @Override
    public projectViewHolder onCreateViewHolder( ViewGroup parent, int viewType) {
    View mview= LayoutInflater.from(parent.getContext()).inflate(R.layout.cardview,parent,false);

    return new projectViewHolder(mview);
    }

    @Override
    public void onBindViewHolder(projectViewHolder holder, int position) {
    Position=position;
    Dproject current_project= myprojectlist.get(position);
    holder.imageView.setImageResource(R.drawable.projectpic);
    holder.title.setText(current_project.getClient_Name());
    holder.discription.setText(current_project.getProject_Discription());
    holder.address.setText(current_project.getLocation());
    holder.Button1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent=new Intent(context,activity.class);
            context.startActivity(intent);
        }
    });

    }

    @Override
    public int getItemCount()
    {
    return myprojectlist.size();

     }

    public void setproject(List<Dproject> dprojects)
    {
    this.myprojectlist=dprojects;
    notifyDataSetChanged();
    }
    }

These lines are from Logcat
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.builderpro, PID: 21616
java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.List.size()' on a null object reference
    at com.example.builderpro.MyAdaptor.getItemCount(MyAdaptor.java:83)
    at androidx.recyclerview.widget.RecyclerView.dispatchLayoutStep1(RecyclerView.java:4044)
    at androidx.recyclerview.widget.RecyclerView.onMeasure(RecyclerView.java:3534)
    at android.view.View.measure(View.java:19857)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6083)
    at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1464)
    at android.widget.LinearLayout.measureVertical(LinearLayout.java:758)
    at android.widget.LinearLayout.onMeasure(LinearLayout.java:640)
    at android.view.View.measure(View.java:19857)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6083)
    at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
    at androidx.appcompat.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:143)
    at android.view.View.measure(View.java:19857)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6083)

Please help me because i have been stuck on this error for about 5 days. It is really  appreciable.
Answer: Try to change your adapter getItemCount() to return 0 items if the list is not yet intialized
@Override
public int getItemCount()
{
  if (myprojectlist != null)
     return myprojectlist.size();
  else
     return 0;
 }

Comment: it's work .Thanks Man . Im very grateful to you.
Comment: Can you tell me about question is closed by some user bcz im new on this site.
Comment: @UmairKhan usually for common questions, like that of you that has NullPointerException which is the most common exception in Java, questions are closed as they are already asked over and over and the reason is the same, which is calling a method on an object that is not initialized yet .. you can check [this](https://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) out


Android Google Cloud Storage Duplicate Files

Question: When I add compile group: 'com.google.cloud', name: 'google-cloud-storage', version: '0.8.0-beta' it shows an error when I run the app
Error:Execution failed for task ':app:transformResourcesWithMergeJavaResForProductionDebug'.
> com.android.build.api.transform.TransformException: com.android.builder.packaging.DuplicateFileException: Duplicate files copied in APK META-INF/INDEX.LIST
    File1: /.gradle/caches/modules-2/files-2.1/com.google.cloud/google-cloud-storage/0.8.0-beta/92c10417dd9ef400564414c243eecdd0a7f51963/google-cloud-storage-0.8.0-beta.jar
    File2: /.gradle/caches/modules-2/files-2.1/com.google.cloud/google-cloud-core/0.8.0/5fe7f10ded15149a5fc633d98adbacf11b00907f/google-cloud-core-0.8.0.jar

I added excluding the META INF files
packagingOptions {
    exclude 'META-INF/MANIFEST.MF'
    exclude 'META-INF/ASL2.0'
    exclude 'META-INF/DEPENDENCIES.txt'
    exclude 'META-INF/LICENSE.txt'
    exclude 'META-INF/NOTICE.txt'
    exclude 'META-INF/NOTICE'
    exclude 'META-INF/LICENSE'
    exclude 'META-INF/DEPENDENCIES'
    exclude 'META-INF/notice.txt'
    exclude 'META-INF/license.txt'
    exclude 'META-INF/dependencies.txt'
    exclude 'META-INF/LGPL2.1'
}
Tried https://github.com/GoogleCloudPlatform/google-cloud-java#quickstart, same issue
Any solutions?
Answer: Solution
Downloaded jar files from maven and added them to lib folder

google-api-services-storage-v1-rev92-1.22.0.jar
google-cloud-0.8.0.jar
google-cloud-core-0.8.0.jar
google-cloud-storage-0.8.0-beta.jar

And excluded duplicated files in app build.gradle
packagingOptions {
    exclude 'META-INF/LICENSE'
    exclude 'META-INF/io.netty.versions.properties'
    exclude 'META-INF/INDEX.LIST'
}

Answer: You may encounter the emergence of duplicates on the cloud storage.
If this happens, you can use the service to identify and delete duplicates.
http://alternativeto.net/software/duplicate-file-finder-and-remover/


Expectation of maximum between zero and a function of a random variable

Question: Let $v$ be a random variable uniformly distributed over [0,1]. Let $\alpha$ be a constant, where $0<\alpha<1/2$, so that $0<2\alpha<1$.
How can I express: $\mathbb{E}\left(Max\{2\alpha, v\}-v\right)$?

Here's what I've tried "intuitively":

$$\mathbb{E}(Max\{2\alpha, v\}-v) = \mathbb{E}(Max\{2\alpha-v, 0\})\\
=\mathbb{P}(2\alpha-v \geq 0)\cdot (2\alpha-v)+ [1-\mathbb{P}(2\alpha-v \geq 0)]\cdot 0 \\
= \mathbb{P}(v \leq 2\alpha) \cdot (2\alpha-v) + 0 = 2\alpha \cdot (2\alpha-v)$$

Which seems incorrect given this very similar question here. Instead,

$$\mathbb{E}(Max\{2\alpha, v\}-v) = \mathbb{E}(Max\{2\alpha-v, 0\})\\
=\mathbb{P}(2\alpha-v \geq 0)\cdot \mathbb{E}(2\alpha-v|2\alpha-v\geq0)+ [1-\mathbb{P}(2\alpha-v \geq 0)]\cdot 0 \\
= \mathbb{P}(2\alpha-v \geq 0)\cdot \mathbb{E}(2\alpha-v|2\alpha-v\geq 0) \\
= \mathbb{P}(v \leq 2\alpha) \cdot \mathbb{E}(2\alpha-v|2\alpha-v\geq 0)\\
= 2\alpha \cdot \mathbb{E}(2\alpha-v|2\alpha-v\geq 0)$$
However I am not sure about $\mathbb{E}(2\alpha-v|2\alpha-v>0)$, in turn because I can't find the distribution of $2\alpha-v$, is it a Uniform over [-1, 1]? so that we would have: $\mathbb{E}(2\alpha-v|2\alpha-v> 0)=1/2$, and $\mathbb{E}\left(Max\{2\alpha, v\}-v\right) = \alpha$?
Thanks,
Comment: You cannot have the answer in terms of $v$ (which is a r.v.. So your attempt fails.
Answer: Distribution of $2\alpha -v$ is not needed. Use the fact that if $X$ has density function $f$ then $Eg(X)=\int g(x)f(x)dx$
$E(2\alpha -v|2\alpha -v \geq 0)=\frac 1 {2\alpha} \int_0^{2\alpha} (2\alpha -t)dt=\alpha$.
[The denominator is $P(v \leq 2\alpha)$].
Comment: First question: YES. Second question: You have to evaluate it using the density function. That is what I have done in my answer.  @Banalaude
Comment: Thank you! Is $\mathbb{E}(2\alpha -v | 2\alpha -v \geq 0)$ equal to $\mathbb{E}(2\alpha -v | v \leq 2 \alpha)$ ?
If no, maybe I've done a mistake earlier and not formulate my question correctly... (sorry about that). What would be $\mathbb{E}(2\alpha -v | v \leq 2\alpha)$ equal to then?
Comment: All good now, thanks again!
Answer: You are right in that your "intuitive" method (1) is not correct - notice that your random variable $v$ still appears at the end of your expected value, which should be a number.
Your method (2) following the linked post uses a wise strategy (the "law of total expectation" to decompose it into two manageable parts). Your calculations up to the end look correct, so it suffices to compute $\mathbb{E}[2\alpha - v \mid 2\alpha - v > 0]$ as you recognised.
Notice that $v \sim \mathrm{Uniform}(0, 1)$, so $2\alpha - v \sim \mathrm{Uniform}(2\alpha, 2\alpha - 1)$. You can prove that $2 \alpha - v \mid 2\alpha - v > 0$ is actually uniform over $[0, 2\alpha]$ - intuitively this is by symmetry, and more rigorously you can prove this by using the definition of conditional probability. Thus, the expected value is $\alpha$.
(Alternatively, the answer by @Kavi Rama Murthy is of course true in general as well, since it is essentially using the definition of expectation.)
Comment: Thank you! All good :)


Range Slider that accepts User input to set the range?

Question: I'm beginning to think this might not be possible? I have looked around thoroughly and cannot seem to find a case where user can input numbers into 2 different boxes, hit enter, then have the range slider adjust accordingly. This is what I am trying to accomplish.
I am using the jQuery UI range slider. However if there are other means of accomplishing this, I would love to hear it.
This is what I have so far:    https://codepen.io/pen/

    From:
    <input type="text" id="range_from" name="range_from" style="color:#b9cd6d;font-weight:bold;width:60px;">

    To:
    <input type="text" id="range_to" name="range_to" style="color:#b9cd6d;font-weight:bold;width:60px;">

$(function () {
    var from = document.getElementById('range_from').value;
    var to = document.getElementById('range_to').value;
    var myValues = [from, to];

    $("#slider").slider({
        range: true,
        min: 0,
        max: 1000,
        values: myValues,
        slide: function (event, ui) {
            $("#range_from").val("$" + ui.values[0]);
            $("#range_to").val("$" + ui.values[1]);
        }
    });
});

Range values are displaying and change depending on position of the slider handles, which is great, but in addition to this I want user to be able to input their own numbers in the boxes then have the range slider adjust itself based on the new values.
I found this jsfiddle that is very similar to what I'm trying to accomplish, except user has to click a button to change the slider values as opposed to user hitting enter on keyboard or it just changing right as a new value is entered:
http://jsfiddle.net/YSEGU/1
Maybe what I am trying to do is not possible?
Answer: Just add a listener on the change event of the inputs like this:

['min', 'max'].map(x => document.getElementById(x)).forEach(x => x.addEventListener('change', function (e) {
    let [min, max] = $("#slider-range").slider('values');
    if (e.target.id === 'min') {
      min = parseInt(e.target.value, 10);
    } else if (e.target.id === 'max') {
      max = parseInt(e.target.value, 10);
    }
    $("#slider-range").slider('values', [min, max]);
    updateValues(min, max);
  }));

const minInit = 75;
const maxInit = 300;

$("#slider-range").slider({
  range: true,
  min: 0,
  max: 500,
  values: [minInit, maxInit],
  slide: function (_, { values: [min, max] }) {
    updateValues(min, max);
  }
});

updateValues(minInit, maxInit);

function updateValues(min, max) {
    $("#amount").val(`\$${min} - \$${max}`);
}
<link rel="stylesheet" href="http://code.jquery.com/ui/1.9.0/themes/base/jquery-ui.css" />

    Price range:
    <input type="text" id="amount" style="border: 0; color: #f6931f; font-weight: bold;" />

    Min :<input type='text' id='min' /> Max:<input type='text' id='max' />
Comment: Thank you, this works nicely for a visual representation. The slider bar changes depending on the inputted values. But the actual value themselves are not changing. When I console.log, the min and max will always be what is assigned in the beginning (0, 500).
Comment: What exactly did you `console.log`? The actual values are easily retrievable at any moment with `let [min, max] = $("#slider-range").slider('values');`
Comment: I used `console.log(min, max);`  but I was doing it in the wrong area of the code. I see the line of code you are speaking of. Thank you for this solution, much appreciated!
Comment: Here is an updated codepen if anyone wants to see in action: https://codepen.io/hodgestr/pen/XWMRyJM


Why aren't controllers for players 3 and 4 detected for Battle Arena mode?

Question: We are trying to play the 4-player split screen multiplayer mode of LEGO Dimensions Battle Arena on the Wii U.
I have 3 WiiMotion Plus with Nunchucks controllers and the Wii U gamepad.  We are trying to play with 4 players.

The Wii U gamepad registers player 1 correctly.
The first wiimote (left square lit) registers player 2 correctly when the + button is pressed.
The second and third wiimotes (with their second and third player lights lit on each wiimote respectively) are not being detected by the game.  The screen continues to prompt to press a button on the controllers for players 3 and 4.
During gameplay, it continues to prompt to connect a Wii remote / pro controller for players 3 and 4.

Why might these 2 player controllers not be detected by LEGO Dimensions?  They are registered with the WiiU system and they have fresh batteries, and their led lights indicate the appropriate player positions.
Comment: I also put a ticket in with WB Games support, so if I find out anything, I'll update the question or add an answer.
Answer: Apparently my kid failed to allow all of the most recent updates to download and patch the game.  Once those were done, I started up Battle Arena and was able to get each controller recognized via the + in order of

Gamepad
Wiimote with Plus Attachment with Nyko nunchuk
Wiimote with Plus Attachment with Nintendo nunchuk
Wiimote Plus with Nintendo nunchuk

Lego Capture the Flag with Finn vs B.A.vs. The Doctor vs. Peter Venkman is fun.


Is It safe to have underfloor heating with lead paint?

Question: We're in the process of renovating an old farm house with a old section and a new side.
Because the house has a hydronic heat system we are looking to convert to underfloor heating throughout. Right now it's a mix of forced air in the old part of the house and underfloor Heating in the new.
We just hit a bump though, having discovered that all the 2nd floor rooms have lead painted floors underneath a plywood subfloor and then a laminate or engineered flooring (depends on the room).
We plan on keeping the old board sealed under a newer floor, but should we look to remove the paint first? Will the underfloor heating cause the paint to off gas or something?
Thanks,
Comment: Generally, lead compounds are *not* volatile. As long as *installing* underfloor heating doesn't create access to the paint, and does not create dust during installation, it should not be a problem. Check local codes, though.
Answer: Lead melts at 621°F. Fumes are released at 900°F. Your in-floor heating and floor are going to be at temperatures an order of magnitude lower than the temperature you need to create off-gassing.
You should be safe.
Comment: PbCrO4, and Pb3O4 are the lead states that would most likely be present within the paint.  They both have even higher melting/boiling points. I gave the "worst case" scenario and even the "worst-case" is quite acceptable.
Comment: Why do you assume that the paint contains elemental lead?


Android Wear: Peek card background under clocks

Question: I am trying to build an analog version of "Simple" watch face. Example code is clear enough, I based my code on SweepWatchFaceService.java, but when I set .setBackgroundVisibility(WatchFaceStyle.BACKGROUND_VISIBILITY_PERSISTENT)
on surface holder, it covers the clocks (canvas). Is there a simple way to render peek card background as a surface holder (watch face) background?
Comment: Dived in a little more and what I need to do is to get instance of peek card background to set it as a face background. Is that possible?
Answer: It is not possible.
The watch face is rendered as a wallpaper, while the notification backgrounds are rendered inside the top activity. As a results, the backgrounds are always over the watch face.
The reason you can show the digital watch face (if you set the WatchFaceStyle option) is because the top activity also renders that.


How do I blast Mettaton ex arms off?

Question: I've looked on the internet countless times and I can't seem to Blow his arms off!
The only thing that helped me the tiniest bit is shooting his heart but the only thing that happens is I go down to 15 hp. And I can only get to abbout 5000 fans or followers. Help Please.
Answer: Maettaton EX will do a heart-to-heart a few times. When he does, just shoot the heart. After two rounds of heart-to-hearts, his arms will fall off. One more heart-to-heart, and his legs will fall off. If you get his limbs to fall off, you only need 10k viewers. Otherwise, you need 12k.
Answer: You have to get the viewers to 10k I believe. He will then do a few attacks and do a heart to heart. Break his heart again and the arms should come off. If you are doing a pacifist run that would be when you throw the stick.

How do I blast Mettaton ex arms off?


Replacement options for Checkbox and Radio buttons

Question: In my web application there are a lot forms where I need to use radio buttons and checkboxes. To make the forms look not so boring I replaced radio buttons with toggle buttons (similar to ios) and checkboxes with selectable button list like this.

I'm afraid about the understanding of the user about these controls. Toggle seems fine, but is there a better replacement option for checkboxes?
Any valid suggestions on how to make the form look awesome is appreciated.
Comment: As always, if the form is long and boring, it's an opportunity to look at the underlying data and question if anything is superfluous or has become unused over time. Thus allowing you to remove any form fields that aren't required. Diminishing returns should always be in your mind when designing a form.
Answer: I wouldn't recommend changing your UI because it looks boring. You could style (colors, for example) it to fit better with your site.
Toggle buttons require:

Toggle button requirements:

Have at least three toggle buttons in a group
Label buttons with text, an icon, or both

The following combinations are recommended:

Multiple and unselected
Exclusive and unselected
Exclusive only

As you can see toggle buttons can be used to select only one and several elements at the same time.
Now, toggle buttons are buttons.
<code>User interacts -> with a button -> to fire an action
</code>
This doesn't seem like your case, as you are talking about a form. So my suggestion is to stick with radio and checkboxes and style them (staying inside the standards) to fit your site.

Radio checkboxes and switches are selection controls:

Selection controls
Selection controls allow the user to select options.
(...)

Checkboxes allow the selection of multiple options from a set.
Radio buttons allow the selection of a single option from a set.
Switches allow a selection to be turned on or off.
Answer: Long and complicated forms involving lots of repetitive entries will always be 'boring' to the user. Replacing one type of input field for another doesn't necessarily make the process more interesting, but it could improve the efficiency or accuracy (e.g. if it is on a mobile device versus desktop).
If it is a web application, it might also help to make the input field neutral rather than specific to a native platform's look & feel (e.g. iOS or Android or Windows) as it will be easiest to use and understand for all users.


How do I use data from a rest response into ag-grid using javascript?

Question: I'm quite new to javascript and ag-grid and have been following what's in the tutorial to move forward.
in ag-grid's tutorial, remote data can be fetched using the code below:
  // fetch the row data to use and one ready provide it to the Grid via the Grid API
  agGrid.simpleHttpRequest({url: 'https://www.ag-grid.com/example-assets/row-data.json'})
      .then(data => {
          gridOptions.api.setRowData(data);
      });

But what if I want to use data from an api call? say the JSON response from this URI: https://api.opencritic.com/api/game/1520
Hope someone can shed some light. Thanks!
Answer: You can perform whatever transformation you need on the data before passing it to setRowData:
agGrid.simpleHttpRequest( ... )
  .then(data => {

    // transform the data into whatever format you need
    const rowData = data.reduce(...) // or whatever. not _necessarily_ reduce

    gridOptions.api.setRowData(rowData);

  })

According to your comment you're getting an object {} instead of an array [] for discounts. I'd recommend you fix this on the API side so you get an array back to begin with, but assuming that's not possible it's trivial to convert it.
Given an object x, calling Object.values(x) will get you an array of the, well, values in x. For example:
const x = {
  foo: 'a',
  bar: 'b',
  baz: 'c',
}

const v = Object.values(x);

// v is now ['a', 'b', 'c']

The values can be objects too. You get back an array of objects:
const x = {
  foo: { label: 'a', bang: 1 },
  bar: { label: 'b', bang: 2 },
  baz: { label: 'c', bang: 3 },
}

const v = Object.values(x);

// [{ label: 'a', bang: 1 }, { label: 'b', bang: 2 }, { label: 'c', bang: 3 }]

Now that you have an array, you can use array methods like map to transform it:
const bangs = v.map(value => value.bang);
// [1, 2, 3]

Note: All of these examples are using the implicit return syntax for arrow functions.
If you prefer, you can use destructuring to tighten up the above expression. The expression below is functionally equivalent to the one above, without the repetition of "value". It doesn't make much difference in this case but it starts to add up if you need multiple fields from the input object.
const bangs = v.map(({bang}) => bang);
// [1, 2, 3]

Destructuring also provides a mechanism for renaming a field on the way in. The example below renames bang to x and returns an object with an x property:
// v = [{ label: 'a', bang: 1 }, { label: 'b', bang: 2 }, { label: 'c', bang: 3 }]

const bangs = v.map(({bang: x}) => ({x}));
// [{x: 1}, {x: 2}, {x: 3}]

You can do this shorthand destructuring/renaming with multiple fields. Here we're renaming bang to x, label to y, and returning a new object with those properties:
// v = [{ label: 'a', bang: 1 }, { label: 'b', bang: 2 }, { label: 'c', bang: 3 }]

const bangs = v.map(({bang: x, label: y}) => ({x, y}));
// [{x: 1, y: 'a'}, {x: 2, y: 'b'}, {x: 3, y: 'c'}]

Using this approach you can remap the BasePrice and SalePrice fields in your discounts object to whatever format you need. In the example below I'm remapping them to an array of objects with x and y properties. I don't know that that's what agGrid expects, but tweaking it to suit your needs should be straightforward.

// function that converts the sample data format to an array of
// coordinates, e.g. [{ x: 555, y: 999 }, { x: 123, y: 456 }]
function transform (input) {
  return Object.values(input.discounts)
    .map(({BasePrice: x, SalePrice: y}) => ({x, y}))
}

fakeApiRequest() // simulate the request
  .then(apiData => {
    const rowData = transform(apiData); // transform the response data
    show(rowData); // show the result
})

//-------
// everything below is just utility and convenience stuff
// for the demo. mostly irrelevant/ignorable for your purposes
//-------

// sample data
const sampleData = {
  "discounts": {
    "0": { "BasePrice": "1499", "SalePrice": "449" },
    "1": { "BasePrice": "1299", "SalePrice": "519" }
  }
}

// simulates an api request; waits a moment then resolve with sample data.
// not really relevant to your issue; just hand-waving for the demo
async function fakeApiRequest () {
  return new Promise(resolve => {
    setTimeout(() => resolve(sampleData), 100)
  });
}

// irrelevant. just a convenience utility for showing the output.
function show(d) {
  document.querySelector('pre').innerHTML = JSON.stringify(d, null, 3);
}

Comment: Hi Ray, thanks for the response. I don't think I was clear enough with my question. What I was trying to ask was, how do I declare an ag-grid request to get a response from an API? Do I still use simpleHttpRequest?
Comment: I guess I don't understand the "API" distinction you're making here. It's an http request that returns json. How is any different from the tutorial example?
Comment: I just realized that yes there was no distinction, and the reason why it was not working for me was because the tutorial example had a json file with arrays that starts with "[".

The api response I was trying to get to work is formatted like this:

`{
    "discounts":
    {
        "0":
        {
            "BasePrice": "1499",
            "SalePrice": "449",
        },
        "1":
        {
            "BasePrice": "1299",
            "SalePrice": "519",
        }
    }
}`

Any idea how can I set BasePrice, SalePrice as my row data? Thanks!
Comment: Thank you so much for this! My Problem was solved!


What is the use of epsilon in the Möller–Trumbore intersection algorithm?

Question: The Möller–Trumbore intersection algorithm compares the determinant with an epsilon. What is this epsilon and how is its value chosen?
Answer: The epsilon is there to counter floating-point accuracy problems.  Note that the code checks that the algorithm is between $-\epsilon$ and $\epsilon$; that is, close to zero.  If the determinant is zero, then the ray lies in the plane of the triangle and can be safely said to not intersect it (as the alternative, an edge-on intersection, should be caught by neighbouring triangles in the mesh).
The Cramer's rule computation of the intersection point then divides by the determinant, and here's where the floating-point accuracy comes in.  If the determinant is merely very close to zero, not exactly equal to it, then its reciprocal will be very large.  We multiply the other determinants by this reciprocal, so small floating-point errors in their values will be blown up into significance and make the difference between an intersection and a non-intersection.
I haven't tested it, but I suspect that leaving out the epsilon will cause intersections on the silhouette of a mesh (i.e. with triangles close to parallel with the ray direction) to become very nondeterministic.  This would result in nearby rays either missing or hitting the triangles unpredictably and giving you speckling.
The value of the epsilon depends on the floating-point precision you're using. It should be small enough that only very grazing intersections are culled, but large enough that it avoids the speckling problem.  It can be determined by experiment, or by just eyeballing it.  The implementation you linked to uses $\epsilon = 10^{-7}$, which is a reasonable choice for single-precision arithmetic; you may want to use $10^{-9}$ or $10^{-10}$ for double-precision computations.


How to pass varaible in pipe rxjs?

Question: There is a code that first loads config file then scripts and as result gets token:
 return configService.loadConfig().pipe(
      (tap((config: Config) => {
        const { mapUrl, panoramaUrl, configAuth, backendUrl, backendGuid } =
          config;
        const url = `${backendUrl}/${configService.user_auth_url}`;
        scriptService.set([configAuth, mapUrl, panoramaUrl]);
      }),
      switchMap(() => from(scriptService.load(scriptService.get()))),
      switchMap(() => authService.loadToken(url, backendGuid)))
    );

Problem is I can not get access for url, backendGuid in last switchMap.
I have tried this:
return configService.loadConfig().pipe(
      map((config: Config) => {
        const { mapUrl, panoramaUrl, configAuth, backendUrl, backendGuid } =
          config;
        return {
          mapUrl,
          panoramaUrl,
          configAuth,
          backendUrl,
          backendGuid,
        };
      }),
      switchMap(({ mapUrl, panoramaUrl, configAuth }) =>
        from(
          scriptService.load(
            scriptService.set([configAuth, mapUrl, panoramaUrl])
          )
        )
      ),
      switchMap(({ mapUrl, backendGuid }) =>
        authService.loadToken(mapUrl, backendGuid)
      )
    );

Problem is the last switchMap has not { mapUrl, backendGuid }
Comment: Problem is the last switchMap has not { mapUrl, backendGuid }
Comment: Does this answer your question? [Keep access to variables between pipe operators](https://stackoverflow.com/questions/52690067/keep-access-to-variables-between-pipe-operators)
Comment: it's not `this.scriptService`? -see the this, that is a service you inject in constructor-
Answer: You can try something like this
 return configService.loadConfig().pipe(
      // use map rather than tap so that you can pass a value to the next operator
      (map((config: Config) => {
        const { mapUrl, panoramaUrl, configAuth, backendUrl, backendGuid } =
          config;
        // move the definition of the const url downstream
        // const url = `${backendUrl}/${configService.user_auth_url}`;
        scriptService.set([configAuth, mapUrl, panoramaUrl]);
        // return the data read from the configuration
        return config;
      }),
      // config now is a input parameter for the function passed to switchMap
      switchMap((config) => from(scriptService.load(scriptService.get()))
      // when the scripService.get() emits then we trigger a map that returns
      // the config value received from upstream
      .pipe(
        map(() => config)
      ),
      switchMap((config) => {
        const { mapUrl, panoramaUrl, configAuth, backendUrl, backendGuid } =
          config;
        // here we define the const url
        const url = `${backendUrl}/${configService.user_auth_url}`;
        authService.loadToken(url, backendGuid)
      })
    );

How to pass varaible in pipe rxjs?


How can I precompile assets using Travis CI?

Question: In the rails guides they have an example on how to precompile assets with Capistrano. It is as simple as adding load 'deploy/assets' to the Capfile. I simply want to achieve the same effect, precompiling assets, while using Travis CI instead. This is what I've done so far:
script/travis.sh:
run "bundle exec rake assets:precompile"

.travis.yml:
 before_install:
  - chmod +x script/travis.sh
 script: script/travis.sh
 language: ruby
 rvm:
 - 2.2
 deploy:
   provider: heroku

When this is built on Travis it fails and I get this from the log:
$ script/travis.sh
script/travis.sh: line 1: run: command not found
The command "script/travis.sh" exited with 127.

I also want to add that my shell script knowledge is very limited.
Answer: I'm not entirely sure, but I'm leaning towards the run command not being available in the travis shell, as against Capistrano. I'd say you should probably just leave your travis.sh as:
bundle exec rake assets:precompile

And try again. Let me know the results of that
Comment: After switching to your suggestion the build pass, but I get this:

`# HEAD detached at 0a16f9c
# Changes not staged for commit:
#   (use "git add ..." to update what will be committed)
#   (use "git checkout -- ..." to discard changes in working directory)

# modified:   public/assets/.sprockets-manifest-2e58c9853eed847b777ae1ce5e9b3103.json
# modified:   script/travis.sh`

and some untracked files.
Comment: yeah, I believe that's because the compiled assets are not automatically tracked. Simply adding `git commit -m #whatever commit message` to your travis.sh should resolve these new issues.
Comment: hey missed one step: `git add public/assets`, then `git commit -m` above
Comment: Thank you sir! Greatly appreciated.


Solving equation with floor

Question: Is it possible to solve for $i$ in the following equation?
EDIT- WolframAplha says it is possible but how do I do it?

$$\left \lfloor{\displaystyle \frac n{2^i}}\right \rfloor =1  $$

I am not sure on how to separate the floor to solve for $i$
Comment: If $\floor{x}=1$ then $1≤x<2$. Then just solve the inequality.
Answer: $\lfloor x \rfloor = 1$ if and only if $1 \le x < 2$.  Thus you want
$2^i \le n < 2^{i+1}$.  Take base-$2$ logarithms of both sides, and you
find $i = \lfloor \log_2(n) \rfloor$.
Answer: We can introduce a slack variable $\epsilon$:
$$
1 = \lfloor n / 2^i \rfloor = n/2^i - \epsilon \quad (\epsilon \in [0,1))
$$
Then
$$
1 + \epsilon = n / 2^i \iff \\
2^i = n /(1+ \epsilon) \iff \\
i = \log_2(n/(1+\epsilon))
$$
This means
$$
\log_2(n/2) < i \le \log_2(n)
$$
You might want $i \in \mathbb{Z}$ as well (going by the name). Because we have
$$
\log_2(n) - \log_2(n/2) = \log_2(n/(n/2)) = \log_2(2) = 1
$$
we can now go reverse and have
$$
i = \log_2(n) - \epsilon' = \lfloor \log_2(n) \rfloor \quad (\epsilon' \in [0,1))
$$

Solving equation with floor


Easily switching between two different implementations of a java library?

Question: I am currently working on a project that uses a third party library to manage hardware.
I wish to create a substitute library that presents the same interface, but instead of controlling actual hardware just presents a nice fake GUI. Preferably this can be done just by replacing the jar.
The problem is that all of the third party code is in the namespace edu.edu.wpi.first.wpilibj, and of course the namespace for my library is going to be very different.
Is there any way of easily switching implementations between the two libraries providing the same interface in java?
Comment: `import edu.edu.wpi.first.wpilibj.*` vs `import my.package.*`
Comment: @OlafDietsche For every single file in the entire project? Seems a little error-prone and tedious.
Comment: You're right, if you have a really large project, this might not work. On the other side, this can be automated and then it would be less intrusive, than any other solution.
Answer: Yes, there are design patterns to do that.
You can look into Strategy pattern.
Even better you can look into Dependency injection.
You can use Google Guice as container and based on your configuration, at runtime, your implementation can switch between using N libraries.
At the end of the day, you need to wrap those libraries around some abstraction.
here is an example:
interface ISomeOperation{
    void process();
}

class ThatUsesTheWPILIBJ implements ISomeOperation{

    void process(){
      //use library here
    }

}

class ThatUsesYourMock implements ISomeOperation{
    void process(){
      //use your mock here
    }
}

public YourUIClass{

    private ISomeOperation _operatingClass;

    public YourUIClass(ISomeOperation  operatingClass){

        _operatingClass = operatingClass;
    }

    public void render(){
        _operatingClass.process();
    }
}

Now all you need to do is wiring. Look at google guice configuraion.
Answer: Yes. ServiceLoader.
It allows to switch implementations by puting jar in classpath (or by some configuration).
But it does not help with existing code. (But once done, switching to any other implementation is easy.
Its easy to library that uses it, but if library does not use it, it can be hard to introduce service loading. You would need to create service-loading wrapper. And if another library uses the original library, you would need to change and recompile it too.
Another approach would be puting it in same package as original library and mirror its public interface. But that is ugly.


Ubuntu 13.10 won't connect to the Internet - BCM4312

Question: I've installed Ubuntu 13.10 on a netbook from a USB, replacing the Windows 7 that came with it, and now it doesn't connect to the internet (it did connect when it was running Windows).
It also doesn't recognize an Ethernet cord.

3.11.0-15-generic
BCM4312 [14e4:4315]
Answer: The Broadcom 14e4:4315 is quite unusual in that the solution changes from earlier Ubuntu versions to later. In Ubuntu 13.10, which you are using, the device uses the native b43 driver and firmware that needs to be downloaded separately. Please first try to undo any possibly failed previous attempts; open a terminal and do:
sudo apt-get purge bcmwl-kernel-source

If the terminal reports that it was not installed so not removed, that's fine, please continue. Get a temporary wired ethernet connection and do:
sudo apt-get install linux-firmware-nonfree

Detach the ethernet, reboot and let us hear your report.


Unknown column 'fromip' in 'where clause'

Question: This is my "functions" add-on code I'm using to connect database and this shortcode [plink url="" name="" expiry="" attempts=""] in WP:
<code>    $fromip=plad_getip();

$sqla = "select downcode from `permissions` where fromip = '".$fromip."' and url = '{$url}' and timestamp > (NOW() - INTERVAL 3600 second) limit 1 ";

$resulta=mysqli_query($conn,$sqla) or die(mysqli_error($conn));

    if(mysqli_num_rows($resulta)>0){
        return get_option('plad_url').'/download.php?downcode='. plad_mysqli_result($resulta, 0,'downcode');
    }
</code>
...and Title of my question is my issue.  How do I solve this?
Comment: pretty self-explanatory error. Post your db schema
Answer: You don't have fromip field on permissions table.


Get inputs from multiple textfields to array and insert to db field

Question: I have an order form. It has 10 textfields for the user to input a quantity. How do you store the inputs to an array and insert to a db field(separated by comas)? Note: It is NOT required to input on all the textfields. For instance, the inputs are 1,2,3,4..it should appear in the db field also 1,2,3,4
examples and descriptions would be great. I'm relatively new to this.
Comment: use implode to make the input a quantity a string with delimeter , then insert into the db.
Comment: @SuchitKumar Can you demonstrate? i've got no idea how to do it.sorry
Comment: see in answer i hace echoed $data you need to insert it using sql to your table ,no need to echo. @kim
Comment: everyone thanks for answering but the chosen one was the easiest to understand for me. I'll take note of them though. have a nice day.
Answer: So, let's say you have a table with four text fields - fieldOne, fieldTwo, fieldThree, fieldFour.
Your html form should look like this (i'm skipping irrelevant parts).
<form method="POST">
    <textarea name='data[fieldOne]'></textarea>
    <textarea name='data[fieldTwo]'></textarea>
    <textarea name='data[fieldThree]'></textarea>
    <textarea name='data[fieldFour]'></textarea>
</form>

Now, your PHP code:
$data = $_POST['data']; // PHP converts names like data[fieldOne] into arrays.

foreach ($data as $key => $value) {
    $fieldNames[] = "`{$key}`";    //field names for our insert statement - `fieldOne`, `fieldTwo`, etc...
    $values[":{$key}"] = strip_tags($value);
}

$stmt = $pdo->prepare("INSERT INTO `tableName` (".implode(', ', $fieldNames).") VALUES (".implode(", ", array_keys($values)).")"; // If you're not using PDO and prepared statements you're doing it wrong, so i absolutely recommend you learning that if you haven't already.
$stmt->execute($values);

That should do the trick.
Notice, using prepared statements frees you from manually escaping your data. However, if you're concerned about XSS attacks, you still should use strip_tags of a filter extension.
Comment: Arent u missing a `:` in front of the `array_keys($values)`?
Comment: Nope, because of `$values[":{$key}"]`
Answer: HTML
<form action="my_page_that_processes_orders.php" method="post">
  <input type="text" name="order[product1]" />
  <input type="text" name="order[product2]" />
  <input type="text" name="order[product3]" />
  <input type="text" name="order[product4]" />
  <input type="submit" />
</form>

my_page_that_processes_orders.php
$data = $_POST["order"];// Advisable to perform checks for security reasons (not going to do it)

$aux = '';
foreach($data as $product => $qty) {
 // Do whatever you please with the data.
 $aux .= "$product $qty,"; // For instance.
}

$string_to_insert = rtrim($aux, ",");
// Insert it in DB or do more processing stuff.

Hope it helps.
Kind regards.
Answer: suppose this is your form: if you are only bothering about order array nothing else like corresponding key.
<form action="submit.php" method="post">
  <input type="text" name="order[]" />
  <input type="text" name="order[]" />
  <input type="text" name="order[]" />
  <input type="text" name="order[]" />
  <input type="submit" />
</form>

your submit.php:
     <?php
       $data ="";
  foreach($_POST["order"] as $key=>$val){
    if(isset($val) && $val !="")
      $data.=$val.",";
  }
   $data=trim($data);
    echo $data;// use data

Note:  do not use mysql use PDO or mysqli instead. mysql is deprecated.
Comment: it worked thanks a lot but it leaves comas to the blank textfields. how to fix that?i have 10 textfields but if only 2 have inputs, it results to 1,2,,,,,,,,
Comment: @kim use trim for this:$data = implode(',',$_POST["order"]);
echo trim($data,',');
Comment: In mysql field it still appears like that 1,2,,,,,,,,
Comment: Hi. i just tested again. If the inputs from textfield skips in between, like input 1,2,3 from textfld1,textfld2, and textfld5, it still results to 1,2,,,3
Comment: can you tell me why you are storing like this.
Comment: it's for school.and this is the only way i can think of when ordering.you see i'm not trying to follow the common right way to order a product(add to cart).the product names are in checkbox and that inserts to a field.the only way i know to store the equivalent quantity of product is to insert in another field.
Comment: if it is not for commercial use then fine.


FOSJsRoutingBundle: Cannot Generate routing url inside javascript

Question: I am using FOSJsRoutingBundle to generate Symfony 2 routing url's in a JavaScript file.
I have installed the bundle as per the documentation (https://github.com/FriendsOfSymfony/FOSJsRoutingBundle/tree/master/Resources/doc)
Trying to implement a form submission using ajax script, where user can rate and comment.
Here is my twig/html code:
<form id="feedback" method="post" name="feedback">

                Rate Us:
                <input type="radio" name="rating" value="1">One
                <input type="radio" name="rating" value="2">Two
                <input type="radio" name="rating" value="3">Three
                <input type="radio" name="rating" value="4">Four
                <input type="radio" name="rating" value="5">Five

                Please give your feedback
                <textarea rows="5" cols="32" id="comment" name="feedback"></textarea>

        <input type="submit" class="comment_submit" name="validate" value="Submit">

    </form>

Here is my JavaScript code:
//Ajax Form Submission
$(function() {
    $('.comment_submit').click(function() {
        var rating = $(':radio').val();
        var comment = $('#comment').val();
        alert("comment: "+comment);
        var route = Routing.generate('user_feedback');

        alert("Route: "+route);

        /* $.ajax({
          type: "POST",
          url: Routing.generate('user_feedback', { "rating": rating, "comment": comment}),
          success: function() {
            $('div.middle').html("

");
            $('.message').html("
Thank You!
")
            .append("
Your comment has been submitted
")
            .hide()
            .fadeIn(1500);
          }
        });
        return false; */

        //alert("Rating"+comment);
        //alert("Feedback Submited");
    });
});

I have added the routing url in my routing.yml file also
Now the problem is when i submit the form, i cannot get the route value. I am trying to alert out the route value as you can see in the code, but i am not getting the vaue. The form just refreshes when i submit.
Is there any problem with the code?
I am new to Symfony 2 so, please help me.
Thank You
Answer: Check your config routes:
my_route_to_user_feedback:
    pattern:  /user/feedback
    defaults:  { _controller: HelloBundle:User:feedback }
    options:
        expose: true

options expose must be true. It is important for FOSJsRoutingBundle!
Answer: its not a symfony problem, the problem is in javascript
you have a submit button, which will submit your form. to prevent form submission you have to change your click function following way:
$('.comment_submit').click(function(e) {
    e.preventDefault();
    // your code goes here
    return false;
}


convergence in $L^p$ implies convergence in measure

Question: I am trying to show that if $f_n$ converges to $f$ in $L^p(X,\mu)$ then $f_n\to f$ in measure, where $1\le p \le \infty$.
Here is my attempt for $p\ge 1$: Let $\varepsilon>0$ and define $A_{n,\varepsilon}=\lbrace x: \vert f_n(x)-f(x) \vert \ge \varepsilon\rbrace$. I want to show $\mu (A_{n,\varepsilon})\to 0$. $\Vert f_n-f \Vert_p=\left(\int _X \vert f_n-f\vert ^p\right)^{1/p}\ge \left(\int _{A_{n,\varepsilon}}\vert f_n-f\vert ^p\right)^{1/p}\ge \varepsilon \mu (A_{n,\varepsilon})^{1/p}$ so that $\mu (A_{n,\varepsilon})\le \left(\frac{\Vert f_n-f\Vert_p }{\varepsilon}\right)^{p}$ and the RHS tends to $0$ as $f_n\to f$ in the $L^p$ norm.
How can I deal with the case $p=\infty$?
Comment: Perhaps I'm missing something, but shouldn't the $L^{\infty}$  case be the simplest? Since $||f_n-f||_{\infty}<\epsilon \implies \mu(|f_n-f|\geq \epsilon) =  0$.
Answer: The case $p = \infty$ is the simplest since $\|f_n-f\|_{\infty} < \epsilon$ means that $|f_n-f|$ is less than $\epsilon$ almost everywhere, and therefore $\mu\big(|f_n-f|\ge\epsilon\big) = 0$.
If $1\le p < \infty$, you can use Tchebychev's inequality:
$$
\mu\big(|f_n-f|\ge\epsilon\big) = \mu\big(|f_n-f|^p\ge\epsilon^p\big) \le \frac{1}{\epsilon^p}\int|f_n-f|^p\,d\mu = \frac{1}{\epsilon^p}\|f_n-f\|_p^p,
$$
where the last expression can be made arbitrarily small by taking $n$ sufficiently large.
Comment: @JackLondon: Good question, yes it can. Probably the easiest way to see that is to observe that $f/\lambda \ge 1$ on $\{f \ge \lambda\}$, so Tchebychev's inequality is really only a consequence of monotonicity of integration: $\mu(f\ge \lambda) = \int_{\{f \ge \lambda\}} 1 \le \int_{\{f\ge \lambda\}} (f/\lambda) \le (1/\lambda)\int f$ (if $f\ge 0$, say).
Comment: A quick question: Tchebychev's inequality can be applied also to measures $\mu$ which are not finite, right?