text:
Q: Python regex: capturing group captures/overrides subsequent matches In a regex, how can I match any number of any character (e.g., (.|\n)*) without consuming other matches that could follow? If that question isn't clear, here is my situation:
In a text file, I have a bunch of emails including headers all pasted together.
Edit: The cleaner version below has each header at the start of a newline. That may or may not be the case with my actual data. Each header component (like 'From: xxx') may be preceded by anything or nothing. In some instances, many emails and headers could all be on one line, after a bunch of other cruft. On top of that, there are other email headers I'll need to recognize that include 'From:' in them. So, I need to recognize this entire header style.
Several answers below given before my edit rely on things like ^ or tab separation, which I can't count on. They seem like they might work with a little modification, but I'm (obviously) not great with regex and I've been unable to adjust them myself. I'm sorry for omitting this before, only for several answerers to seize on it... another product of my inexperience with regexes.
Here is an ugly version - this is a string i'm actually trying to match. It contains two headers and messages to pull out.
emailsString = u"""From:\n     Lastname, Firstname\n     Sent:\n     Monday, June 24, 2013 1:48 PM\n     To:\n     Othername, Name\n     Subject:\n     RE: Center update\n    Message message message.\n    Such a lovely message\n    Take care,\n    Firstname Lastname, MS\n     Long signature\n     in this email\n   \n    E-mail:\n     email@email.com\n     Web\n     my blog\n     From:\n     Lastname, Firstname\n     Sent:\n     Monday, June 24, 2013 9:33 AM\n     To:\n     Othername, Name\n     Subject:\n     Center update\n     Importance:\n     High\n    Good Morning Name,\n    I hope this finds you doing well.\n    I wanted to inform you of some changes. The Center will be closing August 30\n     th\n     .  or September 1\n     st\n     .  I\u2019ve enjoyed my experience. """

Here is a cleaner version to show what the headers look like
From: Lastname, Firstname
Sent: Monday, July 15th, 2011, 9:36 AM
To: Othername, Name
Subject: blah
Importance: High

Message message message
second line of message

second para of message

From: Lastname, Firstname
Sent: Thursday, July 18th, 2011, 10:45 AM
To: Othername, Name
Subject: blahblah

message

...

I'm trying to regex out the information in the headers along with the message itself. I have a regex that can successfully match all the headers, but I'm struggling with the message. The problem is, a message can contain anything (or nothing). There could be multiple newlines, etc. I want to get all of this, but I still want to split up the emails. My attempt (note that the 'Important' part of the header is optional):
for hit in re.finditer(r'[\s\n]*From:[\s\n]*(?P<from>.*)[\s\n]*Sent:[\s\n]*(?P<date>.*)[\s\n]*To:[\s\n]*(?P<to>.*)[\s\n]*Subject:[\s\n]*(?P<subject>.*)[\s\n]*(?:Importance:)?[\s\n]*.*[\s\n]*(?P<message>(.|\n)*)', allEmailsString):
    print "from: " + hit.group("from")
    print "to: " + hit.group("to")
    print "date: " + hit.group("date")
    print "subject: " + hit.group("subject")
    print "message: " + hit.group("message")

The problem is, the message group is grabbing everything. So, I get the first email header's from/to/etc correctly, and then see a message containing that emails message, along with all following email headers and messages. I need to grab 'everything up until the next email header/regex match or until the end of the string'.
I've already got a workaround - I can get rid of the message capturing group and grab only the headers. Then, iterate through the match objects and slice the string based on their start/end. E.g., message1 is from match1.end up to match2.start.
So, I'm asking...

*

*Is there a way I can do this with capturing groups in my regex instead?

*Is there a better workaround?

A: A regex can be used to extract chunks of a text only if the text is composed of variable parts and stable portions (or at least portions having a stable variability...)
In the following regex pattern, I did some suppositions on the "stable" portions to raise the amount of them, making it possible to discriminate the emails and to extract the desired chunks in texts that seem to have few sure anchors:

*

*I supposed that in the 'sent' part, there is always a name of one of the week's day

*I supposed that if the line 'Importance' exist, there's only one word to describe this importance, then [^ \t\r\n]+

*I supposed that the subject description can't be on several lines, then [^\r\n]+
If the amount of stable portion in a text is too low, that is to say the structure of the text is too loose, using a regex begins impossible.
The pattern [ \t\r\n]*(?P<from>.*?[^ \t\r\n])[ \t\r\n]*' has a strip effect on the captured group.
Then, if several blank lines constitute the message, the result of the match says that the message is ''
The presence of \Z is necessary to catch the mast email if there are no other lines after the last message, as in my text example.
import re

emailsString = (u'     From:\n'
                '     Lastname, Firstname\n'
                '     Sent:\n'
                '     Monday, June 24, 2013 1:48 PM\n'
                '     To:\n'
                '     Othername, Name\n'
                '     Subject:\n'
                '     RE: Center update\n'
                '    Message message message.\n'
                '    Such a lovely message\n'
                '    Take care,\n'
                '    Firstname Lastname, MS\n'
                '     Long signature\n'
                '     in this email\n'
                '   \n'
                '    E-mail:\n'
                '     email@email.com\n'
                '     Web\n'
                '     my blog\n'
                '     From:\n'
                '     Lastname, Firstname\n'
                '     Sent:\n'
                '     Monday, June 24, 2013 9:33 AM\n'
                '     To:\n'
                '     Othername, Name\n'
                '     Subject:\n'
                '     Center update\n'
                '     Importance:\n'
                '     High\n'
                '    Good Morning Name,\n'
                '    I hope this finds you doing well.\n'
                '    I wanted to inform you of some changes. The Center will be closing August 30\n'
                '     th\n'
                '     .  or September 1\n'
                '     st\n'
                '     .  I\u2019ve enjoyed my experience. ')

allEmailsString = '''
From: FirstLastname, FirstFirstname
Sent: Monday, July 15th, 2011, 9:36 AM
To: TheOne
Subject: blah
Importance: High

Message message message
second line of message

second para of message

From: MidLastname, MidFirstname
Sent: Thursday, July 18th, 2011, 10:45 AM
To: TWOTWO
Subject: once upon

From: LastLastname, LastFirstname
Sent: Saturday, July 20th, 2011, 12:51 AM
To: Mr Three
Subject: blobloblo

Nothing to say. '''

dispat = ("*  from: {from}\n"
          "*  to: {to}\n"
          "*  date: {date}\n"
          "*  subject: {subject}\n"
          "** message (beginning on next line):\n{message}\n"
          "-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-")

regx = re.compile('From:[ \t\r\n]*(?P<from>.*?[^ \t\r\n])'
                  '[ \t\r\n]*'
                  'Sent:[ \t\r\n]*'
                  '(?P<date>.*?(?:Mon|Tues|Wednes|Thurs|Fri|Satur|Sun)day.*?[^ \t\r\n])'
                  '[ \t\r\n]*'
                  'To:[ \t\r\n]*(?P<to>.*?[^ \t\r\n])'
                  '[ \t\r\n]*'
                  'Subject:[ \t\r\n]*(?P<subject>[^\r\n]+)'
                  '[ \t\r\n]*'
                  '(?:Importance:[ \t\r\n]*(?P<importance>[^ \t\r\n]+))?'
                  '[ \t\r\n]*'
                  '(?P<message>.*?)'
                  '(?=[ \t\r\n]*From:.*?'
                  'Sent:.*?(?:Mon|Tues|Wednes|Thurs|Fri|Satur|Sun)day.*?'
                  'To.*?Subject:|\Z)',
                  re.DOTALL)

for s in (emailsString,allEmailsString):
    print ''.join(dispat.format(**d)
                  for d in (ma.groupdict('') for ma in regx.finditer(s)))
    print '\n#######################################\n'

result
*  from: Lastname, Firstname
*  to: Othername, Name
*  date: Monday, June 24, 2013 1:48 PM
*  subject: RE: Center update
** message (beginning on next line):
Message message message.
    Such a lovely message
    Take care,
    Firstname Lastname, MS
     Long signature
     in this email

    E-mail:
     email@email.com
     Web
     my blog
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-*  from: Lastname, Firstname
*  to: Othername, Name
*  date: Monday, June 24, 2013 9:33 AM
*  subject: Center update
** message (beginning on next line):
Good Morning Name,
    I hope this finds you doing well.
    I wanted to inform you of some changes. The Center will be closing August 30
     th
     .  or September 1
     st
     .  I\u2019ve enjoyed my experience.
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-

#######################################

*  from: FirstLastname, FirstFirstname
*  to: TheOne
*  date: Monday, July 15th, 2011, 9:36 AM
*  subject: blah
** message (beginning on next line):
Message message message
second line of message

second para of message
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-*  from: MidLastname, MidFirstname
*  to: TWOTWO
*  date: Thursday, July 18th, 2011, 10:45 AM
*  subject: once upon
** message (beginning on next line):

-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-*  from: LastLastname, LastFirstname
*  to: Mr Three
*  date: Saturday, July 20th, 2011, 12:51 AM
*  subject: blobloblo
** message (beginning on next line):
Nothing to say.
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-

#######################################

A: I'd just divide (split) and conquer (re.match):
import re

# `data` is your text file
delimiter = r'(^|\n)From:'
capturer = re.compile(r'From:[\n\s]*(?P<from>.*)[\n\s]*'
                      r'Sent:[\n\s]*(?P<date>.*)[\n\s]*'
                      r'To:[\n\s]*(?P<to>.*)[\n\s]*'
                      r'Subject:[\n\s]*(?P<subject>.*)[\n\s]*'
                      r'(?:Importance:)?[\n\s]*.*[\n\s]*'
                      r'(?P<message>(\n|.)*)')

raw_emails = ['From:' + d for d in re.split(delimiter, data) if d.strip()]
emails = []
for raw_email in raw_emails:
    parts = capturer.match(raw_email)
    emails.append(parts.groupdict())

For your example data this output:
[{'date': 'Monday, July 15th, 2011, 9:36 AM',
  'from': 'Lastname, Firstname',
  'message': 'Message message message\nsecond line of message\n\nsecond para of message\n',
  'subject': 'blah',
  'to': 'Othername, Name'},
 {'date': 'Thursday, July 18th, 2011, 10:45 AM',
  'from': 'Lastname, Firstname',
  'message': '...\n',
  'subject': 'blahblah',
  'to': 'Othername, Name'}]

