text:
Q: generating calls to lambdas with arbitrary number of parameters The following definition has proven to be very useful for me:
template<class Func, class... Args>
void apply_on_each_args(Func f, Args... args)
{
    (f(args), ...);
}

Basically, the arguments pack folded on comma operator, allows to define several calls to a function taking an argument. For example:
apply_on_each_args([] (auto x) { cout << x << endl; }, 1, 2, "hello");

will call the anonymous lambda on 1, 2 and "hello".
That idea presented, I would like to do the same thing but passing lambdas taking two, three, and so on arguments. For example, something like that
apply_on_each_args([] (auto x, auto y) { /* use x and y */ }, 1, 2, "hello",  "bye");

Any clue, technique, idea, etc that allow achieving it?

A: The best I can imagine (at the moment) is the good old recursive way.
By example
// ground case
template <typename Func>
void apply_on_each_2_args (Func)
 { }

// recursive case
template <typename Func, typename A0, typename A1, typename ... Args>
void apply_on_each_2_args (Func f, A0 a0, A1 a1, Args ... args)
 { f(a0, a1); apply_on_each_2_args(f, args...); }

A: Ok, my voodoo is strong tonight:
auto foo(int, int) -> void;

template <class Func, class... Args, std::size_t... I>
void apply_on_2x_indexes(Func f,  std::index_sequence<I...>, std::tuple<Args...> t)
{
    (f(std::get<I * 2>(t), std::get<I * 2 + 1>(t)), ...);
}

template<class Func, class... Args>
void apply_on_each_2_args(Func f, Args... args)
{
    apply_on_2x_indexes(f, std::make_index_sequence<sizeof...(Args) / 2>{},
                        std::tuple{args...});
}

auto test()
{
    apply_on_each_2_args(foo, 1, 2, 3, 4); // calls foo(1, 2) foo(3, 4)
}

Forwarding omitted for brevity.
To better understand how this works we can manually expand:
apply(on_each_2_args(foo, 1, 2, 3, 4))
↳ apply_on_2x_indexes(f, std::index_sequence<0, 1>{}, std::tuple{1, 2, 3, 4})
  ↳ (f(std::get<0 * 2>(t), std::get<0 * 2 + 1>(t)),  f(std::get<1 * 2>(t), std::get<1 * 2 + 1>(t)))
    (f(std::get<0>(t), std::get<1>(t)),  f(std::get<2>(t), std::get<3>(t)))
    (f(1, 2), f(3, 4))

Another approach:
One thing that I don't like in your call syntax
apply_on_each_2_args([] (auto x, auto y) { }, 1, 2, "hello",  "bye");

is that is not clear how arguments are grouped per call.
So I would like to group them. Unfortunately I can't get it to work like this for varargs:
apply_on_each_2_args([] (auto x, auto y) { }, {1, 2}, {"hello",  "bye"});

but we can be a little more verbose with tuple:
template<class Func, class... Args>
void apply_on_each_2_args(Func f, Args... args)
{
    (std::apply(f, args), ...);
}

auto test()
{
    apply_on_each_2_args([](auto a, auto b){ /*use a, b*/ },
                         std::tuple{1, 2}, std::tuple{"hello", "bye"});
}

Is not exactly what you asked but is an approach worth considering.

A: A way to make a apply_on_each() that receive a lambda (or a function) that receive an undefined number of generic arguments and call they (partially) unfolding in a C++17 way.
To be honest, it's only the generalization of the Bolov's voodoo answer.
First of all, a set of constexpr functions to detect the number of arguments of a function (supposing the arguments are generic, so supposing a list of integer zeros is acceptable)
template <typename F, typename ... Ts>
constexpr auto numArgsH (int, Ts ... ts)
   -> decltype( std::declval<F>()(ts...), std::size_t{} )
 { return sizeof...(Ts); }

template <typename F, typename ... Ts>
constexpr auto numArgsH (long, Ts ... ts)
 { return numArgsH<F>(0, 0, ts...); }

template <typename F>
constexpr auto numArgs ()
 { return numArgsH<F>(0); }

Now the apply_on_each() function that detect the number of arguments for the function func and, following the Bolov's example, call a (first) helper function adding a (double, in this generalization) list of indexes and the std::tuple of arguments
template <typename F, typename ... Ts>
void apply_on_each (F func, Ts ... ts)
 {
   static constexpr auto num_args { numArgs<F>() };

   apply_on_each_h1(func,
                    std::make_index_sequence<sizeof...(Ts)/num_args>{},
                    std::make_index_sequence<num_args>{},
                    std::make_tuple(ts...));
 }

Now the first helper function that "unpack" the first index sequence, using C++17 folding, and call the second helper function
template <typename F, std::size_t ... Is, std::size_t ... Js,
          typename ... Ts>
void apply_on_each_h1 (F func,
                       std::index_sequence<Is...> const &,
                       std::index_sequence<Js...> const & js,
                       std::tuple<Ts...> const & t)
 { (apply_on_each_h2<Is>(func, js, t), ...) ; }

Now the last helper function that, playing with indexes, call the func with the right arguments
template <std::size_t I, typename F, std::size_t ... Js, typename ... Ts>
void apply_on_each_h2 (F func,
                       std::index_sequence<Js...> const & js,
                       std::tuple<Ts...> const & t)
 { func(std::get<I*sizeof...(Js)+Js>(t)...); }

The following is a full example
#include <tuple>
#include <utility>
#include <iostream>
#include <type_traits>

template <typename F, typename ... Ts>
constexpr auto numArgsH (int, Ts ... ts)
   -> decltype( std::declval<F>()(ts...), std::size_t{} )
 { return sizeof...(Ts); }

template <typename F, typename ... Ts>
constexpr auto numArgsH (long, Ts ... ts)
 { return numArgsH<F>(0, 0, ts...); }

template <typename F>
constexpr auto numArgs ()
 { return numArgsH<F>(0); }

template <std::size_t I, typename F, std::size_t ... Js, typename ... Ts>
void apply_on_each_h2 (F func,
                       std::index_sequence<Js...> const & js,
                       std::tuple<Ts...> const & t)
 { func(std::get<I*sizeof...(Js)+Js>(t)...); }

template <typename F, std::size_t ... Is, std::size_t ... Js,
          typename ... Ts>
void apply_on_each_h1 (F func,
                       std::index_sequence<Is...> const &,
                       std::index_sequence<Js...> const & js,
                       std::tuple<Ts...> const & t)
 { (apply_on_each_h2<Is>(func, js, t), ...) ; }

template <typename F, typename ... Ts>
void apply_on_each (F func, Ts ... ts)
 {
   static constexpr auto num_args { numArgs<F>() };

   apply_on_each_h1(func,
                    std::make_index_sequence<sizeof...(Ts)/num_args>{},
                    std::make_index_sequence<num_args>{},
                    std::make_tuple(ts...));
 }

int main()
 {
   auto l1 = [](auto a)
    { std::cout << "- l1:" << a << std::endl; };

   auto l2 = [](auto a, auto b)
    { std::cout << "- l2:" << a << ", " << b << std::endl; };

   auto l3 = [](auto a, auto b, auto c)
    { std::cout << "- l3:" << a << ", " << b << ", " << c << std::endl; };

   apply_on_each(l1, 1, 2l, 3ll, "4", '5', 6.0);
   apply_on_each(l2, 1, 2l, 3ll, "4", '5', 6.0);
   apply_on_each(l3, 1, 2l, 3ll, "4", '5', 6.0);
 }


text:
Q: Implementing and indexing User Defined Fields in an SQL DB I need to store a large table (several millions or rows) that contains a large number of user-defined fields (not known at compile time, but probably around 20 to 40 custom fields). It is very important (performance-wise) for me to be able to query the data based on those custom fields: i.e. "Select the rows where this attribute has that value, that attribute is that value, etc.". Each query has some 20 to 30 WHERE clauses.
My ideas so far:

*

*Change the database schema everytime a new user field is implemented. Keep each user defined field as a column in the table. Add and maintain indexes on each custom-created column. How to properly build those indexes is a big problem, as I don't know what attributes(columns) will be used in the WHERE queries.

*Store the custom fields as an XML type column. As I understand from SQL2005 I can query inside the XML in the XML type columns. Not so sure about performance though.

*Entity Attribute Value . This is what I am using now, but it's a pain.
Any suggestions?
Edit:
Some clarifications on my requirements. I have a table, 40 -50 million rows of (say) ID numbers and various attributes associated with those IDs.
Let's say 20 million of them have "CustomAttribute1" equal to 2, then 5 million have "CustomAttribute2" equal to "Yes" and 3 million have "CustomAttribute20" equal to 'No'
I need a FAST method of returning all IDs where:
     1. CustomAttribute1  = 2
     2. CustomAttribute2  = 'Yes'
     3. CustomAttribute4  = null
     4. CustomAttribute20  != 'No'
  etc...

We have this implemented as EAV: the select query is a nightmare to implement and maintain, it takes a long time to return result, and most anoyingly the DB scales to huge sizes even for small ammounts of data, which is weird since the EAV is essentially normalizing the data but I assume all the indexes take up a bunch of space.

A: It seems like you've listed your available options. EAV can be a pain for querying (and slow, depending on how many criteria you want to search on simultaneously), but it tends to be the most "sane" and RDBMS-agnostic implementation.
Modifying the schema is a no-no...obviously it can be done, but such a practice is abhorrent. I do not approve.
The XML option is a solution, and SQL Server can query inside the structure. I'm not certain about other RDBMS's, and you don't list which one you're using in the post or the tags.
If you're going to be querying on many attributes (say, 20+) simultaneously, then I would probably recommend the XML solution just to limit the number of joins you'll have to make. Aside from that, I would stick with EAV.

A: You could represent all of the user defined fields with an XML Column, e.g.
"But I am not sure what the performance impact of doing this would be, however it is definitely the prettiest way of handling UDF's in a database in my opinion."
   <UDF>
      <Field Name="ConferenceAddress" DBType="NVarChar" Size="255">Some Address</Field>
      <Field Name="ConferenceCity" DBType="NVarChar" Size="255">Some City</Field>
      ...etc
   </UDF>

Then what I would do is put a trigger on the table so that when the column is updated it recreates a view for the table which pulls out the xml values as columns on the view. Lock the view etc during the recreation of it to prevent access errors application side.
Then I would create a stored procedure for updating the XML so that it would work for any XML Column following your User Defined Field xml formatting, e.g. Insert/Update/Remove/Get
GetUDFFieldValue
AddUDFField
UpdateUDFField
DeleteUDFField
--Shared Parameters
TableName
ColumnName
(e.g. use Dynamic SQL to get the XML from X table by X Column Name to make it universal/generic to all of your UDF Fields)
Here is an article on XML Performance Optimization from Sql Server 2005 (not seeing an equivalent in newer versions):
http://technet.microsoft.com/en-us/library/ms345118(v=sql.90).aspx
Lastly:
Are you sure you even need an RDBMS?  NoSql Is a better fit for User Generated Fields, I might even consider using Both NoSql and Sql Server.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Blank space occupied when ads are not showing in flutter I am using admob_flutter plugin to display ads in my app. Everything is working fine but when ads are not ready to display or someone is offline then I am getting blank space on the place of ads Banner. like image below

