text:
Q: knockoutjs mapping: adding observables in a tree I'm using knockoutjs to visualize a tree. I have a initial AJAX-call to load the hole tree. Mapping happens using the knockout-mapping-plugin. Everything is working fine :) thanks for this great piece of software.
My problem is: I want to add additional observables to the model. I can do this using mapping options.
Object:
{ id: ko.observable(), parentID: ko.observable(), description: ko.observable(), children: ko.observableArray() }

Mappingoptions:
var mappingOptions = {
            create: function (options) {
                console.log("create");
                var vm = ko.mapping.fromJS(options.data);
                vm.newObservable = ko.observable(true);
                return vm;
            }
        };

Mapping:
ko.mapping.fromJS(response, mappingOptions, self.nodes);

response is the list of objects(nodes). self.nodes is the observableArray() holding the list of objects(nodes)
Every node has the children-observalbeArray containing also nodes(with children)
So nothing special, that's basically how a tree works :)
But this only adds this new observable to the root node. I want this extra observable also in every child and child's child (and so on...).
I tried:
var mappingOptions = {
    create: function (options) {
        console.log("create");
        var vm = ko.mapping.fromJS(options.data);
        vm.newObservable = ko.observable(true);
        return vm;
    },
    'children': {
        create: function (options) {
            console.log("children.create");
            options.data.newObservable = ko.observable(true);
            return ko.mapping.fromJS(options.data);
        }
    }
};

I found this somewhere on the internet. It is not working.
Can someone help me?
Thanks!
P.S.: i can't provide a fiddle, because the service seems to be broken right know (or my firewall is blocking it :( )

A: I would try creating a data model. Let's call it Node:
var Node = function Node(data) {
  this.parentID    = ko.observable( data.parentID );
  this.description = ko.observable( data.description );
  this.children    = ko.observableArray([]);

  data.children.forEach(function(child) {
    this.children.push( new Node(child) );
  }, this);
}

This makes it easy to create any additional properties on every node you wish.
In your viewmodel:
var Viewmodel = function Viewmodel() {
  this.nodes = ko.observableArray([]);

  this.getResponse = function getResponse() {
    // response is loaded here

    response.forEach(function(node) {
      this.nodes.push( new Node(node) );
    }, this);
  };
}

Please note that I'm using the native Array.prototype.forEach here. If you need to support IE < 9, you can replace it with Knockouts ko.utils.arrayForEach instead.


text:
Q: Change/Update Object Value with TextBox DataBind c# in my code i have something like that:
myTextBox.DataBindings.Add(new Binding("Text", myObject, "id",
true,System.Windows.Forms.DataSourceUpdateMode.OnPropertyChanged, "0", "N0"));

The bind work correctly but when i change the value of textbox my id value doesn't refresh.

A: This Works for me,
myTextBox.DataBindings.Add(new Binding("Text", myPlane, "id")

And in my class add the interface INotifyPropertyChanged:
class Planes : INotifyPropertyChanged
{}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Phone number validation in angularjs I am trying to validate phone number for the below condition,
    If all 10 digits are of same number,it should display an error message.
    If it starts with 1, it should display an error message.
Please share your suggestion if you have come across such scenario.

A: Without example code, it will be hard for us to see what you are trying to do - and if you have even attempted at solving it yourself.
But oh well, there are multiple ways of doing this, what you want is serverside validation - as you NEVER want to validate on the users end.
How can you limit the value from input using AngularJS?
Adding a listener on a model in angularjs With this one (And I 'THINK' this is what you want), you can update 'something' according to what is being input into the text area.


text:
Q: BottomNavigationBar // Cannot control item label color Goal: I want to give the item label a specific font and color depending on if it is selected or not.
My approach: As the label cannot be styled directly, I'm using the properties "unselectedLabelStyle" and "selectedLabelStyle".
The Problem:

*

*The properties work for font and fontweight, but I cannot directly control the text color

*I can influence the label color of the selected item; but not with the "selectedLabelStyle" property, but with the color I specifiy under "seltectedItemColor".

*"unselectedLabelStyle" also works for font and fontweight, but not for the color. I cannot find a property, that would allow me to change the color. > THIS IS THE PROBLEM
Pretty picture (code below):

The code:
BottomNavigationBar(
      elevation: 0,
      onTap: (index) => selectPage(index),
      currentIndex: selectedPageIndex,
      selectedItemColor:
          Provider.of<CustomColors>(context).customColorScheme['Dark Teal'],
      unselectedLabelStyle:
          Provider.of<CustomTextStyle>(context, listen: false)
              .customTextStyle('IconLabel'),
      selectedLabelStyle:
          Provider.of<CustomTextStyle>(context, listen: false)
              .customTextStyle('IconLabel'),
      backgroundColor: Colors.white,
      type: BottomNavigationBarType.fixed,
      items: [
        //home
        bottomNavIcon(
          context: context,
          icon: Image.asset(
            "assets/icons/icon_home.png",
          ),
          icon_active: Image.asset("assets/icons/icon_home.png",
              color: Provider.of<CustomColors>(context)
                  .customColorScheme['Dark Teal']),
          label: 'Home',
        ),
        //favorite
        bottomNavIcon(
          context: context,
          icon: Image.asset("assets/icons/icon_favorite.png"),
          icon_active: Image.asset("assets/icons/icon_favorite.png",
              color: Provider.of<CustomColors>(context)
                  .customColorScheme['Dark Teal']),
          label: 'Favorite',
        ),
        //loockback
        bottomNavIcon(
          context: context,
          icon: Image.asset("assets/icons/icon_lookback.png"),
          icon_active: Image.asset("assets/icons/icon_lookback.png",
              color: Provider.of<CustomColors>(context)
                  .customColorScheme['Dark Teal']),
          label: 'Lookback',
        ),
        //info & support
        bottomNavIcon(
          context: context,
          icon: Image.asset("assets/icons/icon_info.png"),
          icon_active: Image.asset("assets/icons/icon_info.png",
              color: Provider.of<CustomColors>(context)
                  .customColorScheme['Dark Teal']),
          label: 'Info & Support',
        ),
      ],
    ),

Code for the icons
BottomNavigationBarItem bottomNavIcon(
{required BuildContext context,
required Image icon,
required Image icon_active,
required String label}) {

return BottomNavigationBarItem(
    icon: Padding(
      padding: EdgeInsets.only(top: 6.h, bottom: 3.h),
      child: icon,
    ),
    activeIcon: Padding(
      padding: EdgeInsets.only(top: 6.h, bottom: 3.h),
      child: icon_active,
    ),
    label: label,
  );
}

A: If you want the unselected items to have a certain color, use:
unselectedItemColor: Colors.red,

This will change the color of label and icon both for unselected items.
Example:

Unfortunately, unselectedLabelStyle property works for changing font weight, font size etc but not for color.
Also check this answer for unselectedLabelstyle don't work in Flutter

A: As the docmumentation say's, you can change the text color using the color property of TextStyle : https://api.flutter.dev/flutter/painting/TextStyle-class.html
Once this say's perharps BottomNavigationBar overide the color when setting selectedItemColor and/or unselectedItemColor
After giving a try, effectively color is overide even if you don't provide selectedItemColor and/or unselectedItemColor


text:
Q: Laravel "artisan tinker" stops with a colon (:)
When a lot of text is printed (example User::all()), old tinker v2.7.1 prints all data. The new tinker stops with a colon (:). Is there a way to return the old behavior?

A: Tinker uses Psysh.
Psysh has a config option for setting pager.
From https://github.com/bobthecow/psysh/wiki/Config-options

If this is not set, it falls back to less. It is recommended that you
set up cli.pager in your php.ini with your preferred output pager.

For anything more than one page long, less will interrupt output with a colon.
I fixed this by switching the pager to 'cat'.
To update psysh options for tinker, create a .psysh.php file in the laravel project root directory and throw this in it:
<?php

return [
    'pager' => "cat"
];

Now when you run tinker, you'll get uninterrupted output (like it used to be).


text:
Q: Find out whether two rectangles are intersecting in 3D space I've got two rectangles in 3D space, each given by the coordinates of their 4 corners. They are not axis aligned, meaning their edges are not necessarily parallel/perpendicular to the world axes. Each rectangle can have any orientation.
Is there an easy way to know whether or not the two rectangles are intersecting?

A: Find the intersection points of both rectangles in the plane of the other. You achieve that by plugging the coordinates of the vertices in the implicit equation of the plane and detecting a change of sign.
If you obtain four intersection points, which define two line segments, it suffices to test if these segments overlap (and where if you need the endpoints). Project the points on the direction of the common line (cross-product of the normal vectors), and you will get scalar values corresponding to abscissas along that line.
Checking for overlap in 1D is trivial.

A: There are easy ways to decide (in some cases) the complement of this question, which is why you can devise a test to eliminate false positives. The problem is all the pathological fencepost cases, which you'll have to tackle systematically (one common vertex, one common edge etc) and floating point / precision issues, which are the bane of computational geometry.
For the first elimination test, I'd use the bounding boxes of the rectangles. If no more than two of the three coordinate ranges $\{min(x), max(x)\},\{min(y), max(y)\},\{min(z), max(z) \}$ of the two rectangles overlap, there is no intersection. You can convince yourself of that. You can check the x-, y- and z-ranges in succession eliminating false positives this way. ("Overlap" has to be understood as a non-empty set produced when you take the set intersection of the respective intervals).
After one round of elimination comes the tougher part. Even if there is overlap in the x,y, and z- ranges of two space rectangles, it does not mean that they intersect (think parallel rectangles). However, you can easily find the equations of the planes containing the two rectangles (taking three points each), so you can eliminate parallel planes.
Pairs of rectangles that pass both tests still need not intersect. At this stage you can try solving for the equation of the line in which both planes containing the rectangles intersect. Now you have to test the (endpoints of the) line against your intersection bounding box. If it lies outside, it is another false positive eliminated. If it lies inside, well, you still have more work to do.

A: If you can test for line-rectangle intersection, then two rectangles A and B intersect if and only if either a line from A intersects B or a line from B intersects A (inclusive of the endpoints).  Each of A and B are only four lines, so this shouldn't be too bad to check.

A: A point in each rectangle is individuated vectorially by
$$
\eqalign{
  & {\bf P}_{\,1}  = {\bf t}_{\,1}  + a{\bf u}_{\,1}  + b{\bf v}_{\,1} \quad \left| {\;0 \le a,b \le 1} \right.  \cr
  & {\bf P}_{\,2}  = {\bf t}_{\,2}  + c{\bf u}_{\,2}  + d{\bf v}_{\,2} \quad \left| {\;0 \le c,d \le 1} \right. \cr}
$$
with an obvious meaning of the vectors
 - ${\bf t} _k$: vector of a chosen vertex;
 - ${\bf u} _k$: vector parallel to a side from the chosen vertex;
 - ${\bf v} _k$: vector parallel to the other side from the chosen vertex;
Therefore, for the points to coincide we shall have
$$
{\bf P}_{\,1}  = {\bf P}_{\,2} \quad  \Rightarrow \quad a{\bf u}_{\,1}  + b{\bf v}_{\,1}  - c{\bf u}_{\,2}  - d{\bf v}_{\,2}  = {\bf t}_{\,2}  - {\bf t}_{\,1}
$$
which is a linear system of $3$ equations in $4$ unknowns .
For the rectangles to intersecate each other, we shall verify that
 - the system is solvable (in $a,b,c,d$);
 - the set of solutions intersect the domain $[0,1]^4$.
There are various approaches to verify the first condition.
We can for instance go algebraically and check the  the rank of the coefficients matrix, and that of the complete matrix:
 - if both have rank $3$, we have a set of $\infty ^1$ solutions (a line), depending on one of the unknowns taken as a parameter,
geometrically that means that the planes of the ractangles intersect on a line;
 - if the coefficients matrix has rank $2$, then the rectangles planes are parallel,
and they will be coincident or not depending if the complete matrix has  rank $2$ or $3$,
if they have both rank $2$ then we have $\infty ^2$ solutions (two parameters);
 - if the coefficients matrix has rank $1$, one or both the rectangles are degenerated
(and you can check this case in advance).


text:
Q: Is id a python builtin function? Would you please look at code below,
def getCrewListAll(self):
    """
    Set to crew list to all available crew
    """
    crew = getIdNumbers()
    return map(lambda cr: cr.id, crew)

What is the meaning of cr.id here, is id a builtin python function or?

A: In your example, the reference to cr.id is not a function call. Its accessing a member attribute of the cr variable, which is a placeholder for whatever the crew objects are.
id is the name of a builtin function, yes. But there is no way to know if its being used under the hood in these objects without seeing the actual class definitions.
As an example... if this were, say, a django application, model instances have id member attributes that give you the database id of that record. Its part of the design of the class for that framework.
Even though I am assuming its an attribute... for all we know it could also be a computed property which is similar to a method call that acts like an attribute. It could be doing more logic that it seems when looking at your example.
Lastly, since the cr.id could be anything, it could even be a method and the map is returning a lis of callables: cr.id()

A: cr.id isn't a builtin function (unless you've assigned it to be...), it's a normal member of the cr object there.
id(cr) would be an invocation of that builtin and would return the identity of cr.