A: This might be painfull to look at. Its expanded for clarity.
Use Multi-Line mode, and No-DotAll.
@mobabo - Edit to this after your first comment.
There must be a clear delineation of your keywords, and there is. Your statement of
I can't count on things like '^From' to work shows you didn't look at the previous
regex, and that part is the same in this one. ^[^\S\n]*From: is not the same as ^From
Additionally, there is no clear delineation between Subject and Message
or Importance and Message. If 'Importance' is part of the email, the Subject has an end point.
I've made a regex that handles your dirty and clean emails, at the bottom is a Perl
program that exercises it. The output is included. See if that can solve your issues
(see below).
Unfortunately, this is the best you can hope for.
Good Luck Sir!
(A Note - if Python had recursion, this regex would be 1/4 th this size)
 # Compressed
 # -------------------
 #  ^[^\S\n]*From:\s*(?P<from>(?:(?!\s*^[^\S\n]*(?:From|Sent|To|Subject|Importance):)[\S\s])*)(?:\s*^[^\S\n]*Sent:\s*(?P<sent>(?:(?!\s*^[^\S\n]*(?:From|Sent|To|Subject|Importance):)[\S\s])*))?(?:\s*^[^\S\n]*To:\s*(?P<to>(?:(?!\s*^[^\S\n]*(?:From|Sent|To|Subject|Importance):)[\S\s])*))?(?:\s*^[^\S\n]*Subject:\s*(?P<subject>(?:(?!\s*^[^\S\n]*(?:(?:From|Sent|To|Subject|Importance)):)[\S\s])*)(?:\s*^[^\S\n]*Importance:\s*(?P<importance>(?:(?!\s*^[^\S\n]*(?:From|Sent|To|Subject|Importance):)[\S\s])*))?)?

 # Expanded
 # -------------------
 #

 ^ [^\S\n]* From: \s*
 (?P<from>
      (?:
           (?!
                \s* ^ [^\S\n]*
                (?: From | Sent | To | Subject | Importance )
                :
           )
           [\S\s]
      )*
 )

 (?:
      \s* ^ [^\S\n]* Sent: \s*
      (?P<sent>
           (?:
                (?!
                     \s* ^ [^\S\n]*
                     (?: From | Sent | To | Subject | Importance )
                     :
                )
                [\S\s]
           )*
      )
 )?

 (?:
      \s* ^ [^\S\n]* To: \s*
      (?P<to>
           (?:
                (?!
                     \s* ^ [^\S\n]*
                     (?: From | Sent | To | Subject | Importance )
                     :
                )
                [\S\s]
           )*
      )
 )?

 (?:
      \s* ^ [^\S\n]* Subject: \s*
      (?P<subject>
           (?:
                (?!
                     \s* ^ [^\S\n]*
                     (?:
                          (?: From | Sent | To | Subject | Importance )
                     )
                     :
                )
                [\S\s]
           )*
      )

      (?:
           \s* ^ [^\S\n]* Importance: \s*
           (?P<importance>
                (?:
                     (?!
                          \s* ^ [^\S\n]*
                          (?: From | Sent | To | Subject | Importance )
                          :
                     )
                     [\S\s]
                )*
           )
      )?
 )?

 # // Output from Perl sample code (below)
 # //
 # // ======================
 # // From:
 # //         Lastname, Firstname
 # // Sent:
 # //         Monday, July 15th, 2011, 9:36 AM
 # // To:
 # //         Othername, Name
 # // Subject:
 # //         blah
 # // Importance/Message:
 # //         High
 # //
 # // Message message message
 # // second line of message
 # //
 # // second para of message
 # //
 # //
 # // ======================
 # // From:
 # //         Lastname, Firstname
 # // Sent:
 # //         Thursday, July 18th, 2011, 10:45 AM
 # // To:
 # //         Othername, Name
 # // Subject/Message:
 # //         blahblah
 # //
 # // message
 # //
 # //
 # // ======================
 # // From:
 # //         Lastname, Firstname
 # // Sent:
 # //         Monday, June 24, 2013 1:48 PM
 # // To:
 # //         Othername, Name
 # // Subject/Message:
 # //         RE: Center update
 # //     Message message message.
 # //     Such a lovely message
 # //     Take care,
 # //     Firstname Lastname, MS
 # //      Long signature
 # //      in this email
 # //
 # //     E-mail:
 # //      email@email.com
 # //      Web
 # //      my blog
 # //
 # //
 # // ======================
 # // From:
 # //         Lastname, Firstname
 # // Sent:
 # //         Monday, June 24, 2013 9:33 AM
 # // To:
 # //         Othername, Name
 # // Subject:
 # //         Center update
 # // Importance/Message:
 # //         High
 # //     Good Morning Name,
 # //     I hope this finds you doing well.
 # //     I wanted to inform you of some changes. The Center will be closing August 30
 # //
 # //      th
 # //      .  or September 1
 # //      st
 # //      .  I've enjoyed my experience.
 # //

 # ------------------------------------------------------------
 # # Perl sample code
 # use strict;
 # use warnings;
 #
 # $/ = undef;
 #
 # my $str = <DATA>;
 #
 #
 #
 # while ( $str =~ /
 #     ^[^\S\n]*From:\s*(?P<from>(?:(?!\s*^[^\S\n]*(?:From|Sent|To|Subject|Importance):)[\S\s])*)(?:\s*^[^\S\n]*Sent:\s*(?P<sent>(?:(?!\s*^[^\S\n]*(?:From|Sent|To|Subject|Importance):)[\S\s])*))?(?:\s*^[^\S\n]*To:\s*(?P<to>(?:(?!\s*^[^\S\n]*(?:From|Sent|To|Subject|Importance):)[\S\s])*))?(?:\s*^[^\S\n]*Subject:\s*(?P<subject>(?:(?!\s*^[^\S\n]*(?:(?:From|Sent|To|Subject|Importance)):)[\S\s])*)(?:\s*^[^\S\n]*Importance:\s*(?P<importance>(?:(?!\s*^[^\S\n]*(?:From|Sent|To|Subject|Importance):)[\S\s])*))?)?
 # /xmg)
 #
 # {
 #  print "\n\n======================\n";
 #  print "From: \n\t$+{from}\n";
 #  if (defined $+{sent})
 #  {
 #      print "Sent: \n\t$+{sent}\n";
 #  }
 #  if (defined $+{to})
 #  {
 #      print "To: \n\t$+{to}\n";
 #  }
 #  if (defined $+{importance})
 #  {
 #      print "Subject: \n\t$+{subject}\n";
 #      print "Importance/Message: \n\t$+{importance}\n";
 #  }
 #  elsif (defined $+{subject})
 #  {
 #      print "Subject/Message: \n\t$+{subject}\n";
 #  }
 # }
 #
 #
 # __DATA__
 #
 # From: Lastname, Firstname
 # Sent: Monday, July 15th, 2011, 9:36 AM
 # To: Othername, Name
 # Subject: blah
 # Importance: High
 #
 # Message message message
 # second line of message
 #
 # second para of message
 #
 # From: Lastname, Firstname
 # Sent: Thursday, July 18th, 2011, 10:45 AM
 # To: Othername, Name
 # Subject: blahblah
 #
 # message
 #
 #
 #
 #
 #
 # From:
 #      Lastname, Firstname
 #      Sent:
 #      Monday, June 24, 2013 1:48 PM
 #      To:
 #      Othername, Name
 #      Subject:
 #      RE: Center update
 #     Message message message.
 #     Such a lovely message
 #     Take care,
 #     Firstname Lastname, MS
 #      Long signature
 #      in this email
 #
 #     E-mail:
 #      email@email.com
 #      Web
 #      my blog
 #      From:
 #      Lastname, Firstname
 #      Sent:
 #      Monday, June 24, 2013 9:33 AM
 #      To:
 #      Othername, Name
 #      Subject:
 #      Center update
 #      Importance:
 #      High
 #     Good Morning Name,
 #     I hope this finds you doing well.
 #     I wanted to inform you of some changes. The Center will be closing August 30
 #      th
 #      .  or September 1
 #      st
 #      .  I've enjoyed my experience.
 #
 #


text:
Q: What are IntelliJ IDEA sbt imported 'xxx-build' modules for? When importing a multi-project build.sbt from intelliJ IDEA 2016.1.2 using the native sbt import function, it prompts me which modules I would like to include. The list includes the subprojects/subdirectories in the directory structure I would expect e.g. 'aaa', 'bbb', 'ccc', but then it also offers to import 'aaa-build', 'bbb-build', 'ccc-build', which I have not created.
Ignoring/deselecting the '-build' modules doesn't appear to have any adverse effects.
Can somebody tell me what the purpose of those extra modules is? Just curious.
The directory structure looks something like this:
root/bulid.sbt
root/project
root/aaa
root/aaa/build.sbt
root/aaa/src/main/scala
root/aaa/src/test/scala
root/bbb
root/bbb/build.sbt
...

A: A newer to scala,if something gets wrong with my answer, I'll improve it.
Those *-build ,they are project subfold in your projects,when you compile these projects with sbt, sbt will read it's peoperties and plugins from peoject fold. It's just like your config which has been compiled.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Separate link in address line for single page different content If I have two links in index.php  page:

with different data to show on the same page:
function content1() {
   text.innerHTML = "text 1";
   ...
}

function content2() {
   text.innerHTML = "text 2";
   ...
}

How to attach separate link name in browser address line and its different content  function call with using of this links in single page. If I'm not loading some separate page.html,  but get same result as with different pages:
www.mysite.org/cont1

www.mysite.org/cont2

A: You can use URLSearchParams
var urlParams = new URLSearchParams(window.location.search);
if (urlParams.get('content') == 'cont1') {
    content1();
}
else if (urlParams.get('content') == 'cont2') {
    content2();
}

You'll need to link like this:
www.mysite.org/?content=cont1


text:
Q: pass the foreign key of a model in the url I've two different models with the names TvShow and Episode but episode is connected with tvshow through a foreign key
tvshow = models.ForeignKey(Media, on_delete=models.CASCADE)

so I was trying to add it to urls of episode model like this
path('<str:tvshow_title>/<int:season_number>/<int:episode_number>', views.episode, name='episode')

but the views.py of Episode have a hard time defining it:
def episode(request, tvshow_title, season_number, episode_number):

    tvshow = Media.objects.filter(media_type='TV', title=tvshow_title).first()

    episode = get_object_or_404(
        Episode, tvshow=tvshow, season_number=season_number, episode_number=episode_number)

    context = {
        'episode': episode
    }

    return render(request, 'media/episode.html', context)

I'm not sure what the problem is I'm not sure if this is how you pass more than one parameter to get_object_or_404.

A: Follow Django documentation, you can use the filter directly in get_object_or_404
episode = get_object_or_404(
    Episode, tvshow__title=tvshow_title, tvshow__media_type='TV', season_number=season_number, episode_number=episode_number)


text:
Q: Permission Error when installing pygame on python 3.5 When I install pygame-1.9.2a0-cp35-none-win32.whl for python 3.5 I get a permission error:
PermissionError: [WinError 5] Access is denied

and then it says the error is in a site package of pygame.

A: Fixed it by reinstalling python outside the program files.


text:
Q: Kuberenetes importing issue Python 3.6.8 on CentOS 7 I have been banging my head on the wall trying to get the following import to work.
from kubernetes import config, client
I pip installed kubernetes==11.0.0
It works perfectly fine on https://repl.it/languages/python3 but getting import error on my CentOS 7 box.
from kubernetes import config, watch, client
ImportError: cannot import name 'config'
I have been using Python for 7-8 years, I am not sure what I am missing.
Thanks!

A: Found my issue, file name was kubernetes.py. Renamed it and solved issue :|.

A: It seems that when you name your file kubernetes.py, the import is attempted from that particular file than from the library


text:
Q: The download /back-up of Google scripts (.gs files) bounded to Google Spreadsheets I have google spreadsheets having Google scripts (.gs files) bounded to it. When I download them from Google Drive, only csv or xlsx get downloaded. The associated scripts files (.gs files) are not downloaded. However the standalone scripts can be downloaded from Google Drive. How can the back up of Google scripts (.gs files) bounded to Google Spreadsheets can be taken? How can they be downloaded?

A: You can back up file-bound scripts locally on your machine using the command line tools for Google Apps Script (clasp).
The clasp is an open-source tool, provided by Google, to interact with Google App script projects. It may be used, for instance, to develop websites or Google Docs plugins locally instead of using the web environment. You can use clasp to download or to deploy projects to the Google App Scritps.
You may check a tutorial in a the Google codelab for Clasp.