I tried boolean method too but I can'nt figure out the problems.
ListView.builder(
          itemCount: _storyListByCategory.length,
            itemBuilder: (context, index) {
              if (index % 7 == 0 && index != 0)
              return Column(
                children: [
                  AdmobBanner(
                    adUnitId: AdManager.bannerAdUnitId,
                    adSize: AdmobBannerSize.BANNER,
                  ),
                  StoryByCategory(
                    this._storyListByCategory[index],
                  ),
                ],
              );
              else return StoryByCategory(
                this._storyListByCategory[index],
              );
            },
        ),

Please suggest me how can I get rid of this problem?

A: import 'dart:io';
before your return Widget
  bool isonline = false;
  final result = await InternetAddress.lookup('google.com');
  if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
    isonline = true
  }

then in your list :
ListView.builder(
          itemCount: _storyListByCategory.length + isonline ? 1:0,
            itemBuilder: (context, index) {
              if (index % 7 == 0 && index != 0)
              return Column(
                children: [
                  isonline ? AdmobBanner(
                    adUnitId: AdManager.bannerAdUnitId,
                    adSize: AdmobBannerSize.BANNER,
                  ), :
                  AdsMakemeliveWidget() ,
                  StoryByCategory(
                    this._storyListByCategory[index],
                  ),
                ],
              );
              else return StoryByCategory(
                this._storyListByCategory[index],
              );
            },
        ),

A: bool _adShown=true;
ListView.builder(
      itemCount: _storyListByCategory.length,
      itemBuilder: (context, index) {
        if (index % 7 == 0 && index != 0)
          return Column(
            children: [
              _adShown?AdmobBanner(
                  adUnitId: AdManager.bannerAdUnitId,
                  adSize: AdmobBannerSize.BANNER,
                  listener: (AdmobAdEvent event,m){
                    if (event == AdmobAdEvent.loaded) {
                      setState(() {
                        _adShown=true;
                      });
                    } else if (event == AdmobAdEvent.failedToLoad) {
                      setState(() {
                        _adShown = false;
                      });
                    }
                  }
              ):Container(),
              StoryByCategory(
                this._storyListByCategory[index],
              ),
            ],
          );
        else return StoryByCategory(
          this._storyListByCategory[index],
        );
      },
    ),

You shall use listener in admob to check whether ad has loaded or not.

A: In that type of cases you can always use ternary operator.
here is simple example :-

*

*create a function which check internet connectivity continuously then call this function before building widget tree..

*then use  SizeBox.shrink() to shrink.

*description :-

*

*checkNet():for checking internet connection.

*_wiget():Simple widget

*set ? _wiget() : SizedBox.shrink(), _wiget() : ternary operation

*set :bool variable

*the most import thing is to call checkNet() Continuously so for that call checkNet() every time before building widget.*
 class EnrollCourse extends StatefulWidget {
 @override
 _EnrollCourseState createState() => _EnrollCourseState();
}

class _EnrollCourseState extends State<EnrollCourse> {
bool set;
@override
void initState() {
 // TODO: implement initState
 super.initState();
 checkNet();
}

@override
Widget build(BuildContext context) {
 checkNet();
 return Scaffold(
   body: Center(
     child: new Column(
       crossAxisAlignment: CrossAxisAlignment.center,
       mainAxisAlignment: MainAxisAlignment.center,
       children: [_wiget(), set ? _wiget() : SizedBox.shrink(), _wiget()],
     ),
   ),
 );
}

void checkNet() async {
 try {
   final result = await InternetAddress.lookup('google.com');
   if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
     setState(() {
       print("yes internet");
       set = true;
     });
   }
 } on SocketException catch (_) {
   setState(() {
     print("No internet");
     set = false;
   });
 }
}

Widget _wiget() {
 return Padding(
   padding: const EdgeInsets.all(8.0),
   child: new Container(
     color: Colors.red,
     height: 200,
     width: 200,
     child: new Text("child 1"),
   ),
  );
}
}


text:
Q: jQuery infinite-scroll Not Triggering I'm making a simple little website to apply a different formatting style to Reddit posts, I'm trying to add the infinite-scroll jQuery plugin but it doesn't do anything. I tried following the (very simple) instructions on the infinite-scroll page and when it didn't do anything I thought I must have entered something wrongly, but then I just copy/pasted the code from the Masonry/Infinite-Scroll example and it still didn't work. Masonry is working perfectly (finally) but I just can't figure out what is wrong with infinite-scroll. I understand the basics of jQuery and JavaScript, but obviously not as much as most of you people, so could you please help me out and let me know what is wrong? My site is live at reddit.ymindustries.com.
Thanks heaps, you guys have rarely failed me so far.
YM
EDIT: If there aren't enough images to fill up the page on the homepage, visit reddit.ymindustries.com/r/aww for more images.
EDIT 2: I believe I located the issue, it is described here: https://github.com/paulirish/infinite-scroll/issues/5
Now to figure out a fix...
EDIT 3: Added a little bit of a hack in to make it sort of work, but it just seems to loop the second page endlessly now. Hmm...

A: I think your problem is actually css. Make your page longer that client area height. add more images to $container
Point is, botom edge of your $container need to pass bottom of window so scroll event fires so infinite scroll can react on this event and calculate weather or not edge is reached
BTW, in same cases, for instance, when I shrink my window, the example you set is working.
=== UPDATE ===
I found some time to play with infinitescroll and here is final working script, just set pathParse method in your script
$(function () {

        var $container = $('#itemContainer');

        $container.imagesLoaded(function () {
            $container.masonry({
                itemSelector:'.item'
            });
        });
        $container.infinitescroll({
                    navSelector:'.navigation', // selector for the paged navigation
                    nextSelector:'.navigation #next', // selector for the NEXT link (to page 2)
                    itemSelector:'.item', // selector for all items you'll retrieve
                    bufferPx:40,
                    debug:true,
                    columnWidth:function (containerWidth) {
                        return containerWidth / 5;
                    },
                    loading:{
                        finishedMsg:'No more pages to load.',
                        img:'http://i.imgur.com/6RMhx.gif'
                    },
                    pathParse: function(path,page){
                        return $(this.nextSelector).attr("href");
                    }
                },
                // trigger Masonry as a callback
                function (newElements) {
                    // hide new items while they are loading
                    var $newElems = $(newElements).css({ opacity:0 });
                    // ensure that images load before adding to masonry layout
                    $newElems.imagesLoaded(function () {
                        // show elems now they're ready
                        $newElems.animate({ opacity:1 });
                        $container.masonry('appended', $newElems, true);
                    });
                    //console.log("test (never fired :( )");
                }
        );

    });

