text:
Q: Angular momentum of child and swing system when a child is riding a swing the angular velocity of the swing with respect to the point of suspension keeps on increasing (given that, the child is keep on swinging by his own).
Who is providing external torque in this situation?
Why the angular momentum of the swing + child system is not constant?

A: If you think of the swing as an oscillator you can add a force to drive the oscillator, and if the driving force is near the resonance frequency then the amplitude of the oscillator will grow.
So a child rocking back and forth on the swing is using their own energy to change their center of gravity and its position with respect the lines holding the seat. So the moment of inertia of the swing and child is not constant as the swing moves. One way to model that in a paper by Case and Swanson

If you work out the equations you can find that at least for small angles it is like a driven oscillator driven at $\omega$, while for larger amplitudes it can be driven like like a parametric oscillator at frequency $2\omega$.
There are other ways to drive the swing, instead of leaning back and forth, a kid can just straighten their knees out a the appropriate frequency, or a more extreme case could crouch and stand in the swing. In the second case, it would be more like a parametric oscillator since if the swing was at rest, standing up and down would not start the motion. There would need to be some initial oscillation.
So shifting the center of mass (using the internal energy of the child) is adding energy from the gravitational field to the system at the right times. Or by rotating the legs with a kick adding to the angular momentum at the right time.

A: Gravity introduces external moment, once you managed to move the centre of gravity from the vertical projection of the hinge of the swing.
And you can move the centre of gravity, relying on the reaction of the hinge as an external force
More to come if needed


text:
Q: STR function in SQL SELECT ltrim (STR (1234.34968311,44,16));

Result: 1234.3496831099999000
SELECT ltrim (STR (123.34968311,44,16));

Result: 123.3496831100000000
Can someone please help me to understand why the first query returns the varchar value which is not exactly the same as the input.

A: Because STR operates on a FLOAT datatype so your decimal number constant is converted to a FLOAT before being transformed into a VARCHAR of the requested size. And as we all know, FLOAT values are an approximation of the number you thought you would get :-) so you end up with differing values after the decimal point.
For example, try STR (1234.1,44,16) and you get 1234.0999999999999000.
If you read the manual at http://msdn.microsoft.com/en-us/library/ms189527.aspx it says float_expression - Is an expression of approximate numeric (float) data type with a decimal point. Yes, APPROXIMATE.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to fix - 502 Bad Gateway Hello I'm totally clueless here,
I've been working with Patternlab on a local PHP env on mac. I had wifi troubleshooting, I restarted my computer and since then my localhost:8080 is showing the error below.
502 Bad Gateway
Socks5ProtocolException("SOCKS5 mode failure: SocksError('Invalid SOCKS version. Expected 0x05, got 0x47',)",)

I'm working on a php local server but I see the error without even lunching it. The error is showing when typing localhost:8080 in the browser.
(FYI last week I had problem with my PHP memory cache, I needed to updated the memory_limit = 128M to memory_limit = 256Mof the /etc/php.ini file can this be relevent to the issue ? It worked fine for 4 days after the change so this may not be the cause of problem but I really don't know what to do! )
Mac info :
macOSMojave 10.14.5

A: The problem is solved.
I followed theses steps to fix the issue :

*

*Go to apple icone

*Click system preferences

*Click network -> advanced setting -> proxies

*Uncheck all the options

*Select ok and apply the change restart.


text:
Q: Why do I get an error if I didn't specify brackets in a function even if it's only one statement in C? In for-loops, while-loops, and if-statements allow me to not specify the brackets if I put only statement in it like so:
for (fahr = LOWER; fahr <= UPPER; fahr = fahr + STEP)
    printf("%3d %6.1f\n", fahr, fahrToCelsius(fahr));

But if I do it in a function like so:
float fahrToCelsius(int fahr)
    return (5.0/9.0)*(fahr-32);

It gives me an error.
Why can't I omit brackets in functions with only one statement?

A: Because there is a C standards specification backing the language compiler and its implementation.
Breaking specifications(like writing non-standard code) is a bad idea in general and should be avoided to increase readability, maintainability and portability of your application.
Good compilers enforce standards based coding.
See here Open C Standards

A: Simply put, it's required by the language syntax.
The C language syntax says that a function-definition must end with a compound-statement, and a compound-statement must begin with { and end with }.
The syntax for for loops, while loops, and if statements must end with a "statement" syntax, which doesn't have to be a compound-statement (though it can be).
See the "Language syntax summary" in the C language standard (Annex A in C11).

A: Well you cant because C standart says so, as other answers mentioned, but if you really don't like brackets, you can try with preprocessor.
#define fahrToCelsius(fahr) ((5.0/9.0)*(fahr-32))


text:
Q: Foundation 6 Top Bar dropdown menu not working not work I copied the foundation navbar syntax straight from their site https://foundation.zurb.com/sites/docs/top-bar.html and the dropdown menu feature doesnt seem to be working
Here's the code:

Site Title

        One

One

Two

Three

Two

Three

<input type="search" placeholder="Search">

<button type="button" class="button">Search</button>

Here's what it looks like

A: Make sure to initialize foundation:
$(document).foundation();

A: I had the same issue -
This appears to be a known issue with Foundation 6.2 ~ 6.4 - at least for Rails apps using the foundation-rails gem.
The fix was to update the foundation_and_overrides.scss include order, move
@include foundation-dropdown-menu;

to the bottom as per here


text:
Q: Prevent tag creation on the post edition page Writers on my websites have no discipline. I told them to only use tags found via autocompletion, but they keep creating tags with mistake, typos and specially duplicate.
The best could be to remove the tags if they are not found, in JS, directly after the ajax request that do the autocompletion.
But I find no place were I could hook to forbid user to create tags, either in JS nor wp actions.
Any idea how to perform this?

A: This will disable the Tags suggesstion:
function wpse207107_dequeue_suggest() {
    global $post_type;

    if ( is_admin() && $post_type == 'post' ) {
        wp_dequeue_script( 'suggest' );
        wp_deregister_script( 'suggest' );
    }
}
add_action( 'admin_enqueue_scripts', 'wpse207107_dequeue_suggest', 5 );

However, that might disable some other suggest functionalities if other plugins uses the script. Alternatively, you can entirely remove the Tags metag box for non-admin if you want them not to tag the post while keeping it for admins.
function wpse207107_remove_tags_meta_box() {
    if ( !current_user_can( 'administrator' ) ) {
        remove_meta_box( 'tagsdiv-post_tag', 'post', 'side' );
    }
}
add_action( 'do_meta_boxes', 'wpse207107_remove_tags_meta_box' );


text:
Q: Python sqlite3 extra character in queries result So I am trying to run a simple query in python using sqlite to try it out . I get the result of the query right, but I get an extra "u" at the beginning of each text field and I am not sure why. Here is the code:
import sqlite3

db = sqlite3.connect(':memory:')
c = db.cursor()

c.execute("create table Students (ID INTEGER Primary key AUTOINCREMENT, FN text, LN text);")

c.execute("INSERT into Students (FN,LN) Values ('FirstName','LastName');")

c.execute("Select * from Students")

for i in c:
    print(i)

and here is the result I get:
(1, u'FirstName', u'LastName')

Process finished with exit code 0

any clue why this happens ?
Thanks

A: In Python source code, Unicode literals are written as strings prefixed with the u or U character.
If you don't want that your word became unicode you can encode with unicode-escape:
>>> s.encode('unicode-escape')
'FirstName'


text:
Q: Text not appearing on textfield To appear softkeyboard for android app i written textfield.needsSoftKeyboard = true and onclick on textfield call textfield.requestSoftKeyboard() method. keyboard is appearing..but the problem is text is not appearing on textfield...

A: It would make sense if you could post the code snippet here for further investigation. Other than that, it might be that your textfield loses focus for some reason so you may get your issue resolved by calling "stage.focus = textfield;". It could also be the case that there is a problem with font embedding or styles (e.g. white text on white background). Make sure the textfield shows text at all by passing a prefilled text to it. There is currently also a bug, where Chinese and Japanese chars cannot be displayed on some Android devices (https://bugbase.adobe.com/index.cfm?event=bug&id=3839647).

A: Problem is textfield loses focus.Finally I got solution.We have to set Focus for that tlf textfield like this.txtField.textFlow.interactionManager = new EditManager();
txtField.textFlow.interactionManager.selectRange(0, 0);
txtField.textFlow.interactionManager.setFocus();


text:
Q: Add values from Pandas row to dictionary I have a dataframe in Pandas that has columns that will correspond to the key and value of a dict.
for values in ['A','B']:
    MYDICT[values] = [] # Initialize to empty list

Name    ID    othercolumns
A       5     ...
B       6     ...
A       3     ...

I am trying to find a simple way to assign every value of Name to ID so MYDICT[NAME].append(ID)
The solution I currently have is to iterate over every row in the dataframe
for index, x in df.iterrows():
    WINNERS[x['Name']].append(x['ID'])

Is there a better way to do this without having to use iterrows()?

A: You can group by Name and aggregate ID into a list
WINNERS = df.groupby('Name')['ID'].apply(list).to_dict()
WINNERS

Out:
{'A': [5, 3], 'B': [6]}


text:
Q: How to start RabbitMQ cluster with IP addresses and no DNS entry? I am trying to create a RabbitMQ cluster using nodes that have no entries in DNS. Even though I have added the respective entries in /etc/hosts, the cluster always fails with this error:
$ rabbitmqctl join_cluster rabbit@pcomdvsns1
Clustering node rabbit@pcomdvsns2 with rabbit@pcomdvsns1 ...
Error: {cannot_discover_cluster,"The nodes provided are either offline or not running"}

Is DNS entry a must for getting this started?

A: Make sure that in your /etc/hosts there is an entry for pcomdvsns1 pointing to the correct IP, then verify if you can reach your node using:
rabbitmqctl status -n rabbit@pcomdvsns1

Then check if you have the same erlang cookies on both servers.

A: I think you want to make cluster taking advantage of rabbitmqctl.
Did you check whether the elrang cookie is same or not between these machine?
If you didn't, the message you said shows to us.


text:
Q: Validation with two related fields with variable regex test So I have a world wide list of countries and I want to validate the VAT / Tax Number for countries from the EU.
Here is an example for the countries array:
  {
    name: "Belarus",
    dialCode: "+375",
    code: "BY"
  },
  {
    name: "Belgium",
    dialCode: "+32",
    code: "BE",
    EU: true,
    vatPrefix: "BE",
    regex: `0[0-9]{9}`
  },
...

I have my countries and tax number fields, but so far I can't manage to differentiate if a country is from EU or not.
Here is my validation code (not working):
 return Yup.string().when("???", {
    is: "EU",
    then: schema.test("regexPattern", t("validation.invalidValue"), (value: unknown) =>
    regexPattern.test(String(value))
  ),
    otherwise: Yup.string()
    .trim()
    .min(5, t("validation.minLength", { minLength: 5}))
    .required(t("validation.required"));
  });

I was trying to get the countryCode from the countryField and with that make the query to the countries array and if it has a regex then pass the variable to the regex validation. But I have no idea how to do it.
This is really similar to this question but our approaches are totally different since I also need to handle countries outside EU.

A: Ok, so apparently I was missing some possible functions that work here!
Here is my solution:
Yup.string().when("countryCode", {
    is: value => {
      const country = getCountryBy.code(value);
      return country?.EU;
    },
    then: validateAgainstRegexps(getEuCountries.regex()),
    otherwise: Yup.string()
      .trim()
      .min(genericTaxIdMinLength, t("validation.minLength", { minLength: genericTaxIdMinLength }))
      .required(t("validation.required"))
  });

All I needed to do was to add the logic within .when() as stated here: is: (value) => value == true which I thought it only admitted equalities (===).


text: Q: Apache Superset Dashboard Embedding Currently, Im working on a Vue.js project and I would like to embed some dashbords  in my application. Using the fetchGuestToken, my access is only given to the public user, Is there any way to access these dashboards with users created within superset with their List Roles and Row Level Security?


text:
Q: Service won't start I have a windows service (c++ that involves some C# code).
At production I have a machine with working service, and another that doesn't - immediately stops with this Error 1053..
I compared the procmon of both and saw that before I get the "Thread Exit" Operation it tries to "Load Image" - and the succuss machine - just keep starting...
100842  6:07:26.3394767 PM  MyService.exe   3848    Load Image  C:\Windows\winsxs\x86_microsoft.vc80.crt_1fc8b3b9a1e18e3b_8.0.50727.6195_none_d09154e044272b9a\msvcm80.dll  SUCCESS Image Base: 0x67a50000, Image Size: 0x7d000
100843  6:07:26.3399390 PM  MyService.exe   3848    Thread Exit     SUCCESS Thread ID: 4372, User Time: 0.0000000, Kernel Time: 0.3281250

Do you have an idea how to work it from here?

A: What did solved my issue was reinstall the patch of the subsystem...


text:
Q: Probability of occurring of two dependent events happening in sequence? There is a sports gun whose probability of working is $0.8$, i.e. it functions $80\%$ of the time I operate it. The probability that it hits the target accurately when i use it is $0.6$, i.e. $60\%$ of the time the gun hits the target accurately.  0.8 is the serviceability of the gun, the gun is serviceable for firing. 0.6 is the probability that i as a shooter hit the target accurately. i can hit target accurately only 6 out of 10 times.

*

*What is the probability that the gun when fired hits the target, on any given day if I use the gun ?

*I understood that functioning of gun and target accurately being hit are dependent events. Because if the gun is not functioning, I can't hit the target. Also I can't change the sequence of events. Due to these reasons I assumed they are dependent events, is my assumption correct? Are they dependent events?

*Is the data adequate to calculate probability of hitting the target if I pick up the gun any day?

A: Yes, the event "The gun shoots and hits the target" and "The gun is working, i.e. it shoots" are dependent. We can actually prove that this is the case if we can show that
$$\mathbb{P}(\text{ The gun shoots and hits the target}) \neq \mathbb{P}(\text{ The gun shoots and hits the target} \ | \ \text{ The gun is working }).$$
In fact we know that the second probability is $0.6$ by the assumptions (as clarified in the comments). The first probability can be rewritten as
$$\mathbb{P}(\text{ The gun shoots and hits the target} \ | \ \text{ The gun is working }) \mathbb{P}(\text{ The gun is working }),$$
since on the envent "The gun is not working" the probability of hitting the target is zero. You know both terms in this product, so a multiplication will answer everything.


text: Q: Are different Jupyter Notebooks automatically run in parallel? Does anyone know whether, when I run multiple Jupyter Notebooks (different files) simultaneously, they are automatically distributed over multiple cores? Or are they by default threaded on a single core? I am not explicitly using a multiprocessing package of any kind and not looking for a way to implement parallel computing. I'm just curious whether the computer automatically sends the calculations to different cores.


text:
Q: Safari CSS Animation Multiple Translates Not Working I have the following code that works in all other browsers except Safari:
.background {
  width: 300px;
  height: 100px;
  background: cyan;

  transform: translateX(-42px) translateY(166px) skew(25deg);
  animation: background-anim 5s 0s step-end 2;
}

@keyframes background-anim {
  0%, 49%, 100% {
    transform: translateY(0) skew(25deg);
  }

  50%, 99% {
    transform: translateX(-42px) translateY(166px) skew(25deg);
  }
}

The translateY() works but the translateX() does not during the animation. However it works outside of the animation (after it finishes).
CodePen example.

A: I fixed it by adding a translateX(0) to the first keyframe:
@keyframes background-anim {
  0%, 49%, 100% {
    transform: translateX(0) translateY(0) skew(25deg);
  }

  50%, 99% {
    transform: translateX(-42px) translateY(166px) skew(25deg);
  }
}

Another way was to use translate(0,0) and translate(-42px, 166px) instead of splitting out into X and Y.


text:
Q: Trailing icon property of ListTile removed when I tapped on bottomnavigationbar 'favorite' I have a GIF to describe below.
And how to when I tapped on trailing icon at the music_page.dart, then the music_favorite_page.dart will build value that.
This main.dart
import 'package:abc/pages/music_page.dart';
import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Material App',
      home: HomePage(),
    );
  }
}