Making a copy of a Google Apps Script project

*

*To use clasp, you must install first Node-js. You can download an installer for Windows or Linux from the official website

*

*Node.js download page

*One installed Node.js, you must install clasp. Using a command line terminal, you may execute npm to perform the installation
npm install -g @google/clasp

*After installing clasp, you can download the project files using the script id. You can go to Google Script Editor and copy the Script Id under File -> Project properties.

*On your computer, create a folder for the project and navigate into the newly created folder. You can use a File Explorer to create the folder. Using Windows, Linux or Mac, you can create the folder using the command line terminal and the following commands:
mkdir gas-project
cd gas-project

*Finally, to make the copy, you must execute the following command, where 'scriptid' is the id you copied from Project properties.
clasp clone <scriptid>

Once you have a local copy of the files, you can run clasp pull to update the code locally or clasp push to send any locally-made changes to the server.


text:
Q: Create manual mock for @material-ui withStyles in React with Jest I am trying to create manual mocks for the @material-ui/core/styles module, which exports the HOC called withStyles.
Using the inline mock with jest.mock works perfectly, but when I try to move this logic into sharable __mocks__ folder, it does not work anymore.
I removed from the file being tested all the unecessary code, just keeping the two lines creating the issues:
import { withStyles } from '@material-ui/core/styles';

console.log('loaded styles:', withStyles);

export default 'hello';

And the test simplified as well, just to see if the mock is working, is the following:
import test from '../test';
console.log(test);

What I have tried is to create a __mocks__ folder in the root of the project, where I have the node_modules folder.
There I created a first folder called @material-ui and inside it another folder called core.
Inside this folder I have a file called styles.js with the following code:
export const withStyles = 'hello world';

So the structure looks like:
- __mocks__
  - @material-ui
    - core
      - styles.js
- node_modules

This is the code which works, with the mock defined inside the same testing file:
jest.mock('@material-ui/core/styles', () => ({
  withStyles: () => Component => props => (
    <Component
      classes=""
      {...props}
    />
  ),
}));

What is happening with the __mocks__ folder is that, if I do not call any
jest.mock('@material-ui/core/styles');

inside my test file, it uses the real withStyles, so the real module.
No mock at all is being used.
If I use the:
jest.mock('@material-ui/core/styles');

It uses an automatic mock autogenerated by jest (or it looks so), skipping the one I define above.
Just a note about packages, I used CRA for bootstrapping the app and the jest version I currently have is the 20, with the react-scripts version 1.0.17
Thanks to you all for you the help!

A: Here is how you should use manual mocking in __mocks__/@material-ui/core/styles.js:
// Grab the original exports
import * as Styles from '@material-ui/core/styles';

const mockWithStyles = () => {
  console.log('withStyles being mocked'); // this shows that it works
  /**
   * Note: if you want to mock this return value to be
   * different within a test suite then use
   * the pattern defined here:
   * https://jestjs.io/docs/en/manual-mocks
   */

  return () => {}; // your mock function (adjust as needed)
  // you can also return the same implementation on certain conditions
  // return Styles.makeStyles;
};

module.exports = { ...Styles, withStyles: mockWithStyles };

Here is how I manual mock makeStyles:
// Grab the original exports
// eslint-disable-next-line import/no-extraneous-dependencies
import * as Styles from '@material-ui/core/styles';
import createMuiTheme from '@material-ui/core/styles/createMuiTheme';
import options from '../../../src/themes/options';

const mockMakeStyles = func => {
  /**
   * Note: if you want to mock this return value to be
   * different within a test suite then use
   * the pattern defined here:
   * https://jestjs.io/docs/en/manual-mocks
   */

  /**
   * Work around because Shallow rendering does not
   * Hook context and some other hook features.
   * `makeStyles` accept a function as argument (func)
   * and that function accept a theme as argument
   * so we can take that same function, passing it as
   * parameter to the original makeStyles and
   * binding it with our custom theme
   */
  const theme = createMuiTheme(options);
  return Styles.makeStyles(func.bind(null, theme));
};

module.exports = { ...Styles, makeStyles: mockMakeStyles };

And makeStyles result uses React.useContext, so we have to avoid mocking useContext for makeStyles. Either use mockImplementationOnce if you use React.useContext(...) first in you component, or just filter it out in your test code as:
jest.spyOn(React, 'useContext').mockImplementation(context => {
  console.log(context);
  // only stub the response if
  if (context.displayName === 'MyAppContext') {
    return {
      auth: {},
      lang: 'en',
      snackbar: () => {},
    };
  }

  const ActualReact = jest.requireActual('react');
  return ActualReact.useContext(context);
});

And on your createContext() call, probably in a store.js, add a displayName (standard), or any other custom property to Identify your context:
const store = React.createContext(initialState);
store.displayName = 'MyAppContext';

The makeStyles context displayName will appear as StylesContext and ThemeContext and their implementation will remain untouched to avoid error.
This fixed all kind of mocking problem with makeStyles. But I haven't use withStyles to know its structure deeply, but similar logic should be applicable.

A: I created the file src/__mocks__/@material-ui/core/styles.jsx in my project and inside I put:
import * as Styles from '@material-ui/core/styles';
import React from 'react';

const withStyles = () => Component => props => <Component classes={{}} {...props} />;

module.exports = { ...Styles, withStyles };


text:
Q: C# Color coding for windows 8.1 (tablet) in visual studio 2013 May I know how should I write the color code for

grid-background / textblock-foreground

if(Condition ==true)
{
   gridName.Backgroud = //How to set color here
}

in visual studio 2013? (For Windows 8.1 tablet (surfaceRT) )

A: you can try these options
if(Contition == true)
{
    // you can try this
    grid.Background = new SolidColorBurush(Colors.Green);

    // you can try this too
    grid.Background =  new SolidColorBrush(Color.FromArgb(255, 0, 255, 0);
}

If you having Error that Colors or Color does not exists or you are missing some assembly.
so just right Click on Colors/Color and choose Resolve Option. it is all done :)
Hope this helps :)

A: For ex
if(something == true)
{
   grid.Background = new SolidColorBurush(Windows.UI.Colors.Red);
}


text:
Q: Linux chmod command error: chmod: invalid mode: I want assign the privilege to directory app, my command as below:
sudo chmod -R hduser /app

hduser is username in Linux, however, I got error message:

chmod: invalid mode: `hduser'

anything need update?

A: I think the command you're searching for is chown.
http://linuxcommand.org/man_pages/chown1.html
Enter somethink like :
sudo chown -R username[:groupname] /app


text:
Q: Erlang demo app? I'm in a group at work reading Seven Languages in Seven Weeks by Bruce A. Tate and we are having a presentation on one language each week.  I'm partially responsible for Erlang in 2 weeks and am looking for a good demo app that would show off the strengths of Erlang.  I plan to go through the programming exercises in the book, but am looking for that little, interesting app for the demo.  I will need to be able to write it in just a few hours once I become more familiar with the language.  Any suggestions are welcome.

A: I ran a neat demo at Dyncon in Stockholm last weekend: https://gist.github.com/854389
It's a "virus" that jumps between connected nodes (which the attendees start on their machines and connect to the presenter's already "infected" node).
It demos distribution very nicely. To complement, I started up an Erlang shell and spawned over a million idle processes (that waited in a receive loop), printing every thousand process number to the shell, until my laptop ran out of memory. Very nice effect. :-)

A: If you want you can take a look at eirc. It is more of an IRC library but it is a compliant OTP app. Easy to understand and to use and build on (example in the README file) so I think it would be good for a first project.
You can find it here: https://github.com/mazenharake/eirc

A: I ended up writing an answer to Project Euler's problem 22 in order to show some of the list functions, then I came up with a concurrency app on my own which was pretty well received.  Thanks Adam and Mazen for the thoughts.


text:
Q: Prove or disprove there is a sequence of polynomials which converge uniformly to $z \mapsto (\overline{z})^2$. I'm studying for my complex qual and am trying to go through a lot of questions quickly.  Let $g(z) = (\overline{z})^2$.  The problem is to prove or disprove the existence of a sequence of polynomials which converge uniformly to $g$ on the unit circle $|z| = 1$.
On the unit circle, $g$ is just the restriction of the function $h(z) = \frac{1}{z^2}$.  Now $h$ is holomorphic on $\mathbb{C} \setminus \{0\}$.  For any point $c \neq 0$, we can represent $h$ as a power series at $c$ with radius of convergence $|c|$, uniformly convergent on any disc of radius  $< |c|$.  So I can get a sequence of polynomials which converge to $g$ uniformly on just up to half the disc (by taking $c$ very far away from $0$).  Not sure what I should do now.
It would be neat to center a power series at infinity somehow, so I could include the whole circle in the area of uniform convergence, but exclude the origin, but I'm not really familiar with complex analysis on $\mathbb{C} \cup \{\infty\}$.

A: Hint: What is $\int_C z g(z)\; dz$?


text:
Q: Google Apps Script to Truncate Text with TimeDrivenTigger I'm trying to create a script that limits text strings in a google sheets.  The script that I am using works when I manually add text to the sheet, but when I import data using Zapier, the script does not run.
I was trying to set up a Time Driven Trigger to run the script every hour, but have not had success.
This is what I'm using:
function createTimeDrivenTriggers() {
  // Trigger every 1 hours.
  ScriptApp.newTrigger('myFunction')
  .timeBased()
  .everyHours(1)
  .create();

  function MyFunction(e) {
    var limit = 4;
    if(e.value.length > limit) {
      e.range.setValue(e.value.substring(0, limit));
    }
  }
}

A: You were initially calling MyFunction with an onEdit() trigger, which passes an Event Object to the function. This is the parameter e that you get the value of. A time-driven trigger doesn't pass in any arguments, so you will have to re-write MyFunction a little, to find the range you're interested in "from scratch."
Also, your trigger calls myFunction (lowercase), while the function is defined as MyFunction (uppercase), which could be an issue.


text:
Q: Issue related to the rect data in SVG I'm currently writing a parser for SVG for a project I'm working on. I'm using inkscape as the editor

And the plain SVG I get from inkscape is this
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!-- Created with Inkscape (http://www.inkscape.org/) -->

<svg
   width="256"
   height="256"
   viewBox="0 0 25.6 25.6"
   version="1.1"
   id="svg5"
   xmlns="http://www.w3.org/2000/svg"
   xmlns:svg="http://www.w3.org/2000/svg">
  <defs
     id="defs2" />
  <rect
     style="fill:#800080;stroke-width:0.0566834"
     id="rect122"
     width="10.274419"
     height="9.6836576"
     x="10.734594"
     y="-6.7066712"
     transform="matrix(0.84492681,0.53488194,-0.51677089,0.85612373,0,0)" />
</svg>

My question is, what does the x and y of rect tag mean exactly in this context?
I'm also confused as to why the y-coordinate is negative?

A: Animation showing the original and transformed positions of the rectangle.

svg {
  border: solid 1px grey;
  background: linen;
  margin: 100px 0 0 0;
  overflow: visible;
}

rect {
   animation: move 3s linear infinite;
}

@keyframes move {
  0% { transform: matrix(1, 0, 0, 1, 0, 0); }
  50% { transform: matrix(0.84492681,0.53488194,-0.51677089,0.85612373,0,0); }
  100% { transform: matrix(1, 0, 0, 1, 0, 0); }
}
<svg
   width="256"
   height="256"
   viewBox="0 0 25.6 25.6"
   version="1.1"
   id="svg5"
   xmlns="http://www.w3.org/2000/svg"
   xmlns:svg="http://www.w3.org/2000/svg">
  <defs
     id="defs2" />
  <rect
     style="fill:#800080;stroke-width:0.0566834"
     id="rect122"
     width="10.274419"
     height="9.6836576"
     x="10.734594"
     y="-6.7066712"
     transform="matrix(0.84492681,0.53488194,-0.51677089,0.85612373,0,0)" />
</svg>


text:
Q: Adding VPI to project with a lot of dependencies causes error on pre-3.0 devices  I recently switched from eclipse to intellij, it has been a great experience so far I am really loving it. However, I have run into a strange issue that I have been hitting my head against the wall with. I am trying to use ViewPagerIndicator, ActionBarSherlock, RoboSherlock, and RoboGuice as well as some other common frameworks in my application. It all works fine until I add VPI.
Basically, when adding the ViewPagerIndicator dependency to my project it breaks the application for pre 3.0 devices (runs fine on 3.0+).
The error is rather confusing because it seems to be something wrong with an ABS compatible theme not being picked up when the VPI apklib is present (please note that I am using an ABS compatible theme in my manifest).
>09-18 10:33:15.986: ERROR/COM.IRIE.TASTEBUD/ObserverMethodListener.java:34(509): main java.lang.reflect.InvocationTargetException
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:507)
        at roboguice.event.eventListener.ObserverMethodListener.onEvent(ObserverMethodListener.java:32)
        at roboguice.event.EventManager.fire(EventManager.java:130)
        at com.github.rtyley.android.sherlock.roboguice.activity.RoboSherlockActivity.onCreate(RoboSherlockActivity.java:63)
        at com.irie.tastebud.view.activity.MainActivity.onCreate(MainActivity.java:38)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)

When I look deeper at the trace I see the below (even though I am using a sherlock theme):

   Caused by: java.lang.IllegalStateException: You must use Theme.Sherlock, Theme.Sherlock.Light, Theme.Sherlock.Light.DarkActionBar, or a derivative.
    at com.actionbarsherlock.internal.ActionBarSherlockCompat.generateLayout(ActionBarSherlockCompat.java:1007)
    at com.actionbarsherlock.internal.ActionBarSherlockCompat.installDecor(ActionBarSherlockCompat.java:919)
    at com.actionbarsherlock.internal.ActionBarSherlockCompat.setContentView(ActionBarSherlockCompat.java:853)
    at com.actionbarsherlock.app.SherlockActivity.setContentView(SherlockActivity.java:218)
    at roboguice.inject.ContentViewListener.optionallySetContentView(ContentViewListener.java:21)
    ... 19 more**

See full exception stack trace and activity/manifest/pom.xml code  @ https://gist.github.com/3743646 .
Once again - this only happens on pre-3.0 devices when adding the VPI project as a maven dependency. If I remove VPI - the app runs fine on 2.2+ devices.
My Pom.xml is almost exactly like the Android Bootstrap application which works fine on 2.2+ as far as I know.
My guess is that I have some kind of dependency configuration issue on my end. I am pretty green with maven and intellij so it has been quite difficult to trouble shoot.
I am not sure if anyone else has seen this behavior, or if I am making a rookie mistake. Any help is appreciated - if I solve the issue, I will update this question with the answer.
Thanks to everyone in advance and sorry if I broke any stackoverflow etiquette with this post.
EDIT: Found potential related issue @ http://youtrack.jetbrains.com/issue/IDEA-90719

A: So instead of using a default android build configuration, I used the android maven plugin and did a mvn android:deploy-dependencies and android:run, and the problem is gone.
Before I was just using the default android build configuration for intellij, which now looking back does not look like it was the right approach considering I am using the android maven plugin to manage my dependencies in the first place.
Hope this helps someone.
P.S. intellij-idea rocks!

A: I found another workaround for this issue that works much faster. In Android facet config change resource processing from "Run 'process-resources' Maven task before Make" to "Compile resources by IDE". See screenshot in attachment. After this change all works fine and fast on all android versions


text:
Q: How to append an element in a list a declared in global , while list.append() statement is inside a function corrected code for query , both var and result are global variables which are required to be accessed inside a function
import copy
result = []
var = 'second list empty'

def permute(arr1,arr2):
    if(len(arr2) <= 0):
        global result.append(var)
        return
    stx = "".join(arr1)
    for x in arr2:
       var = stx + x
       arr3 = copy.deepcopy(arr2)
       arr3.remove(x)
       permute(var.split(),arr3)

A: Remove the word global from your append statement.
You have:
global result.append(var)

It should be:
result.append(var)

You only need the global keyword when you`re reassigning a global variable inside the function, and you use it just to declare the variable global; you can't do anything else with it in that statement.


