text:
Q: Split value according to shares in other table DB-Fiddle
CREATE TABLE costs (
    id SERIAL PRIMARY KEY,
    event_date DATE,
    country VARCHAR,
    channel VARCHAR,
    costs_per_day_per_country DECIMAL);

INSERT INTO costs
(event_date, country, channel, costs_per_day_per_country)
VALUES
('2020-02-08', 'DE', 'channel_01', '400'),
('2020-02-08', 'DE', 'channel_02', '400'),
('2020-02-08', 'FR', 'channel_01', '400'),
('2020-02-08', 'FR', 'channel_02', '400'),
('2020-02-08', 'NL', 'channel_01', '400'),
('2020-02-08', 'NL', 'channel_02', '400'),

('2020-04-15', 'DE', 'channel_01', '300'),
('2020-04-15', 'DE', 'channel_02', '300'),
('2020-04-15', 'FR', 'channel_01', '300'),
('2020-04-15', 'FR', 'channel_02', '300'),
('2020-04-15', 'NL', 'channel_01', '300'),
('2020-04-15', 'NL', 'channel_02', '300');

CREATE TABLE revenue (
    id SERIAL PRIMARY KEY,
    event_date DATE,
    country VARCHAR,
    revenue_share DECIMAL);

INSERT INTO revenue
(event_date, country, revenue_share)
VALUES
('2020-02-08', 'DE', '0.60'),
('2020-02-08', 'FR', '0.30'),
('2020-02-08', 'NL', '0.10'),

('2020-04-15', 'DE', '0.60'),
('2020-04-15', 'FR', '0.30'),
('2020-04-15', 'NL', '0.10');

Expected Result:
event_date    |    country   |     channel       |            costs              |
--------------|--------------|-------------------|-------------------------------|---------
2020-02-08    |      DE      |     channel_01    |      120  (=400 x 0.6 / 2)    |
2020-02-08    |      DE      |     channel_02    |      120  (=400 x 0.6 / 2)    |
2020-02-08    |      FR      |     channel_01    |       60  (=400 x 0.3 / 2)    |
2020-02-08    |      FR      |     channel_02    |       60  (=400 x 0.3 / 2)    |
2020-02-08    |      NL      |     channel_01    |       20  (=400 x 0.1 / 2)    |
2020-02-08    |      NL      |     channel_02    |       20  (=400 x 0.1 / 2)    |
--------------|--------------|-------------------|-------------------------------|---------
2020-04-15    |      DE      |     channel_01    |       90  (=300 x 0.6 / 2)    |
2020-04-15    |      DE      |     channel_02    |       90  (=300 x 0.6 / 2)    |
2020-04-15    |      FR      |     channel_01    |       45  (=300 x 0.3 / 2)    |
2020-04-15    |      FR      |     channel_02    |       45  (=300 x 0.3 / 2)    |
2020-04-15    |      NL      |     channel_01    |       15  (=300 x 0.1 / 2)    |
2020-04-15    |      NL      |     channel_02    |       15  (=300 x 0.1 / 2)    |

In the first table I have costs_per_day_per_country.
Now, I want to split those costs according to the revenue_share in the second table to each country.
Addtionally, the allocated costs should be split equally to each channel.
I tried to go with this query:
SELECT
c.event_date,
c.country,
c.channel,

  /* Allocate the costs_per_day_per_country according to the revenue share */
  (CASE WHEN c.country IN ('DE') THEN MAX(c.costs_per_day_per_country) * MAX(t1.revenue_share)
        WHEN c.country IN ('FR') THEN MAX(c.costs_per_day_per_country) * MAX(t1.revenue_share)
        WHEN c.country IN ('NL') THEN MAX(c.costs_per_day_per_country) * MAX(t1.revenue_share)
  END)

  /* Split the allocated costs equally to each channel */
  * (1.0 / COUNT(*) OVER (PARTITION BY c.event_date, c.country)) AS costs_allocated

FROM costs c
LEFT JOIN

  (SELECT
  r.event_date,
  r.country,
  r.revenue_share
  FROM revenue r
  GROUP BY 1,2,3
  ORDER BY 1,2,3) t1 ON t1.event_date = c.event_date

GROUP BY 1,2,3
ORDER BY 1,2,3;

It almost gives me the expected result but it somehow does not apply the revenue_share correctly to each country.
It applies the 0.6 to every country.
How do I need to modify the query to get the expected result?

A: If my understanding is correct the solution is far simple than the query you implemented, all you need to do is to join the two tables and use a COUNT() over (PARTITION BY) appropriately to count the channels
SELECT
c.event_date,
c.country,
c.channel,
(costs_per_day_per_country * revenue_share)/COUNT(c.channel) over (partition by c.event_date, c.country) dt

FROM costs c
LEFT JOIN
 revenue t1 ON t1.event_date = c.event_date and t1.country=c.country

ORDER BY 1,2,3;


text:
Q: Load initialState dynamically with createSlice in Redux Toolkit Is there a well-known pattern for injecting a payload of dynamic initial state into Redux-Toolkit's initialState object?
That is, I would like to do this -
import initialState from './initialState';

function generateSlice(payload = {}){
  const postsSlice = createSlice({
    name: 'posts',
    initialState: {...initialState, ...payload}, /// inject data here
    reducers: {...}
  })
}

For example, {availableRooms: []} is an empty array, unless injected on init with data {availableRooms: [{...}]}
This pattern doesn't work, however, b/c I want to export actions to be dispatch-able, something like this-
 const postsSlice = createSlice({
    name: 'posts',
    initialState: {...initialState, ...payload},
    reducers: {...}
  })

export {actionName} from postsSlice.actions;

*****
import {actionName} from '../mySlice'

...
const dispatch = useDispatch();
dispatch(actionName('exampleVal'));
...

I am constrained by the airbnb linting rules, so I can't export on let -
let actions; ///Bad
function generateSlice(payload){
  const postsSlice = createSlice({
    name: 'posts',
    initialState: {...initialState, ...payload},
    reducers: {...}
  })
  actions = postsSlict.actions
}

export actions;

The functionality that I am after is a bit easier without using createSlice. The reason for my question is that I have seen in multiple places that createSlice is recommended over createAction + createReducer, but I don't see any simple way to introduce the dynamic data that I am looking for.
I don't know anything about redux-orm but I think the functionality that I am after is similar to this SO question

A: Here's my current work-around, which skips createSlice altogether.
In the root render
...
const store = initStore(data);
 <Provider store={store}>
  <App />
</Provider>

And the init function (pared down for brevity)
import {
  configureStore,
  getDefaultMiddleware,
  combineReducers,
} from '@reduxjs/toolkit';
import reservationReducer from '@reservation/reducer';
import spaceHierarchyReducer from '@map/reducer';
import appStoreReducer from '@app/reducer';

let ReduxStore;

function initStore(
  ssrState: Partial<RootStore> = {},
) {
  if (ReduxStore) {
    return ReduxStore;
  }
  const slices = {
    reservation: reservationReducer,
    spaceHierarchy: spaceHierarchyReducer,
    appStore: appStoreReducer,
  };
  const reducer = combineReducers(slices);
  const preloadedState = getInitialState(ssrState);
  const store = configureStore({
    reducer,
    middleware,
    preloadedState,
  });

  ReduxStore = store;
  initDispatch(store);
  return store;
}

In getInitialState, I parse the URL and set-up the store based on business requirements, a mixture of server-side data + url-injectable params. Then, in initDispatch, I invoke store.dispatch() for some init logic based that injected initial state.
Here the usage of Typescript is quite helpful, as it enforces the shape of the data returned from getInitialState as well as the shape of the reducers.

A: I found a work around with Redux Tool Kit. I'm kind of new to Redux because Context API cannot rerender React Native Navigation Screens as they are not part of the main tree. I don't know if my approach is good enough, but here was my thinking:

*

*generateSlice() wouldn't fill actions variable because at the time the export is made to be used by RTK module, generateSlice hasn't been called yet.

*At the beginning, RTK module just need the structure and configuration for createSlice, but not the store object yet. Only the configureStore really care about the store itself. So that with a duplicate call: exporting actions with normal default initialState and then recalling it inside generateSlice(initValue) with the real default initialValue seems to work well.

To keep it simpler for everyone, I'm giving an example with the official short tutorial on RTK https://redux-toolkit.js.org/tutorials/quick-start :
counterSlice.js :
import { createSlice } from '@reduxjs/toolkit';

const initialState = {
  value: 0,
};

const slicer = initState =>
  createSlice({
    name: 'counter',
    initialState: initState,
    reducers: {
      increment: state => {
        // Redux Toolkit allows us to write "mutating" logic in reducers. It
        // doesn't actually mutate the state because it uses the Immer library,
        // which detects changes to a "draft state" and produces a brand new
        // immutable state based off those changes
        state.value += 1;
      },
      decrement: state => {
        state.value -= 1;
      },
      incrementByAmount: (state, action) => {
        state.value += action.payload;
      },
    },
  });

const generateSlice = initState => {
  return slicer(initState).reducer;
};

export const counter = slicer(initialState);

// Action creators are generated for each case reducer function
export const { increment, decrement, incrementByAmount } = counter.actions;

export default generateSlice;

store.js becoming a function now, rename it getStore if necessary :
import { configureStore } from '@reduxjs/toolkit';
import generateCounterReducer from '../states/reducers/counter';

export const store = states => {
  return configureStore({
    reducer: {
      counter: generateCounterReducer(states.counter),
    },
  });
};

App.js or index.js where you put the redux Provider:
<Provider
  store={store({
    counter: { value: 7 },
  })}
>

And when I load the component, the value 7 is rendered by default. The only problem with it is that it executes the createSlice 2 times. But since this only happens at the App start, then I see no performance issue with that approach. Maybe the pattern will conflict with advanced usage, so if anyone see any bottleneck, we can discuss it and figure out how to improve it.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to get href attribute using selenium for python? I want to get the href attributes from the given HTML code so that i can go inside the link and scrape some data from it.

 Aaron Finch
AUSTRALIA

 Fakhar Zaman
PAKISTAN

I want to get the attributes of href and save it to a list.

A: You can use regular expressions to parse out thinks in the HTML such as that href tag.
Here is an article explaining that: https://medium.com/@tracy_blog/regex-and-selenium-2c5a89f23a17

A: To accomplish this, I would consider using get_attribute(name) over a regular expression.


text:
Q: Permission denied when running npm test via mocha on Travis-CI I'm setting up a simple NodeJS application which I'm integrating with Travis-CI. I'm using Mocha to help with my tests. However, while these tests run fine locally, I'm failing the tests when on Travis-CI before deploying to Openshift. Some help on figuring this out would be cool =)
Travis-CI output
CAT@0.0.1 test /home/travis/build/melvrickgoh/CAT
> mocha test/
sh: 1: mocha: Permission denied
npm ERR! Test failed.  See above for more details.
npm ERR! not ok code 0

This is what is have inside my package.json
"scripts": {
    "start": "node app.js --websocket-port=$OPENSHIFT_NODEJS_PORT --log-level=1",
    "test": "mocha test/ "
  },

A: Same issue, adding this to my .travis.yml this fixed it for me:
before_script: chmod 0777 ./node_modules/.bin/mocha

A: Had same issue on OpenShift when trying to run tests. Solved by making the the mocha file executable, as follows:
chmod 0777 /var/lib/openshift/53ef9c315973cabb00034c/app-root/runtime/repo/node_modules/.bin/mocha

A: I encountered the same problem, with mocha installed as a dev dependency.
I could solve it by simply uninstalling then reinstalling mocha:
npm uninstall --save-dev mocha

then
npm install --save-dev mocha

Maybe you could do the same for a global installation of mocha, but I did not test it myself.