Now, since your next link will not update by it self (http://reddit.ymindustries.com/?after=t3_yh4av), you need to change the callback to pull out last element from ajax response and change next link... could be something like this
function (newElements) {
                        // hide new items while they are loading
                        var $newElems = $(newElements).css({ opacity:0 });
                        // ensure that images load before adding to masonry layout

                        // ======> if query parameter after=... is caring filename then do this
                        var lastImageUrl= $newElements[$newElements.length-1].attr("src");
                        var lastFileName= lastImageUrl.substring(lastImageUrl.lastIndexOf("/") +1, lastImageUrl.lastIndexOf("."));
                        $("#next").attr("href", "http://reddit.ymindustries.com/?after="+lastFileName);

                        $newElems.imagesLoaded(function () {
                            // show elems now they're ready
                            $newElems.animate({ opacity:1 });
                            $container.masonry('appended', $newElems, true);
                        });
                        //console.log("test (never fired :( )");
                    }

A: You also need to take care of wich version of infinite-scroll your using since if you use the ones that comes with masonry/isotope (version 2.0b2.110713), both need a little hack in order to call the function and not use the predefined array:
//old code, to be changed (line 489)
desturl = path.join(opts.state.currPage);
// new code
desturl = (typeof path === 'function') ? path(opts.state.currPage) : path.join(opts.state.currPage);

This is already fixed in the newer versions of infinite-scroll

A: I had the same problem with jQuery's "infinitescroll" and Masonry. You might just solve this by giving your page more initial items so that the plugin's scrolling detection kicks in.
In WordPress this is under the "Reading" settings. By default WordPress only opens 10 items at a time. You could increase that number to 100/page to be more sure the window will be full initially. I had some code here that was just horrible, turns out I just needed longer pages, not more code.
So it's difficult to test these plugins on large displays if you don't have enough images. Maybe the solution is to scale the images larger on large displays so you're more sure about getting your content below the fold.
If you think someone might get to your website with a really huge display, I'm not sure what the answer is other than showing more items/page and maybe adding $('#masonry').infinitescroll('retrieve'); to your footer to load an extra page just in case.


text:
Q: how to remove non-schema params from the query according to the fastify 4.0 docs, the default options for Ajv include removeAdditional: true. I have a queryString schema, and when I send a query with a param that is not in the schema, I expect that param to be removed. But no such thing happens. The schema itself is pretty run-of-the-mill
querystring: {
    type: "object",
    properties: { … }
}

Some of my params are of type array, and there too I would like any additional values (outside of those specified via enum to be removed. How can I achieve this?
update: I am adding the actual schema below (with some info snipped for brevity)
{
  '$schema': 'https://json-schema.org/draft/2020-12/schema',
  '$id': 'https://example.com/treatments.schema.json',
  title: 'Treatments',
  summary: 'Fetches treatments',
  description: 'Treatments are…',
  response: {},
  querystring: {
    type: 'object',
    additionalProperties: false,
    properties: {
      treatmentId: {
          type: "string",
          maxLength: 32,
          minLength: 32,
          description: "A 32 character string: treatmentId=388D179E0D564775C3925A5B93C1C407"
      },
      … <snipped> …
    }
  },
  tags: [ 'zenodeo' ]
}

I know the schema is being validated because http://localhost:3010/v3/treatments?treatmentId=foo gives an error {"statusCode":400,"error":"Bad Request","message":"querystring/treatmentId must NOT have fewer than 32 characters"} (that is good ) but the additionalProperties: false constraint is still not working because http://localhost:3010/v3/treatments?foo=bar gives no error and foo is also not removed from request.query (that is not good )

A: With removeAdditional: true you must still set additionalProperties: false on your schema:
querystring: {
  type: "object",
  properties: { … },
  additionalProperties: false
}

See https://ajv.js.org/json-schema.html#additionalproperties
You can also change the default behavior to removeAdditional: 'all' in which case you don't have to set additionalProperties: false on your schema.
See about halfway down the page here: https://www.fastify.io/docs/latest/Reference/Validation-and-Serialization/


text:
Q: Reading Android attributes on my custom view I have created a custom layout class (extends RelativeLayout) and have a TextView as part of the layout.
I want to apply the properties declared in XML to my TextView, is there anyway I can read the android attributes (not my custom attributes, that part is already taken care of).
For example in my XML I'll have this:
<my.custom.MyLayout
    android:layout_width="100dp"
    android:layout_height="20dp"
    android:text="SomeText" />

I want to read the text attribute and apply it to my TextView (currently it is being applied to the RelativeLayout) instead of creating my own attribute and reading it.
My custom layout is something like this :
public class MyLayout extends RelativeLayout {

    private TextView textView;
    public void MyLayout(final Context context, final AttributeSet attrs) {
        /**Read android attributes and apply it to TextView **/
        ??
    }

My current solution is creating custom attributes and reading them, but I feel that is not a good solution as I'll be duplicating every attribute declared to TextView.
More info about my current solution.
I have a custom attribute called myText which I use to apply the text declared in XML to my TextView.
In my layout XML :
myNameSpace:myText="SomeText"

And read it in my Java class :
String text= a.getString(R.styleable.MyStyleable_myText);
textView.setText(text);

I'm looking to get rid of my custom attributes and read "android:" attributes.

A: First of all I am not sure if setting android:text will be possible for view extending RelativeLayout. If it is possible do it like in TextView implementation:
final Resources.Theme theme = context.getTheme();
a = theme.obtainStyledAttributes(attrs, com.android.internal.R.styleable.TextView, defStyleAttr, defStyleRes);
text = a.getText(attr);

So basically it's the same way you get your custom properties but with different styleable.
If it's not working I would consider another approach. I did it for one of my custom views. Since you have a TextView in your custom view you could create it in XML and then get a reference to that child inside your custom view.
<YourCustomView>
    <TextView android:text="someText"/>
<YourCustomView/>


text:
Q: How to remove built-in datastore indexes The app engine defines a built-in index for every field by default. I didn't create them, and I don't want them.
My actual entities are only consuming 159MB, but the indexes consume an additional 680MB. I am only ever going to be doing key-queries on these entities, so I do not need any indexes at all. How can I remove these?
EDIT: Output of vacuum_indexes:
Found 0 unused indexes on the server.

Details:
No indexes were deleted.

vacuum_indexes completed successfully.

A: You can not remove built-in indexes. They are built-in :)
What you can do is reduce the number of indexed used by your app's models. By default every property is indexed in AppEngine. I think you really mean about this.
To make a property unindexed, add a param to de property declaration like this:
class MyModel(db.Model):
    FirstName = db.StringProperty(Indexed=False)
    LastName = db.StringProperty(Indexed=False)
    ...

Thst's way, appengine will stop to use/create an index for that specific property. Next time you run you SDK console, indexes.yaml file will be updated automatically.
The last thing you need to do is execute appcfg.py vacuum_indexes myapp/. Read more about the last command on the Appengine SDK docummentation.

A: With the low-level Java API you need to use the setUnindexedProperty method for all properties you don't want to have an built-in index on.
There's no way of simply changing some definiton file and vacuuming to get rid of index entries that are already there.
The only way to remove those built-in index entries (or to create new ones) is to re-write all your entities. Be aware though, that deletion of one index entry on one single entity will count as 2 full writes against your quota as these are actually 2 index entries - one in ascending the other in descending order.


text:
Q: iOS12 adMob Rewarded video: test ad not working Until yesterday night AdMob test ad was working fine, but then it suddenly stopped working.
I have tried all of the solutions proposed for similar problems but i'm still getting the same errors:
WF: === Starting WebFilter logging for process
WF: _userSettingsForUser mobile: {
filterBlacklist =     (
);
filterWhitelist =     (
);
noOverridingAllowed = 1;
restrictWeb = 1;
useContentFilter = 0;
useContentFilterOverrides = 0;
whitelistEnabled = 0;
}
WF: _WebFilterIsActive returning: NO
<Google> Cannot find an ad network adapter with the name(s): com.google.DummyAdapter. Remember to link all required ad network adapters and SDKs, and set -ObjC in the 'Other Linker Flags' setting of your build target.

I think that the code is correct and I'm using the correct test IDs provided by Google. I'm running the code on a test device with iOS12 and i have updated Google Mobile Ads SDK to the latest version: 7.33.1.
Here is the code that I'm using:
AppDelegate:
func application(_ application:UIApplication,didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {GADRequest().testDevices = [ "2077ef9a63d2b398840261c8221a0c9b" ]
    GADMobileAds.configure(withApplicationID: "ca-app-pub-3940256099942544~1458002511")
    GADRewardBasedVideoAd.sharedInstance().delegate = self
    GADRewardBasedVideoAd.sharedInstance().load(GADRequest(), withAdUnitID: "ca-app-pub-3940256099942544/1712485313")
    return true
}
func rewardBasedVideoAd(_ rewardBasedVideoAd: GADRewardBasedVideoAd, didRewardUserWith reward: GADAdReward) {
    let firstController = window?.rootViewController as! ViewController
    firstController.plusOneLife()
}

func rewardBasedVideoAdDidClose(_ rewardBasedVideoAd: GADRewardBasedVideoAd) {
    GADRewardBasedVideoAd.sharedInstance().load(GADRequest(), withAdUnitID: "ca-app-pub-3940256099942544/1712485313")
}

func rewardBasedVideoAd(_ rewardBasedVideoAd: GADRewardBasedVideoAd,
                        didFailToLoadWithError error: Error) {
    print("Reward based video ad failed to load.")
}

ViewController:
    @IBAction func watchAd(_ sender: Any) {
    if GADRewardBasedVideoAd.sharedInstance().isReady == true {
        GADRewardBasedVideoAd.sharedInstance().present(fromRootViewController: self)
    }
}

Does anyone have a solution?

A: I believe you are having the same issue as me, It is on Google's end.
I have reached out to them, you can monitor the progress at the link below here
https://groups.google.com/forum/#!category-topic/google-admob-ads-sdk/ios/f-W_HmEndw4


text:
Q: What is the difference between http-equiv="author" and name="author"? Hello I'm learning HTML5 and I'm wondering what is the difference between these two meta elements ?
<meta http-equiv="author" content="Jon Smith" />
<meta name="author" content="Jon Smith" />

A: The first is not valid, http-equiv is enumerated, i.e. it has a set of values that are valid for it and author is not one. (Its intended as a way to pass pragma data to the browser such as rendering instructions, not meta data like document properties.)
<meta name="author" content="Jon Smith" /> is valid.


text:
Q: Framer motion page transition depending on state My Problem:
I want to controll the page transition behavior based on state. My state is the URL the user is coming from.
Examples:
A user coming from Component1 going to Component2 --> slide Component1 out and at the same time slide Component2 in.
A user coming from Componen3 going to Component2 --> fade Component3 out and at the same time fade Component2 in.
The issue is that setting the transition dynamically makes the transition type change during the transition as it's not waiting for the transition to finish.
Also, some transitions need exitBeforeEnter to be true to fade accordingly. The slide page transition on the other hand needs it to be turned off for a transition without a gap.
Working with only one transition slide or fade works like a charm.
You will find the logic for switching the page-transition-stye in Component1. If you want to see the transition working replace variantsFade with variantsSlide.
What I tried:
Using useContext to keep track of the BroserHistory --> prevRoute and currRoute
And setting the variants based on state as soon as the URL changes.
What I'm looking for:
A solution to allow switching between slide transitions with exitBeforeEnter=false and fading transition with exitBeforeEnter=true based on state while route switching.
Sandbox-Link:
https://codesandbox.io/s/different-page-transition-kkp81n?file=/components/Component1.tsx


text:
Q: Dash search not finding some files Unity dash is no longer searching for files since I encrypted the drive and reinstalled Ubuntu (I'm not sure if this is the cause).
Searching for files usually shows me results from 'Recent' files if I have usage history enabled but that's not what I'm after.
Sometimes searching for a file gives me no results, like so:
(this file is on my secondary drive /mnt/...)

Sometimes it does return results: (note that all these files are also on the same drive /mnt/...)
**Edit: These files are actually in the 'Recent' category even though I have history disabled and cleared, in Privacy settings. Odd. Which means that in fact NO files are being found appart from the history.

Files on my main drive are also omitted.
It does however seem to be finding folders just fine:

This wasn't happening before I reinstalled Ubuntu 16.04LTS with encryption (both system and /home). But I'm not sure if that's the cause.
I tried changing /etc/updatedb.conf, removing ecryptfs and sudo updatedb as suggested in some other questions but that hasn't worked either.
This is the original content of the updatedb.conf file:
PRUNE_BIND_MOUNTS="yes"

# PRUNENAMES=".git .bzr .hg .svn"
PRUNEPATHS="/tmp /var/spool /media /home/.ecryptfs /var/lib/schroot"

PRUNEFS="NFS nfs nfs4 rpc_pipefs afs binfmt_misc proc smbfs autofs iso9660 ncpfs coda devpts ftpfs devfs mfs shfs sysfs cifs lustre tmpfs usbfs udf fuse.glusterfs fuse.sshfs curlftpfs ecryptfs fusesmb devtmpfs"

P.S. Also, I'd like to know if there is a way to remove the recent files altogether. Since I have cleared and disabled the privacy settings and they still show up.

A: After some reading, I found out that in fact Unity dash doesn't scan all the files on the system, it mostly uses the zeitgeist code to look through recently used files and applications. This means that the recent files that I'm seeing is actually an intended result.
By disabling 'Record file and application usage' in Privacy settings I'm disabling zeitgeist and recently used files no longer show up in the main dash lens. Also, the 'Recent' section in nautilus becomes disabled.
Some have mentioned that the newest versions of Ubuntu also use locate  to locate files through the dash. I  installed the locate package which seems to have been missing on my system. and I don't know if I'm seeing a difference. However searching for an exact name does seem to produce a result (e.g myfilesomewhere.odt)
I'll update this answer as I learn more about the dash functionality.

A: The problem is with your configuration:
The likely source of your issue is the PRUNEFS entry.
PRUNEFS
A whitespace-separated list of file system types (as used in /etc/mtab) which should not be scanned by updatedb(8). The file system type matching is case-insensitive. By default, no file system types are skipped.
When scanning a file system is skipped, all file systems mounted in the subtree are skipped too, even if their type does not match any entry in PRUNEFS.
A less likely possibility is:
PRUNE_BIND_MOUNTS
One of the strings 0, no, 1 or yes. If PRUNE_BIND_MOUNTS is 1 or yes, bind mounts are not scanned by updatedb(8). All file systems mounted in the subtree of a bind mount are skipped as well, even if they are not bind mounts. As an exception, bind mounts of a directory on itself are not skipped.
By default, bind mounts are not skipped.
NOTE:
       The accompanying locate(1) utility was designed to be compatible to slocate and attempts to be compatible to  GNU  locate
       where possible.  This is not the case for updatedb.

Sources:
https://linux.die.net/man/5/updatedb.conf
https://unix.stackexchange.com/questions/198590/what-is-a-bind-mount


text:
Q: Cómo detectar si paso una cierto tiempo y no se hizo click en ningún elemento? Estoy tratando de detectar que pase un tiempo determinado y si no hicieron click que se ejecute una función, como puedo hacerlo ? gracias

A: deberias poner un ejemplo mínimo de que intentaste hacerlo tu, no estamos para hacerte todo, sino para ayudarte con tu código, pero tratandose de que hoy es feriado en mi país y estoy aburrido, ahi va una posible solución:
<script>
  let clicks = 0;
  document.addEventListener('click', function(){
   clicks ++
  })
  setTimeout(() => {
   if(clicks === 0){
    console.log("No hiciste ningun click");
   }else {
    console.log("Has hecho " + clicks + " clicks.");
   }
  }, 3000);
 </script>

Te explico un poco de que se trata:
La instrucción document.addEventListener() pone al documento a la escucha de un click, sea donde sea que lo hagas dentro de la ventana del navegador.
Por otro lado inicio una variable para almacenar los clicks y dentro del listener le sumo 1 cada vez que se hace click.
Luego en el setTimeout, que es un temporizador, por asi decirlo, con un condicional determino si hubo o no clicks.
Por supuesto debes reemplazar a los console.log() por la funcion que quieras que se ejecute.
Espero te sea de utilidad!!


text:
Q: One-parameter group not a group? Why? So one-parameter group $G$ is defined with a continuous group homomorphism $\phi: \mathbb{R} \rightarrow G$.
But according to the texts I read, they say that $G$ must be distinguished from groups as $G$ is not a group. So my wonder is, but there is group homomorphism there... So what is going on?

A: What is going on is that we are referring to the continuous group homomorphism itself as a "one-parameter (sub)group." Much like how a curve, in differential geometry (or topology more generally), may be described as a continuous map from an interval into a space. Different functions can have the same image, and a single group may be parametrized in different ways even though the image the two parametrizations inhabit inside the codomain are identical. One may think of the parametrization as extra data attached to a bona fide (sub)group.


text:
Q: How to find value of a cell from named range Is in EXCEL some formala, that can find value of a cell. Something like INDEX, but instead of an index column, a named range.
I want to find cell in this named range and i know index of row

A: Just use INDEX as you would normally, and specifiy the name rather than the range, eg if YourNamedRange names the range A1:A100 then
=INDEX(YourNamedRange, IndexNumber)

and
=INDEX(A1:A100, IndexNumber)

are equivalent

A: for vba
range("YourNamedRange").cells(1,1)
will get you the value of the first cell in the range


text:
Q: Significance (p-value) in regression/size of parameter estimate In a linear (OLS) regression, I find that the sizes of the coefficients vary a lot: one of them is about 0.0005 and another is ~150. The p-values are all under 0.1. Is this  reliable result? These are time-series variables by the way.
Separately, in another OLS time series regression, I am finding a variable to be significant which according to the business client, should not be. This variable has much higher variance than other input variables we tried in the model and also has high correlation with the dependent variable. COUld the low p-value/statistical significance/ high correlation arise due to the variance? The other variables have low variance over the observed time period.
Thanks for any insight.

A: The size of the coefficients is dependent on the scale of the explanatory/right-hand-side/independent/x-variable. Say we use annual household income as an explanatory variable measured in euros. The coefficient will tell us how much we expect the outcome to change for a euro change in annual income. That effect will in all likelihood be very small. It would probably make more sense to measure annual income in 1000s of euros (just divide the old income by 1000). In that case the effect will be a 1000 times the old effect. The p-value will remain unchanged, as we did not change the model: If 1 euro increase leads to a 0.01 change in y, then a 1000 euro increase will lead to a 10 change in y. These are just different ways of saying the same thing. So it is very well possible to have such huge differences in coefficients and similar p-values. In practice, if I see such large differences in coefficients I always reconsider the unit of the explanatory variables.


text:
Q: php extract from array/query and define php session variable by row without overwriting I have a mySQL database that is queried and displayed in tables in index.php. I have a file called up.php that handles a click on an  in each table that is output from the query in index.php. I need to have a variable that I can extract from a field in each seperate row that is queried, so that when the  is clicked it passes the variable to the up.php file to be manipulated. Right now the variable is just being over written and is equal to the value of the last row queried and the database is updated frequently, so I can't just set one to each row, it has to be dynamic.
Here is the index.php file
<?php
$sql = mysql_query("SELECT * FROM blogData ORDER BY id DESC");
//query for even numbered rows where mes_id = even
$sql2=mysql_query("SELECT * FROM messages WHERE mod(mes_id,2) = 0 ORDER BY mes_id DESC");
//query for odd numbered rows where mes_id = even
$sql3=mysql_query("SELECT * FROM messages WHERE mod(mes_id,2) = 1 ORDER BY mes_id DESC");

while(($row = mysql_fetch_array($sql))AND($row2 = mysql_fetch_array($sql2))AND($row3 = mysql_fetch_array($sql3)) ){
$id = $row['id'];
$title = $row['title'];
$content = $row['content'];
$category = $row['category'];
$podcast = $row['podcast'];
$datetime = $row['datetime'];

$message1=$row2['msg'];

//******* this is the variable from the query that needs to be held and not overwritten ********
$mes_id1=$row2['mes_id'];

$totalvotes1=$row2['totalvotes'];

$message2=$row3['msg'];

//******* this is the second variable from the query that needs to also be held and not overwritten *******
$mes_id2=$row3['mes_id'];

$totalvotes2=$row3['totalvotes'];

//attempting to implement this array...? not sure how to use it correctly...
$valuess[]=$row2['mes_id'];

//******* I was trying to use these session variables in up.php but they were being overwritten in the query ********
$_SESSION['message1'] = $row2['msg'];
$_SESSION['message2'] = $row3['msg'];
$_SESSION['mes_id1'] = $row2['mes_id'];
$_SESSION['mes_id2'] = $row3['mes_id'];
$_SESSION['totalvotes1'] = $row2['totalvotes'];
$_SESSION['totalvotes2'] = $row3['totalvotes'];
$_SESSION['valuess'] = $valuess[1];
?>

<?php
// variable used to display file name of $podcast without the extension
$noext = $podcast;
$echodub = rawurlencode($podcast);
// code to display $noext without the file extension
$info = pathinfo($noext);
$noext_name =  basename($noext,'.'.$info['extension']);
?>

 <?php echo $title; ?>

 <?php echo $datetime; ?>

 <?php echo $category; ?>
 <?php echo $_SESSION['mes_id1']; ?>
 <?php echo $_SESSION['mes_id2']; ?>
 <?php echo session_id(); ?>

 <?php echo $content; ?>

<a href="<?php echo"uploads/$podcast"; ?>"><?php echo"$noext_name"; ?>

<a href="up.php" class="" id="<?php echo $_SESSION['mes_id']; ?>" name="up">

<?php echo $_SESSION['totalvotes1'] ?>

<?php echo $_SESSION['message1'] ?>

//********the down.php file is the same as the up.php file... just with opposite variables... im not concerned with this yet until i get the variables to display correctly in up.php

<?php echo $_SESSION['totalvotes2'] ?>

<a href="down.php" class="" id="<?php echo $_SESSION['mes_id2']; ?>" name="down">

<?php echo $_SESSION['message2'] ?>

<?php
}
?>

and here is the up.php file
up.php
<?php
session_start();
include("config.php");

$message1 = $_SESSION['message1'];
$message2 = $_SESSION['message2'];
$mes_id1 = $_SESSION['mes_id1'];
$mes_id2 = $_SESSION['mes_id2'];
$totalvotes1 = $_SESSION['totalvotes1'];
$totalvotes2 = $_SESSION['totalvotes2'];
$ip=$_SERVER['REMOTE_ADDR'];

$ip_sql=mysql_query("select ip_add from Voting_IP where mes_id_fk='$mes_id1' and ip_add='$ip'");
$count=mysql_num_rows($ip_sql);
$ip_sql2=mysql_query("select ip_add from Voting_IP where mes_id_fk='$mes_id2' and ip_add='$ip'");
$count2=mysql_num_rows($ip_sql2);
//********* testing if these variables are being passed.....
echo $mes_id1;
echo $mes_id2;
$valuess[0] = $_SESSION['valuess'];
echo $valuess[0];
//********
// if the user has already voted, execute script
if($count==0 && $count2!=0)
{
$sql = "update Messages set totalvotes=totalvotes+1  where mes_id='$mes_id1'";
mysql_query( $sql);
$sql_in = "insert into Voting_IP (mes_id_fk,ip_add) values ('$mes_id1','$ip')";
mysql_query( $sql_in);
$sql = "update Messages set totalvotes=totalvotes-1  where mes_id='$mes_id2'";
mysql_query( $sql);
$sql_in = "DELETE FROM Voting_IP WHERE mes_id_fk='$mes_id2'";
mysql_query( $sql_in);
// if the user has not voted, execute script
}
else if($count==0 && count2==0)
{
$sql = "update Messages set totalvotes=totalvotes+1  where mes_id='$mes_id1'";
mysql_query( $sql);
$sql_in = "insert into Voting_IP (mes_id_fk,ip_add) values ('$mes_id1','$ip')";
mysql_query( $sql_in);
echo $mes_id1;
echo $mes_id2;
}
?>

Thank you so much to anybody who is able to help me!
$(".vote").click(function()
{

var id = $(this).attr("id");
var name = $(this).attr("name");
var dataString = 'id='+ id ;
var parent = $(this);

if(name=='up')
{

$(this).fadeIn(200).html('');
$.ajax({
type: "POST",
url: "up.php",
data: dataString,
cache: false,

success: function(html)
{
parent.html(html);

}  });

}
else
{

$(this).fadeIn(200).html('');
$.ajax({
type: "POST",
url: "down.php",
data: dataString,
cache: false,

success: function(html)
{
   parent.html(html);
 }

 });

  }

});

  });

A: With the javascript, I can see what you need to do in order to get it working how you want.
Instead of putting the key1=value1 etc attached to the href, put it in its own attribute called data-options, without the ? pre-pending it.  So looking like:
Up/Down

From there, you would modify the JS to be:
$(".vote").click(function()
{

var id = $(this).attr("id");
var name = $(this).attr("name");
var eData = $(this).attr("data-options");
var dataString = 'id='+ id + '&' + eData ;
var parent = $(this);

From there, you would access them in the up.php and down.php files by using $_POST['key1'], and only need to echo out what your JS is expecting in return from its AJAX call. ^^


text:
Q: What does "return" do in Javascript? I just taught myself how to code with tutorials from the internet.
I'm currently trying to learn Javascript and I don't really undesrtand the purpose of "return". I made a "rock, paper, scissors" game at the end of my lesson, using the return function. The game looks like this:
var userChoice = prompt("Do you choose rock, paper or scissors?");
var computerChoice = Math.random();
if (computerChoice < 0.34) {
    computerChoice = "rock";
} else if(computerChoice <= 0.67) {
    computerChoice = "paper";
} else {
    computerChoice = "scissors";
} console.log("Computer: " + computerChoice);

var compare = function(choice1, choice2){
    if(choice1 === choice2){
        return "The result is a tie!";
    }
    else if(choice1 === "rock"){
        if(choice2 === "scissors"){
            return "rock wins";
        }
        else{
            return "paper wins";
        }
    }
    else if(choice1 === "paper"){
        if(choice2 === "rock"){
            return "paper wins";
        }
        else{
            return "scissors wins";
        }
    }
    else if(choice1 === "scissors"){
        if(choice2 === "paper"){
            return "scissors wins";
        }
        else{
            return "rock wins";
        }
    }
};
compare(userChoice, computerChoice);

What exactly would be the difference if I used console.log("....") instead of "return" here?

A: According to W3Schools,

The return statement stops the execution of a function and returns a
  value from that function.

But

console.log writes into the browser console.

In other words, you can't see the output of console.log unless you open 'Developer Tools'
According to MDN (a much more reliable source),

When a return statement is called in a function, the execution of
  this function is stopped. If specified, a given value is returned to
  the function caller. If the expression is omitted, undefined is
  returned instead. The following return statements all break the
  function execution:

return;
return true;
return false;
return x;
return x + y / 3;

But

console.log() outputs a message to the Web Console.

For example,
function myFunction() {
    return Math.PI;
}

would return 3.141592653589793 when the function is called.
But using console.log instead, would not show anything, on a webpage (except in developer tools).

A: In JavaScript, most things are expressions, and every expression has a value. That can be a number (5), a string ("Hello, World!"), an object ({ foo: 'bar' }) or something other, like a regex.
When you use an operator, e.g. choice1 === "rock", that's also an expression, which has a boolean value (true or false). The expression 5 + 3 has a value, too. It is 8.
When you call a function, that's also an expression, which has a value. The prompt function, for example, has the value that the user entered. It's what you get back when you call prompt(...). The value of a function call is refered to as the "return value" of that function.
When you define your own function, you can also give them a return value. And later, when you call the function, this return value is what you get back. Remember functions in the maths class in school? Things like f(x) = x * x? When you "call" f with 5, then 25 is the value of that "function call": f(5) = 5 * 5 = 25.
Now, let's define our own JavaScript function that has a return value:

function add (a, b) {
  return a + b; // make the sum of a and b the return value of "add"
}

var result = add(5, 3); // store the value of the function call
console.log(result); // should log 8

Many built-in JavaScript functions have a return value: Math.min() returns the smallest of the arguments passed to it, document.getElementById() returns the HTML element with the id that you passed to it.
For some functions, it doesn't make any sense to return the result of an action. What should be the result of console.log()? Those functions return the value undefined. When your own functions don't have a return statement, their return value is undefined.
It is very important to note that the execution of a function stops when it hits a return statement. It then immediately returns to the location in the script where the function was called:

function test () {
  console.log('Hello 1');
  return 5; // return to the caller
  console.log('Hello 2'); // will not execute
}

var result = test();
console.log(result); // 5

When you leave out the value after the return ...;, so you just say return;, then the return value will also be undefined. You can use that if you want to stop the execution without a value to return:

function divide (a, b) {
  return a / b;
}

function printQuotient (a, b) {
  if (b === 0) {
    // the divisor is zero, do nothing
    return;
  }

  // divisor is not zero, print the result of the division
  console.log(divide(a, b));
}

printQuotient(10, 5); // prints 2
printQuotient(10, 0); // prints nothing

A: The concept of return is to return something.
for ex you could have var winner = compare(userChoice, computerChoice);
That would set the winner as the string returned from the function compare(), and you could use that var later for display. So in all actuality winner could be equal to any of your if/else strings. so for another ex, winner could be read as winner = 'rock wins' (if that was the logical winner)

A: When a return is encountered in a function. It will return to the point immediately after the code that called the function.  If nothing is specified after the return statement, that is all that happens. However if a literal is returned like 2 or 3,etc, a literal is returned.  You can also return a Boolean "true/false ", a string, or a variable.  Console.log ()  means what the name implies, it literally displays the value inside the parentheses to the development console. Its primary use is for troubleshooting.

A: console.log will display or emit the parameter passed to the log method in the console window of your browser and can be used almost anywhere in the code.
Meanwhile when using the return statement, the function will stop executing, and return the specified value.
Read more;

*

*What is console.log?

*Difference between console.log and return in
javascript?

*Why should I use return instead of console.log?


text:
Q: How do we get a dictionary from classes, this code does not run as I want it to:
class A():
    def __init__(self,b,c):

        self.b = 1
        self.c = 2

def get_dict(self):

    mydict={}
    for att in A():
        mydict[att]=self.att
    return mydict

print(get_dict(s))

A: You mean by this:
class A():
    def __init__(self):

        self.b = 1
        self.c = 2

def get_dict(self):

    mydict={}
    for att in [i for i in dir(A()) if not i.startswith('__')]:
        mydict[att]=getattr(self,att)
    return mydict

print(get_dict(A()))

Output:
{'b': 1, 'c': 2}

A: You can just use the special attribute __dict__ of you class:
class A():
    def __init__(self,b,c):

        self.b = 1
        self.c = 2

Output:
a = A(3,4)
print(a.__dict__)

{'b': 3, 'c': 4}

A: You can use the __dict__ attribute to get a dict of all the attributes of an object.
class A():
    def __init__(self,b,c):

        self.b = b
        self.c = c

    def get_dict(self):
        return self.__dict__

print(A(1, 2).get_dict())

This outputs:
{'b': 1, 'c': 2}

A: This question is a bit ambiguous.
If you're asking for the simple attributes for instances of simple classes, this is exactly what the vars builtin is for:
def get_dict(self):
    return vars(self)

While we're at it, it's pretty weird to call a parameter self when you're not writing a method; let's call it something different:
def get_dict(obj):
    return vars(obj)

But there are a lot of things this won't pick up, including:

*

*Properties.

*Any attributes of a __slots__ class.

*Class attributes.

*Dynamic attributes from __getattr__/__getattribute__ and __dir__.

If you want as many of those as possible, that's what the dir builtin is for. But dir just returns a list of names; you then have to look each one up:
def get_dict(obj):
    return {name: getattr(obj, name) for name in dir(obj)}

This is pretty close to "every whatever I could do an obj.whatever with".

But that's probably more than you want. It'll include private members, and bound methods, and special stuff used by the Python interpreter. You have to decide exactly what you want to filter out, but once you have a rule, it should be easy to implement. For example:
def get_dict(obj):
    public = ((name, getattr(obj, name)) for name in dir(obj) if not name.startswith('_'))
    noncallablepublic = {name: value for name, value in everything if not callable(value)}
    return noncallablepublic

If you want to get fancier, look at the inspect module, which has helper functions for this kind of filtering.

While we're at it, if you have a good reason for doing this on some particular set of classes, you might want to design those classes to be easier to convert to a dict—and to be able to customize how they're converted.
For example, if you build your classes with @dataclass—or with the third-party attrs library, which is more powerful and doesn't require Python 3.7—it's trivial:
>>> @dataclasses.dataclass
... class A:
...     b: int = 1
...     c: int = 2
>>> a = A()
>>> a
A(b=1, c=2)
>>> print(dataclasses.asdict(a))
{'b': 1, 'c': 2}

The dataclasses library built the __init__ method for me, and also the __repr__ method, and the other stuff needed to support things like asdict, so I didn't have to write anything at all.


text:
Q: why cache doesn't work as it supposed to be? According to http://igoro.com/archive/gallery-of-processor-cache-effects/, while trying Example 2, time should drop until the offset equals to the cache line zie.
However, on my machine, it doesn't work.
The code is just like following.
#define SIZE 1024*1024*64

int main()
{
struct timeval start, end;
int k;
int i;

for(k = 1; k <= 1024; k *= 2)
{

    int *arr = (int*)malloc(SIZE * sizeof(int));
    gettimeofday(&start, NULL);
    for(i = 0; i < SIZE; i += k)
        arr[i] *= 3;
    gettimeofday(&end, NULL);

    printf("K = %d, time = %d\n", k,
            (end.tv_sec - start.tv_sec)*1000000 + (end.tv_usec - start.tv_usec));

    free(arr);
}
return 0;
}

The result comes out as:
K = 1, time = 410278
K = 2, time = 265313
K = 4, time = 201540
K = 8, time = 169800
K = 16, time = 155123
K = 32, time = 142496
K = 64, time = 137967
K = 128, time = 135818
K = 256, time = 135128
K = 512, time = 135167
K = 1024, time = 135462

A: It depends upon the compiler (its version), the optimization levels, and the CPU. Apparently, most of the time is spent in malloc so I moved it out of the loop and increased SIZE.
I'm trying on Debian/Sid with GCC 4.8.1 on a i3770K processor with 16Gbytes of RAM.
with
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <time.h>
#define SIZE 1024*1024*1024

int main ()
{
  struct timeval start, end;
  clock_t startcl, endcl;
  int k, i;

  int *arr = (int *) malloc (SIZE * sizeof (int));
  if (!arr) { perror("malloc"); exit(EXIT_FAILURE); };
  for (k = 1; k <= 1024; k *= 2)  {
      gettimeofday (&start, NULL);
      startcl = clock();
      for (i = 0; i < SIZE; i += k)
        arr[i] *= 3;
      gettimeofday (&end, NULL);
      endcl = clock();
      printf ("K = %d, time = %ld, cpu clock=%ld microsec\n", k,
              (end.tv_sec - start.tv_sec) * 1000000
              + (end.tv_usec - start.tv_usec),
              (long) (endcl - startcl));
    }
  free (arr);
  return 0;
}

and compiling with gcc -Wall -mtune=native -O3 ./wilsonwen.c -o ./wilsonwen-O3 then running it:

K = 1, time = 696074, cpu clock=680000 microsec
K = 2, time = 361173, cpu clock=360000 microsec
K = 4, time = 341920, cpu clock=340000 microsec
K = 8, time = 341767, cpu clock=340000 microsec
K = 16, time = 342065, cpu clock=340000 microsec
K = 32, time = 224502, cpu clock=230000 microsec
K = 64, time = 119544, cpu clock=120000 microsec
K = 128, time = 51089, cpu clock=50000 microsec
K = 256, time = 26447, cpu clock=20000 microsec
K = 512, time = 14104, cpu clock=20000 microsec
K = 1024, time = 8385, cpu clock=10000 microsec

which is more consistent with the blog you mentioned. Moving the malloc out of the outer loop on k is really important (if you don't, you don't see the cache effect, apparently because malloc and the underlying mmap syscall is eating quite a lot of time).
I cannot explain why for k=1 it takes more time (perhaps, because the malloc-ed memory is taken into RAM by page faults?). Even by adding a for (i=0; i<SIZE/1024; i++) arr[i] = i; loop to "pre-fetch the pages" before your for (k loop  the time  for k=1 is still nearly twice as bigger than for k=2 . We do see the plateau for k=2 to k=16 mentioned in Igor Ostrovsky's blog. Replacing malloc with calloc is not very significant. Using clang (3.2) instead of gcc (4.8) for compilation gives very similar timing results.
Optimizing is very important, by trying with gcc -Wall -O0 ./wilsonwen.c -o ./wilsonwen-O0 and running that I don't see any plateau (which you'll see even with -O1). It is well known that gcc without any optimization flags spit quite poor machine code.
A general rule when benchmarking is to enable the compiler optimizations.

A: The same as mine.
Someone got the same result in the discussion under that article. And he said maybe it is  just the the real CPU time for arr[i] *= 3.
When K = 1 , it needs to run SIZE times. But when K = 2, it only needs to run SIZE/2 times.
So you could rewrite the code to run the same times despite whatever the K is. Then check whether it is the same. I just had this thought while typing. I will try this later. If you have tried , please add a comment.
Here is my code:
#include <stdio.h>
#include <time.h>
#include <stdint.h>
#define SIZE 64*1024*1024
int32_t arr [SIZE];
struct timespec ts;

int main(int argc, char *argv[])
{
long i,j= 0;
long start;
long start_sec;
int count = 1;
int k = 0;

// init the arr;
for (i = 0; i< 64*1024*1024;++i){
    arr[i] = 0;
}

for (j = 1; j< 1025;){
    clock_gettime(CLOCK_REALTIME, &ts);
    start = ts.tv_nsec;
    start_sec = ts.tv_sec;
    for (i = 0, k = 0; i< 64*1024*1024; i++, k+=j){
        k = k & (SIZE -1);
        arr[k] *=3;
        arr[k] =1;
    }
    clock_gettime(CLOCK_REALTIME, &ts);
    printf ("%d, %ld, %ld\n", count,(ts.tv_sec-start_sec)*1000000000+(ts.tv_nsec -start), j);
    count++;
    j *= 2;
}
return 0;
}

and the output is below:
1, 352236657, 1
2, 356920027, 2
3, 375986006, 4
4, 494875602, 8
5, 957796009, 16
6, 1397285233, 32
7, 1784398514, 64
8, 1070586859, 128
9, 1130548756, 256
10, 1169113810, 512
11, 1312605482, 1024

If I comment out the arr-init loop, it takes more time than K=2 when K=1.
And we can see that, the time just increases as the expectation(before K = 128). Because we alway have a loop of 64*1024*1024 times despite the K. Greater the K is, more time the cache line will flush.
Well, but I can't explain the decreasing from K = 64 to K = 128.
And @Mysticial talked about the lazy-malloc, so I also did a experiment with the original code in the article, but added the arr-init loop to avoid the lazy-malloc problem. The cost of K = 1 did decrease, but it is still greater than K=2's cost and closer to K=2's cost * 2 than original version. Data is below:
1, 212882204, 1
2, 111660951, 2
3, 67843457, 4
4, 62980310, 8
5, 62092973, 16
6, 42531407, 32
7, 27686909, 64
8, 9142755, 128
9, 4064936, 256
10, 2342842, 512
11, 1130305, 1024

So I think the reason of the decreasing from K = 1 to K = 2 and K=2 to K=4 is the decreasing of the number of iterations from SIZE to SIZE/2.
This is what I think, but I'm not sure.
======================================================
I complied the code with -Ox, the decreasing disappeared (but have to add the arr-init loop). Thanks to @Basile.
I will check the differences in the asm code later.
This is the differences between the asm code:
Without O1,
    movq    $0, -32(%rbp)
    jmp .L5
.L6:
    movq    -32(%rbp), %rax
    movl    arr(,%rax,4), %edx
    movl    %edx, %eax
    addl    %eax, %eax
    addl    %eax, %edx
    movq    -32(%rbp), %rax
    movl    %edx, arr(,%rax,4)
    movq    -24(%rbp), %rax
    addq    %rax, -32(%rbp)
.L5:
    cmpq    $67108863, -32(%rbp)
    jle .L6

And with O1,
    movl    $0, %eax
.L3:
    movl    arr(,%rax,4), %ecx # ecx = a[i]
    leal    (%rcx,%rcx,2), %edx # edx = 3* rcx
    movl    %edx, arr(,%rax,4) # a[i] = edx
    addq    %rbx, %rax # rax += rbx
    cmpq    $67108863, %rax
    jle .L3

And I change the asm code without O1 to this,
    movq    $0, -32(%rbp)
    movl    $0, %eax
    movq    -24(%rbp), %rbx
    jmp .L5
.L6:
    movl    arr(,%rax,4), %edx
    movl    %edx, %ecx
    addl    %ecx, %ecx
    addl    %ecx, %edx
    movl    %edx, arr(,%rax,4)
    addq    %rbx, %rax
.L5:
    cmpq    $67108863, %rax
    jle .L6

Then I get the result:
1, 64119476, 1
2, 63417463, 2
3, 63732534, 4
4, 66703562, 8
5, 65740635, 16
6, 47743618, 32
7, 28402013, 64
8, 9444894, 128
9, 4544371, 256
10, 2991025, 512
11, 1242882, 1024

It's almost just the same as the O1.
It seems that the movq -32(%rbp), %rax stuff costs too much. But I don't know why.
Maybe I'd better ask a new question about it.


text:
Q: Android loading contact images with UniversalImageLoader In my app iam trying to load the contact images using UniversaImageLoader, i ran into few problems, and have few queries
1) Eventhough when iam running the Uniimagloader alone on my phone iam  getting the list but no images,
   what am i doing wrong?
2) i used some of the code from that proj , and also loaded the jarfile but still iam getting folloing error
FATAL EXCEPTION: main
12-19 20:37:22.050: E/AndroidRuntime(10152): java.lang.NoClassDefFoundError: com.nostra13.universalimageloader.core.ImageLoader
12-19 20:37:22.050: E/AndroidRuntime(10152):    at org.app.activity.BaseActivity.<init>(BaseActivity.java:11)
12-19 20:37:22.050: E/AndroidRuntime(10152):    at org.app.activity.ProfileActivity.<init>(ProfileActivity.java:39)
12-19 20:37:22.050: E/AndroidRuntime(10152):    at java.lang.Class.newInstanceImpl(Native Method)
12-19 20:37:22.050: E/AndroidRuntime(10152):    at java.lang.Class.newInstance(Class.java:1301)
12-19 20:37:22.050: E/AndroidRuntime(10152):    at android.app.Instrumentation.newActivity(Instrumentation.java:1022)

3) configuration for ImageLoader : iam doing this in my adapter , can i do that? doing this iam getting error at maxImageWidthForMemoryCache(800) it says Add cast to method reciever.
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context)
                    .maxImageWidthForMemoryCache(800)
                    .maxImageHeightForMemoryCache(800)
                    .httpConnectTimeout(5000)
                    .httpReadTimeout(30000)
                    .threadPoolSize(5)
                    .threadPriority(Thread.MIN_PRIORITY + 2)
                    .denyCacheImageMultipleSizesInMemory()
                    .memoryCache(new UsingFreqLimitedMemoryCache(2000000))
                    .discCache(new UnlimitedDiscCache(cacheDir))
                    .defaultDisplayImageOptions(DisplayImageOptions.createSimple())
                    .build();

