Randomness without Cumulative distribution function

Question: It might sound weird but up until now in my studies the randomness was assigned to a Cumulative distribution function which is a deterministic mapping (for discrete and continuous) random variables.
My question is can we go a little more further ? i.e. are there random phenomenon (maybe from physics or economy or constructed by maths) to which it is proven that we cannot assign a (deterministic) Cumulative distribution function ?
Thank you for your answer,
Comment: The CDF exists for any random variable.
Comment: You might be interested in this: https://math.stackexchange.com/questions/3820145/true-random-number-set
Answer: To elaborate on @fesman's comment, a random variable $X$ is a measurable function on a measurable space $(\Omega, \mathbb P)$. We define for any such $X$ the cumulative distribution function $F_X:(-\infty,\infty)\to[0,1]$ by
$$
F_X(x) := \mathbb P(X\leqslant x),
$$
or to be more explicit,
$$
F_X(x) := \mathbb P(\{\omega\in\Omega : X(\omega)\leqslant x).
$$
We cannot define a "random phenomenon" without a distribution function. It is more likely that the "randomness" in your studies did not consist of rigorous probability theory.
Comment: about the 'cannot define', is the following relevant? '[Every function with these four properties is a CDF, i.e., for every such function, a random variable can be defined such that the function is the cumulative distribution function of that random variable.](https://en.wikipedia.org/wiki/Cumulative_distribution_function)'
Comment: @BCLC I don't think you're understanding the question being asked. It is not whether one can define such a function without the concept of randomness, but instead whether one can rigorously define "randomness" without e.g. such a function.
Comment: Math1000 not for the question specifically, i mean in general. oh wait i mean 'related' not 'relevant'. i think that was where i confusing


Passing rvalue to function that may not use it

Question: Lets say I have a class defined as follows:
class Foo {
public:
    ...
    bool add_widget(Widget&& w) {
        if (some condition) {
            return false;
        }

        container.push_back(std::move(w));
        return true;
    }

private:
    std::deque<Widget> container;
}

and I call the class as follows:
int main(int argc, char* argv[]) {
    Foo f;
    Widget w;

    if (!f.add_widget(std::move(w))) {
        // Can I still use w here?
    }
}

If some condition is true, the Widget w will not be added to Foo's container. In main(), when add_widget() returns indicating that the add was not successful, can I still use w, or should I always assume it has been moved and is no longer usable?
Is it bad practice to write a function like add_widget() that takes an r-value reference but may not actually move it's argument?
Comment: I'd be afraid that one day someone would come and change the signature of `add_widget` into `bool add_widget(Widget w)`, so I perceive this style as bad practice
Comment: IMHO if a client `std::move`'s a value into a function, they should assume that the object has been moved out from under them, even if that's not always the case (client shouldn't necessarily care about the implementation of the function, only the preconditions and postconditions). It's not necessarily bad practice to write it as you have; it all depends on your use case.  There are times when Piotr's solution is better, and times when yours is.
Comment: The code is technically fine, though it perhaps violates the standard guidance that a value bound to an rvalue reference has no aliases. An alternative that doesn't suffer from this problem would be to take an lvalue reference and perform the move inside the function.
Comment: Regarding good/bad practice: if it is not expected to be part of normal behaviour for `add_widget` to fail, then throwing an exception is good practice. It keeps your code clean because you don't have to wrap everything in `if` tests.  If it is normal for `add_widget` to fail then perhaps the function should indicate that in its filename, e.g. one convention is that `foo()` throws, and `tryFoo()` returns a boolean.
Answer: If "some condition" evaluates to true then the add_widget member function will return before the input w is moved in deque. Thus, you can use w in main safely.
Have in mind that std::move doesn't actually move an object. std::move is nothing more than a type cast.
Even if w was moved then w in main would have been in a valid but unspecified state.
Meaning that you could perform any operation on w which would have no preconditions. If there's an operation with preconditions you would like to perform, then you would have to perform that operation indirectly, because you wouldn't know if the unspecified-state of the object satisfies the preconditions.
LIVE DEMO
Answer: It is perfectly fine to use widget in that case, as its state is not altered in any way.
However, you should only rely on this behavior, if you explicitly document it in the function description and - as a result - are willing to commit to that guarantee even in case of future refactoring.
One could argue, whether or not this is too clever and/or surprising, but in fact it is not too different from relying on the strong exception guarantee of functions like std::vector::push_back().
Answer: This idiom is used in the standard library as of c++17.
Have a look at the second form of std::map::try_emplace
reference: http://en.cppreference.com/w/cpp/container/map/try_emplace
Note that the key type (and indeed in some cases, the arguments used to construct the value) are r-value references, but they are only moved into the map if the key is not already present.


Unable to mock native module

Question: I'm trying to test a component I've created that uses MapView from react-native-maps as a child component. I know I need to mock that native component but what I've written still flags up an error:
import 'react-native';
import React from 'react';
import Detail from '../js/components/Detail';

// Note: test renderer must be required after react-native.
import renderer from 'react-test-renderer';

jest.mock('react-native-maps', () => 'MapView');

it('renders correctly', () => {
  const tree = renderer.create(
    <Detail />
  ).toJSON();
  expect(tree).toMatchSnapshot();
});

and the error I receive:
TypeError: Cannot read property 'setNativeProps' of null
Any help would be appreciated.
EDIT: If it helps, here's the component I'm trying to test...
import React, { Component } from 'react';
import {
  Dimensions,
  LayoutAnimation,
  StyleSheet,
  Text,
  TouchableHighlight,
  View,
} from 'react-native';
import MapView from 'react-native-maps';

import MapExpandButton from './buttons/MapExpandButton';

const styles = StyleSheet.create({
  ...
});

export default class AppointmentDetail extends Component {
  constructor(props) {
    super(props);
    this.state = {
      expanded: false,
    }
  }

  componentWillUpdate() {
    LayoutAnimation.easeInEaseOut();
  }

  renderMap() {
    return (
      <MapView
        initialRegion={{
          latitude: 51.501211,
          longitude: -0.110530,
          latitudeDelta: 0.005,
          longitudeDelta: 0.005,
        }}
        scrollEnabled={this.state.expanded}
        pitchEnabled={this.state.expanded}
        zoomEnabled={this.state.expanded}
        rotateEnabled={this.state.expanded}
        loadingEnabled={true}
        showsPointsOfInterest={false}
        style={[styles.map, this.state.expanded ? styles.mapExpanded : undefined]}>
        <MapView.Marker
          coordinate={{
            latitude: 51.501211,
            longitude: -0.110530,
          }}
          title='My Pin'
          description='Somewhere'
        />
      </MapView>
    );
  }

  renderSummary() {
    return (
      <View style={styles.section}>
        <Text style={styles.headline}>
          Appointment Type
        </Text>
        <Text style={styles.subheading}>
          on Date at Timeslot
        </Text>
      </View>
    );
  }

  renderAddress() {
    if (!this.state.expanded) {
      return (
        <View style={styles.section}>
          <Text style={styles.body}>
            Address Line 1,
          </Text>
          <Text style={styles.body}>
            Address Line 2,
          </Text>
          <Text style={styles.body}>
            City POSTCODE,
          </Text>
        </View>
      );
    }
  }

  renderSections() {
    return (
      <View>
        { this.renderSummary() }
        { this.renderAddress() }
      </View>
    );
  }

  toggleExpand() {
    const newExpandedState = !this.state.expanded;
    this.setState({ expanded: newExpandedState });
    if (this.props.didChangeExpandedState) {
      this.props.didChangeExpandedState(newExpandedState);
    }
  }

  render() {
    return (
      <View style={styles.container}>
        { this.renderMap() }
        { this.renderSections() }
        <View style={{ position: 'absolute', right: 8, top: 8 }}>
          <MapExpandButton onPress={this.toggleExpand.bind(this)} />
        </View>
      </View>
    );
  }
}

Answer: Found a solution from this issue on GitHub: https://github.com/facebook/jest/issues/1960
I think the issue was that MapView.Marker child components weren't being mocked. This answer is mocking the child components as well.
jest.mock('react-native-maps', () => {
  return class MockMapView extends React.Component {
    static Marker = props => React.createElement('Marker', props, props.children);
    static propTypes = { children: React.PropTypes.any };

    render() {
      return React.createElement('MapView', this.props, this.props.children);
    }
  }
});

Comment: Apart from this, following is also needed:
```jest.mock(`react-native-maps`, () => {
  const React = require('React');
});```

[see this git issue](https://github.com/facebook/jest/issues/2567#issuecomment-271937555)
Answer: When I ran into this issue I added the modules to the ignore list under jest in your package.json:
"transformIgnorePatterns": [
  "node_modules/(?!react-native|react-native-maps)"
]

Comment: Great thanks, I'll give that a try. Am I using the correct name though? Not sure if it should be the package name or the component name
Comment: Yea, pretty sure you're doing it correctly. You might have to add more to the transformignorepatters though, I just kept running it and every error about native packages I got I threw in there.
Comment: Ok I've added that and made sure I'm using the correct names for the mock function but I get this error `Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. Check the render method of 'AppointmentDetail'.`
Comment: I think I've got it now, it's passing successfully with an answer from GitHub, I'll add it as an answer if you'd like to have a look. I think the problem was that I was using MapView.Marker child components and they weren't being mocked.
Answer: Please try this for the latest react-native-maps library version:

jest.mock('react-native-maps', () => {
  const React = require('react');
  const {View} = require('react-native');

  class MockMapView extends React.Component {
    render() {
      const {testID, children, ...props} = this.props;

      return (
        <View
          {...{
            ...props,
            testID,
          }}>
          {children}
        </View>
      );
    }
  }

  class MockMarker extends React.Component {
    render() {
      const {testID, children, ...props} = this.props;

      return (
        <View
          {...{
            ...props,
            testID,
          }}>
          {children}
        </View>
      );
    }
  }

  return {
    __esModule: true,
    default: MockMapView,
    Marker: MockMarker,
    enableLatestRenderer: jest.fn(),
  };
});

Unable to mock native module


How to remove a css file from an already-overridden definition?

Question: I want to create a custom theme and remove a css file from diretory themes/stable/css/filter.caption.css from Stable theme. I found this file in stable.info.yml
libraries-override:
  filter/caption:
    css:
      component:
          css/filter.caption.css: css/filter/filter.caption.css

From my_custom.info.yml
libraries-override:
  filter/caption:
    css:
      component:
        css/filter.caption.css: false

or
libraries-override:
  filter/caption:
    css:
      component:
        css/filter/filter.caption.css: false

I tried that way but it is not work to remove a css file themes/statble/css/filter.caption.css.
Comment: This may be an open bug in Drupal, but there are workarounds: https://www.drupal.org/project/drupal/issues/2642122
Comment: This seems to have been asked a few times here in the past.
Comment: How can I do that when a css file defined in info.yml?
Comment: Does this answer your question? [How can I override or disable a parent theme's CSS file?](https://drupal.stackexchange.com/questions/182528/how-can-i-override-or-disable-a-parent-themes-css-file)
Comment: That link does not answer my question. I want to remove a css file from stable theme but that file is curently override from another css file.
Comment: Thank you @cilefen for helping me
Answer: In stable.info.yml we have
libraries-override:
  filter/caption:
     css:
       component:
         css/filter.caption.css: css/filter/filter.caption.css

So my_theme.info.yml to disable it could be:
libraries-override:
  filter/caption:
    css:
      component:
        /themes/contrib/stable/css/filter/filter.caption.css: false

A bug in libraries-override makes it difficult to override a library or library asset that has already been overridden. See https://www.drupal.org/project/drupal/issues/2642122#comment-11830072 for more information.
Comment: In case anyone looking at this answer is using core/themes/stable9 instead of themes/contrib/stable, you would need to include this instead after component including the leading slash: /core/themes/stable9/css/...


Convert type in setter method, possible? When yes how?

Question: guess I wanted to gernerate a commandline with flags and so on. Flags are of type bool but the commandline is a string like " /activeFlag". Is there a way to program a setter in C# which takes a bool but the getter returns a string?
like
private string activeFlag {
 get { return activeFlag; }
 set {
    // the value here should be the bool
    activeFlag = value ? " /activeFlag" : "";
 }
}

Answer: There no way to have a property with different data types for its setter and getter.
What you can do is something like this:
private bool IsActiveFlagSet { get { return ActiveFlag == " /activeFlag"; } }
private string ActiveFlag { get; set; }

Comment: @Marc Yeah you're right.. it's too early =P  I'll edit to reflect.
Answer: You need another setter.
private string activeFlag {
 get { return _activeFlag; }
}
private bool activeFlagByBool {
 set {
    // the value here should be the bool
    _activeFlag = value ? " /activeFlag" : "";
 }
}

Answer: No, but you could use a custom TypeConverter to achieve the same thing, via TypeDescriptor. If you really wanted. Not sure it would be worth it, though, unless you desparately wanted to display it in a DataGridView, PropertyGrid, or similar.
There is also a separation of concerns issue; the purpose of the flag is to understand a boolean value - the string representation relates only to the UI. You could use a custom attribute:
[CommandLine("/activeFlag")]
public bool IsActive {get;set;}

and take it from there?
Answer: I don't believe so, have a look at this project Automatic Command Line Parsing in C# I've used this and it is a nice solution.


Setting Local Notifications on a new thread?

Question: I need to know if it is possible to create a new thread to handle setting local notifications.
My app depends heavily on these notifications, so I want to make the app work while the phone sets the notifications.
Example:
(now)
you launch the app, the app hangs at the splash screen to set the local notifications, then it launches.
(I want)
The app launches and is usable while the Local notifications are set.
I need some sample code, too, please :)
(for the record, i am setting 60 local notifications each time the app enters foreground for my own reasons...)
Thanks!!
Answer: One way to do threads is with is with performSelectorInBackground.
For example:
[myObj performSelectorInBackground:@selector(doSomething) withObject:nil];

You should note, however, that Apple is pretty strongly recommending that you use higher-level concepts like NSOperations and Dispatch Queues instead of explicitly spawning threads. See the Concurrency Programming Guide
Comment: Thanks for your contribution!
Comment: it's crashing even more. :(
Answer: Yes this can be done, I do it all the time:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Add the navigation controller's view to the window and display.
    [NSThread detachNewThreadSelector:@selector(scheduleLocalNotifications) toTarget:self withObject:nil];
    [window addSubview:navigationController.view];
    [window makeKeyAndVisible];

    return YES;
}

-(void) scheduleLocalNotifications
{

    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

    for (int i = 0; i < 60; i++)
    {
        UILocalNotification *localNotif = [[UILocalNotification alloc] init];
        if (localNotif == nil)
            return;
        NSDate *sleepDate = [[NSDate date] dateByAddingTimeInterval:i * 60];
        NSLog(@"Sleepdate is: %@", sleepDate);

        localNotif.fireDate = sleepDate;

        NSLog(@"fireDate is %@",localNotif.fireDate);
        localNotif.timeZone = [NSTimeZone defaultTimeZone];
        localNotif.alertBody = [NSString stringWithFormat:NSLocalizedString(@"This is local notification %i"), i];

        localNotif.alertAction = NSLocalizedString(@"View Details", nil);
        localNotif.soundName = UILocalNotificationDefaultSoundName;
        localNotif.applicationIconBadgeNumber = 1;

        [[UIApplication sharedApplication] scheduleLocalNotification:localNotif];
        NSLog(@"scheduledLocalNotifications are %@", [[UIApplication sharedApplication] scheduledLocalNotifications]);
        [localNotif release];

    }

    [pool release];
}

Taken from a project I am working on now, I can confirm that It works as expected.
EDIT:
Example was leaking in scheduleLocalNotifications because handling the NSAutoreleasePool was missing – now it's added to the example.
Comment: Using UIApplication out of the main thread is not safe and can cause 'Unexpected Results'.  I'd question why you need to do it off thread.   I doubt it's taking up much time.   If it needs to be off thread, you still need to run 'scheduleLocalNotification' on the main thread to be safe.
Comment: Hey np.. that's what we are here for


VBA Excel Search for cell that contain one of different word

Question: I need to make a script to color or delete the row that contain at least one of the word that i need to search. For example, I've an array or simply a list of word like "alpha" "beta" "gamma" and i need to search in colum A and B where there are different words and string if these words exist, at least one of them, and then color or delete the row, but that's not the problem. This is what I've made, finding somewhere over internet, but it doesn't work. I've about 30 words to search and even more. Can you help me?
   Sub Macro2()
'
' Macro2 Macro
'

For i = 2 To 1000
If Evaluate("COUNT(SEARCH({""alpha"",""beta"",""gamma""}," & Cells(i, 1).Address & "))") > 0 Then
Rows(i).Interior.Color = RGB(127, 187, 199)
GoTo Prossimo
End If
If Evaluate("COUNT(SEARCH({""alpha"",""beta"",""gamma""}," & Cells(i, 2).Address & "))") > 0 Then
Rows(i).Interior.Color = RGB(127, 187, 199)
GoTo Prossimo
End If
Prossimo:
Next i
End Sub

Thank you guys!
Answer: I would first create an array of your special words
words = Array("alpha", "beta", ...)

Then you can loop through the rows in your spreadsheet and the items in your array, looking for matches.
words = Array("alpha", "beta", ...)
for i = 2 to 1000
    for j = lbound(words) to ubound(words)
        if cells(i,1)=words(j) or cells(i,2)=words(j) then
            rows(i).interior.color=rgb(127,187,199)
        end if
    next j
next i

Comment: there's something strange but it start and finish without color nothing..
Comment: It worked fine when I tested it. What is does your input look like?
Answer: Try this
Option Explicit

Sub Macro2()
   Dim cell as Range
   Dim myWords as String

   myWords = "|alpha|beta|gamma|"
   With Worksheets("MySheet") '<--| change "MySheet" to your actual sheet name
      For Each cell in .Range("A2:A" & .Cells(.Rows.Count,"A").End(xlUp).Row)
         If InStr(myWords, "|" & cell.Value & "|") > 0 or InStr(myWords, "|" & cell.Offset(,1).Value & "|") > 0 Then cell.EntireRow.Interior.Color = RGB(127, 187, 199)
      Next cell
   End With
End Sub

Comment: seems nothing happen
Comment: I'm not by any PC to check it
Comment: I'm not by any PC to check it. So try stepping through the code and querying in the Immediate Window the values of "cell", "cell.Address", "InStr(myWords, "|" & cell.Value & "|")" and "InStr(myWords, "|" & cell.Offset (,1).Value & "|")" at every loop. The code assumes the following: 1) the relevant sheet is named after "MySheet" 2) values in columns A and B are checked from row 2 to the last non empty row of column A. 3) At every row if cell in either column A or B has the content "alpha" or "beta" or "gamma" then the whole row is colored
Comment: @BigBlack now I tested it and it works, with assumptions as per my previous comment. what is your issue?
Comment: I'm trying to see in the local variable windows but I don't know where to search to see if it find words.


Cannot find Symbol = new

Question: Java is complaining!
cannot find symbol
symbol  : constructor Bar()
location: class Bar
         JPanel panel = new Bar();
                        ^

QUESTION: Why am I getting this error?...everything seems to be correct.
this is the coding:
    public class JFrameWithPanel
    {
      public static void main(String[] args)
      {
           JPanel panel = new Bar();
      }
    }

Bar( ) is
public class Bar extends JPanel
{
    public Bar(final JFrame frame)
    {
        super(new BorderLayout());
        String[] tests = { "A+ Certification", "Network+ Certification", "Security+ Certification", "CIT Full Test Package" };
        JComboBox comboBox = new JComboBox(tests);
        TextArea text = new TextArea(5, 10);
        add(new JLabel("Welcome to the CIT Test Program "));
        add(new JLabel("Please select which Test Package from the list below."));

        JMenuBar menuBar = new JMenuBar();
        JMenu fileMenu = new JMenu("File");
        JMenu editMenu = new JMenu("Edit");
        JMenu helpMenu = new JMenu("Help");
        menuBar.add(fileMenu);
        menuBar.add(editMenu);
        menuBar.add(helpMenu);
        JMenuItem newMenu = new JMenuItem("New  (Ctrl+N)");
        JMenuItem openMenu = new JMenuItem("Open  (Ctrl+O)");
        JMenuItem saveMenu = new JMenuItem("Save  (Ctrl+S)");
        JMenuItem exitMenu = new JMenuItem("Exit  (Ctrl+W)");
        JMenuItem cutMenu = new JMenuItem("Cut  (Ctrl+X)");
        JMenuItem copyMenu = new JMenuItem("Copy  (Ctrl+C)");
        JMenuItem pasteMenu = new JMenuItem("Paste  (Ctrl+V)");
        JMenuItem infoMenu = new JMenuItem("Help  (Ctrl+H)");
        fileMenu.add(newMenu);
        fileMenu.add(openMenu);
        fileMenu.add(saveMenu);
        fileMenu.add(exitMenu);
        editMenu.add(cutMenu);
        editMenu.add(copyMenu);
        editMenu.add(pasteMenu);
        helpMenu.add(infoMenu);
        this.add(comboBox, BorderLayout.NORTH);
        this.add(text, BorderLayout.SOUTH);
        frame.setJMenuBar(menuBar);
        add(new JButton("Select")
        {
            {
                addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent e) {
                        frame.dispose();
                        JOptionPane.showMessageDialog(frame, "IT WORKS!");

                    }
                });
            }
        });

    }
}

