text:
Q: How to average two variables in Javascript? I am attending CoderCamps and I am in week 2. My final project is to create a web app using HTML and Javascript that allows the user to type a passage inside of a textarea and then display the average words per sentence, the number of words, spaces and sentences on the web page.
I have everything working properly except I can't seem to get the average to sum up... Any help would be much appreciated.
Thank you.
Here's my code so far.
var button = document.getElementById("button");
var text = document.getElementById("textarea");
var totalSpaces = 0;
var totalWords = 0;
var avgWords = 0;
var totalSentences = 0;

button.addEventListener("click", function(){
    var text = document.getElementById("textarea").value;
    text.length

    for (var i =0; i<text.length; i++){
        if(text[i] == " "){
            totalSpaces++;
        }
        if(text[i] == "."){
            totalSentences++;
        }
        if(text[i] == "?"){
            totalSentences++;
        }
        if(text[i] == "!"){
            totalSentences++;
        }

    }

    document.getElementById("avg").innerHTML = totalWords / totalSentences;
    document.getElementById("words").innerHTML = totalWords = totalSpaces +1;
    document.getElementById("sentences").innerHTML = totalSentences;
    document.getElementById("spaces").innerHTML = totalSpaces;

    totalSpaces = 0;
    totalWords = 0;
    avgWords = 0;
    totalSentences = 0;
});

A:

var button = document.getElementById("button");
var text = document.getElementById("textarea");
var totalSpaces = 0;
var totalWords = 0;
var avgWords = 0;
var totalSentences = 0;

button.addEventListener("click", function(){
  var text = document.getElementById("textarea").value;

  for (var i =0; i<text.length; i++){
      if(text[i] == " "){
          totalSpaces++;
      }
      if(text[i] == "."){
          totalSentences++;
      }
      if(text[i] == "?"){
          totalSentences++;
      }
      if(text[i] == "!"){
          totalSentences++;
      }

  }
  totalWords = totalSpaces;

  document.getElementById("avg").innerHTML = totalWords / totalSentences;
  document.getElementById("words").innerHTML = totalWords;
  document.getElementById("sentences").innerHTML = totalSentences;
  document.getElementById("spaces").innerHTML = totalSpaces;

  totalSpaces = 0;
  totalWords = 0;
  avgWords = 0;
  totalSentences = 0;
});


text:
Q: iPad won't launch any app, won't update, won't reset My iPad Pro (2018, iPadOS 15.1) will not launch any app anymore.

*

*The home screen / springboard is responsive, I can reorganize apps and browse the App Library. The home screen only has app icons (1 page then the App Library), I removed all widgets earlier just in case.

*Launching any app will try to launch it but freeze and quit it. Safari opens a black page with the address bar then quits after 30 seconds. Apple apps and third-party apps all behave the same except the Camera app for some reason. Things (the Cultured Code app) used to freeze and quit all day but somehow now started to work no problem as I'm typing this.

*I can open the Settings app but trying to install the iPadOS 15.2.1 update freezes and quits, so does tapping "Transfer or Reset iPad".

*I've rebooted several times by long-pressing the home and power buttons.

*I've tried updating it to 15.2.1 or resetting it using my M1 MacBook Air (macOS 12.1) and an Apple USB-C to Lightning cable (no dock or dongle in between), and the Finder gets stuck on "Preparing to install the software" or "Preparing to restore the software" for hours with no progress.

Is there any way to get out of this? It's like the iPad is soft-bricked, I've never seen this in 10+ years of using iPads.

A: While I did not figure out how to get the apps to launch, I did find a way to reset the iPad and restore it from a backup:

*

*Connect the iPad to an up-to-date Mac

*Enter recovery mode by long-pressing the Home and Power buttons until the  Recovery Mode screen appears (more info: https://www.lifewire.com/ipad-recovery-mode-stuck-at-apple-logo-1994540). Without entering Recovery Mode, my Mac was unable to update or reset the iPad. I imagine DFU Mode would have also worked in this situation.

*In Finder, click "Restore…" to reset the iPad to factory settings, which in my case also installed iPadOS 15.2.1, after which I was able to choose "Restore from an iCloud backup" to get all apps and settings back.

The backup has been working well so far, with none of the symptoms from the initial questions. All apps are running fine and smoothly like they did a few days ago.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Null check operator used on a null value with flutter and dart I resently came across this error while building my flutter app.

======== Exception caught by widgets library =======================================================
The following _CastError was thrown building StreamBuilder<QuerySnapshot<Object?>>(dirty, state: _StreamBuilderBaseState<QuerySnapshot<Object?>, AsyncSnapshot<QuerySnapshot<Object?>>>#97a1b):
Null check operator used on a null value

The relevant error-causing widget was:
StreamBuilder<QuerySnapshot<Object?>> StreamBuilder
===============================================================================

This occured right after i try to display a screen/layout which has to stream data from firestore
Here is my firebase instance and the code I tried on my own.
final Stream<QuerySnapshot> teachersRegistered = FirebaseFirestore.instance.
    collection('userData').snapshots();

StreamBuilder<QuerySnapshot<Object?>>(
    stream: teachersRegistered,
    builder: (context, snapshot) {
      if (snapshot.hasError) {
        return const Text('Error');
      } else if (snapshot.connectionState == ConnectionState.waiting) {
        return const Text("waiting for connection");
      } else if (snapshot.connectionState == ConnectionState.done) {
        return const Text("Online");
      } else if (snapshot.connectionState == ConnectionState.none) {
        return const Text("THere's no connection");
      } else if (snapshot.hasData) {
        List<DropdownMenuItem> teachersItem = [];
        for (int i = 0; i < snapshot.data!.docs.length; i++) {
          DocumentSnapshot data = snapshot.data!.docs[i];

          teachersItem.add(DropdownMenuItem(
            value: user!.uid,
            child: Column(
              children: [
                Text(data['name']),
              ],
            ),
          ));
        }
        return DropdownButton(
          isExpanded: false,
          items: teachersItem,
          onChanged: (teacherItemValue) {
            setState(() {
              valueTeacher1 = teacherItemValue;
            });
          },
          value: valueTeacher1,
          hint: const Text("Teacher"),
        );
      }
      return const Text("No data");
    })

A: for me add did unusual way i down graded my flutter version
in terminal i typed this command : Flutter downgrade
and it solved my error which was : Error: Expected ';' after this. platform_channel.dart:313       6throw MissingPluginException('No implementation found for method $method on channel $name');

A: Can you try to convert data type like
  final Stream<QuerySnapshot<Map<String, dynamic>>> teachersRegistered =
      FirebaseFirestore.instance.collection('userData').snapshots();

  StreamBuilder<QuerySnapshot<Map<String, dynamic>>>(
      stream: teachersRegistered,


text:
Q: How to get First and Last for every month How to Add First for 1 to 10 dates for a month and Add Last for 20 to 30 days of month.
DECLARE @Today DATE = '2016-11-05'

Select  CONVERT(VARCHAR(5),datepart (DW, @Today)-1 )+' DAYS of '+ LEFT(DATENAME(month,@Today),3) Comments

I'm getting like this
Comments
6 DAYS of Nov

How to get like this :
Comments
First 6 DAYS of Nov

if I give date as '2016-11-24'
need output like this
     Comments
     Last 4 DAYS of Nov

Suggest me the way to proceed

A: Use a case statement:
Select (CASE WHEN day(@today) <= 10 THEN 'First '
             WHEN day(@today) >= 20 THEN 'Last '
             ELSE ''
        END) + CONVERT(VARCHAR(5), datepart(DW, @Today)-1 ) + ' DAYS of ' +
        LEFT(DATENAME(month, @Today), 3) as Comments

EDIT:
Oh, now I see the original query was not right.  So you want something more like this:
Select (CASE WHEN day(@today) <= 10 THEN 'First ' + DATENAME(day, @today) + ' DAYS of ' + LEFT(DATENAME(month, @Today), 3)
             WHEN day(@today) >= 20 AND MONTH(@Today) IN (1, 3, 5, 7, 8, 10, 12) THEN 'Last ' + CAST(31 - day(@today) as varchar(255))
             WHEN day(@today) >= 20 AND MONTH(@Today) IN (4, 6, 9, 11) THEN 'Last ' + CAST(30 - day(@today) as varchar(255))
             WHEN day(@today) >= 20 AND MONTH(@Today) IN (2) AND YEAR(@Today) % 4 = 0 THEN 'Last ' + CAST(29 - day(@today) as varchar(255))
             WHEN day(@today) >= 20 AND MONTH(@Today) IN (2) AND YEAR(@Today) % 4 <> 0 THEN 'Last ' + CAST(29 - day(@today) as varchar(255))
             ELSE CAST(day(@today) as varchar(255))
        END)  + ' DAYS of ' + LEFT(DATENAME(month, @Today), 3) as Comments

A: DECLARE @Today DATE = '2016-11-09'

Select (CASE WHEN day(@today) <= 10 THEN 'First ' + DATENAME(day, @today)
             WHEN day(@today) >= 20 THEN 'Last ' + CAST(DAY(DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,@Today)+1,0))) - day(@today) as varchar(255))
             ELSE CAST(day(@today) as varchar(255) )
        END)  + ' DAYS of ' + LEFT(DATENAME(month, @Today), 3)

A: With SQL Server 2012 developers can now use new SQL date function EOMonth() for calculating the last date of the month where a given date is in.
Here is my query
--DECLARE @Today DATE = '2016-11-05'
DECLARE @Today DATE = '2016-11-24'

SELECT
 case when DATEPART(dd,@Today) <= 10 then
 'First ' + convert(varchar(2), DATEPART(dd,@Today)) + ' of ' + DATENAME(mm,@Today)
 else
 'Last ' + convert(varchar(2), DATEDIFF(dd, @Today, EOMONTH (@Today))) + ' of ' + DATENAME(mm,@Today)
 end

The SQL EOMonth() function makes it easier to calculate the last date of a month, and also indirectly calculating the first date of next month or previous month

A: SELECT case when DATEPART(dd,@Today) <= 10 then
 'First ' + convert(varchar(2), DATEPART(dd,@Today)) + ' DAYS of ' + DATENAME(mm,@Today)
WHEN DATEPART(dd,@Today) >= 20 then  'Last ' + convert(varchar(2),
DATEDIFF(dd, @Today, EOMONTH (@Today))) + ' DAYS of ' + DATENAME(mm,@Today)
ELSE @Today END


text:
Q: Get userinput in JavaScript I want to get user inputs using the  tag in HTML and not the prompt function in JavaScript.
I also don't want to have to use another language on top of this like php.
Edit
Something like this would be desirable
<form action="demo_form.asp">
  First name: <input type="text" name="fname">

  <input type="submit" value="Submit">
</form>

but without using a .asp

A: Create an input tag with id attribute
<input type="text" id="a" name="b" />

in javascript, you can get the value of an input field via its id
var x = document.getElementById('a').value;

A: <input type="text" id="input1" />
<button onclick="myJsFunction()"></button>

A: and for textbox
<!DOCTYPE html>

Click the button to demonstrate the prompt box.

        <button onclick="myFunction()">Press me</button>

A: JavaScript has three kind of popup boxes: Alert box, Confirm box, and Prompt box.
<!DOCTYPE html>

Click the button to display an alert box.