I am struck. Any help is appreciated.

A: Try to make sure that context variable is an Activity instance. It has this kind of error in the past.


text:
Q: Why there is no VSS for sqlite? The SQL Server implementation by Microsoft contains the VSS writer and other components with it to help it take backups without making a considerable impacy on performance.
But there is no such VSS capability built into Sqlite.
So I would like understand the importance of VSS in SQL Server and how it can be useful for Sqlite?

A: VSS is a mechanism for achieving high concurrency.
SQLite is not designed for high concurrency in the first place.
(That said, in WAL mode, it is possible to make a backup without affecting other readers and writers, and even without WAL, the backup API has a mechanism to restart the backup if another writer would have made it inconsistent.)


text:
Q: Copy all fields to larger structure I have two structures, A and B, and I would like to copy all of the fields from B into A. I can't do a simple assignment of A=B; because A has many other fields that I want to remain unaffected. For now I've been assigning each field individually by name. Is there a good way to copy all of fields from B to A without having to assign each one individually? The best I've been able to come up with is assigning them all in a loop using A.(fieldname) syntax, but I was hoping there might be a one-line solution out there.

A: If you want to copy only some fields, then the dynamic field referencing is the best approach.
fields_to_copy = {'one', 'two'};

for k = 1:numel(fields_to_copy)
    A.(fields_to_copy{k}) = B.(fields_to_copy{k});