class HomePage extends StatefulWidget {
  HomePage({Key key}) : super(key: key);

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

class _HomePageState extends State<HomePage> {
  int _currentIndex = 0;
  final List<Widget> _children = [MusicPage(), MusicFavoritePage()];

  void _onTappedBar(int index) {
    setState(() {
      _currentIndex = index;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      // appBar: AppBar(
      //   title: Text("App"),
      // ),
      body: _children[_currentIndex],
      bottomNavigationBar: BottomNavigationBar(
        onTap: _onTappedBar,
        currentIndex: _currentIndex,
        items: [
          BottomNavigationBarItem(
            icon: Icon(Icons.library_music),
            title: Text("Music"),
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.favorite),
            title: Text("Favorite"),
          ),
        ],
      ),
    );
  }
}

This music_page.dart
import 'package:flutter/material.dart';

class MusicPage extends StatefulWidget {
  MusicPage({Key key}) : super(key: key);

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

class _MusicPageState extends State<MusicPage>
    with AutomaticKeepAliveClientMixin {
  final _karaokeList = Karaoke.getAll();
  final _savedKaraoke = <Karaoke>{};

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Scaffold(
      appBar: AppBar(
        title: Text("Music"),
      ),
      body: _buildListViewKaraokeList(),
    );
  }

  Widget _buildListViewKaraokeList() {
    return ListView.builder(
      itemCount: _karaokeList.length,
      itemBuilder: (context, index) =>
          _buildListTileKaraokeList(_karaokeList[index]),
    );
  }

  Widget _buildListTileKaraokeList(Karaoke karaoke) {
    final _isTapped = _savedKaraoke.contains(karaoke);

    return ListTile(
      leading: Text(karaoke.maBaiHat),
      title: Text(karaoke.tenBaiHat),
      subtitle: Text(karaoke.tenCaSi),
      trailing: Icon(
        _isTapped ? Icons.favorite : Icons.favorite_border,
        color: _isTapped ? Colors.red : null,
      ),
      onTap: () {
        setState(() {
          if (_isTapped) {
            _savedKaraoke.remove(karaoke);
          } else {
            _savedKaraoke.add(karaoke);
          }
        });
      },
    );
  }

  @override
  bool get wantKeepAlive => true;
}

This music_favorite_page.dart

class MusicFavoritePage extends StatefulWidget {
  MusicFavoritePage({Key key}) : super(key: key);

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

class _MusicFavoritePageState extends State<MusicFavoritePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Music Favorite"),
      ),
      body: Center(
        child: Text("Music Favorite Page"),
      ),
    );
  }
}

GIF:

A: You can copy paste run full code below
You can use PageView, you can see working demo below
code snippet
void _onTappedBar(int index) {
    print("onItemSelected");
    setState(() => _currentIndex = index);
    _pageController.jumpToPage(index);
  }
...
body: SizedBox.expand(
        child: PageView(
          controller: _pageController,
          children: _children,
          onPageChanged: (int index) {
            print("onPageChanged");
            setState(() {
              _currentIndex = index;
            });
          },
        ),

working demo

full code
import 'package:flutter/material.dart';

class Karaoke {
  String maBaiHat;
  String tenBaiHat;
  String tenCaSi;

  Karaoke({this.maBaiHat, this.tenBaiHat, this.tenCaSi});
}

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: HomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class HomePage extends StatefulWidget {
  HomePage({Key key, this.title}) : super(key: key);

  final String title;

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

class _HomePageState extends State<HomePage> {
  int _currentIndex = 0;
  PageController _pageController = PageController();
  final List<Widget> _children = [MusicPage(), MusicFavoritePage()];

  void _onTappedBar(int index) {
    print("onItemSelected");
    setState(() => _currentIndex = index);
    _pageController.jumpToPage(index);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SizedBox.expand(
        child: PageView(
          controller: _pageController,
          children: _children,
          onPageChanged: (int index) {
            print("onPageChanged");
            setState(() {
              _currentIndex = index;
            });
          },
        ),
      ),
      bottomNavigationBar: BottomNavigationBar(
        currentIndex: _currentIndex,
        selectedItemColor: Colors.amber[800],
        unselectedItemColor: Colors.blue,
        onTap: _onTappedBar,
        items: const <BottomNavigationBarItem>[
          BottomNavigationBarItem(
            icon: Icon(Icons.library_music),
            title: Text("Music"),
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.favorite),
            title: Text("Favorite"),
          ),
        ],
      ),
    );
  }
}

class MusicPage extends StatefulWidget {
  MusicPage({Key key}) : super(key: key);

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

class _MusicPageState extends State<MusicPage>
    with AutomaticKeepAliveClientMixin {
  final _karaokeList = [
    Karaoke(maBaiHat: "a", tenBaiHat: "a1", tenCaSi: "a2"),
    Karaoke(maBaiHat: "b", tenBaiHat: "b1", tenCaSi: "b2"),
    Karaoke(maBaiHat: "c", tenBaiHat: "c1", tenCaSi: "c2")
  ]; //Karaoke.getAll();
  final _savedKaraoke = <Karaoke>{};

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Scaffold(
      appBar: AppBar(
        title: Text("Music"),
      ),
      body: _buildListViewKaraokeList(),
    );
  }

  Widget _buildListViewKaraokeList() {
    return ListView.builder(
      itemCount: _karaokeList.length,
      itemBuilder: (context, index) =>
          _buildListTileKaraokeList(_karaokeList[index]),
    );
  }

  Widget _buildListTileKaraokeList(Karaoke karaoke) {
    final _isTapped = _savedKaraoke.contains(karaoke);

    return ListTile(
      leading: Text(karaoke.maBaiHat),
      title: Text(karaoke.tenBaiHat),
      subtitle: Text(karaoke.tenCaSi),
      trailing: Icon(
        _isTapped ? Icons.favorite : Icons.favorite_border,
        color: _isTapped ? Colors.red : null,
      ),
      onTap: () {
        setState(() {
          if (_isTapped) {
            _savedKaraoke.remove(karaoke);
          } else {
            _savedKaraoke.add(karaoke);
          }
        });
      },
    );
  }

  @override
  bool get wantKeepAlive => true;
}

class MusicFavoritePage extends StatefulWidget {
  MusicFavoritePage({Key key}) : super(key: key);

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

class _MusicFavoritePageState extends State<MusicFavoritePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Music Favorite"),
      ),
      body: Center(
        child: Text("Music Favorite Page"),
      ),
    );
  }
}

A: Right now, whenever you visit the MusicPage, _savedKaraoke list is setting a null array like {} in here:
    final _savedKaraoke = <Karaoke>{};

For a very simple solution, you can use app state provider to get or set the _savedKaraoke list.


text:
Q: The parameter can't have a value of "null" - error
I don't know how to resolve this error, i try to set the parameter how nnull parameter with 'String? assetImage' but continue to retrivies an error, how can i resolve this ?

A: remove the @ in every @required
MyCard({required this.assetImage, ...});

more info