<button onclick="myFunction()">Try it</button>


text:
Q: Is there a most suited filesystem for distributed game tree traversal? I have been looking at this paper on distributed game tree traversal and (with help from others) attempted to make a Python/mpi4py clone of the software tree traverser in order to solve 2-player abstract strategy games.
Firstly, Wikipedia provides a breif description on how to "solve" a game.
It is a common optimization to remember results that have already been solved so further tree traversal is un-needed. As a cluster of computers cannot trivially share the results amongst each other a variety of approaches have been taken to solve this issue. The method in the paper (Transposition Table Driven Work Scheduling) works essentially as follows:

*

*Give an ID to each computer 1 to n (I just used the standard MPI rank)

*At any particular point a computer may receive a position. Check to see if the position is in the look up table or trivially done. If it is, send back the resulting value, otherwise, generate the children.

*Hash each child position so they have an associated value of 1 to n. Send each position to the "correct" computer with the ID of the hash.

*Repeat until the initial position has been solved.

As the paper even mentions, this method works somewhat paradoxically, having an incredibly high communication rate.
Here are the issues:
On a single computer it seems to work fine. I then ran some tests on my school's cluster and ran into some serious issues. Solving a game like TicTacToe was abysmal often timing out in "debug mode" (4 nodes, 20 cores, and 15 minute time limit).
I saved the TicTacToe solution database to what they call the "user directory" (more can be found here). This is in contrast to the "scratch" directory which is normally used to store data. When I did this, the database for TicTacToe was solved in a matter of seconds.
I noticed that the "scratch" space used "Lustre FS" which appears to be a poor choice for "peer-to-peer" applications:

While a Lustre file system can function in many work environments, it
  is not necessarily the best choice for all applications. It is best
  suited for uses that exceed the capacity that a single server can
  provide, though in some use cases, a Lustre file system can perform
  better with a single server than other file systems due to its strong
  locking and data coherency.
A Lustre file system is currently not particularly well suited for
  "peer-to-peer" usage models where clients and servers are running on
  the same node, each sharing a small amount of storage, due to the lack
  of data replication at the Lustre software level. In such uses, if one
  client/server fails, then the data stored on that node will not be
  accessible until the node is restarted.

I might just not have a solid enough grasp of distributed computing, but it seems that Lustre FS might not objectively be good fit for this kind of problem. Unfortunately, the cluster I was using is locked in to using Lustre FS. Another option is something like Google Cloud Engine or AWS to do the task, however I am confused about some points:

*

*A lot of the abstractions seem to scare me. All of these cloud platforms offer "scalable solutions" which often involve "load balancing" which is not only unnecessary, but detrimental to the algorithm. (It is imperative the positions are sent to the correct computers so they can be looked up quickly). Does Google Cloud Engine or AWS provide away of getting bare bones enough for this algorithm to work effectively?

*What filesystem should I be using? Google Cloud Engine recomends NFS or Gluster, but I am unsure. The paper is fairly outdated and doesn't seem to use anything special. Does AWS or Google Cloud Engine offer an appropriate filesystem for this kind of task?

A: Without any code nor a description of how the filesystem is used, it is really hard to provide some valuable help.
Anyway, if i read between the line

*

*you build a "database" of solutions

*this "database" is implemented on top of a filesystem

*adding an entry is a file creation

*a lookup is a file existence check

did i get it right ?
if yes, then this is not a surprise performance is awful and do not scale.
you are basically asking a parallel filesystem what it does worst : a lot of metadata access from all nodes, which involve under the hood traffic to keep a consistent view of the filesystem.
how much data do you need to store the solutions ?
at first glance, it might be faster to store them in an old school database (such as MySQL).
an other option would be to store this on a local filesystem, and have the remote nodes issue queries to the task running where the data is stored (create this file, does this file exist) so there is no need to keep meta-data consistent accross nodes.
a better version would be to have all the nodes store solutions and replies to queries. you could hash a solution and deduce on which node it is stored, so you know which MPI tasks should be asked to store the solution or issue a query.
if you really have to use a filesystem, then NFS might be a better choice than a parallel filesystem such as lustre, glusterfs or gpfs.


text:
Q: How to make zoomable LinearLayout? I am having an xml file which I want to make zoomable.

A: use this jar in your application
1.Create a new layout (R.layout.zoomableview) for Views that i want to apply the zooming functionality.
2.Place it inside ZoomView.
3.Then place the ZoomView to the main container where you want to show the zoomable view.
private ZoomView zoomView;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_zoomable);

View v = ((LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.zoomableview, null, false);
v.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));

zoomView = new ZoomView(this);
zoomView.addView(v);

main_container = (LinearLayout) findViewById(R.id.main_container);
main_container.addView(zoomView);            }


text:
Q: Passing password between linux commands and Python I want to execute some  Linux commands using  superuser privileges in Python.
Initially i want to input the password from user and then store the password in variable for future use while executing Linux commands using Superuser privileges.
Below its a sample code, what i intended to do:
import os, sys, getpass**

# To input password from user then use this password while execution of Linux commands using superuser privileges.

password = getpass.getpass()
# Before executing below line it'll prompt to enter the password and here i want to use password variable.

os.system("sudo  -s")
# [sudo] password for <username>: # <Password>

After successful execution of above command i  want to execute rest of code as superuser privileges.
NOTE: I want to use standard method (i.e stdin, stdout, stderr, pipe etc) for inputing  password while execution of os.system("sudo -s") command. I know there are other methods too to deal with this problem.
For Example:
import os

password = "my-password"
command = "echo {0} | sudo -s {1}".format(password, "my-command")
os.system(command)

Please assist me, how can i do it or correct me if my intention is wrong  for doing so.

A: You can do it with pexpect:
Python 2.7.12 (default, Nov 19 2016, 06:48:10)
[GCC 5.4.0 20160609] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import pexpect
>>> terminal = pexpect.spawn('/bin/sh')

Launching the shell
>>> terminal.sendline('sudo aptitude help')
19

Sending the command
>>> terminal.expect('andy:')
0

Expecting [sudo] password for <user>: or just <user>: to appear in the output (terminal will wait for it)
>>> import getpass
>>> password = getpass.getpass()
Password:

Getting the password
>>> terminal.sendline(password)
16

Sending the password to the terminal
>>> result = ''
>>> while True:
...     try:
...         result += terminal.read_nonblocking(1, 1)
...     except pexpect.TIMEOUT:
...         break
...

Getting the result
>>> result
'\r\naptitude 0.7.4\r\n\xd0\x98\xd1\x81\xd0\xbf\xd0\xbe\xd0\xbb\xd1\x8c\xd0\xb7\xd0\xbe\xd0\xb2\xd0\xb0\xd0\xbd\xd0\xb8\xd0\xb5: aptitude [-S \xd0\xb8\xd0\xbc\xd1\x8f \xd1\x84\xd0\xb0\xd0\xb9\xd0\xbb\xd0\xb0] [-u|-i]\r\n       aptitude [\xd0\xbf\xd0\xb0\xd1\x80\xd0\xb0\xd0\xbc\xd0\xb5\xd1\x82\xd1\x80\xd1\x8b] <\xd0\xb4\xd0\xb5\xd0\xb9\xd1\x81\xd1\x82\xd0\xb2\xd0\xb8\xd0\xb5> \xe2\x80\xa6\r\n  \xd0\x94\xd0\xb5\xd0\xb9\xd1\x81\xd1\x82\xd0\xb2\xd0\xb8\xd1\x8f (\xd0\xb5\xd1\x81\xd0\xbb\xd0\xb8 \xd0\xbd\xd0\xb5 \xd0\xb7\...'

(it's Russian)
Pexpect docs here


text:
Q: Start Appium on jenkins and wait for it to fully complete startup I m setting up jenkins to run appium scripts. The issue I am seeing is if I run main.js to start appium the jenkins will not execute next commands and if I put appium in background next statements are executed immediately. Is there any way to start appium in background and wait for it to complete? and also once test execution complete how will I stop appium if appium process is in background?
Thanks in Advance
Shrikanth

A: You can create one folder called build and put your application in same folder and create a batch file using following commands :
cd /d C"":\Program Files (x86)\Appium\node_modules""
node appium  --address 127.0.0.1 --port 4723 --app C:\Build\Application.apk --pre-launch --platform-name Android --platform-version 23 --automation-name Appium --device-name "DEVICEID" --log-no-color
Trigger this batch file from Jenkins and give wait of 20000 millisecond before running your test script.


text:
Q: How to read non-standard binary data into numpy array? Can numpy be used to efficiently and elegantly unpack data from binary? For instance, I have a 64-bit word. Its int interpretation is 7998445715760012608.
As binary this is:
>>> bin(7998445715760012608)
0b110111100000000001100000000000000111011000111101101110101000000

This number is actually 5 values packed back to back:
        data fields:
            [63-56, 55-44, 43-9,8-5,4-0 ]
            [E     ,D    , C,   B,  A   ]

That is:
          E        D            C                                   B    A
binary:   11011110 000000000110 00000000000001110110001111011011101 0100 0000
decimal:  222      6            3874525                             4    0

I can do this manually with bit shifting etc. but then I want to construct a numpy array with the end data. I would like to instead use numpy directly to read the binary data.
I have tried using numpy's structured arrays but the complication is that my bits do not fit into standard datatypes, like u8 or u16. Instead, I need u5 and u35 which do not exist.


text:
Q: How to connect multiple xml files My app needs different screens and each screen should be connected with each other. For example there are 5 screens, the main screen, 4 other screens connected to the main screen. The main screen contains 4 buttons to goto other screens and the other screens has a button to go back to the main screen. The problem is i cant get the ids of other screens. And do i need to create 4 .java files for the new screens?
This is the code for connecting main screen to others:
LayoutInflater inflater;
View one;
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.total_assets);
    inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    one = inflater.inflate(R.layout.total_assets,null);

    Button home = (Button) findViewById(R.id.goback);

    home.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub
            setContentView(R.layout.activity_acc_soft);
        }
    });

total_assets is the second screen and actinity_acc_soft is the main screen.
(plz help newbie to android)

A: You can also use  and  tag in your main.xml file to include other xml files....
http://developer.android.com/training/improving-layouts/reusing-layouts.html

A: use <include/> in your main xml to include other xmls in your layout.
OR
Use fragments.

A: You can use ViewFlipper. You just have to add all layouts to your main layout. And then you can go in your MainActivity.java through all layouts. >ViewFlipper<
But thats an older version of going through the views.
A nicer and more up to date method is using Fragments >Fragments<
Fragements Tut 1
Fragments Tut 2
Fragments Tut 3
There are many other tutorials and examples. Just google for "Android fragments Tutorial/example"