text:
Q: TypeError: 'module' object is not callable ( when importing selenium ) i have problem when running this code :
>>> from selenium import webdriver
>>> driver = webdriver.firefox()
Traceback (most recent call last):
File "<pyshell#19>", line 1, in <module>
driver = webdriver.firefox()
TypeError: 'module' object is not callable

i have searched for the problem and i got some results. but unfortunately , they didn't work. So , how can i solve this?
thanks.

A: the same goes for other browsers!
e.g.
webdriver.chrome Vs. webdriver.Chrome

(its even harder to notice this!)
thanks so much for the help! ;)

A: You have made a typo.
webdriver.Firefox()

Note the capital F.

A: Another way is:
from selenium.webdriver import Chrome.

driver = Chrome()

When typing "Chrome" Note the capital C.
You probably gonna need to specify the executable_path for chromedriver.exe:
driver = Chrome(executable_path="path_in_here")

A: This error message...
TypeError: 'module' object is not callable

......implies that your program is trying to call a python module.

You  need a minor modification in the offending line of code. You have used:
driver = webdriver.firefox()

Where as firefox is a module for example as in:
selenium.webdriver.firefox.options

So you have to change firefox() to Firefox() and your effective line of code will be:
driver = webdriver.Firefox()

Likewise:

*

*For Chrome:
driver = webdriver.Chrome()

*For Internet Explorer:
driver = webdriver.Ie()


text:
Q: Find the identifier of a certain data set in firebase I'm searching through clients invoices
These invoices are stored within the client json.
so...
clients: {
   ... : {
      invoices: {
      },
   },
}

I'm doing this by this:
    var ref = new Firebase(fbUrl+'/clients/'+client+'/invoices/');
    ref.on("value", function(snapshot) {
        var list = snapshot.val();
        angular.forEach(list, function(item) {
            if(item.settings.number == id)
            {
                console.log(item.id());
                invoice.details = item;
            }
        })
    });

Inside the "if" how do I get the unique id auto generated by Firebase? In your html your able to do $id typically.

A: Once you call snapshot.val(), you're just dealing with a Javascript object. See the documentation for angular.forEach. You just need to specify a second argument to the function.
angular.forEach(list, function(item, key) {
    ...
});


text:
Q: In PyQt5 how do I properly move rows in a QTableView using Drag&Drop I (simply) want to be able to use a QTableViews Drag&Drop mechanism to move existing rows. I found lots of sources (e.g. here, here or here) which describe some aspects of dragging, dropping, inserting etc. but I'm still struggling to make it work for my case.
Here is what the solution I'm looking for should be capable of:

*

*work on a 'Qt-free' data structure, e.g. a list of tuples.

*operate on the data structure. i.e. when the order of items gets
modified in the view it should be modified in the data structure

*look and feel of standard drag&drop enabled lists:

*

*select/move whole rows

*show a drop indicator for the whole line

*Further operations like deleting/editing of cells must still be possible
i.e. not be touched by the drag&drop approach

This tutorial shows a solution which is very close to what I need but it uses a QStandardItemModel rather than QAbstractTableModel which looks semi-optimal to me because I have to operate on a 'mirrored' data structure based on QStandardItem which is needed by QStandardItemModel (am I right?)
The code which represents my current progress is appended  below.
Currently I see two possible approaches:
Approach 1: Implement against QAbstractTableModel and implement all needed events/slots to modify the underlying data structure:
* pro: most generic approach
* pro: no redundant data
* con: I don't know how to get informed about a finished drag&drop
  operation and what index got moved where
In the code I've appended I trace all related methods I know of and print out all arguments. Here is what I get when I drag line 2 onto line 3
dropMimeData(data: ['application/x-qabstractitemmodeldatalist'], action: 2, row: -1, col: -1, parent: '(row: 2, column: 0, valid: True)')
insertRows(row=-1, count=1, parent=(row: 2, column: 0, valid: True))
setData(index=(row: 0, column: 0, valid: True), value='^line1', role=0)
setData(index=(row: 0, column: 1, valid: True), value=1, role=0)
removeRows(row=1, count=1, parent=(row: -1, column: -1, valid: False))

This output raises the following questions for me:

*

*why do moveRow/moveRows not get called? when would they be called?

*why are insertRow/removeRow not called but only insertRows/removeRows?

*what does a row index of -1 mean?

*what can I do with mime data provided in dropMimeData? Should I use it to copy data later?

Approach 2: Use QStandardItemModel and modify your data in parallel to the data managed by QStandardItemModel.
* pro: there's a working example
* contra: you manage a redundant data structure which has to be consistent
  with another internally managed data structure.
* contra: didn't find out how to do that exactly neither

Here is my current approach using QAbstractTableModel:

from PyQt5 import QtWidgets, QtCore, QtGui

class MyModel(QtCore.QAbstractTableModel):
    def __init__(self, data, parent=None, *args):
        super().__init__(parent, *args)
        self._data = data

    def columnCount(self, parent):
        return 2

    def rowCount(self, parent):
        return len(self._data)

    def headerData(self, column: int, orientation, role: QtCore.Qt.ItemDataRole):
        return (('Regex', 'Category')[column]
                if role == QtCore.Qt.DisplayRole and orientation == QtCore.Qt.Horizontal
                else None)

    def data(self, index, role: QtCore.Qt.ItemDataRole):
        if role not in {QtCore.Qt.DisplayRole, QtCore.Qt.EditRole}:
            return None

        print("data(index=%s, role=%r)" % (self._index2str(index), self._role2str(role)))
        return (self._data[index.row()][index.column()]
               if index.isValid()
               and role in {QtCore.Qt.DisplayRole, QtCore.Qt.EditRole}
               and index.row() < len(self._data)
               else None)

    def setData(self, index: QtCore.QModelIndex, value, role: QtCore.Qt.ItemDataRole):

        print("setData(index=%s, value=%r, role=%r)" % (self._index2str(index), value, role))
        return super().setData(index, value, role)

    def flags(self, index):
        return (
           super().flags(index)
            | QtCore.Qt.ItemIsDropEnabled
            | (QtCore.Qt.ItemIsEditable | QtCore.Qt.ItemIsDragEnabled)
              if index.isValid() else QtCore.Qt.NoItemFlags)

    def dropMimeData(self, data, action, row, col, parent: QtCore.QModelIndex):
        """Always move the entire row, and don't allow column 'shifting'"""
        print("dropMimeData(data: %r, action: %r, row: %r, col: %r, parent: %r)" % (
            data.formats(), action, row, col, self._index2str(parent)))
        assert action == QtCore.Qt.MoveAction
        return super().dropMimeData(data, action, row, 0, parent)

    def supportedDragActions(self):
        return QtCore.Qt.MoveAction

    def supportedDropActions(self):
        return QtCore.Qt.MoveAction | QtCore.Qt.CopyAction

    def removeRow(self, row: int, parent=None):
        print("removeRow(row=%r):" % (row))
        return super().removeRow(row, parent)

    def removeRows(self, row: int, count: int, parent=None):
        print("removeRows(row=%r, count=%r, parent=%s)" % (row, count, self._index2str(parent)))
        return super().removeRows(row, count, parent)

    def insertRow(self, index, parent=None):
        print("insertRow(row=%r, count=%r):" % (row, count))
        return super().insertRow(row, count, parent)

    def insertRows(self, row: int, count: int, parent: QtCore.QModelIndex = None):
        print("insertRows(row=%r, count=%r, parent=%s)" % (row, count, self._index2str(parent)))
        return super().insertRows(row, count, parent)

    @staticmethod
    def _index2str(index):
        return "(row: %d, column: %d, valid: %r)" % (index.row(), index.column(), index.isValid())

    @staticmethod
    def _role2str(role: QtCore.Qt.ItemDataRole) -> str:
        return "%s (%d)" % ({
            QtCore.Qt.DisplayRole: "DisplayRole",
            QtCore.Qt.DecorationRole: "DecorationRole",
            QtCore.Qt.EditRole: "EditRole",
            QtCore.Qt.ToolTipRole: "ToolTipRole",
            QtCore.Qt.StatusTipRole: "StatusTipRole",
            QtCore.Qt.WhatsThisRole: "WhatsThisRole",
            QtCore.Qt.SizeHintRole: "SizeHintRole",

            QtCore.Qt.FontRole: "FontRole",
            QtCore.Qt.TextAlignmentRole: "TextAlignmentRole",
            QtCore.Qt.BackgroundRole: "BackgroundRole",
            #QtCore.Qt.BackgroundColorRole:
            QtCore.Qt.ForegroundRole: "ForegroundRole",
            #QtCore.Qt.TextColorRole
            QtCore.Qt.CheckStateRole: "CheckStateRole",
            QtCore.Qt.InitialSortOrderRole: "InitialSortOrderRole",
        }[role], role)