text:
Q: How to access Backbone.Model methods from Marionette.js ItemView template? I'm trying to access a model's method from within an .eco template using backbone/marionette.js. I have an Expense model with a day() method which, using moment.js, returns '13th'; for example:
class Expense extends Backbone.Model
  day: ->
    moment.get('date').format('Do')

I can create a new Expense as follows, and call the day() method:
coffee = new Expense({name: "Coffee", amount: 2.50, date: "2014-01-13T13:50:00Z"})
coffee.day() # 13th

However, trying to access day() from within the following view and template is causing me some problems:
class ExpenseView extends Marionette.ItemView
  template: "views/_expense"

# views/_expense.jst.eco

<%= @name %>

<%= @day() %>

I understand why it isn't working...the ItemView calls serializeData which returns @model.toJSON()... therefore, the Expense's day() method isn't accessible. Is there an established pattern in the backbone/marionette community that makes model methods available to templates?
So far, I've done the following to make it work:
class ExpenseView extends Marionette.ItemView
  template: "views/_expense"

  serializeData: ->
    _.extend(@model.toJSON(), model: @model)

  templateHelpers:
    day: ->
      @model.day()

But I'm unsure whether this is the best way to go about the problem? Thanks!

A: You can always add it to templateHelpers or serializeData - but what you're really asking about is a virtual attribute - one that can be part of every template, an attribute that is used solely as part of a ViewModel.  In this way we can also disable it from syncing to the server on sync events such as save()
There are several plugins out there that do this, my personal favorite to use is Backbone Mutators - https://github.com/asciidisco/Backbone.Mutators
Others like Backbone Computed Fields - https://github.com/alexanderbeletsky/backbone-computedfields give you Ember like computed properties.
With Backbone Mutators you would write your mutators in the Backbone Model.
class Model extends Backbone.Model
  mutators:
    day: ->
      moment.get('date').format('Do')

Alternatively to prevent the 'day' attribute from syncing to the backend...
class Model extends Backbone.Model
  mutators:
    day:
      get: -> moment.get('date').format('Do')
      transient: true

The day attribute will be present in all toJSON() calls now.

A: Why don't you just add it to serializeData ? (Can't remember Coffee syntax...)
serializeData: function(){
    var data = _.clone(this.model.attributes);
    data.day = this.model.day();
    return data;
}


text:
Q: EF Core 2.0 Trouble 'Cascading' Inserts for Related Entities When Updating Principle Entity ASP.NET Core 2 Web application using a REST API.  Currently using sqlite3 for development database.   (Also tried migrating to SQL Server and got same results as below).
I'm sending an entity to web client, the client makes changes to the entity that involve adding a new related entity and then that updated principle entity gets sent back as json in body of PUT a request.
I was hoping the new related entity would get created automatically, but this is not  happening.  The simple properties on the principle entity are updated properly, but not reference properties.  I'm not getting any exceptions or anything - it just seems to be ignoring the reference properties.
Simplified Classes (I removed other properties that shouldn't affect the relationship):
public partial class DashboardItem {
    public int Id { get; set; }
    public int? DataObjectId { get; set; }
    public DataObject DataObject { get; set; }

}

public partial class DataObject {
    public int Id { get; set; }
}

Portion of DbContext Fluent API for associated property:
        modelBuilder.Entity<DashboardItem>(entity => {
            entity.HasOne(p => p.DataObject)
            .WithMany()
            .HasForeignKey(p => p.DataObjectId);
        });

Controller Method for PUT:
    [HttpPut("{id}")]
    public async Task<IActionResult> PutDashboardItem([FromRoute] int id, [FromBody] DashboardItem entity)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        if (id != entity.Id)
        {
            return BadRequest();
        }

        _context.Entry(entity).State = EntityState.Modified;

        try{
            await _context.SaveChangesAsync();
        }catch (DbUpdateConcurrencyException)
        {
            if (!DashboardItemExists(id)){
                return NotFound();
            }else {
                throw;
            }
        }
        return NoContent();
    }

The simplified json (without all the other properties) would look like this (I've tried different variations of have the foreign key "DataObjectId" removed from the json, set to null, or set to zero in case that might be interferring.):
{
  Id:1,
  DataObjectId:null,
  DataObject:{
    Id: 0
  }
}

When debugging in the controller action method, the  existing "DashboardItem" principle entity created from the request body has the reference property "DataObject" populated before getting added to the DbContext, but the new DataObject never gets created in the database.  There is only a SQL UPDATE statement issued for DashboardItem and no INSERT for DataObject.
I've also tried making the controller method synchronous instead of async, using DbContext.SaveChanges() instead of .SaveChangesAsync(), since there used to be a problem with that in earlier versions of EF Core related to creating related entities, even though I'm using 2.0 which already has a fix for that. Same result.
This EFCore Doc sounds like it should just work out of the box.
This has worked for me in a prior project.  What am I missing here?

A: Basically, my mistake was in assuming the process of updating data was much simpler than it actually is when sending the updated data from a client in a web application.
After digging a lot more, it seems that the following line in my controller method for handling the PUT request is the problem:
_context.Entry(entity).State = EntityState.Modified;

Setting the entity entry state to Modified in this way results in Entity Framework Core ignoring the reference properties for the related objects - the SQL UPDATE generated will only address the columns in the entity table.
This simple summary eventually got me started down the right path.

Summarizing what I've now learned:
This controller method is dealing with a 'detached' entity that was edited and sent back from the client.  The DbContext is not yet tracking this entity since I get a new instance of the context with each http request (hence the entity is considered 'detached').  Because it is not being tracked yet, when it is added to the DbContext, the context needs to be told whether this entity has been changed and how to treat it.
There are several ways to tell the DbContext how to handle the detached entity.  Among those:
(1) setting the entity state to EntityState.Modified will result in ALL properties being included in the SQL update (whether they've actually changed or not), EXCEPT for the reference properties for related entities:
      _context.Entry(entity).State = EntityState.Modified;

(2) adding the entity with a call to DbContext.Update will do the same as above, but will include the reference properties, also include ALL properties on those entities in the update, whether they've changed or not:
       _context.Update(entity)

Approach #2 got things working for me, where I was just trying to get the new related child entity to be created in the Update to its parent.
Beyond that, DbContext.Attach() and DbContext.TrackGraph sound like thy provide more find-grained control over specifying what specific properties or related entities to include in the update.


text:
Q: Php script not finding include file I am running a php command (edited) from the command line that runs a php file on the web server.
In that file I need to include a file that is one level up from its location.
I have tried
include(../the_file_in the parent.php)

and every other suggestion I could find here for the last two days.
I keep getting the same error in the CLI:
PHP Warning:  require_once($_SERVER[DOCUMENT_ROOT]/html/wp-load.php): failed to open stream: No su
ch file or directory in /var/www/html/wp-admin/email_processor.php on line 16
PHP Fatal error:  require_once(): Failed opening required '$_SERVER[DOCUMENT_ROOT]/html/wp-load.ph
p' (include_path='.:') in /var/www/html/wp-admin/email_processor.php on line 16

As with all thing computing, I have a sneaking suspicion this is ridiculously simple...that's why it is taking so long to get it sorted.
Any assistance would be greatly appreciated.

A: This might be useful:
<?php
  include $_SERVER['DOCUMENT_ROOT']."/parentfilepath/filename.php";
?>

or
include __DIR__ . '/../parentfile.php';


text:
Q: Default property/method in module In Visual Basic 6, it is possible to define a method/property as "default". When this is applied to a class, and a class instance is used, certain assignments use the default property/method defined on that class implicitly.
However, it is also possible to apply default to a property/method that is housed in a module. What would this achieve? How would it be possible to use an implicit method/property call that is housed in a module?

A: Like you, I don't see how it can have any effect. You can also set methods in modules as AboutBox or Refresh, which surely can't mean anything? I think it's probably an oversight that you can set the procedure ID (DispID) for methods and properties in standard BAS modules.

A: No its not possible.  The Default property is achieved by using a DispID of 0 on a member of an interface.  Since Modules do not implement interfaces its not possible to indicate that function in a module is a "Default".
Why would you want to do this in a module anyway?

A: You can set a default property/method in a user-defiend class, but not for the existing classes for the reasons stated above.
Setting a default property in a user-defined class


text:
Q: Past vs Past Perfect While writing a paper for my English class, I couldn't decided whether past or past perfect tense was needed. It's basically about how a guy whose house is destroyed because the government wants to build a freeway over it:

Walking towards where my house was built, I see that only my mailbox had survived the wreckage, while I try to salvage all I could. Looking through my mail, I see a letter from the government telling me kindly that they are going to build a freeway where my house had once stood. Attached is a sum of money reimbursing my devastating loss, but it could not account for the number of generations who had once lived there.

Basically, I can't decide if there following are correct. It's supposed to be in present tense. (The guy is currently standing at the wreckage.)
1) "had survived"
2) try to salvage all I "could"
3) where my house "had once stood"
4) but it "could" not account
5) number of generations who "had once lived" there
Please provide some sort of explanation. Thanks!

A: You say that you want to cast your narrative in the present tense.
Consequently, these actions and perceptions —your guy's— occur in the "narrative present", and so should be in the present tense:

I see ... I try ... I can ... I see ... they are going to build* [because you are reading this in the narrative present] ... it can

This, since it started in the past but continues into the narrative present, could be in either the present or present perfect:

house survives or has survived ...

The rest are events or states which occurred before the narrative present and therefore should be in simple past:

house was built ... house stood ... generations lived

Put them together:

Walking towards where my house was built, I see that only my mailbox has survived the wreckage, while I try to salvage all I can. Looking through my mail, I see a letter from the government telling me kindly that they are going to build a freeway where my house once stood. Attached is a sum of money reimbursing my devastating loss, but it cannot account for the number of generations who once lived there.

You use past perfect only if you are locating an action at some time before a specific event in the past—for instance, if you cast your narrative in the past, the pasts in the last version would become past perfects:

Walking towards where my house had been built, I saw that only my mailbox had survived the wreckage, while I tried to salvage all I could. Looking through my mail, I saw a letter from the government telling me kindly that they were going to build a freeway where my house had† once stood. Attached was a sum of money reimbursing my devastating loss, but it could not account for the number of generations who had† once lived there.

*Yes, I know this is called future tense — but it's formed here with a present-tense auxiliary. I would call the auxiliary's tense non-past and the construction a future mode, but I'm eccentric.
†Actually, nobody will object if you cast these in the simple past, since the adverb once effectively locates the standing before the narrative past.


text:
Q: С++ - Вызвано исключение по адресу 0x00502974 После вписывания массива пишет - Вызвано исключение по адресу 0x00502974 в Project2.exe: 0xC0000005: нарушение прав доступа при чтении по адресу 0xFDFDFE01.
Код:
#include <iostream>
using namespace std;
int main() {
    int n,b,c,d,e;
    cin >> n;
    int** a = new int* [n];
    for (int i = 0; i < n; i++)
        a[i] = new int[n];
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++)
            cin >> a[i][j];
    }
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            cout.width(4);
            cout << a[i][j];
        }
        cout << endl;
    }
    e = n - 1;
    d = 1;
    c = n-1;
    b = n;
    for (int i =0; i < n-1; i++) {
        for (int j = d; j < n; j++) {
            if (a[i][j] == a[b][c]) c -= 1;
            else { cout << "ne simetr" << endl;
            system("pause");
            return 0;
            }
        }
        d += 1;
        e--;
        c = e;
        b -= 1;
    }
    cout << "simetr" << endl;
    system("pause");
    return 0;
}

Ошибка в этой части:
if (a[i][j] == a[b][c]) c -= 1;

