text:
Q: How get all text in one html page, only between two tag Im Sorry for my bad English
I need help for my problem. When we open page source of HTML page like google, we will found HTML TAG : (in this google was found my string)
<!doctype html><title>bla bla bla

**bla bla bla..**

**bla bla bla..**

**bla bla bla..**

</script>

and my problem is :
How PHP get all string between
 ..
, but keep HTML TAG (inlude
 and
). So, all string before first
 and after last
, or all string between
 and next
 will be deleted or not show.
I can do this in VB but can't on PHP.
Thanks

A: Hopefully I'm understanding your question correctly, but if not, I appologize.
Starting on a side note: The method you use to get the result you are looking for in VB should be the same method you will use in PHP, but with a different syntax, I presume.
That being said, if you are looking to only the ordered lists on the page, I would recommend doing that with some sort of XML processing.  Using XPATH, you should be able to get an array of
...
 elements.  I would then take those and build the page based off of that.  Just using Regex could be painful per the following html string:

subdata1

.  What you would want is the whole
 element, but unless you're clever w/ regex, you will most likely end up with:

subdata1

 and miss the last

Anyway, just a thought.  I would look first into re-writing your VB app in PHP, but if that is not possible, I recommend reading up a bit on processing XML w/ PHP using XPATH queries.

A: You can use the PHP string functions, php regular expression functions or XML parsing functions.
The fastest would be to use string functions like strpos() and substr(). However, regular expressions with preg_match() or XML functions like with SimpleXML are easier to use.

A: This my VB code :
Dim start_string As String
Dim end_string As String
dim g as string
On Error Resume Next
  start_string = "
"
  end_string = "
"
  st = 1
  Data = (URL)

  s = InStr(st, Data, start_string, 1)
  While s > 0
  d = InStr(Len(start_string) + s, Data, end_string, 1)
  g = Mid(Data, s, d - s + Len(end_string))
  DoEvents

  g = Trim(g)

  st = d + 1
  s = InStr(st, Data, start_string, 1)
  Wend

A: You may want to read up on PHP's support of regular expressions.


text:
Q: I keep getting this error int cannot be dereferenced The code is supposed to return the first and the last letter of a string ,but I keep getting these errors Line 5: int cannot be dereferenced and Line 6: int cannot be dereferenced
public String firstAndLast(String str)
  {
  int length = str.length();
  char first= length.charAt(0);
  char last= length.charAt(length - 1);
  return String.valueOf(first) + String.valueOf(last);
  }

A: Not
char last= length.charAt(length - 1);

but
char last= str.charAt(length - 1);

More important, the error message is telling you exactly where your problem is -- which line, and what's wrong -- you're trying to call a method on length, an int. In the future, read the error messages critically as they'll usually give you the problem and a solution can be obvious once you understand the problem.

A: length is a primitive type int variable. You can not invoke methods through it, maybe the code would be in this way?
    public String firstAndLast(String str)
    {
        int length = str.length();
        char first= str.charAt(0);
        char last= str.charAt(length - 1);
        return String.valueOf(first) + String.valueOf(last);
    }

redpajama_set_name: RedPajamaStackExchange


text:
Q: how to search files in a directory using 2 words in php In mydirectory

green.txt
  black.txt
  shadow.txt

and my php code
<?php
$key = "black+shadow"
$dir = 'file/dir';
$ext = '.txt';
$i=0;
$search = $key;
$results = glob("$dir/*$search*$ext");
if(count($results) != 1) {
    foreach($results as $item) {
      echo $item;
    }
  }?>

I want to get the output "black.txt" and "shadow.txt"

A: $key = "black+shadow";
$dir = "file/dir"
$ext = '.txt';

foreach (explode("+", $key) as $filePart) {
    $fileName = $filePart . $ext;
    if (file_exists("{$dir}/{$fileName}")) {
        echo $fileName . '<br>';
    }
}

This assumes that the pattern will always be filepart separated by +
You can use glob if you end up with more complex solutions - but this is probably the fastest and easiest way to understand IMHO.

A: <?php
$key = "{black,shadow}";
$ext = '.txt';
$i=0;
$search = $key;
$results = glob("$search*$ext",GLOB_BRACE);
if(count($results) != 1) {
    foreach($results as $item) {
      echo $item;
    }
  }?>

per the manual,
GLOB_BRACE - Expands {a,b,c} to match 'a', 'b', or 'c'

i added braces around your search terms and added the GLOB_BRACE flag.
(dir removed as i ran a local test)


text:
Q: phpMyDataGrid select field, dynamiclly make dropdown list menu from other tables I am using phpMyDataGrid , and I cannot make the dropdown list menu in a column.
$objGrid = new datagrid;
$objGrid->closeTags(true);
$objGrid->friendlyHTML();
$objGrid->methodForm("get");
$objGrid->conectadb("localhost", "root", "", "STEM_DB");
$objGrid->salt("Myc0defor5tr0ng3r-Pro3EctiOn");
$objGrid->language("en");
$objGrid->buttons(true,true,true,false);
$objGrid->Form('grant', true);
$objGrid->searchby("GrantName");
$objGrid->tabla ("GrantProgram");
$objGrid->keyfield("GrantID");
$objGrid->datarows(20);
$objGrid->orderby("GrantName", "ASC");
$objGrid->FormatColumn("GrantID", "Grant ID", 5, 5, 0, "5", "center", "integer");
$objGrid->FormatColumn("GrantName", "Grant Name", 20, 20, 0, "100", "center", "text");
$objGrid->FormatColumn("Funder", "Funder", 20, 20, 0, "100", "center", "text");