class MyTableView(QtWidgets.QTableView):
    class DropmarkerStyle(QtWidgets.QProxyStyle):
        def drawPrimitive(self, element, option, painter, widget=None):
            """Draw a line across the entire row rather than just the column we're hovering over.
            This may not always work depending on global style - for instance I think it won't
            work on OSX."""
            if element == self.PE_IndicatorItemViewItemDrop and not option.rect.isNull():
                option_new = QtWidgets.QStyleOption(option)
                option_new.rect.setLeft(0)
                if widget:
                    option_new.rect.setRight(widget.width())
                option = option_new
            super().drawPrimitive(element, option, painter, widget)

    def __init__(self):
        super().__init__()
        self.setStyle(self.DropmarkerStyle())
        # only allow rows to be selected
        self.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows)
        # disallow multiple rows to be selected
        self.setSelectionMode(QtWidgets.QAbstractItemView.SingleSelection)
        self.setDragEnabled(True)

        self.setDragDropMode(QtWidgets.QAbstractItemView.InternalMove)
        self.setDropIndicatorShown(True) # default
        self.setAcceptDrops(False)           # ?
        self.viewport().setAcceptDrops(True) # ?
        self.setDragDropOverwriteMode(False)

class HelloWindow(QtWidgets.QMainWindow):
    def __init__(self) -> None:
        super().__init__()

        model = MyModel([("^line0", 0),
                         ("^line1", 1),
                         ("^line2", 2),
                         ("^line3", 3)])

        table_view = MyTableView()
        table_view.setModel(model)
        table_view.verticalHeader().hide()
        table_view.setShowGrid(False)

        self.setCentralWidget(table_view)

def main():
    app = QtWidgets.QApplication([])
    window = HelloWindow()
    window.show()
    app.exec_()

if __name__ == "__main__":
    main()

A: I have no clue yet how to make QAbstractTableModel or QAbstractItemModel work as described but I finally found a way to make the QTableView handle drag & drop and just makes the model move a row.
Here's the code:
from PyQt5 import QtWidgets, QtCore

class ReorderTableModel(QtCore.QAbstractTableModel):
    def __init__(self, data, parent=None, *args):
        super().__init__(parent, *args)
        self._data = data

    def columnCount(self, parent=None) -> int:
        return 2

    def rowCount(self, parent=None) -> int:
        return len(self._data) + 1

    def headerData(self, column: int, orientation, role: QtCore.Qt.ItemDataRole):
        return (('Regex', 'Category')[column]
                if role == QtCore.Qt.DisplayRole and orientation == QtCore.Qt.Horizontal
                else None)

    def data(self, index: QtCore.QModelIndex, role: QtCore.Qt.ItemDataRole):
        if not index.isValid() or role not in {QtCore.Qt.DisplayRole, QtCore.Qt.EditRole}:
            return None
        return (self._data[index.row()][index.column()] if index.row() < len(self._data) else
                "edit me" if role == QtCore.Qt.DisplayRole else "")

    def flags(self, index: QtCore.QModelIndex) -> QtCore.Qt.ItemFlags:
        # https://doc.qt.io/qt-5/qt.html#ItemFlag-enum
        if not index.isValid():
            return QtCore.Qt.ItemIsDropEnabled
        if index.row() < len(self._data):
            return QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsEditable | QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsDragEnabled
        return QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsEditable

    def supportedDropActions(self) -> bool:
        return QtCore.Qt.MoveAction | QtCore.Qt.CopyAction

    def relocateRow(self, row_source, row_target) -> None:
        row_a, row_b = max(row_source, row_target), min(row_source, row_target)
        self.beginMoveRows(QtCore.QModelIndex(), row_a, row_a, QtCore.QModelIndex(), row_b)
        self._data.insert(row_target, self._data.pop(row_source))
        self.endMoveRows()

class ReorderTableView(QtWidgets.QTableView):
    """QTableView with the ability to make the model move a row with drag & drop"""

    class DropmarkerStyle(QtWidgets.QProxyStyle):
        def drawPrimitive(self, element, option, painter, widget=None):
            """Draw a line across the entire row rather than just the column we're hovering over.
            This may not always work depending on global style - for instance I think it won't
            work on OSX."""
            if element == self.PE_IndicatorItemViewItemDrop and not option.rect.isNull():
                option_new = QtWidgets.QStyleOption(option)
                option_new.rect.setLeft(0)
                if widget:
                    option_new.rect.setRight(widget.width())
                option = option_new
            super().drawPrimitive(element, option, painter, widget)

    def __init__(self, parent):
        super().__init__(parent)
        self.verticalHeader().hide()
        self.setSelectionBehavior(self.SelectRows)
        self.setSelectionMode(self.SingleSelection)
        self.setDragDropMode(self.InternalMove)
        self.setDragDropOverwriteMode(False)
        self.setStyle(self.DropmarkerStyle())

    def dropEvent(self, event):
        if (event.source() is not self or
            (event.dropAction() != QtCore.Qt.MoveAction and
             self.dragDropMode() != QtWidgets.QAbstractItemView.InternalMove)):
            super().dropEvent(event)

        selection = self.selectedIndexes()
        from_index = selection[0].row() if selection else -1
        to_index = self.indexAt(event.pos()).row()
        if (0 <= from_index < self.model().rowCount() and
            0 <= to_index < self.model().rowCount() and
            from_index != to_index):
            self.model().relocateRow(from_index, to_index)
            event.accept()
        super().dropEvent(event)

class Testing(QtWidgets.QMainWindow):
    """Demonstrate ReorderTableView"""
    def __init__(self):
        super().__init__()
        view = ReorderTableView(self)
        view.setModel(ReorderTableModel([
            ("a", 1),
            ("b", 2),
            ("c", 3),
            ("d", 4),
        ]))
        self.setCentralWidget(view)

        self.show()

if __name__ == '__main__':
    app = QtWidgets.QApplication([])
    test = Testing()
    raise SystemExit(app.exec_())

A: MyData class should be inherited from QStandardItemModel
revised your code to solve drag-drop and extension class function call issue.
from PyQt5 import (QtWidgets, QtCore)
from PyQt5.QtWidgets import (QApplication, QTableView)
from PyQt5.QtGui import (QStandardItem, QStandardItemModel)

class MyModel(QStandardItemModel):
    def __init__(self, data, parent=None, *args):
        super().__init__(parent, *args)
        self._data = data

        for (index, data) in enumerate(data):
            first = QStandardItem('Item {}'.format(index))
            first.setDropEnabled(False)
            first.setEditable(False)
            second = QStandardItem(data[0])
            second.setDropEnabled(False)
            second.setEditable(False)
            self.appendRow([first, second])

    def columnCount(self, parent):
        return 2

    def rowCount(self, parent):
        return len(self._data)

    def headerData(self, column: int, orientation, role: QtCore.Qt.ItemDataRole):
        return (('Regex', 'Category')[column]
                if role == QtCore.Qt.DisplayRole and orientation == QtCore.Qt.Horizontal
                else None)

    def data(self, index, role: QtCore.Qt.ItemDataRole):
        if role not in {QtCore.Qt.DisplayRole, QtCore.Qt.EditRole}:
            return None

        print("data(index=%s, role=%r)" % (self._index2str(index), self._role2str(role)))
        return (self._data[index.row()][index.column()]
                if index.isValid() and role in {QtCore.Qt.DisplayRole, QtCore.Qt.EditRole} and index.row() < len(
            self._data)
                else None)

    def setData(self, index: QtCore.QModelIndex, value, role: QtCore.Qt.ItemDataRole):
        print("setData(index=%s, value=%r, role=%r)" % (self._index2str(index), value, role))
        return super().setData(index, value, role)

    def flags(self, index):
        return (
            super().flags(index)
            | QtCore.Qt.ItemIsDropEnabled
            | (QtCore.Qt.ItemIsEditable | QtCore.Qt.ItemIsDragEnabled)
            if index.isValid() else QtCore.Qt.NoItemFlags)

    def dropMimeData(self, data, action, row, col, parent: QtCore.QModelIndex):
        """Always move the entire row, and don't allow column 'shifting'"""
        print("dropMimeData(data: %r, action: %r, row: %r, col: %r, parent: %r)" % (
            data.formats(), action, row, col, self._index2str(parent)))
        assert action == QtCore.Qt.MoveAction
        return super().dropMimeData(data, action, row, 0, parent)

    def supportedDragActions(self):
        return QtCore.Qt.MoveAction

    def supportedDropActions(self):
        return QtCore.Qt.MoveAction | QtCore.Qt.CopyAction

    def removeRow(self, row: int, parent=None):
        print("removeRow(row=%r):" % (row))
        return super().removeRow(row, parent)

    def removeRows(self, row: int, count: int, parent=None):
        print("removeRows(row=%r, count=%r, parent=%s)" % (row, count, self._index2str(parent)))
        return super().removeRows(row, count, parent)

    def insertRow(self, index, parent=None):
        print("insertRow(row=%r, count=%r):" % (row, count))
        return super().insertRow(row, count, parent)

    def insertRows(self, row: int, count: int, parent: QtCore.QModelIndex = None):
        print("insertRows(row=%r, count=%r, parent=%s)" % (row, count, self._index2str(parent)))
        return super().insertRows(row, count, parent)

    @staticmethod
    def _index2str(index):
        return "(row: %d, column: %d, valid: %r)" % (index.row(), index.column(), index.isValid())

    @staticmethod
    def _role2str(role: QtCore.Qt.ItemDataRole) -> str:
        return "%s (%d)" % ({
                                QtCore.Qt.DisplayRole: "DisplayRole",
                                QtCore.Qt.DecorationRole: "DecorationRole",
                                QtCore.Qt.EditRole: "EditRole",
                                QtCore.Qt.ToolTipRole: "ToolTipRole",
                                QtCore.Qt.StatusTipRole: "StatusTipRole",
                                QtCore.Qt.WhatsThisRole: "WhatsThisRole",
                                QtCore.Qt.SizeHintRole: "SizeHintRole",

                                QtCore.Qt.FontRole: "FontRole",
                                QtCore.Qt.TextAlignmentRole: "TextAlignmentRole",
                                QtCore.Qt.BackgroundRole: "BackgroundRole",
                                # QtCore.Qt.BackgroundColorRole:
                                QtCore.Qt.ForegroundRole: "ForegroundRole",
                                # QtCore.Qt.TextColorRole
                                QtCore.Qt.CheckStateRole: "CheckStateRole",
                                QtCore.Qt.InitialSortOrderRole: "InitialSortOrderRole",
                            }[role], role)