Answer: The problem is that you have a constructor that expects a JFrame:
public Bar(final JFrame frame)

but you care calling it with no arguments:
JPanel panel = new Bar();

You need to pass Bar an instance of a JFrame.
Comment: I dont get it. Please explain
Comment: JPanel panel = new Bar(new JFrame()); ... but you will need more that that to make it work (that will get it to compile though).  You still need to make the frame visible etc...
Comment: Ok that works. Now where would I start adding the code to make the frame visible and set size, since this new Frame() doesnt exactly have a variable name
Comment: I'd give it a name, and pass the variable into the constructor.
Answer: You are calling the Bar() constructor, but you do not have a no arguments constructor.  You need to pass the JFrame argument.
Answer: In addition to TofuBeer answer - consider using an IDE like eclipse or netbeans (just to name two examples). Those IDE's will show errors of this kind already on typing the code.

Cannot find Symbol = new


pager query with join

Question: I plan to list all polls in the most recent order where I need to join my "poll" table with the "node" table and display them with pager. Here is what I do:
$polls_query = db_select('poll', 'p')
              ->extend('PagerDefault')
              ->limit(3);
$polls_query->join('node', 'n', 'n.nid = p.nid')
            ->fields('p', array('nid'))
            ->condition('p.active', 1, '=')
            ->orderBy('n.created', 'DESC');