This line doesn't work:
$objGrid->FormatColumn("Personnel", "Personnel", 100, 100, 0, "100", "center","SELECT
* FROM Personnel");

I get the following error:

Warning: Invalid argument supplied for foreach() in /Applications/XAMPP/xamppfiles/htdocs/stem/phpmydatagrid.class.php on line 1079

line from 1077 to 1085 are following
                        case 'select':
                            $strInput.= "<select id='$fldname' class='dgSelectpage' >$br";
                            foreach ($selData as $key=>$value){
                                $selected=($value==$default)?"selected='selected'":"";
                                $strInput.= "<option value='$key' $selected. >$value</option>$br";
                            }
                            $strInput.= "</select>";
                            $campos[] = $fldname;
                        break;

And the FormatColumn() function is like this:
# FormatColumn: Define fields to show and their settings
function FormatColumn($strfieldName, $strHeader, $fieldWidth=0, $maxlength=0, $inputtype=0, $columnwidth=0, $align= 'center', $Mask='text', $default='', $cutChar=0){
    if ( $strfieldName=="" or !$this->validField( $strfieldName)){
        $mask = strtolower($Mask);
        $this->fieldsArray["$strfieldName"]["strfieldName"] = $strfieldName;          # Field Name
        $this->fieldsArray["$strfieldName"]["strHeader"]    = $strHeader;             # Title to show in top of grid
        $this->fieldsArray["$strfieldName"]["fieldWidth"]   = $fieldWidth;            # Input size
        $this->fieldsArray["$strfieldName"]["maxlength"]    = $maxlength;             # Input maxlength
        $this->fieldsArray["$strfieldName"]["columnwidth"]  = intval($columnwidth)."px"; # Column width
        $this->fieldsArray["$strfieldName"]["align"]        = $align;                 # Left, center, right, justify
        $this->fieldsArray["$strfieldName"]["mask"]         = $Mask;                  # Mask for data output
        $this->fieldsArray["$strfieldName"]["default"]      = $default;               # Default value for new records
        $this->fieldsArray["$strfieldName"]["select"]       = '';                     # Auxiliar field for data in masks (check, select)

        $this->fieldsArray["$strfieldName"]["cutChar"]      = $cutChar;               # Amount of chars to show.

        $datatype='text';
        if ($mask=='textarea') $datatype='textarea';
        if (substr($mask,0,5)=='image') $datatype='image';
        if (substr($mask,0,9)=='imagelink'){ $datatype='imagelink'; }
        $pmask = !(strpos($this->numerics,trim($mask)) === false);
        if (substr($mask,0,5)=='money' or $pmask)$datatype='number';
        if (substr($mask,0,4)=='date') $datatype='date';
        if (substr($mask,0,4)=='link') $datatype='link';
        if (substr($mask,0,4)=='calc') {$datatype='calc'; $this->hasCalcs = "true"; echo "<script type='text/javascript'> var thereisCalc = true;</script>";  $inputtype=3; }
        if (substr($mask,0,5)=='chart'){$datatype='chart'; $this->hasChart = true; $inputtype=5;
            if (strpos($mask,':') > 0) {
                $arrMask=explode(':',$Mask); $arrMask=array_slice($arrMask,1);
            }else{
                $arrMask=array("none:sum");
            }
            $this->fieldsArray["$strfieldName"]["select"] = $arrMask;
        }
        if (substr($mask,0,4)=='bool' or substr($mask,0,5)=='check'){ $datatype='check';
            if (strpos($mask,':') > 0) {
                $arrMask=explode(':',$Mask); $arrMask=array_slice($arrMask,1);
            }else{
                $arrMask=array($this->message['false'],$this->message['true']);
            }
            $this->fieldsArray["$strfieldName"]["select"] = $arrMask;
        }
        if (substr($mask,0,6)=='select'){ $datatype='select';
            $maskData = array();
            if (strpos($mask,':') >0 ){
                $mask=explode(':',$Mask);
                if (strtoupper(substr($mask[1],0,7)) == 'SELECT ') {                    #Select data from Table. Format [SELECT key, value FROM table]
                    if ($this->isADO){
                        if (($objResult = $this->connectionHandler->Execute($mask[1])) === false)
                                $this->SQLerror($mask[1],$this->connectionHandler->ErrorMsg());
                        while (!$objResult->EOF){
                            $arrResult = $objResult->fields;
                            $maskData[$arrResult[0]]=$arrResult[1];
                            $objResult->MoveNext();
                        }
                    }else{
                        $objResult = mysql_query($mask[1]) or $this->SQLerror($mask[1], mysql_error());
                        while ($arrResult = mysql_fetch_array($objResult))
                            $maskData[$arrResult[0]]=$arrResult[1];
                    }
                }else{                                                                  #literal select: keyfield must be of the same datatype as the list
                    $arrMask=array_slice($mask,1);
                    foreach ($arrMask as $ArrData)  {
                        $arrOptions = explode( '_', $ArrData);
                        $rowID = $arrOptions[0];
                        if (isset($arrOptions[1])) $rowName = $arrOptions[1]; else $rowName = $rowID;
                        $maskData[$rowID]=$rowName;
                    }
                }
                $this->fieldsArray["$strfieldName"]["select"] = $maskData;
            }
        }

Anybody can help? Thanks in advance

A: On phpmydatagrid, when using a query as data input mask, the statement shall follow the pattern bellow:
SELECT key, value FROM table

Besides that, the parameter shall have the "select:" prefix.
As an example, your statement should read:
$objGrid->FormatColumn("Personnel", "Personnel", 100, 100, 0, "100", "center","select:SELECT idPersonnel, name FROM Personnel");


text:
Q: How to use ggrepel to place data labels First is the sample data and some manipulations
  A<- c(150,125,0,-300,-350,-370)
  Series<-
  c("Construction","Manufacturing","Information","Health_Care","Education","Government")

  testdf <- data.frame(A,Series)

  jobgrowth<-ggplot(data=testdf, aes(y=A, x = reorder(Series,A))) +
  geom_col(color="blue") + coord_flip() +
  labs(x = NULL) + ggtitle("Interesting Title") +
  theme(plot.title.position = "plot",
      plot.title = element_text(hjust = 0.5))+

From looking around, I am finding that ggrepel is a good package for this (https://ggrepel.slowkow.com/articles/examples.html). However, my attempts result in an error
   Error: geom_text_repel requires the following missing aesthetics: label

So my question is where would insert the labels text and then how to get the data labels to fit on the right when the value is positive and on the left when it is negative? Construction, for example, would have 150 to the right of the bar.

A: You don't need ggrepel. ggrepel is an excellent choice if you have to deal with overlapping labels. However, in case of your bar chart I would suggest to go with default geom_text like so:
Using ifelse you can

*

*set hjust to right or left align your labels

*add some space between the bars and the labels

A <- c(150, 125, 0, -300, -350, -370)
Series <-
  c("Construction", "Manufacturing", "Information", "Health_Care", "Education", "Government")

testdf <- data.frame(A, Series)

library(ggplot2)

ggplot(data = testdf, aes(y = A, x = reorder(Series, A))) +
  geom_col(color = "blue") +
  coord_flip() +
  scale_y_continuous(expand = expansion(mult = 0.5)) +
  geom_text(aes(label = A, hjust = ifelse(A > 0, 0, 1), y = A + ifelse(A > 0, 10, -10))) +
  labs(x = NULL) +
  ggtitle("Interesting Title") +
  theme(
    plot.title.position = "plot",
    plot.title = element_text(hjust = 0.5)
  )


text:
Q: Sharing cookies across .test sub-domains in Safari 13 not possible I have a self-certificate for apache for https://example.test & https://m.example.test
When browsing https://m.example.test cookies are set to the base domain '.example.test' using php 'session.cookie_domain'. This DOES work in Chrome, Firefox or Safari up-to-version-12.
However, it does not work anymore in Safari 13 (iOS 13 or Catalina).
What's even more strange is that the cookie is still set to the base domain on Safari 13 with my production machine for https://example.COM & https://m.example.COM
I have the same apache server configuration for both the COM and TEST servers. It simply stopped working on my development ".test" server after updating my iOS devices to iOS 13 or in MacOS after Catalina. Chrome, Firefox still work. Even old iOS devices connecting to my development machine (through a proxy) still store the cookie to the base domain ".example.test". So it looks like it is something specific to Safari 13 and only in ".test" domains.
I have created new certificates for my .TEST server using latest recommendations from Apple (max 825 days and so on) but it did not make any difference. It looks like something may have changed with self-signed certificates. Or perhaps a new rule exists for ".test" (not public) domains? It's something either specific to Safari, ".test" not-public-domains or certificates. Or something else I did not even think about.
Any idea how to configure Apache/Macosx/certificates so that I can still share a cookie across subdomains using Safari 13 in development .test domains? Thanks.

A: This is not an issue with certificates, but it seems to be a difference in how Safari parses the .test TLD.
We solved this by setting the cookie explicitly for each subdomain we need. In our Rails app, in the development environment, we set up the session store like this:
config.session_store(
  :active_record_store,
  key: 'our_app_session',
  domain: ['ourapp.test', 'api.ourapp.test', 'help.ourapp.test']
)

If you can figure out the way to do the same thing in your backend, you should be able to use the same cookie for your different .test subdomains.

A: I had the same problem with wildcard subdomains and cookies for the .test tld. It worked in Chrome, but Safari 13 did not set the cookie.
My workaround was to use .local instead. This worked in Safari too.
(Specifying each subdomain separately like @gueorgui suggested does not work as expected, because the browser will set a separate cookie for each subdomain)


text:
Q: Delete docker specific images I need some kind of Docker behaviour. Imagine docker image name is imagename and image also have tag(1, 2, 3 ...). Now I want to delete all images with the name imagename and with the tag that isn't x. For example if I have images:
imagename:1
imagename:2
imagename:3
imagename:4
imagename:5
imagename:6

with 1, 2, 3 ...6 tags, and I want to have only one Image with name imagename and tag 6, what command should I run?

A: I don't think it's possible with the docker command alone. I would use a small shell loop. For example remove every python image which is not tagged 3.6:
docker images | awk -v img='python' -v tag='3.6' '$1==img && $2!=tag{print $3}' \
  | while read -r id ; do docker rmi "${id}" ; done


text:
Q: Cascade delete all children using Entity Framework Core with One-to-Many and Many-To-Many relationships I have following simplified schema for a .net core 2 with entity framework core solution:
           1+--------+1
    +-------+Blogs   +-------+
    |       +--------+       |
   *|                        |*
+--------+             +----------+
|Posts   |             |Tags      |
+--------+             +----------+
    |1                      1|
    |   *+-------------+*    |
    +----+PostTags    |------+
         +-------------+

With following models:
public class Blog
{
    public int Id { get; set; }

    public ICollection<Post> Posts { get; set; }
    public ICollection<Post> Tags { get; set; }
}

public class Post
{
    public int Id { get; set; }

    public Blog Blog { get; set; }
    public ICollection<PostTag> PostTags { get; set; }
}

public class Tag
{
    public int Id { get; set; }

    public Blog Blog { get; set; }
    public ICollection<PostTag> PostTags { get; set; }
}

public class PostTag
{
    public int PostId { get; set; }
    public Post Post { get; set; }

    public int TagId { get; set; }
    public Tag Tag { get; set; }
}

And the corresponding DbContext:
public class DataDbContext : DbContext
{
    public DbSet<Blog> Blogs { get; set; }
    public DbSet<Post> Posts { get; set; }
    public DbSet<Tag> Tags { get; set; }
    public DbSet<PostTag> PostTags { get; set; }
}

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<PostTag>()
        .HasKey(u => new { pt.TagId, pt.PostId });

    modelBuilder.Entity<PostTag>()
        .HasOne(pt => pt.Post)
        .WithMany(p => p.PostTags)
        .HasForeignKey(pt => pt.PostId)
        .OnDelete(DeleteBehavior.Cascade)
        .IsRequired();

    modelBuilder.Entity<PostTag>()
        .HasOne(pt => pt.Tag)
        .WithMany(t => t.PostTags)
        .HasForeignKey(pt => pt.TagId)
        .OnDelete(DeleteBehavior.Cascade)
        .IsRequired();
}

The cascade delete works, but leaves Tags with blog nulled. If I [Require] the blog in Tag, I receive a circular constraint error.
I think I just found the answer myself:

"In SQL Server, a table cannot appear more than one time in a list of
  all the cascading referential actions that are started by either a
  DELETE or an UPDATE statement. For example, the tree of cascading
  referential actions must only have one path to a particular table on
  the cascading referential actions tree

from weblogs.asp.net
Is there an elegant solution for this in EF Core to ensure all Tags and Posts get deleted as soon as a Blog is being deleted?

A:
Is there an elegant solution for this in EF Core to ensure all Tags and Posts get deleted as soon as a Blog is being deleted?

Your two options are:
1) Have a Posts->PostTags cascade delete and Blogs-> BlogTags cascade delete, and delete all the Blog's posts first, then delete the blog.
2) Write an INSTEAD OF DELETE trigger on Blogs to delete the related Posts and BlogTags before deleting the Blog.


text:
Q: Python Numpy - Treat really small numbers as zero I want to calculate the Determinant of a Singular Matrix (which has a 0 determinant) with Numpy and when I print the determinant it shows a really small number (which is nearly zero = -7.09974814699e-30) but not zero itself...
when I try to print the determinant either with %s, %d or %f, sometimes it's zero, sometimes -0 and sometimes -7.09974814699e-30 .
Here's the Code :
import numpy as np

array = np.arange(16)
array = array.reshape(4, -1)
determinant = np.linalg.det(array)

print("Determinant is %s" % determinant)
print("Determinant is %d" % determinant)
print("Determinant is %f" % determinant)

Determinant is -7.09974814699e-30
Determinant is 0
Determinant is -0.000000

How can I make Numpy treat really small numbers such as -7.09974814699e-30 as zero and show zero to me. I also asked this question before, if you take a look at the matrix you see that it's filled with really small numbers but not zero while it should be a diagonal matrix with numbers on the diagonal and zeros elsewhere...
Thank you...

A: >>> if np.abs(determinant) < 0.000001:
...     determinant=0
...
>>> print determinant
0

In case of array you can do it using a single operation (see my answer to your other question: https://stackoverflow.com/a/36395905/5088142)
To set array elements that are less than eps to zero:
array[np.abs(array) < eps] = 0

A: You can troncate less significant digits with np.round . But it's better do keep  accuracy for float arithmetic. What you have to control is just the format of the final output, with the str.format function.
In [7]: a=rand(12,12)
In [8]: deta=det(a)
#0.0063854296972496311

In [10]: detar=det(a.round(3))
# 0.0063817871557592153

In [12]: '{:.5f}'.format(deta)
Out[12]: '0.00639'

In [13]: '{:.5f}'.format(detar)
Out[13]: '0.00638'

Last line shows a false result due to earlier optimisation.

A: Use numpy.set_printoptions and enable the suppress option:
>>> import numpy as np
>>> np.set_printoptions(precision=3, suppress=True)
>>> array = np.arange(16)
>>> array = array.reshape(4, -1)
>>> determinant = np.linalg.det(array)
>>> print("Determinant is:", determinant)
Determinant is: 0.0

A: I am using Python 2.7.11 |Anaconda custom (x86_64)| (default, Dec  6 2015, 18:57:58) IPython 4.0.3 -- An enhanced Interactive Python. and I got results as below,
In [6]: print("Determinant is %s" % determinant)
Determinant is 0.0

In [7]: print("Determinant is %d" % determinant)
Determinant is 0

In [8]: print("Determinant is %f" % determinant)
Determinant is 0.000000

I think if you update numpy it might fit it for you else you use below approach
In [9]: sam = 0.000000121

In [10]: sam
Out[10]: 1.21e-07

In [11]: print sam if sam > 0.00001 else 1
1

This does not exactly answer your question "How can I make Numpy treat really small numbers such as -7.09974814699e-30 as zero and show zero to me.", I think you do work around for this.
In general as it comes to floats/exponents, calculations beyond certain point carry minor error,.. for example by your e power -30 case. So if you are using high level floats or exponents it better you expect some error.


text:
Q: Why should I avoid creating gitignore and README on GitHub I forget what docs I read but one of them says not to create the readme and gitignore files in the Create Repository form on GitHub.  Does anyone know WHY?  Why they state it causes problems, in what circumstances and how does it cause issues?

A: The problem arises when you want to create a new repository on GitHub to contain an existing repository. Consider the following:

*

*You create a local repository with git init and commit some work:
[master] A---B---C

*You create a remote home for it on GitHub, letting GitHub create some files:
[master] Z

In this case, GitHub creates a commit Z in which the README.md and .gitignore files are committed.

*You run git push -u origin master to push your local changes up to GitHub, but it fails.
Since your local copy lacks the commit Z, Git cannot accept your push as a fast-forward update.
You are now forced to do something like

*

*fetch Z, rebase your local copy onto it, and push again, or

*force push, which will cause that commit to be lost on GitHub.

There's nothing wrong with creating .gitignore and README.md in the new repository wizard for new repositories. In this case you will

*

*create the GitHub repository, letting GitHub create these two files, and then

*clone that repository to your local machine.

You'll end up with a local copy containing those files.


text:
Q: Google Drive: Disable "Open with" our app from Google Drive dashboard We have a Google Drive integrated app (marqueed.com) that allows you to authenticate and upload your Google Drive images from inside our app.
However, we don't want Google Drive users to be able to open files ("Open with") our Marqueed app from the Google Drive dashboard:

We don't want our app to show up in the above screenshot, is there a way to do this?

A: Your application shows up in the Open With menu for those files whose MIME types or extensions are listed in the Drive SDK tab of the APIs Console: https://code.google.com/apis/console/
Just remove those values from both Default and Secondary MIME Types and Extensions and your application will not show up anymore.
For more details, check the documentation at https://developers.google.com/drive/register#setting_mime_types_and_extensions


text:
Q: Cant create a record within viewset custom view based on url parameters Hello I have a django rest framework view set. For the create view I want to create a custom view that will create a new record based on two different parameters that are passed on through the url which are namespace and path. I looked at the documentation but i couldnt find how it should look like. I am noit sure what I need to do in order to create a record based on both url parameters.
I basically tried setting the create to a CreateAPIView but it did not work
class PreferenceViewSet(viewsets.ViewSet):
    queryset = Preference.objects.all()
    serializer_class = PreferenceSerializer

    def get_permissions(self):
        if self.action == 'create' or self.action == 'destroy':
            permission_classes = [IsAuthenticated]
        else:
            permission_classes = [IsAdminUser]
        return [permission() for permission in permission_classes]

    def list(self, request):
        queryset = Preference.objects.all()
        serializer = PreferenceSerializer(queryset, many=True)
        return Response(serializer.data)

    def create(self, request):
        queryset = Preference.objects.all()
        serializer = PreferenceSerializer(queryset, many=True)
        return Response(serializer.data)

I want to setup the create to create a preference with the two parameters that are passe in the url
path('preferences/<str:namespace>/<str:path>', preference_path, name='preference-path'),

I wanted it to create a new object with the namespace and path

A: You need to do this in 2 steps:

*

*Add the url arguments to serializer context from viewset

*Override create method on the serializer and use data passed on the context to create the record

So, at first override get_serializer_context method to add the arguments to context:
class PreferenceViewSet(viewsets.ViewSet):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self._namespace = None
        self._path = None
    ...
    ...

    def get_serializer_context(self):
        context = super().get_serializer_context()
        context.update(namespace=self._namespace, path=self._path)
        return context

    def create(self, request):
        self._namespace = self.kwargs['namespace']
        self._path = self.kwargs['path']

        queryset = Preference.objects.all()
        serializer = PreferenceSerializer(queryset, many=True)
        return Response(serializer.data)

Now, you can access the parameters inside the overriden create method of the serializer and create the record as you want e.g.:
class PreferenceSerializer(serializers.HyperlinkedModelSerializer):
    ...
    ...
    def create(self, validated_data):
        namespace = self.context['namespace']
        path = self.context['path']
        # Create object here based on the params


text:
Q: Why does my bootstrap grid looks different on stackoverflow and on localhost? I clicked on "external library" and added the bootstrap library, but as you can see if you click on the run button, the rows are not displayed in one row.

/* Optional theme */
@import url('//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap-theme.min.css');

div {
  border: 1px solid red;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>

        Text

        Text

        Text

If i execute the same code on my local machine then it looks like this:

A: That's because the view your looking at is too small and as bootstrap works it's getting re-sized one at a line. If you take a look in the full page view, you will see the following image :


text:
Q: Prices not matching up with items when printing price+item name data collected from Amazon from argparse import Action
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.common.action_chains import ActionChains
import time
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import sys
from selenium.webdriver.chrome.options import Options
import os
from selenium.webdriver.chrome.service import Service

product = input('Item: ')

PATH = r"C:\Users\raymo\Documents\Coding-Programs\chromedriver.exe"
s=Service(PATH)
driver = webdriver.Chrome(service=s)
driver.get('https://www.amazon.ca/ref=nav_logo')

total_prices = []
temp_list = []
temp_item_names = []
item_names = []
sorted_prices = []

try:
    element = WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.XPATH,'//*[@id="twotabsearchtextbox"]'))
    )