A: I think the real problem here is that you don't understand the code you have posted.
In this context you need to understand map and lambda.
map is a function which applies a function to each element of a list and returns this as a list:
>>> def func(a):
...   return a * 2
...
>>> map(func, [1,2,3])
[2, 4, 6]

lambda can be seen as a shortcut to create functions. The above could be written with lambda:
>>> func = lambda a: a * 2
>>> map(func, [1,2,3])
[2, 4, 6]

So what your code map(lambda cr: cr.id, crew) is doing: It returns a list of the id attribute from each of the objects in the list crew.
The problem is that this code is actually not pretty good. You can write the same function with a list comprehension, which is much more intuitive:
def getCrewListAll(self):
    return [cr.id for cr in getIdNumbers()]

A: there is a built in id function but may or may not be related to this, depending on the implementation of that object, either way id here is a member/property of that object.
If you are curious to see what kind of members/fields that object has you can do dir(crew[0]) assuming its retuning at least one, and if its properly document you can also do this help(crew[0].id)


text:
Q: AWS CLI V2 Issue with Docker I am running a local docker container which installs the v2 AWS CLI using CURL, unzip, .aws/install.
I am able to get output from aws2 --version, but when I try to run any command such as aws2 iam get-user, it returns the following:

local variable 'process' referenced before assignment

There is a new line if that helps in debugging. Cannot figure out why this would ever happen...


text:
Q: Отправить udp запрос через Socks5 proxy средствами php Мне нужно отправить udp запросы и получить ответ, используя Socks5 прокси с авторизацией на php.
Нигде не могу найти рабочий вариант, находил только отправку http запроса.


text:
Q: Regex: Remove every two or more spaces between specific tags and leave just a space instead I want to remove every two or more spaces between specific tags and leave just a space instead:
For example:

  The context of articles,   stories, and conversations helps you     figure out and understand the meaning   of English words in the text that are new to you.

My desire output:

The context of articles, stories, and conversations helps you figure out and understand the meaning of English words in the text that are new to you.

I tried something but it did not work
(?<=
)\s*|\s*(?=
)

A: This removes 2 or more spaces only inside
 and
 and keep any other multiple spaces.

*

*Ctrl+H

*Find what: (?:
|\G)(?:(?!
).)*?\s\K\s+

*Replace with: LEAVE EMPTY

*check Wrap around

*check Regular expression

*DO NOT CHECK . matches newline depending if you want to match multiple lines or not.

*Replace all
Explanation:
(?:                         # start non capture group

 # literally
 |                          # OR
  \G                        # restart from position of last match
)                           # end group
(?:                         # start non capture group
  (?!
)                  # negative lookahead, make sure we haven't reach

  .                         # any character
)*?                         # group may appear 0 or more times, not greedy
\s                          # a space
\K                          # forget all we have seen until this position
\s+                         # 1 or more spaces

Given text:
other     text

  The context of articles,   stories, and conversations helps you     figure out and understand the meaning   of English words in the text that are new to you.

other    text

Result for given example:
other     text

 The context of articles, stories, and conversations helps you figure out and understand the meaning of English words in the text that are new to you.

other    text

Note: it keeps space just after
 and just before

If you want to remove these spaces, you have to run another regex:

*

*Ctrl+H

*Find what: (?<=
)\s+|\s+(?=
)

*Replace with: LEAVE EMPTY

*UNcheck Match case

*check Wrap around

*check Regular expression

*Replace all
Explanation:
(?<=                        # start positive lookbehind, make sure we have

 # literally
)                           # end lookbehind
\s+                         # 1 or more spaces
|                           # OR
\s+                         # 1 or more spaces
(?=                         # start positive lookahead

                      # literally
)                           # end lookahead

Result for given example:
other     text

The context of articles, stories, and conversations helps you figure out and understand the meaning of English words in the text that are new to you.

other    text

A: HTML does not in general care for blanks.
If you display your HTML you will see that the blanks have disappeared.
I have created for you a JSFiddle
for testing.
A much simpler solution is to just replace two blanks by one and repeat as many
times as possible, but blanks are really unimportant unless in
preformatted text which is using the

 Tag.

A: FIND THE SOLUTION:
SEARCH:
(?s)(\G|
)((?!
).)*?\K((?<=>)\h+|\h+(?=<|\h))
REPLACE BY:
(leave empty)


text:
Q: Symmetric key authentication protocol Does anybody know some simple authentication and data transfer protocol based on symmetric keys only? Due to memory constraints (kilobytes RAM and ROM) we cant afford asymmetric cryptography and due to closed environment asymmetric cryptography does not increase security of any way.
I am looking for simple symmetric cryptography protocol that can be kept in head and written on one paper sheet. I was looking in EAP-PSK https://www.rfc-editor.org/rfc/rfc4764#page-4 but still think that 2^6 pages is way to much for something simple and secure.
Does anybody know some useful url, paper or idea?

A: I think you're looking for the Diffie-Hellman key exchange: only requires bignum integer arithmetic (powers, multiplication, and modulus only, at that): http://en.wikipedia.org/wiki/Diffie–Hellman_key_exchange

A: For secrecy, use AES-CBC.  For message authentication, use HMAC-SHA256.  Use a different key for each.
In both cases, use an existing, validated, timing-attack-free implementation of the cryptographic primitives.


text:
Q: How to use objective function with MultiOutputRegressor in regression problem I am working on a time series regression problem, predict future 5 days stock price, I think this is multiple continuous outputs (multi regression).
Hence, I use MultiOutputRegressor in sklearn to do what I want.
But the predicted value for the first three days of the future is more important than the fourth and fifth days of the future.
Therefore, I want to use a weight to penalize the first three days, anyone knows how to fix this problem with customer objective function? or have other methods to fix this problem
Data and code is below
{"date": {"0": "2003-06-30", "1": "2003-07-01", "2": "2003-07-02", "3": "2003-07-03", "4": "2003-07-04", "5": "2003-07-07", "6": "2003-07-08", "7": "2003-07-09", "8": "2003-07-10", "9": "2003-07-11"}, "open": {"0": 37.1, "1": 37.09, "2": 38.17, "3": 40.6, "4": 39.1, "5": 39.6, "6": 42.0, "7": 41.3, "8": 41.2, "9": 39.6}, "max": {"0": 37.4, "1": 38.1, "2": 38.82, "3": 40.6, "4": 39.26, "5": 41.0, "6": 42.0, "7": 41.3, "8": 41.2, "9": 39.97}, "min": {"0": 36.92, "1": 37.09, "2": 38.1, "3": 38.81, "4": 38.75, "5": 39.6, "6": 40.7, "7": 40.81, "8": 40.05, "9": 39.3}, "close": {"0": 37.08, "1": 38.05, "2": 38.69, "3": 39.0, "4": 39.26, "5": 41.0, "6": 41.19, "7": 41.22, "8": 40.05, "9": 39.91}, "stock_id": {"0": 50, "1": 50, "2": 50, "3": 50, "4": 50, "5": 50, "6": 50, "7": 50, "8": 50, "9": 50}, "target_next_1_day": {"0": 38.05, "1": 38.69, "2": 39.0, "3": 39.26, "4": 41.0, "5": 41.19, "6": 41.22, "7": 40.05, "8": 39.91, "9": 40.66}, "target_next_2_day": {"0": 38.69, "1": 39.0, "2": 39.26, "3": 41.0, "4": 41.19, "5": 41.22, "6": 40.05, "7": 39.91, "8": 40.66, "9": 40.19}, "target_next_3_day": {"0": 39.0, "1": 39.26, "2": 41.0, "3": 41.19, "4": 41.22, "5": 40.05, "6": 39.91, "7": 40.66, "8": 40.19, "9": 40.85}, "target_next_4_day": {"0": 39.26, "1": 41.0, "2": 41.19, "3": 41.22, "4": 40.05, "5": 39.91, "6": 40.66, "7": 40.19, "8": 40.85, "9": 39.8}, "target_next_5_day": {"0": 41.0, "1": 41.19, "2": 41.22, "3": 40.05, "4": 39.91, "5": 40.66, "6": 40.19, "7": 40.85, "8": 39.8, "9": 39.92}}

data = pd.DataFrame(data)
X = data[['open', 'max', 'min', 'close']]
Y = data[['target_next_1_day', 'target_next_2_day', 'target_next_3_day', 'target_next_4_day', 'target_next_5_day']]

def customer_obj(target, predict):
    gradient = ????
    hess = ????
    return gradient, hess
clfpre = xgb.XGBRegressor(n_estimators=5, objective =customer_obj)
clf = MultiOutputRegressor(clfpre).fit(X.values, Y.values)

A: MultiOutputRegressor just builds independent model for each target variable. Hence creating a customized objective function cannot be useful for MultiOutputRegressor.
Your customer_obj can only account for a individual target variable. For example, you can change the default objective reg:squarederror to something like Mean Absolute Error.
From Documentation:

Multi target regression
This strategy consists of fitting one regressor per target. This is a
  simple strategy for extending regressors that do not natively support
  multi-target regression.