text:
Q: ManualResetEvent.WaitOne() with 0 timeout returns unexpected false although event was set I have a class that wraps ManualResetEvent (see in the code sample below)
During my application flow I call the WaitOne method with a 0 parameter a few times.
It returns true as expected, except for one particular check that returns false although no exception was thrown and I can clearly see from my logs that the event was set.
Could there be another reason for WaitOne to return false?
I will also mention that I have 2 different engines inheriting from the same engine that has a SafeManualResetEvent member. Lets call them A and B.
The flow is that A.SafeManualResetEvent was set, and a few calls of A.WaitOne(0) returned true.
Then, B.Set() is called and completed. Then, A.WaitOne(0) is called again and returns false.
After that, all A.WaitOne(0) and B.WaitOne(0) return true as expected.
Is it possible that the two instances of ManualRestEvent are disturbing each other?
I am adding here a very abstract sample. Please note that the waitOne calls can be from different threads in our app. Please also note that this issue doesn't happen consistently. Out of thousands of users running this app, only one complained about it but we are still struggling to figure out what's different in his environment.
public void Main()
    {
        PolicyEngine policy = new PolicyEngine();

        policy.WaitEngine(); //will return true because initial state is true

        policy.LoadEngine();

        policy.WaitEngine(); //will return true

        FileEngine file = new FileEngine();

        policy.WaitEngine(); //will return true

        file.LoadEngine();

        policy.WaitEngine(); //returns false - unexpected!

        policy.WaitEngine(); //returns true

        file.WaitEngine(); //returns true
    }

    public class Engine
    {
        protected virtual string GetName()
        {
            return "base";
        }

        private readonly SafeManualResetEvent _engineLoadedEvent = new SafeManualResetEvent(true);

        public Engine()
        {
            _engineLoadedEvent._name = GetName();
            Console.WriteLine("base");
        }

        public void LoadEngine()
        {
            _engineLoadedEvent.Reset();

            //some code that loads the engine

            _engineLoadedEvent.Set();
        }

        public void WaitEngine()
        {
            bool result = _engineLoadedEvent.WaitOne(new TimeSpan(0));
            Console.WriteLine($"waitOne result is: {result}");
        }
    }

    public class FileEngine : Engine
    {
        override protected string GetName()
        {
            return "file";
        }
    }

    public class PolicyEngine : Engine
    {
        override protected string GetName()
        {
            return "policy";
        }
    }

    public class SafeManualResetEvent : IDisposable
    {
        public string _name;

        public SafeManualResetEvent(bool initialState)
        {
            ManualResetEvent = new ManualResetEvent(initialState);
        }

        public ManualResetEvent ManualResetEvent { get; }

        public bool WaitOne(TimeSpan timeout)
        {
            try
            {
                Console.WriteLine($"waitOne event for {_name}");
                return ManualResetEvent.WaitOne(timeout);
            }
            catch (ObjectDisposedException)
            {
                return false;
            }
        }

        public void Reset()
        {
            try
            {
                Console.WriteLine($"reset event for {_name}");
                ManualResetEvent.Reset();
            }
            catch (ObjectDisposedException)
            {
            }
        }

        public void Set()
        {
            try
            {
                Console.WriteLine($"set event for {_name}");
                ManualResetEvent.Set();
            }
            catch (ObjectDisposedException)
            {
            }
        }

        public void Dispose()
        {
            Console.WriteLine($"dispose event for {_name}");
            ManualResetEvent.Dispose();
        }
    }


text:
Q: SQL Error: 900 when running update query with multiple fields Running JPA native query with multiple fields from SQL developer console works, but the same query results in SQL Error: 900, SQLState: 42000 from JPA repository.
Query in JPA -
@Query(value = "UPDATE SUBSCRIPTIONFILE SET DESCRIPTION = ?1, FILENAME = ?2, VERSION = ?3 WHERE (PLATFORM = ?4 AND PRODUCTSKU = ?5)", nativeQuery = true)
    SUBSCRIPTIONFILE updateUsingEmbdedKey(String DESCRIPTION, String FILENAME, String VERSION, String PLATFORM, String PRODUCTSKU);

And as the debug console shows -
2018-12-03 18:37:02.734 DEBUG 5180 --- [           main] org.hibernate.SQL                        : UPDATE SUBSCRIPTIONFILE SET DESCRIPTION = ?, FILENAME = ?, VERSION = ? WHERE (PLATFORM = ? AND PRODUCTSKU = ?)
2018-12-03 18:37:04.405 TRACE 5180 --- [           main] o.h.type.descriptor.sql.BasicBinder      : binding parameter [1] as [VARCHAR] - [newDescription!]
2018-12-03 18:37:04.427 TRACE 5180 --- [           main] o.h.type.descriptor.sql.BasicBinder      : binding parameter [2] as [VARCHAR] - [bla bla bla]
2018-12-03 18:37:04.437 TRACE 5180 --- [           main] o.h.type.descriptor.sql.BasicBinder      : binding parameter [3] as [VARCHAR] - [bla]
2018-12-03 18:37:04.445 TRACE 5180 --- [           main] o.h.type.descriptor.sql.BasicBinder      : binding parameter [4] as [VARCHAR] - [xyz]
2018-12-03 18:37:04.455 TRACE 5180 --- [           main] o.h.type.descriptor.sql.BasicBinder      : binding parameter [5] as [VARCHAR] - [testSave]

My questions:
1 - is the query syntax is OK?
2- is there a better way to do it using a built-in JpaRepository query?
Entire JpaRepository -
public interface SubscriptionRepo extends JpaRepository<SUBSCRIPTIONFILE, SUBSCRIPTIONFILE_KEY>{

    @Query(value = "UPDATE SUBSCRIPTIONFILE SET DESCRIPTION = ?1, FILENAME = ?2, VERSION = ?3 WHERE (PLATFORM = ?4 AND PRODUCTSKU = ?5)", nativeQuery = true)
            SUBSCRIPTIONFILE updateUsingEmbdedKey(String DESCRIPTION, String FILENAME, String VERSION, String PLATFORM, String PRODUCTSKU);
     }

A: Since this is an update you need a @Modifying annotation to go with your @Query annotation.


text:
Q: RegExMatch backreference group with literal string I can't figure out how to make a back reference pass a group of string instead of only 1, hard for me to explain but I hope you can understand.
This is what I have, XX([^---]+?)XX
It WILL match 12345XX text XX54321
It will NOT match 12345XX -text- XX54321
the problem lies here > ([^---]+?) <
I can't figure out how to make it match 3 dashes instead of 1.
I would appreciate any help. =)

A: I attempted to come up with a regex for you, this match a simple string, a string within dash and all dashes
Regex
(?:XX\s?)([\w-]+)(?:\sXX)

Test string

12345XX text XX54321
12345XX -text- XX54321
12345XX --- XX54321

Result
MATCH 1

*

*[8-12]  text
MATCH 2

*

*[29-35] -text-
MATCH 3

*

*[52-55] ---
try demo here

SET 2
Regex
(?:XX\s?[^\w]*)([\w]+)(?:[^\w]*\sXX)

Test string

12345XX text XX54321
12345XX -text- XX54321
12345XX ---test--- XX54321

Result
MATCH 1

*

*[8-12]  text
MATCH 2

*

*[30-34] text
MATCH 3

*

*[55-59] test
try demo here
Note: test string and regex are based on assumptions, we can adjust as needed


text:
Q: Git hook to update superproject on submodule change? I have three git repositories: A, B, and C. C is a superproject including submodules A and B, tracking each submodule's respective master branch.
When the master branch of A or B is changed, I must do the following in C:
git submodule update --remote
git add A
git add B
git commit -m "Update submodule A or B"
git push

At this point an automated build and deploy from C is executed.
I'm looking for ways to streamline this process. Ideally, any commit to the master branch of A or B would trigger a hook to update, commit, and push to C. Any ideas how to achieve this?
Edit: In case there's a vendor-specific feature I should be aware of, I'm using Azure DevOps for the git hosting and Azure Pipelines for the build and deploy process.

A: You can use a git post-commit hook, when you do a commit in the submodules the hook will be executed and will do the commands.

*

*Go to each sub module repo.

*Create file .git/hooks/post-commit with following content:
#!/bin/sh

branch="$(git rev-parse --abbrev-ref HEAD)"

if [ "$branch" = "master" ]; then
  cd {super repo location}
  git submodule update --remote
  git add A
  git add B
  git commit -m "Update submodule A or B"
  git push
fi

*Make it executable (not required on Windows):
$ chmod +x .git/hooks/pre-commit


text:
Q: Assigning values to numbers in a text string using sql in mysql This is an example of a string inserted into a mysql db field after a multiple choice checkbox form field has been submitted. (including the brackets): [1,0,1]
1=box checked
When the first number in the string = 1 value = pie, when the second number in this string =1 value= cookies, when the third number in this string =1 value = fruit. So the output for this string would be cookies, fruit.
I need to assign values to these numbers in an sql query. Something like:
select answer_data
from answers
where if the first number in the string = 1, the value is pie; if the 2nd number in the string = 1, the value is cookies;if the third number in the string=1, the value is fruit;

A: Caveat: Storing the data in this implied mapping to an array definition is a very brittle design.  A better approach would be to just store the actual text values as JSON.
However, if you must use that approach...
If you defined a stored procedure

*

*https://dev.mysql.com/doc/refman/8.0/en/create-procedure.html
You could use the Substring function to tease out the values - and assemble desired output

*

*https://dev.mysql.com/doc/refman/8.0/en/string-functions.html#function_substring


text:
Q: Generalization of primitive roots The standard definition is that $a\in\mathbb{Z}$ is a primitive root modulo $p$ if the order of $a$ modulo $p$ is $p-1$.
Let me rephrase, to motivate my generalization: $a\in\mathbb{Z}$ is a primitive root modulo $p$ if the linear recurrence defined by $x_0=1$, $x_n=ax_{n-1}$ for $n\geq1$ has maximum possible period in $\mathbb{Z}/p\mathbb{Z}$.
So, we could define $(a_1,\ldots,a_r)\in\mathbb{Z}^r$ to be an $r$-primitive root modulo $p$ when the order $r$ linear recurrence defined by $x_0=\cdots=x_{r-2}=0$, $x_{r-1}=1$, and $x_n=a_1x_{n-1}+\cdots+a_rx_{n-r}$ for $n\geq r$ has the maximum possible period (for such sequences) in $\mathbb{Z}/p\mathbb{Z}$.
Is anything known about the generalized version of primitive roots I've described? I chose my initial values $x_0=\cdots=x_{r-2}=0$, $x_{r-1}=1$ in analogy with the Fibonacci numbers, but is there a standard / most general choice? The starting values affect the period a lot, so it's important to be working with the "right" ones, I guess. What is the maximum achievable period for a linear recurrence in $\mathbb{Z}/p\mathbb{Z}$? An obvious upper bound is $p^r-1$, but it's not clear to me that this is the correct number to replace $p-1$ in the standard definition of primitive root. Is anything known in the direction of Artin's conjecture for "$r$-primitive roots", as I've called them?
Other thoughts: because there is no "formula" for the order of $a$ modulo $p$ (this would amount to a formula for the discrete logarithm), there certainly isn't a formula for the period of the linear recurrence defined by $(a_1,\ldots,a_r)$ modulo $p$. I tried to come up with one for a while before I realized this, so I just wanted to save anyone else the trouble.

A: If $(a_1,\ldots,a_r)$ is an $r$-primitive root in your definition, then the polynomial $x^r-a_1x^{r-1}-\cdots-a_r$ is irreducible in $Z/pZ[x]$ and any of
its roots is a generator (i.e. a primitive root) of the multiplicative group of the field of $p^r$ elements and conversely. This maximal period is $p^r-1$. See, e.g., Lidl-Niederreiter Finite Fields.