finally:
    search = driver.find_element(By.XPATH, '//*[@id="twotabsearchtextbox"]')
    search.send_keys(product)
    search.send_keys(Keys.RETURN)
    try:
        element = WebDriverWait(driver, 10).until(
            EC.presence_of_element_located((By.CLASS_NAME, "a-price-whole"))
        )
    finally:
        temp_prices = driver.find_elements(By.CLASS_NAME, 'a-price-whole')
        try:
            element = WebDriverWait(driver, 10).until(
                EC.presence_of_element_located((By.CSS_SELECTOR, '.a-size-base-plus.a-color-base.a-text-normal'))
            )
        finally:
            raw_item_names = driver.find_elements(By.CSS_SELECTOR, '.a-size-base-plus.a-color-base.a-text-normal')

            #converts from web element to string values
            for k in range(len(raw_item_names)):
                temp_item_names.append(raw_item_names[k].text)

            for i in range(len(temp_prices)):
                num = (temp_prices[i].text)
                edited_num = num.replace(",",'')
                temp_list.append(edited_num)
            print(temp_list)

            #To filter outliers that probably aren't the right product
            for i in range(len(temp_list)):
                try:
                    p = float(temp_list[i])
                    if i > 0:
                        #If the price is within an acceptable range from the most relevant result
                        if p >= total_prices[0]*0.1:
                            item_names.append(temp_item_names[i])
                            total_prices.append(p)
                    else:
                        item_names.append(temp_item_names[i])
                        total_prices.append(p)
                except:
                    None
            for u in range(len(total_prices)-1):
                sorted_prices.append(total_prices[u])
            sorted_prices.sort()

sum = 0

for a in range(len(total_prices)):
    print(f'{item_names[a]} ${total_prices[a]}')

for j in range(len(total_prices)):
    sum = sum + total_prices[j]

average = round(sum/len(total_prices), 2)
print(f'The average price of {product} on amazon.ca is ${average}')

lowest_price = round(sorted_prices[0],2)
highest_price = round(sorted_prices[len(sorted_prices)-1], 2)
print(f'The lowest price of {product} on amazon.ca is ${lowest_price}')
print(f'The highest price of {product} on amazon.ca is ${highest_price}')

driver.quit()

I can't seem to figure out why the end item names and the prices don't match up when the data is outputted. I ran some debugging tests and the amount of items and prices match up, and theoretically since I only add items to the outputted lists if they meet the requirement of not being an outlier in terms of price, then the item and price should match up since item[i] should match with price[i]...?