text:
Q: Use VB to calculate an area of a shape I'm using Arcmap 10.1, running python 2.7 on a Windows 8.1 machine. I have a script that uses the arcpy.CalculateField_management function to calculate the area of a shape, however, for some reason when i use the python expression to calculate the field, python crashes. The only way i can use the arcpy.CalculateField_management function is by using a VB expression. Does anyone one how i can translate this line to VB
arcpy.CalculateField_management("TAZ_un_Buffer_Dissolve1.shp", "totalArea","!shape.area!", "PYTHON", "")
Have in mind that the line below returns an error.
'arcpy.CalculateField_management("TAZ_un_Buffer_Dissolve1.shp", "totalArea","[shape.area]", "VB", "")'
How else can i accomplish this without using the arcpy.CalculateField_management function?

A: The documentation only makes mention of being able to use shape.area on Python expressions. You will need to use a Python expression to do this.
I would very strongly recommend reinstalling ArcGIS. Python not working is indicative of a corrupt installation of ArcGIS, and working around it will not alleviate the problem in other areas.

A: Maybe you should start with a "repair geometry" and check your coordinate system to make sure that your shapefile is not the source of your problem.
If calculateField still doesn't work, but the rest of your Python script runs properly, probably the best solution would be to use an arcpy.da.updateCursor() and compute the area for each row.
Possible workaround would be to use "calculate area" or to export your data in a geodatabase. In both cases you end up with a new feature class that would have a field with the area of your polygons (but it creates a new data).
If none of those work, then you should reinstall.
NOTE : In older (<10) versions,  you would have needed a codeblock expression to return the area in VBA, but VBA is now deprecated.  A vbscript version should look like this but it is not working anymore with ArcObjects as variables since ArcGIS 10.1:
expression = "dblArea"
codeblock = """Dim dblArea
Dim pArea ' as IArea in VBA
Set pArea = [shape]
dblArea = pArea.area"""
arcpy.CalculateField_management("TAZ_un_Buffer_Dissolve1.shp", "totalArea","expression", "VB", "codeblock")

A: Thanks for all the help but I think I fixed the problem. The computer had two versions of python 27 installed and seems that that is the reason  behind python crashing when using the CalcFiled method. I removed the version Arcgis does not use and it is not crashing anymore so its working normal  now.
Thanks for the help


text:
Q: Refresh Table When Action Create, Read, Update,Delete (CRUD) in datatables I have a problem
How To Refresh Tables when Action Create, Read, Update,Delete (CRUD) in datatables
Screnshot Tables : http://prntscr.com/3voq2l
Header Code / Head Code

Body Code
<?php
if (!function_exists("GetSQLValueString")) {
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "")
{
  if (PHP_VERSION < 6) {
    $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;
  }

  $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);

  switch ($theType) {
    case "text":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;
    case "long":
    case "int":
      $theValue = ($theValue != "") ? intval($theValue) : "NULL";
      break;
    case "double":
      $theValue = ($theValue != "") ? doubleval($theValue) : "NULL";
      break;
    case "date":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;
    case "defined":
      $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
      break;
  }
  return $theValue;
}
}

mysql_select_db($database, $koneksi);
$query_rs_datatables = "SELECT * FROM galeri";
$rs_datatables = mysql_query($query_rs_datatables, $koneksi) or die(mysql_error());
$row_rs_datatables = mysql_fetch_assoc($rs_datatables);
$totalRows_rs_datatables = mysql_num_rows($rs_datatables);
?>

Table Code

    Title
        Date
            Link Video
                Link Photo
                    Image
                        Action

  <?php do { ?>

      <?php echo $row_rs_datatables['judul']; ?>
        <?php echo tgl($row_rs_datatables['tgl']); ?>

            <?php if ($row_rs_datatables['video']!=NULL){?>

<a href="#youtube-popup-<?php echo $row_rs_datatables['id']; ?>" data-effect="mfp-zoom-in">LINK

                <div id="youtube-popup-<?php echo $row_rs_datatables['id']; ?>" class="video-popup mfp-with-anim mfp-hide">

                        <iframe src="http://www.youtube.com/embed/<?php echo $row_rs_datatables['video']; ?>" allowfullscreen>

                <?php } else { ?>

-

                <?php }?>

            <?php if ($row_rs_datatables['linkfoto']!=NULL){?>

<a class="zooming" href="<?php echo $row_rs_datatables['linkfoto']; ?>" title="<?php echo $row_rs_datatables['judul']; ?>">LINK

                <?php } else { ?>

-

                <?php }?>

            <?php if ($row_rs_datatables['foto']!=NULL){?>

<a class="zooming" href="../images/galeri/<?php echo $row_rs_datatables['foto']; ?>" title="<?php echo $row_rs_datatables['judul']; ?>">LINK

                <?php } else { ?>

-

                <?php }?>

     <a href="#popup-edit-<?php echo $row_rs_datatables['id']; ?>" data-effect="mfp-zoom-in" style="text-decoration:none">
     <a href="#popup-delete-<?php echo $row_rs_datatables['id']; ?>" style="text-decoration:none">

        <div id="popup-edit-<?php echo $row_rs_datatables['id']; ?>" class="white-popup mfp-with-anim mfp-hide">
            <form action="" method="POST" >

                                    EDIT GALLERY

                                        Title Gallery
                                        <input type="text" maxlength="50" class="form-control" id="addgallery" name="ti" value="<?php echo $row_rs_datatables['judul']; ?>" placeholder="Title Gallery">

                                        Date
                                        <input type="text" name="dt" class="form-control" value="<?php echo $row_rs_datatables['tgl']; ?>" readonly>

                                                    You must choose one of the following

                                        Unique Link Youtube
                                        <input type="text" value="<?php echo $row_rs_datatables['video']; ?>" class="form-control" id="un" name="yo" placeholder="Eg: HigyM915gw8">

                                        Link Photo
                                        <input type="text" value="<?php echo $row_rs_datatables['linkfoto']; ?>"  class="form-control" id="li" name="li" placeholder="Link Photos">

                                        Upload Photo

                                                <input type="file" name="ph" >

                                        <input type="text" class="form-control" value="<?php echo $row_rs_datatables['foto']; ?>" readonly>

                                      <button type="submit" class="btn btn-primary">Submit</button>  <button type="reset" class="btn btn-danger">Reset</button>

                                       </form>

        <div id="popup-delete-<?php echo $row_rs_datatables['id']; ?>" class="white-popup mfp-with-anim mfp-hide">

                Are You Sure Delete Gallery "<?php echo $row_rs_datatables['judul']; ?>" ?
                <form action="" method="POST">

                    <button type="submit" class="btn btn-primary">Yes</button>  <button type="button" title="Close (Esc)" class="mfp-close">x</button>

                </form>

    <?php } while ($row_rs_datatables = mysql_fetch_assoc($rs_datatables)); ?>

                <?php
mysql_free_result($rs_datatables);
?>

I have not made a coding delete, create and update, I try via phpmyadmin


text:
Q: viewDidAppear not being triggered after initial load Currently running into an issue where I am trying to update my view after using a show segue to a separate popup view. The initial viewDidAppear is being triggered on load, but after i close out of my other view and transition back to the other view, it is not reloading.
I'm looking for an option to either trigger a reload of my data, or to try and refresh the information on a view being closed.

A: When you close out of the view controller, are you dismissing it or performing a new segue. If you are just performing a new segue, then the view controller would have already been loaded. You would need to use this function:
override func dismissViewControllerAnimated(flag: Bool, completion: (() -> Void)?) {

}

A: Try calling the reloadData() method on the tableview IBOutlet from within the button being clicked to segue to the viewController.
for Ex:
@IBAction func segueButton(sender: AnyObject) {
tableView.reloadData()

}


text:
Q: Filtering in MS graph by subproperty I'm trying to filter lists by their template since I only want to get document libraries, however, when I try to do that as in the following example, I get error The provided filter statement is not supported.
v1.0/sites/root/lists?$filter=list/template eq 'documentLibrary'

Besides that I also tried filtering by startswith(list/template, 'document') but with this approach I get An unspecified error has occurred.
In general, I'm trying to get document libraries for a root, but querying /drives seems to be quite slow (takes around 3 seconds to get them) and I believe that getting them via list could be faster.
Thanks


text:
Q: Torque control of a BLDC motor acting as a generator I'm trying to build a dyno for electric motors. The dyno consists of two motors: a motor under test (MUT) and a load motor. The two motors are connected together through a shaft. On the shaft there's a torque sensor mounted.
For a load motor, I'm using a Revolt 160 Pro (12kW) with a SEVCON GEN4 controller. The idea is to run the motor from a battery or a power supply (connected to the SEVCON controller). When the load motor is acting as a generator, the three phase terminals of the load motor are gonna be switched to a circuit with a dump load to dissipate all the generated power.
My question is: let's say that I have an 8Nm clockwise input on the MUT and a 4Nm clockwise input on the load motor (since I want to load the MUT with 4Nm). The net result on the shaft it's going to be 4 Nm (clockwise referred to the MUT). Therefore, the load motor is going to act as a generator. When it's acting as a generator, the SEVCON controller and power supply are no longer part of circuit, the load motor is just connected to a circuit with a dump load. How can I control the load motor (now acting as a generator) so now it loads the MUT with exactly 4Nm? Do I need to have a variable and controllable dump load to achieve this application?

EDIT:
This is a rough schematic of the circuit of the dynamometer on the load side. There's two circuits, one used for the motor when it acts as a generator and another one used when the motor acts as a motor (and therefore it's controlled by a SEVCON controller). My question was how to control the motor when it acts as a generator, i.e. how to control the generator's load on the shaft.

A: *

*A dynamometer must provide negative torque, torque that opposes the motion of the shaft driven by the MUT. Dyno torque plus motor torque = zero.

*The same parameter, torque or speed, can not be controlled by both the motor controller and the dyno controller. In this case, it is probably to control MUT speed and dyno torque.

*The dyno controller is useless unless it can control negative torque and return energy to the source.

*The easiest way to control the dyno is probably to not control the dyno motor at all. Just operate it as an uncontrolled generator. Rectify the generator output and use a chopper to control the load current. The current can be set manually or the current reference can be derived from a torque control error signal.


text:
Q: Grails - uninstalling Spring Security Core What is the correct way to uninstall spring-security-core plugin completely? I'm working on a Grails app that no longer needs a login and I'd like to remove it.
Even though I have uninstalled it via:
grails uninstall-plugin spring-security-core
Plugin [spring-security-core-1.1.3] is installed, but was not found in the application's metadata, do you want to uninstall? [y,n]
My choice doesn't seem to effect anything.
I keep getting message "Configuring Spring Security ..." when starting application.

A: You should also make sure you clean up any references to Spring Security beans that you may have used.  For example, if you are injected springSecurityService into your controllers/services/etc to retrieve the currently logged in user - you will now find missing beans on startup/null pointer exceptions

A: uninstall-plugin should work, but you can do it manually. Edit application.properties and remove the line for the plugin, then delete the directory under $HOME/.grails/<grails version>/projects/<your project>/plugins. Then run grails clean to remove any old classes.
In general this will work, as long as the plugin doesn't do any work in its _Uninstall.groovy script, which is the case for Spring Security Core (it's empty).


text:
Q: Create button using OpenGL in Android Can anyone give me an simple example of creating a button using OpenGL in Android?
I googled but did not find any suitable link.

A: There are frameworks such as Cocos2d you may use. If you want to create it from scratch it's really just a textured rectangle as MadcoreTom commented, you do need to still write all the handling with touches and probably some states. Another problem is putting on some text from string. But again in most cases it's just a textured rectangle and an if statement...


text:
Q: Matlab: find a value in a matrix I have the following matrix:
A= [23 34 45 0 0 0; 21 34 0 0 23 11; 34 23 0 0 0 22]