A: The proof is short enough to give here.
Proposition:  A finite subgroup of the multiplicative group of a field is cyclic.
Proof.  Let $G$ be a finite subgroup of the multiplicative group of a field $K$.  Since $g^{|G|} = 1$ for all $g$ and since polynomials over a field have at most as many roots as their degree, it follows necessarily that $\prod_g (x - g) = x^{|G|} - 1$.  By inspecting the roots of the polynomials $x^d - 1, d | |G|$, it follows that $G$ has $\phi(d)$ elements of order $d$, and this condition is equivalent to $G$ being cyclic (indeed it implies that there is at least one element of order $|G|$).
Corollary:  $(\mathbb{F}_{p^n})^*$ has an element of order $p^n - 1$.  (This gives the primitive element theorem for finite fields.)
Let $\alpha$ be such an element and let $f(x) = x^n - a_{n-1} x^{n-1} - ... - a_0 = \prod_{i=0}^{n-1} (x - \alpha^{p^i})$ be its minimal polynomial.  The generating function $\frac{1}{x^n f \left( \frac1x \right)} \bmod p$ has a partial fraction decomposition containing terms corresponding to $(p^n - 1)^{th}$ roots of unity, so its coefficients necessarily have period exactly $p^n - 1$.

A: There are good results related to what you are asking. Hans Roskam stated and proved a quadratic analogue of Artin's conjecture (and I think his paper is much easier to read than Hooley's). He studies the density of primes in which a fundamental unit in a real quadratic field has a maximal order.
The paper is titled, "A quadratic Analogue of Artin's Conjecture on Primitive Roots" Journal of Number Theory 81, 93-109, doi: 10.1006/jnth.1999.2470.
You can find his papers here and this is also good.
Hope this helps.


text:
Q: Discord.py wait_for command when user adds reaction So I need some help!
So far I have the code do the following... Someone inputs the !stage command and then their stage(int)... It sends a message in another where the FTO will react to the message. When reacted the FTO will get a DM with info!
So my question is how do I use wait_for for the user who originally sent the command to be contacted by the bot when the FTO clicks the reactions. Like I need the bot to send that original command user a DM with who clicked the reaction.
@client.command()
async def stage(ctx, *, stage):
    ftochannel = client.get_channel(1043289756794093639)
    logchannel = client.get_channel(1037550844935147622)
    embed=discord.Embed(title=f"{ctx.author.mention} has requested ride along for stage **{stage}**",description=f"If you want to assist this member with their requested stage react below!", color=0x660066)
    log=discord.Embed(title=f"Discord Log // User Requested Ride Along in BCSO Discord",description=f'Ran By: {ctx.author.mention}\nActual Command Finish: {ctx.author.mention} has just requested the following stage: {stage}! ',color=0x660066)
    emoji = "\N{Large Yellow Circle}"

    msg = await ftochannel.send(embed=embed)
    await msg.add_reaction(emoji)

    await ctx.send("When an FTO member answers me You will get a message from me with more information! Please be patient!")
    await logchannel.send(embed=log)

@client.event
async def on_raw_reaction_add(payload):
    if str(payload.emoji) == "\N{Large Yellow Circle}":
        member = payload.member
        sendEmbedToUser = discord.Embed(title=f'Hello', description=f'You have accepted THIS PERSONS Stage RIDE ALONG!\nPlease Arrive in <#1038926472259313732> within **10 Minutes**!\n\nHere is some helpful documentation for your ride along:\n[LINK SHORTNER 1]\n[LINK SHORTNER 1]\n[LINK SHORTNER 1]\n[LINK SHORTNER 1]')
        await member.send(embed=sendEmbedToUser)

[]
With some help from friends I no know I need to used wait_for somewhere in the stage command but I have no clue how to do it!


text:
Q: Python regular expression sub pattern with format string I have a simple output:
def main():
    output = ['Sum is 60', \
              'Sum is 30','range pattern is normal', 'area is 3', \
              'Sum is 20', 'range pattern is stub', 'area is 1' \
              'Sum is 50']
    cmdOut = '\n'.join(output)
    rangePattern = "range pattern is (?P<rP>(normal|stub))\s*" \
                   "area is (?P<id>[0-9]+)"
    areaPattern = "Sum is (?P<num>[0-9]+)\s*" \
           "(?P<range>(%s)+)?" % (rangePattern)
    patt = "(?P<area>(%s)+)" % (areaPattern)
    for m in re.finditer( patt, cmdOut ):
      print m.group( 'area' )
      print '-'

and I want to group each occurrence of sum and range pattern in one group (area). This is my desired output
Sum is 60
-
Sum is 30
range pattern is normal
-
Sum is 20
range pattern is stub
-
Sum is 50

However, this is what I got:
Sum is 60
Sum is 30
range pattern is normal
-
Sum is 20
range pattern is stub
-
Sum is 50

I wonder why it does not separate the first and second group although it successfully separates the 3rd and 4th.

A: The problem isn't the string formatting at all; it just doesn't help the readability of your pattern.
The problem is your quantifiers.  The complete pattern you have is this:

(?P(Sum is (?P[0-9]+)\s*(?P(range pattern is (?P(normal|stub))\s*area is (?P[0-9]+))+)?)+)

If I rewrite it for clarity (not for actual functionality) it would look like this:
(?P<area>(sum\s(range)?)+)

When your pattern matches, the whole "range" part is optional, and the whole thing can be repeated.  So on your first set of input it matches the "Sum ... 60" part, matches the newline, then repeats with the "Sum ... 30\nrange ..." part.
Perhaps you don't want the one-or-more repetition in your group?  Changing that makes your example work for me.  (note that the first match will contain a newline at the end; you may want to remove that before printing it)


text:
Q: CodePipeline CloudFormation resource has dependency on exported variable created by a resource I have 3 parts to my application

*

*API Server (API Gateway)

*Frontend

*Lambda

I have setup CodePipeline to build my application stack.
I have CodeBuild to build my API gateway SAM application. And CloudFormation to deploy. This CloudFormation exports a variable ApiEndpoint. This variable is used my my web CodeBuild to use.

The problem now is CloudFormation is saying

No export named skynet-infra-server-ApiEndpoint found. Rollback requested by user.

I understand now that its because the Server build has not complete thus that variable is not exported. But how can I resolve this?
AWSTemplateFormatVersion : '2010-09-09'
Description: 'Skynet stack for Infrastructure. CodePipeline, S3'

Parameters:
  PipelineName:
    Type: String
    Description: Pipeline Name (Lower case only, since S3 bucket names can only have lowercase)
    Default: skynet-pipeline
  AppName:
    Type: String
    Description: App Name
    Default: skynet
  GitHubOwner:
    Type: String
    Description: GitHub Owner
    Default: 2359media
  GitHubRepo:
    Type: String
    Description: GitHub Repo
    Default: 'skynet'
  GitHubBranch:
    Type: String
    Description: GitHub Branch
    Default: master
  GitHubToken:
    Type: String
    Description: GitHub Token
    NoEcho: true