text:
Q: Updating a Google App Engine module When I try to update my Google App Engine module, I get an error saying that the name and version are already in use (which they are, I'm trying to UPDATE). I've tried updating the whole EAR as well as just the module that I want to update, but both result in the same errors:
Unable to update:
com.google.appengine.tools.admin.HttpIoException: Error posting to URL: https://appengine.google.com/api/appversion/create?module=stomp&app_id=<my_app_id>&version=stomp&
400 Bad Request
Version 'stomp' is already in use as a module name. Please use a different version.

    at com.google.appengine.tools.admin.AbstractServerConnection.send1(AbstractServerConnection.java:293)
    at com.google.appengine.tools.admin.AbstractServerConnection.send(AbstractServerConnection.java:253)
    at com.google.appengine.tools.admin.AbstractServerConnection.post(AbstractServerConnection.java:232)
    at com.google.appengine.tools.admin.AppVersionUpload.send(AppVersionUpload.java:973)
    at com.google.appengine.tools.admin.AppVersionUpload.beginTransaction(AppVersionUpload.java:645)
    at com.google.appengine.tools.admin.AppVersionUpload.doUpload(AppVersionUpload.java:147)
    at com.google.appengine.tools.admin.AppAdminImpl.doUpdate(AppAdminImpl.java:445)
    at com.google.appengine.tools.admin.AppAdminImpl.update(AppAdminImpl.java:55)
    at com.google.appengine.tools.admin.AppCfg$UpdateAction.execute(AppCfg.java:1339)
    at com.google.appengine.tools.admin.AppCfg.executeAction(AppCfg.java:325)
    at com.google.appengine.tools.admin.AppCfg.<init>(AppCfg.java:211)
    at com.google.appengine.tools.admin.AppCfg.<init>(AppCfg.java:122)
    at com.google.appengine.tools.admin.AppCfg.main(AppCfg.java:118)
com.google.appengine.tools.admin.AdminException: Unable to update app: Error posting to URL: https://appengine.google.com/api/appversion/create?module=stomp&app_id=<my_app_id>&version=stomp&
400 Bad Request
Version 'stomp' is already in use as a module name. Please use a different version.

    at com.google.appengine.tools.admin.AppAdminImpl.doUpdate(AppAdminImpl.java:451)
    at com.google.appengine.tools.admin.AppAdminImpl.update(AppAdminImpl.java:55)
    at com.google.appengine.tools.admin.AppCfg$UpdateAction.execute(AppCfg.java:1339)
    at com.google.appengine.tools.admin.AppCfg.executeAction(AppCfg.java:325)
    at com.google.appengine.tools.admin.AppCfg.<init>(AppCfg.java:211)
    at com.google.appengine.tools.admin.AppCfg.<init>(AppCfg.java:122)
    at com.google.appengine.tools.admin.AppCfg.main(AppCfg.java:118)
Caused by: com.google.appengine.tools.admin.HttpIoException: Error posting to URL: https://appengine.google.com/api/appversion/create?module=stomp&app_id=<my_app_id>&version=stomp&
400 Bad Request
Version 'stomp' is already in use as a module name. Please use a different version.

    at com.google.appengine.tools.admin.AbstractServerConnection.send1(AbstractServerConnection.java:293)
    at com.google.appengine.tools.admin.AbstractServerConnection.send(AbstractServerConnection.java:253)
    at com.google.appengine.tools.admin.AbstractServerConnection.post(AbstractServerConnection.java:232)
    at com.google.appengine.tools.admin.AppVersionUpload.send(AppVersionUpload.java:973)
    at com.google.appengine.tools.admin.AppVersionUpload.beginTransaction(AppVersionUpload.java:645)
    at com.google.appengine.tools.admin.AppVersionUpload.doUpload(AppVersionUpload.java:147)
    at com.google.appengine.tools.admin.AppAdminImpl.doUpdate(AppAdminImpl.java:445)
    ... 6 more

A: I think it is complaining that both the module and version share the same name 'stomp', try using different version and module names.
I have not yet found this documented in the App Engine documentation, but it appears to be a restriction that you cannot have a module name the same as its version name, for example a module with this yaml file will not be updatable:
application: my-app-id
version: test
module: test
runtime: python27
api_version: 1
threadsafe: true

Although you will be able to run an update, to upload the initial version of your module, when you try to update it a second time it will fail with this error:
Error 400:
--- begin server output ---
Version 'test' is already in use as a module name. Please use a different version.
--- end server output ---


text:
Q: Building insert string to sql has problems from CSV/Json I'm trying to build a string from a .CSV file. I convert it to Json and want to build an insert statement to my SQL Server.
I'm using ChoETL nuget to convert from csv to json.
When I build my string I get this:
Insert into dbo.JsonMeta (Json) values('{
  "ID": "xxxxx",
  "FLYTTEDATO": "01/02/2020",
  "FLYTTE_TIDSPUNKT": "1000'"
}')

As you can see after the 1000 digit. There is a ' character. And this makes my string cause an error, because it ends the string.
How can I remove this ' character or do something smart?

A: Once you have a JSON string, don't paste it into a SQL statement.  Use a parameter instead.
This solves your problem, and protects you from SQL injection attacks.
Insert into dbo.JsonMeta (Json) values(@json)

A: Just escape it with another single quote, right next to it. You would still retain that single quote in the data.
Insert into dbo.JsonMeta (Json) values('{
  "ID": "xxxxx",
  "FLYTTEDATO": "01/02/2020",
  "FLYTTE_TIDSPUNKT": "1000''"
}')


text:
Q: Bluetooth LE on iOS cannot work with many services and characteristics I develop a BLE application, using Core Bluetooth in my iPhone app.
My iPhone communicates with linux with bleno launched.
The problem is that it cannot work with more than one characteristic or service, though just one characteristic works nice.
Here is my code for iOS and .js code for Node.js:
http://pastebin.com/k5pUrbLt
http://pastebin.com/biCWLmJ3
Thank you!
P.S. That's what i get in console:

2014-07-24 13:18:02.819 lexy[142:60b] didDiscoverPeripheral

2014-07-24 13:18:04.503 lexy[142:60b] didDiscoverServices

2014-07-24 13:18:04.506 lexy[142:60b] D61191C0-FCE8-4F5A-912C-15EE39D927B4

I.e. I successfully discover and connect to the peripheral, but I do not find any characteristics. In that case I have one service with many characteristics.

A: iOS can work with multiple characteristics and multiple services on a remote device.
Your ObjC code seems okay (1 service with 2 characteristics).
Console output suggests that you send a discoverCharacteristics request but that it hangs and never returns. You could add logging to the didDisconnectPeripheral delegate method to see if there is a disconnect happening.
What you could also do is to look at the logs of the Bluetooth stack and to compare them to how the logs look like if you access a TI Sensor Tag (those tags are the hello world of BLE).
iOS 7.1 instructions for Bluetooth logs are located here, for iOS 8 you'll have to resort to Apple's official way to get the logs (installation of a configuration profile) but their logs contain less information than the ones by BluetoothCompanion.

A: Apparently, it works on Ubuntu 14.04, but doesn't work on OpenSuse 13.1.


text:
Q: Compactness in $L^p([a,b])$ Consider $\Omega$ an open non-empty set of $\mathbb{R}^n$; We know that $(L^p(\Omega),\left\lVert \cdot\right\rVert_{L^p})$ is an infinite dimensional vector space, thus thanks to Riesz's lemma we know that the closed unit ball $B_{L^p}$ is not compact (with respect to $\left\lVert \cdot\right\rVert_{L^p}$).
Let $\Omega=(0,1)$: I'm wondering if $B_{L^2((0,1))}$ is relatively compact in $(L^1((0,1),\left\lVert \cdot\right\rVert_{L^1}$).
I'm asking directly the "relactive compactness" because, if I'm not wrong, $B_{L^2((0,1))}$ is not closed in $(L^1((0,1)),\left\lVert \cdot\right\rVert_{L^1})$.
I know, thanks to a corollary of Riesz-Frechet-Kolmogorov theorem, that if $B_{L^2((0,1))}$ is bounded, and it holds that, for every $f\in B_{L^2((0,1))}$,     $$\lim_{v\rightarrow 0} \left\lVert \tau_v\hat{f}-\hat{f}\right\rVert_{L^1}=0,$$
where $\hat{f}$is the extension of $f$ to the whole $\mathbb{R}$ ($0$ outisde $(0,1)$), $v\in\mathbb{R}$ and $\tau_v(f)(x)=f(x+v)$, then $B_{L^2((0,1))}$ is relatively compact in $(L^1((0,1),\left\lVert \cdot\right\rVert_{L^1})$.
I studied this theorem, but apart from remembering the claim I have no idea how to check these properties: I have the feeling this set is at least bounded, but again, no idea on how to prove it. This whole question is probably nonsense since it was my thought and not an exercise.
Any hint or solution would be much appreciated... Thanks in advance.

A: The $f_n: t \longmapsto e^{2i\pi nt}$ are in $B_{L^2}$, and converge weakly as $L^1$ functions to zero: however, their $L^1$ norm is $1$ so there isn't any convergent subsequence.


text:
Q: Android Geofencing - No coming intents? I have a strange problem.
I implemented geofencing using Google Services. (Implementation below)
On my devices (Samsung Galaxy S and Moto X) they work perfect. On some other devices (HTC Incredible S, Galaxy Note), I receive no transition intents. Never. With great, accurate GPS fix, standing in the middle of fence. Nothing. Nothing suspicious in logs. No errors, no warnings. No itents come, the service does not start.
Have anyone ever seen such a thing? (It is weird because I can't see any connection between devices which work and devices that does not. It's not manufacturer, it's not Android version, Play Services were up to date on all of them.)
Implementation:
Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="test.package"
android:installLocation="auto"
android:versionCode="17"
android:versionName="1.1" >

<uses-sdk
    android:minSdkVersion="7"
    android:targetSdkVersion="19" />

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-feature android:name="android.hardware.sensor.accelerometer" android:required="true" />

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >

    <activity
        android:name="test.package.MainActivity"
        android:label="Compass"
        android:screenOrientation="portrait" />

    <service android:name="test.package.services.geofences.ShowNotificationService"
            android:label="@string/app_name"
            android:exported="false"/>

    <receiver android:name="test.package.services.geofences.UpdateGeofences">
        <intent-filter>
            <action android:name="test.package.updateGeofecnes"/>
            <action android:name="android.intent.action.BOOT_COMPLETED" />
        </intent-filter>
    </receiver>

Update Geofences:
 public class UpdateGeofences extends BroadcastReceiver implements
        GooglePlayServicesClient.ConnectionCallbacks,
        GooglePlayServicesClient.OnConnectionFailedListener,
        LocationClient.OnAddGeofencesResultListener,
        DataUpdateCallback {

    private LocationClient mLocationClient;
    private Context ctx;

    @Override
    public void onReceive(Context context, Intent intent) {
        Log.d("NOTICE", "Updating Geofences");
        ctx = context;
        mLocationClient = new LocationClient(context, this, this);
        mLocationClient.connect();
    }

    @Override
    public void onConnected(Bundle bundle) {
        GeofenceProvider geofenceProvider = new GeofenceProvider(ctx);
        geofenceProvider.open();

        //reactivate geofences
        List<Geofence> geofences = geofenceProvider.getActiveGeofences(mLocationClient.getLastLocation());
        Intent intent = new Intent(ctx, ShowNotificationService.class);
        PendingIntent pendingIntent = PendingIntent.getService(ctx, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        if (geofences.size() > 0) mLocationClient.addGeofences(geofences, pendingIntent, this);
        else mLocationClient.disconnect();
    }

    @Override
    public void onAddGeofencesResult(int i, String[] strings) {
        // If adding the geofences was successful
        if (LocationStatusCodes.SUCCESS != i) {
            Log.e("Geofences", "Error adding geofences: "+ Arrays.toString(strings)+ " Code: "+i);
        }
        mLocationClient.disconnect();
    }
}

Show notification service:
    public class ShowNotificationService extends IntentService {

    public ShowNotificationService() {
        super("ReceiveTransitionsIntentService");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        Log.d("NOTICE", "Android geofence notification!");
        if (LocationClient.hasError(intent)) {
            int errorCode = LocationClient.getErrorCode(intent);
            Log.e("ReceiveTransitionsIntentService", "Location Services error: " + Integer.toString(errorCode));
            Crashlytics.logException(new RuntimeException("Location Services error: "+errorCode));
        } else {
            int transitionType = LocationClient.getGeofenceTransition(intent);
            if (transitionType == Geofence.GEOFENCE_TRANSITION_ENTER) { //ak vstupujem pozriem sa ci uz sa mi to nevyhodilo dnes
                List<Geofence> triggerList = LocationClient.getTriggeringGeofences(intent);
                Log.d("NOTICE", "Transition Enter");
                GeofenceProvider mProvider = new GeofenceProvider(this);
                mProvider.open();
                try {
                    for (Geofence geofence : triggerList) {
                        String id = geofence.getRequestId();
                        String[] data = id.split(MyGeofence.delimiter);
                        Log.d("NOTICE", "Show notification: "+id);
                        if (data.length != 3) {
                            Crashlytics.logException(new RuntimeException("Invalid geofence id: " + id + "Data: "+ Arrays.toString(data)));
                            continue;
                        }
                        if (mProvider.updateLastFire(Integer.valueOf(data[2]))) {
                            NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
                            builder.setContentTitle(data[0]);
                            builder.setContentText(data[1]);
                            builder.setSmallIcon(R.drawable.noticon);
                            Intent result = new Intent(this, CompassActivity.class);
                            PendingIntent pendingResult = PendingIntent.getActivity(this, 0, result, PendingIntent.FLAG_UPDATE_CURRENT);
                            builder.setContentIntent(pendingResult);
                            builder.setOngoing(false);
                            builder.setAutoCancel(true);
                            Notification not = builder.build();
                            not.defaults = Notification.DEFAULT_ALL;
                            NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
                            int notID = Integer.valueOf(data[2]);
                            mNotificationManager.notify(notID, not);
                        }
                    }
                } catch (Exception e) {
                    Crashlytics.logException(e);
                    e.printStackTrace();
                } finally {
                    mProvider.close();
                }

            } else if(transitionType == Geofence.GEOFENCE_TRANSITION_EXIT) {    //ak odchadzam, oznacim to patricne v db
                List<Geofence> triggerList = LocationClient.getTriggeringGeofences(intent);
                Log.d("NOTICE", "Transition leave");
                GeofenceProvider mProvider = new GeofenceProvider(this);
                mProvider.open();
                try {
                    for (Geofence geofence : triggerList) {
                        String id = geofence.getRequestId();
                        String[] data = id.split(MyGeofence.delimiter);
                        if (data.length != 3) {
                            Crashlytics.logException(new RuntimeException("Invalid geofence id: " + id + "Data: "+ Arrays.toString(data)));
                            continue;
                        }
                        mProvider.invalidateLastFire(Integer.valueOf(data[2]));
                        Log.d("NOTICE", "Invalidate last fire: "+id);
                    }
                } catch (Exception e) {
                    Crashlytics.logException(e);
                    e.printStackTrace();
                } finally {
                    mProvider.close();
                }

            } else {    // An invalid transition was reported
                Log.e("ReceiveTransitionsIntentService", "Geofence transition error: " + Integer.toString(transitionType));
                Crashlytics.logException(new RuntimeException("Invalid geofence transition"));
            }
        }
    }
}

In UpdateGeofences I omitted methods required to connect to PlayServices, since they are basically copied from demo app and I am using them successfully in other places...
Main activity is irrelevant, it just sends broadcast to start UpdateGeofences every time it starts.
GeofenceProvider is also isn't a problem, I am using same code elsewhere with no problems.

A: Eventualy, I managed to fix this by setting exported="true" in ShowNofiticationService.
Like this:
<service android:name="test.package.services.geofences.ShowNotificationService"
        android:label="@string/app_name"
        android:exported="true"/>

It seems the intents were fired by process with wrong id, and that coused security error. Not sure why would that happen, though...


text:
Q: Add item to property with an array value in specialized component Let's say I have the following component in React
const SpecializedTextField= props => {
    return (
        <TextField
            {...props}
            validate={[isNumber, isPositiveNumber]}
        />

    );
};

And I want to add another validation to the validate prop:
<SpecializedTextField validate={[isRequired]} />
That would add the validation to the TextField so it would result in validate={[isRequired, isNumber, isPositiveNumber]}
Of course i could just retrieve both arrays and merge them. But is there a clean way (some sort of syntactic sugar) to append the two properties together in es6/react?

A:
Of course i could just retrieve both arrays and merge them.

That's pretty much what you need to do, but it's pretty concise with spread notation:
const SpecializedTextField= props => {
    const {validate = [], ...other} = props;
    return (
        <TextField
            {...other}
            validate={[isNumber, isPositiveNumber, ...validate]}
        />

    );
};

Of course, that assumes that either you won't get isNumber or isPositive in the validate prop, or that having duplicates isn't a problem. It also creates and spreads a blank array if there's no validate prop given.
If those assumptions are invalid and/or creating and spreading the blank array bothers you (it would me, micro-opt or not), you'll need to build a unique set, which you could do yourself or via Set. Perhaps:
const specializedTextFieldValidations = [isNumber, isPositiveNumber];
const SpecializedTextField = props => {
    let {validate = specializedTextFieldValidations, ...other} = props;
    if (validate !== specializedTextFieldValidations) {
        validate = [...new Set([...specializedTextFieldValidations, ...validate]).values()];
    }
    return (
        <TextField {...other} validate={validate} />
    );
};

(It's too bad the Set constructor only accepts a single Iterable rather than a variable number of them...)
Speaking of micro-optimization, it would appear that spread is currently  much slower than concat, so
validate = [...new Set([...specializedTextFieldValidations, ...validate]).values()];

may be better written as
validate = [...new Set(specializedTextFieldValidations.concat(validate)).values()];

A: In addition to @T.J. Crowder's answer, you don't need to destructure props to extract validate and other. validate prop has the same name and will be overriden due to attribute order in jsx:
const SpecializedTextField= props => {
    return (
        <TextField
            {...props}
            validate={[...props.validate, isNumber, isPositiveNumber]}
        />
    );
};

SpecializedTextField.defaultProps = {
    validate: [],
};


text:
Q: rspec it block inside loop I want to test that every link on a page returns a certain status code. I have a working test, something like this:
it "does not throw 400/500 error for any link" do
  visit '/'
  within(".wrapper") do
    all('a').each do |link|
      http_status = Faraday.head(link[:href].to_s).status
      puts "#{link.text}, #{http_status}"
      expect((400..500)).not_to include(http_status)
    end
  end

However this is pretty terrible for output since all the links are checked in one test (hence the puts inside the test to show me which link breaks the test). I would like to be able to have a separate test for each link, without manually writing a test for every single link on the page.
I tried this:
context "does not throw 400/500 error for any link" do
  visit '/'
  within(".wrapper") do
    all('a').each do |link|
      it "does not throw 400/500 error for #{link}" do
        link_status_code_is_not(link, (400..500))
      end
    end
  end
end

and got this error
`visit` is not available on an example group (e.g. a `describe` or
`context` block). It is only available from within individual examples
(e.g. `it` blocks) or from constructs that run in the scope of an
example (e.g. `before`, `let`, etc).

so i tried moving the visit to a before hook but got the same issue with the within block (which I can't really move). I've been able to do something like this in jasmine, but I can't seem to find a way to do it in rspec.
tl:dr; Is there any way to put an it block inside a loop in rspec?

A: You can create an it block inside of a loop:
RSpec.describe "numbers" do
  [*1..10].each do |number|
    it "#{number} should not be multiple of 10" do
      expect(number % 10).not_to be_zero
    end
  end
end

Your problem though is it doesn't look like you can visit outside of an it block (or "constructs that run in the scope of an example") and you need to grab your data from a page that you visit and loop through and create it blocks from that data. I'm not sure if that can be done nicely.
If what you're wanting is just better output for your links, you can use aggregate_failures along with Customized messages to provide a better output for your test. For a contrived example, let's say I have a ton of dynamic, only available within it blocks or from constructs that run in the scope of an example, pairs of numbers and I need to make sure none of their products are multiples of 10:
RSpec.describe "numbers" do
  it "are not a multiple of 10" do
    [*1..10].product([*1..10]).each do |base, multiplier|
      expect((base * multiplier) % 10).not_to be_zero
    end
  end
end

The output here isn't very good, it just tells me expected 0.zero? to return false, got true, not which pair of numbers failed. By using the aggregate failures and a custom message though, I can fix that:
RSpec.describe "numbers" do
  it "are not a multiple of 10" do
    aggregate_failures do
      [*1..10].product([*1..10]).each do |base, multiplier|
        expect((base * multiplier) % 10).not_to be_zero, "#{base} * #{multiplier} is a multiple of 10"
      end
    end
  end
end

Now, I get only 1 failure reported in the stats (which may be good or bad for your use case), but I get 27 sub failures:
Failures:

  1) numbers are not a multiple of 10
     Got 27 failures from failure aggregation block.

     1.1) Failure/Error: ...
            1 * 10 is a multiple of 10
          # ...backtrace...
     1.2) Failure/Error: ...
            2 * 5 is a multiple of 10
          # ...backtrace...
     ...
     1.27) Failure/Error: ...
             10 * 10 is a multiple of 10


text:
Q: NVCC extremely slow to compile CUBIN file I have CU file with a single kernel defined in it. The kernel calls a function which in turn calls one of two other. In total, all the functions combined is only around ~600 lines, however, some of those contain long mathematical expressions that are around ~1200 characters long. There are maybe 3 or 4 of these long expressions, 3 or 4 half that size and then a few comparatively short expressions. I am compiling this into a CUBIN file to be loaded at runtime in another program. The resulting CUBIN file is only around 800 kB.
Compiling this code for the host (in plain C) using gcc completes in less than a second. NVCC ends up taking ~20-30 minutes or more!
My command-line looks something like this:
nvcc -cubin -arch=sm_20 -m64 -ccbin g++ foo.cu -o foo.cubin -Xptxas -O0 -Xcompiler -Wno-unused-variable

What could be causing this? Is it possible to make it faster in any way?


text:
Q: App which will user to upload an excel sheet and update the sharepoint list with the rows in the excel trying to build a powerapp which would help user to upload an excel sheet via app and update a sharepoint list with the rows in the excel sheet. Request to help/suggest how can this be achieved.

A: We suggest you follow this video to upload excel files to SharePoint in PowerApps, then use flow to update list item based on the uploaded excel file.(Not fully compliant, need to make some changes)
https://www.youtube.com/watch?v=3QaiM8SeWfM
https://powerusers.microsoft.com/t5/Building-Flows/Update-Sharepoint-List-From-Excel-File/td-p/111477


text:
Q: Using custom-build C-API Python 3.3.5 module I am trying to import a C-API Python module for a game (Assetto Corsa) that uses Python 3.3.5 as scripting extension.
I am using MSVC 10.0 as described here for building the extension which works fine.
Importing the produced *.pyd file works in the terminal (using Python 3.3.5) and as well in the game when the script is called.
However, instantiating a class object works only in the terminal but leads to a crash when executing it in the game.
By logging all the executed statements I know that the constructor in the C-API is called correctly, so the problem must lie somewhere else.
I think that posting all the code might be too much, and as I said, it works as expected.

Does anybody have an idea, what might be wrong?

The target platform is obviously Windows.

A: I solved the problem myself, however, I am not sure what was the cause.
Removing the garbage collection flag 'Py_TPFLAGS_HAVE_GC' and the function pointer to the destructor from the 'PyTypeObject' description did the trick.
Be careful, this might lead to a memory leak! :)


text:
Q: Flutter draw a semicircle (half circle) but without space at the bottom I try to create a semi-circe with custom paint. the problem is that it is always drawn from the center. this creates a space at the bottom area that i don't want. how can i crop it?

I have checked this but this question is not answered here:
Flutter how to draw semicircle (half circle)
class myPainter extends CustomPainter {

@override
void paint(Canvas canvas, Size size) {
    var centerX = size.width / 2;
    var centerY = size.height / 2;
    var center = Offset(centerX, centerY);
    var radius = min(centerX, centerY);

   canvas.drawArc(Rect.fromCircle(center: center, radius: radius -25),
      doubleToAngle(-90), doubleToAngle(180), false, redCircle);

 bool shouldRepaint(bmiPainter oldDelegate) {
    //return true;
    return oldDelegate._angle != _angle;
  }

@override
  double doubleToAngle(double angle) => angle * pi / 180.0;

}

I embed the custom painter like this:
Flexible(
        flex: 2,
        fit: FlexFit.tight,
        child: Container(

              child: Transform.rotate(
                angle: -pi / 2,
                child: CustomPaint(
                  size: Size(300, 150),
                  key: backgroundKey,
                  painter: myPainter(),
                  child: Container(),
                ),
              ),
            ),
),

It has nothing to do with flexible. If I take a container and make it smaller, the semicircle also becomes smaller.
I played with Size but I it does not change anything. For what exactly is Size

A: Rect.fromCircle has center argument, and you can pass size's bottomCenter value.
Here is a working example:
Custom Painter
class MyPainter extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) {
    final redCircle = Paint()
      ..color = Colors.red
      ..style = PaintingStyle.stroke;
    final arcRect = Rect.fromCircle(
        center: size.bottomCenter(Offset.zero), radius: size.shortestSide);
    canvas.drawArc(arcRect, 0, -pi, false, redCircle);
  }

  @override
  bool shouldRepaint(MyPainter oldDelegate) => false;
}