I want to find if a value is present and if it's present, I want to find the following values.
Eg I want to find in A the value 23, if it's present I want like output a matrix only with 23 and its following values
B= [23 34 45 0 0 0; 0 0 0 0 23 11; 0 23 0 0 0 22]

A: This is an interesting question, and I have a non-loopy answer, it uses the interesting effect of cumsum and find to great efficiency.
G = zeros(size(A));
T = find(A==23);
G(T) = 1;
mask = cumsum(G,2)>0;

result = mask .* A;

>> result =

23    34    45     0     0     0
 0     0     0     0    23    11
 0    23     0     0     0    22

This is I think, one of the more efficient way of doing this.
========EDIT========
even better, use logical indexing:
B = A.*(cumsum(A==23,2)>0);

Thanks to @obchardon

A: find() returns the row and the column of the desired value, in your case "23", in matrix A.
using a for loop you can copy the value and its following ones:
A = [23 34 45 0 0 0; ...
    21 34 0 0 23 11; ...
    34 23 0 0 0 22];
[r, c] = find(A==23);

B = zeros(3,6);

for i=1:length(r)
    columns = c(i):length(B);
    B(i,columns) = A(r(i),columns);
end;


text:
Q: Is there still a use for inline? I believed, inline was obsolete because I read here:

No matter how you designate a function as inline, it is a request that the compiler is allowed to ignore: the compiler might inline-expand some, all, or none of the places where you call a function designated as inline.

However, Angew seems to understand something I don't. In this question he and I go back and forth quite a bit, on whether inline is still useful.
This question is not a question on:

*

*The historical use of inline or where inline could still be used to hint to the compiler to inline functions: When should I write the keyword 'inline' for a function/method?.

*The benefits or drawbacks of inlining function code: Benefits of inline functions in C++?

*Forcing the compiler to inline function code: force inline function in other translation unit
Bearing in mind that the compiler can inline at will, so inline is not helpful there: Where can inline be used to force, not suggest, a change in compiled code?

A: I will try to explain my "secret understanding" the best way I can.
There are two entirely separate concepts here. One is the compiler's ability to replace a function call by repeating the function body directly at the call site. The other is the possibility of defining a function in more than one translation unit (= more than one .cpp file).
The first one is called function inlining. The second is the purpose of the inline keyword. Historically, the inline keyword was also a strong suggestion to the compiler that it should inline the function marked inline. As compilers became better at optimising, this functionality has receded, and using inline as a suggestion to inline a function is indeed obsolete. The compiler will happily ignore it and inline something else entirely if it finds that's a better optimisation.
I hope we've dealt with the explicit inline–inlining relationship. There is none in current code.
So, what is the actual purpose of the inline keyword? It's simple: a function marked inline can be defined in more than one translation unit without violating the One Definition Rule (ODR). Imagine these two files:
file1.cpp
int f() { return 42; }

int main()
{ return f(); }

file2.cpp
int f() { return 42; }

This command:
> gcc file1.cpp file2.cpp

Will produce a linker error, complaining that the symbol f is defined twice.
However, if you mark a function with the inline keyword, it specifically tells the compiler & linker: "You guys make sure that multiple identical definitions of this function do not result in any errors!"
So the following will work:
file1.cpp
inline int f() { return 42; }

int main()
{ return f(); }

file2.cpp
inline int f() { return 42; }

Compiling and linking these two files together will not produce any linker errors.
Notice that of course the definition of f doesn't have to be in the files verbatim. It can come from an #included header file instead:
f.hpp
inline int f() { return 42; }

file1.cpp
#include "f.hpp"

int main()
{ return f(); }

file2.cpp
#include "f.hpp"

Basically, to be able to write a function definition into a header file, you have to mark it as inline, otherwise it will lead to multiple definition errors.

The last piece of the puzzle is: why is the keyword actually spelled inline when it has nothing to do with inlining? The reason is simple: to inline a function (that is, to replace a call to it by repeating its body on the call site), the compiler must have the function's body in the first place.
C++ follows a separate compilation model, where the compiler doesn't have access to object files other than the one it's currently producing. Therefore, to be able to inline a function, its definition must be part of the current translation unit. If you want to be able to inline it in more than one translation unit, its definition has to be in all of them. Normally, this would lead to a multiple definition error. So if you put your function in a header and #include its definition everywhere to enable its inlining everywhere, you have to mark it as inline to prevent multiple definition errors.
Notice that even today, while a compiler will inline any function is sees fit, it must still have access to that function's definition. So while the inline keyword is not required as the hint "please inline this," you may still find you need to use it to enable the compiler to do the inlining if it chooses to do so. Without it, you might not be able to get the definition into the translation unit, and without the definition, the compiler simply cannot inline the function.
The compiler cannot. The linker can. Modern optimisation techniques include Link-Time Code Generation (a.k.a. Whole Program Optimisation), where the optimiser is run over all object files as part of the linking process, before the actual linking. In this step, all function definitions are of course available and inlining is perfectly possible without a single inline keyword being used anywhere in the program. But this optimisation is generally costly in build time, especially for large projects. With this in mind, relying solely on LTCG for inlining may not be the best option.

For completeness: I've cheated slightly in the first part. The ODR property is actually not a property of the inline keyword, but of inline functions (which is a term of the language). The rules for inline functions are:

*

*Can be defined in multiple translation units without causing linker errors

*Must be defined in every translation unit in which it is used

*All its definitions must be token-for-token and entity-for-entity identical

The inline keyword turns a function into an inline function. Another way to mark a function as inline is to define (not just declare) it directly in a class definition. Such a function is inline automatically, even without the inline keyword.

A: inline is mostly just an external linkage specifier now, for the reasons you stated.
So yes, it does have a use, but it's a different one than actually inlining functions. It allows you to define the same method multiple times between compilation units and properly link them together, instead of getting multiple definition errors.
//header.h
inline void foo() {}
void goo() {}

//cpp1.cpp
#include "header.h"

//cpp2.cpp
#include "header.h"

// foo is okay, goo breaks the one definition rule (ODR)

Actually forcing function inlining is up to the compiler, some might have support via specific attributes or pragmas or (__forceinline) or whatnot.
Simply put, it allows you to define functions in headers without breaking the ODR...


text:
Q: InteropBitmap synchronization WPF InteropBitmap can be created from shared memory, i.e.
Imaging.CreateBitmapSourceFromMemorySection()

In this case, we can update shared memory in another thread or process, and then after updating, calling InteropBitmap.Invalidate() to present the changes.
From the WPF source code, InteropBitmap is just a wrapper of IWICBitmap, but it doesn't expose IWICBitmap::lock which is used for exclusive writing.
So, how do I sync writing and reading of WPF InteropBitmap?

*

*Updating occurs in user's thread.

*Reading always occurs in WPF internal render thread via IWICBitmapSource::CopyPixels
Thanks

A: You can create a WrapperClass which exposed a lock object and the methods to manipulate the Image. Is some work but would work 100%
something like:
class InteropBitmapSyncWrapper
{

    public InteropBitmapSyncWrapper(InteropBitmap wrappedBitmap)
    {
        WrappedBitmap = wrappedBitmap;
        this.Lock = new Object();
    }

    public InteropBitmap WrappedBitmap
    {
        get;
        set;
    }

    public Object Lock
    {
        get;
        private set;
    }
}


text:
Q: Using Python: How to divide two different indicators (amount and exchange rate) in case two attributes match (Country AND date)? I downloaded and imported a csv file from an economics research database which contains three columns (screenshot of the table): "Country-Code", "Time", "Indicator". There are basically two types of indicators (1. amount in local currency and 2. EUR exchange rate). How can I create a new column "EUR_amount" in Python that divdes the amount with the rate in case the countrycode and the month is the same for both items, e.g. EUR = amount/rate where country and time matches?
Any help highly appreciated! (Please keep in mind that I am quite a noob with python and this is my first question on stackoverflow ever.) Thanks a lot in advance.
Edit: Adding this code after receiving feedback from mozway (thanks for that):
import pandas as pd
df = pd.DataFrame({'country_code':['EU','UK','US','EU','UK','US','EU','UK','US','EU','UK','US','EU','UK','US','EU','UK','US'],
               'date':['2019-03','2019-03','2019-03','2019-04','2019-04','2019-04','2019-05','2019-05','2019-05','2019-03','2019-03','2019-03','2019-04','2019-04','2019-04','2019-05','2019-05','2019-05'],
              'item':['exposure','exposure','exposure','exposure','exposure','exposure','exposure','exposure','exposure','FX-rate','FX-rate','FX-rate','FX-rate','FX-rate','FX-rate','FX-rate','FX-rate','FX-rate'],
              'value':[15000,9000,13000,16500,8750,17000,17000,7999,25000,1.00,1.25,0.90,1,1.23,0.93,1.00,1.24,0.95]})
print(df)

So, to restate my question: How can I divide the item exposure with the item FX-rate under the condition of country_code AND date are matching?

A: You can first split the data frames into two parts - exposure and FX-rate
fx = df[df["item"]=="FX-rate"]
exp = df[df["item"]!="FX-rate"]

After that, you can use
merged_df = pd.merge(fx,exp,on=["country_code","date"],how='outer')

See https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.merge.html for other arguments and examples.
The above will result in

country_code
date
item_x
value_x
item_y
value_y

EU
2019-03
FX-rate
1.00
exposure
15000.0

UK
2019-03
FX-rate
1.25
exposure
9000.0

US
2019-03
FX-rate
0.90
exposure
13000.0

EU
2019-04
FX-rate
1.00
exposure
16500.0

UK
2019-04
FX-rate
1.23
exposure
8750.0

US
2019-04
FX-rate
0.93
exposure
17000.0

EU
2019-05
FX-rate
1.00
exposure
17000.0

UK
2019-05
FX-rate
1.24
exposure
7999.0

US
2019-05
FX-rate
0.95
exposure
25000.0

Next is just a matter of division
merged_df["Convert"] = merged_df["value_y"]/merged_df["value_x"]


text:
Q: How to reset ONLY a single input tag in a formfield with just html5 i tried the following example and my aim is to achieve that if i press the reset button, only the field in the current line will be reseted, is this possible with only html5 and no jquery/ javascript ? any ideas are welcome :)
<form action="fieldset_legend.htm">
  <fieldset>
    <legend>Absender</legend>

        Ihr Vorname:
        <input id="vor" size="40" maxlength="40" name="Vorname" type="text">
        <input type="reset" for="vor" value="reset">

        Ihr Zuname:
        <input  id="nach" size="40" maxlength="40" name="Zuname" type="text">
        <input type="reset" for="nach" value="reset">

  </fieldset>
</form>

A: Use javascript...
function resetInput(id) {
   document.getElementById(id+"input").value="";
}

HTML:
    Ihr Vorname:
    <input id="vorInput" size="40" maxlength="40" name="Vorname" type="text">
    <input type="button" id="vor" onclick="resetInput(this.id) "value="reset">

    Ihr Zuname:
    <input  id="nachInput" size="40" maxlength="40" name="Zuname" type="text">
    <input type="button" id="nach" onclick="resetInput(this.id) value="reset">

A: I don't believe there is a way to avoid JavaScript in this case as the input 'reset' will reset for all the elements in the form.

reset: A button that resets the contents of the form to default
  values.

Input elements

A: I found a workarround what works for me.
You need to put your fields into nested forms e.g. like this:
<form action="fieldset_legend.htm">
  <fieldset>
    <legend>Absender</legend>
      <form id="line1">
        Ihr Vorname:
        <input id="vor" size="40" maxlength="40" name="Vorname" type="text">
        <input type="reset" for="vor" value="reset">
      </form>

      <form id="line2">
        Ihr Zuname:
        <input  id="nach" size="40" maxlength="40" name="Zuname" type="text">
        <input type="reset" for="nach" value="reset">
      </form>

  </fieldset>