end

If you don't want to overwrite any fields in A, you could create your list of fields to copy in the following way
fields_to_copy = setdiff(fieldnames(B), fieldnames(A));

Alternately, if you have specific fields in A that you'd like to keep
fields_to_copy = setdiff(fieldnames(B), {'keep', 'these', 'fields'});


text:
Q: logstash: not able to connect mysql with logstash? I am trying to make connection with MySQL using logstash and write into elastic search below in my code in conf file
input {
    jdbc {
        jdbc_connection_string => "jdbc:mysql://192.168.2.24:3306/test"
        # The user we wish to execute our statement as
        jdbc_user => "uname"
        jdbc_password => "pass"
        # The path to our downloaded jdbc driver
        jdbc_driver_library => "/usr/local/Cellar/logstash/6.2.4/mysql-connector-java-8.0.11.jar"
        jdbc_driver_class => "com.mysql.jdbc.Driver"
        # our query
        statement => "SELECT * FROM report_table"
    }
}

output {
    elasticsearch {
    action => "index"
    hosts => "localhost:9200"
    index => "mysqlsample"
    document_type => "record"
    }
}

on running the above getting the below error :

Error: com.mysql.jdbc.Driver not loaded. Are you sure you've included
  the correct jdbc driver in :jdbc_driver_library?   Exception:
  LogStash::ConfigurationError   Stack:
  /usr/local/Cellar/logstash/6.2.4/libexec/vendor/bundle/jruby/2.3.0/gems/logstash-input-jdbc-4.3.9/lib/logstash/plugin_mixins/jdbc.rb:162:in
  open_jdbc_connection'
  /usr/local/Cellar/logstash/6.2.4/libexec/vendor/bundle/jruby/2.3.0/gems/logstash-input-jdbc-4.3.9/lib/logstash/plugin_mixins/jdbc.rb:220:in
  execute_statement'
  /usr/local/Cellar/logstash/6.2.4/libexec/vendor/bundle/jruby/2.3.0/gems/logstash-input-jdbc-4.3.9/lib/logstash/inputs/jdbc.rb:264:in
  execute_query'
  /usr/local/Cellar/logstash/6.2.4/libexec/vendor/bundle/jruby/2.3.0/gems/logstash-input-jdbc-4.3.9/lib/logstash/inputs/jdbc.rb:250:in
  run'
  /usr/local/Cellar/logstash/6.2.4/libexec/logstash-core/lib/logstash/pipeline.rb:514:in
  inputworker'
  /usr/local/Cellar/logstash/6.2.4/libexec/logstash-core/lib/logstash/pipeline.rb:507:in
  block in start_input'