$result = $polls_query->execute();
foreach ($result AS $poll) {
  $polls[] = array('data' => drupal_render(node_view(node_load($poll->nid), 'teaser')));
}
$content['pager_list'] = array(
  '#theme' => 'item_list',
  '#items' => $polls,
  '#title' => t('Listing Consensus'),
  '#type' => 'ul',
);
$content['pager_pager'] = array('#theme' => 'pager');
return drupal_render($content);

Unfortunately I see a white screen of death and the php error log says "PHP Fatal error:  Call to a member function fields() on a non-object in  .. " and thats the line where I mention after fields. If I dont use join, everything works fine.
If anyone else has had similar problems, please share the solution.
Answer: The join() method doesn't return the query object to isn't chainable.
If you change your code to this you should be fine:
$polls_query = db_select('poll', 'p')
  ->extend('PagerDefault')
  ->limit(3);

$polls_query->join('node', 'n', 'n.nid = p.nid');

$polls_query->fields('p', array('nid'))
  ->condition('p.active', 1, '=')
  ->orderBy('n.created', 'DESC');

// etc...

Comment: super! i actually resolved it myself and was about to post the solution.. but there you go, you have already done that.. many thanks!

pager query with join


Accessing parent class when doing custom converter

Question: I am currently using Dozer to map to sets of objects.
I have a situation where I need to use a custom converter to map a String to TypeA.
The way I convert TypeA to a String depends on the type of Object TypeA is a member of.
Specifically TypeA has 2 fields lets call them prefix and postfix.  Sometimes I need to split the String by a space, or dash or slash.  That character to split on is defined in the parent of TypeA.
Is there a way to do this in Dozer with custom converters?  I need to go up the chain...
Thanks in advance for any help.
Comment: So far I'm thinking that I'll have to do a post-processor to clean up the destination objects...
Answer: So you should map a String to the parent of TypeA. In your xml file, to get to the "prefix" and "postfix" you would type, parent.TypeA.prefix or parent.TypeA.postfix. Hope this helps.


How react hooks are updating state

Question: I have a long process that updates the state. I want to show red background when it's running and blue when it's done.
const MapBuilder = (props) => {
    const [backgroundColor, setBackgroundColor] = useState(false);
    const [fancyResult, setFancyResult] = useState(null);

    console.log(`stop 1 backgroundColor ${backgroundColor} fancyResult ${fancyResult}`)
    const veryHardWork = () => {
         setBackgroundColor("red");
         console.log(`stop 2 backgroundColor ${backgroundColor} fancyResult ${fancyResult}`)
         for (let i = 0; i < 1000; i++) {
            for (let j = 0; j < 1000; j++) {
              console.log("So hard")
         }
    }

   setFancyResult("done")
   console.log(`stop 3 backgroundColor ${backgroundColor} fancyResult ${fancyResult}`)
   setBackgroundColor("blue")
   console.log(`stop 4 backgroundColor ${backgroundColor} fancyResult ${fancyResult}`)
}

return (

   <button className="btn btn-primary" onClick={veryHardWork}></button>

)
}

Here is an output of such run
stop 1 backgroundColor false fancyResult null
MapBuilder.js:13 stop 2 backgroundColor false fancyResult null
10000MapBuilder.js:16 So hard
MapBuilder.js:20 stop 3 backgroundColor false fancyResult null
MapBuilder.js:22 stop 4 backgroundColor false fancyResult null
MapBuilder.js:10 stop 1 backgroundColor blue fancyResult done

I understand from this that the state change only happens after the method veryHardWork  is finished. In my real project, I actually want to show a spinner the question is how can I do it if the state is only changed at the end of the method.
I think some clarification needs to be added. In reality, I allow the user to choose a file after the user chooses the file it is loaded and some heavy processing is performed on files data while the processing is running I want to show a spinner no Asyn work involved.
Some of the answers sugested to use useEffect and moving it to a promise I tryied both but it did not help here is a different take on it which also did not work
const MapBuilder = (props) => {
  const [backgroundColor, setBackgroundColor] = useState(false);
  const [fancyResult, setFancyResult] = useState(null);
  const [startProcessing, setStartProcessing] = useState(null);

  useEffect(() => {
    let myFunc = async () => {
      if (startProcessing) {
        setBackgroundColor("red");
        await hardWork();
        setBackgroundColor("blue");
        setStartProcessing(false);
      }
    }

    myFunc();
  }, [startProcessing])

  const hardWork =  () => {
    return new Promise((resolve)=> {
      for (let i = 0; i < 500; i++) {
        for (let j = 0; j < 100; j++) {
          console.log("So hard")
        }
      }
      setFancyResult("sdsadsad")
      resolve("dfsdfds")
    })
  }

  return (

    <button className="btn btn-primary" onClick={() => setStartProcessing(true)}></button>

)
}

export default MapBuilder;

Comment: The task that you wish to perform on button click is it a synchronous task or an asynchronous task?
Comment: It is synchronous
Comment: What kind of synchronous work is it? Can you *not* move it to the backend? Because it would effectively freeze the entire browser until that heavy task is done.
Answer: You already control state of fancyResult,
 or you can use showSpinner state for only reason to show spinner
You can use for long progress Promise [Link] And Async/Await [Link]

const veryHardWork = async () => {
    setBackgroundColor("red");
    const awaiting = await new Promise((resolve, reject) => {
        for (let i = 0; i < 1000; i++) {
            for (let j = 0; j < 1000; j++) {
                resolve(console.log("So hard"));
            }
        }
    })
    // After Finished Awating Hardwork
    setFancyResult("done");
    setBackgroundColor("blue") ;
}

  return (

      <button className="btn btn-primary" onClick={veryHardWork}></button>
      { fancyResult === 'done' && 'Show Spinner' }

  )