</form>

The reset button will only reset the "closesest" form it finds, in this case it will reset only the "line1" form for the first button and the line2 form the other button.
EDIT:
I found acticles where people are calling nested forms a "hack" (like this one ), because it seems not to be part of the browser standards.
So keep in mind, that this nested forms solution, could cause unexpected behavior in some browsers, because this is currently not part of the standards (even if this works since decades of years)


text:
Q: How do I stop and remove KDE Baloo that is broken and filling up my syslog file? KDE baloo has recently caused rsyslog to start logging many errors.
Part of 'Syslog'
Mar  3 15:01:53 harry-S340 baloo_file.desktop[2982]: org.kde.baloo.engine: PositionDB::put MDB_BAD_TXN: Transaction must abort, has a child, or is invalid
Mar  3 15:01:53 harry-S340 baloo_file.desktop[2982]: org.kde.baloo.engine: PostingDB::put MDB_BAD_TXN: Transaction must abort, has a child, or is invalid
Mar  3 15:01:53 harry-S340 baloo_file.desktop[2982]: org.kde.baloo.engine: PositionDB::put MDB_BAD_TXN: Transaction must abort, has a child, or is invalid
Mar  3 15:01:53 harry-S340 baloo_file.desktop[2982]: org.kde.baloo.engine: PostingDB::put MDB_BAD_TXN: Transaction must abort, has a child, or is invalid
Mar  3 15:01:53 harry-S340 baloo_file.desktop[2982]: org.kde.baloo.engine: PositionDB::put MDB_BAD_TXN: Transaction must abort, has a child, or is invalid
Mar  3 15:01:53 harry-S340 baloo_file.desktop[2982]: org.kde.baloo.engine: PostingDB::put MDB_BAD_TXN: Transaction must abort, has a child, or is invalid
Mar  3 15:01:53 harry-S340 baloo_file.desktop[2982]: org.kde.baloo.engine: PostingDB::put MDB_BAD_TXN: Transaction must abort, has a child, or is invalid
Mar  3 15:01:53 harry-S340 baloo_file.desktop[2982]: org.kde.baloo.engine: PositionDB::put MDB_BAD_TXN: Transaction must abort, has a child, or is invalid
Mar  3 15:01:53 harry-S340 baloo_file.desktop[2982]: org.kde.baloo.engine: PostingDB::put MDB_BAD_TXN: Transaction must abort, has a child, or is invalid
Mar  3 15:01:53 harry-S340 baloo_file.desktop[2982]: org.kde.baloo.engine: PositionDB::put MDB_BAD_TXN: Transaction must abort, has a child, or is invalid
Mar  3 15:01:53 harry-S340 baloo_file.desktop[2982]: org.kde.baloo.engine: PostingDB::put MDB_BAD_TXN: Transaction must abort, has a child, or is invalid

It caused my /var/log/syslog to grow exponentially, it filled the disk once already, I've since disabled rsyslog to stop this from destroying my SSD and making Ubuntu unusable but I don't know what Baloo is or how to stop and uninstall it. When i fist noticed this /var/log/syslog had grown to 66GB causing my disk to be FULL. I was able to delete it and log back in and disable rsyslog through recovery mode. Running rsyslog for one second caused it to go up to 75MB.
'Neofetch --off' result
OS: Ubuntu 19.10 x86_64
Host: 81NC Lenovo IdeaPad S340-15API
Kernel: 5.3.0-40-generic
Uptime: 11 mins
Packages: 3040 (dpkg), 38 (snap)
Shell: bash 5.0.3
Resolution: 1920x1080
DE: GNOME
WM: Mutter
WM Theme: Adwaita
Theme: Yaru-dark [GTK2/3]
Icons: Yaru [GTK2/3]
Terminal: gnome-terminal
CPU: AMD Ryzen 5 3500U with Radeon Vega Mobile Gfx (8) @ 2.100GHz
GPU: AMD ATI 04:00.0 Picasso
Memory: 2756MiB / 5945MiB

I don't want to uninstall the whole of KDE straight away but if that is the only way to get rid of this broken program then I happily will.
Other commands
harry@harry-S340:~$ whereis baloo
baloo:

harry@harry-S340:~$ sudo apt-get autoremove baloo
[sudo] password for harry:
Reading package lists... Done
Building dependency tree
Reading state information... Done
Package 'baloo' is not installed, so not removed
0 to upgrade, 0 to newly install, 0 to remove and 4 not to upgrade.

harry@harry-S340:~$ whereis baloo_file
baloo_file: /usr/bin/baloo_file

harry@harry-S340:~$ sudo apt-get autoremove baloo_file
Reading package lists... Done
Building dependency tree
Reading state information... Done
E: Unable to locate package baloo_file

harry@harry-S340:~$ sudo systemctl status baloo_file
Unit baloo_file.service could not be found.

Pressing tab to see all the commands that have baloo in them:
harry@harry-S340:~$ baloo
balooctl                           baloo_filemetadata_temp_extractor
baloo_file                         baloosearch
baloo_file_extractor               balooshow

these all don't have any manuals
harry@harry-S340:~$ man baloo
No manual entry for baloo
harry@harry-S340:~$ man baloo_file
No manual entry for baloo_file
harry@harry-S340:~$ man balooctl
No manual entry for balooctl
harry@harry-S340:~$ man baloosearch
No manual entry for baloosearch
harry@harry-S340:~$ man balooshow
No manual entry for balooshow
harry@harry-S340:~$ man baloo_filemetadata_temp_extractor
No manual entry for baloo_filemetadata_temp_extractor
harry@harry-S340:~$ man baloo_file_extractor
No manual entry for baloo_file_extractor

Desktop file mentioned in syslog
[Desktop Entry]
Type=Application
Exec=baloo_file
X-KDE-StartupNotify=false
X-KDE-autostart-condition=baloofilerc:Basic Settings:Indexing-Enabled:true
X-KDE-autostart-phase=0
X-GNOME-Autostart-enabled=true
OnlyShowIn=KDE;GNOME;Unity;XFCE
NoDisplay=true

Requests
Balooctl status
harry@harry-S340:~$ balooctl status
Baloo File Indexer is running
Indexer state: Indexing file content
Total files indexed: 109,311
Files waiting for content indexing: 3
Files failed to index: 4
Current size of index is 507.65 MiB

harry@harry-S340:~$ sudo balooctl disable
[sudo] password for harry:
Disabling and stopping the File Indexer

this stopped rsyslog filling up /var/log/syslog.
Thanks,
Harry

A: For me, it just helped to disable content indexing like this:
balooctl config set contentIndexing no

This way, baloo should quickly make the index just for file names, so you can still search for file names in Dolphin.

A: I need to keep baloo, this corrected the syslog debugging issue, so I ran the following with success:
balooctl disable && balooctl purge && balooctl enable

Checking Status with balooctl status I get:
Baloo File Indexer is running
Indexer state: Idle
Total files indexed: 1,287
Files waiting for content indexing: 0
Files failed to index: 0
Current size of index is 16.04 MiB

Everything is now fine, disabling, purging, re-enabling the service keeps monitoring syslog in case

A: Here is how I removed baloo
balooctl disable                  # stops the service
sudo apt install -s baloo         # where to find baloo
sudo apt remove --purge libkf5balooengine5
rm -rf .local/share/baloo/        # removes the index files; they can be several GB

There are some related answers at Baloo creates 64GB index, takes half my memory and 25% CPU

A: This removed everything baloo without removing dolphin, plasma, kde. I was having screen lockups and the baloo_file indexer taking 112% cpu--I lost work rebooting because I could not even move into a terminal window and kill baloo_file. I am going to make this a cron script in case upgrades re-install baloo. You'd think the maintainer would renice baloo_file to lowest priority! That would not be great. I'm in Ubuntu 20.10 desktop.
balooctl disable

for baloo in `dpkg --list 'baloo-kf5*' 'libkf5baloo5*' 'libkf5balooengine5*' 'libkf5baloowidgets-bin*' 'libkf5baloowidgets-data*' 'libkf5baloowidgets5*' | sed -n -E '/^ii/s/^ii[\t ]+([^\t :]+).*/\1/p'`
 do echo $baloo
 sudo snap remove $baloo
 sudo dpkg --ignore-depends=$baloo --purge $baloo
done

rm -rf .local/share/baloo/

sudo updatedb ; ls `locate baloo`


text:
Q: Class in mainfile, method in another file I have two files, in the mainfile I have a class, in the other file I have a method which uses/edits the object of the class, how can I import the file.
mainfile:
import..? # the other file

class Fields:
        def __init__(self, y , x):
            self.positionx=x
            self.positiony=y
            self.color = 'white'
            self.free = True

            self.update()

        def update(self):
            ###

Field1=Fields(1,3)
###
### whatever...

2ndfile:
def change_color():
    actualcolor=Field1.color
    Field1.color='blue'
    Field1.update()
    ###

I tried:
    form 2ndfile import change_color
but it gave me the error:
NameError: name 'Field1' is not defined

Is it clear? How do I need to do that?
Tkx

A: What you are trying to do here is called Circular imports, which is something that is not supported by Python.
You can read more about it here, in general, it means that it's not possible to have 2 files which are dependent on each other.
To solve that problem, all you have to do is to extract the resource both files need, to another file they can import from, for example:
models.py
class Fields:
        def __init__(self, y , x):
            self.positionx=x
            self.positiony=y
            self.color = 'white'
            self.free = True

            self.update()

        def update(self):
            ###

Field1=Fields(1,3)

main.py
from models import Field1
from other_file import ...

def main():
    # Do stuff

other_file.py
from models import Field1
def change_color():
    actualcolor=Field1.color
    Field1.color='blue'
    Field1.update()
    ###


text:
Q: window form when form load unable direct navigate to another form when frmlogin form load i would like to direct navigate to another form, but it will just show frmLogin, unable to show form1
 private void frmLogin_Load(object sender, EventArgs e)
 {
     //if else condition to navigate to another form
     form1 frm = new form1();
     frm.Show();
     this.Hide();
 }

currently when click on button only able to navigate to another form
 private void button1_Click(object sender, EventArgs e)
 {
      frmSelectProfile frm = new frmSelectProfile();
      frm.Show();
      this.Hide();
 }

Please advice me on how can i navigate to another form when page load.

A: Form has "shown" event, use from it:
  private void Form1_Shown(object sender, EventArgs e)
  {
     var frm = new form1();
     this.Hide();
     frm.Show();
  }


text:
Q: i have two table find out only mismatch id table 1:
id
1
2
3
5
6

table 2:
id
2
3
7

I want only mismatch id from table 1 like my result should be 1,5,6.
Please help on this, thanks in advance.

A: You can use NOT IN
select id from table1 where id not in (select id from table2)

A: Try this:
SELECT * FROM table1 WHERE id NOT IN (SELECT id FROM table2)

A: This should work on mysql:
SELECT id FROM table1 LEFT JOIN table2 ON table1.id = table2.id WHERE NOT ISNULL(table2.id)

On mssql you can use table2.id IS NOT NULL instead of the NOT ISNULL(table2.id) construct

A: SELECT ID1

FROM TABLE_1

WHERE ID1 NOT IN(SELECT ID2 FROM TABLE_2);

You need to simply use the NOT IN clause in the WHERE condition , which will return to you unique IDs matching in TABLE_1


text:
Q: should I extend or create instance of the class I have two classes  Class A and Class B
In Class A, I have three methods that perform the save, delete and select operation based upon the object I pass them. In Class B I perform the logic operations, such as modification to the property of the object before being passed to the methods of Class A.
My problem is in Class B, should it extend Class A, and call the methods of class A , by parent::methodName or create instance of class A and then call
Class A does not includes any property just methods.
class A{
  public function save($obj){
         //code here
    }