A: if (a[i][j] == a[b][c])

при этом b = n и размер массива n x n, т.е. [0..n-1][0..n-1]
а теперь угадайте куда происходит обращение по адресу [n][n-1] - в массив или наружу? :)


text:
Q: Any rails server doesn't start Getting the same error every time when trying to start ANY project on rails 4 or 5 using ruby 2.2.5 and 2.3.1 even on the fresh projects.
Tried to reinstall rbenv but didn't help. Anybody got a solution?
  fedyay@fedyay-note:~/shit$ rails s
  => Booting WEBrick
  => Rails 4.2.3 application starting in development on http://localhost:3000
  => Run `rails server -h` for more startup options
  => Ctrl-C to shutdown server
  Exiting
  /home/fedyay/.rbenv/versions/2.2.5/lib/ruby/2.2.0/psych.rb:370:in `parse': (<unknown>): did not find expected alphabetic or numeric character while scanning an alias at line 22 column 20 (Psych::SyntaxError)
    from /home/fedyay/.rbenv/versions/2.2.5/lib/ruby/2.2.0/psych.rb:370:in `parse_stream'
    from /home/fedyay/.rbenv/versions/2.2.5/lib/ruby/2.2.0/psych.rb:318:in `parse'
    from /home/fedyay/.rbenv/versions/2.2.5/lib/ruby/2.2.0/psych.rb:245:in `load'
    from /home/fedyay/.rbenv/versions/2.2.5/lib/ruby/gems/2.2.0/gems/railties-4.2.3/lib/rails/application.rb:391:in `secrets'
    from /home/fedyay/.rbenv/versions/2.2.5/lib/ruby/gems/2.2.0/gems/railties-4.2.3/lib/rails/application.rb:178:in `key_generator'
    from /home/fedyay/.rbenv/versions/2.2.5/lib/ruby/gems/2.2.0/gems/railties-4.2.3/lib/rails/application.rb:206:in `message_verifier'
    from /home/fedyay/.rbenv/versions/2.2.5/lib/ruby/gems/2.2.0/gems/globalid-0.3.7/lib/global_id/railtie.rb:25:in `block (2 levels) in <class:Railtie>'
    from /home/fedyay/.rbenv/versions/2.2.5/lib/ruby/gems/2.2.0/gems/activesupport-4.2.3/lib/active_support/lazy_load_hooks.rb:36:in `call'
    from /home/fedyay/.rbenv/versions/2.2.5/lib/ruby/gems/2.2.0/gems/activesupport-4.2.3/lib/active_support/lazy_load_hooks.rb:36:in `execute_hook'
    from /home/fedyay/.rbenv/versions/2.2.5/lib/ruby/gems/2.2.0/gems/activesupport-4.2.3/lib/active_support/lazy_load_hooks.rb:45:in `block in run_load_hooks'
    from /home/fedyay/.rbenv/versions/2.2.5/lib/ruby/gems/2.2.0/gems/activesupport-4.2.3/lib/active_support/lazy_load_hooks.rb:44:in `each'
    from /home/fedyay/.rbenv/versions/2.2.5/lib/ruby/gems/2.2.0/gems/activesupport-4.2.3/lib/active_support/lazy_load_hooks.rb:44:in `run_load_hooks'
    from /home/fedyay/.rbenv/versions/2.2.5/lib/ruby/gems/2.2.0/gems/railties-4.2.3/lib/rails/application/finisher.rb:62:in `block in <module:Finisher>'
    from /home/fedyay/.rbenv/versions/2.2.5/lib/ruby/gems/2.2.0/gems/railties-4.2.3/lib/rails/initializable.rb:30:in `instance_exec'
    from /home/fedyay/.rbenv/versions/2.2.5/lib/ruby/gems/2.2.0/gems/railties-4.2.3/lib/rails/initializable.rb:30:in `run'
    from /home/fedyay/.rbenv/versions/2.2.5/lib/ruby/gems/2.2.0/gems/railties-4.2.3/lib/rails/initializable.rb:55:in `block in run_initializers'
    from /home/fedyay/.rbenv/versions/2.2.5/lib/ruby/2.2.0/tsort.rb:226:in `block in tsort_each'
    from /home/fedyay/.rbenv/versions/2.2.5/lib/ruby/2.2.0/tsort.rb:348:in `block (2 levels) in each_strongly_connected_component'
    from /home/fedyay/.rbenv/versions/2.2.5/lib/ruby/2.2.0/tsort.rb:429:in `each_strongly_connected_component_from'
    from /home/fedyay/.rbenv/versions/2.2.5/lib/ruby/2.2.0/tsort.rb:347:in `block in each_strongly_connected_component'
    from /home/fedyay/.rbenv/versions/2.2.5/lib/ruby/2.2.0/tsort.rb:345:in `each'
    from /home/fedyay/.rbenv/versions/2.2.5/lib/ruby/2.2.0/tsort.rb:345:in `call'
    from /home/fedyay/.rbenv/versions/2.2.5/lib/ruby/2.2.0/tsort.rb:345:in `each_strongly_connected_component'
    from /home/fedyay/.rbenv/versions/2.2.5/lib/ruby/2.2.0/tsort.rb:224:in `tsort_each'
    from /home/fedyay/.rbenv/versions/2.2.5/lib/ruby/2.2.0/tsort.rb:203:in `tsort_each'
    from /home/fedyay/.rbenv/versions/2.2.5/lib/ruby/gems/2.2.0/gems/railties-4.2.3/lib/rails/initializable.rb:54:in `run_initializers'
    from /home/fedyay/.rbenv/versions/2.2.5/lib/ruby/gems/2.2.0/gems/railties-4.2.3/lib/rails/application.rb:352:in `initialize!'
    from /home/fedyay/shit/config/environment.rb:5:in `<top (required)>'
    from /home/fedyay/shit/config.ru:3:in `require'
    from /home/fedyay/shit/config.ru:3:in `block in <main>'
    from /home/fedyay/.rbenv/versions/2.2.5/lib/ruby/gems/2.2.0/gems/rack-1.6.4/lib/rack/builder.rb:55:in `instance_eval'
    from /home/fedyay/.rbenv/versions/2.2.5/lib/ruby/gems/2.2.0/gems/rack-1.6.4/lib/rack/builder.rb:55:in `initialize'
    from /home/fedyay/shit/config.ru:in `new'
    from /home/fedyay/shit/config.ru:in `<main>'
    from /home/fedyay/.rbenv/versions/2.2.5/lib/ruby/gems/2.2.0/gems/rack-1.6.4/lib/rack/builder.rb:49:in `eval'
    from /home/fedyay/.rbenv/versions/2.2.5/lib/ruby/gems/2.2.0/gems/rack-1.6.4/lib/rack/builder.rb:49:in `new_from_string'
    from /home/fedyay/.rbenv/versions/2.2.5/lib/ruby/gems/2.2.0/gems/rack-1.6.4/lib/rack/builder.rb:40:in `parse_file'
    from /home/fedyay/.rbenv/versions/2.2.5/lib/ruby/gems/2.2.0/gems/rack-1.6.4/lib/rack/server.rb:299:in `build_app_and_options_from_config'
    from /home/fedyay/.rbenv/versions/2.2.5/lib/ruby/gems/2.2.0/gems/rack-1.6.4/lib/rack/server.rb:208:in `app'
    from /home/fedyay/.rbenv/versions/2.2.5/lib/ruby/gems/2.2.0/gems/railties-4.2.3/lib/rails/commands/server.rb:61:in `app'
    from /home/fedyay/.rbenv/versions/2.2.5/lib/ruby/gems/2.2.0/gems/rack-1.6.4/lib/rack/server.rb:336:in `wrapped_app'
    from /home/fedyay/.rbenv/versions/2.2.5/lib/ruby/gems/2.2.0/gems/railties-4.2.3/lib/rails/commands/server.rb:139:in `log_to_stdout'
    from /home/fedyay/.rbenv/versions/2.2.5/lib/ruby/gems/2.2.0/gems/railties-4.2.3/lib/rails/commands/server.rb:78:in `start'
    from /home/fedyay/.rbenv/versions/2.2.5/lib/ruby/gems/2.2.0/gems/railties-4.2.3/lib/rails/commands/commands_tasks.rb:80:in `block in server'
    from /home/fedyay/.rbenv/versions/2.2.5/lib/ruby/gems/2.2.0/gems/railties-4.2.3/lib/rails/commands/commands_tasks.rb:75:in `tap'
    from /home/fedyay/.rbenv/versions/2.2.5/lib/ruby/gems/2.2.0/gems/railties-4.2.3/lib/rails/commands/commands_tasks.rb:75:in `server'
    from /home/fedyay/.rbenv/versions/2.2.5/lib/ruby/gems/2.2.0/gems/railties-4.2.3/lib/rails/commands/commands_tasks.rb:39:in `run_command!'
    from /home/fedyay/.rbenv/versions/2.2.5/lib/ruby/gems/2.2.0/gems/railties-4.2.3/lib/rails/commands.rb:17:in `<top (required)>'
    from /home/fedyay/shit/bin/rails:9:in `require'
    from /home/fedyay/shit/bin/rails:9:in `<top (required)>'
    from /home/fedyay/.rbenv/versions/2.2.5/lib/ruby/gems/2.2.0/gems/spring-2.0.0/lib/spring/client/rails.rb:28:in `load'
    from /home/fedyay/.rbenv/versions/2.2.5/lib/ruby/gems/2.2.0/gems/spring-2.0.0/lib/spring/client/rails.rb:28:in `call'
    from /home/fedyay/.rbenv/versions/2.2.5/lib/ruby/gems/2.2.0/gems/spring-2.0.0/lib/spring/client/command.rb:7:in `call'
    from /home/fedyay/.rbenv/versions/2.2.5/lib/ruby/gems/2.2.0/gems/spring-2.0.0/lib/spring/client.rb:30:in `run'
    from /home/fedyay/.rbenv/versions/2.2.5/lib/ruby/gems/2.2.0/gems/spring-2.0.0/bin/spring:49:in `<top (required)>'
    from /home/fedyay/.rbenv/versions/2.2.5/lib/ruby/gems/2.2.0/gems/spring-2.0.0/lib/spring/binstub.rb:31:in `load'
    from /home/fedyay/.rbenv/versions/2.2.5/lib/ruby/gems/2.2.0/gems/spring-2.0.0/lib/spring/binstub.rb:31:in `<top (required)>'
    from /home/fedyay/.rbenv/versions/2.2.5/lib/ruby/2.2.0/rubygems/core_ext/kernel_require.rb:69:in `require'
    from /home/fedyay/.rbenv/versions/2.2.5/lib/ruby/2.2.0/rubygems/core_ext/kernel_require.rb:69:in `require'
    from /home/fedyay/shit/bin/spring:14:in `<top (required)>'
    from bin/rails:3:in `load'
    from bin/rails:3:in `<main>'

A: Seems like you have tabs in your YAML file instead of spaces.
Change them to spaces from your editor settings
Solution for similar question is given here

A: So not realy sure what's going on but it started OK with 'sudo rails s'.


text:
Q: Get list of processes running on Kubernetes nodes I have written a code in rust, which uses sysinfo crate and lists all the processes running on a machine.
The code works fine on my local Ubuntu.
When I run this code on Kubernetes, as a deployment, the code gives me list of processes running on the particular pod, but what I really expect is the list of processes running on that node !
I tried using DaemonSet instead of a Deployment, that created 1 pod per node, but still it does not show processes running on node. How should I configure this ?
How should I approach to do so ? Is that even possible ?
Thanks in advance !


text:
Q: Для чего используется символ ` (обратная кавычка, backquote, backtick)? Для чего используют символы `?
Например:
python3.4 `which ptpython`

A: Обратные кавычки используются в баше для записи какой-то выполнимой команды, результат работы которой будет использован в скрипте.
Например попробуйте: echo `whoami` и echo 'whoami'

Первый вариант выполнит команду whoami и распечатает ее результат (имя текущего пользователя), второй вариант просто распечатает строку "whoami".

A: это несколько устаревшая форма записи для вызова вложенной оболочки.
уже в posix version 2 (1997) присутствует и более удобная (и рекомендуемая стандартом posix) форма записи: $(command).
удобство можно увидеть наглядно при вложении нескольких вызовов один внутрь другого:
$ echo `echo \`echo \\\`echo 1\\\` 2\` 3` 4
1 2 3 4
$ echo $(echo $(echo $(echo 1) 2) 3) 4
1 2 3 4