(using with bounds)
Padding(
  padding: EdgeInsets.all(16),
  child: CustomPaint(
    painter: MyPainter(),
    child: SizedBox(width: 128, height: 64),
  ),
),

(using without bounds)
Flexible(
  child: Padding(
    padding: EdgeInsets.all(16),
    child: CustomPaint(
      painter: MyPainter(),
      child: AspectRatio(
        aspectRatio: 2,
        child: SizedBox(),
      ),
    ),
  ),
),


text:
Q: $\sum \limits_{k~ \in~ K_e} \frac{a^k}{k!} - \sum \limits_{k~ \in~ K_o} \frac{a^k}{k!} = \sum \limits_{k=0}^{\infty} \frac{(-a)^k}{k!}$ Given:
$$K_e = \{\text{even numbers: 0, 2, 4, ...}\}$$
$$K_o = \{\text{odd numbers: 1, 3, 5, ...}\}$$
How to prove this equality is true?
$$\sum \limits_{k~ \in~ K_e}  \frac{a^k}{k!} - \sum \limits_{k~ \in~ K_o}  \frac{a^k}{k!} = \sum \limits_{k=0}^{\infty} \frac{(-a)^k}{k!}$$

A: $(-a)^k = a^k$ for $k$ even and
$(-a)^k = - a^k$ for $k$ odd
Split the series in two and apply it