   public function delete($obj){
         //code here
    }

    public function select($obj){
         //code here
    }
 }

//Should I extend class A, and call the method by parent::methodName($obj)
   or create an instance of class A, call the method $instanceOfA->methodName($obj);
 class B extends A{

    public function checkIfHasSaved($obj){
         if($obj->saved == 'Yes'){
                  parent::save($obj);   //**should I call the method like this**
                 $instanceOFA = new A();   //**or create instance of class A and call without extending class A**
                 instanceOFA->save($obj);
            }
             //other logic operations here
      }

 }

A: The examples given by you could have had meaningful class names, this would favor much better responses.
Since class A does not have any properties, it is safe to use methods from the instance you already have:
class B extends A
{
    public function checkIfHasSaved($obj)
    {
        if($obj->saved)
            $this->save($obj);
    }
}

Another alternative would be to use Dependency injection instead:
class B
{
    protected $a;

    public function __construct(A $theObject)
    {
        $this->a = $theObject;
    }

    public function checkIfHasSaved($obj)
    {
        if($obj->saved)
            $this->a->save($obj);
    }
}

A: Without knowing the names and purposes of the real classes it's hard to say.  The decision hinges on whether class B is really a type of class A or whether class B just needs some service class A provides.  For example, a lot of programmers make the mistake of building model classes by extending a database access layer class on the grounds that they need to access the database in order to persist their state. This is almost always a mistake.  A model class needs a database connection but it almost certainly isn't a kind of database connection.
It boils down to whether the link between the classes A and B is an is-a relationship or a has-a relationship.  In the former it makes sense to think of class B as a kind of class A, and if it's impossible for class B to gain or lose the behaviour of class A during its lifetime then an is-a relationship (subclassing) makes sense.  If the behaviour of class A is something that class B only needs under some circumstances, or if it doesn't make sense to think of class B in terms of being a kind of class A then composition (has-a relationship) is the more sensible approach.
Say you're modelling a school and have Person, Student and Teacher classes.  At first glance you might think that Student and Teacher are kinds of Person, and therefore Student and Teacher should extend Person.  But what happens should a particular student get a job at the school as a teacher after they graduate?  Student and Teacher are in fact roles that a Person can take on, they can discard those roles at the right time too.  In some systems the same person could hold more than one role at once (suppose a doctor gets hit by a car when going to work in a hospital, she could end up as a patient at that hospital!)
On the other hand, if you have a Car class, a Ferrari class and a Bugatti class, then it makes sense for Bugatti and Ferrari to be subclassed from Car.  The reason is that Ferraris and Bugattis are both kinds of car, and a Ferrari is always going to be a Ferrari from the moment it leaves the factory to the moment it's scrapped.  There's no circumstance under which a Ferrari is going to become a Bugatti.
So basically, TL:DR, it depends.

A: Since it's semantically correct to ask your object if it's saved then I guess it would be OK to ask it to save. If you extend saving will be a public method on your object and available from the outside.
You'll need to decide if that's OK or not.


text:
Q: How to find surface around a point on a multi variable function I have a function of 5 variables that represent a real physical system that I want to study.
I know the function and its 1st and 2nd derivative, but they are very long and you cannot say nothing by "looking at it".
So I would like to simplify it by writing its "tangent plane" around a point in which I know this system will work.
In three dimensions, I know that the equation of the tangent plane is:
$z = f(x_0, y_0) + \frac{\partial f} {\partial x} (x_0, y_0) (x - x_0) + \frac{\partial f} {\partial y} (x_0, y_0) (y - y_0)$
By adding the other variables, I obtain the equation of the 5 variables of my interest.
But doing this I will know only the effect of every single variable on the system, but I'm sure there will be interaction between variables. How can I find the equation that include the interactions?
Intuitively, I think I have to find partial derivative of two-by-two variables and find an equation like:
$z = f(x_0, y_0) + \frac{\partial f} {\partial x} (x_0, y_0) (x - x_0) + \frac{\partial f} {\partial y} (x_0, y_0) (y - y_0) + \frac{\partial f} {\partial x \partial y} (x_0, y_0) (x - x_0) (y - y_0)$
But I'm not sure this is the correct way, by searching on the web I cannot find answer.
So, is this correct?
And, is this the best way to study this type of function, or must I doing it another way?


text:
Q: Getting coordinates on touch event relative to scrollable map Is there a way to get the coordinates of a touch event on a scrollable map?
Meaning when I touch at one point on the screen, getX() and getY() return the respective values and then when I scroll the map, the coordinates returned should be relative to the map, not the screen.
eg. I have a 750x750 background map, and my device screen size is 480x800.
when I first touch, say the coordinates returned are (100, 200). now when I scroll the map and touch somewhere else,  I get the coordinates as 200, 200.
I want to get the coordinates with respect to the map and not the screen.
I've been trying to figure this out for a long time and have scoured the net and other sites in vain.
please help.
thanks in advance
\m/
i need the coordinates coz i'm developing a game in which  i have a large map and objects placed on it. when i scroll the map, i need the objects to move along with in the same position.
here is my code:
@Override
public boolean onTouchEvent(MotionEvent ev) {

    switch (ev.getAction()) {

    case MotionEvent.ACTION_DOWN:
         touchStart.set(ev.getX(), ev.getY());
     x = ev.getX();
     y = ev.getY();
        break;
    case MotionEvent.ACTION_MOVE:
        newX = ev.getX() - touchStart.x + prevPicStart.x;
        newY = ev.getY() - touchStart.y + prevPicStart.y;
        if ((newX <= 0 && newX > 0 - mBG.getWidth() + Craz.DISP_WIDTH)) {
            picStart.x = newX;
          }
        if ((newY <= 0 && newY > 0 - mBG.getHeight() + Craz.DISP_HEIGHT)) {
            picStart.y = newY;

        }
        invalidate();
        break;

    case MotionEvent.ACTION_UP:

        prevPicStart.x = picStart.x;
        prevPicStart.y = picStart.y;

        break;
    }
    return true;
}

@Override
protected void onDraw(Canvas canvas) {
    Paint paint = new Paint();
    canvas.drawBitmap(mBG, picStart.x, picStart.y, paint);

    canvas.translate(picStart.x, picStart.y);

    mBDoor.draw(canvas);
}

A: Its pretty easy. When you scroll your map, you have an offset. If you scroll to the right (the background will move to the left), your offset will be negative. Lets say, you have an offset on x of -50, and you click the screen coordinates 100 you simply do the math:
mapCoordX = screenX - offsetX; // makes: 100 - (-50) = 150

just looking at the X coordinate, for Y it should be the same.
I have written a tutorial about a map of tiles and scrolling over it. Maybe you take a look at it, too.
Pseudocode!
for (int id = 0; id < mapSize; id++) {
  Tile tile = new Tile(id);
  startX = id * tileWidth;
  startY = id % rowLenght + id / rowLenght;
  tile.setBackground(createCroppedBitmap(background, startX, startY));
}


text:
Q: How to extract the node from the subsequent page after clicking the submit button using selenium and xpath? I'm trying to use xpath to test a site.  I have been able to go to the site, enter a value in the input text box and submit. But for my next portion, I need to go to the URL that the site goes to after submitting the input button. This is what I have so far:
driver.get(url)
driver.find_element_by_xpath(".//input[@id='keyword']").send_keys(company_name)
driver.find_element_by_class_name('button').click()

After the click, the page navigates to a different url than the one I initially provided. The next page is where all the remaining test needs to be performed. I could find out any information on how to retrieve the url for the next page and rerun the driver to locate other nodes. Is there a way to do this?


text:
Q: How to Set OnClickListener to Card in PlaceholderView? I am using PlaceHolderView library to show an Infinite List of contents like the Facebook Android app. I was using InfinitePlaceHolderView for it. It looks like this:
And here is how it looks like output
Now If the story is large then a user can click on the card view and it will take him to a new activity where there will be a detail of that story. For this, I need to add a Listener. But I could not find any documentation at all, how to implement it. The documentation shows that all those cards are dynamically created and not any of those cards have any id so that I can put a listener.
How to implement it?

A: So, what I did is given below:
In my feed.xml file which contain the above view, I set an id for the whole view. Then I used that id and used it ItemView.java from here:
feed.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/home_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/grey_100"
    android:orientation="vertical"
    android:weightSum="4"
    tools:context="com.example.shamsad.tutionhub.activities.FeedActivity">

    <android.support.v7.widget.Toolbar
        android:layout_width="match_parent"
        android:layout_height="?android:attr/actionBarSize"
        android:id="@+id/tbHome"
        android:background="@color/colorPrimary"
        app:titleTextColor="@color/grey_100">
    </android.support.v7.widget.Toolbar>

    <com.mindorks.placeholderview.InfinitePlaceHolderView
        android:id="@+id/loadMoreView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

</LinearLayout>

ItemView.java
@Click(R.id.rootView)
    public void onCardClick() {
        Intent intent = new Intent(mContext, DetailActivity.class);
        intent.putExtra("title", mInfo.getTitle());
        intent.putExtra("caption", mInfo.getCaption());
        intent.putExtra("salary", mInfo.getSalary());
        intent.putExtra("routine", mInfo.getRoutine());
        intent.putExtra("time", mInfo.getTime());
        Log.d("sajid", "onClick");
        mContext.startActivity(intent);
    }

So, in this onCardClick() method, the clickable id is set up by this code @Click(R.id.rootView). And that's all. It basically sets the whole card-view as a clickable thing.
And also thanks to the writer of this great library Janisher Ali. I contacted him and he helped a lot, and it worked.
This is a great library. To me much better than RecyclerView. You can try it out :)

A: In step three of the documentation you have an example of the Event Bind:
@Animate(Animation.ENTER_LEFT_DESC)
@NonReusable
@Layout(R.layout.gallery_item_big)
public class ImageTypeBig {

    @View(R.id.imageView)
    private ImageView imageView;

    private String mUrl;
    private Context mContext;
    private PlaceHolderView mPlaceHolderView;

    public ImageTypeBig(Context context, PlaceHolderView placeHolderView, String url) {
        mContext = context;
        mPlaceHolderView = placeHolderView;
        mUrl = url;
    }

    @Resolve
    private void onResolved() {
        Glide.with(mContext).load(mUrl).into(imageView);
    }

    @LongClick(R.id.imageView)
    private void onLongClick(){
        mPlaceHolderView.removeView(this);
    }

}

More information:
https://github.com/janishar/PlaceHolderView#step-3-create-item-class-to-bind-and-define-view-operations


text:
Q: Based on if else conditon show the sidebars in angular I am beginner in angular. I am working on project  like want to give if else condition in root and if means shows one sidebar1 and else means sidebar2.i do not know am doing correct or not
In app.component.html
<div *ngIf ="show; else hide">
<sidebar1-cmp></sidebar1-cmp>
<ng-template #hide>
<Sidebar2-cmp></sidebar2-cmp>
</ng-template>
</div>