A: Sounds like it's an issue with jdbc_driver_library => "/usr/local/Cellar/logstash/6.2.4/mysql-connector-java-8.0.11.jar".
Are you sure it's a valid path? Is that the correct connector? Maybe try to use the one that the documentation mentions: mysql-connector-java-5.1.36-bin.jar


text:
Q: Return the value from a range that matches with another cell I have something like this:

From A8:A10 I have a list with few companies; maybe more, maybe less, perhaps different from the ones in A2:A4. How can I get in B8 the value from C if there is a company in A2:A4 called the same as A8?

A: What about a simple VLOOKUP:
=VLOOKUP(A8,$A$2:$B$4,2)

or if you want the value in C:
=VLOOKUP(A8,$A$2:$C$4,3)


text:
Q: Chi-squared and T distribution when s.d isn't 1
I have answered the first question but I have no clue where to start with b) and c). I'm pretty sure b) looks like the chi-squared distribution but am not sure how to work anything out as the standard deviation of the normal distributed X values is 4?

A: (b) By simulation with a million iterations, assuming normal $\sigma = 4,$ we can expect about three significant digits of accuracy. [Sampling and
computation in R.]
set.seed(131)
x1 = rnorm(10^6, 0, 4)
x2 = rnorm(10^6, 0, 4)
x3 = rnorm(10^6, 0, 4)
x4 = rnorm(10^6, 0, 4)
q = x1^2 + x2^2 + x3^2 + x4^2
quantile(q,.99)
     99%
211.7721

So, if $Q = \sum_{i=1}^4 X_i^2,$ then
$P(Q \le 211.8) \approx 0.99.$
But $Q/16 \sim \mathsf{Chisq}(\nu=4),$
so $P(Q/16 \le h) = P(Q \le 16h) = 0.99,$ where $h= 13.2767$ and $16h = 212.4273.$
qchisq(.99, 4)  # Look in printed chi-sq CDF table.
[1] 13.2767


text:
Q: Multiple Regression Forecast I made a model based on approx 75% of the data set(in the sample). Then applied the model's estimator on the remaining values of the data set. The regression had approx 40% adj R^2.
Google lets you download 90-day interval of daily data, which has to be merged with weekly SVIs in order to have the same scale. I believe this is the reason why my prediction is so jagged compared to the actual values.
Any suggestions on how to mitigate this?
Forecast: Blue = Actual, Orange = Predicted