text:
Q: Is there a way to dynamically state which flavor route files to import to deal with boilerplate code when making new flavors? One of our apps has quite a few Flutter flavors, where a router needs to be set up for each flavor in order to navigate around the app, as the individual router file will contain the correct imports to the views.
For example, we might have MenuView that exists in
views/flavor1/menu_view.dart
and
views/flavor2/menu_view.dart
and flavor_2_router.dart would navigate to the MenuView as defined by the import ../flavor2/_views.dart statement.
The problem is, when adding a new flavor, or a new view, it's getting slightly cumbersome to copy and paste routes which are shared across all flavors.
I'm essentially wondering if there's a way to dynamically state which files to import (and thus get the classes from) or another type of design pattern that would help deal with this growing boilerplate code?
Fragment of the router code:
// Flavor Specific Imports
import 'package:mycompany/ui/flavors/flavor_1/views/_views.dart';

Route<dynamic> generateRoute(RouteSettings settings) {

  switch (settings.name) {
    case AppUpgradeRoute:
      return _getPageRoute(
        routeName: settings.name,
        viewToShow: AppUpgradeView(),
      );
    case LoginRoute:
      return _getPageRoute(
        routeName: settings.name,
        viewToShow: LoginView(),
      );
    case StartUpRoute:
      var startupSettings = settings.arguments as StartupSettings;
      return _getPageRoute(
        routeName: settings.name,
        viewToShow: StartUpView(startupSettings: startupSettings),
      );
    ...

Any suggestions?


text:
Q: cart total in Django shows blank space I'm trying to get cart total sum of products in the html template, while the the total sum of particular products works fine, the cart total price/quantity shows blank spaces.
Models:
from django.db import models

import Accounts.models as accounts_models
import Products.models as products_models

class Order(models.Model):
    customer = models.ForeignKey(accounts_models.Customer, on_delete=models.SET_NULL, blank=True, null=True)
    date_ordered = models.DateTimeField(auto_now_add=True)
    complete = models.BooleanField(default=False)
    transaction_id = models.CharField(max_length=100, null=True)

    def __str__(self):
        return str(self.id)

    @property
    def get_cart_total(self):
        orderproducts = self.orderproduct_set.all()
        total = sum([product.get_total for product in orderproducts])
        return total

    @property
    def get_cart_products(self):
        orderproducts = self.orderproduct_set.all()
        total = sum([product.quantity for product in orderproducts])
        return total

class OrderProduct(models.Model):
    product = models.ForeignKey(products_models.Products, on_delete=models.SET_NULL, blank=True, null=True)
    order = models.ForeignKey(Order, on_delete=models.SET_NULL, blank=True, null=True)
    quantity = models.IntegerField(default=0, null=True, blank=True)
    date_added = models.DateTimeField(auto_now_add=True)

    @property
    def get_total(self):
        total = self.product.price * self.quantity
        return total

views:
def cart(request):

    if request.user.is_authenticated:
        customer = request.user.customer
        order, created = Order.objects.get_or_create(customer=customer, complete=False)
        items = order.orderproduct_set.all()
    else:
        items = []
    context = {'items': items}
    return render(request, 'cart.html', context)

html template:
                {% for item in items %}

                        {{ item.product.name }}
                        {{ item.quantity }}
                        ${{ item.product.price }}
                        ${{ item.get_total }}

                {% endfor %}

                    Total:
                    ${{ order.get_cart_total }}

How can I start showing the total numbers in the html template?

A: You didn't pass order in your cart view, here is updated view:
def cart(request):
    if request.user.is_authenticated:
        customer = request.user.customer
        order, created = Order.objects.get_or_create(customer=customer, complete=False)
        items = order.orderproduct_set.all()
    else:
        items = []
        order = None  # Add this line to handle the case when there is no order
    context = {'items': items, 'order': order}  # Add the order object to the context dictionary
    return render(request, 'cart.html', context)


text:
Q: Django displaying default photo next to each category Im new to Django and don't really know how to write the part of code. I have few categories under Class Offers, I would like to add default photo for each category, so while adding a new offer the default photo will be connected to the category
my Model of offer:
CATEGORY = (
    ("Babysitting", "Babysitting"),
    ("Housework", "Housework"),
    ("Private lessons", "Private lessons"),
    ("Agro", "Agro"),
)

class Offers(models.Model):
    category = models.CharField(choices=CATEGORY, max_length=20, null=True)

    description = models.CharField(max_length=255)
    paid_per_hr = models.IntegerField()
    created = models.DateTimeField(auto_now_add=True )
    updated = models.DateTimeField(auto_now_add=True)

i'm bit stuck with problem on how to assign the default photo different to each category
class AddOfferView(LoginRequiredMixin, View):
    def get(self, request):
        form = OfferForm()
        return render(request, 'offer.html', {'form': form})

I can add the new offer with default one phono but then each category has same photo.


text:
Q: Error while connecting remotely i m using sql server 2005 with service pack-2.
When I connect sql server with by registering the remote server with IP, username and password. I have done all the neccessary setting for connecting remotely "SQL Server 2005 Surface Area Configuration".
  i got following error while connection:
This version of Microsoft SQL Server Management Studio can only be used to connect to SQL Server 2000 and SQL Server 2005 servers. (ConnectionDlg)
Can you please provide me possible reasons for the above mentioned error.
Thanks,
Saurabh

A: I would also add that this can also happen if you are trying to connect to a lower version too!
I would also suggest checking which version of SQL 2005 you are attempting to connect to and make sure it is a RTM or higher, and not an older CTP release.
The other possibility is that there is another SQL Server instance (not 2000, or 2005) running on the IP that you are connecting to. Try connecting via server or instance name if possible.
Kev

A: Only reason for this can be if you are trying to connect to higher version of SQL Server. Please check again if it is SQL Server 2005 or 2008 you are trying to connect.
Here is similar problem and solution for it at sql-server-performance site
edit:- also if you have installed some version of SQL Server 2008 it may also break Management Studio.

A: Right - to get to the bottom of this I would check the version from the command prompt, from the machine experiencing the problem:
sqlcmd -Q "SELECT @@VERSION" -S myserver\myInstance -U myUserName -P myPassword

This will give you the version of SQL Server you are connecting to. 'sqlcmd' will run against old and new versions of SQL Server.
You can use the same technique, with different SQL to identify which server you are really connecting to, etc.


text:
Q: How to make removeattr button I want to do the following, on click it works.if 0 or 1 is clicked, the button is not-allowed save on a new load, if 2 is clicked, the default is saved on a new load
 $('table tr[value=0]').click(function() {
   $('#btn').attr('disabled', 'disabled');
             });
  $('#btn').prop('disabled', false);
   $('table tr[value=1]').click(function() {
   $('#btn').attr('disabled', 'disabled');
             });
   $('#btn').prop('disabled', false);
    $('table tr[value=2]').click(function() {
    $('#btn').attr('disabled',false );
             });

i tried with this jQuery('#btn').prop('disabled', false); or jQuery('#btn').prop('disabled', true);
but on reload it gives me false and true, on click I want to save the value after reloading


text:
Q: Can't get simple CosmosDB query to work via Node.js - but works fine via Azure's Query Explorer I'm using CosmosDB (node.js via documentdb api) - partitioned on 'id' only.
A simple query (SELECT * FROM c WHERE c.akunaCustomer = "xyz") works fine from Azure Query Explorer, but my node.js code gives the following error - running the identical query.
code: 400, BadRequest, Cross partition query is required but disabled. Please set x-ms-documentdb-query-enablecrosspartition to true, specify x-ms-documentdb-partitionkey, or revise your query to avoid this exception.

Here's my code:

var documentClient = require("documentdb").DocumentClient;
var config = require("./config");

var client = new documentClient(config.endpoint, {"masterKey": config.primaryKey});

var databaseUrl = `dbs/${config.database.id}`;
var collectionUrl = `${databaseUrl}/colls/${config.collection.id}`;

client.queryDocuments(collectionUrl,
    'SELECT * FROM c WHERE c.akunaCustomer = "xyz"'
    ).toArray((err, results) => {
        if(err) {
            console.log(err);
        }
         else {
            for (var queryResult of results) {
                let resultString = JSON.stringify(queryResult);
                console.log(`Query: ${resultString}`);
            }
        }
    });

Clearly I'm missing something. :-(  Any help would be appreciated.

A: The error message is quite clear: because your query spans multiple partitions, you need to set enableCrossPartitionQuery option to true:
client.queryDocuments(
    collectionUrl,
    'SELECT * FROM c WHERE c.akunaCustomer = "xyz"',
    { enableCrossPartitionQuery: true }
)


text:
Q: Set items in table java web scraping Okey so my problem is next: I use web scraping to take some data from web page IMDB in this case, that data is titles of movies, and I already tried to print it in console and that works fine. My problem is that I can not save that titles in my table columns, I put all needed codes for this problem, and I cant find where I made mistake and why titles wont show in table columns. At the and, user need to pick one title and that title need to be stored in text field. Have someone any idea, please?
I have table:
TableColumn izborAuta = new TableColumn("Izbor auta");
TableColumn lokacijaPreuzimanja = new TableColumn("Lokacija
preuzimanja");
TableColumn lokacijaVracanja = new TableColumn("Lokacija Vracanja");
TableColumn cena = new TableColumn("Cena");

I have this code to setup columns:
izborAuta.setCellValueFactory(new PropertyValueFactory<Vozila, String>
("izborAuta"));
lokacijaPreuzimanja.setCellValueFactory(new
PropertyValueFactory<Vozila, String>("lokacijaPreuzimanja"));
lokacijaVracanja.setCellValueFactory(new
PropertyValueFactory<Vozila, String>("lokacijaVracanja"));
cena.setCellValueFactory(new PropertyValueFactory<Vozila, String>
("cena"));
tableView.setItems(Baza.baza.prikazBaze());
tableView.getColumns().addAll(izborAuta, lokacijaPreuzimanja,
lokacijaVracanja, cena);

I have this code, so when I pick one item from table that item need to be stored in textField:
tableView.setOnMouseClicked((e) -> {
    Vozila v = (Vozila)
    tableView.getSelectionModel().getSelectedItem();
    txIzborAuta.setText(v.getIzborAuta());
    txLokacijaPreuzimanja.setText(v.getLokacijaPreuzimanja());
    txLokacijaVracanja.setText(v.getLokacijaVracanja());
    txCena.setText(v.getCena());
});

And at the end I use web scraping to save items in table:
Document doc = Jsoup.connect("https://www.imdb.com/chart/top?
ref_=nv_mv_250").get();
Elements elems = doc.select("table.chart.full-width");
for (Element e : elems) {
    String izborAuta = e.select(".titleColumn").text();
    String lokacijaPreuzimanja = e.select(".titleColumn").text();
    String lokacijaVracanja = e.select(".titleColumn").text();
    String cena = e.select(".titleColumn").text();
    Vozila v = new Vozila();
    v.setIzborAuta(izborAuta);
    v.setLokacijaPreuzimanja(lokacijaPreuzimanja);
    v.setLokacijaVracanja(lokacijaVracanja);
    v.setCena(cena + " " + "RSD");
    Baza.insertVozila(v);
}


text:
Q: Mouse hover CSS Position absolute div display on another TD I am using HTML table. My goal simple. I am trying to make a menu when mouse hover open div open. But in this implement in table.
When I mouse hover on Telephone: element as soon as below element
...
 visible on right side  element (using z-index) as position absolute.
View JsFiddle
HTML:

      Telephone:

My Dashboard

My Dashboard

My Dashboard

My Dashboard

    555 77 854

Using CSS, jquery.

A: You can do this in CSS alone using the :hover and sibling selectors:
table span:hover + .secondary_menu {
    display: block;
}

Updated fiddle

A: check this below code as per you requested for demo

$(".maincontent").hover(function() {
    $('.secondary_menu').addClass(".active");
}, function() {
    $('.secondary_menu').removeClass(".active");
});
table,
tr td:last-child {
  position: relative;
}
td > div {
  position: absolute;
  opacity: 0;
  transition: opacity 0.5s;
}
tr:hover td > div {
  opacity: 1;
}
tbody tr td:first-child:before {
  content: '';
  display: block;
  background: rgba(0, 0, 0, 0);
  transition: background 0.5s;
}
tbody tr:hover td:first-child:before {
  background: rgba(0, 0, 0, 0.6);
}
td > div > a {

  background: #1DE9B6;
  color: #FFF;
  text-decoration: none;
  border-radius: 2px;
  padding: 3px;
  transition: color 0.5s, background 0.5s;
  margin-left : 10px;
}
/*Not important -- example only*/

td > div > a:hover {
  background: #A7FFEB;
  color: #000;
}
table {
  border-collapse: collapse;
  border: solid 1px #EEE;
}
th,
td {
  border: solid 1px #EEE;
  transition: background 0.5s;
}
tr:nth-child(even) {
  background: #E3F2FD;
}

table  tr  td {
  width : 50%;
}

.secondary_menu li{
  width : 300px;
  list-style-type : none;
}

.secondary_menu{
  display : none;
  width : 70px;
}

.maincontent:hover .secondary_menu {
  display : block !important;
  width : 70px;
}

.maincontent{
  padding : 5px;
  cursor: pointer;
}
.active{display : block !important;}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>

        Telephone:

My Dashboard

My Dashboard

My Dashboard

My Dashboard

989898989898989898989898

        Telephone:

My Dashboard

My Dashboard

My Dashboard

My Dashboard

989898989898989898989898

A: You can use the sibling selector to change the display of the secondary_menu when the span is hover
span:hover+.secondary_menu {
  display: block;
}

Here is the example http://jsfiddle.net/GchWZ/214/


text:
Q: How to play twitch.tv live streaming video with native control in iOS? I like to play twitch.tv live streaming videos into my mobile application. currently I am playing with webview and iFrame.
Is there any way to play the live steam with native controls like AVPlayer.


text:
Q: array in a separate class other than main method/class I keep getting this error, its about needing braces after the array decleration.

I do not know what to do about this. I want to make an array that is not in my main method. I want the array to be supertype populated with subclass.
Here is my code
public class ArrayTest {

Employee [] employees = new Manager[2];
employees[0]= new Manager("Thomas", "Cummings");

}

public class Manager extends Employee{
private int employees;

public Manager() {
    super();
    employees = 0;
}

public Manager(int employees) {
    super();
    this.employees = employees;
}

public Manager(String f_name, String l_name) {
    super(f_name, l_name);
}

public Manager(String f_name, String l_name, int employees) {
    super(f_name, l_name);
    this.employees = employees;
}

public int getEmployees() {
    return employees;
}

public void setEmployees(int employees) {
    this.employees = employees;
}

public void setManager(String f_name, String l_name){
    this.setF_name(f_name);
    this.setL_name(l_name);
}

public void setManager(String f_name, String l_name, int employees){
    this.setF_name(f_name);
    this.setL_name(l_name);
    this.employees = employees;
}
@Override
public String toString(){
    return "\nName " + getF_name() + " " + getL_name() +
            "\nEmployee ID " + getEmp_id() +
            "\nNum of employees " + getEmployees();
}
}

public class Employee {

private String f_name, l_name;
private static long emp_id = 001;

public Employee(){
    f_name = "";
    l_name = "";
    emp_id ++;
}
public Employee(String f_name, String l_name) {
    this.f_name = f_name;
    this.l_name = l_name;
    emp_id ++;
}
public String getF_name() {
    return f_name;
}
public void setF_name(String f_name) {
    this.f_name = f_name;
}
public String getL_name() {
    return l_name;
}
public void setL_name(String l_name) {
    this.l_name = l_name;
}
public long getEmp_id() {
    return emp_id;
}
public void setEmp_id(long emp_id) {
    Employee.emp_id = emp_id;
}

public String toString(){
    return "\nName " + getF_name() + " " + getL_name() +
            "\nEmployee ID " + getEmp_id();
}
}

A: The reason of error is the following statement:
employees[0]= new Manager("Thomas", "Cummings");

as you cannot put executable statements outside of code blocks(methods, blocks, constructors) in a java class.
One way to resolve this problem is by moving the initialization statement in a constructor:
public class ArrayTest {

Employee [] employees = new Manager[2];

public ArrayTest() {
    employees[0]= new Manager("Thomas", "Cummings");
}

}

A: employees[0]= new Manager("Thomas", "Cummings");

this is an statement which needs to be placed in proper executable block (method, constructor, initialization block)


text:
Q: bin\debug versus obj\debug: What's the difference? What's the difference between bin\debug and obj\debug in a Visual Studio project. (VB.NET in my case). I've been poking around on Google and bin\debug seems to hold the "official" compiled code (in spite of "debug" in the filename). If that's true, are the contents of obj\debug important to the developer?

A: Both directories are used by Visual Studio when you build your solution.
The obj directory contains intermediate files generated from your source code. They are building blocks that are used in order to produce the final executable. This directory also acts as a cache between builds and allows you to do incremental compilation. Everything doesn't necessarily have to be recreated every time you do a build, which can speed up the build process.
The bin directory contains the final executable generated during the build. These are the files that you would typically give to a user.
Both directories contains subdirectories, one for each of your solution configurations as you build them. By default these are called Debug and Release, but you can create any number of configurations from within Visual Studio's configuration manager. These allow you to have different configurations depending on the kind of build that you want to do.
They are important in the sense that Visual Studio has to store the files from the build somewhere. But you can safely remove them if you don't want them. They will be recreated when needed.


text:
Q: Use assertz while within a clause within swi-prolog I'm trying to make a modified version of the expert system example within swi-prolog.org. I'm trying to modify it to be able to do:
good_pet(X) :- bird(X), small(X).
good_pet(X) :- cuddly(X), small(X).
good_pet(X) :- cuddly(X), yellow(X).

Without the program reasking if small() or cuddly is true.
I tried doing:
:- dynamic ([small/1, cuddly/1 ]).
good_pet(X) :- bird(X), assertz(small(X)).
good_pet(X) :- bird(X), small(X).
good_pet(X) :- assertz(cuddly(X)), assertz(small(X)).
good_pet(X) :- cuddly(X), small(X).
good_pet(X) :- cuddly(X), yellow(X).

As expained here.
But that ends up giving this error:
No permission to access private_procedure `assertz/1'
In:
   [4] clause(assertz(cuddly(tweety)),_1306)
   [3] prove(assertz(cuddly(tweety))) at  line 11
   [2] prove((assertz(...),assertz(...))) at  line 8
   [1] prove(good_pet(tweety)) at  line 12

Is there a solution to this error or any another way to save the result of the asked questions?

A: The meta-interpreter that you are trying to use does not take into account clauses that call built-in predicates such as assertz/1. Try:
prove(true) :- !.
prove((B, Bs)) :- !,
    prove(B),
    prove(Bs).
prove(H) :-
    predicate_property(H, built_in),
    !,
    call(H).
prove(H) :-
    clause(H, B),
    prove(B).
prove(H) :-
    askable(H),
    writeln(H),
    read(Answer),
    Answer == yes.


text:
Q: How state updates to existing instances/sessions are generally done? This is a very broad question, but maybe someone has a worthwhile response.
There is a general synchronization issue that often has to be solved, but always seems to be difficult. Here's an example:
I was working on a remote system and had an ssh-connection and a remote desktop open at the same time for some reason. I happened to create a file on the desktop in shell, and of course it also appeared on the remote desktop view.
For this to happen one of two things must take place:
1) the desktop session must be constantly polling the filesystem for changes. Costly, ugly, and of course unlikely.
2) The system knows that this change made by the ssh-session requires action on the remote desktop side, and updates the view. This is neat and elegant in a sense, but maintaining an accurate capability to decide when any action performed by any process in the system should cause this update is horrendously complex.
In this case the culprit is the linux kernel (or Desktop environment?) and I presume what it does is the option 2). It's also very common to encounter small bugs and issues that are clearly the result of this kind of issue not being taken care of.
This kind of a problem where any of multiple changes to a common resource can have an effect on other instances, but determining when is very tedious pops up in many places.
Is there a general approach to this?
Do we form separate trackers that know how the instance is sensitive to changes and that object can be interrogated?
Does every change to the resource (filesystem in this case) include a stage of making sure this kind of stuff takes place? If so, that too must compound to be a massive ordeal.
Does someone happen to know how linux handles this specific example case?

A: This is the curse of not having configurable physics.
Cause must happen before effect, but how closely these things appear, or even when they appear depends entirely upon where you are, your distance from the activity, and how time is passing for you.
And because we are talking about abstract process and logic (which is a very messy topology, not something as clean cut as space-time) it is hard to get a reasonable grasp on what distance and time even are.
Polling
Polling is certainly an option. While not necessarily the quickest option it is possible that any message about a state change simply has not reached your program yet. It may be that you can more quickly access the updated value, than be informed of the event that caused the update. You might not even be informed...
Events
Events are another solution. Intuitively when the state changes, the event should be sent out. If you are listening for it, then you can receive it and react.
The problem is that you cannot hear something before you register a listener for it, which means you have no idea about the state of the system now, unless registration also passes along some sort of state of the system event, which could be huge....
The other problems are:

*

*Perhaps a listener before you cancels the event so it is never received,

*perhaps the event takes such a long time to arrive it is marked as old and discarded,

*perhaps so many events are happening that the listener starts dropping them,

*perhaps the events arrive out of order mixing up what the systems real state is,

*perhaps the sender never sends the event but changed the state anyway...

Transaction Logs
Also sometimes called Event Logs, Event Streams, State Logs, Audit Trails, Block Chain, Raft Logs, etc...
These solutions require state changes to be recorded in a log first.

*

*At some point the values recorded in the log are acknowledged as being the "new" state.

*If a record proposes a state change that is illegal, its not acknowledged as correct, and is ignored.

*Because the log is serial there is a definitive order to the change in state.

*If the message never arrives that is fine, poll the log and resume reading from the last event previously processed, even if the process stops listening for a long time.

*If events arrive late, are dropped, or arrive out of order all is well poll the log for the missing events.

*The state of the system can be rebuilt to a specific point in time, even an historic point.

*When two processes wish to discuss state everyone can agree on a time and discuss the state in a synchronised way.

The down side is that the authority of state, moves from the logical models (which are now just views) into the log entries.


text:
Q: Route AngularJS app without changing URI I am trying to create an Angular API which should be able to be integrated on any webpage. I have a frontApp using AngularJS and a backend which uses Laravel 4.
The problem is that my routing look like this at the moment :
angular.module('FrontApp').config(['$routeProvider', function ($routeProvider) {
    $routeProvider
        .when('/home', {
            templateUrl: 'views/home.html',
            controller: 'HomeCtrl'
        })
        .when('/login', {
            templateUrl: 'views/login.html',
            controller: 'LoginCtrl'
        })
        .when('/register', {
            templateUrl: 'views/register.html',
            controller: 'RegisterCtrl'
        })
        .when('/members', {
            templateUrl: 'views/main.html',
            controller: 'MainCtrl'
        })
        .when('/apinotfound', {
            templateUrl: 'views/api.html'
        })
        .otherwise({
            redirectTo: '/login'
        });
}]);

But since my App will be integrated on a webpage whose URI can not changed, I can not use this routing system. I was wondering if a trick would be possible, to keep those routes in a variable maybe, and then route my App without changing the URI of the page?


text:
Q: C++ It's not reading from the file back into the dynamic struct so you can adopt a pet (kind of buggy right now since it doesn't read in the value)
In the file i'll see it turn into a 1 from a 0; which means it is true. and therefore it should say adopted.
is this the correct way to read in a bool? The problem is in the read function, my problem is that the
read >>
#include <iostream>
#include <cctype>
#include <cstring>
#include <fstream>
using namespace std;

const int TEMP_SIZE = 250;

struct animal
{
    char *name;
    char *breed;
    float age;
    float weight;
    char *desc;
    bool adopted;
//we generate this
    int ID;
};

struct family
{
    char *host;
    char *address;
    int numDogs;
};

class petAdoption
{
    public:
    //petAdoption();
    //~petAdoption();
    void enroll(animal pet[], int & count);
    void read(animal pet[], int & count);
    void display(animal pet[], int & count);
    void adoptPet(animal pet[], int & count);
    void getNum(int & count);
};

void petAdoption::enroll(animal pet[], int & count)
{
//name Dynamic array 1;
    char temp[TEMP_SIZE];
    cout << "Please your pet's name: ";
    cin.get(temp, TEMP_SIZE);
    cin.ignore(100, '\n');
    pet[count-1].name = new char[strlen(temp)];
    strcpy(pet[count-1].name, temp);
//breed Dynamic array 2;
    cout << "Please your pet's breed: ";
    cin.get(temp, TEMP_SIZE);
    cin.ignore(100, '\n');
    pet[count-1].breed = new char[strlen(temp)];
    strcpy(pet[count-1].breed, temp);
//desc Dynamic array 3;
    cout << "Please a desc of your pet: ";
    cin.get(temp, TEMP_SIZE);
    cin.ignore(100, '\n');
    pet[count-1].desc = new char[strlen(temp)];
    strcpy(pet[count-1].desc, temp);
//not adopted
    pet[count-1].adopted = false;
    ofstream write;

    write.open("pets.txt", ios::app);
        write << pet[count-1].name << '\n';
    write.close();
    write.open(pet[count-1].name);
        write << pet[count-1].name << '\n'
        << pet[count-1].breed << '\n'
        << pet[count-1].desc << '\n'
        << pet[count-1].adopted << '\n';
    write.close();
}

//This method basically, allocates memory for the array.
void petAdoption::getNum(int & count)
{
    ifstream read;
    char temp[TEMP_SIZE];
    read.open("pets.txt");
        if(!read)
        {
            cout << "error 1" << endl;
            count = 1;
        }
        else{
            while(!read.eof())
            {
                read.getline(temp, TEMP_SIZE);
                count = ++count;
            }
        }
    read.close();
}

void petAdoption::read(animal pet[], int & count)
{
    ifstream read;
    char temp[TEMP_SIZE];

//read in the names
    int k = 0;
    read.open("pets.txt");
    if(!read)
    {
        cout << "There's No pets.txt file! (Ignore this!)" <<endl;
    }
    else
    {
        while(!read.eof())
        {
            read.getline(temp, TEMP_SIZE);
            pet[k].name = new char[strlen(temp)+1];
            strcpy(pet[k].name, temp);
        ++k;
        }
    }
    read.close();

    for (int i = 0; i < count-1; ++i)
    {
        read.open(pet[i].name);
            if(!read)
            {
                cout << "error 2" << endl;
            }
            else{
                while(!read.eof())
                {
        //name
                    read.getline(temp, TEMP_SIZE);
                    pet[i].name = new char[strlen(temp)+1];
                    strcpy(pet[i].name, temp);
        //breed
                    read.getline(temp, TEMP_SIZE);
                    pet[i].breed = new char[strlen(temp)+1];
                    strcpy(pet[i].breed, temp);
        //desc
                    read.getline(temp, TEMP_SIZE);
                    read.ignore(100, '\n');
                    pet[i].desc = new char[strlen(temp)+1];
                    strcpy(pet[i].desc, temp);

                    read >> pet[i].adopted;
                cout << i << endl;
                }
            }
        read.close();
    }
}

void petAdoption::display(animal pet[], int & count)
{
    for (int i = 0; i < count-1; ++i){
        cout << "Pet id = " << i << '\n' << endl;
        cout << pet[i].name << '\n' << pet[i].breed << '\n' << pet[i].desc << '\n';
        cout << pet[i].adopted << endl;
        if (pet[i].adopted == false){
            cout << "Not adopted" << '\n' << endl;
        }
        if (pet[i].adopted == true){
            cout << "Adopted" << '\n' << endl;
        }
    }
}

void petAdoption::adoptPet(animal pet[], int & count)
{
    int adoptID;
    cout << "Which pet would you like to adopt? (Please enter the ID, EG: 2 or 5): ";
    cin >> adoptID;
    cin.ignore(100, '\n');

    pet[adoptID].adopted = true;
    cout << pet[adoptID].adopted << endl;

    ofstream write;
    for (int i = 0; i < count; ++i){
        write.open(pet[i].name);
            write << pet[i].name << '\n'
            << pet[i].breed << '\n'
            << pet[i].desc << '\n'
            << pet[i].adopted << '\n';
        write.close();
    }
}

int main()
{
//When starting the program, we read in from the text files first
//and then we count how many animals we have had in the shelter
//and we use that as a base to dynamically allocate the structs
    petAdoption adopt;
    char again;
    int choice;
    do {
        int count = 0;
        adopt.getNum(count);
        animal *pet;
        pet = new animal[count];
        adopt.read(pet, count);
        cout << "~~~~~~~~~~~~~~~~~~MENU~~~~~~~~~~~~~~~~~~" << endl;
        cout << "1) Enroll a pet" << endl;
        cout << "2) Display pets" << endl;
        cout << "3) Adopt a pet" << endl;
        cout << "Please make your selection (1-3): ";
        cin >> choice;
        cin.ignore(100,'\n');
        if (1 == choice){
            adopt.read(pet, count);
            adopt.enroll(pet, count);
        }
        if (2 == choice){
            adopt.read(pet, count);
            adopt.display(pet, count);
        }
        if (3 == choice){
            adopt.read(pet, count);
            adopt.adoptPet(pet, count);
        }
        cout << "Would you like to try again? (y/n): ";
        cin >> again;
        cin.ignore(100,'\n');
    } while ('Y' == toupper(again));
}

A: It seems problem is in your logic, i have fixed few things in you code and it is working take a look:
Things I fixed are:
 - enroll(animal pet[], int & count)
 - getNum(int & count)
 - read(animal pet[], int & count)
 - display(animal pet[], int & count)
#include <iostream>
#include <cctype>
#include <cstring>
#include <fstream>
using namespace std;

const int TEMP_SIZE = 250;

struct animal
{
    char *name;
    char *breed;
    float age;
    float weight;
    char *desc;
    bool adopted;
//we generate this
    int ID;
};

struct family
{
    char *host;
    char *address;
    int numDogs;
};

class petAdoption
{
    public:
    //petAdoption();
    //~petAdoption();
    void enroll(animal pet[], int & count);
    void read(animal pet[], int & count);
    void display(animal pet[], int & count);
    void adoptPet(animal pet[], int & count);
    void getNum(int & count);
};

void petAdoption::enroll(animal pet[], int & count)
{
//name Dynamic array 1;
    char temp[TEMP_SIZE];
    cout << "Please your pet's name: ";
    cin.get(temp, TEMP_SIZE);
    cin.ignore(100, '\n');
    pet[count-1].name = new char[strlen(temp)];
    strcpy(pet[count-1].name, temp);
//breed Dynamic array 2;
    cout << "Please your pet's breed: ";
    cin.get(temp, TEMP_SIZE);
    cin.ignore(100, '\n');
    pet[count-1].breed = new char[strlen(temp)];
    strcpy(pet[count-1].breed, temp);
//desc Dynamic array 3;
    cout << "Please a desc of your pet: ";
    cin.get(temp, TEMP_SIZE);
    cin.ignore(100, '\n');
    pet[count-1].desc = new char[strlen(temp)];
    strcpy(pet[count-1].desc, temp);
//not adopted
    pet[count-1].adopted = false;
    ofstream write;

    write.open("pets.txt", ios::beg | ios::app);
    write << pet[count-1].name << '\n';
    write << pet[count-1].breed << '\n';
    write << pet[count-1].desc << '\n';
    write << pet[count-1].adopted << '\n';
    write.close();
}

//This method basically, allocates memory for the array.
void petAdoption::getNum(int & count)
{
    ifstream read;
    char temp[TEMP_SIZE];
    int count_temp = 0;
    read.open("pets.txt");

    while(!read.eof())
    {
        read.getline(temp, TEMP_SIZE);
        count_temp++;
        if (count_temp == 4){
           count++;
           count_temp = 0;
        }
    }

    read.close();
}

void petAdoption::read(animal pet[], int & count)
{
    ifstream read;
    char temp[TEMP_SIZE];

//read in the names
    int k = 0, i =0;
    read.open("pets.txt");

    while(read.good()){
        if (i < count){
    //name
            read.getline(temp, TEMP_SIZE);
            pet[i].name = new char[strlen(temp)+1];
            strcpy(pet[i].name, temp);
    //breed
            read.getline(temp, TEMP_SIZE);
            pet[i].breed = new char[strlen(temp)+1];
            strcpy(pet[i].breed, temp);
    //desc
            read.getline(temp, TEMP_SIZE);
            pet[i].desc = new char[strlen(temp)+1];
            strcpy(pet[i].desc, temp);

            read.getline(temp, TEMP_SIZE);
            if (strcmp(temp,"0") == 0){
                pet[i].adopted = true;
            }else{
                pet[i].adopted = false;
            }
        }else{
          cout << i << endl;
          break;
        }

        i++;
    }

        read.close();

}

void petAdoption::display(animal pet[], int & count)
{
    for (int i = 0; i < count; i++){
        cout << "Pet id = " << i << '\n' << endl;
        cout << pet[i].name << '\n' << pet[i].breed << '\n' << pet[i].desc << '\n';
        cout << pet[i].adopted << endl;
        if (pet[i].adopted == false){
            cout << "Not adopted" << '\n' << endl;
        }else{
            cout << "Adopted" << '\n' << endl;
        }
    }
}

void petAdoption::adoptPet(animal pet[], int & count)
{
    int adoptID;
    cout << "Which pet would you like to adopt? (Please enter the ID, EG: 2 or 5): ";
    cin >> adoptID;
    cin.ignore(100, '\n');

    pet[adoptID].adopted = true;
    cout << pet[adoptID].adopted << endl;

    ofstream write;
    write.open("pets.txt", ios::beg);

    for (int i = 0; i < count; ++i){
            write << pet[i].name << '\n'
            << pet[i].breed << '\n'
            << pet[i].desc << '\n'
            << pet[i].adopted<<'\n';
    }
        write.close();
}


text:
Q: Which of these is more efficient to choose a function? So lets say I have 2 functions to choose from based on whether number is even or odd. I came up with this:
(void (*[])()){f1 ,f2}[n%2]();.
Is it more or less efficient than simply:
n%2 ? f2() : f1();

A: Profile it; most likely too small to measure.
Assuming a naive compiler, the second will be a lot shorter to execute. But the first is written terribly; could be squashed down to
((n1&1) ? f1 : f2)();

now it's pretty much a toss-up. the first generates something like
test al, 1
jz +3
call f1
jmp +1
call f2

and the second something like
test al, 1
jmp +3
lea  rcx, [f1]
jmp +1
lea  rcx, [f2]
call rcx

but a good optimizer could flatten that down to
lea  rcx, [f1]
test al, 1
cmovcc rcx, f2
call rcx

while all this is true; the initial statement applies. It's most likely too small to measure.
Additional question in comments involving "easier to expand"; well yes. After a surprisingly short number of functions, the array lookup becomes faster. I'm skeptical of things and would not write the array inline but somebody could come along and prove me wrong. If there's more than two I would write
static  void (*dispatch_table[])() = {f1 ,f2};
dispatch_table[n % (sizeof(dispatch_table) / sizeof(dispatch_table[0]))]();

This complex mod expression compiles to a compile-time constant; which lets the compiler optimize out the % to something more performant; it's written as so so that adding more entries doesn't require changing the second argument to % when adding to the array.
As is being pointed out in comments I didn't handle n negative. Most RNG sources don't generate negative numbers.

A: Godbolt to the rescue (64-bit Clang 11.0 with -O3 optimizations):  https://godbolt.org/z/MWjPnn
First implementation:
void impl1(int n)
{
    (void (*[])()){evenfunc ,oddfunc}[n%2]();
}

    mov     qword ptr [rsp - 16], offset evenfunc()
    mov     qword ptr [rsp - 8], offset oddfunc()
    mov     eax, edi
    shr     eax, 31
    add     eax, edi
    and     eax, -2
    sub     edi, eax
    movsxd  rax, edi
    jmp     qword ptr [rsp + 8*rax - 16]    # TAILCALL

Second implementation:
void impl2(int n)
{
    n%2 ? oddfunc() : evenfunc();
}

        test    dil, 1
        jne     .LBB1_1
        jmp     evenfunc()                    # TAILCALL
.LBB1_1:
        jmp     oddfunc()                     # TAILCALL


text:
Q: How to use `log_loss` in `GridSearchCV` with multi-class labels in Scikit-Learn (sklearn)? I'm trying to use the log_loss argument in the scoring parameter of GridSearchCV to tune this multi-class (6 classes) classifier. I don't understand how to give it a label parameter.  Even if I gave it sklearn.metrics.log_loss, it would change for each iteration in the cross-validation so I don't understand how to give it the labels parameter?
I'm using Python v3.6 and Scikit-Learn v0.18.1
How can I use GridSearchCV with log_loss with multi-class model tuning?
My class representation:
1    31
2    18
3    28
4    19
5    17
6    22
Name: encoding, dtype: int64

My code:
param_test = {"criterion": ["friedman_mse", "mse", "mae"]}
gsearch_gbc = GridSearchCV(estimator = GradientBoostingClassifier(n_estimators=10),
                        param_grid = param_test, scoring="log_loss", n_jobs=1, iid=False, cv=cv_indices)
gsearch_gbc.fit(df_attr, Se_targets)

Here's the tail end of the error and the full one is here https://pastebin.com/1CshpEBN:
ValueError: y_true contains only one label (1). Please provide the true labels explicitly through the labels argument.

UPDATE:
Just use this to make the scorer based on based on @Grr
log_loss_build = lambda y: metrics.make_scorer(metrics.log_loss, greater_is_better=False, needs_proba=True, labels=sorted(np.unique(y)))

A: my assumption is that somehow your data split has only one class label in y_true. while this seems unlikely based on the distribution you posted, i guess it is possible. While i havent run into this before it seems that in [sklearn.metrics.log_loss](http://scikit-learn.org/stable/modules/generated/sklearn.metrics.log_loss.html) the label argument is expected if the labels are all the same. The wording of this section of the documentation also makes it seem as if the method imputes a binary classification if labels is not passed.
Now as you correctly assume you should pass log_loss as scorer=sklearn.metrics.log_loss(labels=your_labels)

A: You can simply specify "neg_log_loss_scorer" (or "log_loss_scorer") in older versions which will use the negative log loss.


text:
Q: Negation - Cauchy sequence Suppose that $(x_i)_{i \geq 1}$ is not a Cauchy sequence of real numbers.
How to prove that there exist $\varepsilon >0 $ and an increasing sequence $(i_n)$ of indices such that
$$
|x_{i_{n+1}}-x_{i_n}|\geq \varepsilon
$$
for any $n \geq 1$?


text:
Q: Reading from URL, store data as double? public static void getClientUpdate() {
    try {
        String inputLine;
        double version = 0;
        URL url = new URL("http://ds-forums.com/client/version.txt");
        BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
        while ((inputLine = in.readLine()) != null)
            System.out.println(inputLine);
        in.close();
        version = inputLine;
        System.out.println("The version is: " + version);
    } catch (Exception x) {
        System.out.println(x);
    }
}

This is going to sound really stupid but I have a txt file that contains a double and I want to save it as a double. Instead it wants a string.  Am I doing this wrong or is there just a few steps I need to add?

A: Well, you need to parse the string into a double. For example, using Double.parseDouble. I should point out that a version string doesn't sound like a great idea to store as a double... you might want to consider using BigDecimal instead. Doubles are generally better for "real world" physical values such as distances - not "artificial" values such as version numbers. I don't think I'd even use BigDecimal to be honest... it's not like version numbers are usually treated in the same way as "normal" numbers.
Have you considered creating your own type to represent a version number?

A: You can parse the string you obtained: Double.parseDouble(inputLine.trim())
But, in fact, I don't think versions should be doubles. In your particular case, today, this might be the case, but it can easily change. Here are some examples of popular "versionings", that cannot be represented as doubles:

3.0.5
  2.1.GA
  1.5-SNAPSHOT
  0.8b

So, I'd suggest leaving this a string.

A: Double.parseDouble(string) is what you're after.


text:
Q: how to fix my Metric/Imperial unit conversion project in Javascript i am trying to build a solo project in javascript. I am having trouble to display a function when an number input is submitted.
this is my HTML code

Metric/Imperial unit conversion

    <form>
      <input type="number" name="input" id="input1">
    <input type="submit" onclick="meterFeet()">
    </form>

Length (Meter/Feet)

and this is my javascript code
let miucn = document.getElementById("input1");

function meterFeet() {
  document.getElementById("p-l1").textContent =
    miucn +
    " meters = " +
    (miucn * 3.281).toFixed(3) +
    " feet | " +
    miucn +
    " feet =" +
    (miucn / 3.281).toFixed(3) +
    " meters";
}

A: I made some small fixes in your code.

*

*change input type from submit to button

*put (document.getElementById("input1").value) inside the function

*parseInt() the input value

function meterFeet() {
  let miucn = parseInt(document.getElementById("input1").value);

  document.getElementById("p-l1").textContent =
    miucn +
    " meters = " +
    (miucn * 3.281).toFixed(3) +
    " feet | " +
    miucn +
    " feet =" +
    (miucn / 3.281).toFixed(3) +
    " meters";
  return false;
}

Metric/Imperial unit conversion

    <form>
      <input type="number" name="input" id="input1">
      <input type="button" onclick="meterFeet()" value="Submit">
    </form>

Length (Meter/Feet)


text:
Q: get the string after the searching for another string I have multiple processes running as below:
User 18870     1  1 09:44 ?        00:03:11 java -DENV_SYSTEM_DETAILS=linux-gnu2.6.32 -DENV_PROJECT_NAME=TEST -DENV__APP_PATH=/opt/enterprise/V2.0 -DENV_DATABASE_PATH=/opt/ORACLE11G -Dswing.aatext=true -Xms512m -Xmx1024m -XX:PermSize=64m -XX:MaxPermSize=128m -XX:+OptimizeStringConcat -DsuppressSwingDropSupport=true  -Number 1234 -c 1234-SM
User 18871     1  1 09:44 ?        00:03:11 java -DENV_SYSTEM_DETAILS=linux-gnu2.6.32 -DENV_PROJECT_NAME=TEST -DENV__APP_PATH=/opt/enterprise/V2.0 -DENV_DATABASE_PATH=/opt/ORACLE11G -Dswing.aatext=true -Xms512m -Xmx1024m -XX:PermSize=64m -XX:MaxPermSize=128m -XX:+OptimizeStringConcat -DsuppressSwingDropSupport=true  -Number 1264 -c 1264-SM
User 18872     1  1 09:44 ?        00:03:11 java -DENV_SYSTEM_DETAILS=linux-gnu2.6.32 -DENV_PROJECT_NAME=TEST -DENV__APP_PATH=/opt/enterprise/V2.0 -DENV_DATABASE_PATH=/opt/ORACLE11G -Dswing.aatext=true -Xms512m -Xmx1024m -XX:PermSize=64m -XX:MaxPermSize=128m -XX:+OptimizeStringConcat -DsuppressSwingDropSupport=true  -Number 1634 -c 1634-SM
User 18873     1  1 09:44 ?        00:03:11 java -DENV_SYSTEM_DETAILS=linux-gnu2.6.32 -DENV_PROJECT_NAME=TEST -DENV__APP_PATH=/opt/enterprise/V2.0 -DENV_DATABASE_PATH=/opt/ORACLE11G -Dswing.aatext=true -Xms512m -Xmx1024m -XX:PermSize=64m -XX:MaxPermSize=128m -XX:+OptimizeStringConcat -DsuppressSwingDropSupport=true  -Number 2334 -c 2334-SM

I would like to get output of only -Number 1234, the number differs from process to process. So, I need output something like below
-Number 1234
-Number 1264
-Number 1634
-Number 2334

Or with out number would be more better
1234
1264
1634
2334

A: Using awk
awk '{print $21}'

Where $21 is the position where your expected output is located having in mind that the default delimiter is a space.
$ echo "User 18870     1  1 09:44 ?        00:03:11 java -DENV_SYSTEM_DETAILS=linux-gnu2.6.32 -DENV_PROJECT_NAME=TEST -DENV__APP_PATH=/opt/enterprise/V2.0 -DENV_DATABASE_PATH=/opt/ORACLE11G -Dswing.aatext=true -Xms512m -Xmx1024m -XX:PermSize=64m -XX:MaxPermSize=128m -XX:+OptimizeStringConcat -DsuppressSwingDropSupport=true  -Number 1234 -c 1234-SM" | awk '{print $21}'
1234

A: A safer and easier solution would possibly be to use the filtering capabilities provided by the tool you are using for listing processes.
That said, using sed, with an eye to portability and trying to minimize false positives, you can pipe your text through this:
sed -n -e 's/.*[[:blank:]]\{1,\}-Number[[:blank:]]\{1,\}\([0123456789]\{1,\}\).*/\1/p'

When a line includes one or more blank characters followed by the literal -Number followed by one or more blank characters followed by one or more digits, the whole line is replaced with the captured sequence of digits (the part enclosed in \( \)) and the result is printed.
Note that, if the above sequence is repeated more than once in a line, only the first number is printed.
A more concise AWK alternative, assuming that -Number and the following sequence of digits are separated by a single space as shown in your data sample:
awk -v RS=' ' '/^-Number$/ { getline; print; }'

This treats every single-space-separated string as a record. When a record made of exactly the string -Number is found, the next one is read and printed.

A: With GNU grep or compatible:
ps -wwAo args= | grep -Po '^java.* -Number\s+\K\S+'

-o is a GNU grep extension that tells it to output the matched parts as opposed to the lines with at least one match.
-P is another GNU grep extension that tells it to use perl-compatible regexps instead of basic regular expressions.
\K is a perl regexp operator that resets the start of the matched portion. So the matched portion will be the sequence of one or more (+) non-whitespace characters (\S) that follows -Number<whitespaces>.
ps -Ao args= is the POSIX command to list all the argument list of all processes (concatenated with spaces). -w is an extension supported by a few ps implementation to make it wider (as many ps implementations otherwise truncate it).

A: Use grep with oE
grep -oE "\-Number(.*?)\s-" | grep -oE [[:digit:]]+

-o -> to output only matching strings
-E -> Extended regex


text:
Q: Android: Extract data from ArrayList I want to extract data from an ArrayList, but the LogCat shows null value.
My code is:
try {
   String sql = "SELECT Cname FROM demo";
   Statement stmt = con.createStatement();
   final ResultSet rs = stmt.executeQuery(sql);
   while (rs.next()) {
      arrData.add(rs.getString("Cname").toString());
   }
   Campaign campaign_data[] = new Campaign[] {
      new Campaign(R.drawable.empty, "Today:"+ arrData.indexOf(0)),
      new Campaign(R.drawable.empty, "This Month:" + arrData.indexOf(1))
   };
} catch() {
}

A: Is arrData of type ArrayList?
You seem to be calling indexOf(0) on it which is probably not what you want.

public int indexOf(Object o)
Returns the index of the first occurrence
  of the specified element in this list, or -1 if this list does not
  contain the element. More formally, returns the lowest index i such
  that (o==null ? get(i)==null : o.equals(get(i))), or -1 if there is no
  such index.

I would assume you meant to call get(i), so try the following:
      new Campaign(R.drawable.empty, "Today:"+ arrData.get(0)),
      new Campaign(R.drawable.empty, "This Month:" + arrData.get(1))


text:
Q: Passing data from model to router in node js I am trying to pass some data from my db to the router which then passes the data to the view.
My model code :
var mysql = require('mysql');

var connection = mysql.createConnection({
  host:       'localhost',
  user:       'root',
  password:   '',
  database:   'test'
});

var result; // empty var which should later be filled with the querys result

connection.connect();

var query = connection.query('SELECT * FROM users', function(err, res, fields) {
  if (err) throw err;

  result = res; // overwrite result with the querys result
  console.log(res); // This prints out everything I need
});

module.exports = {
  data: result // should contain the query result (= 2 objects in this case)
}

Now to my route file :
var express = require('express');
var router = express.Router();

var Users = require('../models/users');

console.log(Users.data);
/* GET home page. */
router.get('/users', function(req, res) {
    res.render('api', { data: Users.data, title: "Test API Output" });
});

module.exports = router;

When I console.log Users or Users.data I get undefined. I don't really get why this is the case. How else am I supposed to pass data along the files.
All help is gladly read :) Thank you.

A: module.exports are being evaluated the second you require and variables are not passed by reference in this case.
What that means for your code is the following:
    var result;  // result is "undefined" because it does not contain a value here
    // You are doing your DB queries here...
    module.exports = {
        data: result  // ...and because the query has not finished here yet, result
                      // is still undefined.
        // This is also a good example of a so called "race condition", because there is a
        // slight (improbable) chance that the query might have already finished.
        // Hence, it could happen that sometimes result is already filled.
    }

When you now require the above file in another file of your code, the above is being evaluated and saved straight away (result is undefined at that point in time, hence it is also undefined when it exports).
Your query is being executed and written into the result variable, but at that point in time you can not modify the exported variable anymore – because it is it's own variable and not merely a reference to result).
What you could do is the following:
    function getData(callback) {
        connection.query('SELECT * FROM users', function(err, res, fields) {
            callback(err, res);
        });
    }

    module.exports = {
        getData: getData
    }

and then in your other file:
    var Users = require('../models/users');

    Users.getData(function(err, result) {
        // TODO: Error handling.
        console.log(result);
    });

That's exactly why it's so easy with JavaScript to end up in callback hell, because of it's asynchronous nature.
The above is the exact same situation as if you, f.e., want to get some data via AJAX from a server and then fill tables with it. When you start creating the table before you have the data (so the AJAX request is not yet complete), you end up with an empty table. What could do is:

*

*you create a variable that holds your data and

*a function that creates the table

when you then ask the server for the data (via AJAX) you wait until you get the data (completion callback) and only then you start creating the table: filling your variable and calling the function to fill the table with the data.
Server-Side JavaScript is the same as client-side. Never forget this.
As a little homework for the reader: the way to get out of callback hell is by reading up on promises – a pattern/architecture which reduces indents and saves lots of headaches :)
(update: Lucas' answer is basically telling the same thing as I did)
(update 2: wrong way of handling err)

A: I suggest realize the consult in the route file, some like this:
    var express = require('express');
    var router = express.Router();

    var Users = require('../models/users');

    var mysql = require('mysql');

    var connection = mysql.createConnection({
        host:       'localhost',
        user:       'root',
        password:   '',
        database:   'test'
   });

   var result; // empty var which should later be filled with the querys result

connection.connect();

    /* GET home page. */
    router.get('/users', function(req, res) {

        var query = connection.query('SELECT * FROM users', function(err, res, fields) {
            if (err) throw err;

            result = res; // overwrite result with the querys result
            res.render('api', { data: res.data, title: "Test API Output" });
        });
    });

    module.exports = router;

But you can configure the connection with database in another file, in libs/mysql_connect.js.
The undefined is caused because the response of connection.query don't works out of the connection.query.

A: If you really want the query to run only once and then just re-use the already queried data, I think you are after something like this for your model:
...
var data;
var mymodel = {};
...
mymodel.getData = function(callback) {
    if(data) {
        callback(data);
    } else {
        db.query('select * from users', function(err,res,fields) {
            // error checking and such
            data = res;
            callback(data);
        });
    }
}
module.exports = mymodel

In your router, you'd then use it like this:
...
router.get('/users', function(req, res) {
    Users.getData(function(mydata) {
        res.render('api', { data: mydata, title: "Test API Output" });
    });
});

The first time you call getData, you'll get a fresh result, and on subsequent calls you get the cached result.
While you could expose data in mymodel directly, and only use the callback in case it is still undefined, that'd make your code in the router more convulated.


text:
Q: Eclipse with ADT performance issue I've been using ADT for about a year now.
We have a Git project on bitbucket.
Just before Christmas I started having some performance issues when pulling/fetching from our repository.
What appears to happen is that the fetch downloads the changes, but then my PC runs for hours resolving the deltas.
Looking at the task manager shows javaw.exe using a single core, and nearly a Gig of memory. It will eventually complete, but this process used to only take minutes. Here's a screenshot:

This is where it's "stuck"

As you can see, it's not the worlds largest update.

*

*My Eclipse version is  4.2.1.v20130118-173121-9MF7GHYdG0B5kx4E_SkfZV-1mNjVATf67ZAb7.

*My ADT version is 23.0.2.1259578.

*JDK is now 1.7u75, it was 1.7u55 before I updated it.

I know this is a pretty random question, but I have no idea what else to try.
Any help greatly appreciated.

A: It seems more a stability problem of your pc. However if your problem seems to be on javaw.exe i suggest to update to last JDK jdk-8u31 you can find it for all platform on http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html.
If is not a problem for your project try to change version of Eclipse switching to
Eclipse Java EE IDE for Web Developers.
Version: Luna Service Release 1a (4.4.1)
Build id: 20150109-0600
This is the last Eclipse version, code name Luna and supports well JDK 8.


text:
Q: Drop privilege to tables only, Not to database I created a user with drop privilege to a database.
How can I create a user who has the privilege to drop tables of a specified database, but not database.

A: Do GRANT DROP ON TABLE thedatabase.* TO user1.
The MySQL Reference Manual is a great place to look for this kinds of things.


text:
Q: PHPExcel: Combine 2 Excel files into 1 into the same worksheet I have 2 excel files birds.xlsx and bees.xlsx both of which have the same number of columns and same type of column header. I've seen how PHPExcel does wonders with excel files but is there some way to combine 2 separate files into the same worksheet and saving it as a new file? The analogy that comes to mind is something like the SQL UNION command.

A: Something like:
// Load both spreadsheet files
$objPHPExcel1 = PHPExcel_IOFactory::load("birds.xlsx");
$objPHPExcel2 = PHPExcel_IOFactory::load("bees.xlsx");

// Find the last cell in the second spreadsheet
$findEndDataRow = $objPHPExcel2->getActiveSheet->getHighestRow();
$findEndDataColumn = $objPHPExcel2->getActiveSheet->getHighestColumn();
$findEndData = $findEndDataColumn . $findEndDataRow;
// Read all the data from second spreadsheet to a normal PHP array
//    skipping the headers in row 1
$beeData = $objPHPExcel2->getActiveSheet->rangeToArray('A2:' . $findEndData);

// Identify the row in the first spreadsheet where we want to start
//     adding merged bee data without overwriting any bird data
$appendStartRow = $objPHPExcel1->getActiveSheet->getHighestRow() + 1;
// Add bee data from the PHP array into the bird data
$objPHPExcel1->getActiveSheet->fromArray($beeData, null, 'A' . $appendStartRow);

// Save the spreadsheet with the merged data
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel1, 'Excel2007');
$objWriter->save(str_replace('animals.xlsx');


text:
Q: Bean shell script to clear a line from the file after execution in Jmeter I have a condition in Jmeter that the extracted data from the file have to be deleted one by one. Actual situation is, I am getting some IDs from json and saving it in txt file. During my test, I have to delete the Json Content by ID and then I have to clear the text file. Since I am using fragment as test case, while the Thread count increases, the delete statement takes the first line from the txt file and so the same ID getting deleted again and again.
I am using below script to delete the file, but there is no change in the file
try {
            File file = new File("groupId.txt");
            PrintWriter writer = new PrintWriter(file);
            writer.print("");
            writer.close();
            line=$(head -n 1 file)
        } catch (Exception e) {

     }

Either I have to configure to increase the line index or I have to clear the ID from the txt file after using it.

A: In order to update file you need to save it in a temporary file and then remove old file and rename temp file.see solution


text:
Q: How can I prevent default notifications when encountering an error when using an external datasource as my datastore? I'm building a custom content part that fetches its information from an external repository, mostly following the advice found @ How to change Orchard record repository and using a custom handler to fetch the data.
Working with external data stores opens up the possibility of all sorts of network exceptions, etc., which would cause the underlying record not be saved. However, if there's an exception thrown in the ContentHandler, it's swallowed up by the Invoke<TEvents> method so that (unless it's a "fatal" exception) the user wouldn't know about the exception and would be notified by the AdminController that "Your {0} has been saved.", when in fact it hasn't been.
A workaround that's obvious to me is to intercept the error somehow and notify the content driver for my content part, which exposes the executing AdminController. At that point, I can hook into the controller's ModelState and introduce an error, which would then be caught and then I'd be notified of an error without any false positive notifications.
Are there any other extensibility points available in Orchard that would handle this kind of external access better than altering the controller's ModelState via a content driver?

A: The easiest way would be to implement you own, simple, per-request storage object for those errors, ie.
public interface IErrorLog : IDependency {
    public void Add(string message){ ... }
    public IEnumerable<string> List() { ... }
}

public class DefaultErrorLog : IErrorLog { ... }

Inject IErrorLog in both your controller and handler. In the handler, catch all errors you need to catch and add them to the collection with Add(...). Then, in the controller, call List() and add model error for each entry.
UPDATE
If you're not in control of a Controller that updates your content item, then you should use a driver. Catch the exception during item save (the second Editor method with 3 params) and push some error info using AddModelError of the provided IUpdateModel object. Way easier, but you'll be able to catch only those errors that happen when an item is saved.
UPDATE 2
If you're not in control of a Controller that updates your content item but would like to have a pure solution and gain control over the whole process, you can use your own controller for editing items. In order to do that:

*

*create a new controller (or copy and alter the default AdminController found in Orchard.Core\Contents) first

*now tell Orchard to use this controller instead of the default one for all types that contain your custom part. It can be done by putting something like this in your handler:
OnGetContentItemMetadata<MyCustomPart>((context, part) =>
{
    context.Metadata.AdminRouteValues = new RouteValueDictionary
    {
        { "Area", "My.Module" },
        { "Controller", "Admin" },
        { "Action", "Edit" },
        { "id", context.ContentItem.Id }
    };
});


text:
Q: css doesn't render correctly on Safari until browser window is resized I've seen similar questions regarding this issue, but they are either related to the mobile version of Safari, or they relate to javascript issues.  Neither of those, I think, are the issue my page is having.
I have a simple paragraph of text that gets centered horizontally using CSS, and the text is responsive so that it scales and wraps within the viewport to always fit and have a specific percentage width of the viewport.
The CSS works perfectly fine in every browser except that in Safari, when the window is narrower than the MAX-width of the paragraph, the paragraph upon page load initially starts out left justified to the viewport.  Only after scaling the viewport manually by even one pixel, or hovering over the menu items which have their own CSS styling, does the paragraph get properly centered.
I am not sure what part of all the code involved I should be including here, so any help would be appreciated.
Thanks.
I've added a link to a codepen I just created with a stripped-down version of the code, but the codepen itself doesn't show the error, so I've attached screen shots in the attached image.
https://codepen.io/anon/pen/MZEOMQ

      * {
          margin: 0;
          -webkit-box-sizing: border-box;
                  box-sizing: border-box;
      }
      body, html {
          background-color: black;
      }

      .info_wrapperClass {
        display: -webkit-box;
        display: -ms-flexbox;
        display: flex;
        -webkit-box-pack: center;
            -ms-flex-pack: center;
                justify-content: center;
        -webkit-box-orient: vertical;
        -webkit-box-direction: normal;
            -ms-flex-direction: column;
                flex-direction: column;
        position: relative;
      }
      .infoNoticeParagraphBugreportClass {
        font-size: calc(11px + .5vw);
      }
      @supports ((display: -ms-grid) or (display: grid)) {
        .info_wrapperClass {
          display: -ms-grid;
          display: grid;
          -ms-grid-columns: 1fr auto 1fr;
          grid-template-columns: 1fr auto 1fr;
          -ms-grid-rows: auto 1vh auto 1vh auto 1vh auto 1vh auto 1vh -webkit-min-content;
          -ms-grid-rows: auto 1vh auto 1vh auto 1vh auto 1vh auto 1vh min-content;
          grid-template-rows: auto auto auto auto auto -webkit-min-content;
          grid-template-rows: auto auto auto auto auto min-content;
          grid-row-gap: 1vh;
              grid-template-areas:
                                ". info_heading_area ."
                                ". info_notice_area ."
                                ". info_blog_heading_area ."
                                ". info_text_area ."
                                ". separator_line_area ."
                                ". innerwrapper .";
        }
        .info_headingClass {
          -ms-grid-row: 1;
          -ms-grid-column: 2;
          grid-area: info_heading_area;
        }
        .infoNoticeParagraphClass {
          -ms-grid-row: 3;
          -ms-grid-column: 2;
          grid-area: info_notice_area;
        }
        .info_blog_headingClass {
          -ms-grid-row: 5;
          -ms-grid-column: 2;
          grid-area: info_blog_heading_area;
        }
        .infoBlogParagraphClass {
          -ms-grid-row: 7;
          -ms-grid-column: 2;
          grid-area: info_text_area;
        }
      }
      .info_headingClass {
        margin-top: 40px;
      }
      .infoNoticeParagraphClass {
        padding-bottom: 40px;
        max-width: 100vw;
        -ms-flex-item-align: center;
            -ms-grid-row-align: center;
            align-self: center;
        margin-top: 4vh;
      }
      .infoNoticeParagraphClass p {
        margin-left: 5vw;
        margin-right: 5vw;
        max-width: 60em;
        min-width: 20em;
      }
      .info_blog_headingClass {
        -ms-flex-item-align: center;
            -ms-grid-row-align: center;
            align-self: center;
        margin-top: 4vh;
      }
      .infoBlogParagraphClass {
        padding-bottom: 40px;
        max-width: 100vw;
        -ms-flex-item-align: center;
            -ms-grid-row-align: center;
            align-self: center;
        margin-left: auto;
        margin-right: auto;
        margin-top: 4vh;
      }
      .infoBlogParagraphClass p, h3 {
        margin-left: 5vw;
        margin-right: 5vw;
        max-width: 60em;
        min-width: 20em;
      }
      h1.info_headingClass {
        font-weight: bold;
        font-size: calc(20px + .5vw);
        text-align: center;
        font-family: Verdana, Geneva, sans-serif;
        color: white;
      }
      .infoNoticeParagraphClass p {
        font-size: calc(12px + .5vw);
        text-align: center;
        font-family: Verdana, Geneva, sans-serif;
        color: red;
      }
      h2.info_blog_headingClass {
        font-weight: bold;
        font-size: calc(18px + .5vw);
        text-align: center;
        font-family: Verdana, Geneva, sans-serif;
        color: white;
      }
      .infoBlogParagraphClass > h3 {
        font-weight: bold;
        text-decoration: underline;
        text-align: left;
        font-size: calc(12px + .5vw);
        font-family: Verdana, Geneva, sans-serif;
        padding-bottom: .5em;
        color: white;
      }
      .infoBlogParagraphClass > p {
        text-align: left;
        padding-bottom: 1ch;
        line-height: 1.25em;
        font-size: calc(12px + .25vw);
        font-family: Verdana, Geneva, sans-serif;
        color: white;
      }
      @media screen and (min-width: 1400px) {
        h1.info_headingClass {
          font-size: 1.75em;
        }
        .infoNoticeParagraphClass p {
          font-size: 1.2em;
        }
        .infoNoticeParagraphBugreportClass {
          font-size: 1.2em;
        }
        h2.info_blog_headingClass {
          font-size: 1.7em;
        }
        .infoBlogParagraphClass > h3 {
          font-size: 1.25em;
        }
        .infoBlogParagraphClass > p {
          font-size: 1em;
        }
      }
      @media screen and (max-width: 479px) {
        .info_headingClass {
          margin-top: 10px;
        }
        .infoNoticeParagraphClass {
          padding-bottom: 10px;
          max-width: 90vw;
          min-width: 60vw;
        }
        .infoBlogParagraphClass {
          padding-bottom: 10px;
          max-width: 90vw;
          min-width: 60vw;
        }
        .infoBlogParagraphClass p, h3 {
          margin-left: 5vw;
          margin-right: 5vw;
          max-width: 50em;
          min-width: 20em;
        }
        h1.info_headingClass {
          font-size: calc(16px + .5vw);
        }
        .infoNoticeParagraphClass p {
          font-size: calc(10px + .5vw);
        }
        h2.info_blog_headingClass {
          font-size: calc(14px + .5vw);
        }
        .infoBlogParagraphClass > p{
          padding-bottom: 1ch;
          font-size: calc(10px + .5vw);
        }
      }

Lorem Ipsum

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Labore possimus ipsam iure repellendus. Odit sit eveniet laboriosam dolores volupt

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Placeat sit, beatae, a neque dolorum temporibus! Corporis aliquam obcaecati rerum praesentium ducimus sequi consectetur, consequuntur, error deserunt ea quos autem similique, sapiente ratione nostrum? Magnam quos obcaecati error rerum ipsa rem itaque ipsam at, natus dicta facilis. Odit provident

Lorem

Lorem ipsum dolor sit amet, elit. Ab

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Modi placeat perspiciatis magnam, atque voluptatibus veritatis. Velit inventore doloribus minus, nisi incidunt eum ea beatae possimus, enim ipsam earum laborum nostrum

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Asperiores, commodi magnam sequi, sed, velit quos quasi rerum numquam animi nam laboriosam. Voluptas

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Hic similique incidunt quas autem atque, voluptatem quaerat illum possimus vitae nulla. Aliquam ea at iusto aut odit necessitatibus ex exercitationem quae quasi sunt laudantium, ratione voluptatem optio commodi quisquam sequi, molestiae in, vel eum quod eveniet laboriosam tenetur.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Earum voluptates libero totam placeat optio nemo, quos voluptate velit ullam possimusa?


text:
Q: Bootstrap horizontal navbar plus sidebar I'm trying to create an application layout utilizing the Bootstrap framework that has both a horizontal navbar as well as a vertical sidebar.
The basic layout I have is:

            Logo

Action

Another action

Something else here

Separated link

Body

However, what I'd like is for the navbar to be positioned beginning at column 3. Currently it is positioned to the left, effectively covering the logo.
Any assistance would be much appreciated. I'd like the solution to be responsive.
Regards,
Dan