Simply
If()
{ Shows sidebar1}
Else
{shows sidebar2}
I do not know,how do use this reference variable(#show,#hide) in child components(sidebar1,sidebar2)

A: Try moving the *ngIf to sidebar1 component tag, like the following:
<div>
  <sidebar1-cmp *ngIf="show; else hide"></sidebar1-cmp>
  <ng-template #hide>
    <Sidebar2-cmp></sidebar2-cmp>
  </ng-template>
</div>


text:
Q: How many ways are there to read years like "123 BC","49","1500","2009",etc.? I've heard people say "2 thousand and 15", "twenty fifteen", "two-O-one-five",are they all acceptable?
How many ways are there to express such years like "23 BC","49 AD","1500","2009",etc.?

A: When it comes to a two-digit number, I don't think of any other possibility.

23 BC - Twenty three BC

When you talk about a four digit year, there are two possibilities I can think of.

2015 - Two thousand fifteen or twenty fifteen

'Two O one five' is technically correct, but I don't remember that it is exclusively used to call some year. It serves more as a number  than a year to me.
For 1500, again, only one way:

1500 - fifteen hundred

Just a note: We write BC after the year and AD before the year.

23 BC

But

AD 2050

A: The most traditional style, commonly used on certificates until the late 1900's (that's "nineteen hundreds"), is such for the year 1909:

In the year of our Lord One Thousand Nine Hundred and Nine...

This can also be found in some older academic papers, and is a direct translation of Anno Domini 1909, or AD 1909. More modernly, the direct religious reference has made it fall out of style in many circles.


text:
Q: Riemann zeta for real argument between 0 and 1 using Mellin, with short asymptotic expansion The following would appear to be true.
For real $0 < \sigma < 1,$ we seem to have a very satisfying sum minus integral limit,
$$  \zeta(\sigma)  \; \; = \; \;  \lim_{n \rightarrow \infty} \; \; \left( \sum_{k=1}^n \frac{1}{k^\sigma}   \right) - \frac{n^{1-\sigma}}{1-\sigma} \; \; . $$
A little more detail in these examples:
$$ \lim_{n \rightarrow \infty} \; \; \left( \sum_{k=1}^n \frac{1}{\sqrt k}   \right) - 2 \sqrt n - \frac{1}{2 \sqrt n} + \frac{1}{24 n^{3/2}} \; \; = \; \; \zeta \left(\frac{1}{2}\right) \approx -1.460354508809586  $$
$$ \lim_{n \rightarrow \infty} \; \; \left( \sum_{k=1}^n \frac{1}{\sqrt[3] k}   \right) - \frac{3 n^{2/3}}{2} - \frac{1}{2 \sqrt[3] n} + \frac{1}{36 n^{4/3}} \; \; = \; \; \zeta \left(\frac{1}{3}\right) \approx -0.973360248350782  $$
So, are the above items really really true (rather than wishful thinking), and, if so, given $0 < \sigma < 1,$ what real numbers $A = A(\sigma), B = B(\sigma),$  make the short asymptotic expansion below correct?
$$ \left( \sum_{k=1}^n \frac{1}{k^\sigma}   \right) - \frac{n^{1-\sigma}}{1-\sigma} - A n^{-\sigma} + B n^{-1-\sigma} \; \; = \; \;  \zeta(\sigma) \; \; + \; \;  O(n^{-2-\sigma}) \; \; ? $$
Here is an estimate of $\zeta\left( \frac{1}{5} \right)$ using Daniel's expansion as far as the $3+\sigma$ term, ignoring $5+\sigma$: $$ \zeta(\sigma) =\left( \sum_{k=1}^n \frac{1}{k^\sigma}   \right) - \frac{n^{1-\sigma}}{1-\sigma} - \frac{1}{2 n^\sigma} + \frac{\sigma}{12 n^{1 + \sigma}} - \frac{\sigma (1 + \sigma)(2 + \sigma)}{720 n^{3+\sigma}} + O \left( \frac{1}{n^{5 + \sigma}} \right)$$
I think it will let me fit 33 lines in a "code" window without introducing a scroll bar.
    1   1                   -0.7340666666666666
    2   1.870550563296124   -0.7339263390330826
    3   2.673292125056355   -0.7339216399387463
    4   3.431150408311554   -0.7339210905379737
    5   4.155930071989249   -0.7339209776636304
    6   4.854757190760828   -0.7339209455319796
    7   5.532368104161309   -0.7339209342063361
    8   6.192122059547756   -0.7339209295629763
    9   6.836516074525011   -0.7339209274322004
   10   7.467473419005204   -0.7339209263652269
   11   8.086517339689049   -0.7339209257924113
   12   8.694881681582254   -0.7339209254668952
   13   9.293584537123753   -0.7339209252729478
   14   9.883479099480143   -0.7339209251526775
   15   10.46528985863283   -0.7339209250754953
   16   11.03963903613135   -0.7339209250244763
   17   11.60706632180293   -0.7339209249898626
   18   12.16804389452603   -0.7339209249658375
   19   12.72298804735438   -0.7339209249488197
   20   13.27226831900744   -0.7339209249365428
   21   13.81621476189632   -0.7339209249275397
   22   14.35512379575268   -0.7339209249208374
   23   14.8892629725969    -0.7339209249157863
   24   15.41887489312131   -0.7339209249119263
   25   15.94418045400206   -0.733920924908948
   26   16.46538156214071   -0.7339209249066238
   27   16.98266342011249   -0.7339209249047942
   28   17.49619646365717   -0.7339209249033369
   29   18.00613801451264   -0.7339209249021712
   30   18.51263369862476   -0.7339209249012291
   31   19.01581866962328   -0.733920924900462
   32   19.51581866962328   -0.7339209248998368
   33   20.0127509533112    -0.7339209248993227

A: The Euler-Maclaurin formula gives the asymptotic expansion
\begin{equation}
  \sum_{k = 1}^{n} \frac{1}{k^{\sigma}} = \zeta(\sigma) + \sum_{k = 0}^{\infty} \frac{(-1)^k}{1-\sigma} \binom{1-\sigma}{k} B_k n^{1-\sigma-k}\,.
\end{equation}
Thus $A = -B_1 = \frac{1}{2}$ and $B = -\frac{(-1)\sigma}{2}B_2 = \frac{\sigma}{12}$.
Taking a few more terms, we get
\begin{align}
\zeta(\sigma) &= \sum_{k = 1}^n \frac{1}{k^{\sigma}} - \frac{n^{1-\sigma}}{1-\sigma} - \frac{1}{2n^{\sigma}} + \frac{\sigma}{12 n^{1+\sigma}} - \frac{\sigma(1+\sigma)(2+\sigma)}{720 n^{3+\sigma}} \\
&\qquad+ \frac{\sigma(1+\sigma)(2+\sigma)(3+\sigma)(4+\sigma)}{30240n^{5+\sigma}} + O(n^{-7-\sigma})\,.
\end{align}

A: There is  a standard technique  that produces the  complete asymptotic
expansion  for this  sum and  many  others like  it, which  is to  use
harmonic sums and Mellin transforms.
Introduce the telescoping sum where $0\lt\sigma\lt 1$
$$S(x) = \sum_{k\ge 1} \left(\frac{1}{k^\sigma}-
\frac{1}{(x+k)^\sigma}\right).$$
This sum has the property that
$$S(n) = \sum_{p=1}^n \frac{1}{p^\sigma},$$
so that $S(n)$ is the value we are looking for.
Re-write the sum as follows:
$$S(x) = \sum_{k\ge 1} \frac{1}{k^\sigma}
 \left(1-\frac{1}{(x/k+1)^\sigma}\right).$$
The sum term is harmonic and  may be evaluated by inverting its Mellin
transform.
Recall the harmonic sum identity
$$\mathfrak{M}\left(\sum_{k\ge 1} \lambda_k g(\mu_k x);s\right) =
\left(\sum_{k\ge 1} \frac{\lambda_k}{\mu_k^s} \right) g^*(s)$$
where $g^*(s)$ is the Mellin transform of $g(x).$
In the present case we have
$$\lambda_k = \frac{1}{k^\sigma},
\quad \mu_k = \frac{1}{k} \quad \text{and} \quad
g(x) = 1 - \frac{1}{(1+x)^\sigma}.$$
It follows that
$$\sum_{k\ge 1} \frac{\lambda_k}{\mu_k^s} =
\sum_{k\ge 1} \frac{1}{k^\sigma} \times k^s
= \zeta(\sigma-s)$$
which has fundamental strip $\sigma-s > 1$ or $s < \sigma-1.$
We need the Mellin transform $g^*(s)$ of $g(x)$ which is
$$\int_0^\infty \left(1 - \frac{1}{(1+x)^\sigma}\right) x^{s-1} dx$$
which is immediately seen to be a beta function integral with value
$$g^*(s) = - \frac{1}{\Gamma(\sigma)} \Gamma(s)\Gamma(\sigma-s)$$
and  fundamental strip  $\langle -1,  0  \rangle.$ We  check that  the
abscissa of  convergence of the  zeta function  term is right  in this
strip as required. It follows that  the Mellin transform $Q(s)$ of the
harmonic sum $S(x)$ is given by
$$Q(s) =
- \frac{1}{\Gamma(\sigma)} \Gamma(s)\Gamma(\sigma-s)
\zeta(\sigma-s).$$
The Mellin inversion integral here is
$$\frac{1}{2\pi i}
\int_{\sigma-1-\varepsilon-i\infty}
^{\sigma-1-\varepsilon+i\infty} Q(s)/x^s ds$$
which we  evaluate by  shifting it  to the right  for an  expansion at
infinity.
First  treat the  pole from  the zeta  function term  at $s=\sigma-1$,
which has
$$\mathrm{Res}(Q(s)/x^s; s=\sigma-1) =
-\frac{1}{\Gamma(\sigma)} \Gamma(\sigma-1)\Gamma(1)
\times -1 \times x^{1-\sigma}
= -\frac{1}{1-\sigma} x^{1-\sigma}.$$
For the pole at $s=0$ from the simple gamma function term we obtain
$$\mathrm{Res}(Q(s)/x^s; s=0) =
-\frac{1}{\Gamma(\sigma)} \Gamma(\sigma) \zeta(\sigma)
= -\zeta(\sigma).$$
For the pole at $s=\sigma$ from the compound gamma function term we obtain
$$\mathrm{Res}(Q(s)/x^s; s=\sigma) =
 -\frac{1}{\Gamma(\sigma)} \Gamma(\sigma) \times -1 \times\zeta(0)
\times \frac{1}{x^\sigma}
= -\frac{1}{2} \frac{1}{x^\sigma}.$$
The remaining poles are at $s = q+\sigma$ where $q\ge 1$ and contribute
$$\mathrm{Res}(Q(s)/x^s; s=q+\sigma) =
-\frac{1}{\Gamma(\sigma)} \Gamma(\sigma+q)
\frac{(-1)^{q+1}}{q!} \zeta(-q) \frac{1}{x^{q+\sigma}}
\\ = - \prod_{p=0}^{q-1} (p+\sigma) \times
 \frac{(-1)^{q+1}}{q!} (-1)^q \frac{B_{q+1}}{q+1} \frac{1}{x^{q+\sigma}}
= {q+\sigma-1\choose q}
\frac{B_{q+1}}{q+1}  \frac{1}{x^{q+\sigma}}.$$
The  zero   values  of  the  Bernoulli   numbers  correctly  represent
cancelation of  the gamma function poles  by the trivial zeros  of the
zeta function.
Setting $x=n$  and observing that  the shift  to the right  produces a
minus sign we obtain the following asymptotic expansion:
$$S(n) = \sum_{p=1}^n \frac{1}{p^\sigma}
\\ \sim \frac{1}{1-\sigma} n^{1-\sigma}
+ \zeta(\sigma) + \frac{1}{2} \frac{1}{n^\sigma}
- \sum_{q\ge 1} {q+\sigma-1\choose q}
\frac{B_{q+1}}{q+1}  \frac{1}{n^{q+\sigma}}.$$
Actually computing the Bernoulli number terms we get for the example
by OP with $\sigma=1/3$ the expansion
$$3/2\,{n}^{2/3}+\zeta  \left( 1/3 \right)
+1/2\,{\frac {1}{\sqrt [3]{n}}}
-1/36\,{n}^{-4/3}+{\frac {7}{4860\,{n}^{10/3}}}
\\-{\frac {13}{26244\,{n}^{16/3}}}
+{\frac {247}{590490}{n}^{-{\frac {22}{3}}}}
-{\frac {6175}{9565938}{n}^{-{\frac {28}{3}}}}
\\+{\frac {406999}{258280326}{n}^{-{\frac {34}{3}}}}
-{\frac {12966835}{2324522934}{n}^{-{\frac {40}{3}}}}+\cdots$$
This    MSE    link
points to a series of similar calculations.