Resources:
  S3WebBucket:
    Type: AWS::S3::Bucket
    Properties:
      BucketName: !Sub '${AppName}-web'
      WebsiteConfiguration:
        IndexDocument: index.html
        RoutingRules:
          - RedirectRule:
              ReplaceKeyPrefixWith: '#'
            RoutingRuleCondition:
              HttpErrorCodeReturnedEquals: '404'

      AccessControl: PublicRead
      Tags:
        - Key: Cost Center
          Value: !Ref AppName
        - Key: Owner
          Value: Jiew Meng

  Pipeline:
    Type: AWS::CodePipeline::Pipeline
    Properties:
      Name: !Ref PipelineName
      RoleArn: !GetAtt [PipelineRole, Arn]
      ArtifactStore:
        Location: !Ref PipelineArtifactStore
        Type: S3
      DisableInboundStageTransitions: []
      Stages:
        - Name: GitHubSource
          Actions:
          - Name: Source
            ActionTypeId:
              Category: Source
              Owner: ThirdParty
              Version: 1
              Provider: GitHub
            Configuration:
              Owner: !Ref GitHubOwner
              Repo: !Ref GitHubRepo
              Branch: !Ref GitHubBranch
              OAuthToken: !Ref GitHubToken
            OutputArtifacts:
              - Name: SourceCode
        - Name: Build
          Actions:
          - Name: Lambda
            InputArtifacts:
              - Name: SourceCode
            OutputArtifacts:
              - Name: LambdaPackage
            ActionTypeId:
              Category: Build
              Owner: AWS
              Version: 1
              Provider: CodeBuild
            Configuration:
              ProjectName: !Ref CodeBuildLambda
          - Name: Server
            InputArtifacts:
              - Name: SourceCode
            OutputArtifacts:
              - Name: ServerPackage
            ActionTypeId:
              Category: Build
              Owner: AWS
              Version: 1
              Provider: CodeBuild
            Configuration:
              ProjectName: !Ref CodeBuildServer

        - Name: CreateChangeSet
          Actions:
          - Name: Lambda
            InputArtifacts:
              - Name: LambdaPackage
            OutputArtifacts:
              - Name: LambdaDeployment
            ActionTypeId:
              Category: Deploy
              Owner: AWS
              Version: 1
              Provider: CloudFormation
            Configuration:
              ActionMode: CHANGE_SET_REPLACE
              ChangeSetName: !Sub
                - '${PipelineName}-lambda'
                - {PipelineName: !Ref PipelineName}
              RoleArn: !GetAtt [CloudFormationRole, Arn]
              StackName: !Sub
                - '${PipelineName}-lambda'
                - {PipelineName: !Ref PipelineName}
              TemplatePath: 'LambdaPackage::SkynetLambdaPackaged.yml'
              Capabilities: CAPABILITY_NAMED_IAM
              ParameterOverrides: !Sub '{"AppName": "${PipelineName}-lambda"}'
          - Name: Server
            InputArtifacts:
              - Name: ServerPackage
            OutputArtifacts:
              - Name: ServerDeployment
            ActionTypeId:
              Category: Deploy
              Owner: AWS
              Version: 1
              Provider: CloudFormation
            Configuration:
              ActionMode: CHANGE_SET_REPLACE
              ChangeSetName: !Sub
                - '${PipelineName}-server'
                - {PipelineName: !Ref PipelineName}
              RoleArn: !GetAtt [CloudFormationRole, Arn]
              StackName: !Sub
                - '${PipelineName}-server'
                - {PipelineName: !Ref PipelineName}
              TemplatePath: 'ServerPackage::SkynetServerPackaged.yml'
              Capabilities: CAPABILITY_NAMED_IAM
              ParameterOverrides: !Sub '{"AppName": "${PipelineName}-server"}'

        - Name: Deploy
          Actions:
          - Name: Lambda
            ActionTypeId:
              Category: Deploy
              Owner: AWS
              Version: 1
              Provider: CloudFormation
            Configuration:
              ActionMode: CHANGE_SET_EXECUTE
              ChangeSetName: !Sub
                - '${PipelineName}-lambda'
                - {PipelineName: !Ref PipelineName}
              StackName: !Sub
                - '${PipelineName}-lambda'
                - {PipelineName: !Ref PipelineName}
          - Name: Server
            ActionTypeId:
              Category: Deploy
              Owner: AWS
              Version: 1
              Provider: CloudFormation
            Configuration:
              ActionMode: CHANGE_SET_EXECUTE
              ChangeSetName: !Sub
                - '${PipelineName}-server'
                - {PipelineName: !Ref PipelineName}
              StackName: !Sub
                - '${PipelineName}-server'
                - {PipelineName: !Ref PipelineName}
          - Name: Web
            InputArtifacts:
              - Name: SourceCode
            ActionTypeId:
              Category: Build
              Owner: AWS
              Version: 1
              Provider: CodeBuild
            Configuration:
              ProjectName: !Ref CodeBuildWeb

  CodeBuildLambda:
    Type: AWS::CodeBuild::Project
    Properties:
      Name: !Sub '${PipelineName}-lambda'
      Artifacts:
        Type: CODEPIPELINE
      Environment:
        ComputeType: BUILD_GENERAL1_SMALL
        Image: aws/codebuild/nodejs:7.0.0
        Type: LINUX_CONTAINER
        EnvironmentVariables:
          - Name: S3_BUCKET
            Value: !Ref PipelineArtifactStore
      ServiceRole: !Ref CodeBuildRole
      Source:
        BuildSpec: 'lambda/buildspec.yml'
        Type: CODEPIPELINE

  CodeBuildServer:
    Type: AWS::CodeBuild::Project
    Properties:
      Name: !Sub '${PipelineName}-server'
      Artifacts:
        Type: CODEPIPELINE
      Environment:
        ComputeType: BUILD_GENERAL1_SMALL
        Image: aws/codebuild/nodejs:7.0.0
        Type: LINUX_CONTAINER
        EnvironmentVariables:
          - Name: S3_BUCKET
            Value: !Ref PipelineArtifactStore
      ServiceRole: !Ref CodeBuildRole
      Source:
        BuildSpec: 'server/buildspec.yml'
        Type: CODEPIPELINE

  CodeBuildWeb:
    Type: AWS::CodeBuild::Project
    Properties:
      Name: !Sub '${PipelineName}-web'
      Artifacts:
        Type: CODEPIPELINE
      Environment:
        ComputeType: BUILD_GENERAL1_SMALL
        Image: aws/codebuild/nodejs:7.0.0
        Type: LINUX_CONTAINER
        EnvironmentVariables:
          - Name: S3_BUCKET
            Value: !Ref S3WebBucket
          - Name: API_URL
            Value:
              Fn::ImportValue:
                !Sub '${PipelineName}-server-ApiEndpoint'
      ServiceRole: !Ref CodeBuildRole
      Source:
        BuildSpec: 'web/buildspec.yml'
        Type: CODEPIPELINE

  PipelineArtifactStore:
    Type: AWS::S3::Bucket
    Properties:
      BucketName: !Sub '${PipelineName}-artifacts'
      VersioningConfiguration:
        Status: Enabled

  CodeBuildRole:
    Type: AWS::IAM::Role
    Properties:
      RoleName: !Sub '${PipelineName}-codebuild'
      AssumeRolePolicyDocument:
        Version: '2012-10-17'
        Statement:
          Effect: Allow
          Principal:
            Service: codebuild.amazonaws.com
          Action: sts:AssumeRole
      Policies:
        - PolicyName: !Sub '${PipelineName}-codebuild'
          PolicyDocument:
            Version: '2012-10-17'
            Statement:
              - Effect: Allow
                Resource: 'arn:aws:logs:*:*:*'
                Action:
                - 'logs:CreateLogGroup'
                - 'logs:CreateLogStream'
                - 'logs:PutLogEvents'
              - Effect: Allow
                Resource:
                  - !Sub 'arn:aws:s3:::codepipeline-${AWS::Region}-*/*'
                  - !Sub
                    - '${PipelineArtifactStoreArn}/*'
                    - {PipelineArtifactStoreArn: !GetAtt [PipelineArtifactStore, Arn]}
                Action:
                  - 's3:GetObject'
                  - 's3:GetObjectVersion'
                  - 's3:PutObject'
              - Effect: Allow
                Resource:
                  - !Sub
                    - '${S3WebArn}/*'
                    - {S3WebArn: !GetAtt S3WebBucket.Arn}
                Action:
                  - 's3:*'

  CloudFormationRole:
    Type: AWS::IAM::Role
    Properties:
      RoleName: !Sub '${PipelineName}-cloudformation'
      AssumeRolePolicyDocument:
        Version: '2012-10-17'
        Statement:
        - Effect: Allow
          Principal:
            Service: cloudformation.amazonaws.com
          Action:
          - sts:AssumeRole
      ManagedPolicyArns:
        - 'arn:aws:iam::aws:policy/AWSLambdaExecute'
      Policies:
        - PolicyName: !Sub '${PipelineName}-cloudformation'
          PolicyDocument:
            Version: '2012-10-17'
            Statement:
              - Effect: Allow
                Resource: '*'
                Action:
                - 's3:GetObject'
                - 's3:GetObjectVersion'
                - 's3:GetBucketVersioning'
              - Effect: Allow
                Resource: 'arn:aws:s3:::codepipeline*'
                Action:
                - 's3:PutObject'
              - Effect: Allow
                Resource: '*'
                Action:
                - 'lambda:*'
              - Effect: Allow
                Resource: !Sub 'arn:aws:apigateway:${AWS::Region}::*'
                Action:
                - 'apigateway:*'
              - Effect: Allow
                Resource: '*'
                Action:
                - 'lambda:CreateEventSourceMapping'
                - 'lambda:DeleteEventSourceMapping'
                - 'lambda:GetEventSourceMapping'
              - Effect: Allow
                Resource: '*'
                Action:
                - 'iam:GetRole'
                - 'iam:CreateRole'
                - 'iam:DeleteRole'
                - 'iam:PassRole'
                - 'iam:AttachRolePolicy'
                - 'iam:DetachRolePolicy'
                - 'iam:DeleteRolePolicy'
                - 'iam:PutRolePolicy'
              - Effect: Allow
                Resource: '*'
                Action:
                - 'iam:PassRole'
              - Effect: Allow
                Resource: !Sub 'arn:aws:cloudformation:${AWS::Region}:aws:transform/Serverless-2016-10-31'
                Action:
                - 'cloudformation:CreateChangeSet'
              - Effect: Allow
                Resource: '*'
                Action:
                - 'events:*'

  PipelineRole:
    Type: AWS::IAM::Role
    Properties:
      RoleName: !Sub '${PipelineName}-pipeline'
      AssumeRolePolicyDocument:
        Version: '2012-10-17'
        Statement:
        - Action: ['sts:AssumeRole']
          Effect: Allow
          Principal:
            Service: [codepipeline.amazonaws.com]
      Path: /
      Policies:
        - PolicyName: SkynetPipeline
          PolicyDocument:
            Version: '2012-10-17'
            Statement:
              - Action:
                - 's3:GetObject'
                - 's3:GetObjectVersion'
                - 's3:GetBucketVersioning'
                Effect: 'Allow'
                Resource: '*'
              - Action:
                - 's3:PutObject'
                Effect: 'Allow'
                Resource:
                - !GetAtt [PipelineArtifactStore, Arn]
              - Action:
                - 'codecommit:CancelUploadArchive'
                - 'codecommit:GetBranch'
                - 'codecommit:GetCommit'
                - 'codecommit:GetUploadArchiveStatus'
                - 'codecommit:UploadArchive'
                Effect: 'Allow'
                Resource: '*'
              - Action:
                - 'codedeploy:CreateDeployment'
                - 'codedeploy:GetApplicationRevision'
                - 'codedeploy:GetDeployment'
                - 'codedeploy:GetDeploymentConfig'
                - 'codedeploy:RegisterApplicationRevision'
                Effect: 'Allow'
                Resource: '*'
              - Action:
                - 'elasticbeanstalk:*'
                - 'ec2:*'
                - 'elasticloadbalancing:*'
                - 'autoscaling:*'
                - 'cloudwatch:*'
                - 's3:*'
                - 'sns:*'
                - 'cloudformation:*'
                - 'rds:*'
                - 'sqs:*'
                - 'ecs:*'
                - 'iam:PassRole'
                Effect: 'Allow'
                Resource: '*'
              - Action:
                - 'lambda:InvokeFunction'
                - 'lambda:ListFunctions'
                Effect: 'Allow'
                Resource: '*'
              - Action:
                - 'opsworks:CreateDeployment'
                - 'opsworks:DescribeApps'
                - 'opsworks:DescribeCommands'
                - 'opsworks:DescribeDeployments'
                - 'opsworks:DescribeInstances'
                - 'opsworks:DescribeStacks'
                - 'opsworks:UpdateApp'
                - 'opsworks:UpdateStack'
                Effect: 'Allow'
                Resource: '*'
              - Action:
                - 'cloudformation:CreateStack'
                - 'cloudformation:DeleteStack'
                - 'cloudformation:DescribeStacks'
                - 'cloudformation:UpdateStack'
                - 'cloudformation:CreateChangeSet'
                - 'cloudformation:DeleteChangeSet'
                - 'cloudformation:DescribeChangeSet'
                - 'cloudformation:ExecuteChangeSet'
                - 'cloudformation:SetStackPolicy'
                - 'cloudformation:ValidateTemplate'
                - 'iam:PassRole'
                Effect: 'Allow'
                Resource: '*'
              - Action:
                - 'codebuild:BatchGetBuilds'
                - 'codebuild:StartBuild'
                Effect: 'Allow'
                Resource: '*'

Outputs:
  WebsiteUrl:
    Description: Website URL
    Value: !GetAtt S3WebBucket.WebsiteURL

A: Here's two approaches that should work:

*

*You could put the Web CodeBuild action after the Server CloudFormation update, and then pass the output from the CloudFormation action as input to CodeBuild. Seeing as CodePipeline only allows one input to the CodeBuild action you may need to put all your build logic inside an overridden buildspec rather than having it inside the artifact.

*Call the CloudFormation APIs to look up these values as part of the build.


text:
Q: Variance of complex exponential Martingale want to estimate the decay:
$ \mathbb{E} |e^{i\cdot B_{\frac{1}{k}}}-e^{-\frac{1}{2k}}|$, when $ k \to \infty $
where $ B_t$ is one dim standard Brownian Motion.
is it possible that it has exponential decay, say,
$ \mathbb{E} |e^{i\cdot B_{\frac{1}{k}}}-e^{-\frac{1}{2k}}|\le e^{-k} ?$
Thanks in advance!

A: This is only a sketch, I believe you can fill in the technical details.
It's the same as asking about $\mathbb{E} |e^{i\cdot B_{t}}-e^{-t/2}|$ as $t\to 0$. Even more tractable expression is $\mathbb{E} |e^{is X}-e^{-s^2/2}|$, where $X$ is standard normal:
$$
 \mathbb{E} \bigl|e^{is X}-e^{-s^2/2}\bigr| = \int_{-\infty}^{\infty} \bigl|e^{is x}-e^{-s^2/2}\bigr|e^{-x^2/2} \frac{dx}{\sqrt{2\pi}} = \\