A: $$\begin{aligned}\sum_{k\in\mathbb{K_e}}\frac{a^k}{k!}&=1+\frac{a^2}{2!}+\frac{a^4}{4!}+\cdots \\ \sum_{k\in\mathbb{K_o}}\frac{a^k}{k!}&=\frac{a}{1!}+\frac{a^3}{3!}+\frac{a^5}{5!}+\cdots\\ \sum_{k=0}^{\infty}\frac{(-1)^ka^k}{k!}&=1-\frac{a}{1!}+\frac{a^2}{2!}-\frac{a^3}{3!}+\cdots\end{aligned}$$

A: It is true since
$$
\sum\limits_{k \in K_e } {\frac{{a^k }}{{k!}}}  = \sum\limits_{k \in K_e } {\frac{{( - a)^k }}{{k!}}}
$$
and
$$
 - \sum\limits_{k \in K_o } {\frac{{a^k }}{{k!}}}  = \sum\limits_{k \in K_o } {( - 1)\frac{{a^k }}{{k!}}}  = \sum\limits_{k \in K_o } {( - 1)^k \frac{{a^k }}{{k!}}}  = \sum\limits_{k \in K_o } {\frac{{( - a)^k }}{{k!}}} .
$$


text:
Q: Google closure library goog.forwardDeclare namespace javascript I have some problem, and I sure community can help me )))
For Example: I have the next javascript files
file1.js

goog.provide('namespace.ModuleName');
goog.require('namespace.ModuleName.Item')

/**
* @param {Object} args
*@constructor
*/

namespace.ModuleName = function(args) {
....
..Initialization..
...
var item = [];
item.push(new namespace.ModuleName.Item(args)) // THIS ERROR
}

/**
* @private
*/
namespace.ModuleName.prototype.MyMethod = function() {
...
...
...
}

The next part. I want create new file
file2.js

goog.provide('namespace.ModuleName.Item')

/**
* @param {Object} args
*@constructor
*/
namespace.ModuleName.Item = function(args) {

}

I have some problem because  "namespace.ModuleName.Item" Doesn't know about namespace.ModuleName. I can fix it. I need write goog.require('namespace.ModuleName') below goog.provide('namespace.ModuleName.Item').
But I have again some problem. Google Closure compiler writes "Require LOOP" . I can delete line where "goog.require('namespace.ModuleName.Item')". But these solution is not correct
What's the correct way to name modules
I ask this question on google forum. Guys told me "use goog.forwardDeclare"
https://groups.google.com/forum/#!topic/closure-library-discuss/PptH2fzcs_M
I tried write goog.forwardDeclare('namespace.ModuleName') above\below goog.provide('namespace.ModuleName.Item'). But it it's not worked for me. Can you help me ? Please. Or maybe write some examples. How use goog.forwardDeclare.


text:
Q: Using Jade templates in Backbone.js I love the HAML-like syntax of Jade's templating engine in Node.js, and I would love to use it client-side within Backbone.js.
I've seen Backbone commonly using Underscore.js templating in the following style.
/* Tunes.js */
window.AlbumView = Backbone.View.extend({
  initialize: function() {
    this.template = _.template($('#album-template').html());
  },

  // ...
});

/* Index.html */

What I'd like to see is a way to use AJAX (or some other method) to fetch Jade templates and render them within the current HTML.

A: I just open sourced a nodejs project, called "asset-rack", that can can precompile jade templates and offer them in the browser as javascript functions.
This means that rendering is blazingly fast, even faster then micro-templates because there is no compilation step in the browser.
The architecture is a little different then what you mention, just one js file for all templates called "templates.js" or whatever you want.
You can check it out here, https://github.com/techpines/asset-rack#jadeasset
First you set it up on the server as follows:
new JadeAsset({
    url: '/templates.js',
    dirname: __dirname + '/templates'
});

If you template directory looked like this:
templates/
  navbar.jade
  user.jade
  footer.jade