A: This is indeed true. In fact, this formula can be derived from the Euler summation formula with $f(x)=x^{-s}$ with $0<s<1$. We have
$$\begin{align*}
\sum_{n\leq x}\frac{1}{x^s}&=\int_1^x\frac{dt}{t^s}-s\int\frac{t-[t]}{t^{s+1}}dt+1-\frac{x-[x]}{x^s} \\
 &=\frac{x^{1-s}}{1-s}-\frac{1}{1-s}+1-s\int_1^\infty\frac{t-[t]}{t^{s+1}}dt+O(x^{-s}).
\end{align*}$$
If we take the limit as $x\rightarrow\infty$ we find that
$$1-\frac{1}{1-s}-s\int_1^\infty\frac{t-[t]}{t^{s+1}}dt=\zeta(s)$$
so we then have
$$\lim_{x\rightarrow\infty}\left(\sum_{n\leq x}\frac{1}{n^s}-\frac{x^{1-s}}{1-s}\right)=\zeta(s),\;\;0<s<1$$
as desired.
Note that $[t]$ is the greatest integer function. This proof can be found in Introduction to Analytic Number Theory by Apostol.


text:
Q: How can I hide a class member from other objects of the same type? I'm writing a card game program in C#. I have a Player class, and each player can store multiple cards. For simplicity sake let's say that each Player has two cards, the VisibleCard and the HiddenCard. The VisibleCard is something everyone can see - imagine it's a card you play on the table. The HiddenCard is something only the player can see - i.e. it's what the player would hold in their hand.
I want to restrict the HiddenCard field so that only the Player object whom it belongs to can read it, and all other Player objects cannot. In other words, I want to encapsulate these fields on the object-level, not the class-level.
I've written a cursory attempt to implement this behaviour, but I'm wondering if there is a neater or more elegant way to do this in C#, or whether this approach has any holes in it?
class Program
{
    sealed class Player
    {
        public string Name;

        private string VisibleCard { get; }

        private string HiddenCard { get; }

        public Player(string name, string visibleCard, string hiddenCard)
        {
            Name = name;
            VisibleCard = visibleCard;
            HiddenCard = hiddenCard;
        }

        public void ReadPlayerCard(Player otherPlayer)
        {
            Console.Write("\n{0}'s hidden card: ", otherPlayer.Name);
            if (this == otherPlayer)
                Console.WriteLine(otherPlayer.HiddenCard);
            else
                Console.WriteLine("You can't see that.");

            Console.Write("{0}'s visible card: ", otherPlayer.Name);
            Console.WriteLine(otherPlayer.VisibleCard);

        }
    }

    static void Main(string[] args)
    {
        Player Alice = new Player("Alice", "Seven of Diamonds", "Four of Clubs");
        Player Bob = new Player("Bob", "Queen of Hearts", "Ace of Spades");

        Console.WriteLine("Bob is reading Alice's cards:");
        Bob.ReadPlayerCard(Alice);

        Console.WriteLine("\nAlice is reading Alice's cards:");
        Alice.ReadPlayerCard(Alice);

        Console.ReadLine();
    }
}

Leading to this result:
Bob is reading Alice's cards:

Alice's hidden card: You can't see that.
Alice's visible card: Seven of Diamonds

Alice is reading Alice's cards:

Alice's hidden card: Four of Clubs
Alice's visible card: Seven of Diamonds

So it does work, but I'm wondering: are there any ways that this could be exploited? The class is sealed so it can't be inherited, but I'm not sure whether this is the most straightforward approach to encapsulate members from other objects of the same type.
Any suggestions?

A: Access modifiers purpose
The purpose of all access modifiers is to help a fellow programmer* from doing stuff with the class he is not supposed to do. They do not offer security in any way, shape or form.
And you should not overuse them. Way too often a unessesary acessor forced programmers to rewrite a entire library from scratch - because they need that one piece that for no sensible reason was marked as private.
Security in Multiplayer Games
The first security level in multiplayer games, is to not display information the user is not supposed to have. The only way to circumvent that would be direct memory access. Access modifiers in no way, shape or form make that attack harder.
The 2nd security level in multiplayer games is to not transmit information to the client programm in the first place. No memory access can retreive information that is not there. Access modifiers again do not help in any way I can imagine.
*This fellow programmer could be your future self. The reason why you should write commentents, is that in 1-6 months you will have completely forgotten everything about that code. So you yourself might be the one that needs this guidance from his past self - or has to relearn the whole class from scratch.


text:
Q: Table with two columns with fixed width I want to create a table of two columns with fixed width, like in the following image:

I used this code:
\begin{tabular}{c c}
\setlength\arraycolsep{10pt}

AVG & The average weight of a document is calculated as the sum of weights W(t,c) of its terms dithe document.  \\
STD & The standard deviation of the weighted as    of the snus the av\\
MIN & The minimum weight of a document is the l)  in the document.  \\
MAX & The  weight of a  term weight W(t,c) found  \\
PROB & The overall weight of a docuvided by the total number the docu \\
PROP & The between the number of vocabulary terms of the docume
\end{tabular}

But the problem is, there are no borders !, also the text is overlapped with the second column of the document !!

A: Use this:
\documentclass[twocolumn]{article}

\usepackage{tabularx, ragged2e, caption, lipsum}
\setlength{\extrarowheight}{2pt}

\begin{document}

\lipsum[1]
\begin{table}[!htb]
\caption{my caption} \label{some-label}% for cross references
\begin{tabularx}{\linewidth}{|l|>{\arraybackslash\RaggedRight}X|}
\hline
    AVG & The average weight of a document is calculated as the sum of weights W(t,c) of its terms dithe document. \\
    \hline
    STD & The standard deviation of the weighted as of the snus the av\\
    \hline
    MIN & The minimum weight of a document is the l) in the document. \\
    \hline
    MAX & The weight of a term weight W(t,c) found \\
    \hline
    PROB & The overall weight of a docuvided by the total number the docu \\
    \hline
    PROP & The between the number of vocabulary terms of the document\\
    \hline
    \end{tabularx}
\end{table}

\end{document}


text:
Q: Add Extra Tab in Products Storefront UI - Opencart v3 I'm attempting to add another tab in addition to the Reviews and Description to the default opencart v3 default products.
Demo here to help clarify
https://demo.opencart.com/index.php?route=product/product&path=20_27&product_id=41
I've found little documentation on this new version of opencart, so I'm hoping to find out what files I need to modify in order to do this.
So far I'm sure of
/store/public_html/catalog/view/theme/default/template/product/product.twig
What other files will I need to modify in order to to add an extra tab?


text:
Q: Handling dependency injection when seeding the database I need to seed the application database with default users. I don't use Entity Framework in this project, I've decided to use Dapper instead.
Simplest thing that I can do is to have a simple class like DatabaseConfig (or AccountsConfig) with a Seed() static method:
public class DatabaseConfig {

    public static void Seed() {

        using(var conn = new SqlConnection()) {

            conn.ConnectionString = GetConnectionString();
            conn.Open();

            var query = "insert into users (username, [password]) values (@username, @password)";

            var queryParams = new {
                username = "Admin",
                password = HashedPassword.CreateHash("DefaultSecretKey")
            }

            conn.Execute(query, queryParams);
        }

    }

    private static string GetConnectionString() {
        return ConfigurationManager.ConnectionStrings["appDb"].ConnectionString;
    }
}

and then to call it in the Global.asax:
DatabaseConfig.Seed();

I have two dependencies here:

*

*I call a ConfigurationManager to get a connection string. I don't know if this is a bad approach. For other services I use in the application I pass the connection strings as a constructor parameters in the SimpleInjector initializer:
private static void InitializeContainer(Container container) {

    var appDbConnString = ConfigurationManager.ConnectionStrings["appDb"].ConnectionString;
    container.RegisterSingleton<IUsersRepository>(new UsersRepository(appDbConnString));

}

*The other dependency is HashedPassword class. I don't expect it to change with time but still this is a dependency. Should I resolve it? How do I resolve it?

A:
I call a ConfigurationManager to get a connection string. I don't know if this is a bad approach.

In general, you should only read the config file at application startup, and preferably only within the startup path of the application. This allows the reading of the config file to be centralized in one single place and it allows the application to fail fast in case some configuration value is missing.
You seem to follow that practice, so I would say what you're doing is fine.

The other dependency is HashedPassword class. I don't expect it to change with time but still this is a dependency. Should I resolve it?