= \int_{-\infty}^{\infty}  \bigl((\cos sx -e^{-s^2/2})^2 + \sin^2 sx\bigr)^{1/2}e^{-x^2/2} \frac{dx}{\sqrt{2\pi}}
$$
Note that $\cos sx - e^{-s^2/2} = O(s^2)$, $s\to 0$, (the expression $e^{-s^2/2}$ is not very relevant; $1$, $e^{s^2}$ or $\cos s^2$ would be as good), $\sin^2 sx\sim s^2x^2$, $s\to 0$. Therefore,
$$
 \mathbb{E} \bigl|e^{is X}-e^{-s^2/2}\bigr| \sim |s|\int_{-\infty}^\infty |x|e^{-x^2/2} \frac{dx}{\sqrt{2\pi}} = |s|\sqrt{\frac2\pi},\ s\to 0.
$$


text:
Q: Apache Camel with ActiveMQ clustering I'm trying to determine my options for clustering my ServiceMix 3.3.1/Camel 2.1/AMQ 5.3 application.  I'm performing high volume message processing and I need to cluster for high availability and horizontal scalability.
Here is basically what my application does...HTTP->QUEUE->PROCESS->DATABASE->TOPIC
from("jetty:http://0.0.0.0/inbound")
.to("activemq:inboundQueue");
from("activemq:inboundQueue?maxConcurrentConsumers=50")
.process(decode())
.process(transform())
.process(validate())
.process(saveToDatabase())
.to("activemq:topic:ouboundTopic");
So, I've read all the ServiceMix and AcitveMQ clustering pages, but am still not sure which way to go.
I know I can use a Master/Slave setup for HA, but that doesn't help with scalability.
I've read about network of brokers, but am not sure how this applies.  For example, if I deploy identical Camel routes on multiple nodes in a cluster, how will they "interact" exactly?  If I point my HTTP producer at one node (NodeA), which messages will get sent to NodeB?  Will the queues/topics be shared between Node A/B...if so how, are messages split or duplicated?  Also, how would an external client subscribe to my "outboundTopic" exactly (and get all messages, etc)?
Alternatively, I've been thinking that I should just share a broker between multiple ServiceMix instances.  That would be cleaner in that there would only be one set of queues/topics to manage and I could scale by adding more instances.  But, now I'm limited to the scalability of a single broker and I'm back to a single point of failure...
If anyone can clarify the trade-offs for me...I'd appreciate it.

A: There are a multiple strategies to scale up when you're using the ServiceMix/Camel/ActiveMQ. Because each piece of software offers so many options, there are a variety of paths you could take depending on what portion of the app needs to scale. Below is a high level list of a few strategies:

*

*Increase the number of inbound Jetty instances - This requires starting more instances of the web server and either load balancing requests across the multiple instances or exposing multiple URLs and sending all requests to the same inbound queue in ActiveMQ.

*Increase the number of ActiveMQ instances - By starting up additional ActiveMQ instances and networking them together, you're creating a network of brokers. In some circles this is referred to this as distributed queues because a given queue can be made available across all of the brokers in the network. But if you're going to start up multiple instances of ActiveMQ, you should just consider starting up additional instances of ServiceMix.

*Increase the number of ServiceMix instances - Each instance of ServiceMix embeds an instance of ActiveMQ. By increasing the number of instances of ServiceMix, not only are you increasing the number of ActiveMQ instances (which can be networked together to form a network of brokers) but you then have the ability to deploy more copies of your application across these instances of ServiceMix. If you need to increase the number of ActiveMQ or ServiceMix instances, then you can deploy a consuming application with the appropriate amount of concurrent consumers for each instance. Messages don't get split or duplicated, they are distributed in a round robin fashion to all consumers on the queue, no matter where they are located, based on consumer demand. I.e., if one ActiveMQ instance in the network has no consumers, it won't have any messages on it's instance of the queue to be consumed. This leads to my last suggestion, increasing the number of consumers polling the inbound queue.

*Increase the number of JMS consumers on the inbound queue - This is probably the easiest,  most powerful and most manageable way to increase throughput. It's the easiest because you're deploying additional instances of your consuming application so that they compete for messages from the inbound queue (no matter whether they're competing for a local queue or a queue that is distributed through a network of brokers). This may be as simple as increasing the number of concurrent consumers or a bit more involved by splitting apart the portion of the application that contains the consumers and deploying it to many instances of ServiceMix. It's the most powerful because it's not usually difficult and scaling event driven applications is always done by increasing the number of consumers. It's the most manageable because you have the ability to change the way that your applications are packaged so that the consuming application is wholly separate giving it the ability to be distributed.
This last suggestion is the most powerful way to scale your application. As long as the incoming HTTP endpoint can handle a large amount of traffic, you may only need to increase the consumers on the inbound queue. The big reason for doing this is that either the consumers or the bean to which they hand off is doing all the heavy lifting, the major amount of processing and validation. Typically it's this process that ultimately needs the most resources.
Hopefully this provides the information you need to begin to go in one direction, or possibly a few, depending on what portion of your app you actually need to scale. If you have any questions, please let me know.
Bruce


text:
Q: What is an intersection matrix and how it works? At this page there is a doc about how to handle spatial coordinates and shapes, the figure shows an intersection matrix and according to the writer this matrix generates a bit pattern.
\begin{matrix}
  1 & 0 & 1 \\
  0 & 0 & 1 \\
  1 & 1 & 1
 \end{matrix}
I don't understand what are the inputs ( vectors ? scalars ? ) , how this matrix works ( I'm supposed to add, multiply, ... ? this matrix with something else ) and what kind of mapping is that assuming that is linear mapping.
Does this matrix really exist or is an exotic adaptation of a concept that has a different name in math ?


text:
Q: presenting imagePickerController modally over collectionViewController I'm trying to present an ImagePicker over my collectionViewController but every time my code runs I just get an error saying:

Warning: Attempt to present UIImagePickerController: 0x15c50a370  on <CameraViewController: 0x15c6098a0> which is already presenting (null)

Here's my code:
#import "HomeViewController.h"
#import <Parse/Parse.h>
#import "PhotoCell.h"

@interface HomeViewController ()

@end

@

implementation HomeViewController

-

    (void)viewDidLoad
    {

    [super viewDidLoad];

    UIStoryboard *storyBoard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];
    HomeViewController *vc = (HomeViewController *) [storyBoard instantiateViewControllerWithIdentifier:@"Home"];

    [vc initWithCoder:nil];

    self.edgesForExtendedLayout = UIRectEdgeNone;

    self.title = @"fade";

    self.collectionView.backgroundColor = [UIColor whiteColor];

    [self.collectionView registerClass:[PhotoCell class] forCellWithReuseIdentifier:@"photo"];

    PFUser *currentUser = [PFUser currentUser];
    if (currentUser) {
        NSLog(@"Current User: %@", currentUser.username);
    }
    else {
        [self performSegueWithIdentifier:@"showLogin" sender:self];
    }

}

-(void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {

    if ([segue.identifier isEqualToString:@"showLogin"]) {

        [segue.destinationViewController setHidesBottomBarWhenPushed:YES];
    }
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return 10;
}

- (UICollectionViewCell *) collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"photo";

    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:CellIdentifier forIndexPath:indexPath];

    cell.backgroundColor = [UIColor lightGrayColor];

    return cell;
}

- (id)initWithCoder:(NSCoder*)coder
{
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];

    layout.itemSize = CGSizeMake(306.0, 306.0);
    layout.minimumInteritemSpacing = 150.0;
    layout.minimumLineSpacing = 50.0;

    return (self = [super initWithCollectionViewLayout:layout]);
}

@end


text:
Q: What method is defined to be called if the argument matches multiple method signatures? Given code:
public static void main(String[] args)
{
    doSomething(new ArrayList());
}

public static void doSomething(Collection collection) {
    System.out.println("Collection here!");
}

public static void doSomething(List list) {
    System.out.println("List here!");
}

This prints out List here! as expected, but is this behaviour defined somewhere in the Java Specifications so I can rely on it, given any Java implementation?

A: At compile time most specific method choosen to invoke.
In your case
ArrayList > List > Collection

Since ArrayList is the most specific sub type of List and List is the most Specific subtype of Collection.
Here is specification on rules for method invokation
https://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.12.2.2

A: There's even more interesting behaviour:
public static void main(String[] args)
{
    Collection myCollection = new ArrayList();
    doSomething(myCollection);
}

public static void doSomething(Collection collection) {
    System.out.println("Collection here!");
}

public static void doSomething(List list) {
    System.out.println("List here!");
}

This will print Collection here!


text:
Q: iphone how to post audio or .caf on php server asynchronous in my application i need to record sound .after this i need to post sound file on php server asynchronous

A: consider to use ASIHTTPRequest http://allseeing-i.com/ASIHTTPRequest/ . It is a handy framework to make http connections.
This example is good for your question:
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];

    // Upload a file on disk
    [request setFile:@"/Users/ben/Desktop/ben.jpg" withFileName:@"myphoto.jpg" andContentType:@"image/jpeg"
    forKey:@"photo"];

    // Upload an NSData instance
    [request setData:imageData withFileName:@"myphoto.jpg" andContentType:@"image/jpeg" forKey:@"photo"];


text:
Q: What would an idiomatic, monadic version of maximumBy look like? How can I get a maximum element of an effectful container where computing attribute to compare against also triggers an effect?
There has to be more readable way of doing things like:
latest dir = Turtle.fold (z (ls dir)) Fold.maximum

z :: MonadIO m => m Turtle.FilePath -> m (UTCTime, Turtle.FilePath)
z mx = do
    x <- mx
    d <- datefile x
    return (d, x)

I used overloaded version rather than non-overloaded maximumBy but the latter seems better suite for ad-hoc attribute selection.
How can I be more methodic in solving similar problems?