A: You have time series data which is not the same as cross-sectional data as there may be trends , level shifts , dynamic response to causals etc.. OLS (simple regression) does not incorporate memory unless you introduce appropriate lags in your variables. Time series methods identify the appropriate/required lag structure and anomalies . Your tool of choice is wanting ... why don't you post the weekly data fro both series in a csv file and I will demonstrate the art of the possible. Prediction lines are often never as smooth as actual values (but can be !) but your prediction line seems biased suggesting possibly inferior analytics. Analytics that are free often come with a subsequent price.
Please be specific about your "training data set" and your forecast region including any specification of future values for the predictor series.
Google output would also help explain their potential analytical shortcomings.
EDITED AFTER RECEIPT OF DATA :
It is inconguent to me that GOOGLE would a 2 variable OLS model on time series data. OLS models assume (by specification) that there are no lags needed in a predictor series to capture the relationship between the two observed series. Furthermore there are no untreated anomalies i.e. unusual values in either of the two series. Additionally there is an assumption that neither series has been effected by an individual exogenous event (e.g. a level shift) or that both series have been similarly effected. Furthermore there is the assumption that the errors from the model have constant variance. Furthermore there is the assumption that the parameters of the model are invariant over time. I suggest taking GOOGLE's free analysis with a big grain of salt.
Now the bad news is that your data has missing days ( holidays and such ) . Time series methods (ARMAX) including causal variables require a complete accounting. Now you could consider Your series to be a 5 day per week data series WITH  holiday values to be interpolated. The 5 day-per-week series may have a day-of-the-week effects which need to be considered in order to get a good reading on the response of Y to X . This day-of-the-week effect can either be deterministic or stochastic(adaptive) . If you wish to post two columns of 5 day-of-the-week data I will see what I can do to bring clarity to your analysis.


text:
Q: how to filter typeahead on basis of a particular dropdown value using Angular JS My requirement is that I have to filter input JSON data on basis of a value in one drop down means if dropdown value is "agency1" then I can show values of  only that JSON object  having "agency 1" value in "agency" key.
My JSON is this-
 $scope.myAgencies= [

  {
    "agency": "Agency1",
    "category" : "Plan",
    "name" : "ABC plan8",
    "type" : "BHC Plan"
  },
  {
    "agency": "Agency1",
    "category" : "Plan",
    "name" : "ABC plan",
    "type" : "PHC"
  },
  {
    "agency": "Agency2",
    "category" : "Plan",
    "name" : "LMN plan",
    "type" : "CHC"
  },
  {
    "agency": "Agency2",
    "category" : "Plan",
    "name" : "ABC plan",
    "type" : "BHC Plan"
  },
  {
    "agency": "Agency3",
    "category" : "Plan",
    "name" : "ABC plan",
    "type" : "PHC"
  },
  {
    "agency": "Agency3",
    "category" : "Plan",
    "name" : "ABC quote",
    "type" : "CHC"
  },
   {
    "agency": "Agency3",
    "category" : "Plan",
    "name" : "LMN Quote",
    "type" : "PHC"
  }

];

I am getting value of that dropdown by one function and storing its value like this-
$scope.listByCategory= function(){

$scope.result=$scope.selectedAgency;
}

in typeahead I am giving like this-
<input type="text" ng-model="customSelected" id="inputTypeahead" placeholder="Custom agency" typeahead="agency.result as agency.name for agency in myAgencies | filter:$viewValue" typeahead-template-url="agencyTemplate.html" class="form-control">

I have created a plunker here-
https://plnkr.co/edit/HNgxjCajodFM6onsRMQH?p=preview
My problem is that it is filtering on basis of "agency" not for a particular value of "agency"(means chosen dropdown value like "agency1") . Can anybody tell me how can I achieve that?

A: You filter for the type-ahead is only filtering by the type-ahead input, not the selected agency.
Change the filter to this:
filter:{name: $viewValue, agency: selectedAgency}

And it will work.
Update:
This is working, but when you select "All" again, you will get no results. To fix this, use this filter:
filter:{name: $viewValue, agency: selectedAgency.length ? selectedAgency : undefined}

This filter will check if the string in selectedAgency is not empty, and if it is empty, will set the filter for agency to undefined, so it will not affect the filter.


text:
Q: How to monitor a .NET (Core) app in the cloud? We have a webapp consisting of different front- and back-end components. Most of these components are built with .NET Framework (ASP.NET), some are built with ASP.NET Core. Our product is currently installed on-premise at customers, but we're now moving our product to the cloud (AWS).
Now that we move our product to the cloud, we are also investigating how we can monitor our components. We've been investigating New Relic and Dynatrace, and both of them give Distributed Tracing, which will show us the performance of a request as it moves through our application. But we're wondering if this will provide us with enough information to find the root cause of an incident. E.g. both tools are able to pinpoint which API call was slow, but they don't provide details why it was slow, or which method inside that API call was slow.
So what are your experiences with APM tools like Dynatrace and New Relic? Do they provide enough information in case of incidents? Or do you still need other tools, like a .NET Profiler, to find the root cause?

A: Dynatrace gives you full details how requests are moving through your application.

*

*With Service Flow you can visualize that path.

*With Response time hotspot you can view details how your request executed

*With Method hospot you can determine where was the slowest method in request chain

*with Backtrace you can understand what services are depend on your service request

*Tab Failure rate gives you information about all errors with description and further analysis

*Problems tab gives you full information about incident and analyze root cause of it. Baseling in action, with support of AI.

Main success story in my case was when Dynatrace help us find developers errors in code execution.


text:
Q: I keep getting syntax error, unexpected 'catch' (T_CATCH) in ... eval()'d code on line 185 I am a complete beginner to PHP.
I can't find my mistake in the following code.
It says "syntax error, unexpected 'catch' (T_CATCH) in ... eval()'d code on line 185".
This "    ?>" is line 185...
Is anyone able and willing to help me?
Thank you in advance,
Tim
I have nearly the same code for the tablet version of the website and there I don't have any errors.
<?php
    global $wpdb;
    global $startplz;
    global $zielplz;
    global $wertkategorie;
echo '<form class="kalkulator-phone" style="padding: 10px;" method="post" action="https://greendragon-webdesign.de/#kalkulator" >

PLZ Kalkulator
In 3 Schritten zum Frachtpreis

1. Schritt Fahrzeug wählen...

';
$wertkategorie = $_POST["kategorieList"];
if ($wertkategorie == 1){
  echo '<input type="radio" id="pkw" name="kategorieList" value="1" checked= "checked"> PKW';
}
else {
  echo '<input type="radio" id="pkw" name="kategorieList" value="1"> PKW';
}
echo '