смысл использования: во время интерпретации команды оболочка, встретив конструкцию $(command) (или `command`), запускает новый процесс оболочки, в котором выполняется указанная команда, а всё, что возвратит команда в stdout, будет подставлено вместо этой конструкции (то, что команда возвратит в stderr, добавится к stderr основного процесса оболочки).

Например: python3.4 `which ptpython`

в данном случае сначала будет выполнена команда which ptpython, которая вёрнет (в stdout) полный путь к программе ptpython. если, конечно, такая программа присутствует в вашей системе в каком-либо из каталогов, упомянутых в переменной окружения $PATH. если отсутствует — будет возвращена пустая строка.
затем результат (полный путь либо пустая строка) будет передана программе python3.4 в качестве первого аргумента. если, конечно, такая программа присутствует в вашей системе в каком-либо из каталогов, упомянутых в переменной окружения $PATH. если отсутствует — вы получите сообщение об ошибке: command not found.

посмотреть текущее значение переменной окружения, например, $PATH, можно так:
$ echo $PATH


text:
Q: CSS3 not working on visual studio 2010 I have a solution built in Visual Studio 2008 and wish to add some new features of CSS3, hence I converted the solution to Visual Studio 2010.
Even after its successful conversion I am still not able to see the CSS3 features. I need to use border-radius property of CSS3.
Can I use it on the solution converted from Visual Studio 2008 to Visual Studio 2010?
Please help.