A: So I know nothing about Turtle; no idea whether this fits well with the rest of the Turtle ecosystem. But since you convinced me in the comments that maximumByM is worth writing by hand, here's how I would do it:
maximumOnM :: (Monad m, Ord b) => (a -> m b) -> [a] -> m a
maximumOnM cmp [x] = return x -- skip the effects if there's no need for comparison
maximumOnM cmp (x:xs) = cmp x >>= \b -> go x b xs where
    go x b [] = return x
    go x b (x':xs) = do
        b' <- cmp x'
        if b < b' then go x' b' xs else go x b xs

I generally prefer the *On versions of things -- which take a function that maps to an Orderable element -- to the *By versions -- which take a function that does the comparison directly. A maximumByM would be similar but have a type like Monad m => (a -> a -> m Ordering) -> [a] -> m a, but this would likely force you to redo effects for each a, and I'm guessing it's not what you want. I find *On more often matches with the thing I want to do and the performance characteristics I want.

A: Since you're already familiar with Fold, you might want to get to know FoldM, which is similar.
data FoldM m a b =
  -- FoldM step initial extract
  forall x . FoldM (x -> a -> m x) (m x) (x -> m b)

You can write:
maximumOnM ::
  (Ord b, Monad m)
  => (a -> m b) -> FoldM m a (Maybe a)
maximumOnM f = FoldM combine (pure Nothing) (fmap snd)
  where
    combine Nothing a = do
      f_a <- f a
      pure (Just (f_a, a))
    combine o@(Just (f_old, old)) new = do
      f_new <- f new
      if f_new > f_old
        then pure $ Just (f_new, new)
        else pure o

Now you can use Foldl.foldM to run the fold on a list (or other Foldable container). Like Fold, FoldM has an Applicative instance, so you can combine multiple effectful folds into one that interleaves the effects of each of them and combines their results.

A: It's possible to run effects on foldables using reducers package.
I'm not sure if it's correct, but it leverages existing combinators and instances (except for Bounded (Maybe a)).
import Data.Semigroup.Applicative (Ap(..))
import Data.Semigroup.Reducer (foldReduce)
import Data.Semigroup (Max(..))
import System.IO (withFile, hFileSize, IOMode(..))

-- | maxLength
--
-- >>> getMax $ maxLength ["abc","a","hello",""]
-- 5
maxLength :: [String] -> (Max Int)
maxLength = foldReduce . map (length)

-- | maxLengthIO
--
-- Note, this runs IO...
--
-- >>> (getAp $ maxLengthIO ["package.yaml", "src/Lib.hs"]) >>= return . getMax
-- Just 1212
--
-- >>> (getAp $ maxLengthIO []) >>= return . getMax
-- Nothing
maxLengthIO :: [String] -> Ap IO (Max (Maybe Integer))
maxLengthIO xs = foldReduce (map (fmap Just . f) xs) where
    f :: String -> IO Integer
    f s = withFile s ReadMode hFileSize

instance Ord a => Bounded (Maybe a) where
    maxBound = Nothing
    minBound = Nothing


text:
Q: Expression of a metric tensor with constant curvature on surface Consider the plane $\mathbb{R}^2$ together with a metric $\mathsf{g}$. Choosing suitable local coordinates $(x_1,x_2)$, $\mathsf{g}$ takes the form :
$$
\mathsf{g}=r(x_1,x_2)\left((dx_1)^2+\epsilon (dx_2)^2\right),\quad r>0\quad\textrm{and}\quad\epsilon = \pm1.
$$
Question : Assume that $\mathsf{g}$ has constant curvature $K$, is there a closed form expression for $r(x,y)$ ? In particular in [1] (p. 331)  it is claimed $\mathsf{g}$ is isometrically equivalent to
$$
\mathsf{g} =\frac{1}{\left(1+\frac{K}{4}\left((y_1)^2+\epsilon(y_2)^2\right)\right)^2}\left((dy_1)^2+\epsilon (dy_2)^2\right)
$$
Is this true ? and if so can somebody provides a reference or a proof of that result ?
My work : When trying to solve the question myself, I'm stuck with the following non-linear PDE (Liouville equation)
$$
\frac{\partial ^2r}{\partial (x_1)^2}r + \epsilon\frac{\partial ^2r}{\partial (x_2)^2}r
+\left(\frac{\partial r}{\partial x_1}\right)^2  - \epsilon\left(\frac{\partial r}{\partial x_2}\right)^2
= - K
$$
[1] George R. Wilkens. "Centro-Affine Geometry in the Plane and Feedback Invariants of Two-State Scalar
Control Systems". Proceedings of Symposia in Pure Mathematics. Ed. by G. Ferreyra et al. Vol. 64. Amer-
ican Mathematical Society, 1998. doi: 10.1090/pspum/064/1654544.

A: By Minding's Theorem, surfaces with the same constant curvature are locally isometric, and the metric they give you is the standard model metric for constant curvature $K$.


text:
Q: Issues updating pip Using pip to install various packages I need, I get the following message in yellow text (in the terminal):
You are using pip version 7.0.3, however version 7.1.2 is available.
You should consider upgrading via the 'pip install --upgrade pip' command.

Doing exactly that, i.e. sudo pip install --upgrade pip, I get in return
Requirement already up-to-date:
pip in /opt/local/Library/Frameworks/Python.framework/
Versions/2.7/lib/python2.7/site-packages

This obviously isn't a huge error (or really anything to worry about too much), but what exactly is going on here?


text:
Q: Is it grammatically correct to begin a sentence with "Which" (in academic style)? What references, or your  specific expertise tell about the  permissibility of passages like: "We shall assume that 2x2=5. Which, of course, is not quite correct, but..."

A: Starting a sentence with which like that would be exceedingly rare.
Either
...2x2=5 — which is, of course, not quite correct
or
...2x2=5, which is, of course, not quite correct
would do.


text:
Q: What would be a good example of "sending messages to objects" within Python? I recently watched Nothing is Something by Sandi Metz, and in her talk she uses the idea of sending messages to objects and goes over how that's done in Ruby. The 4:10-7:30 section would be a good entry point where she begins on the topic (it's a building block that then permeates over half the talk).
Now, for some background: I don't have a lot of experience with writing programs in Ruby, and zero experience with smalltalk. My OO experience is somewhat limited and very stale. I also looked up send object message python in Google, and all I saw was relating to sending messages over sockets and email, which isn't quite what I had in mind.
I'm not sure how to interpret this concept in Python, or how to implement it. Any ideas? :)

Side note: She mentions her OO-views are derived from experience with smalltalk, so I'm adding that as a tag to this question.