Answer: The problem with the approach is that the heavy calculation is happening at the main loop with the same priority. The red color change will not ever cause any changes until all things at the event handler have been finished.
With Reach 18 you can make your heavy calculation to be with lower priority and let the UI changes happen with normal priority. You can make this happen with minor change on your code base:
const veryHardWork = () => {
  setBackgroundColor("red");

  // Set heavy calculation to happen with lower priority here...
  startTransition(() => {
    console.log(`stop 2 backgroundColor ${backgroundColor} fancyResult ${fancyResult}`)
    for (let i = 0; i < 1000; i++) {
      for (let j = 0; j < 1000; j++) {
        console.log("So hard")
      }
    }
    setFancyResult("done")
    setBackgroundColor("blue")
  }
}

Answer: So I've made you a more real world example as the code you posted doesn't look like what you're actually wanting to achieve.
The scenario to my understanding is you want to preform some setup actions to get your state / data ready before showing it to the user.
cool, so first we will need some state to keep track of when we're ready to show content to the user lets call it isLoading. This will be a boolean that we can use to conditionally return either a loading spinner, or our content.
next we need some state to keep hold of our data, lets call this one content.
each state will be created from React.useState which can be imported with import { useState } from 'react';. We will then create variables in the following format:
const [state, setState] = useState(null);
nice, so now lets do somthing when the component mounts, for this we will use React.useEffect this hook can be used to tap into the lifecycle of a component.
inside our useEffect block we will preform our set up. In this case I'll say it's an async function that get some data from an API and then sets it to state.
lastly we will use our isLoading state to decide when we're ready to show the user something more interesting than a spinner.
All together we get something like this:

import { useState, useEffect } from 'react';

const MyComponent = () => {
  // create some state to manage when what is shown
  const [isLoading, setIsLoading] = useState(true);
  // create some state to manage content
  const [content, setContent] = useState(null);

  // when the component is mounted preform some setup actions
  useEffect(() => {
    const setup = async () => {
      // do some setup actions, like fetching from an API
      const result = await fetch('https://jsonplaceholder.typicode.com/todos/1')
        .then(r => r.json());

      // update our state that manages content
      setContent(result);
      // when we are happy everything is ready show the user the content
      setIsLoading(false);
    };
    // run our setup function
    setup();
  }, [ ]);

  // if we are not yet ready to show the user data, show a loading message
  if (isLoading) {
    return (

spinner goes in this div

    )
  }

  // when we are ready to show the user data is will be shown in this return statement
  return (

this div will show when the `isLoading` state is true and do something with the content state is wanted

  )
}

I believe you'll find this more useful than the example you provided
Comment: No, unfortunately, this will not work it's not an asynchronous API call. It's loading a file and then (loading is actually fast) making some heavy processing with it. UseEffect will not work in such a situation
Comment: can you expand? because I still think this is along the right lines, you could await a promise that handles your processing and update the state to show once the promise resolves. As for useEffect, in the way I've used it above it simply ensures that the setup is only ran once.
Answer: Try this:
import { useState, useEffect } from "react";
import { flushSync } from "react-dom";

const MapBuilder = (props) => {
  const [backgroundColor, setBackgroundColor] = useState(false);
  const [fancyResult, setFancyResult] = useState(null);

  // this will only be called on the first mount
  useEffect(() => {
    console.log(
      `backgroundColor ${backgroundColor} fancyResult ${fancyResult}`
    );
  }, [backgroundColor, fancyResult]);

  const veryHardWork = () => {
    setBackgroundColor("red");

    setTimeout(() => {
      for (let i = 0; i < 1000; i++) {
        for (let j = 0; j < 1000; j++) {
          for (let k = 0; k < 1000; k++) {
            // console.log("So hard");
          }
        }
      }

      setFancyResult("done");
      // flushSync(() => setFancyResult("done"));

      console.log(
        `inside closure - OUTDATED: backgroundColor ${backgroundColor} fancyResult ${fancyResult}`
      );

      setBackgroundColor("blue");
    }, 0);
  };

  return (

      <button className="btn btn-primary" onClick={veryHardWork}>
        Work!
      </button>

  );
};
export default MapBuilder;

CodeSandbox
Explanation:
Unblocking the UI thread
In order for the color to change to red, the UI thread must be freed up to

make the state changes (set background color to red) and
do the re-render.

One way to achieve this is by using setTimeout. This puts a function on a queue to be run later, allowing the UI thread to finish the above 2 tasks before tackling the actual work. You should note though, this doesn't actually run your work on a new thread, so once the work starts getting done, the UI will be unresponsive until the work is done. Consider using a Web Worker to solve this in the future.
Logging the current state
The other thing to understand about React is that every time a re-render occurs, the entire function ('MapBuilder' in this case) is re-run. This means that your 'stop 1' message will be displayed every re-render, and therefore every time the state changes.
Additionally, logging the state from within veryHardWork will log the state when the function was defined. This means that the value will be outdated, i.e. stale. This is because of a functional concept called closures. From Wikipedia "Unlike a plain function, a closure allows the function to access those captured variables through the closure's copies of their values or references, even when the function is invoked outside their scope."
So how should we log the current state when it is changed? By using the useEffect hook. This function will be re-run whenever any of the dependencies change ([backgroundColor, fancyResult] in this case).
Console.log undefined behavior
Another thing to note is that many console.logs should not be used as the 'work'. The rendering of the log will happen asynchronously, so 'firing' the logs will be much quicker than they will actually show up. This leads the observer watching the console to think that the 'red' stage has been skipped. Instead, we can just loop more times, or do some math in the loop, etc (which is closer to what your actual synchronous work will be anyway). In fact, console.log seems to be quite unpredictable, as noted here.
Automatic Batching
You might be wondering why "done" and "blue" show up as a single state update (i.e. stop 3 and 4 happen at the same time). This is because of automatic batching. As a performance optimization, react attempts to 'batch' state changes to prevent additional re-renders. To prevent this behavior, you can uncomment line 27 flushSync(() => setFancyResult("done")). This is not necessary for this use-case, as the batching is appropriate here, but it's helpful to understand what's going on.
Comment: Unfortunately, this does not work the background color is indeed red at first but after a few seconds, it turns blue. What's strange is that the 3*For are still running but somehow it reaches setBackgroundColor("blue"); although they suppose to be iin the same thread
Comment: @urag this is not accurate. Refer to the code sandbox, I have edited it to be keeping track of a count variable, incrementing it each iteration of the nested loop. It then displays below the work button. As you can see, the color turns to blue at the same moment that the number is shown.

How react hooks are updating state


Gradient of a partial differential matrix

Question: $X$ is a $2$ $\times$ $2$ matrix, $W$ is a $2$ $\times$ $3$ matrix, and $Y=XW$,as we know,$Y$ is a $2$ $\times$ $3$ matrix.Now,Set $L$ is a scalar,and the gradient
$ \frac{\partial L}{\partial Y}=$
$$
    \begin{bmatrix}
    \frac{\partial L}{\partial Y_{11}} & \frac{\partial L}{\partial Y_{12}} & \frac{\partial L}{\partial Y_{13}} \\
    \frac{\partial L}{\partial Y_{21}} & \frac{\partial L}{\partial Y_{22}} & \frac{\partial L}{\partial Y_{23}} \\
    \end{bmatrix}
$$
and by the chain rule,we know that:$\frac{\partial L}{\partial X}=\frac{\partial L}{\partial Y}\frac{\partial Y}{\partial X}$,$\frac{\partial L}{\partial W}=\frac{\partial L}{\partial Y}\frac{\partial Y}{\partial W}$,please show the gradient of $\frac{\partial L}{\partial X}=\frac{\partial L}{\partial Y}W^{T}$
So in fact,i have to prove  $W^T=\frac{\partial Y}{\partial X}$, however,the size of $X$ and $Y$ are not the same,it means the number of the element in $X$ and $Y$ are not the same either,in this situation, how to calculate the $\frac{\partial Y}{\partial X}$ ?
Comment: What exactly is $L$? It is unclear how you could have the matrix you wrote for $\frac{\partial{L}}{\partial{Y}}$.
Comment: The question didn't say what exactly is $L$ either,just say it is a scalar
Answer: Given the relationship $Y=XW$ and the gradient wrt $Y$ of some function, i.e. $$G=\frac{\partial L}{\partial Y}$$
you must find the gradient wrt $X$.
Rather than using the chain rule, simply expand the differential of the function and then perform a change of variable to obtain the desired result
$$\eqalign{
  dL &= G:dY \cr
  &= G:dX\,W \cr
  &= GW^T:dX \cr
\frac{\partial L}{\partial X} &= GW^T \cr
}$$
where colon denotes the trace/Frobenius product, i.e.
$$A:B = {\rm tr}(A^TB)$$


Why does javascript onchange event only work in first modal from a data table

Question: Hello and I thank you for taking the time to read my question.
This is my first post, I have tried to be as comprehensive as possible and follow the expected requirements of posting!
My set up
I have a data table populated from a mysql database, each row has an 'Edit' button.
The 'Edit' button opens a modal with the data from the row. This all works correctly.
In the modal form, I have a 'select' dropdown element with an 'onchange' event to trigger a message.
The issue
From within the first modal (opened from the first table row's 'Edit' button) the
 message is triggered no problem - in the modal window linked to the first row.
But if I click on any other row's 'Edit' button to launch it's modal - and then I change the 'select' dropdown value, the message is not displayed - as if the javascript function is not being processed.
My Research so far
Having spent time googling and searching through Stack Overflow, I think the problem could be related to non-unique IDs or Class Names - and may be they should be different for each record row?
I tried to implement this by generating ID names and Class Names dynamically by using the row's ID number - so each modal had it's own unique ID for the 'select' element - but this did not fix the issue.
I am also thinking it could be a cache issue where the script is holding on to old data, but it does not matter if I click the first row on the first time, or if I click the first row after clicking several other rows before it, it is only the first row which successfully processes the onchange event.
My files

index.php (to display the data table and 'Edit' buttons)

        Fruit ID
        Fruit Name
        Action

            <?php echo $row['fruitID']; ?>
            <?php echo $row['fruitName']; ?>

            <a href="#edit<?php echo $row['fruitID']; ?>" data-toggle="modal" class="btn btn-warning">Edit
            <?php include('button.php'); ?>

button.php (the modal content with 'select' element and message div)
    <div class="modal fade" id="edit<?php echo $row['fruitID']; ?>" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">

            <select class="mySelector" id="mySelector" name="mySelector" onchange="show_value()">
                <option value="Apple">Apple</option>
                <option value="Orange">Orange</option>
                <option value="Banana">Banana</option>
                <option value="Mango">Mango</option>
            </select>

script (at the bottom of button.php to trigger the message)

Comment: You have the same `id="mySelector"` in every modal. IDs are supposed to be unique. `getElementById("mySelector")` will just select the first one.
Comment: Hi Barmar - thanks for your comment. As mentioned, I did try dynamic IDs so each 'select' had a unique ID  like this `id="` but this did not fix the issue
Comment: Did you change `show_value()` so it knows which selector to get the value from?
Answer: You can get the select element value easily...

be patient while i'm trying to process the best way to display the value
Comment: For this to work you need to change it to `onchange="show_value(event)"`
Comment: I have gotten used to the frameworks as some of them do it automatically but that is 100% correct @Barmar
Comment: Maybe you're thinking of jQuery `.on()` or `addEventListener`, which automatically pass the event as the parameter. But if you use `onXXX` you have to do it explicitly.
Answer: You just need to pass your ids as parameters as shown below. Since you already have a unique id from $row['fruitID'], you can just append that number to each id so that they will be unique too.
<div class="modal fade" id="edit<?=$row['fruitID']?>" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">

                  <select class="mySelector" id="mySelector<?=$row['fruitID']?>" name="mySelector" onchange="show_value('mySelector<?=$row['fruitID']?>', 'result<?=$row['fruitID']?>')">
                      <option value="Apple">Apple</option>
                      <option value="Orange">Orange</option>
                      <option value="Banana">Banana</option>
                      <option value="Mango">Mango</option>
                  </select>

              <div id="result<?=$row['fruitID']?>">

Comment: OK @Nosajimiki - I just noticed you suggested passing the parameter IDs to the modal ID and result message ID - not just the Select element ID. This does appear to be working - many thanks - I am just checking if it will work OK for other functions / validations I need to process inside the modals - but I think you may have found the solution
Comment: Sorry, I was missing a few closing  tags which may have messed things up.  Also, certain special characters or value collisions in your fruitID could cause issues, but as long as you're using an auto-incremented key integer from your database as I'd assume it is, this should not be an issue.
Answer: you can pass the current id in javascript by just using this.id here is an example
<input type="text" id="username" class="form-control" name="username"  onchange="formhelper(this.id)">

now in your function you can use this id as you like example
function formhelper(currentID)
{

  consolele.log('the current id is ' + currentID);
}

you can also make the id dinamically using the php tags using this example
id="<?= $value['id']?>"


The relation between GCD/LCM of 3 polynomials and the factors decomposition?

Question: Is it  true that : the GCD of 3 polynomials is the product of the common factors (after factorization) of the these 3 polynomials ?
and the LCM of 3 polynomials is the product of all the common factors of the 3 polynomials ?
Comment: Why don't you take some examples and check?
Answer: In a polynomial ring over a field as well as in $\mathbf Z$ (actually in any U.F.D.):

The g.c.d. of two (hence any number of) polynomials is the product of the irreducible factors of each of them, with the lowest exponent. As consequence, only the common irreducible do appear in the g.c.d.
The l.c.m. of two (hence any number of) polynomials is the product of the irreducible factors of each of them, with the highest exponent.

Example, as suggested by @amWhy:
$\gcd(x^2-1, x+1, x^2+2x+1)=\gcd\bigl((x-1)(x+1), x+1, (x+1)^2\bigr)=x+1$.
$\operatorname{lcm}(x^2-1, x+1, x^2+2x+1)=(x-1)(x+1)^2$.


Como fazer uma função SE no SQL entre duas colunas

Question: Tenho o seguinte código, filtrei TAL.TIPO_PEDIDO sendo (000008,000061), mas preciso que quando for 000061, o código entenda que o almoxarifado será o 47, diferente do que está trazendo no ALM.ALMOXARIFADO, se for TAL.TIPO_PEDIDO = 000008, ai sim ele traz ALM.ALMOXARIFADO.
SELECT TAL.nome_cliente,
       TAL.data_entrega,
       TAL.referencia,
       TAL.desc_combi,
       TAL.talao,
       TAL.sld,
       TAL.elab,
       TAL.disp,
       TAL.emp
FROM   pcm_pedido_item PEDI,
       talao_tudo TAL,
       pcm_almoxarifado ALM
WHERE  PEDI.pedido = TAL.pedido
       AND TAL.item = PEDI.item
       AND ALM.almoxarifado = TAL.almoxarifado
       AND TAL.tipo_pedido IN ( 000008, 000061 )
       AND PEDI.situacao_comercial NOT IN ( 2, 6 )
       AND TAL.disp > 0
       AND TAL.sld > 0
       AND TAL.data_cadastro >= '01/05/2021'
/*AMOXARIFADO*/
ORDER  BY TAL.data_entrega

Comment: Seria tipo um Se( TAL.TIPO_PEDIDO=000061; ALM.ALMOXARIFADO=47), senão segue trazendo o ALM.ALMOXARIFADO igual está.
Answer: Pode resolver isso usando lógica boleana, basta escrever uma expressão descreva o que precisa para cada caso:
"quando for 000061, o código entenda que o almoxarifado será o 47"
O que seria:
TAL.tipo_pedido = '000061' AND ALM.ALMOXARIFADO = 47.
Agora se não for (ou OR) será:
TAL.tipo_pedido = '000008' AND ALM.ALMOXARIFADO = TAL.almoxarifado
Agora basta combinar isso no WHERE usando () para separar cada expressão:
WHERE .....
  AND (
        (TAL.tipo_pedido = '000061' AND ALM.ALMOXARIFADO = 47)
       OR
        (TAL.tipo_pedido = '000008' AND ALM.ALMOXARIFADO = TAL.almoxarifado)
      )

Claro, remova a linha AND ALM.almoxarifado = TAL.almoxarifado que já está sendo feita ai nessa condição.


JavaScript RegExp from a string then running .test() doesn't seem to work

Question: I thought that by instantiating a pattern = new RegExp() and passing a string then using .test(value) would be the same as using /^...$/.test(value), but they don't appear to be equal as using RegExp and passing a string fails each time.  Is this not correct? On MDN it seems to say that this should work.
SHOULD ALL FAIL AND THEY DO
var str = "7D>";
var res = /^[A-Za-z0-9\d=!\-@._*]*$/.test(str);
console.log(res); // false which is correct

var patt = /^[A-Za-z0-9\d=!\-@._*]*$/;
var res = patt.test(str);
console.log(res); // false which is correct

var patt = new RegExp("/^[A-Za-z0-9\d=!\-@._*]*$/");
var res = patt.test(str);
console.log(res); // false which is correct, but suspicious based on follow results

SHOULD ALL PASS AND THEY DON'T
var str = "7D";
var res = /^[A-Za-z0-9\d=!\-@._*]*$/.test(str);
console.log(res); // true which is correct

var patt = /^[A-Za-z0-9\d=!\-@._*]*$/;
var res = patt.test(str);
console.log(res); // true which is correct

BUT BOTH THESE ATTEMPTS FAIL WHEN THEY SHOULD PASS
var patt = new RegExp("/^[A-Za-z0-9\d=!\-@._*]*$/");
var res = patt.test(str);
console.log(res); // false which is NOT correct

var patt = new RegExp("^[A-Za-z0-9\d=!\-@._*]*$");
var res = patt.test(str);
console.log(res); // ALSO false which is NOT correct

Comment: You have to escape the `\-` in the string you pass to `new RegExp` as `\\-`. Otherwise, put the `-` at the end of the character set.
Comment: @torazaburo: *Beginning*, not end. *Edit:* Hey, interesting, both work. Useful to know. At least one rex engine I used (not JavaScript) took `-` at the end to mean no upper bound on the character class.
Comment: @T.J.Crowder *beginning **or** end*?
Comment: @torazaburo: Yup, apparently.
Answer: Two things:

You don't include the / when using a string
You do have to escape backslashes (as always, in a string literal)

So this:
var patt = new RegExp("/^[A-Za-z0-9\d=!\-@._*]*$/");

should be
var patt = new RegExp("^[A-Za-z0-9\\d=!\\-@._*]*$");
//                    ^           ^^   ^^        ^

If you had flags, you'd include them as a second string argument:
var patt = new RegExp("^[a-z\\d=!\\-@._*]*$", "i");

Side note:
\d means "digit" which is defined in the spec as 0-9, so having 0-9 and \d in the character class is redundant


Web stacks - listing of common web stacks/environments

Question: Just out of curiosity - I know there's LAMP - Linux, Apache, MySQL, and PHP. But what other abbreviations for web stack alternatives are there? anything like LAMR - Linux, Apache, MySQL Ruby on Rails?
Could someone please provide a listing of various common web stacks/environments?
Answer: MEAN

MongoDB
express.js
angular.js
node.js

The common denominator among these technologies is javascript. Developers using the MEAN stack can reason about the data being stored, searched, and displayed in the same way across the technologies.
This stack also usually has an Nginx server in front of it for security and load balancing.
Answer: I hoped to find an overview here, but alas, I'll just chip in an acronym I recently came across as it typified myself; the WISA stack:

Windows (Operating system)
IIS (Application server)
SQL Server (Database)
ASP.NET (Server side Language)

So hopes that leaves you a bit wisa' to :). Notice the client side is missing here. Personally I mostly stack on AngularJS (with Bootstrap layout) and WEBAPI (2) to handle the AJAX calls. But they don't create particularly nice acronyms.
Answer: I think the new term-de-jour is 'Web-Stack' because the you now need a LAMP and several LED's.
Used to be that LAMP was the acronym that put a nice tidy bow on the open-source-community' web-stack options.
i.e: LAMP:

Linux
Apache
MySQL
Python || Perl || PHP.

python == mod_python, and mod_wsgi... which gives you django, turbogears, web2py, etc.
perl == mod_perl, which gives you Catalyst, Mason etc.
PHP == Zend, Yii

These were considered to be the 'Open-Source-Community' stack, and a tidy acronym L-A-M-P
summed it up nicely. Now I think you have to add 2 alternatives to the dbms slot. SQLite && PostgreSQL, also there is a glaring absence from the application stack language slot, as you pointed out. Ruby-on-Rails.
Finally I feel obligated to point out that this space has grown alot:
http://en.wikipedia.org/wiki/Comparison_of_web_application_frameworks
With the advent of Web 2.0 and additional necessities in the env like XMPP or AMQP.
The term L-A-M-P has been replace with the more generic Web-Stack.
I highly encourage you to investigate the user-community size before embarking into the web-stack journey. Also remember when the term L-A-M-P was coined the 'explosion' of client-side technologies had not become so prevalent.
http://en.wikipedia.org/wiki/LAMP_(software_bundle)
Answer: MERN

MongoDB
Express.js
React.js
Node.js
Answer: Vangie Beal has been maintaining a compilation of the growing list of stack acronyms, here: https://www.webopedia.com/reference/webstack-acronyms/
To save you a click, here's the current list:

AMP  Apache, MySQL, and PHP (with the omission of an operating system)

BAMP BSD, Apache, MySQL, and PHP

BAPP BSD, Apache, PostgreSQL, and PHP

FAMP FreeBSD, Apache, MySQL, and PHP

FWAP Firebird, Windows, Apache, and PHP

FWIP FreeBSD, Windows, IIS, and PHP

JAMP Java, Apache, MySQL, and PHP

JOLT Java, Oracle, Linux, and Tomcat

LAMJ Linux, Apache, MySQL, JSP servlets

LAMP Linux, Apache, MySQL, and PHP

LAMAR    Linux, Apache, MySQL, AJAX, and Ruby on Rails

LAMR Linux, Apache, MySQL, and Ruby

LAPP Linux, Apache, PostgreSQL, and PHP

MARS MySQL, Apache, Ruby, and Solaris

MAMP Macintosh OS, Apache, MySQL, and PHP

NAMP NetBSD, Apache, MySQL, and PHP

NAPP NetBSD, Apache, PostgreSQL, and PHP

OPAL Oracle, PHP, Apache, and Linux

SAMP Solaris, PHP, Apache, and Linux

WAMP Windows, Apache, MySQL, and PHP

WIMSA    Windows, IIS, Microsoft SQL Server, and ASP

WISA Windows, IIS, Microsoft SQL Server, and ASP

XAMPP    (X could by any one of the following four operating systems; Linux, Solaris, Macintosh, or Windows), Apache, MySQL, PHP, and Perl
Answer: @bart I've always heard of your "wisa" stack as WINS:

Windows
IIS
.Net
Sql

You say the client side is missing here, but its not. .NET MVC with razor and async js is an inherent part of the .NET framework, being both a server side and client side framework... sure you can add a js framework on top, but it's not a necessity.
Edit:
I just found that WINS and WISA are different, with what Wiki has to say:

WISA using A = ASP.NET representing ASP (Active Server Pages) in the .NET framework, as just the backend framwroke, allowing coding in any .NET supported language (C#, VB).
WINS using N = .NET representing the entire .NET framework


Python implementation of n-body problem issue

Question: I am currently trying to implement the N-body problem using Euler's method for solving differential equations. However, the graphical outputs do not seem correct, and I'm not sure where the issue in my code is after a while of testing. I'm currently using approximate values for Alpha Centauri A and B to test. This is my code:
import numpy as np
import matplotlib.pyplot as plt
from math import floor

# gravitation constant
G = 6.67430e-11
# astronomical units
au = 1.496e11
sec_in_day = 60 * 60 * 24
dt = 1 * sec_in_day

class Body(object):
    def __init__(self, name, init_pos, init_vel, mass):
        self.name = name
        self.p = init_pos
        self.v = init_vel
        self.m = mass

def run_sim(bodies, t):
    mass = np.array([[b.m] for b in bodies], dtype=float) # (n, 1, 1)
    vel = np.array([b.v for b in bodies], dtype=float) # (n, 1, 3)
    pos = np.array([b.p for b in bodies], dtype=float) # (n, 1, 3)
    names = np.array([b.name for b in bodies], dtype=str)

    # save positions and velocities for plotting
    plt_pos = np.empty((floor(t/dt), pos.shape[0], pos.shape[1]))
    plt_vel = np.empty((floor(t/dt), pos.shape[0], pos.shape[1]))

    # center of mass
    com_p = np.sum(np.multiply(mass, pos),axis=0) / np.sum(mass,axis=0)

    curr = 0
    i = 0
    while curr < t:
        dr = np.nan_to_num(pos[None,:] - pos[:,None])
        r3 = np.nan_to_num(np.sum(np.abs(dr)**2, axis=-1)**(0.5)).reshape((pos.shape[0],pos.shape[0],1))
        a = G * np.sum((np.nan_to_num(np.divide(dr, r3)) * np.tile(mass,(pos.shape[0],1)).reshape(pos.shape[0],pos.shape[0],1)), axis=1)

        pos += vel * dt
        plt_pos[i] = pos
        vel += a * dt
        plt_vel[i] = vel
        curr += dt
        i += 1

    fig = plt.figure(figsize=(15,15))
    ax = fig.add_subplot()
    for i in list(range(plt_pos.shape[1])):
        ax.plot(plt_pos[:,i,0], plt_pos[:,i,1], alpha=0.5, label=names[i])
        ax.scatter(plt_pos[-1,i,0], plt_pos[-1,i,1], marker="o", label=f'{i}')
    plt.legend()
    plt.show()

run_sim(bodies = [ Body('Alpha Centauri A', [0, 0, 0], [0,22345,0], 1.989e30*1.1),
                  Body('Alpha Centauri B', [23 * au, 0, 0], [0,-18100,0], 1.989e30*0.907),
                 ],
        t = 100 * 365 * sec_in_day
        )

And this is the resulting plot. I would expect their orbits to be less variant and more circular, sort of in a Venn diagram-esque form.
Comment: how can you call NumPy stuff without importing, fixed the formatting
Comment: my mistake, got cut out when copy/pasting!
Comment: You are using the first order Euler method, unphysical results are to be expected, see https://stackoverflow.com/questions/53645649/cannot-get-rk4-to-solve-for-position-of-orbiting-body, https://stackoverflow.com/questions/53813499/python-euler-method-implementation-in-two-body-problem
Answer: There are 3 steps to a correctly looking plot.
First and most importantly, get the implementation of the physical model right. r3 is supposed to contain the third powers of the distances, thus the third power of the square root has exponent 1.5
        r3 = np.nan_to_num(np.sum(np.abs(dr)**2, axis=-1)**(1.5)).reshape((pos.shape[0],pos.shape[0],1))

This then gives the cleaned up plot

Note the differences in the scales in the axes, one would have to horizontally compress the image  by a factor of 40 to get the same scale in both directions.
Second, this means that the initial velocity is too large, the stars flee from each other. These velocities might be right in the position where the stars are closest together. As a quick fix, divide the velocities by 10. This gives the plot

Better initial values could be obtained by evaluating and transforming the supposedly more realistic data from https://towardsdatascience.com/modelling-the-three-body-problem-in-classical-mechanics-using-python-9dc270ad7767 or use the Kepler laws with the more general data from http://www.solstation.com/orbits/ac-absys.htm
Third, the mass center is not at the origin and has a non-zero velocity. Normalize the initial values for that
    # center of mass
    com_p = np.sum(np.multiply(mass, pos),axis=0) / np.sum(mass,axis=0)
    com_v = np.sum(np.multiply(mass, vel),axis=0) / np.sum(mass,axis=0)
    for p in pos: p -= com_p
    for v in vel: v -= com_v

(or apply suitable broadcasting magic instead of the last two lines) to get the plot that you were probably expecting.

That the orbits spiral outwards is typical for the Euler method, as the individual steps move along the tangents to the convex ellipses of the exact solution.
The same only using RK4 with 5-day time steps gives prefect looking ellipses

For the RK4 implementation the most important step is to package the non-trivial derivatives computation into a separate sub-procedure
def run_sim(bodies, t, dt, method = "RK4"):
    ...

    def acc(pos):
        dr = np.nan_to_num(pos[None,:] - pos[:,None])
        r3 = np.nan_to_num(np.sum(np.abs(dr)**2, axis=-1)**(1.5)).reshape((pos.shape[0],pos.shape[0],1))
        return G * np.sum((np.nan_to_num(np.divide(dr, r3)) * np.tile(mass,(pos.shape[0],1)).reshape(pos.shape[0],pos.shape[0],1)), axis=1)

Then one can take the Euler step out of the time loop
    def Euler_step(pos, vel, dt):
        a = acc(pos);
        return pos+vel*dt, vel+a*dt

and similarly implement the RK4 step
    def RK4_step(pos, vel, dt):
        v1 = vel
        a1 = acc(pos)
        v2 = vel + a1*0.5*dt
        a2 = acc(pos+v1*0.5*dt)
        v3 = vel + a2*0.5*dt
        a3 = acc(pos+v2*0.5*dt)
        v4 = vel + a3*dt
        a4 = acc(pos+v3*dt)
        return pos+(v1+2*v2+2*v3+v4)/6*dt, vel+(a1+2*a2+2*a3+a4)/6*dt

Select the method like
    stepper = RK4_step if method == "RK4" else Euler_step

and then the time loop takes the generic form
    N = floor(t/dt)
    ...
    for i in range(1,N+1):
        pos, vel = stepper(pos, vel, dt)
        plt_pos[i] = pos
        plt_vel[i] = vel

Comment: This is very helpful, thank you! My only other question would be if you can add your RK4 code to your answer so that I make sure I can reproduce the plot myself.


C# Windows Form: Declared/initialized a FileStream object, builds successfully, doesn't run

Question: I'm using a Windows Form to make a Book Catalog (ISBNs, titles, authors, etc.). I have a sample .txt file that I want to be read, then added to my ListBox. Each line of the .txt file is to be an item in the ListBox. The draft version of the Form works great, but I want to be able to load a .txt file of books into my Form. Here's the issue: declaring and initializing a FileStream object as such...
static FileStream file = new FileStream(FILENAME, FileMode.Open, FileAccess.Read);

...allows my program to build successfully, but it doesn't run. It doesn't even throw an error. Instead, I get something that looks like this (screenshot): https://i.stack.imgur.com/kCuBk.jpg And I know it's not the StreamReader object because a StreamReader needs a FileStream object in the first place (for the constructor).
Any ideas? Any way in which my limited knowledge is preventing me from asking a better question?
Comment: attach the image here, don't link
Comment: I unfortunately don't have enough reputation to post images yet. I recently made my account.
Answer: First of all I don't know what you are trying to do with the stream but I would first of all use a using statement (how you are using it I mean)
using (FileStream fileStream = File.Open(@"C:\somefile", FileMode.Open, FileAccess.Read))
{
    ...
}

edit:
I would suggest something like this from (http://msdn.microsoft.com/en-us/library/aa287535(v=vs.71).aspx)
using(var reader = new StreamReader(@"c:\test.txt")){
    while((line = reader.ReadLine()) != null)
    {
        ListBox.Items.Add(line);
    }
}

Comment: Also - notice File.open instead of new FileStream
Comment: I'm doing something to the effect of while(line_from_txt_file != null) { ListBox.Items.Add(line_from_txt_file);}
Comment: thank you for your help! I'm not entirely sure why my textbook's example doesn't use a "using" statement...I'll be sure to figure that out.


ibanez edge III tremolo intonation out of adjustment

Question: i have an ibanez edge III trem and all my strings are 3 cents sharp for intonation. the adjusters are as far as they can go toward the neck..
is there any way to correct this?
Answer: If they are sharp, the length is too short. Luckily they need to be adjusted longer, away from the neck, so there will be room for improvement by screwing the saddles so that the strings are a little longer.


Monitor MySQL Connection and Request

Question: I'm trying to monitor all incoming connections to a mysql database. I've used
tcpdump port 3306 and '(tcp-syn|tcp-ack)!=0'

currently which is showing connections but is there a way to also see what it is sending/receiving?
Currently I see:
11:45:43.275498 IP ip-10-0-40-123.ec2.internal.mysql > ip-10-0-21-17.ec2.internal.35522: Flags [.], ack 1780, win 248, options [nop,nop,TS val 2559781727 ecr 625071366], length 0
11:45:43.277761 IP ip-10-0-40-123.ec2.internal.mysql > ip-10-0-21-17.ec2.internal.35522: Flags [P.], seq 519:538, ack 1780, win 248, options [nop,nop,TS val 2559781729 ecr 625071366], length 19
11:45:43.277799 IP ip-10-0-40-123.ec2.internal.mysql > ip-10-0-41-109.ec2.internal.60718: Flags [P.], seq 32662:32900, ack 1, win 219, options [nop,nop,TS val 2559781729 ecr 2559505629], length 238
11:45:43.278331 IP ip-10-0-41-109.ec2.internal.60718 > ip-10-0-40-123.ec2.internal.mysql: Flags [.], ack 32900, win 24565, options [nop,nop,TS val 2559505675 ecr 2559781729], length 0
11:45:43.278345 IP ip-10-0-21-17.ec2.internal.35522 > ip-10-0-40-123.ec2.internal.mysql: Flags [P.], seq 1780:1989, ack 538, win 211, options [nop,nop,TS val 625071368 ecr 2559781729], length 209
11:45:43.280364 IP ip-10-0-40-123.ec2.internal.mysql > ip-10-0-21-17.ec2.internal.35522: Flags [P.], seq 538:596, ack 1989, win 258, options [nop,nop,TS val 2559781732 ecr 625071368], length 58
11:45:43.280375 IP ip-10-0-40-123.ec2.internal.mysql > ip-10-0-41-109.ec2.internal.60718: Flags [P.], seq 32900:33171, ack 1, win 219, options [nop,nop,TS val 2559781732 ecr 2559505675], length 271
11:45:43.280971 IP ip-10-0-21-17.ec2.internal.35522 > ip-10-0-40-123.ec2.internal.mysql: Flags [P.], seq 1989:1994, ack 596, win 211, options [nop,nop,TS val 625071371 ecr 2559781732], length 5
11:45:43.280983 IP ip-10-0-21-17.ec2.internal.35522 > ip-10-0-40-123.ec2.internal.mysql: Flags [F.], seq 1994, ack 596, win 211, options [nop,nop,TS val 625071371 ecr 2559781732], length 0
11:45:43.281003 IP ip-10-0-40-123.ec2.internal.mysql > ip-10-0-21-17.ec2.internal.35522: Flags [F.], seq 596, ack 1995, win 258, options [nop,nop,TS val 2559781733 ecr 625071371], length 0
11:45:43.281011 IP ip-10-0-41-109.ec2.internal.60718 > ip-10-0-40-123.ec2.internal.mysql: Flags [.], ack 33171, win 24565, options [nop,nop,TS val 2559505677 ecr 2559781732], length 0
11:45:43.281553 IP ip-10-0-21-17.ec2.internal.35522 > ip-10-0-40-123.ec2.internal.mysql: Flags [.], ack 597, win 211, options [nop,nop,TS val 625071372 ecr 2559781733], length 0

I was hoping for something like:
11:45:43.281011 IP ip-10-0-41-109.ec2.internal.60718 > ip-10-0-40-123.ec2.internal.mysql: Flags [.], ack 33171, win 24565, options [nop,nop,TS val 2559505677 ecr 2559781732], length 0 'select userid from users where email = 'firstname.lastname@example.com''
11:45:43.277799 IP ip-10-0-40-123.ec2.internal.mysql > ip-10-0-41-109.ec2.internal.60718: Flags [P.], seq 32662:32900, ack 1, win 219, options [nop,nop,TS val 2559781729 ecr 2559505629], length 238 '1234'

where the last values are what the DB is processing/returning
Comment: MySQL Workbench allows you to view all connections and their queries
Answer: if i understood it right, what you want is to see the payload that is sent in the communication.
I don't know if the communication between the client and the mySQL server is encrypted, but if its not you can add more parameters to the tcdump command.
try something of this sort
tcpdump -vv port 3306 and '(tcp-syn|tcp-ack)!=0' -nnttttA

This should show the payload in ASCII
Comment: This looks close. The return is `2020-01-22 09:56:04.437977 IP (tos 0x0, ttl 64, id 44011, offset 0, flags [DF], proto TCP (6), length 705)
    10.0.21.17.37018 > 10.0.40.123.3306: Flags [P.], cksum 0x0fa7 (correct), seq 385:1038, ack 213, win 211, options [nop,nop,TS val 704892527 ecr 2639602889], length 653
E.....@.@.:.
...
.({......g7...n...........
*..o.U$......INSERT into table
   (columns)
   VALUES (values)` Do you know what the `E.....@.@.:.
...
.({......g7...n...........
*..o.U$......` is?
Comment: might be the package information.

Monitor MySQL Connection and Request


How to add custom metatags in drupal 7?

Question: I need to add a custom metatag to D7 site, something like here: http://groups.drupal.org/node/83069. What are the possible options? I know there is a metatag module, but seems it doesn't support custom tags.
I could modify the theme, but I need some user configurable solution.
Comment: You can have a look at [drupal_add_html_head](http://api.drupal.org/api/drupal/includes--common.inc/function/drupal_add_html_head/7), but you'll need to write a custom module to make it configurable.
Answer: Metatag does support custom tags by implementing hook_metatag_metatags_view_alter(). See the following hook implementation to add the Open Graph video:duration metatag from a custom entity:
/**
 * Alter metatags before being cached.
 *
 * This hook is invoked prior to the meta tags for a given page are cached.
 *
 * @param array $output
 *   All of the meta tags to be output for this page in their raw format. This
 *   is a heavily nested array.
 * @param string $instance
 *   An identifier for the current page's page type, typically a combination
 *   of the entity name and bundle name, e.g. "node:story".
 */
function mycustommodule_metatag_metatags_view_alter(&$output, $instance) {
  if ($instance == 'mycustom:entity') {
    $entity = mycustomentity_load(someid);
    $duration = $entity->duration;
    $output['video:duration']['#attached']['drupal_add_html_head'][0] = array(
      array(
        '#theme' => 'metatag_opengraph',
        '#tag' => 'meta',
        '#id' => 'video:duration',
        '#name' => 'video:duration',
        '#value' => $duration,
      ),
      'video:duration',
    );
  }
}

Answer: Replying late but this may be helpful for others:
I have written about my solution here http://mymixerone.blogspot.in/2012/11/adding-meta-tags-in-drupal-node.html
Just have a look if its helpful.
Here is the solution in brief, Try adding this in your templet.php file:
<?php
function <theme-name>_preprocess_html(&$variables) {
  switch(arg(1)) {
    //current-issues, node id 33
    case "33" :
      // title
      $variables['head_title']= "New Title";

      //key-words
      $page_keywords = array(
        '#type' => 'html_tag',
        '#tag' => 'meta',
        '#attributes' => array(
          'name' => 'keywords',
          'content' => 'all keywords for this node',
        )
      );
      drupal_add_html_head($page_keywords, 'page_keywords');
      break;

    //node id 20
    case "20" :
      // title
      $variables['head_title']= "New Title";
      break;
  }
}
?>

other tags can be added similarly.
Comment: Brief your answer here that will help a lot.
Comment: so basically you're hard-coding metatags into the template? Seems to be a rather dirty way to me. Moreover, in my case the client wished to be able to edit tags, so this approach wasn't feasible.
Comment: Its not dirty as this is done in sub folder of theme. And Intended for someone who needs more control. besides you can always create a form for your client, Save input in a new table and then fetch Tags from there If u do not wish to hardcode :)
Answer: Thank you Atul. I've used your approach to make refreshing page in Drupal support module every 30 seconds.
function garland_preprocess_html(&$vars) {
//Adding Refresh to main tikets page BEGIN
//print 'Node id = ';print(arg(1));
switch(arg(1)){
//check node id : if nid=kontora then use custom "Refresh setup" (must be the name of client you want to refresh)
case "client1" :
/*Implementation of HTML equivalent <meta http-equiv="Refresh" content="30" />*/
$http_equiv = array(
    '#type' => 'html_tag',
    '#tag' => 'meta',
    '#attributes' => array(
    'http-equiv' => 'Refresh',
    'content' => '30',
    )
  );
drupal_add_html_head($http_equiv, 'http_equiv');
// Meta tag code here
break;
/*
//node id 20
case "20" :
      // Meta tag code here
break;*/
     }
//Adding Refresh to main tikets page END
}

Answer: Did you have a look at Meta tags quick?
There is a comparison page for meta tag generation modules.
Comment: btw, if you really have to modify the module and can't override the known tags in your own custom module, remember to write patch and apply it once you upgrade, if not you'll loose your custom tags. Glad I could help :)
Comment: Thanks for an idea. I found that path based metatags don't seem to work with clean urls, but it was really easy to add needed tags by editing known_tags.inc.
Answer: You can also implement hook_metatag_info in a custom module, define your metatag and then you can configure it with UI.
You can see this implementation from metatag module, by example
http://www.drupalcontrib.org/api/drupal/contributions%21metatag%21metatag_opengraph%21metatag_opengraph.metatag.inc/function/metatag_opengraph_metatag_info/7
Answer: Custom meta module will do it.

How to add custom metatags in drupal 7?


what to chose for prior and proposal function for MCMC of a mixture

Question: I generated some data according to a mixture of two lognormals:
$f(x) = p \cdot \mathcal LN(\mu_1, \sigma) + (1-p) \cdot \mathcal LN (\mu_2, \sigma)$
Now I want to use MCMC to find the parameters $p, \mu_1, \mu_2, \sigma$ but I'm unsure what to chose as the prior and the proposal function.
For the prior I chose:
$p \sim Beta$ but what hyperparameters are best?
$\mu_1, \mu_2 \sim Normal$, again, what hyperparameters?
$\sigma \sim Inverse~Gamma$; hyperparameters?
the proposal is a bit more difficult because $p$ has to be drawn of the $[0,1]$ interval. So
$p \sim truncated~Normal$ in $[0,1]$; does this make sense?
$\mu_1, \mu_2, \sigma \sim Normal$  but how do I avoid negative $\sigma$ ?
Is there an R MCMC package that allows custom proposal functions?
Answer:
what hyperparameters are best?

How to select priors is a question that is far too broad for this forum, is somewhat subjective, and entirely depends on what kind of problem you're trying to solve, and what an acceptable prior means to you, for your problem. No one else can do your analysis for you.
For example, one might characterize priors as noninformative, weakly informative and strongly informative. Within each of these taxonomies, reasonable people may disagree about which specific prior fits in each category. And you might disagree about which of those three paradigms are most appropriate.

p∼truncatedNormal in [0,1]; does this make sense?

But what happens when your mean is negative and your standard deviation is small, i.e. when most of the probability mass falls below 0? Rejection sampling will reject almost all of your samples, so the sampler will be slow.
An obvious choice for a parameter in the unit interval is the beta distribution.
Alternatively, you could transform the normal draw to lie in the unit interval: define some function $\mathbb{R}\to[0,1]$.

how do I avoid negative $\sigma$ ?

One of several ways. You could estimate $z=\log (\sigma)$, so that $z \in \mathbb{R}$ and any model of $z$ with real support is acceptable. Or you could select a distribution that only has positive support, e.g. the gamma distribution.

Is there an R MCMC package that allows custom proposal functions?

Yes; in rstan you have the option of penalizing the log-likelihood by any arbitrary function. It includes many default options, but you can also write your own.
Comment: thanks. I have some problems with the gamma distribution when $sigma$ is close to 0.


Proving constants are differentiable using the definition

Question: I'm currently studying differentiability at college, and I can't for the life of me understand how a constant is differentiable. I am using the definition of differentiability (as $h \rightarrow 0$ and you have $h$ at the bottom).
When $f(x) =c$ what is $f(x_0 + h)?$
I understand why x is differentiable but I can't get a hold for constants!
Thank you for reading!
Comment: $f: x \mapsto c$, then $f(x_0 + h) = c$. Was that your question?
Comment: Part of it. If $f(x_0+h) = c \ \text{and if} f(x_0) = c \ \text{then surely the limit is undefined?}$
Answer: Notice that a constant function $f(x) = c$ $\forall x$. That is:
\begin{equation}
f(x_0 + h) = c = f(x_0)
\end{equation}
Using the definition of differentiability:
\begin{equation}
\lim_{h \to 0} \frac{f(x_0 + h) - f(x_0)}{h} = \lim_{h \to 0}\frac{c - c}{h} =\lim_{h \to 0} 0 = 0
\end{equation}
Comment: @EnterpriseMathematics $\frac00$ is undefined, but $\lim_{x\to 0}\frac 0x$ is **not** undefined. Because $\lim_{x\to 0}\frac 0x = L$ if, for **very small but nonzero values** of $x$, the value $\frac0x$ is close to $0$.
Comment: Thank you for your answer, I got to this stage in my working but surely 0/0 is undefined? Or am I missing something
Comment: $0/0$ in a limit need not be undefined, which you'll understand when you learn l'Hospital's rule.
Comment: In defining $f'(x_0)$, you are taking the limit as $h\to 0$ of a function of $h$ (i.e., the difference quotient) defined for all non-zero $h$ (obviously, the difference quotient is not defined at $h=0$, since as you point out, it is $0/0$ which is undefined). In this case, the answer above shows that the function in question is zero for all $h\neq 0$ (remove limit signs in the answer). Now, if a function is $0$ for all non-zero $h$, then its limit at $0$ is also $0$ (remember, we do not need the function to be defined at $0$ to evaluate the limit, and indeed it is not in this case).
Comment: @5xum: One of either the $L$ or the $0$ should be changed to the other.
Answer: As far as I understand, your problem lies a couple of lessons further back, so I'll start there:
Limits
What is a limit of a function? By definition, we have that $$\lim_{x\to a} f(x) = L$$
if and only if for every $\epsilon>0,$ there exists such a $\delta > 0$ that for all $x$ such that $0<|x-a|<\delta$, we have $|L-f(x)|<\epsilon$
What does this mean? Well, it means that the values of $f(x)$ are close to $L$ if $x$ is close to $a$. But there is an important inequality there: $0<|x-a|$. Yes, $x$ is close to $a$, but never equal to it. So, for example, the function $f(x)=\frac {x^2}{x}$, which is undefined at $x=0$, may still have a limit at $x=0$. In fact, that limit is $0$, because:

Take any $\epsilon>0$
Set $\delta = \epsilon$, and let $x$ be such that $|x-a| < \delta$ (where $a$ is of course $0$)
Then, we have $|f(x)-0|=|\frac{x^2}{x}-0| = |x-0|=|x|<\epsilon$, and we are done

Note: the equality $|\frac{x^2}{x}-0| = |x-0|$ **only holds if $x\neq 0$, but the limit does not care about $x=0$, so we are safe.


BCrypt vs Argon2 and their hashing algorithms

Question: i am working in a startup company providing software services and recently we have set security standards for encryption. For hashing, the standards that were set was we should use SHA-512 or SHA-256.
For Java, We are considering using Bcrypt of Spring or Argon2. Actually reading their documentations, can't find any information if their underlying algorithms are using SHA-512 or SHA-256 or something else?
or are these both outdated algorithms for hashing and we should use something else?
Can anyone help me on this?
Comment: Apples and oranges. Bcrypt and argon2 are hashes designed for one purpose and sha-512 and sha-256 are designed for different purpose.
Answer: When you are referring to "security standards for encryption" I'm assuming that you are talking about storing passwords, so I'll write about using "SHA", "BCRYPT" and "ARGON2I" to secure passwords, I'll mention disadvantages and vantages between "SHA" and "BCRYPT/ARGON2I" algorithms.
None of the "SHA" algorithms are designed for hashing passwords, they are fast algorithms making them easy to compute.
For example: They are used for cryptocurrency encryption because they don't encrypt a single word or a short combination of characters, they encrypt a large file containing the currency making it hard to guess the hashed file.
In the other hand hashing methods like "BCRYPT" and "ARGON2I" are made for storing passwords, one of the key differences from "SHA" is that they are slow algorithms meaning that in order to hash a word it can take a full second if configured correctly (because of the cost of the hash).
This means that the time the attacker has to invest in hashing the word that is trying to compare is the same as the word that is hashed (in this example I'm giving 1sec per hash). This dramatically increase up the time that the attacker has to invest in order to match the hashes, making your stored files more secure.
If you want to hash passwords it's recommended to implement slow hashing algorithms, if you want to hash long files it's recommended to implement fast hashing algorithms.
Responding to your last question... Neither "BCRYPT" nor "ARGON2I" are outdated hashing methods. BCRYPT is more reliable in my opinion because of the time it has been on the market, it was released in 1999 and the developers that programmed it are updating it until nowadays. The same happens with "ARGON2I" but it's a newer algorithm (it was created on 2015) meaning that it isn't as tested as "BCRYPT", however it is said that "ARGON2I" is more secure than "BCRYPT" but vulnerabilities could be found forthcoming.
If you notice that I'm speaking about "ARGON2I" and not "ARGON2" is because there are various versions of the algorithm and "ARGON2I" is the one designed for hashing passwords.
These are the links from both slow algorithms Wikipedia and source code in GitHub.
Wikipedia of bcrypt
Wikipedia of argon2
GitHub of bcrypt
GitHub of argon2


Passive and automatic face recognition

Question: Hy guys. At school we use badge for mark who is present, for my exam i want to upgrade that system.
I would like to create a face recognition system, basically i would like to set a raspberry with camera over the doors, like that, when students pass the door will be automatically marked as present.
I know OpenBR but i didn't understand if i can use it for my project, and i have some issues with it, i can't install it, it return me an error when i test it.
I ask you if you know if OpenBR can do the trick for me (you have to know that we are a lot at school), or if there are some other technologies that i can use.
Answer: You could look at using opencv to train an object detector to look for the badge:
http://docs.opencv.org/2.4/doc/user_guide/ug_traincascade.html
https://www.youtube.com/watch?v=WEzm7L5zoZE
If each of the badges have some unique identifier for the students, you could then analyse the identifier to take attendance.
Identifying the badge / face would be the "easy" part.  Identifying the student would be the hard part!
Identifying people from photos is tricky, and I would estimate that Facebook has spent millions on this problem.
Here are a couple of links that may be useful
http://scikit-learn.sourceforge.net/0.6/auto_examples/applications/plot_face_recognition.html
OpenCV identify person with face detection
Comment: Maybe I did not understand, I would like to use only face recognition, in this way, students can even leave badge at home, my project need only of the students's faces. I have to create a DB, where there are stored face with the code of the badge, when the camera "see" a student, the raspberry will send the message to school server and mark that student as present. I will study your links anyway, just in case, tell me if you have other suggestions dude!
Comment: So, you think my project in possible, the rasp will stay all the time recording, taking frames and recognize faces, is that possible? I have a lot of doubts, and i have to be sure to make this project, cause i have not a lot of time to make it, and i cant change it on run.
Comment: Without knowing your time frame: It is possible and detecting faces in general is quite easy. Detecting individual faces is a bit harder and companies have spent a lot of money on this.  But if you are willing to pay you could use a 3rd party sdk where the work has been done for you http://luxand.com/facesdk/
Answer: You use Raspberry Pi for your project, so
Software:
1.OpenCV-Python is a very good choice.
2. SimpleCV is more simple to use but less power than OpenCV. It's still ok for your purpose.
Hardware:
You also need to be aware of hardware, using USB Webcam is not a good choice because of slow speed.
Module camera is better because it uses serial interface to transfer data.

Passive and automatic face recognition


Trouble Upgrading Python / Django on CentOS

Question: As you can see by reading my other thread today here, I'm having some troubles upgrading Python.
At the moment I have Python 2.4 with Django installed on a CentOS machine. However I've recently deployed an application that requires 2.5 which has resulted in me installing that and getting into a whole load of mess. My original assumption was that I could direct Django to a different Python version, however as S.Lott informed me, I had it backwards... you attach Django to Python, not the other way round. Which means I currently have: Python 2.4 with Django and Python 2.5.
I've tried a few things so far to no avail. The first idea being an easy_install which would put Django onto the Python 2.5 (So I'd have 2 versions of python with seperate Djangos). Therefore I went into 2.5's directory and did that, which then allowed me to find out that it had just reinstalls it on 2.4, not 2.5. Therefore first question is How do I direct easy_install to Python 2.5, not 2.4?
Is there no way to just hit 'upgrade' and for a full update to occur? I know this may be asking for much, however it just seems like so much hassle and I'm surprised I can't find anyone else complaining. Any help would be greatly appreciated.
Answer: I don't know anything about CentOS, but if you have multiple Python version installed and you wan't to install packages using easy_install, you just need to call it with the corresponding Python interpreter. This should install the packing into the site-package directory of Python 2.5:
# /path/to/python-2.5 easy_install Django

Answer: assuming your python2.5 interpreter lives in /usr/bin/python2.5, you can install setuptools for python2.5 as such:
curl -O http://peak.telecommunity.com/dist/ez_setup.py
sudo /usr/bin/python2.5 ez_setup.py

Among other things, this installs an "easy_install-2.5" script in your $PATH (check the output of the above command).
Now you have two easy_install scripts: one for python 2.4 ("easy_install") and one for python 2.5 ("easy_install-2.5").
To install Django for your python2.5, use
sudo easy_install-2.5 django

That's it!
Answer: easy_install is a shell script  the first line of which tells it where python is installed (I am on OSX so can't say exactly what your directories will be )
So you could copy easy_install and change the first line to point to 2.5. (or do as Heas suggests)
Althernatively when you installed python 2.5 there might be a file easy_install-2.5 with the correct python (again these were installed for me under OSX so might be a special version)
Answer: You don't need to 'install' Django at all, it just needs to live on the Pythonpath somewhere. Assuming it's currently in the Python2.4 site-packages directory, you can just move it to the 2.5 one:
sudo mv /usr/lib/python2.4/site-packages/django /usr/lib/python2.5/site-packages/django

or whatever the correct path is for CentOS.
However, as I noted on your other question, this won't necessarily help - S.Lott was unfortunately misleading in his answer. To serve Django via modpython or modwsgi with a new Python version, you'll need to recompile those extensions or download packages versions precompiled with Python 2.5.


How can I insert and update a number within the same mysql record?

Question: Hi and thanks for taking the time to read this post
I have a customer database and have been trying to add a loyalty points system so that total of order x value = total loyalty points
I have it working so that when an order is received it updates the table_loyalty with the points and that is working fine
<code>$points = $row["price"] * 1000;

$insert = mysql_db_query($db, "INSERT into table_loyalty (username, orderno, points) VALUES ('$username', '$this_orderno', '$points')", $connection);
check_mysql($insert);
</code>
However, what I would ideally like to be able to do but can't seem to get it to work (tried a few different ways) is to have a running total so that each additional order builds up the $points rather than add a separate record
I'm no coder which I'm sure is obvious but would appreciate any help.
I have tried this but didn't work:
<code>$points = $row["points"];

$newpoints = $row["price"] * 1000;

$update = mysql_db_query($db, "update table_loyalty set points='$points'+'$newpoints' WHERE username='$username'", $connection);
check_mysql($update);

} else {

$insert = mysql_db_query($db, "INSERT into table_loyalty (username, orderno, points) VALUES ('$username', '$this_orderno', '$newpoints')", $connection);
check_mysql($insert);
</code>
Comment: It is better to record the points per order and totalling them separately, since any order can be amended, cancelled, fully or partially returned.
Comment: @Shadow - excellent point ....
Comment: Please wrap your code inside a code block. Example : ``````
Answer: I think I would do a select to check if there already is a record for the given user name. If there is, get its points then execute an update adding additional points to its retrieved total. If there is no record do an insert. I would love to write the php and queries but I'm just on my phone atm. Hope this helps will check later
(UPDATE) Hi Mark apart from the fact that you might want to keep them separate rows because order could be canceled or have other things happen to it (which could be valid points depending on how 'big' your system is. Let's check how you could get the asked for functionality to work.
Do be aware that mysql_db_query has been deprecated since PHP 5.3 and has been completely removed from PHP 7.0.0. So if you want to be able to have this work on the long run I would recommend using http://php.net/manual/en/book.mysqli.php
What I was proposing is the following:
<code>$selectQuery = "SELECT points FROM table_loyalty WHERE username=" . $username . ";"

$selectResult = mysql_db_query($db, $selectQuery, $connection);

// if no results could be found
if (mysql_num_rows($selectResult) == 0) {
  //Presuming this is the order price?
  $newpoints = $row["price"] * 1000;

  $insertQuery = "INSERT into table_loyalty (username, orderno, points) VALUES ('$username', '$this_orderno', '$newpoints')";
  $insertResult = mysql_db_query($db, $insertQuery, $connection);
  // I personally have no idea what the check_mysql() function does, I presume its a function of you own making? With that I'm making the assumption that it handles the result in some way?
  check_mysql($insertResult);

//results have been found
} else {
  $existingPoints = 0;
  while ($row = mysql_fetch_assoc($result)) {
    //There is a catch here. If used in this way you need to make sure that every username only has 1 entry in the table_loyalty. So updating only 1 row per user also means you can ONLY have 1 record per user.
    $existingPoints = $row["points"];
  }

  $newPoints = $row["price"] * 1000;
  $totalPoints = $existingPoints + $newPoints;
  $updateQuery = "update table_loyalty set points='$totalPoints' WHERE username='$username'";

  $update = mysql_db_query($db,updateQuery , $connection);
  check_mysql($update);
}
</code>
Is this something you can work with? It's not the most Elegant solution but in the basics this is what you might want :).
Comment: Thanks (I have updated my post with the code I tried)
Comment: Updated my answer, Hope it might help


How do I use AppleScript to get e-mail addresses, account information from Lotus Notes?

Question: We have a mailbox containing roughly 60,000 e-mails, and I've been challenged to pull the names, account numbers and e-mail addresses out of the body of each and export it into a spreadsheet-friendly format.
I was thinking of using AppleScript and Notes 8.5, but I can't find any documentation on how to interact with individual messages in Notes.
Can anyone help?
Answer: If you're familiar with scripting languages, I suggest going with LotusScript instead.  It gives you direct access to the Notes objects rather than Applescript and the Notes C API.
You can create a Notes Agent within the mailbox using the Notes Designer application.  The code would roughly be this:
Dim s as New NotesSession
Dim db as NotesDatabase
Dim dc as NotesDocumentCollection
Dim doc as NotesDocument

Set db = s.CurrentDatabase
Set dc = db.Search(|Form="Memo"|, Nothing, 0)
Set doc = dc.GetFirstDocument

While Not (doc Is Nothing)

    'Process each document here...

    Set doc = dc.GetNextDocument(doc)
End While

The question is how are the email addresses, account numbers, and names stored in the body of each email?
You could pull all the text out of the body of the emails into a large text file, perhaps, and then process that with Applescript, if you're more comfortable with that.
fileNum = Freefile()
pathname = "C:\path\to\file"
Open pathname For Output As fileNum
While Not (doc Is Nothing)

    Set rtitem = doc.GetFirstItem( "Body" )
    Write #fileNum, rtitem.GetFormattedText(False, 0)

    Set doc = dc.GetNextDocument(doc)
End While
Close fileNum

Or you could use the NotesRichTextItem methods to navigate and extract specific data from the body.  This could be useful, perhaps, if the data is stored in tables within the body of the email, as the NotesRichTextItem methods allow you to find a table element and navigate cells (although this is rather difficult, and might be worth posting a second question on StackOverflow to get help with this).
If you're looking to get the email address and names from the To: or From: fields of the email, you can do that more easily by accessing properties of the NotesDocument for each email.  The fields could be extracted like so:
Dim ToEmail as String
Dim FromEmail as String

ToEmail = doc.SendTo(0)   'a document's item properties are zero-based arrays
FromEmail = doc.From(0)

Comment: Thank you so much for the great information! I wish I could +10 your great reply!From what I can tell I don't have the environment for Lotus script
Comment: Do you have access to the Notes designer?  Or perhaps could you get it from another machine?  The Applescript option seems daunting to me, especially with so little documentation.
Comment: It does not appear so. I've look everywhere I can think of, and I even fixed my Notes Help issue in the process. :) But, no. It looks like I'm blocked from it. I agree with you. Thank you so much for your help!


Hover em duas divs dentro da mesma coluna

Question: Minha dúvida é a seguinte: tenho uma coluna com uma texto e um ícone, preciso que quando o mouse ficar em cima da coluna tanto o texto quanto o ícone mudem de cor, segue o HTML:

.features .round-icon {
  border: 4px solid #1c1c1c;
  border-radius: 50%;
  display: table;
  height: 100px;
  width: 100px;
  font-size: 3.6rem;
}

.features .round-icon span {
  color: #1c1c1c;
  display: table-cell;
  text-align: center;
  vertical-align: middle;
}

#numeros-coluna2:hover{background-color:#ffc600;}

    5MIL

Comment: Rodolpho, pode adicionar a pergunta o CSS ?
Comment: Basta aplicar o `hover` ao elemento pai.
Comment: Aplica o `hover` a essa `div > #numeros-coluna2`
Comment: Sim, esse div esta com o hover, texto muda a cor, mas o icone nao
Comment: Não está com hover no CSS que você postou.
Comment: adicionado, no caso preciso que o 5MIL e o icone fiquem brancos
Answer:

    5MIL

Answer: O que você pode fazer é selecionar devidamente os elementos filhos a partir do evento hover do elemento pai. Por exemplo, se você deseja alterar tanto a cor da fonte quanto a da borda dos elementos filhos, pode fazer:

.features .round-icon {
  border: 4px solid #1c1c1c;
  border-radius: 50%;
  display: table;
  height: 100px;
  width: 100px;
  font-size: 3.6rem;
}

.features .round-icon span {
  color: #1c1c1c;
  display: table-cell;
  text-align: center;
  vertical-align: middle;
}

.features .columns:hover span {
  color: red;
}

.features .columns:hover div {
  border-color: red;
}

    5MIL

      $

Comment: Valeu Anderson, works like a charm! HAHA