A: Maybe the visual studio doesn't auto-complete the code but the css3 conditions will work on any browser compatible (Chrome, FF, EI9, Opera, Safari),since it's all CSS and not compiled by Visual Studio.
Give it a try on one of those browsers (:

A: I believe there is an update coming that will address that issue, but you should be able to view any CSS3 change when running the site.


text:
Q: Error with member function template I am getting compilation error in below code.
class A
{
public:
    A()
    {
    }
    ~A()
    {
    }
 void func()
 {
     cout <<"Ha ha ha \n";
 }

};

class C
{
public:
    C()
    {
    }
    ~C()
    {
    }
template<typename type> func()
{
    type t;
    t.func();
}
void callme()
{
    func<A>();
}
};

A: The definition of func<T>() doesn't specify its return type, which is invalid in C++.
It should be:
template<typename type> void func()
{
    type t;
    t.func();
}

A: VC6 doesn't support member function templates. You actually have several solutions:
Move func() out of the class definition
template<typename type> void func()
{
    type t;
    t.func();
}

or rewrite callme()
void callme()
{
   A a;
   a.func();
}

or use class template
class C
{
public:
   template<class T> struct func
   {
      void operator()()
      {
         T t;
         t.func();
      }
   };

   void callme()
   {
      func<A>()();
   }
};


text:
Q: Python - single variable built string, from multiple other variables for SMTP me again, with another Python question.
I have a variable that is pieced together from a template in the config file.
This is the format that the config.ini file prepares the variable for sending:
template =#${var1} ${var2}: ${var3}

I set each of the variables in the python code as such:
templateArgs = dict()
    flight = a.flight or a.hex
    flight = flight.replace(" ", "")
    templateArgs['var1'] = aircraftdata.plane(a.hex)
    templateArgs['var2'] = aircraftdata.oper(a.hex)
    templateArgs['var3'] = "%.1f" % a.distance

It is prepared for Twitter, but Im removing that part, but sending the tweet content in the email for someone to review before posting.
This is where it is combined:
tweet = Template(parser.get('tweet', 'tweet_template')).substitute(templateArgs)

Its an SMTP email thats being sent with the data, but Ive got all that part sorted, Im just trying to make it look better. Its a hashtag string for twitter, but Im only using it in an email.
SMTP Email includes like this:

Tweet: """ + tweet + """

Id like, and this is the question for you, how ... in the ini file can I put in a line break so that when the email comes through each of the vars come through on a new line.
Its all working perfectly, its honestly just the new line I want to introduce. All the rest is working fine.
Im perplexed, and working from someone elses code, and a bit lost.
Sorry for the long question...just trying make sure you geniuses have enough info.
Any helpers?
Cheers
Simon


text:
Q: Child class method gets called ( instead of Base class method ) when upcasting the current instance Question: Why when the line int res = 1 + ((Mom) this).foo(); is executed, foo() of Child class gets called instead of Mom's? my reasoning was that - because we have (Mom) this) then we upcast the current instance, i.e. we change the static type of the current object to be of type Mom, and then we call foo() on it ( ((Mom) this).foo() ), hence foo() of Mom class would be called.
public static class Grandma {
    public int func() {return 1;}

    public int foo() {
        System.out.println(" Grandma foo ");
        return 1;
    }
}

public static class Mom extends Grandma {
    public int foo() {
        System.out.println(" Mom foo ");
        return 1 + super.foo();
    }
}

public static class Child extends Mom {
    public int func() {
        int res = 1 + ((Mom) this).foo();
        res += super.func(); // #
        return res;
    }

    public int foo() {
        System.out.println(" Child foo ");
        return 1 + super.foo();
    }
}

public static void main(String[] args) {
    Mom m = new Child();
    System.out.println(m.func());
}

Output:
Child foo
Mom foo
Grandma foo
5

I expected the output to be:
Mom foo
Grandma foo
5

`
Thanks in advance for any help!


text:
Q: Excel round by variable decimal places I have a huge list of values like:
0,1686448
216,4577890
0,00000453
0,0045663

and need to round them by the last two values not zero like:
0,17
216,46
0,0000045
0,0046

The first 2 numbers are not the problem by setting ROUND to 2 Decimals. But for the last 2 numbers like 0,00000453 I get 0.
Is there a formula to round anytime for the last two values not zero?

A: You could use:
=INT(A1)+ROUND(MOD(A1,1),INT(2-LOG(MOD(A1,1))))

A: Split into two criteria: if rounded to 2 d.p. = 0 then round to 2 s.f.
=LET(n, A1, sf, 2,  x, ROUND(n,2), IF(x=0, ROUND(n,sf-(1+INT(LOG10(ABS(n))))), x))

Uses the generic round to significant figures formula
ROUND(number,digits-(1+INT(LOG10(ABS(number)))))


text:
Q: Limit IPs that have access to PHP built-in server Is it possible to whitelist which IP's can access a built-in PHP server?
If opened with php -S 127.0.0.1:8082 it will only be visible to localhost. If done with php -S 192.168.0.10:8082 it will be visible to my entire local network. If done by php -S 0.0.0.0:8082 makes it available to whole internet.
Is it possible to limit the webserver availability to a specific set of IPs (just few IPs in my local network) without using apache, but only PHP's built in server?

A: It is just not possible to not give away that there is a PHP server running on a specific port by using PHP code, because before the script starts, a connection with the webserver is established to then process the request.


text:
Q: What's the best debugger for Akka development? I am using Idea 10 with the scala plugin. Evaluating variables and adding watches for scala and akka variables is impossible. Have to resort to println. Is this any better on Eclipse ?

A: I'm able to use breakpoints and inspect members in the current eclipse plugin but it doesn't manage to hook successfully to source when stepping through lines of code nor have I been able to get expression evaluation (watches) to work.  There may be a trick to that I've missed though.


text:
Q: Where should I put this custom data? My client needs to store food nutrient data in his site's database. I have food name, calories, protein, fat, carb, fiber and other data to store for many food items.
I'm a developer but new to WP. Where is the best place to store this information? A custom table, custom post, regular...
Thanks!

A: Supposing that each food item is treated as a post (perhaps even a custom post type), and the parameters (name/calories/etc.) are attributes of this post, you would do well to treat them as post meta fields.
Various means exist to grant end-users the ability to maintain custom fields; my preferred option is Developer's Custom Fields, but other solutions exist.  Regardless of the method used, the assumption is that for a given post certain meta fields have been populated and must be queried at runtime.
Within a loop (in particular, after invoking the_post()), and for a particular custom field (for illustration I will use "calories"), you would retrieve the value using get_post_meta() as shown below:
echo "Calories: " . get_post_meta(get_the_ID(), "calories", true);

Some assumptions are made here (that you're in a page/post loop, the data you are requesting has already been entered, and the name of your custom field is "calories").


text:
Q: Issue in vertical multi-level popup menu using jQuery I am trying to develop a vertical multi-level popup menu. I am unable to set the child's top against to its parent LI position. The approach I took was, I am calculating outerwidth of the UL tag and top of parent LI tag for the respective left and top positions of the child tag. But It doesn't seem to work well.
If I set left and top using CSS, the first level looks good, but for the rest of the levels the top is always set to 0.
_pm.child.show().css({left:left-2,top:top-1});

And if I use the position function, all the levels are shown as very closer to its parent.
_pm.child.show().position({left:left-2,top:top-1});

I am not getting what's gone wrong. Here is the fiddle.
Can somebody help me?

A: change the mouseout by mouseleave and it will work :)


text:
Q: Can I cancel the RxJs delay? I have a delay between some backend requests configured to 60 seconds using RxJs delayWhen.
What I want to achieve is the possibility to cancel the ongoing delay at some point.
Let's say 30 seconds of delay passed and user is making some action. I want to trigger a backend request immediately, without waiting for the next 30 seconds to pass.
Is there a way to do this using rxJs?

A: This is theoretical and there might be better ways to do it, but the takeUntil operator might be helpful.
What could happen is that you could have a button on your page. The button, when clicked, could emit an event buttonClicked$. The operation that you want to trigger may listen to that event:
yourDesiredEvent$.pipe(
  takeUntil(buttonClicked$),
  ...
)

And once your button is clicked (which would emit the buttonClicked$ event), it could cancel listening to the 30 seconds rule and just trigger the backend call.
If any information here is faulty let me know, so I remove it in the hopes to not be misleading. :)


text:
Q: Navigation Menu Will Not Stay Dropped Down on Hover hopefully someone here can help me out. I've created a drop down navigation menu and it works great except once you hover over the drop down items, anything past the 2nd one on the list, it won't stay hovered over & the menu closes up again. Here's the CSS:
 ******************************************************
 *Design the main ul
 ******************************************************
*/
 #ajonav ul {
 background-color: #a01013;
 padding: 0 0px;
 list-style: none;/*To remove the bullets*/
 position: relative;
 display: inline-block;
 }

/*
 ************************************
 *Design the main ul li
 ************************************
*/
 #ajonav ul li {
 float: left;
 border-right: 1px solid #a01013;
 }
 #ajonav ul li:hover {
 background-color: #a01013;
 }
 #ajonav ul li:nth-child(5){border-right:none; }

#ajonav ul li:hover a {
  color: #efb009;
 }

 #ajonav ul li a {
  color: #E4E4E4;
  text-decoration: none;
  padding: 10px 10px;
  display: block;
  font-family: sans-serif,serif;
 }

/*
 ************************************
 *(Dropdown) Design the sub ul li
 ************************************
*/
/*
 ******************************************************
 *Hide the submenu ul at start
 ******************************************************
*/
 #ajonav ul ul{visibility:hidden;display: none;}
/*
 ******************************************************
 *Show the submenu when li gets hover
 ******************************************************
*/
 #ajonav ul li:hover > ul {

visibility:visible;display: block;}
 #ajonav ul ul {
 position: absolute;
 background-color: #a01013;
 padding: 0px;
 }

 #ajonav ul ul li {
  position: relative;
  float: none;
  border-top: 1px solid #727272;
 }

 #ajonav ul ul li a {
  padding: 15px 20px;
  color: #fff;
 }

 #ajonav ul ul li a:hover {
color: #ffffff;
  background-color: #a01013;
 }

If anyone can help me out; I'd appreciate it.

A: Thank you trolle,

   I created a jsfiddle and it worked fine in there; don't get why it's not staying the same way in the actual website page.  Strange.

 Home

   Adopt

Petfinder Animal List

Petango Animal List

Adoption Information

Printable Adoption Application

Pet of the Week

 About Us

General Info

Our Staff

Statistics

Our Services

Pet Surrendering

Microchipping

Community Service Workers

Trap Rental

Humane Education

Found Animals

Lost Animals

 Get Involved

Donate

Happy Hour

Wish List

Volunteer

Events

Aluminum Can Drive

 Contact Us

Hours & Address

Phone/Email

******************************************************
 *Design the main ul
 ******************************************************
*/
 #ajonav ul {
 background-color: #a01013;
 padding: 0 0px;
 list-style: none;/*To remove the bullets*/
 position: relative;
 display: inline-block;
 }

/*
 ************************************
 *Design the main ul li
 ************************************
*/
 #ajonav ul li {
 float: left;
 border-right: 1px solid #a01013;
 }
 #ajonav ul li:hover {
 background-color: #a01013;
 }
 #ajonav ul li:nth-child(5){border-right:none; }

#ajonav ul li:hover a {
  color: #efb009;
 }

 #ajonav ul li a {
  color: #E4E4E4;
  text-decoration: none;
  padding: 10px 10px;
  display: block;
  font-family: sans-serif,serif;
 }

/*
 ************************************
 *(Dropdown) Design the sub ul li
 ************************************
*/
/*
 ******************************************************
 *Hide the submenu ul at start
 ******************************************************
*/
 #ajonav ul ul{visibility:hidden;display: none;}
/*
 ******************************************************
 *Show the submenu when li gets hover
 ******************************************************
*/
 #ajonav ul li:hover > ul {

visibility:visible;display: block;}
 #ajonav ul ul {
 position: absolute;
 background-color: #a01013;
 padding: 0px;
 }

 #ajonav ul ul li {
  position: relative;
  float: none;
  border-top: 1px solid #727272;
 }

 #ajonav ul ul li a {
  padding: 15px 20px;
  color: #fff;
 }

 #ajonav ul ul li a:hover {
color: #ffffff;
  background-color: #a01013;
 }

The coding seems to work fine except when including a fading background; you can check it out here- http://metroanimalshelter.org/testredesigns2.html  - pardon the mess on the page there; I've got a lot of placeholder images in there until I've got the bugs worked out.


text:
Q: Intuition behind the $\epsilon -\delta$ Definition of Limits $\displaystyle\lim _{x\to \:a} f(x) =L $ well this means that :$f(x)$ can be made as close as we want to $L$  provided that $x$ is sufficiently close to $a$. Well this definitely means that: $$\forall \epsilon > 0,\ \exists \delta >0\ \text{ such that }\ |f(x)-L|<\epsilon,$$ provided that $0<|x-a|<\delta$.
But their is a question came to my mind:

Why have we chosen to define it that way? Why haven't we instead defined ''$f(x)$ can be made as close as we want to $L$'' means that: ''$|f(x)-L|=$ any number we want'' instead of ''$\epsilon -\delta$'' one? Why we've defined the limits in the way of neighborhoods not like in a way like  what  I've written? Because if we want to to make $f(x)$ close as we like to $L$, there is a must that the distance between them can be any number, which is $|f(x)-L|=$ any number we want.

A: There are really two subtleties in the definition.
First you need to get rid of the complications that arise due to "$=$" sign . As I said in the comment, you cannot make $|\sin(x)|=2$ for real numbers atleast. Does it mean that the limit does not exist ? . Ofcourse not, you must have learnt in high school calculus that $\sin(x)$ is a continuous function for all real numbers $x\in\Bbb{R}$. So notice that we can definitely make $|\sin(x)|<2$ . In fact we can make $|\sin(x)|<\text{any positive number}$ .
So you should note that your "any(positive) number" definition" has to do with the "epsilon" part of the definition.
Now arises the issue of locality. Typically you want the limit of the function at a point $x=a$ . (More rigorously in terms of set topology , at an accumulation point of the domain set of $f$ ) . So let us again return to the case of $\sin(x)$ and $a=0$ but let us restrict the domain to $[-\frac{\pi}{2},\frac{\pi}{2}]$ .
Now you would want to make sure that the values close to $0$ are being taken when you are near to $0$.
For example, if I choose $\epsilon=0.0001$ (Recall that $\epsilon$ has to do with the "any number" part).
Then I should not be angry if I see that $|\sin(x)|<0.0001$ does not hold if $x$ is near $\frac{\pi}{2}$ or $\frac{\pi}{4}$ . So for this $\epsilon$ , a choice of $\delta=0.8$ would be a bad one. However we can choose it to be such that $0<\delta<\sin^{-1}(0.0001)$ and see that it works.
That is we need to ensure that in a suitable "neighbourhood" of the point $0$ , we should have that the condition $|\sin(x)|<0.0001$ holds. Now obviously this "neighbourhood" would depend on our choice of $\epsilon$. Now as to why $|x-a|<\delta$ is chosen in the definition, the answer to it has to do with something called "open sets" and "basic open sets" in point set topology. If you read further into real analysis, you will get to the point set topology of the real line and you will learn that any open neighbourhood of a point $a$ can be obtained by taking union of sets of the  form $\{x\in\Bbb{R}:|x-a|<\delta\}$ where $\delta$ is varied.
Notice that the above set is what we call an open interval $(a,b)$. Here we are using $(a-\delta,a+\delta)$.
But topology aside, I think you can agree that these symmetric open intervals about a point $(a-\delta,a+\delta)$ really do capture the essence of what it means to be near "$a$" .
So $\epsilon$ takes care of the any positive number part. The inequality sign makes sure that we don't run into a stronger constraint of a equality which might not be possible to achieve. And $\delta$ makes sure that you are concerned with what's happening NEAR the point and not far away from it .


text:
Q: Jekyll - Auto-regeneration not working even with watch used When running any of these commands:
jekyll serve
bundle exec jekyll serve
bundle exec jekyll serve --watch
bundle exec jekyll serve --force_polling

I get:

Auto-regeneration: disabled. Use --watch to enable.

and I can't see local updates until I stop (ctrl+c) and run the command again!
jekyll version (jekyll -v) gives jekyll 3.4.3 which is the same as in my gemfile
What should I do to enable watching changes?

A: The plugin jekyll-admin v0.4.1 disables --watch internally. There are three ways to proceed:

*

*Remove the plugin if you're editing template files.

*Edit your Markdown files through the Admin interface

*Use an older version of the plugin


text:
Q: The least possible "arc length" such that exists an circumscribed square whose every vertex lies within the arc Given $S^1$, the unit circle in $\Bbb R^2$, with the Lebesgue measure restricted to it denoted as $\ell(\cdot)$ (the "arc length"). Now let $R\subset S^1$ be an arbitrary measurable set with $\ell (R)=2\pi p$, then what's the minimal possible value of $p$, if extant, so that there exists a circumscribed square whose every vertex lies in $R$? (If the minimal is not attainable, then at least what's the infimum?)
For a crude estimate, clearly $p>3/4$ can guarantee the existence of such a square: let's identify $S^1$ with $J=[0,1]/\{0,1\}$ and $R$ with a subset of $J$ and $\ell(\cdot)$ with $m(\cdot)$ (the Lebesgue measure on $J$) and thus $m(R)=p$. Then the existence of the square is equivalent to that (mod $1$)$$R\cap (R+1/4)\cap (R+1/2)\cap (R+3/4)\ne \emptyset$$ , which holds if $$m(R^c\cup (R+1/4)^c\cup (R+1/2)^c\cup (R+3/4)^c)<1$$, which again holds (but not a necessary condition!) if $P(R)>3/4$.
However, as indicated in boldface above, there is no guarantee that $3/4$ is optimal.


text:
Q: Dishonored PC god mode? Is there a cheat for the singleplayer mode? All that I find on the net are links to 'trainers', lists of Steam achievements, generic hints and Youtube walkthroughs.

A: If not interested in trainers, no, there are not any ways to cheat in Dishonored.
The debug console was removed prior to release.


text:
Q: Flask-sqalchemy and oracle database id not autoincrement I want to make a new table in my database (Oracle 11g but the Express Edition for Ubuntu 16.04) using Python and Flask framework with the SQLAlchemy module. The first field of the table it's and ID, is an Integer field and I want it to autoincrement, but Oracle database don't support the autoincrement. I have a form to add a new comment, but when I try to add a new record it reports a error:
sqlalchemy.exc.IntegrityError: (cx_Oracle.IntegrityError) ORA-01400: cannot insert NULL into ("WIKTOR"."TBL_COMENTARIOS"."ID") [SQL: 'INSERT INTO tbl_comentarios (usuario, comentario, fecha) VALUES (:usuario, :comentario, :fecha) RETURNING tbl_comentarios.id INTO :ret_0'] [parameters: {'usuario': 'wiktor', 'comentario': 'hola', 'fecha': datetime.datetime(2017, 5, 24, 11, 23, 45, 39450), 'ret_0': }]
Basically it says that the ID cannot be null, that happens because there's no field in the form to add it so it sends the id empty and then the autoincrement of the database model don't work. Here's the code:
db = SQLAlchemy()

class Comentarios(db.Model):
    __tablename__ = 'tbl_comentarios'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    usuario = db.Column(db.String(50))
    comentario = db.Column(db.Text())
    fecha = db.Column(db.DateTime, default = datetime.datetime.now)

def __init__(self, usuario, comentario):
    self.usuario = usuario
    self.comentario = comentario

I also tried:
id = db.Column(db.Integer, primary_key=True)

That code did work in SQL Database but neither works in Oracle Database.
Sorry for my english, I hope someone can help me...
Thanks!

A: You can find here the SQLAlchemy documentation that discusses this. Oracle has no auto increment feature and relies on sequence to mimic the behavior.
So, your id column should look like this:
id_seq = Sequence('id_seq')
id = db.Column(db.Integer, id_seq,
        server_default=id_seq.next_value(), primary_key=True)


text:
Q: Regex works in test file, not in program (HTTP raw response) I am attempting to debug a regex, and for the life of me, I cannot figure out why it works in the test file, but not elsewhere.
I am receiving a raw HTTP response, and have parsed out the section of interest:
UID:5F12F7DA-10B0-4EE3-820D-B56F0B2FC153
DTSTAMP:20120408T041113Z
CLASS:PUBLIC
CREATED:20120408T041113Z
DESCRIPTION:Testfghfghfghfghfghfghfghfghfghfghfghfghfghfghfgh
DTSTART;TZID=America/New_York:20120410T000000
DTEND;TZID=America/New_York:20120419T010000
LAST-MODIFIED:20120408T041228Z
LOCATION:Philadelphia\, PA
SEQUENCE:1
SUMMARY:Test
TRANSP:OPAQUE

Each line ends in (hex:0D0A), which should be '\r\n'.
Here's the call for the summary:
$this->Summary = \Extract\Extract::GetSummary($vevent);
And here's the function:
public static function GetSummary($String) {
            $re1='.*?'; # Non-greedy match on filler
            $re2='(SUMMARY)';   # Word 1
            $re3='(:)'; # Any Single Character 1
            $re4='(.*?)';   # Non-greedy match on filler
            $re5='(\r\n)';  # Any Single Character 2

            if ($c=preg_match_all ("/".$re1.$re2.$re3.$re4.$re5."/is", $String, $matches))
            {

                $word1=$matches[1][0];
                $c1=$matches[2][0];
                $word2=$matches[3][0];
                return $word2;
            }

        }

Preg_match_all evaluates true in my test file, but false in my program. Any ideas? Something about the raw string it doesn't like, or isn't being copied into my test file (so I can't find it)?

A: Try using just the newline character as your final match:
function GetSummary($String) {
  $re1='.*?';       // Non-greedy match on filler
  $re2='(SUMMARY)'; // Token
  $re3='(:)';       // Separator
  $re4='(.*?)';     // Content
  $re5='\n';        // End of line

  if ($c=preg_match_all ("/".$re1.$re2.$re3.$re4.$re5."/is", $String, $matches))
  {
    $word1=$matches[1][0];
    $c1=$matches[2][0];
    $word2=$matches[3][0];
    return $word2;
  }
}

Demo: http://ideone.com/zHr2X
If this still doesn't work, you might try using the end-of-line token $, or sanitize the line endings prior to calling the regex.


text:
Q: Querying External tables with built-in function in Azure Sql I see performance issue in following query while executing on external table vs native database table with built-in function in Azure SQL database. Example
select top  1000000 vs.*
,ROW_NUMBER() over(partition by vs.context_id order by vs.value)
from Tbl_sign vs
JOIN Tbl_cli ce
ON  ce.[Clinical Encounter ID] = vs.[Clinical Encounter ID]
and ce.[CONTEXT_ID] = vs.[CONTEXT_ID]

Execution time for native database table - 1 mins and 10 secs
Execution time for non-native database external table - 4 mins and 5 secs
If anyone has Azure SQL database access, pls check query performance against table in native DB vs exernal table non-native DB with built in function.
ex.

*

*Tbl_sign and Tbl_cli table in native DB called ABC

*Tbl_sign and Tbl_cli external table in non-native DB called DEF having external data source = ABC

Any thoughts on why performance is different?


text:
Q: A self-invoking function is not called I have a problem - I wrote a mini function to the counter on the page. The assumption is that the value is incremented by one at some timeout, unfortunately - nothing happens. What am I doing wrong?

document.getElementById("counter").innerHTML = Math.floor((Math.random() * 1000) + 1);

subscribers = function() {
  document.getElementById("counter").innerHTML++;
  setTimeout(subscribers, 300);
}

A: Chicken and edd: subscribers() calls itself, but you still need to call it the first time.

document.getElementById("counter").innerHTML = Math.floor((Math.random() * 1000) + 1);

subscribers = function() {
  document.getElementById("counter").innerHTML++;
  setTimeout(subscribers, 1000);
}

subscribers(); // <-- Start your loop.

That said, a much more idiomatic solution is to use setInterval():

document.getElementById("counter").innerHTML = Math.floor((Math.random() * 1000) + 1);

setInterval(() => document.getElementById("counter").innerHTML++, 1000);

A: The term for that function is a "recursive" function, and recursive functions don't automatically invoke themselves out of the blue.
If you really did want to define and invoke it in the same place, then you can turn it into an Immediately Invoked Function Expression (IIFE):

document.getElementById("counter").innerHTML = Math.floor((Math.random() * 1000) + 1);

(function subscribers() {
  document.getElementById("counter").innerHTML++;
  setTimeout(subscribers, 300);
})();


text:
Q: Trouble downloading packages When I try to download any of the following package, it shows error.
sudo apt-get install libelf-dev
sudo apt-get install tcl-dev
sudo apt-get install tk-dev

Reading package lists...
Building dependency tree...
Reading state information...
E: Unable to locate package tk-dev

and so on.

A: If apt-get install Unable to locate package, It means that package you are installing may not available on PPA according to your /etc/apt/sources.list
Then You should add appropriate PPA (For Finding PPA Refer Website: http://www.ubuntuupdates.org/ppas)
Then sudo apt-get update and then sudo apt-get install [pkg-name]
For More Information About How To Add PPAs Visit: Ubuntu Help


text:
Q: Unity, ML-Agents "'Actionbuffers' could not be found" error Recently I've been struggling with the ML-Agents Unity error - "error CS0246: The type or namespace name 'Actionbuffers' could not be found (are you missing a using directive or an assembly reference?)". I've downloaded the latest package version of ML-Agents through Unity's Package Manager, also trying to download package through git URL. Nothings worked for me and I haven't been able to find help on the internet.
Here is the small bit of code I have so far plus the error message on Unity:

A: solved. deleted the script. redid it. it worked.


text:
Q: Is there a saying like 'those who find faults with other people tend to be blind to their own faults'? Is there a saying that could be explained as 'those who find faults with other people tend to be blind to their own faults?' As with people who are picky; their criticism of others often applies to themselves.

A: The standard variant is:

Remember that when you point a finger at someone, there are three pointing back at you.

Google threw this one up:

Fools can find fault, but they can't act anymore wisely. - Langbien

A: People who live in glass houses shouldn't throw stones

A: This is a classic, in English and other languages alike:

We see the straw in the eyes of others and we do not see the beam in ours.

Matthew 7:3 is the inspiration.

A: There's

That's the pot calling the kettle black,

...which indicates that a pot hanging over the fire will be just as black (that is, in the same state) as a kettle. There are a number of variations on that saying; it's so well-known that generally it suffices simply to mention "pot" and "kettle" in the same sentence.
And the Bible has something to say on it, eg in Matthew 7.

"Do not judge, or you too will be judged. For in the same way you judge others, you will be judged, and with the measure you use, it will be measured to you.
        "Why do you look at the speck of sawdust in your brother's eye and pay no attention to the plank in your own eye? How can you say to your brother, 'Let me take the speck out of your eye,' when all the time there is a plank in your own eye? You hypocrite, first take the plank out of your own eye, and then you will see clearly to remove the speck from your brother's eye." [NIV]

Again, the last sentence is so well-known that simply reminding someone [using the King James Version] to take the beam out of their own eye will often be enough.

A: Matthew 7:3

And why beholdest thou the mote that is in thy brother's eye, but considerest not the beam that is in thine own eye?

(King James version)
Other versions


text:
Q: How can I sync Xubuntu's calendar Orage with Google Calendar? Does anyone know how to sync Xubuntu 15.10 calendar (Orage) with Google Calendar? I found some old links but it doesn't seem to work anymore.

A: I believe you can modify this file /home/user/.config/orage/oragerc approximately like that:
Archive file=/home/user/Dropbox/orage/orage_archive.ics
Orage file=/home/user/Dropbox/orage/orage.ics

These files are (or should be) originally in /home/user/.local/share/orage (2)
Or you can go in Orage to File -> Share data (or data share?(1)) to change the paths of the files.
So, you could sync with any computer or mobile with Orage (but not Google Calendar) and your Dropbox account. However, I have not tried yet but it works with passwords manager like Keepass.
In any case, synchronizing an application with a Google app requires lowering the security of the Google app.
Do you know? "Orages" means "thunderstorm" in French.
(1)Échanger des données in the french version
(2) If you never used Orage, they will not exist yet

A: There is an interesting article here (8 april 2018 by Ayman Bagabas) that suggests using a utility, Vdirsyncer, to perform the synchronisation. vdirsyncer is a command line tool that can synchronise calendars and address books between servers and the local file system in both directions. Typically, it is run periodically through cron or a systemd service.
Setup is not quite straightforward, and requires some technical experience. Details are outlined in the article.

*

*Using a configuration file, the synchronization is set up with respect to vdirsyncer.

*One needs to enable the CALDAV API for the Google account from within the Google API console.

*Then vdirsyncer needs to be granted access to the Google account.

*Orage must be pointed to the synchronized file

*With cron or systemd, vdirsyncer is run periodically.

In case the article is not available in the future, some information is replicated here. Credit goes to Ayman Bagabas, the author of the article:
Prerequisites
Have vdirsyncer and orage installed:
sudo apt install vdirsyncer orage

1. Configuration file
An example of a configuration file ~/.vdirsyncer/status for vdirsyncer is given as:
[general]
status_path = "~/.vdirsyncer/status/"

[pair calendar]
a = "google_calendar"
b = "local_calendar"
collections = ["from a", "from b"]
metadata = ["color"]

[storage local_calendar]
type = "singlefile"
path = "~/.calendars/%s.ics"

[storage google_calendar]
type = "google_calendar"
token_file = "~/.vdirsyncer/google_token"
client_id = "CLIENT_ID"
client_secret = "CLIENT_SECRET"

2. Enable CALDAV API for your google account

*

*Go to https://console.developers.google.com/ and create a new project.

*Click on "Enable APIs and Services" or on the left side click on Library, then search for "CalDAV" and enable it.

*Click on "create credentials" then choose "CalDAV API" for your API and select "Other" for Application type. Click next and choose a name e.g. "vdirsyncer" then click continue.

*You will get your client id, stick it into your configuration file.

*Click "done" after you get the client id then click on the credentials name and get the client secret from there.

3. Grant vdirsyncer access to your Google account
$ vdirsyncer discover calendar
This will authorize the pair calendar provided in the config file. A browser window will pop up to complete the authorization with google.
4. Point Orage to the synchronised file
In Orage: File -> Exchange data, and add the files under ~/.calendars (according to the example config file above).
Syncronisation should now work, and can be done with the command
vdirsyncer sync
Remains to have that command periodically run (e.g. every hour) using cron or systemd.


text:
Q: Blazor (server side) authentication and static files As per Microsoft's recommendation, I am using a custom AuthenticationStateProvider service for handling authentication/authorization for a Blazor server page.
It all works fine within razor components, where I can use the [Authorize] attribute or the AuthorizeView/Authorized/NotAuthorized tags.
Now, I wanted to serve static files outside the wwwroot folder but have control if the user is authenticated or not in order to serve the files.
Is there a way to control access to static files served outside the wwwroot folder?
What I found is something similar to (in program or startup):
app.UseStaticFiles(new StaticFileOptions
{
    OnPrepareResponse = (context) =>
    {
        if (context.Context.Request.Path.StartsWithSegments("/MyRequestPath"))
        {
            context.Context.Response.Headers.Add("Cache-Control", "no-store");

            if (!context.Context.User.Identity.IsAuthenticated)
            {
                context.Context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
                context.Context.Response.ContentLength = 0;
                context.Context.Response.Body = Stream.Null;
            }
        }
    },
    FileProvider = new PhysicalFileProvider("PathToMyFilesOutsidewwwroot"),
    RequestPath = "/RequestPath"
    });

The problem with that is that is uses Context.User.Identity.IsAuthenticated, i.e., it uses HTTPContext, which is not available within a Blazor page (and that is why we have to use AuthenticationStateProvider).
I'd like to stick to just using Blazor best practices, and not try to circumvent it via scaffoldding, javascript, or whatever.
Thanks in advance.

A: In the end I sticked to using the app.UseStaticFiles... approach, but in order to make it work I had to add authentication via cookies (outside of Blazor). Inside of Blazor I still use AuthenticationStateProvider, so the only thing that I had to take care is to authenticate via cookies and AuthenticationStateProvider at the same time when a user logs in. I suppose it makes sense, because authentication via cookies (prior to entering the Blazor "environment") gives me also the chance to call controllers or other pages out the razor components while still being authenticated (via cookies).


text:
Q: Packing items into fixed number of bins I am looking for an algorithm that will solve my problem in the most efficient way.
Problem description:
I have a list of items (only positive integers are allowed) and fixed number of bins of identical capacity. So far, I thought about branch-and-bound algorithm, but I am not quite sure if it is the best approach in this case.
Example:
Given a list of items:
(3, 4, 4, 2, 3, 9, 2)

and three bins of capacity 9 each
I need to pack them this: (order of items is irrelevant)
[3, 4, 2], [4, 3, 2], [9]

I think this is a variant of the bin-packing problem (which I know is NP-complete), but since I am not trying to minimize number of bins used I wonder if there is a better solution.

A: This is the multibin packing problem:

Given a set of items, each of a specific size, and a set of bins, each
  of a specific size as well – is there a distribution of items to bins
  such that no item is left unpacked and no bin capacity is exceeded?

In general it is NP-hard. However, there are several special cases that may be solved efficiently, either approximately or even optimally.
see Wolfgang Stille aus Göppingen's thesis

A: This is equivalent to the bin packing problem, given a number of bins, maximizing the number of items packed into the bins.
If the optimal solution is larger than or equal to the number of the items in your list, the solution is also your problem's solution. If the optimal solution is less than the number of the items in your list, there is no solution to your problem.
Since the bin packing problem is NP-Hard, there is no polynomial time solution to your problem either. You can use the heuristics developed for the bin packing problem, such as best fit, first fit and so on. But they do not guarantee the optimal solution to be found.


text:
Q: $q$ is a regular value of $f^\circ=f\mid_{M^\circ}$ or $\partial M$, but $S=f^{-1}(q)$ is not a manifold; I just learned the following Sard's theorem:

Sard's theorem: For any smooth map $f$ of a manifold $X$ with boundary into a boundaryless manifold $Y$, almost every point of $Y$ is a regular value of both $f: X \to Y $and $ \partial f: \partial X \to Y$.

I want to find some examples showing that "almost every" condition cannot be strengthened. To be more specific,

Suppose $M$ is a manifold with boundary, $\dim M\geq 2$ and $f: M\to N$ is smooth. $q\in N$, construct two examples:

*

*$q$ is a regular value of $f^\circ=f\mid_{M^\circ}$, but $S=f^{-1}(q)$ is not a manifold;

*$q$ is a regular value of $\partial f=f\mid_{\partial M}$, but $S=f^{-1}(q)$ is not a manifold;

Appreciate any help!

A: This is the version of Sard's theorem specifically when dealing with manifolds with boundary (as Guillemin and Pollack themselves state). The usual version appears earlier on p. 39.
When you are looking for examples, you need to be talking now about manifolds with boundary, not manifolds. The point of the two regular value conditions is that then you will get a submanifold of $X$ with boundary whose boundary is the intersection of the preimage with $\partial X$. Here's an example to contemplate: Consider $f\colon\Bbb H^2\to\Bbb R$, $f(x,y) = x^2+(y-1)^2-1$. Look at $f^{-1}(0)$. Is $0$ a regular value of both maps?
For your second question, it's far easier. Take $f(x,y) = x(y-1)$, still mapping $\Bbb H^2\to\Bbb R$. Now $0$ is a regular value of $\partial f$, but is $f^{-1}
(0)$ a submanifold with boundary of $\Bbb H^2$?


text:
Q: Why isn't JavaScript running when I refernce the external file in between the head tags in my html file? When I put the link to my JS file in between my html header tags the js file will not run. However if I put the external js link after my body tag or somewhere after the bulk of my html code the file runs. Is there any way to make the external js file run when I link the external file in between the head tags. I also should mention that I'm doing HTML DOM in the external js file.
HTML Portion:
<!DOCTYPE html>

    <title>HTMLDOM Practice</title>
    <link rel="stylesheet" type="text/css" href="HTMLDOM Practice.css"/>

Hello World!

Javascript/HTML DOM portion:
var x = document.getElementById('txt');
var b = document.getElementById('box');

x.addEventListener('click',irt,false);
b.addEventListener('click',irt,false);

function irt(){
    x.innerHTML="Goodbye world!";
    b.style.padding="20px";
}

A: i know it can be annoying to place JS code at the bottom of the page just to use DOM. As a good practise I usually load the JS in the head.
You could workaround something like this.
1) Place a function in your JS file which does the initialising
2) Call the initialise function OnLoad.
JS FILE looks like this
var x;
var b;

function irt(){
    x.innerHTML="Goodbye world!";
    b.style.padding="20px";
}

function setEverything(){
    x = document.getElementById('txt');
    b = document.getElementById('box');

    x.addEventListener('click',irt,false);
    b.addEventListener('click',irt,false);
}

HTML body tag

A: The problem as I see it is that the JS is running before the DOM has finished loading. To fix this, simply add defer to your script tag which will defer the execution of the JS until everything else has completed:

Furthermore, if the browser supports it, you can opt for asynchronous download and execution of the JS files by using async. You can combine this with defer for best results across differing browsers:


text:
Q: connection refused error in the very first line when using pycharmdevtools? I want to get the source code of a website, but the html file get by using driver.get() is not showing all te information. So I plan to use these codes I found
import PyChromeDevTools
chrome = PyChromeDevTools.ChromeInterface()
chrome.Network.enable()
chrome.Page.enable()
chrome.Page.navigate(url="https://stackoverflow.com")
html_code=chrome.DOM.getOuterHTML()

Yet When I run the first 2 lines:
import PyChromeDevTools
chrome = PyChromeDevTools.ChromeInterface()

I immediatly get an error saying
ConnectionRefusedError                    Traceback (most recent call last)
File ~\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\urllib3\connection.py:174, in HTTPConnection._new_conn(self)
    173 try:
--> 174     conn = connection.create_connection(
    175         (self._dns_host, self.port), self.timeout, **extra_kw
    176     )
    178 except SocketTimeout:

File ~\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\urllib3\util\connection.py:95, in create_connection(address, timeout, source_address, socket_options)
     94 if err is not None:
---> 95     raise err
     97 raise socket.error("getaddrinfo returns an empty list")

File ~\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\urllib3\util\connection.py:85, in create_connection(address, timeout, source_address, socket_options)
     84     sock.bind(source_address)
---> 85 sock.connect(sa)
     86 return sock

ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it

The existing infromation on this matter does not quite match with the case with the PyChromeDevTools module I was using. Any idea of what might go wrong?
Thanks in advance.


text:
Q: Google Analytics Locks Main Thread in iOS App I've a strange problem with GA. When I launch my app everything works fine, but launching it from another app (App Store, Testflight, or test launcher) leads to dead lock. GA blocks the main thread to process the UIApplicationDidBecomeActiveNotification notification with the following stack trace:
0   libsystem_kernel.dylib          0x000000018d255e1c __psynch_cvwait + 8
1   libsystem_pthread.dylib         0x000000018d31a9d0 _pthread_cond_wait + 640
2   Foundation                      0x000000018ecc1620 -[NSCondition wait] + 240
3   Foundation                      0x000000018ec84a9c -[NSObject(NSThreadPerformAdditions) performSelector:onThread:withObject:waitUntilDone:modes:] + 792
4   Foundation                      0x000000018ec84764 -[NSObject(NSThreadPerformAdditions) performSelector:onThread:withObject:waitUntilDone:] + 128
5   Search                          0x00000001005d457c -[GAIDataStore performBlockAndWait:withError:] + 260
6   Search                          0x00000001005d69f4 -[GAIDataStore save:] + 92
7   CoreFoundation                  0x000000018e22222c __CFNOTIFICATIONCENTER_IS_CALLING_OUT_TO_AN_OBSERVER__ + 20
8   CoreFoundation                  0x000000018e221930 _CFXRegistrationPost + 400
9   CoreFoundation                  0x000000018e2216ac ___CFXNotificationPost_block_invoke + 60
10  CoreFoundation                  0x000000018e290b9c -[_CFXNotificationRegistrar find:object:observer:enumerator:] + 1504
11  CoreFoundation                  0x000000018e163bf4 _CFXNotificationPost + 376
12  Foundation                      0x000000018ec6a6bc -[NSNotificationCenter postNotificationName:object:userInfo:] + 68
13  UIKit                           0x00000001941322b0 -[UIApplication _deactivateForReason:notify:] + 828
14  UIKit                           0x0000000194350470 __61-[UIApplication _sceneSettingsPreLifecycleEventDiffInspector]_block_invoke + 124
[shortened]

This only happens with each launch launch from Testflight. Opening the app from Springboard works fine.
I had a similar problem opening the app as slide over / split view app on an iPad Air. I could solve the problem with a delayed initialization of GA. This is my initialization code:
GAI *theGAI = [GAI sharedInstance];

[theGAI trackerWithTrackingId:kTrackingId];
theGAI.trackUncaughtExceptions = YES;
#ifdef DEBUG
    theGAI.logger.logLevel = kGAILogLevelVerbose;
#endif

How can I avoid this deadlock?

A: I could avoid the freeze by putting the screen tracking into a background thread. The first tracking is delayed to avoid collisions with the initialization code of GAI.
- (void)trackScreen {
    static NSTimeInterval sDelay = 0.75;
    NSString *theName = NSStringFromClass([self class]);
    id<GAITracker> theTracker = self.tracker;

    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(sDelay * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [theTracker set:kGAIScreenName value:theName];
        [theTracker send:[[GAIDictionaryBuilder createScreenView] build]];
        sDelay = 1.0 / 16.0;
    });
}


text:
Q: Как реализовать такую конструкцию с помощью Bootstrap 4?
Есть такой код только из 3-х колонок. Как добавить нижний длинный блок NEWS

Average Sales

Average Sales

Average Sales

A:

Average Sales

Average Sales

Average Sales

    после всех блоков пишешь такую магию =)

 А тут пишешь что душа пожелаеш)


text:
Q: How an object is removing duplicates? I am new to object oriented coding. I found this example when practising.
It is confusing; whenever we are passing an array to a function it is removing the duplicates.
I wondered where are the duplicated values,how they are gone and how it is sorting the array?
Can any one explain me in deeply. I am new to object oriented concepts.

function duplicate(arr) {
  var i, len = arr.length,
    obj = {};
  for (i = 0; i < len; i += 1) {
    obj[arr[i]] = 0;
  }
  return obj;
}
//calling function
console.log(
  duplicate([1, 2, 3, 4, 4, 3, 2, 1, 0, -1, 10, 100])
);

// result::{0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 10: 0, 100: 0, -1: 0}

A: This is quite a strange way to do it but I've commented the code to make it easier to understand.

function duplicate(arr) {
  // declare variables
  var i, len = arr.length,
    obj = {};

  // for each item in the array
  for (i = 0; i < len; i += 1) {
    // create or set key within obj named the current array item with the value 0
    obj[arr[i]] = 0;
  }

  // return the created object
  return obj;
}
//calling function and passing the array
console.log(duplicate([1, 2, 3, 4, 4, 3, 2, 1, 0, -1, 10, 100]))

This works because when the key is set it is unique so calling again will edit the existing entry and not add another.
A quick way to make this better would be to return just the object keys rather than the whole object. You'd do this by changing return obj; to return Object.keys(obj);