A: Essentially "sending a message" is called in most of OO languages as calling a method. The key difference is that in dynamic languages you don't know if the object knows a method or not. So if you do var.jump() you have no idea what the var is. Maybe it's a rabbit and it can jump, or maybe it is a rock and it doesn't know how to do that (the Rock class does not implement the  jump() method). So from conceptual point of view sending a message is asking some object to do something (maybe it does not know what you are asking), while invoking a method is making that object you know do what you want.
In Smalltalk and Ruby it's really easy to send messages with another message, so that if you use 1.send(:to_s) it's the same as 1.to_s. And 1.send(:to_s) itself is a message send that is sent to 1 with parameter :to_s. So you can also expend this to 1.send(:send, :to_s).
In Python meta programming is a real pain in the ass. So if you want to do the same 1.send(:to_s) you have to use something like getattr(1, "to_s")(). Here you obtain the to_s "method" itself using getattr and invoke it with (). This is also a good example of the bad Python design. How do you do something like 1.send(:send, :to_s) in Python? In Ruby send is a method on a code Object. So you can also send it via itself. In Python getattr is an external standalone function.
If you really want to learn the concept of OO programming I suggest you to play with Smalltalk because I find it to have the best design. (also it's not influenced by C++ or other stuff because in 70s they were not around). There is a nice book Pharo by Example that teaches you to program in pharo. Also there is a work in progress version updated for the new releases of the environment.

A: The core idea is called Message passing.
In python you normally send messages by the standard notation:
obj.methodname(args)

If the method name is dynamic, you can do this:
getattr(obj, methodname)(args)

Example:
>>> getattr("  12", "strip")()
'12'

Even though we usually use the standard notation, behind the scenes there's a request for the attribute which you can observe by intercepting the call:
class Test(object):
    def __getattribute__(self, name):
        print "requesting attr:", name
        return object.__getattribute__(self, name)
    def test(self):
        print "Hello"

>>> Test().test()
requesting attr: test
Hello

A: Python uses a slightly different terminology. It is called "calling a method". But it's the same thing. (C++ calls it "calling a virtual function". Again, same difference.)
Personally, I don't like that terminology, it focuses too much on the implementation detail and loses much of the metaphoric power of the "message sending" terminology.
There are other differences with Python, some of the most important ones being:

*

*object-oriented data abstraction is achieved via convention as opposed to being a builtin language feature (e.g. Smalltalk, Ruby), or Design Pattern (Scheme, ECMAScript)

*not all subroutines are methods

The fundamental idea of OO is messaging: you send a message to an object, the object responds. Just like in real life, you have no idea what the object does with the message. All you can observe is the reply. The object might process the message itself, it might employ the help of others, it might blindly forward the message without actually doing any work itself.
Since you can't know what the object does with the message and all you can observe is the object's response, all you know about the object is its protocol (the messages it understands and how it responds to them). You don't know its implementation, you don't know its representation. That's how OO achieves Data Abstraction, Information Hiding, Data Hiding, Encapsulation.
Also, since each object decides independently how to respond to a message, you get Polymorphism.
One typical way of responding to a message, is executing a method corresponding to that message. But that is an implementation mechanism, which is why I don't like that terminology. As a metaphor, it carries none of the connotations I mentioned above.
Alan Kay has said that OO is about three things, Messaging, Data Abstraction, and Polymorphism:

OOP to me means only messaging, local retention and protection and hiding of state-process, and extreme late-binding of all things.

He later clarified that the Big Thing is Messaging:

Just a gentle reminder that I took some pains at the last OOPSLA to try to remind everyone that Smalltalk is not only NOT its syntax or the class library, it is not even about classes. I'm sorry that I long ago coined the term "objects" for this topic because it gets many people to focus on the lesser idea.
The big idea is "messaging" -- that is what the kernal of Smalltalk/Squeak is all about (and it's something that was never quite completed in our Xerox PARC phase). The Japanese have a small word -- ma -- for "that which is in between" -- perhaps the nearest English equivalent is "interstitial". The key in making great and growable systems is much more to design how its modules communicate rather than what their internal properties and behaviors should be. Think of the internet -- to live, it (a) has to allow many different kinds of ideas and realizations that are beyond any single standard and (b) to allow varying degrees of safe interoperability between these ideas.

And in fact, as I laid out above, the other two are just consequences of Messaging, in my opinion.
When Alan Kay came up with the term "Object Orientation", he was heavily inspired by what would later become the ARPANet and then the Internet: independent machines ("objects") with their own private memory ("instance variables") that communicate with each other by sending messages.
Similar points are also made in On Understanding Data Abstraction, Revisited by William R. Cook and also his Proposal for Simplified, Modern Definitions of "Object" and "Object Oriented".

Dynamic dispatch of operations is the essential characteristic of objects. It means that the operation to be invoked is a dynamic property of the object itself. Operations cannot be identified statically, and there is no way in general to exactly what operation will executed in response to a given request, except by running it. This is exactly the same as with first-class functions, which are always dynamically dispatched.

Python's object system is a bit different from other languages. Python was originally a procedural language, the object system was added later on, with the goal of making the absolut minimal amount of changes to the language as possible. The major data structure in Python were dicts (maps / hash tables), and all behavior was in functions. Even before Python's OO features, this minimalism shows itself, e.g. local and global variables are actually just keys in a dict. And so, it was natural to make objects and classes much like dicts and reuse that concept, an object is essentially a dict of values, and a class is a dict of functions. There is no separate idea of "method", rather, you have functions which take the receiver as their first argument. (In most other OO languages, the receiver is a "hidden" zeroth argument and available using a special keyword such as self, this, or me.)

A: What started as "sending a message" in Smalltalk in the early 1970s, is now more generally known as "calling a method"
Sending a message is making a polite request to an object to respond.  It will respond politely if it understands the message it receives, and has a method of responding. i.e. if the message is in the protocol of the receiver.
The protocol is the list of messages it has methods of responding to. Nowadays, we would call the protocol the receiver's API.
Alan Kay, the father of Smalltalk, felt that messaging, rather than inheritance, was the important aspect of what became known as object-oriented programming.


text:
Q: Podcast #67 - Discussion Ideas. (Unofficial) First. We had a pretty awesome thread for Podcast #66 Discussion Ideas. So please check that one out.

What would you like to see discussed on Podcast #67?
Please post only one topic per user and look down the list and vote up things you'd like to see. You can be as detailed as you wish.

Here are some of the highly voted ones from last time that still apply for #67.

How about an interview with the FogCreek dev working on StackExchange. - Nathan Koop
I would like to hear how Jeff (and his team) Get Things Done! - Decio Lira
Since you rag on PHP every week, why not invite a PHP enthusiast - jakemcgraw
Interview David Smalley and/or Paul Farnell from doctype - Jonathan Sampson

Podcast #67   Transcript wiki
<= previous

A: How about an interview with the FogCreek dev working on StackExchange
See full answer here

A: There should be a large boxing match between the people who keep fighting each other on MSO with Jeff and Joel as announcers.

A:
First Suggested
Podcast #66

After reading this post and realising that we actually have a blind-programmer tag and two confirmed blind users on StackOverflow, one with 6000+ reputation already, I would like to know how and what has been done to make the site more accessible for these users, and although a minority how Jeff and Joel feel about reaching such a unique target?
I would also like to hear their input on the What are some good computer science resources for a Blind Programmer? (Question 370976) question on StackOverflow.

A: Waffle-eating contest between Jeff and Joel. Winner gets to apologize for nauseating all listeners by furiously chewing on-air.

A: An official abdication by Jeff of his title as "King of Meta"

A: I've enjoyed most of the guests so far, and while I like the independent theme I would like to see an interview with programmer or sys admin from one of the vast masses of non-tech companies.

A: In reference to my other answer ... I am more than willing to offer my services. :)
I am a computer programmer for the county hospital, with the intriguing twist that while I single-handedly run a server and website (running the home-grown education system) used by 5k users daily - I work in the education department not in the IT department.
I also have public speaking experience and a lovely baritone, so it shouldn't be that bad. Too bad the voice-over I did for our online orientation has been taken down... we needed to do some updates and the VPs didn't want to wait for a re-record.


text:
Q: How to call a variable used in one function in another function? I have created a matlab gui and I want to use the variable magE from the function (pushbutton1) in the function (pushbutton2).
How can I call it?
magE = matrix of 244 rows and 2000 Columns

I would be grateful for any help. Thank you!

A: One way would be to declare magE as a global variable in the main script.
Then, inside each function you should also declare it as global so that it would refer to the same global variable.
e.g.
global magE
<your_code_here>

function [] = pushbutton1()
  global magE
  %%<your_code_here>
end

function [] = pushbutton2()
  global magE
  %%<your_code_here>
end

A: You should be using the hObject handle to pass data between GUI functions and callbacks, it's all quite well explained in the auto-generated comments. Example taken from MATLAB documentation:
% --- Executes just before simple_gui_tab is made visible.
function my_GUIDE_GUI_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
% varargin   command line arguments to simple_gui_tab (see VARARGIN)
% ...
% add some additional data as a new field called numberOfErrors
handles.numberOfErrors = 0;
% Save the change you made to the structure guidata(hObject,handles)

Suppose you needed to access the numberOfErrors field in a push button callback. Your callback code now looks something like this:
% --- Executes on button press in pushbutton1.
function my_GUIDE_GUI_pushbutton1_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
% ...
% No need to call guidata to obtain a structure;
% it is provided by GUIDE via the handles argument
handles.numberOfErrors = handles.numberOfErrors + 1;
% save the changes to the structure
guidata(hObject,handles)


text:
Q: Add specific message in csv pandas I am having two dataframe and I want to add specific message before each dataframe in single csv.
For eg.
df1
id val
1   5
2   6
3   7

df2
id val
8   1
4   2
3   8

I want output in csv file which I can do it using :
with open('1.csv', 'w') as f:
    df1.to_csv(f)
with open('1.csv', 'a') as f:
    df2.to_csv(f, header=True)

It will give two csv file one after another but I want to add specific message before each dataframe and output should be like:
This is df1

id val
1   5
2   6
3   7

This is df2

id val
8   1
4   2
3   8

Any help would be appriciated
Thanks a lot.

A: All you need to do is add print("This is df1.",file=f) inside your two with statements. Of course, what you will end up with is not a CSV file at all


text:
Q: How to do a bar chart to org.apache.spark.sql.DataFrame? I'am new at using Scala and Spark and i'm trying to do a bar chart using org.apache.spark.sql.DataFrame.
I found that i can use scalaFX to do bar chart. The problem is that my task has to be done with jupyternotebook and when i try to import scalafx.application.JFXapp i get "error not found : value scalafx".
I'm using spylon-kernel. This is my data:
var numberOfAppsInCategory=df.select("Category").groupBy("Category").count().orderBy("count")

Can you help me to use scalafx in the spylon-kernel or use another way to do a bar plot to org.apache.spark.sql.DataFrame? Thanks.

A: You can follow some tutorials with plotly , or use vegas or use Breeze
Vegas is compatible with Spark. I used it with Apache Toree, I didn´t test with spylon-kernel. In Toree just import the dependence like
%AddDeps org.vegas-viz vegas_2.11 {vegas-version} --transitive
implicit val render = vegas.render.ShowHTML(kernel.display.content("text/html", _))


text:
Q: A question on the Isbell-Mrowka $\Phi$-space I want to learn the  Isbell-Mrowka $\Phi$-space. Which paper or book is helpful for a beginner to learn Isbell-Mrowka $\Phi$-space. It is better that the literature  includes not only conclusitions but also detailed proofs.
Any links is also welcome. Thanks for your help.


text:
Q: Disable Pull To Refresh in Salesforce Mobile App We have developed a lightning aura component for desktop and mobile views. But we're not able to disable the Pull-To-Refresh feature, impacting the data loss. Is there any specific code to disable this feature from the mobile app?
({
    afterRender: function (component, helper) {
        alert('Hi');
        this.superAfterRender();
        var targetEl = component.find("mainContainer").getElement();
        alert('targetEl'+targetEl);
        targetEl.addEventListener(
            "touchmove",
            helper.scrollStopPropagation,
            true // we use capture!
        );
    }
})

Please help us resolve this asap as we have a timeline for production, we'll really appreciate your help

A: The pull-to-refresh is a standard feature for Salesforce mobile app and there is no official functionality to prevent this behavior.
There is also an Idea logged for this feature request.
I checked that there is an internal investigation #W-9547355 logged with the concerned salesforce product team to have this functionality implemented. Please consider upvoting the idea so that this feature implementation can be prioritized.

A: Disable Pull To Refresh is officially supported for Aura and LWC since Summer 22.

Pull-to-refresh can be disabled by firing a CustomEvent in JavaScript, which you can do from both Lightning web components and Aura components

https://help.salesforce.com/s/articleView?id=release-notes.rn_lwc_disable_pull_to_refresh_in_mobile_components.htm&type=5&release=238
For LWC, there is documentation but I could not find any for Aura.


text:
Q: change database url firebase while domain registration I have a question about firebase website hosting, does the URL of my database change when I got a domain URL, I mean my URL is 'myapp.firebaseapp.com' to the new domain I have 'www.***.com'?
as far as I know it isn't possible to change the database URL after deploying your project, I'm kind of stuck and I need to change it .

A: Adding a custom domain to Firebase Hosting does not change the URL of the Firebase Realtime Database, nor any of the other configuration data that Firebase SDKs may depend on.
When you add a custom domain that change only applies to Firebase Hosting, not to any other Firebase products. It also is an add-only operation, the existing, default URLs keep working after you add a custom domain.


text:
Q: sorting table on elements that don't belong to the table I have table with information about links. But I can sort in only by the created date and name. How can I sort on item that belongs to links?
def links_all
          per_page = 60
          Links.limit(per_page).offset( (@page - 1) * per_page ).order(@sort_column + " " +  @sort_direction).map do |s|
            {
              :name => s.name,
              :item_num => s.items.count,
              :comments_num => s.comments.count,
              :user_name => s.user ? s.user.name : "" ,
              :created_at => s.created_at.to_formatted_s(:db) ,
              :user_id => s.user ? s.user.id : "" ,
              :streme_id => s.id,
              :streme_views =>  s.views ? s.views : ""
            }
          end
        end

A: To sort by an association's column you need to join it. For example, to sort links by  user.name:
Links.joins(:user).order("users.name")


text:
Q: cycle/tween colors while element is tapped I am trying to tween / cycle the color of the background of a page while it is clicked.
When the click is lifted, the cycling stops and the background color remains at the last cycled value. When it is clicked again, the process will continue.
Check the example here to see what I am referring to when I say cycle the color http://www.javascript-fx.com/development/colorcycle/spancycle.html
While browsing for solutions I have come across some libraries like JSTween or GSAP, but with my very fragile javascript experience I failed at implementing the examples to suit my need.
Any suggestions on how to do this will be helpful, preferably without any libraries since it will aid more in my understanding of javascript.
I am not looking for exact code, a pseudocode explanation of the process will also be great.
Best,
Andrei

A: So, Tweening colors is pretty easy with TweenJS or TweenMax (or TweenLite).  I'll show this using TweenMax, mostly because the pseudocode is hard when there is no logic to pseudocode.  Assume you have a text element:

This is some text to colorize

You can tween the color of the text to red (#f00) over two seconds like this:
var textEl = document.getElementById('text');
TweenMax.to(textEl, 2, {color: '#f00'});

As far as cycling goes, you can send an onComplete handler to the tween, which will fire when the tween finishes.  This will cause it to cycle between red and black:
var textEl = document.getElementById('text');

function toRed() {
  TweenMax.to(textEl, 2, {color: '#f00', onComplete: toBlack});
}

function toBlack() {
  TweenMax.to(textEl, 2, {color: '#000', onComplete: toRed});
}

toRed();

Here is a CodePen showing this in action.
If you want to make this a bit more compact, you can cycle by flipping the colorFrom and colorTo:
function cycle(colorFrom, colorTo) {
  TweenMax.to(textEl, 2, {color: colorTo, onComplete: function() {
      cycle(colorTo, colorFrom);
  }});
}

cycle('#000', '#F00');

Doing the same thing in other tweening libraries becomes VERY similar.
Pseudocode for doing this cycle while tapped might be like this:
ON_CLICK:
  ShowCycle = !ShowCycle;
  IF ShowCycle
    TweenHandle = cycle( RED, BLACK )
  ELSE
    IF EXISTS TweenHandle
      cancelCycle( TweenHandle )
      TweenHandle = null
    END IF
  END IF


text:
Q: Add metrics automatically in aws cloud watch widgets In my application, I create a new metric with those dimensions
Collection<Dimension> dimensions =
    Arrays.asList(
      new Dimension().withName("PlacementString").withValue(form.getPlacementString()),
      new Dimension().withName("PlacementPage").withValue(String.valueOf(form.getPlacementPage())),
      new Dimension().withName("Domain").withValue(form.getDomain()));

and the Metric is
Collection<MetricDatum> metricData =
  Collections.singletonList(
    new MetricDatum()
      .withDimensions(dimensions)
      .withMetricName("XYZ")
      .withValue(1D)
      .withUnit("Count"));

In the above example, PlacementString could be something like foo or bar and the PlacementPage could be 1000 or any integer.
So, with every different combination of dimensions, a new metric will be created and published to cloudwatch
what I intend to do is to have a widget in the dashboard on cloudwatch that logs metrics that are published from the app in a dynamic way, I checked the docs, and all that I saw was that we have to pre-define the metrics and the thing is that I don't know what I'm expecting
so, is there a way to have a wildcard so that if a new metric is published from the app to add it automatically in the widget?