Since this Seed method seems to be part of your composition root, it's okay to have strong dependencies on other classes in your system. Or let me put it differently, if the use of this dependency doesn't cause trouble in any way (because you don't want to test the code in isolation, or want to replace, wrap, decorator or intercept the code inside that class), I would say this is okay.
If however you want this HashesPassword class to be injectable, you will have to make it an instance class. In that case you should probably hide it behind an abstraction (like IHashPashword) and pass it as parameter into the Seed() method, or you should promote the DatabaseConfig to a non-static class with non-static methods and inject the IHashPashword abstraction into its constructor. This allows you to resolve DatabaseConfig from the container.

A: you are accessing HashedPassword and ConfigurationManager in static way, this means you need to change them to non static classes in order to dependency inject them. that can be done by changing them (which may be not possible is they are not your classes) or to wrap them in an instance class.


text:
Q: Pandas Iterrows: Faster Alternatives? I am trying to speed up one of my functions. I have read that 'vectorization' is the fastest way to run these types of operations in Pandas, but how is this (or anything else faster) achievable with this code:
Dummy data
a = pd.DataFrame({'var1' : [33, 75, 464, 88, 34], 'imp_flag' : [1, 0, 0, 1, 1], 'donor_index' : [3, np.nan, np.nan, 4, 0]})

>>> a
   var1  imp_flag  donor_index
0    33         1          3.0
1    75         0          NaN
2   464         0          NaN
3    88         1          4.0
4    34         1          0.0

The operation in question
for index, row in a[a['imp_flag'] == 1].iterrows():
    new_row = a[a.index == row.donor_index]
    b = b.append(new_row)

Expected output
>>> b
   var1  imp_flag  donor_index
1    75         0          NaN
1    75         0          NaN
2   464         0          NaN

A: There are several things that I do not understand
How is it possible that your dataFrame returns Nan values in donor_index if there are no Nan value when you create a
a = pd.DataFrame({'var1' : [33, 75, 464, 88, 34], 'imp_flag' : [1, 0, 0, 1, 1], 'donor_index' : [3, 1, 2, 4, 0]})

>>> a
   var1  imp_flag  donor_index
0    33         1            3
1    75         0            1
2   464         0            2
3    88         1            4
4    34         1            0

Are you sure that in your example the selection a[a['imp_flag'] == 1] is correct? It seems the way you get that results on b is the opposite a[a['imp_flag'] == 0]
Then, do you really need duplicated values in dataFrame b?
My solution is the following:
idxs = a[a.imp_flag == 0].donor_index
b = a.iloc[idxs]
# or in one-line b = a.iloc[a[a.imp_flag == 0].donor_index]

>>> b
   var1  imp_flag  donor_index
1    75         0            1
2   464         0            2

A: IIUC, you want to subselect rows if imp_flag equals 1
You can simply use query to match the relevant rows:
b = a.loc[a.query('imp_flag == 1')['donor_index']]

Alternatively, you can index and select your data with:
b = a.loc[a[a['imp_flag'] == 1]['donor_index']]

output:
   var1  imp_flag  donor_index
3    88         1            4
4    34         1            0
0    33         1            3


text:
Q: Failed to detect set buildpack when it's just been set for Python? I've been trying to push a django web app to heroku with no avail because of the following error:
(venv)douglaswong@Douglas-MacBook-Pro ~/testing (testing)$ git push heroku master
Counting objects: 53, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (35/35), done.
Writing objects: 100% (53/53), 41.11 KiB | 0 bytes/s, done.
Total 53 (delta 12), reused 48 (delta 11)
remote: Compressing source files... done.
remote: Building source:
remote:
remote: -----> Fetching set buildpack git://github.com/heroku/heroku-buildpack-python.git... done
remote:
remote:  !     Push rejected, failed to detect set buildpack git://github.com/heroku/heroku-buildpack-python.git
remote: More info: https://devcenter.heroku.com/articles/buildpacks#detection-failure
remote:
remote: Verifying deploy...
remote:
remote: !   Push rejected to sleepy-spire-9508.
remote:
To https://git.heroku.com/sleepy-spire-9508.git
 ! [remote rejected] master -> master (pre-receive hook declined)
error: failed to push some refs to 'https://git.heroku.com/sleepy-spire-9508.git'

It says it failed to detect set buildpack. However, I had set it with
(venv)douglaswong@Douglas-MacBook-Pro ~/testing (testing)$ heroku create --buildpack git://github.com/heroku/heroku-buildpack-python.git
Creating fierce-waters-9228... done, stack is cedar-14
Buildpack set. Next release on fierce-waters-9228 will use git://github.com/heroku/heroku-buildpack-python.git.
https://fierce-waters-9228.herokuapp.com/ | https://git.heroku.com/fierce-waters-9228.git

What are some possible causes for this? I currently have these files in my root directory if it makes a difference:
Procfile         angellistJob     venv
README.md        requirements.txt

Any advice is appreciated, thank you!

A: I had a similar issue. For me the problem was that I forgot to commit the changes to my local repo.
Also, make sure you commit to the same branch you're pushing to.
Hope this helps!

A: Just to bring to the notice of anyone who has the same problem.
Even I had the same problem and was committing to the exact branch I was pushing to. However, since I didn't have the requirements.txt file, the push was being rejected.
So, also make sure you have the Procfile and the requirements.txt before pushing to heroku.

A: I found out that this issue might occur for two reasons:

*

*There isn't the requirements.txt file in the current directory.

*You are pushing on a different branch.

On the other hand you could set the respective buildpacks at the moment of create the app.
heroku create myapp --buildpack heroku/python


text:
Q: When trying to connect jenkins and kubernetes, Jenkins job throws the following error Started by user admin.
Running as SYSTEM.
Building in workspace /var/lib/jenkins/workspace/myjob
[myjob] $ /bin/sh -xe /tmp/jenkins8491647919256685444.sh
+ sudo kubectl get pods
error: the server doesn't have a resource type "pods"
Build step 'Execute shell' marked build as failure
Finished: FAILURE

A: It looks to me that the authentication credentials were not set correctly. Please copy the kubeconfig file  /etc/kubernetes/admin.conf  to  ~/.kube/config? Also check that the KUBECONFIG variable is set.
It would also help to increase the verbose level using the flag  --v=99.
Please take a look: kubernetes-configuration.


text:
Q: Why does windows 7 shutdown require so much hard drive usage? When I shut down linux, for example, it takes a couple seconds. All it does is shut down running services, maybe write a couple log files etc... On my windows 7 box however it takes about 1 minute to shut down and the hdd i/o light is completely lit.
Is windows 7 writing a lot of log files or is something else going on when I shut down? Also, does this happen for linux based oses?

A: In my experience, it also takes a bit longer to log off and subsequently shut down if your computer is connected to a domain network.

A: It's not a problem with Windows 7. It's a problem with how you've maintained your PC. Mine takes around 5 seconds to shut down (Windows 7 64-bit).
Open Task Manager and see what services and processes are running. I bet if you use MSTSC to disable the bulk of your unnecessary background tasks, you'll see a massive performance increase.
I only have my antivirus (Microsoft Security Essentials), and F.lux (automatically sets screen brightness levels depending on time of day) run when my PC starts- no need for anything else. The majority of people only need antivirus to run on system start.
If you've got a bloated antivirus program (Norton/AVG etc.) that will add a few seconds to shutdown.


text:
Q: Android Beta Test Program - Item not found, 0 devices I had difficulty with setting up my APK submission to the Android Beta Test Program.  At first I received 0 devices compatible, then I received Item not found.  It took me days to figure this out so I figured I'd post here.
-J

A: For the 0 devices issue I changed my manifest to set the required features to false and I went from 0 devices to 2k+ (I require lollipop).
For the item not found this was more difficult and I ended up chatting with someone at Google who pointed out I had the APK restricted to my domain.  Once I found that, unchecked, and updated I was able to download from the url.
-J


text:
Q: Is there a latex command to print the name of the font used for text and for math? sometimes I change the fonts I used to build a latex document to see how it looks. So I have few old pdf files build with different fonts.
Is there latex command to print, inside the PDF when it is compiled,  the official font name or specs  used for text and for math? so this information is not lost or hard to find?
I know some PDF readers will allow one to find the fonts used in the PDF but sometimes this is hard to find and not all readers has this feature. I also like to print this in the document itself, may be on the margin or as footnote
somewhere so it is easy to see.
Here is a MWE
\documentclass[12pt]{article}
\usepackage{amsmath}

\usepackage[T1]{fontenc}
\usepackage{fourier}
\usepackage{baskervald}

\begin{document}

%\footnote{This document was compiled using text font \textFontName
%and math font \mathFontName}

This is some math $\sin(x)$
\end{document}

I'd like to do something like the commented code above if there is a way to do it. Let assume there is only one font used in the document, as in the example above.
For example, for default font, I expect the footnote will be
  This document was compiled using text font "Computer Modern"
  and math font "Computer Modern"

Using TL 2018

A: My answer can be improved for math, but it has up to 16 groups, you can check what
\makeatletter\meaning\mv@normal\makeatother produces to get an idea of what is involved.
\documentclass[12pt]{article}
\usepackage{amsmath}

\usepackage[T1]{fontenc}
\usepackage{fourier}
\usepackage{baskervald}

\begin{document}

%\footnote{This document was compiled using text font \textFontName
%and math font \mathFontName}

This is some math $\sin(x)$.

\makeatletter
\edef\textFontName{\fontname\csname
  \f@encoding/\f@family/\f@series/\f@shape/\f@size\endcsname}
\edef\mathFontName{\fontname\textfont0}
\edef\mathLetterFontName{\fontname\textfont1}
\makeatother

See\footnote{Text Font: \textFontName

Math Operator Font: \mathFontName

Math Letter Font: \mathLetterFontName\par
}
\end{document}

With xetex:
\documentclass[12pt]{article}
\usepackage{amsmath}

\usepackage{fontspec}

\begin{document}

%\footnote{This document was compiled using text font \textFontName
%and math font \mathFontName}

This is some math $\sin(x)$.

\makeatletter
\edef\textFontName{\fontname\csname
  \f@encoding/\f@family/\f@series/\f@shape/\f@size\endcsname}
\edef\mathFontName{\fontname\textfont0}
\edef\mathLetterFontName{\fontname\textfont1}
\makeatother

See\footnote{Text Font: \texttt{\textFontName}

Math Operator Font: \texttt{\mathFontName}

Math Letter Font: \texttt{\mathLetterFontName}\par
}
\end{document}

A: Yes, but it won't give you the display name you want.  The \f@family macro will expand to something like cmr instead of Computer Modern Roman, and \the\fam in math mode is a number.


text:
Q: .HTACCESS Redirection Problem: index.php Before URL Slug I am trying to achieve a simple http to https redirect and www to non-www. The problem is that .htaccess puts "index.php" before the url slug, resulting in a server error. Here is what happens:
WRONG BEHAVIOUR:
http://example.com/url-slug -> https://example.com/index.php/url-slug

DESIRED BEHAVIOUR:
http://example.com/url-slug -> https://example.com/url-slug

Note: I want all queries to redirect to the index.php page in the main directory, unless the requested file exists on the server. I'd like to achieve this without changing the url in the browser, which causes the server to crash.
(Objective: www -> non-www & http -> https)
CURRENT .HTACCESS SETTINGS:
RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]

RewriteCond %{HTTPS} off
RewriteRule .* https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

What am I doing wrong?

A: Your http to https 301 redirect should be at the top before other internal rewrite rules
RewriteEngine On
#http to https
RewriteCond %{HTTPS} off
RewriteRule .* https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
#www to non-www
RewriteCond %{HTTP_HOST} ^www\.(.+)$
RewriteRule (.*) https://%1%{REQUEST_URI} [NE,L,R=301]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]

Make sure to clear your browser cache before testing this change.


text:
Q: Angular - expression in templates view I'm new to angular, trying to make a SPA.
Just include the route module, and it works fine, but the templates inside don't process angular expression, just put one inside " {{ 1 + 2 }} ".
And shows me the exact same expression and not "3".
Do i need to make anything else to make templates run expressions?
My code:
index.html
<!HTML>

vista2.html

{{ 1+2 }}

A: Your expression is fine. You should define prCtrl as controller and it should work just fine.
such expresions as :

*

*1+2

*a+b

*user.name

*items[index]

are valid in angular and you can use them in {{ }} brackets. Your problem is lack of controller, that is why expresions are not parsed correctly.
Expressions are described in here.

A: You have to create 'prCtrl' controller.
Simply add this line at the end of your script:
angular.module('Prueba').controller('prCtrl', function($scope){});

And it should work.


text:
Q: Copy files from one path to another path in TFVC repository using Powershell I am trying to copy files from one folder path to another folder path in the TFVC repository using Powershell script in CI as mentioned below.
Get-Item -path $/SCSM/CMC/1.1.0.0/Dev/1.1.1.0/TSC/ServiceRuleScript - Destination $/SCSM/CCB/1.0.0.0/Dev/1.0.1.0/TSC/RulesEngine

When trying the above script getting the below error:
Copy-Item : Cannot find path 'C:\privateagent\_work\66\s\$/SCSM/CMC/1.1.0.0/Dev/1.1.1.0/TSC/ServiceRuleScript

We tried with the copy file task in CI, it is getting executed but we are unable to see the file in the destination folder path
enter image description here
Please help me out with this task.

A: The problem is that your Source Folder is wrong.
Use this Predefined variables:
$(Build.SourcesDirectory)\{your folder want to be copied}

It works on my side:

A: We are trying to call file from one path "Masters\DbProject\V1.0.0.1\PowershellScripts
and we are using the copy task to call file in another path "CCM/1.0.0.0/1.1.0.0/Dev/1.1.1.0". Both are different paths. When we are trying to call the file using copy file task getting the below error.
##[error]Unhandled: Not found SourceFolder: C:\privateagent_work\66\s\Masters\DbProject\V1.0.0.1\PowershellScripts
But the file which we are trying to call is in the below path: "C:\privateagent_work\79\s\Masters\DbProject\V1.0.0.1\PowershellScripts
We have mentioned the below path in our copy task
Source folder in copy task - $(Build.SourcesDirectory)\Masters\DbProject\V1.0.0.1\PowershellScripts
The problem here in the copy task is - The copy file task should call file from "C:\privateagent_work\79\s\Masters\DbProject\V1.0.0.1\PowershellScripts" but it is trying to call the file from "C:\privateagent_work\66\s\Masters\DbProject\V1.0.0.1\PowershellScripts
Please share your inputs.