';
if ($wertkategorie == 2){
  echo '<input type="radio" id="kombi" name="kategorieList" value="2" checked= "checked"> KOMBI';
}
else {
  echo '<input type="radio" id="kombi" name="kategorieList" value="2"> KOMBI}';
echo '

';
if ($wertkategorie == 3){
  echo '<input type="radio" id="transp1" name="kategorieList" value="3" checked= "checked"> BUS';
}
else {
  echo '<input type="radio" id="transp1" name="kategorieList" value="3"> BUS';
}
echo '

';
if ($wertkategorie == 4){
  echo '<input type="radio" id="transp2" name="kategorieList" value="4" checked= "checked"> MAXI Transporter';
}
else {
  echo '<input type="radio" id="transp2" name="kategorieList" value="4"> MAXI Transporter';
}
echo '

2. Schritt Start PLZ

';
$result1 = $wpdb->get_results ( "SELECT distinct (zip1) FROM versuch1" );
$startplz = $_POST["zip1List"];
echo '<select name="zip1List" id="zip1">
  <option selected="selected">';
  if ($startplz > 0) {
    echo $startplz;
  }
  else {
    echo '00000';
  }
  echo '</option>';

  foreach( $result1 as $value1 ) {
 echo '<option value="';

 echo $value1->zip1;

 echo '">';

 echo $value1->zip1;
 echo '</option>';

};
echo '</select>

3. Schritt Ziel PLZ

';
$result2 = $wpdb->get_results ( "SELECT distinct (zip2) FROM versuch1" );
$zielplz = $_POST["zip2List"];
echo '
<select style="margin-bottom: 10px;" name="zip2List" id="zip2">
  <option selected="selected">';
  if ($zielplz > 0) {
    echo $zielplz;
  }
  else {
    echo '00000';
  }
  echo '</option>';

  foreach( $result2 as $value2 ) {
 echo '<option value="';

 echo $value2->zip2;

 echo '">';

 echo $value2->zip2;
 echo '</option>';

};
echo '</select>

<input class="et_pb_button et_pb_custom_button_icon" data-icon="E" type="submit" name="submit" value="Berechnen" >

Ihr Frachtpreis

';
if(isset($_POST['submit'])) {
  if (isset($_POST['kategorieList'])) {
    if (isset($_POST['zip1List'])) {
        if (isset($_POST['zip2List'])) {
          $kategorie = $_POST['kategorieList'];
          $zip1 = $_POST["zip1List"];
          $zip2 = $_POST["zip2List"];
          $resultsap = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM versuch1 WHERE zip1 = %s AND zip2 = %s", $zip1, $zip2 ) );
          foreach ($resultsap as $row) {
            switch ($kategorie) {
              case 1:
        echo "€ $row->cost1";
        break;
    case 2:
        echo "€ $row->cost2";
        break;
    case 3:
        echo "€ $row->cost3";
        break;
    case 4:
        echo "€ $row->cost4";
        break;
            }
          }
        }
      }
    }
  }
echo '

Frachtpreis kann aufgrund von Serviceleistungen (SZ/WZ) abweichen

zzgl. MwSt.

Die PLZ 022113 (Oststeinbek) bzw. PLZ 022145 (Stapelfeld/Braak) für Bezirke außerhalb Hamburg!

Ein Produkt der City-Schnellbote GmbH / Stand 12.2021 / Irrtümer vorbehalten / Gerichtsstand Hamburg / Es gelten unsere AGB

</form>';
?>


text:
Q: Почему Apache возвращает forbidden? В корне сайта нет файла .htaccess , присутствует index.php. Почему при запросе на сайт возникает 403 ошибка?
Права на все папки - 755, на все файлы - 644, владелец - root
 Стоит php 7.0.20
 Конфиги апач
<VirtualHost *:80>
    ServerName myserver.com.ua

    ServerAdmin webmaster@localhost
    DocumentRoot /var/www_myserver.com.ua

<Directory /var/www_myserver.com.ua>
#   Options -Indexes +FollowSymLinks -MultiViews
#        AllowOverride all #Deprecated
#        Order allow,deny #Deprecated
#        Allow from all #Deprecater
#   Require all granted
</Directory>

    LogLevel alert rewrite:trace3
    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined

</VirtualHost>
<IfModule mod_ssl.c>
<VirtualHost *:443>

DocumentRoot /var/www_myserver.com.ua
ServerName myserver.com.ua

#SSLEngine on
#SSLCertificateFile /etc/apache2/ssl/server.crt
#SSLCertificateKeyFile /etc/apache2/ssl/server.key

<Directory /var/www_myserver.com.ua>
#   Options -Indexes +FollowSymLinks -MultiViews
#   AllowOverride all #Deprecated
#   Order allow,deny #Deprecated
#   Allow from all #Deprecated
#   Require all granted #Deprecated
</Directory>
</VirtualHost>
</IfModule>

Дополнил конфиги, попробовал рестартануть апач, выдает ошибку:
Restarting apache2 (via systemctl): apache2.serviceJob for apache2.service failed. See 'systemctl status apache2.service' and 'journalctl -xn' for details.

failed!
Комманда systemctl status apache2.service выдает:
apache2.service - LSB: Apache2 web server
   Loaded: loaded (/etc/init.d/apache2)
  Drop-In: /lib/systemd/system/apache2.service.d
           └─forking.conf
   Active: failed (Result: exit-code) since Tue 2017-07-11 17:36:38 EEST; 2min 3s ago
  Process: 1407 ExecStart=/etc/init.d/apache2 start (code=exited, status=1/FAILURE)

Jul 11 17:36:38 web21 apache2[1407]: Starting web server: apache2 failed!
Jul 11 17:36:38 web21 apache2[1407]: The apache2 configtest failed. ... (warning).
Jul 11 17:36:38 web21 apache2[1407]: Output of config test was:
Jul 11 17:36:38 web21 apache2[1407]: AH00526: Syntax error on line 9 of /etc/apache2/sites-enabled/001-web8.teamgear.conf:
Jul 11 17:36:38 web21 apache2[1407]: Illegal override option #Deprecated
Jul 11 17:36:38 web21 apache2[1407]: Action 'configtest' failed.
Jul 11 17:36:38 web21 apache2[1407]: The Apache error log may have more information.
Jul 11 17:36:38 web21 systemd[1]: apache2.service: control process exited, code=exited status=1
Jul 11 17:36:38 web21 systemd[1]: Failed to start LSB: Apache2 web server.
Jul 11 17:36:38 web21 systemd[1]: Unit apache2.service entered failed state.

A: попробуйте что-то вроде
<Directory "/var/www/example_site_directory">
    AllowOverride All
    Require all granted
</Directory>

в конфиге хоста. А то у вас все опции закомментированы. Это если у вас apache 2.4


text:
Q: List index out of range in Keras model In a CNN model using Keras, I am implementing the following code:
def train_model():
    # Load Dataset

    np.random.seed(666555)
    X = np.memmap('Processed/X_train.npy', 'float64', shape = (256, 224, 224, 3), mode = 'c')
    Y = np.memmap('Processed/Y_train.npy', 'float64', shape = (256), mode = 'c')
    X = np.random.shuffle(X)
    Y = np.random.shuffle(Y)

    # Training our Model on whole Dataset
    model = define_model()
    model.fit(X, Y, epochs = 30, verbose = 1, steps_per_epoch = 4)
    # Saving our Model
    model.save('One_block_VGG.h5')

    X_test = np.load('Processed/X_test.npy', mmap_mode='r')
    Y_test = np.load('Processed/Y_test.npy', mmap_mode='r')
    _, acc = model.evaluate(X_test, Y_test, verbose = 1)
    print('Accuracy of our Model on Test Set: %.3f' % (acc*100))

train_model()

I am getting the following error:
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-59-4dc2ba0c028a> in <module>
----> 1 train_model()

<ipython-input-58-994a78e8019e> in train_model()
     11     # Training our Model on whole Dataset
     12     model = define_model()
---> 13     model.fit(X, Y, epochs = 30, verbose = 1, steps_per_epoch = 4)
     14     # Saving our Model
     15     model.save('One_block_VGG.h5')

C:\Anaconda3\lib\site-packages\keras\engine\training.py in fit(self, x, y, batch_size, epochs, verbose, callbacks, validation_split, validation_data, shuffle, class_weight, sample_weight, initial_epoch, steps_per_epoch, validation_steps, validation_freq, max_queue_size, workers, use_multiprocessing, **kwargs)
   1237                                         steps_per_epoch=steps_per_epoch,
   1238                                         validation_steps=validation_steps,
-> 1239                                         validation_freq=validation_freq)
   1240
   1241     def evaluate(self,

C:\Anaconda3\lib\site-packages\keras\engine\training_arrays.py in fit_loop(model, fit_function, fit_inputs, out_labels, batch_size, epochs, verbose, callbacks, val_function, val_inputs, shuffle, initial_epoch, steps_per_epoch, validation_steps, validation_freq)
    139     indices_for_conversion_to_dense = []
    140     for i in range(len(feed)):
--> 141         if issparse(fit_inputs[i]) and not K.is_sparse(feed[i]):
    142             indices_for_conversion_to_dense.append(i)
    143

IndexError: list index out of range

I am loading only 256 images to check my model, but getting the error. How do I solve this error? The original shape of variables are:
X_train - (18873, 224, 224, 3)
X_test - (6127, 224, 224, 3)
Y_train - (18873,)
Y_test - (6127,)

In case you need to check define_model function:
def define_model():
    model = Sequential()
    model.add(Conv2D(32, (3, 3), activation = 'relu', kernel_initializer = 'he_uniform',
                     padding = 'same', input_shape = (224, 224, 3)))
    model.add(MaxPooling2D((2, 2), strides = (2, 2)))
    model.add(Conv2D(64, (3, 3), activation = 'relu', padding = 'same'))
    model.add(MaxPooling2D((2, 2), strides = (2, 2)))
    model.add(Flatten())
    model.add(Dense(128, activation = 'relu', kernel_initializer = 'he_uniform'))
    model.add(Dense(1, activation = 'sigmoid'))

    opt = SGD(0.001, 0.9)
    model.compile(optimizer = opt, loss = 'binary_crossentropy', metrics = ['accuracy'])

    return model


text:
Q: Can't make MakeFile c++ with -lcrypto Good day. I need to write makefile for my program. I only have ukol2.cpp. When i compile in terminal i write:
g++ -Wall ukol2.cpp -lcrypto -o prog; ./prog d
Also i have template:
CC = gcc
CFLAGS = -g
LDFLAGS = -lcrypto

all: hash stream
run:
    #run your tests here...
hash: hash.o
    $(CC) -o $@ $< $(LDFLAGS)
stream: stream.o
    $(CC) -o $@ $< $(LDFLAGS)
%.o: %.c
    $(CC) -c -o $@ $< $(CFLAGS)

Can you help to write my own makefile with same C and LD flags?


text:
Q: Show custom controls on webpage in other order than layed out in DDE - Xpages I have a number of custom controls layed out on an xpage. I want these controls to be displayed in the order of a setting in a notes document
So my xpage might look like this in DDE
CustomControl1
CustomControl2
CustomControl3
CustomControl4
but when the custom control is displyed on the webpage the custom controls should be displayed in the following order (based on the setting document)
CustomControl4
CustomControl1
CustomControl2
CustomControl3
anyone have any ideas how to accomplish this (server side)

A: Without knowing the real pain of your project I can only assume that the individual position needs to be defined at runtime, or something like that.
In general: controlling a page's layout is a pure CSS job. On the resulting page almost anything can be positioned almost anywhere within the page's range, and it doesn't matter where it was placed at design time. So, if you enclose your custom controls within their own containers (panels / divs) then you should be all set. You might define positioning classes in CSS and then have some SSJS code decide which class is assigned to what div.
If for example you have a custom control for each day of the week, and you always want to have the current day at the top-most position, then you could define 7 css classes as in ".today", ".todayPlus1", ".todayPlus2" ... ".todayPlus6". Write your positioning rules for each class. And finally compute each panel's styleClass property based on the current week day.

A: You can use the xp:switchFacet in combination with a xp:repeat to calculate the order at runtime like this:
<xp:repeat
    id="repeat1"
    rows="30"
    var="rowEntry">
    <xp:this.value><![CDATA[#{javascript:var arr = ["Control1","Control3","Control2"];return arr;}]]></xp:this.value>
    <xe:switchFacet
        id="switchFacet1"
        selectedFacet="#{javascript:rowEntry}">
        <xp:this.facets>
            <xp:panel xp:key="Control1">Control1</xp:panel>
            <xp:panel xp:key="Control2">Control2</xp:panel>
            <xp:panel xp:key="Control3">Control3</xp:panel>
        </xp:this.facets>
    </xe:switchFacet>
</xp:repeat>

Instead of the Array arr you can use data based on a document or xsp.propertie. The Output of this code is Control1 Control3 Control2 and in your Designer you have your controls inside switchFacet in following order: Control1 Control2 Control3.


text:
Q: Redirecting after devise sign up, but user is not logged in I am setting the user to redirect to a subdomain based on a nested form parameter after signup. However, when I do the redirect, the user is not logged in. I can go back in and manually log the user in, and I can verify the user is created, it just appears the session isn't immediately created after registration.
Here's the method I'm using to redirect the user (in registrations_controller.rb):
  def after_sign_up_path_for(resource_or_scope)
    root_url(subdomain: params[:user][:organizations_attributes]["0"][:subdomain])
  end

The routing to the subdomain works fine, btw.
I think this is a problem with sharing sessions across subdomain, as I am logged in when I remove the subdomain from the url and refresh.
I've tried add this this to my app/config/initializers/session_store.rb file:
Vocalem::Application.config.session_store :cookie_store, key: '_vocalem_session', :domain => :all

A: Turns out I just needed to reboot my server!


text:
Q: Error 404 when using AJAX XHR But still goes to Spring Controller I'm trying to upload a file that have a progress bar.
var fileInput = document.getElementById('jquery-ajax-single')
    var form = new FormData();
    form.append('uploadFile',fileInput.files[0]);

    $.ajax({
        url: "file/upload",
        processData : false,
        contentType : false,
        data : form,
        type : 'POST',
        xhr: function() {
            var xhr = $.ajaxSettings.xhr();
            xhr.upload.onprogress = function(e) {
                console.log(Math.floor(e.loaded / e.total *100) + '%');
                $('#progress-jquery-ajax-single.progress-bar-progress').css(
                        'width', Math.floor(e.loaded / e.total * 400)+ 'px'
                );
            };
           return xhr;
        }
    });

Code above is working and is able to go to FileController
@Controller
@RequestMapping("/file")
public class FileController {

    @RequestMapping(value = "/upload", method = RequestMethod.POST, headers = "X-Requested-With=XMLHttpRequest")
    public void upload(@RequestParam MultipartFile uploadFile){

        System.out.println("name : " + uploadFile.getOriginalFilename());
        System.out.println("content-type : " + uploadFile.getContentType());
        System.out.println("size : " + uploadFile.getSize());
    }
}

Every time I process the ajax it shows the progress of the upload, after reaching 100% goes to the FileController and prints the input file information, but upon looking at chrome browser console it returns :
jquery-2.1.4.js:8630 POST http://localhost:8080/FileUploadWeb/file/upload 404 (Not Found).
I also tried to use dropzone.js and it also returns error 404 but the url became http://localhost:8080/FileUploadWeb/file/file/upload
<form id="my-dropzone"action="file/upload" class="dropzone"></form>

A: After stumbling across this, the trick that should work was to return a ResponseBody entity in the POST method:
@PostMapping(value = "/upload")
public ResponseEntity<String> upload(@RequestParam MultipartFile uploadFile) {
    System.out.println("name : " + uploadFile.getOriginalFilename());
    System.out.println("content-type : " + uploadFile.getContentType());
    System.out.println("size : " + uploadFile.getSize());

    return new ResponseEntity<>("File Uploaded Successfully.", HttpStatus.OK);
}


text:
Q: vue-router and pagination links I have simple pagination for search results:

 1">

         <router-link :to="{params: {page: pageNumber}}">${pageNumber}</router-link>

And I try to integrate it with vue-router. It's my router instance:
const router = new VueRouter({
    history: true,
    routes: [
        { path: '/:producent/:type/page/:page' },
        { path: '/:producent/page/:page' }
    ]
})

So I would like to have urls: /mercedes/sedan or just /mercedes for 1-th page of results and /mercedes/sedan/page/x or /mercedes/page/x for others.
At this moment my links works and are generated properly only, when I open url /mercedes/sedan/page/1.
If I open /mercedes/sedan all of my router links are also /mercedes/sedan.
How to fix it?

A: I found a solution. I think it's not elegant, but works... I check url containst /page/ string, and then I just add params (if true) or I add it to the router path.
<router-link :to="{params: {page: pageNumber}}" v-if="$route.path.indexOf('/page/') >= 0">${pageNumber}</router-link>
<router-link :to="{path: $route.path.replace(/\/$/, '') + '/page/' + pageNumber}" v-else>${pageNumber}</router-link>