class MyTableView(QTableView):
    class DropMarkerStyle(QtWidgets.QProxyStyle):
        def drawPrimitive(self, element, option, painter, widget=None):
            """Draw a line across the entire row rather than just the column we're hovering over.
            This may not always work depending on global style - for instance I think it won't
            work on OSX."""
            if element == self.PE_IndicatorItemViewItemDrop and not option.rect.isNull():
                option_new = QtWidgets.QStyleOption(option)
                option_new.rect.setLeft(0)
                if widget:
                    option_new.rect.setRight(widget.width())
                option = option_new
            super().drawPrimitive(element, option, painter, widget)

    def __init__(self):
        super().__init__()
        self.setStyle(self.DropMarkerStyle())
        self.verticalHeader().hide()
        self.setShowGrid(False)
        # only allow rows to be selected
        self.setSelectionBehavior(self.SelectRows)
        # disallow multiple rows to be selected
        self.setSelectionMode(self.SingleSelection)
        self.setDragDropMode(self.InternalMove)
        self.setDragDropOverwriteMode(False)

class HelloWindow(QtWidgets.QMainWindow):
    def __init__(self) -> None:
        super().__init__()
        model = MyModel([("^line0", 0),
                         ("^line1", 1),
                         ("^line2", 2),
                         ("^line3", 3)])
        table_view = MyTableView()
        table_view.setModel(model)
        self.setCentralWidget(table_view)

def main():
    app = QApplication([])
    window = HelloWindow()
    window.show()
    app.exec_()

if __name__ == "__main__":
    main()


text:
Q: Javascript: Programmatically set numbers as object keys I have the following data generated by an API:
{
  "config": {
    1: {"slot1": "SK_DISENGAGE"},
    2: {"slot1": "SK_DISENGAGE"}
  }
}

I transformed config into this array of objects below, as it's easier to deal with when displaying it via react-hook-form, and because the items in the object are subject to change:
{
  "config": [
    {"slot1": "SK_DISENGAGE", element: 1},
    {"slot1": "SK_DISENGAGE", element: 2}
  ]
}

Here's a codesandbox of the code below:
function App() {
  const { register, control, handleSubmit, reset, watch } = useForm({
    defaultValues: {
      config: [
        { slot1: "SK_DISENGAGE", element: 1 },
        { slot1: "SK_DISENGAGE", element: 2 }
      ]
    }
  });
  // Simplified. The data comes from an API, and useForm would be empty until after the async functions are done.

  const { fields } = useFieldArray({ control, name: "config" });

  const onSubmit = (data) => console.log("data", data);

  renderCount++;

  return (
    <form onSubmit={handleSubmit(onSubmit)}>

Field Array

        {fields.map((item, index) => {
          return (

              {`Item:`}
              <input
                name={`config.${item.element}.slot1`}
                defaultValue={`${item.slot1}`}
                ref={register()}
              />

          );
        })}

      <input type="submit" />
    </form>
  );
}

However, I'm having trouble transforming it back, and it ends up like this:
{
  "config": [
    null,
    { "slot1": "SK_DISENGAGE" },
    { "slot1": "SK_DISENGAGE" }
  ]
}

config is now an array of objects, a format the API will not take kindly to. I've tried modifying the name field in the input tag, adding ", ', or no quotes to item.element, but the results are the same.
I assume the first element is null because nothing is setting the element 0.
How do I programmatically set a number as an object key? Is there a slash or something I should put in so it should be taken as a string?

A: You can use Array.prototype.reduce() method to achieve your desired output. The syntax of array reduce array.reduce(function(total, currentValue, currentIndex, arr), initialValue).

const data = {
  config: [
    { slot1: 'SK_DISENGAGE', element: 1 },
    { slot1: 'SK_DISENGAGE', element: 2 },
  ],
};

const ret = {
  config: data.config.reduce((prev, c) => {
    const p = prev;
    p[c.element] = { slot1: c.slot1 };
    return p;
  }, {}),
};
console.log(ret);

A: If you change your field mapping to this:
{fields.map((item, index) => {
      return (

          {`Item:`}
          <input
            name={item.element}
            defaultValue={`${item.slot1}`} // make sure to set up defaultValue
            ref={register()}
          />

      );
    })}

And your onSubmit to this:
const onSubmit = (data) => {

    var newData = Object.entries(data).reduce( (acc, [key,value]) => {
      acc[key] = {slot1:value};
      return acc;
    },{});
    console.log("data", newData);
}

The result is pretty close to your original input.... does that work for you?
Fork of your code: https://codesandbox.io/s/react-hook-form-usefieldarray-forked-olcn3

A: Append an array field to the original object
{
  "config": {
    1: {"slot1": "SK_DISENGAGE"},
    2: {"slot1": "SK_DISENGAGE"}
  },
  "config-arr": [
    {"slot1": "SK_DISENGAGE", element: 1},
    {"slot1": "SK_DISENGAGE", element: 2}
  ]
}


text:
Q: New Relic Custom Metrics - Cannot get it to work I've tried to follow the New Relic documentation at https://docs.newrelic.com/docs/dotnet/dotnet-agent-custom-metrics for setting up custom metrics on our web application but cannot get it to work.
In the New Relic trace we see lots of

Application code (in System.Web.Mvc.MvcHandler.BeginProcessRequest()) - Our agent can't see what is happening in your .NET code. Consult our documentation to find out how to add custom metrics to your app.

So, I've created a MyInstrumentation.xml file, put it in the extensions folder and am still not seeing any additional metrics. What am I doing wrong?
Here is example XML of my custom metrics:
<?xml version="1.0" encoding="utf-8"?>
<extension xmlns="urn:newrelic-extension">
<instrumentation>
  <tracerFactory>
    <match assemblyName="WebSite.Area" className="WebSite.Area.Controllers.MyController">
      <exactMethodMatcher methodName="MyMethod" />
    </match>
  </tracerFactory>
  <tracerFactory>
    <match assemblyName="Business.CustomerBL" className="Business.CustomerBL.MyBusinessClass">
      <exactMethodMatcher methodName="SaveCustomer" />
    </match>
  </tracerFactory>
</instrumentation>
</extension>

A: An application pool recycle was what was required


text:
Q: Did Philip K. Dick purposefully confuse Mrs. Kesselman with Mrs. Keitelbein in "Time Out Of Joint"? I am confused about the Kesselman characters (mother and son).  When a female voice spoke to Ragle on the phone, reminding him about attending his first civil defence class, she said that Walter could drive him to/from the class to save time, being a 15 minute car journey away.  I am assuming this voice was Mrs Keitelbein (as this identity was used by a female who called at Ragle's house in person about joining the CD class), but Mrs Keitelbein only lived a block away, and it was more likely that Mrs Kesselman lived a 15 minute car journey away, because he had driven to her house (on the hill) before.  It's as if during that phone call, Mrs Kesselman momentarily forgot (and so made a mistake) about maintaining her alter ego identity of "Mrs Keitelbein".
If this is correct, then why was the book written that way?  Why does the book seem to purposefully confuse these two identites, as if to merge them together for some reason, so that they become one identity?  (Mr Black mentions to Lowery that he knows someone called Mrs Kesselman, so a person by the name of Kesselman does seem to exist.)
The thing that puzzles me is if there is only one identity, and Mrs Kesselman had created an alter ego (Mrs Keitelbein) in order to sidestep Mr Black and the city authorities (as she was an "undercover lunatic"), then why did the Kesselmans sidestep Ragle in her house on the hill, by escaping from the locked closet, and presumably, alerting the city authorities to Ragle's current location, as he was quickly overcome by a group of city workers?

A: No, there's no confusion with the Kesselmans. The Kesselman house is much farther away, he drove quite a while through the countryside to get there at night.
This is what she says:

"...Walter can drop by and pick you up in his car; and I know he can drive you back home afterward. The class is only about an hour at  the longest, so it wouldn't be more than an hour and fifteen minutes at the very most.
"He doesn't have to give me a ride," Ragle said. "You're only half a block away.""Oh that's so," she said. "You're just up the street from us. Then you surely ought to be able to make it; please, Mr. Gumm—as a favor to me."

So she estimates 15 minutes there and back, as an upper bound. She's only trying to convince him that it won't take too much of his time. That said, it does seem like she didn't remember how far away he is exactly.
The Kesselmans are loyal One Worlders, the Keitelbeins are lunatic agents, different people. Black speculates they chose the name for the similarity, knowing he would have trouble telling them apart, although why he knew the Kesselmans i don't know.


text:
Q: Remix fail to render after i put hour in component white screen
component
time is: '2022-08-31T08:25:00.000Z'
Why remix entry client is failing only when  i put datetime.hour or datetime.minute???
Update:
import React, { useEffect, useState } from "react";
import { DateTime } from "luxon";

type CommonProps = {
  time: String;
};

type Props = CommonProps;

export const MlTimeComponentNew: React.FC<Props> = ({ time }) => {
  // @ts-ignore
  const parsed = DateTime.fromISO(time);

  return (

        {parsed.hour}

  );
};

LAST UPDATE:
Problem was in component actually:
import React, { useEffect, useState } from "react";
import { DateTime } from "luxon";

type CommonProps = {
  time: String;
};

type Props = CommonProps;

export const MlTimeComponentNew: React.FC<Props> = ({ time }) => {
   const parsed2 = DateTime.fromISO(time, {zone: 'utc'});
  const [hour, setHour] = useState(0);

  useEffect(() => {
    setHour(parsed2.hour);
  }, []);

  return (

        {hour}

  );
};

I still don't understand why remix is creating problem with first implementation


text:
Q: What species were the aliens in 'Conspiracy'? In Star Trek: The Next Generation, season 1 episode 25, 'Conspiracy', there were aliens

 who are an insect-like parasite that controls the body of whomever it enters.

What species was this alien?

 Also, was the alien related to the creatures from Ceti Alpha, used by Kahn to control Chexkov and Captain Terell?

A: They never appear again or recieve an official name in Star Trek canon.

In noncanoncial sources sources, however, they are named Bluegills or are simply called Parasites and are closely related to (and in some sources, genetically engineered from) Trill Symbionts (and therefore not related to the Ceti Alpha V creature, as long as we assume that it was truly indigenous to the planet as Khan claimed).
So the answer to your question really depends on which books you read.
Source
Related


text:
Q: Converting string to byte in go Basically what I'm trying to do is convert a string in the hexidecimal format to a byte and append the byte to a byte slice.
I've tried:
func main() {
    bytes := []byte{0xfc}
    string := "0xe8"
    bytes = append(bytes, string...)
    fmt.Printf("%s", bytes)
}

output:
�0xe8

I know I could just declare a byte variable and append the byte.
I need to convert the string into a byte.
Expected output:
��

A: This is work fo me.
func main() {
    bytes := []byte{0xfc}
    str := "0xe8"
    pc, _ := strconv.ParseUint(str, 0, 64)

    bytes = append(bytes, uint8(pc))
    fmt.Printf("%s", bytes)
}

Output:
��


text:
Q: Interpreting a regression equation with summation notaion I am definitely more of an applied statistician than one with a strong background in the specific mathematical notation.  I'd like to recreate a model I ran across in a paper, and though I understand how to do nonlinear regression (in this case, negative binomial), I'm not sure about how to interpret the following equation that was given as the model for the relationship:
$$ln(Q_{it}) = \beta_1 +\sum_{\theta} (\beta_\theta ln(P_{it}) * storetype_{\theta,i} )) + \sum_{\pi} (\beta_\pi ID_{\pi,i}) + \sum_\delta (\beta_\delta Region_{\delta,i} * endcap_{it}) + \beta_2 radio_{it} + \epsilon_i + \gamma_t$$
for item i in time period t.
It's obviously a demand equation.  I understand the general structure of regression equations, but am unsure how to translate the presence of the summations.  There are multiple coefficients for each of the independent variables, and there seems to be a hierarchical structure of some sort.  I haven't been able to find any formal examples of this structure in my searches and I want to make sure I understand what's going on before I proceed.  Thanks for any help you can provide.