Then all your templates come into the browser under the variable "Templates":
$('body').append(Templates.navbar());
$('body').append(Templates.user({name: 'mike', occupation: 'sailor'});
$('body').append(Templates.footer());

Anyway, hope that helps.

A: I was able to run Jade client-side using jade-browser project.
Integration with Backbone is then simple: Instead of _template() I'm using jade.compile().
HTML (scripts and template):

JavaScript (integration with Backbone.View):
var jade = require("jade");

var TestView = Backbone.View.extend({

  initialize: function() {
    this.template = jade.compile($("#test").text());
  },

  render: function() {
    var html = this.template({ item: 'hello, world'});
    $('body').append(html);
  }
});

var test = new TestView();
test.render();

HERE is the code.

A: As @dzejkej mentioned above, one of the best known ways to use Jade templates on the client is to use jade-browser; however, I've always had a few issues with Jade in the browser.

*

*Compiling Jade templates is slow - which is okay, but really, all templates should be cached, and if you cache them on the client, anytime they load a new page, the cache disappears (unless using HTML5 persistent storage, for example).

*File includes can be a pain and can create excess bloat. If you are compiling Jade templates on the browser and the template contains include statements, you may have to do some extra work to get them to compile properly.  In addition, if you decide to compile on the server and send JavaScript to the client, you still have issues.  Whenever Jade templates use file includes, your compiled Jade templates can get rather large because they contain the same code over and over.  For example, if you include the same file again and again, that file's contents will be downloaded to the browser several times, which is wasting bandwidth.

*Lack of support - Jade provides little support for client-side templates out of the box. Yes, you can use the {client: true} compiler option, but the compiled templates are really not optimized for the client, and in addition, there is no mechanism for serving compiled Jade templates to the browser.

These are among some of the reasons why I created the Blade project.  Blade is a Jade-like templating language that supports client-side templates right out of the box.  It even ships with Express middleware designed for serving compiled templates to the browser.  If you are okay with a Jade-like alternative for your projects, check it out!

*

*https://github.com/bminer/node-blade

*https://github.com/bminer/node-blade#blademiddlewaresourcepath-options

*https://github.com/bminer/node-blade#browser-usage

A: You might also checkout my new library for jade inside browser. It is as simple as < jade>...< /jade>. https://github.com/charlieamer/jade-query

A: You won't get the full power of Jade templates, but you can hack it a bit to get jade to properly output underscore templates, the key is preventing jade from escaping the <%> tags with the ! operator, like so:
script#dieTemplate(type='text/template')
    .die(class!='value-<%= value %>')
        i.fa.fa-circle
        i.fa.fa-circle
        i.fa.fa-circle
        i.fa.fa-circle
        i.fa.fa-circle
        i.fa.fa-circle
        i.fa.fa-star


text:
Q: Underscore.js: filter objects with nested array of objs I am trying to filter top-level objects based on nested data (filtering is also needed for nested objects).
Filter params: All records with categoryValue A.
  const table = [
    {
      name: 'Bob',
      detail: [
        { category: 'Employeer', categoryValue: 'A' },
        { category: 'Employeer', categoryValue: 'B' },
      ],
    },
    {
      name: 'Alice',
      detail: [
        { category: 'Employeer', categoryValue: 'C' },
        { category: 'Employeer', categoryValue: 'D' },
      ],
    },
  ];

I am expecting the following result
  const fileredTable = [

    {
      //this
      name: 'Bob',
      detail: [
        //and only this
        { category: 'Employeer', categoryValue: 'A' }

      ],
    }
  ];

A: Ok, after several tries i found this solution:
const filteredTable = table.flatMap((item) => {
  const filteredDetail = item.detail.filter((e) => e.categoryValue === 'A')
  return filteredDetail.length !== 0 ? {...item, detail: filteredDetail} :  []
})


text:
Q: Axiomatic System and Proof Axiom 1: There are exactly three points.
Axiom 2: Every point is on at least two lines.
Axiom 3: Each line passes through at most two points.
Here are the given axioms for the axiom system. It was asked why the proposition There are exactly two lines cannot be an additional axiom. I am confused since I cannot prove that this proposition is true so that when it is added, it will contradict the axiom system.


text:
Q: Forcing unique values before casting (pivoting) in R I have a data frame as follows
Identifier  V1  Location    V2
1   12  A   21
1   12  B   24
2   20  B   15
2   20  C   18
2   20  B   23
3   43  A   10
3   43  B   17
3   43  A   18
3   43  B   20
3   43  C   25
3   43  A   30

I'd like to re-cast it with a single row for each Identifier and one column for each value in the current location column. I don't care about the data in V1 but I need the data in V2 and these will become the values in the new columns.
Note that for the Location column there are repeated values for Identifiers 2 and 3.
I ASSUME that the first task is to make the values in the Location column unique.
I used the following (the data frame is called "Test")
L<-length(Test$Identifier)
for (i in 1:L)
{
temp<-Test$Location[Test$Identifier==i]
temp1<-make.unique(as.character(temp), sep="-")
levels(Test$Location)=c(levels(Test$Location),temp1)
Test$Location[Test$Identifier==i]=temp1
}

This produces
Identifier  V1  Location    V2
1   12  A   21
1   12  B   24
2   20  B   15
2   20  C   18
2   20  B-1 23
3   43  A   10
3   43  B   17
3   43  A-1 18
3   43  B-1 20
3   43  C   25
3   50  A-2 30

Then using
cast(Test, Identifier ~ Location)

gives
Identifier  A   B   C   B-1 A-1 A-2
1   21  24  NA  NA  NA  NA
2   NA  15  18  23  NA  NA
3   10  17  25  20  18  30

And this is more or less what I want.
My questions are
Is this the right way to handle the problem?
I know R-people don't use the "for" construction so is there a more R-elegant (relegant?) way to do this? I should mention that the real data set has over 160,000 rows and starts with over 50 unique values in the Location vector and the function takes just over an hour to run. Anything quicker would be good. I should also mention that the cast function had to be run on 20-30k rows of the output at a time despite increasing the memory limit. All the cast outputs were then merged
Is there a way to sort the columns in the output so that (here) they are A, A-1, A-2, B, B-1, C
Please be gentle with your replies!

A: Usually your original format is much better than your desired result. However, you can do this easily using the split-apply-combine approach, e.g., with package plyr:
DF <- read.table(text="Identifier  V1  Location    V2
1   12  A   21
1   12  B   24
2   20  B   15
2   20  C   18
2   20  B   23
3   43  A   10
3   43  B   17
3   43  A   18
3   43  B   20
3   43  C   25
3   43  A   30", header=TRUE, stringsAsFactors=FALSE)
#note that I make sure that there are only characters and not factors
#use as.character if you have factors

library(plyr)
DF <- ddply(DF, .(Identifier), transform, Loc2 = make.unique(Location, sep="-"))

library(reshape2)
DFwide <- dcast(DF, Identifier ~Loc2, value.var="V2")
#  Identifier  A  B B-1  C A-1 A-2
#1          1 21 24  NA NA  NA  NA
#2          2 NA 15  23 18  NA  NA
#3          3 10 17  20 25  18  30

If column order is important to you (usually it isn't):
DFwide[, c(1, order(names(DFwide)[-1])+1)]
#  Identifier  A A-1 A-2  B B-1  C
#1          1 21  NA  NA 24  NA NA
#2          2 NA  NA  NA 15  23 18
#3          3 10  18  30 17  20 25

A: For reference, here's the equivalent of @Roland's answer in base R.
Use ave to create the unique "Location" columns....
DF$Location <- with(DF, ave(Location, Identifier,
                    FUN = function(x) make.unique(x, sep = "-")))

... and reshape to change the structure of your data.
## If you want both V1 and V2 in your "wide" dataset
## "dcast" can't directly do this--you'll need `recast` if you
##    wanted both columns, which first `melt`s and then `dcast`s....
reshape(DF, direction = "wide", idvar = "Identifier", timevar = "Location")

## If you only want V2, as you indicate in your question
reshape(DF, direction = "wide", idvar = "Identifier",
        timevar = "Location", drop = "V1")
#   Identifier V2.A V2.B V2.C V2.B-1 V2.A-1 V2.A-2
# 1          1   21   24   NA     NA     NA     NA
# 3          2   NA   15   18     23     NA     NA
# 6          3   10   17   25     20     18     30

Reordering the columns can be done the same way that @Roland suggested.


text:
Q: Why can I not modify a variable declared outside a closure? Every time I test my code, an empty string is returned to the pickerUI rather than the college name. Why is that? When debugging, docData is set correctly but changes back to an empty string after the closure.
var ans = "";
var pickerData = [Any?]();
let db = Firestore.firestore();

override func viewDidLoad() {
    super.viewDidLoad();
    let docRef = db.collection("colleges").document("UMD");
    var docData = "";
    docRef.getDocument {  ( document, error) in
        if error == nil {
            docData = document!.get("Name") as! String;

        } else{

        }
    }
    pickerData.append(docData);
    picker.delegate = self
    picker.dataSource = self
}

A: It's because data is loaded from Firestore asynchronously, and your main code continues to run while that is happening. It's easiest to see by placing a few log statements:
let docRef = db.collection("colleges").document("UMD")
print("Before starting to get data")
docRef.getDocument {  ( document, error) in
    print("Got data")
}
print("After starting to get data")

When you run this code, it prints:

Before starting to get data
After starting to get data
Got data

This is probably not the order you expected, but it does completely explain why your code doesn't work. By the time your pickerData.append(docData) runs, the docData = document!.get("Name") as! String hasn't run yet.
For this reason, any code that needs data from the database needs to be inside the closure, or be called from there:
let docRef = db.collection("colleges").document("UMD")
var docData = ""
docRef.getDocument {  ( document, error) in
    if error == nil {
        docData = document!.get("Name") as? String ?? "No Name"

        pickerData.append(docData)
        picker.delegate = self
        picker.dataSource = self
    } else{

    }
}

Also see:

*

*Asign value of a Firestore document to a variable

*Using Firestore DB, how can I break out of a for loop inside of a snapshot listener when a certain condition is met?, which also shows using a custom closure to keep your own code outside of the getDocument closure.

*Storing asynchronous Cloud Firestore query results in Swift, showing using a dispatch group to keep the code


text:
Q: Cannot call member function std::string class::function() without object I know it may seem like this has been asked before but I've looked around and the static method didn't work for me. Here's my code:
struct Customer {
public:
    string get_name();
private:
    string customer,first, last;
};

Here's where I call the function:
void creation::new_account() {
Customer::get_name(); //line it gives the error on.
}

Here's an example of some code that compiles fine.
struct Creation { public: string get_date(); private: string date; };

then I call it the same way
void Creation::new_account() { Creation::get_date();}

Hence my confusion why one works and the other doesn't.
EDIT: Ok I get it, I just realized I was calling a function of another struct inside a function definition that's part of a different class. I got it, thanks to all who answered

A: It is not declared static (needs to be static std::string get_name();). However, get_name() for Customer is a specific attribute of a Customer instance so having it static does not make sense, that is the same name for all instances of Customer. Declare an object of Customer and use it. It would make sense to have the name provided to the constructor of Customer, as surely a customer cannot exist without a name:
class Customer {
public:
    Customer(std::string a_first_name,
             std::string a_last_name) : first_name_(std::move(a_first_name)),
                                        last_name_(std::move(a_last_name)) {}
    std::string get_name();
private:
    std::string first_name_;
    std::string last_name_;
};

Declare an instance of Customer:
Customer c("stack", "overflow");
std::cout << c.get_name() << "\n";

A: Since your get_name is not declared static, it is a member function.
You probably need some constructors in your Customer class. Assuming you have some, you could code
 Customer cust1("foo123","John","Doe");
 string name1 = cust1.get_name();

You need an object (here cust1) to call its get_name member function (or method).
Time to spend many hours reading a good C++ programming book.

A: "The static method didn't work for me". It's not a method it's how the language works.
If you want to call some method without a concrete object, you need it to be static. Otherwise, you need an object.
Your code will work with one of the following :
struct Customer {
public:
    static string get_name();
private:
    string customer,first, last;
};

or
void creation::new_account() {
    Customer c;
    //stuff
    c.get_name();
}


text:
Q: c# RegEx, how to filter the resultset of regex I have a string "banaanapplebanaanappleapplebanaanappleappbanaanaapple",
1.  If I want to extract "apple", the below resultset applys well.
RegEx : apple
result : "banaanapplebanaanappleapplebanaanappleappbanaanaapple"

*If I want to extract "banaana" the below query works well.
RegEx : banaana
result :
"banaanapplebanaanappleapplebanaanappleappbanaanaapple"

*I want to match "apple and banaana"
RegEx : banaana
result :
"banaanapplebanaanappleapplebanaanappleappbanaanaapple"

I want my resultset to contain only two matches of the apple..
How can I achieve this with regex?

A: You actually need an alternation operator with capturing group.
banaana|(apple)

The idea is, first banaana would greedily match all the banaana strings. | OR (apple) capture apple strings only from the remaining characters. So this won't overlap with banaana strings.
Example


text:
Q: How does less display PDFs? I have tried several programs: pdftotext, pdf2txt.py, ... All of them can extract text from PDFs, but the one which is doing the better job is good ol' less: the text from the PDF has a proper layout. How is less doing this? Is it using any library, or is the PDF processing built-in?
I am asking because I would like to use this funcionality programmatically, wihout necessarily having to run less as an external program (I am doing python).
My system is:
» less --version
less 458 (GNU regular expressions)
Copyright (C) 1984-2012 Mark Nudelman

less comes with NO WARRANTY, to the extent permitted by law.
For information about the terms of redistribution,
see the file named README in the less distribution.
Homepage: http://www.greenwoodsoftware.com/less

» uname -a
Linux polyphemus 3.13.0-53-generic #89-Ubuntu SMP Wed May 20 10:34:39 UTC 2015 x86_64 x86_64 x86_64 GNU/Linux

A: Your distribution is probably using the popular lesspipe.sh script. Check the LESSOPEN environment variable.
This script exists in many variations. I'm looking at the Gentoo version. In it, you'll find the following line:
*.ps|*.pdf) ps2ascii "$1" || pstotext "$1" || pdftotext "$1" ;;

That means it will try those commands in the order displayed. $1 is the file name.
Another version uses the following command:
pdftohtml -stdout "$t" | parsehtml -


text:
Q: Should I run my unit tests against the Rollup bundle? What is the best approach for Jest testing a Typescript library I built, i.e.
import *.ts source code files, or the generated Rollup bundle files (CJS, ESM)?
In the latter case, is it advisable to code tests in Typescript?


text:
Q: python string input problem with whitespace! my input is something like this
23 + 45 = astart
for the exact input when i take it as raw_input() and then try to split it , it gives me an error like this
SyntaxError: invalid syntax
the code is this
k=raw_input()
a,b=(str(i) for i in k.split('  +   '))
b,c=(str(i) for i in b.split('  =   '))

its always number + number = astar
its just that when i give number+number=astar i am not getting syntax error ..!! but when i give whitespace i get sytax error

A: Testing with Python 2.5.2, your code ran OK as long as I only had the same spacing
on either side of the + and = in the code and input.
You appear to have two spaces on either side of them in the code, but only one on either
side in the input.  Also - you do not have to use the str(i) in a generator.  You can do
it like a,b=k.split(' + ')
My cut and pastes:

My test script:

print 'Enter input #1:'
k=raw_input()

a,b=(str(i) for i in k.split(' + '))
b,c=(str(i) for i in b.split(' = '))

print 'Here are the resulting values:'
print a
print b
print c

print 'Enter input #2:'
k=raw_input()

a,b=k.split(' + ')
b,c=b.split(' = ')

print 'Here are the resulting values:'
print a
print b
print c

From the interpreter:

>>>
Enter input #1:
23 + 45 = astart
Here are the resulting values:
23
45
astart
Enter input #2:
23 + 45 = astart
Here are the resulting values:
23
45
astart
>>>

A: Edit: as pointed out by Triptych, the generator object isn't the problem. The partition solution is still good and holds even for invalid inputs
calling (... for ...) only returns a generator object, not a tuple
try one of the following:
a,b=[str(i) for i in k.split('  +   ')]
a,b=list(str(i) for i in k.split('  +   '))

they return a list which can be unpacked (assuming one split)

or use str.partition assuming 2.5 or greater:
a, serperator, b = k.partition('+')

which will always return a 3 tuple even if the string isn't found
Edit: and if you don't want the spaces in your input use the strip function
a = a.strip()
b = b.strip()

Edit: fixed str.partition method, had wrong function name for some reason

A: I think I'd just use a simple regular expression:
# Set up a few regular expressions
parser = re.compile("(\d+)\+(\d+)=(.+)")
spaces = re.compile("\s+")

# Grab input
input = raw_input()

# Remove all whitespace
input = spaces.sub('',input)

# Parse away
num1, num2, result = m.match(input)

A: You could just use:
a, b, c = raw_input().replace('+',' ').replace('=', ' ').split()

Or [Edited to add] - here's another one that avoids creating the extra intermediate strings:
a, b, c = raw_input().split()[::2]

Hrm - just realized that second one requires spaces, though, so not as good.

A: Rather than trying to solve your problem, I thought I'd point out a basic step you could take to try to understand why you're getting a syntax error: print your intermediate products.
k=raw_input()
print k.split('  +   ')
a,b=(str(i) for i in k.split('  +   '))
print b.split('  =   ')
b,c=(str(i) for i in b.split('  =   '))

This will show you the actual list elements produced by the split, which might shed some light on the problem you're having.
I'm not normally a fan of debugging by print statement, but one of the advantages that Python has is that it's so easy to fire up the interpreter and just mess around interactively, one statement at a time, to see what's going on.


text:
Q: Logistic regression with two slopes and one intercept I am using R to fit a logistic model to some data. The problem is as follows:
"The effects of the dose of poison $(x)$, in milligrammes, and the method of delivery $(w)$ on the
probability of survival were examined in a study of rats. The two methods of delivery were
as a solid with food or as a liquid in water. For each combination of dose and method of
delivery, a certain number of rats $(r)$ were used and the number who survived $(y)$ is recorded.
Below are the data.

Now when I plot these data, it looks like a model that has a different slope for each delivery method but the same intercept would be suitable:

How would I tell R to do this? I know that to fit a model with different intercepts but the same slope is "glm(p~x+w,...)" and to fit a model with two slopes and two intercepts is "glm(p~x+w+x:w,...)" but can't figure out the case for different slopes and the same intercept.

A: In order to have separate slopes for each group but equal intercepts, explicitly require that in the model.
Instead of
$$
\beta_0+\beta_1x_{group}+\beta_2x_{dose}+\beta_3x_{group}x_{dose}+\epsilon
$$
try
$$
\beta_0+\beta_1x_{dose}+\beta_2x_{dose}+\epsilon
$$
The R code would be something like glm(y~dose + dose:group, family = binomial). This takes the interaction between the dose and the group (to achieve multiple slopes) while excluding the interaction between the intercept and the two groups that you would get by regressing on the group variable on its own.

A: How do you determine that the intercept is the same for both methods of delivery $w$, from a plot of the observed probability of survival $p$ against the dose $x$?
Recall that a logistic regression is a linear model for the log odds (here, of survival):
$$
\begin{aligned}
\log\frac{\operatorname{P}(Y)}{1-\operatorname{P}(Y)} =\mathbf{X}\boldsymbol{\beta}
\end{aligned}
$$
So it's more informative to plot the log odds of survival on the y-axis:

This plot doesn't suggest to me to specify that the slope is the same for both $w$ but to add a quadratic term for $x$.
Here are two fits, both on the logit scale (the link function of the logistic regression is the logit). The first fit is for the model y ~ x + x:w; it has the same intercept, different slopes for $w$. The second fit is for the model y ~ w + rcs(x, 3): restricted cubic splines with 3 knots in the dose $x$, with a vertical shift between the two methods of delivery $w$. The second model suggests that the relationship between dose and the log odds of survival is mostly linear for $x\geq2$.

Created on 2022-12-11 with reprex v2.0.2


text:
Q: Objective-C syntax and compile warning when I compile my app project via Xcode, I got too many warning, most say: 'myClass' may not respond to '+isAliveNetworkConnection:' ,  although the method 'isAliveNetworkConnection' was implemented in the .m file but it does not declare in .h file, I find it works so I do not like to rewrite in the head file again;
I think the Objective-C is not convince to use than Java ...  maybe I am too lazy? :D
does anyone have the same thought?

A: Objective-C is a dynamic language. It's perfectly fine(at compilation time) to send a message to a class that doesn't implement the appropriate method. You can also add methods to classes at runtime! Objective-C will let you get away with a lot of stuff. However, you generally should avoid such practices, unless you have a very good reason for doing so.
As you've found, you're "allowed" to skip declaring methods in your .h file, but it's not recommended. Why? First, if someone else is reading your code, it can be easier to get a quick list of all of the methods implemented. Second, if you're debugging your code, and getting a crash in, say objc_msgsend, where an object is being sent a message it won't respond to, you can easily track down the issue because it will occur as a warning in your code. If you always avoid naming functions in your .h file, you'll have hundreds(thousands?) of warnings, and it won't be easy to sift through them all.
In short, you can get away with a lot, but you should generally follow "good" coding practices.

A: C and Java are different. You have to tell the compiler what methods your class implements in the interface, otherwise it has no way of knowing, which is why you get the warnings.

A: You need to declare all methods that you use in your header file if you want this warning to go away. The compiler doesn't know about the methods in your .m file unless you do this.
You can implement private methods that you don't want in the header by using a category, like so:
in YourClass.m:
@interface YourClass (Private)
- (void)yourPrivateMethod;
@end

@implementation YourClass

- (void)yourPrivateMethod
{
    //do stuff
}
@end

A: The header file is the official API for your class. If you do not specify something there, the compiler will assume that other code using that selector is using some internal functionality.
The reason it gives you a warning is that doing so by mistake risks adding unwanted side effects to your code should the one maintaining the class who's unofficial API you are using decide to change something without knowing that someone else is depending on the selector.
(and while writing this, Mike gave a much more complete answer).
Take my advice, don't be lazy. Unless you are very experienced and know where it is ok to be lazy the risk is rather high it will come back and bite you later.