A: Let's say the equation were:
$$ln(Q_{it}) = \beta_0 + \sum_{\theta} \beta_\theta \ln(P_{it}) \mathit{Storetype}_{\theta,i}  + \epsilon_{it} $$
And imagine $\theta \in \{ 1,2,3\}$ hence the above regression equation would simply be:
$$ln(Q_{it}) = \beta_0 +\beta_1 \ln(P_{it}) \mathit{Storetype}_{1,i}+ \beta_2 \ln(P_{it}) \mathit{Storetype}_{2,i}+ \beta_3 \ln(P_{it})\mathit{Storetype}_{3,i}  + \epsilon_{it} $$
That is, you'd be estimating a different coefficient $\beta_\theta$ for each possible value of $\theta$. The summation is just a more compact way to write the regression model.
But what is $\mathit{Storetype}_{\theta,i}$?
You'll have to read the paper to know for sure, but I'd guess that $\mathit{Storetype}_{\theta,i}$ is an indicator variable:
$$ \mathit{Storetype}_{\theta,i} = \left\{ \begin{array}{ll} 1& \text{if observation $i$ is storetype $\theta$} \\ 0 & \text{otherwise}  \end{array} \right. $$
And then you'd be estimating a different elasticity $\beta_{\theta}$ for each storetype $\theta$. But that's just a guess.


text:
Q: On click show span I am trying to hide span under another span and when someone click on the upper most span it should disappear and show the contents beneath it.
MY HTML:
{{ i.couponCode }}Click to see code

My CSS:
.cTs
{
    left :0px;
    padding:10px;
    height:50px;
    color:white;
    width: 100px;
    position: relative;
    background: black;
}

but i am unable to position the  over the first span...instead it appear on the right of the first span....can someone please help me...

A: Wrap the elements inside a position: relative; container, and than use position: absolute; with top and left values for inner elements
div {
    position: relative;
}

div span {
    position: absolute;
    top: 0;
}

div span:nth-of-type(1) {
    z-index: 1;
}

div span:nth-of-type(2) {
    top: 10px;
    left: 25px;
}

Demo
Using an onclick event


text:
Q: Modify the Ramer–Douglas–Peucker (RDP) algorithm in numpy to return a mask instead of the values I am trying to modify the numpy implementation of the Ramer–Douglas–Peucker (RDP) algorithm, to return a mask of the filtered values instead of a filtered array with the values.
The problem is how to return the correct mask recursively.

A: Well it facilitated to understand the algorithm correctly. If all points between the first and last segment in each recursive call are within epsilon, those should be marked as False while the start and end should be True. Here is my solution:
import numpy as np

def pldist(x0, x1, x2):
    return np.divide(np.linalg.norm(np.linalg.det([x2 - x1, x1 - x0])),
                     np.linalg.norm(x2 - x1))

def rdp_index(M, epsilon=0, dist=pldist):

    dmax = 0.0
    index = -1

    for i in xrange(1, M.shape[0]):
        d = dist(M[i], M[0], M[-1])

        if d > dmax:
            index = i
            dmax = d

    if dmax > epsilon:
        r1 = rdp_index(M[:index + 1], epsilon, dist)
        r2 = rdp_index(M[index:], epsilon, dist)

        return np.vstack((r1[:-1], r2))
    else:
        part_mask = np.empty_like(M, dtype = bool)
        part_mask.fill(False)
        part_mask[0] = True
        part_mask[-1] = True
        return part_mask

Note that this implementation is using recursion, and this solution gave problems with large datasets https://stackoverflow.com/a/2401520/2082968. I.e. the maximum amount of recursion calls were exceeded. Below is a solution that is using a stack and a while loop instead of the recursive calls. In addition, the distances are calculated a bit more efficiently.
def dsquared_line_points(P1, P2, points):
    '''
    Calculate only squared distance, only needed for comparison
    http://en.wikipedia.org/wiki/Distance_from_a_point_to_a_line
    '''
    xdiff = P2[0] - P1[0]
    ydiff = P2[1] - P1[1]
    nom  = (
        ydiff*points[:,0] - \
        xdiff*points[:,1] + \
        P2[0]*P1[1] - \
        P2[1]*P1[0]
    )**2
    denom = ydiff**2 + xdiff**2
    return np.divide(nom, denom)

def rdp_numpy(M, epsilon = 0):

    # initiate mask array
    # same amount of points
    mask = np.empty(M.shape[0], dtype = bool)

    # Assume all points are valid and falsify those which are found
    mask.fill(True)

    # The stack to select start and end index
    stack = [(0 , M.shape[0]-1)]

    while (len(stack) > 0):
        # Pop the last item
        (start, end) = stack.pop()

        # nothing to calculate if no points in between
        if end - start <= 1:
            continue

        # Calculate distance to points
        P1 = M[start]
        P2 = M[end]
        points = M[start + 1:end]
        dsq = dsquared_line_points(P1, P2, points)

        mask_eps = dsq > epsilon**2

        if mask_eps.any():
            # max point outside eps
            # Include index that was sliced out
            # Also include the start index to get absolute index
            # And not relative
            mid = np.argmax(dsq) + 1 + start
            stack.append((start, mid))
            stack.append((mid, end))

        else:
            # Points in between are redundant
            mask[start + 1:end] = False

    return mask


text:
Q: Get the length of properties in a multidimensional array based on dimension? Using vanilla JavaScript, I want to access the length of a multidimensional array based on the "dimension" it is in.
Example:
Here's a multidimensional array
  var myArray = [a, b, c, d, [e, [f], g]]

Dimension 0 in has 5 elements [a, b, c, d, [e, [f], g]]
Dimension 1 has 3 elements [e, [f], g]
Dimension 2 has 1 element [f]
This is what I have so far (which isn't a lot to go off of - I'm really stuck)
var getLength = function(arr, dimension) {
  subarray = [];
  for (var e in arr) {
    if (e instanceof Array) {
     return e.length
    }
  }
}

// getLength(myArray, 2) should equal 1

Can you kindly help?

A: You could reduce and recurse while keeping track of arrays that have been seen:
var depthCount = function(xss, depth) {
  depth = depth || 0
  var seen = []
  return xss.reduce(function(acc, xs) {
    if (Array.isArray(xs)) {
      return acc.concat(depthCount(xs, depth + 1))
    }
    if (seen.indexOf(xss) < 0) {
      seen.push(xss)
      return acc.concat({depth: depth, count: xss.length})
    }
    return acc
  }, [])
}

var xs = [1, 2, 3, 4, [5, [6], 7]]

console.log(depthCount(xs))
// [{depth: 0, count: 5},
//  {depth: 1, count: 3},
//  {depth: 2, count: 1}]

Then you can find out the total by filtering the collection by depth and checking the count. If you sum up the counts it will work when you have multiple arrays of the same depth too:
var xs = [1, [2, 3], [4, 5, [6, 7]]]

var count = depthCount(xs)

console.log(count)
// [{depth: 0, count: 3},
//  {depth: 1, count: 2},
//  {depth: 1, count: 3},
//  {depth: 2, count: 2}]

var countTotalDepth = function(depth, coll) {
  return coll.filter(function(obj) {
    return obj.depth === depth
  }).reduce(function(x, y) {
    return x.count + y.count
  })
}

console.log(countTotalDepth(1, count)) // 5

A: You can have a helper method get the count of members recursively, then use the main method to just access which layer count is wanted using "layer":
Pseudocode for helper function:
// Count members, and store if object
// Recursively get list of lengths from those objects
// Sum up those lists
    // find length of longest array
    // sum up all values, up to length of longest array
// Insert 'count' at front of the list
// Return

Full code:
/*
Main function
Returns a number: the count of members in a layer
*/
function getLength(layer, obj)
{
    return getAllLengths(obj)[layer];
}

/*
Helper function for getLength(..)
Returns an array
*/
function getAllLengths(obj)
{
    var count = 0; // for this layer's # of members
    var objectMembers = []; // list of members that are objects
    var objectsLists = []; // to store list of lists produced recursively from objectMembers
    var result = []; // to return

    // count, and store if object
    for (var mem in obj)
    {
        count++;
        if (obj[mem] instanceof Object)
        {
            objectMembers.push(obj[mem] );
        }
    }

    // recursively get objects' lists
    for (var i in objectMembers)
    {
        objectsLists.push(getAllLengths(objectMembers[i] ));
    }

    ////// sum up lists
    // find length of longest array
    var maxLength = 0;
    for (var i in objectsLists)
    {
        if (objectsLists[i].length > maxLength)
        {
            maxLength = objectsLists[i].length;
        }
    }
    // sum
    for (var i = 0; i < maxLength; i++)
    {
        var sum = 0;
        for (var j = 0; j < objectsLists.length; j++)
        {
            if (objectsLists[j][i] != undefined)
                sum += objectsLists[j][i];
        }
        result.push(sum);
    }

    // complete resulting list to return
    result.splice(0,0, count);

    return result;
}


text:
Q: Адаптивная вёрстка вот код:

#intouch {
  font-family: Arial Rounded MT Bold, bold;
  width: 17%;
  float: left;
  border-right: 2px solid #be0000;
  border-bottom: 2px solid #be0000;
  font-size: 300%;
  color: #be0000;
}

#options {
  background: #be0000;
  font-size: 190%;
  color: #ffffff;
  width: 83%;
  margin-left: 17%;
  padding-top: 1.6%;
}

.option {
  padding-left: 7%;
}

На связи

    Регистрация
    Вход
    Пожертвования
    Контакты

Дело в том что на устройствах с разным разрешением это выводится криво. Как решить этот вопрос без @media?

A: Вариант с flex, точнее flex-flow: row wrap; позволит переносить контент если не будет вмещаться. При этом можно задавать ширину как в процентах (как у Вас) так и фикс, если не вместится на опр. разрешении - блоки будут перестраиваться друг под другом:

* {
  box-sizing: border-box;
}

html,
body {
  padding: 0;
  margin: 0;
}

.top {
  display: flex;
  flex-flow: row wrap;
  align-items: stretch;
}

#intouch {
  font-family: Arial Rounded MT Bold, bold;
  width: 100px;
  float: left;
  border-right: 2px solid #be0000;
  border-bottom: 2px solid #be0000;
  color: #be0000;
  font-size: 20px;

  flex-grow:0;
  flex-shrink:0;
}

#options {
  background: #be0000;
  color: #ffffff;
  width: calc(100% - 100px);
  padding-top: 1.6%;
  padding-bottom: 1.6%;

  display: flex;
  flex-flow: row wrap;
  justify-content: space-between;

  flex-grow:0;
  flex-shrink:0;

  font-size: 14px;
}

На связи

    Регистрация
    Вход
    Пожертвования
    Контакты

Еще если без медиазапросов (@media), то, как вариант, использовать размер шрифта в vw или vh, а то проценты как-то не особо хорошо работают:

* {
  box-sizing: border-box;
}

#intouch {
  font-family: Arial Rounded MT Bold, bold;
  width: 17%;
  float: left;
  border-right: 2px solid #be0000;
  border-bottom: 2px solid #be0000;
  color: #be0000;
  font-size: 4vw;
}

#options {
  background: #be0000;
  color: #ffffff;
  width: 83%;
  margin-left: 17%;
  padding-top: 1.6%;

  font-size: 3vw;
}

.option {
  padding-left: 7%;
}

На связи

  Регистрация
  Вход
  Пожертвования
  Контакты

A: Сделайте внутренние паддинги для #intouch и #options. Если .option { display: inline-block}, то лучше писать .option:not(:last-child){padding-right: 7%} А вообще проценты действительно плохо работают, как сказали выше


text:
Q: rsync start from begin after a power cut off It seems that rsync save a temporary file at local when I sync a big file on remote.
Then the machine encounter a abrupt shut down for power off.
After I start the machine again, it seems that rsync syn the big file from begin, but I found that there is one file already synced about 60%(1G), what's wrong of my rsync usage?
command I used:
rsync --partial -av -r --progress user@remote /local-dir

A: As Tim said, this sounds normal; rsync will know that it's got a file that seems to be a partial copy of the remote file, but it still has to check that the file it has is in fact the  file you're copying from.
As it's doing this check, it will show the number of bytes of the file it has "transferred", so it will look as though it's copying the file again - but if you look at the speed of the transfer, it should be much faster than would be possible across the network. Eventually rsync will get past the bytes it's already copied and find new bytes that need to be transferred across the network, and then you'll see the speed slow down.
In short, I think you're being confused by rsync's output, as it doesn't differentiate between "bytes transferred across the network" and "bytes transferred simply by checking that the local copy matches the remote copy"

A: This is normal. rsync should be going back through the files it's already transferred to check for updates.
The -u flag causes rsync to look at file modification times; if you add this it should skip the files that haven't changed on the source.

A: Just rename the temp file (.somethingXYZ) to the correct filename (something) from the remote source.
Then rsync will DEFINITELY only download the missing stuff.
(If you watch the folder when running rsync, you will see a new .somethingABC file being generated, which will grow by tens of MB/second... because rsync will be reading from the "half-done" local file instead of downloading it again from the remote source over the network).

A: You can force rsync to checksum the file and only copy remaining data with the following command.
rsync -av --progress --checksum --inplace --no-whole-file SOURCE DESTINATION


text:
Q: Failure to unscale coefficients from a linear model with interactions I have data that require scaling fixed effects to fit linear mixed models with the lmer function from the lme4 package that converge. I want to unscale the estimated coefficients to present results in useful units. Previous posts address this issue, but I am unable to successfully unscale coefficients from models including categorical predictors and interaction terms. I used lmer() with my data set, but I have created an example using lm and the diamonds data for simplicity.
related threads:
    https://stackoverflow.com/questions/23642111/how-to-unscale-the-coefficients-from-an-lmer-model-fitted-with-a-scaled-respon
and
    https://stackoverflow.com/questions/24268031/unscale-and-uncenter-glmer-parameters
Below is some code that runs without error, but demonstrates that I can't get unscaling to work correctly:
library(ggplot2)
library(dplyr)

# function to rescale variables around 0
zscore <- function(x) (x - mean(x)) / sd(x)

# creates new dataframe with scaled values included
diamonds_s <- diamonds %>% select(carat, cut, price, depth) %>% mutate_each(funs(s = zscore(.)), -cut)

Create unscaled and scaled models
# Linear model with unscaled interaction specified
m1 <- lm(price ~ carat * depth * cut, data= diamonds_s)
b1<- coef(m1)
# summary(m1)

# Linear model with scaled interaction specified
m1s <- lm(price_s ~ carat_s * depth_s * cut, data= diamonds_s)
b1s <- coef(m1s)
# summary(m1s)

Function to rescale coefficients from answer by Ben Bolker
# https://stackoverflow.com/questions/24268031/unscale-and-uncenter-glmer-parameters

rescale.coefs <- function(beta,mu,sigma) {
    beta2 <- beta ## inherit names etc.
    beta2[-1] <- sigma[1]*beta[-1]/sigma[-1]
    beta2[1] <- sigma[1]*beta[1]+mu[1]-sum(beta2[-1]*mu[-1])
    beta2
}

Use model.matrix to get predictor variables
X <- model.matrix(price ~ carat * depth * cut, data= diamonds_s)

# matrix of response (m[1]) and predictor (m[-1]) means
m <- c(mean(diamonds_s$price), colMeans(X)[-1] )
 s <- c(sd(diamonds_s$price), apply(X, 2, sd)[-1] )

# or with unscaled response (not run because I scaled the response, price_s):
# m <- c(0, colMeans(X)[-1] )
# same for standard deviations
# s <- c(1, apply(X, 2, sd)[-1] )

Now attempt to unscale
b1r <- rescale.coefs(b1s, m, s)

The values obtained are wrong, however.
all.equal(b1, b1r, check.names=FALSE, tolerance=0.001)

I appreciate any input about this issue.

A: I think I had the same problem. I've solved scaling the interactions terms using their own means and standard deviations.
This thread may be useful, check the detailed Ben Bolker answer.


text: Q: Does somebody knows how to register BoostrapVue with Vue in Sails WebApplication schema? I'm using default temps of sails web applications. But right now i want to use BootstrapVue Library inside the app. I'm finding how and where to tell to Vue to use BootstrapVue library


text:
Q: Cannot get True when finding a number in a list that is divisible by 7 def divisible_by_7(lst: List[int]) -> bool:
    """Return True if and only if lst contains an element divisible
    by 7. Otherwise, return False.

    >>> divisible_by_7([4,8,21,6])
    True
    >>> divisible_by_7([1,2,8,9])
    False
    """
    for num in lst:
        if num % 7 == 0:
            return True
        elif num % 7 !=0:
           return False

I keep on getting false even if the answer is true. I know that if we return false it won't work because when the function looks through the list, if there is even one instance where there is a number that isn't divisible by 7, it fails. How do I correct this?

A: How about to iterate thought all list elements?
def divisible_by_7(my_list):
    for num in my_list:
        if num % 7 == 0:
            return True;
    return False;

A: You are returning from the first iteration. The comments and Oleg Butuzov's answer have you covered there. However, the built-in shortcut for this pattern would be any:
def divisible_by_7(lst):
    return any(x % 7 == 0 for x in lst)


text:
Q: Keyboard not visible My application has a ViewPager and dynamic WebView. When the page displays the captcha (anti-bot) to enter, then when you click on the component input, the keyboard is not displayed. When I removed the ViewPager and left just a WebView - keyboard is displayed. In what may be the problem?
adapter=new BrowserPagerAdapter(pages);
    viewpager=new ViewPager(this);
    viewpager.setAdapter(adapter);
    viewpager.setCurrentItem(0);
    setContentView(viewpager);


text:
Q: Javascript add each part of username to keywords array for web-socket queries? I am trying to add the keywords of a user's username for faster querying using websocket events.
In my userSchema I have keywords index set to true:
  keywords: {
      // for live search of username
      type: [String],
      index: true,
    },

For example if a user's username is 'johnsmith', I need to save an array with the following..
user.keywords = [j, jo, joh, john, johns, johnsm, johnsmi, johnsmit, johnsmith]

I will be doing this in my userSchema.pre('save').
Below is what I am going for but how would I append the username to the parts array and then set user.keywords = parts?? Am I properly indexing the user.keywords property??
Thank you!
userSchema.pre(`save`, async function (next) {
  const user = this

  if (user.isModified(`username`)) {
    let parts = []
    for (let i = 0; i < user.username.length; i++) {
      parts.push(*???*)
    }
    user.keywords = parts
  }

  next()
})

A: As I am seeing it you are trying to make sure that if even a part of the name is searched, that it is also found when fetching from the database?
You can just use regex for the search instead of writing the possible requests in an array.
User.find({ username: {$regex : `/^${requestedSearch}/`}});

This will now find you the results where the username starts with the requested string.
If your username is "Steve" and you search for "Ste", it will return you that user from the database.
You can also add options for case sensitive and so on.
Here is some more information: https://docs.mongodb.com/manual/reference/operator/query/regex/


text:
Q: C#-Pandas Process Error (.NET): no module named pandas I have a simple GUI with two buttons and a rich text box. Button One uses the OpenFileDialog() class to fetch a video file and write the path as a string in the rich text box. Button 2 takes the value of the rich text box and sends it file to a Python script. This part works fine. Here is the function for sending the file.
I am operating out of Visual Studio 19.
C# .NET framework
   public void PotatoOne(string path)
    {
        var neat = "r'" + path;
        var shell = "python.exe";
        Process x = new Process();
        x.StartInfo = new ProcessStartInfo()
        {
            FileName = shell,
            Arguments = ($"\"{"C:\\Users\\BeckerLab\\source\\repos\\Final Implementation\\Final Implementation\\untitled7.py"}\" \"{neat}\""),
            ErrorDialog = true,
            WorkingDirectory = Path.GetDirectoryName(@"C:\ProgramData\Anaconda3\envs\tensorflow1"),
            UseShellExecute = false,
            CreateNoWindow = false,
            RedirectStandardError = true,
            RedirectStandardOutput = true
        };

        try
        {
            x.Start();
            var res = x.StandardOutput.ReadToEnd();
            var err = x.StandardError.ReadToEnd();

            Console.WriteLine(res);
            Console.WriteLine();
            Console.WriteLine(err);
            Console.WriteLine();
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
            Console.ReadKey();
        }

BUT the Process says I do not have some of the modules. Here they all are:
(notably, os, sys, numpy and cv2 are all understood. pandas and PIL, are not)
Python Code, (attempted Anaconda3, tensorflow1 envs)
import os
import cv2
import numpy as np
import sys
import pandas as pd
from pandas import ExcelWriter
from pandas import ExcelFile
import PIL

path = sys.argv[1]
I have untitled7.py in its own folder as a python file with its own solution, and they are both using the same Python environments, with the same module patches. Furthermore, untitled7.py has access to all the imports in the regular Python script, but not the .NET process.
It is clear that whatever I am doing, it's not calling the python file to run the same way. Is it because I am calling the Process incorrectly? Do I need to call a virtual environemt? Why can't I call the actual Python environment to run a Python script? Why does the exact same environment not provide the same set of modules for both solutions?
Thank you for your time.