text:
Q: MSBuild stops on the first error when called inside NAnt script? I'm trying to build a VS 2008 solution in NAnt, but it seems msbuild stops the build process after the first compilation errror has occured.
In MSBuild there is a "ContinueOnError=true" or "StopOnFirstFailure=false" attribute, but how to specify this in NAnt ? The failonerror="false"does not solve the problem:

A: I need to confess that this is only a first guess but have you tried passing ContinueOnError=true as property to MSBuild?
Assuming you use the NAntContrib msbuild task you have:
<msbuild project="${projectfile.path}">
  <property
    name="ContinueOnError"
    value="true" />
</msbuild>

Or with exec task:
<exec program="${msbuild.exe.path}">
  <arg value=""${projectfile.path}"" />
  <arg value="/p:ContinueOnError=true" />
</exec>

Wouldn't it be perfect if it was that simple?

A: I have doing configuration management with Nant and CC.Net for a while now. I my experience I would not recommed using the Nant MSBuild task, instead the easiest way is creating and task, create a .bat file that the task executes. There are several reasons that would recommend using the command line Visual Studio, for one MSI packages are not easily build with Nant, even if you use contrib. Also it should eliminate your Nant continue on error request, Devenv should automatically continue to build even if one project fails. Also if you use this method you will not have to worry about changing nant and nant contrib to handle 3.5. If you used Cruise control you will still see your build output in your XML file.
---------2.0 --------
"C:\Program Files\Microsoft Visual Studio 8\Common7\IDE\devenv" C:\YourProject\YourSoultion.sln /Rebuild release
----------3.5--------
"C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\devenv" C:\YourProject\YourSoultion.sln /Rebuild release


text:
Q: Spring embedded ldap server Unable to perform the search I am getting below error while using spring embedded ldap server.
Your login attempt was not successful, try again.

Reason: [LDAP: error code 32 - Unable to perform the search because base entry 'ou=people,dc=example,dc=com' does not exist in the server.]; nested exception is javax.naming.NameNotFoundException: [LDAP: error code 32 - Unable to perform the search because base entry 'ou=people,dc=example,dc=com' does not exist in the server.]; remaining name 'ou=people'

Below are my code
<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.ldap</groupId>
            <artifactId>spring-ldap-core</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-ldap</artifactId>
        </dependency>

        <dependency>
            <groupId>com.unboundid</groupId>
            <artifactId>unboundid-ldapsdk</artifactId>
        </dependency> <!-- This is the ldap server-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

    dn: ou=groups,dc=example,dc=com
    objectclass: top
    objectclass: organizationalUnit
    ou: groups

    dn: ou=people,dc=example,dc=com
    objectclass: top
    objectclass: organizationalUnit
    ou: people

    dn: uid=vandna,ou=people,dc=example,dc=com
    objectclass: top
    objectclass: person
    objectclass: organizationalPerson
    objectclass: inetOrgPerson
    cn: vandna bhimjiyani
    sn: bhimjiyani
    uid: vandna
    userPassword: password

    dn: uid=kaushik,ou=people,dc=example,dc=com
    objectclass: top
    objectclass: person
    objectclass: organizationalPerson
    objectclass: inetOrgPerson
    cn: kaushik andani
    sn: andani
    uid: kaushik
    userPassword: password

    dn: cn=user,ou=groups,dc=example,dc=com
    objectclass: top
    objectclass: groupOfNames
    cn: user
    uniqueMember: uid=vandna,ou=people,dc=example,dc=com

    dn: cn=admin,ou=groups,dc=nascent,dc=com
    objectclass: top
    objectclass: groupOfNames
    cn: admin
    uniqueMember: uid=kaushik,ou=people,dc=example,dc=com

in WebSecurityConfigurerAdapter
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
            auth.ldapAuthentication()
                    .userSearchBase("ou=people")
                    .userSearchFilter("(uid={0})").groupSearchBase("ou=groups")
                    .groupSearchFilter("(member={0})")
                    .contextSource().root("dc=nascent,dc=com")
                    .ldif("src/main/resources/users.ldif");
        }

A: Added top entry in .ldif file

dn: dc=example,dc=com
  objectclass: top
  objectclass: domain
  objectclass: extensibleObject
  dc: nascent

change in WebSecurityConfigurerAdapter

      @Override
  public void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth
            .ldapAuthentication()
            .userDnPatterns("uid={0},ou=people")
            .groupSearchBase("ou=groups")
            .contextSource()
            .url("ldap://localhost:8399/dc=example,dc=com")
            .and()
            .passwordCompare()
            .passwordAttribute("userPassword");
  }

.ldif file path is set in application.properties

spring.ldap.embedded.ldif=classpath:users.ldif
  spring.ldap.embedded.base-dn=dc=example,dc=com
  spring.ldap.embedded.port=8389

redpajama_set_name: RedPajamaStackExchange


text:
Q: UB if unique_ptr-allocated resource deletes itself via said unique_ptr? I'm trying to implement a tasking system that has the ability to make tasks destroy themselves if they run out of instructions. For this I thought of a mechanism in which I could pass back the unique_ptr handle returned by creating the task back to the task and have it run out of scope. I can't show  you the task but imagine in the following example pass_back_ownership would somehow move the unique_ptr to the task function which destroys it if runs out of scope. Am I in UB-land or is this totally legit and good practice?
Demo
#include <future>
#include <memory>
#include <cstdio>

struct task;

using task_ptr = std::unique_ptr<task>;

struct task
{
    task() = default;

    ~task() {
        printf("task deleted!\n");
    }

    auto pass_back_ownership(task_ptr&& ptr) {
        auto tmp = std::move(ptr);
    }

    // Task stack
    // ...
};

int main()
{

    task_ptr ptr = std::make_unique<task>();

    ptr->pass_back_ownership(std::move(ptr));

    printf("end!\n");
}

Output:
task deleted!
end!

A: In the code you have written the task object will be destroyed (with a call to the destructor) at the end of pass_back_ownership.
That is completely fine and no UB in your code. However, main must be careful not to dereference ptr after the call to pass_back_ownership.
Also be careful that there are potential order-of-evaluation issues if pass_back_ownership were to take the parameter by-value instead of by-reference. That would make the code a bit simpler, since you wouldn't need to crate the local tmp variable, but only since C++17 is it guaranteed that ptr->pass_back_ownership will be evaluated before the function parameter is constructed. If the order was the other way around, then you would have UB for dereferencing an empty ptr.

Regarding best practice:
What your call ptr->pass_back_ownership(std::move(ptr)); is saying is that main relinquishes ownership of the task object referenced by ptr to itself. The lifetime of the task object is not intended to be bound to the scope of main anymore.
The question would then be what possible lifetimes the task object could then have. There are basically only two choices: 1. its lifetime ends at latest at the end of the function call, which is your case, or 2. pass_back_ownership stores the passed unique_ptr somewhere outside the function to extend the lifetime.
If you are interested only in 1., then I would question why it is necessary to pass the std::unique_ptr to some random function to achieve the effect. If you intent ptr->pass_back_ownership(std::move(ptr)); to definitively destroy the task object, then why aren't the operations that pass_back_ownership does simply done in the destructor of task? Then you could simply let ptr in main run out-of-scope to have the same effect.
It makes a bit more sense if pass_back_ownership only conditionally actually takes ownership by moving the unique_ptr reference. Then main could test with if(ptr) after the call whether or not the task object was destroyed, but then why is it important for the task object to be destroyed prematurely instead of simply waiting for ptr in main to go out-of-scope? That no instructions are left can also be communicated by either having the function return a bool state or have the task object have some way of checking presence of instructions (e.g. an operator bool).


text:
Q: prove that $5v^2+10$ cannot be a perfect square I was able to prove that $5v^2+10$ cannot be a perfect square by working on the integers modulo 4 where the value of perfect squares are either 0 or 1. Initially, I tried to work in the integers modulo 5 but I couldn't arrive at a contradiction there. I would like to understand what kind of intuition a mathematician uses to pick the right modulo space where the contradiction can be shown. Is it simply trial and error or is there some kind of deeper reasoning / cleverness involved? And if so, how should I go about building this kind of intuition? Number theory books are full of clever solutions but there appears to be little in the way of methodology unlike other (undergraduate-level) math areas.
For the record my proof was that, in the integers modulo 4, perfect squares are either 0 or 1. Therefore $5*a+2$ must be congruent to 0 or 1 (mod 4), with $a$ being either 0 or 1, which is impossible.

A: Let $$k^2=5v^2+10,\qquad k\in\Bbb Z$$
Now, $5\bigg|k^2\implies5\bigg|k$, since $5$ is prime. Therefore, let
$$k=5l, \qquad l\in\Bbb Z\\
\implies 5l^2=v^2+2$$
Now note that $LHS$ is divisible by $5$, whereas $RHS$ is not. We get a contradiction.

A: S=5(v²+2) , as S is a perfect square therefore it must be divisible by 25 implying v²+3 is divisible by 5 .
So v² should be of form 5q+3 .
But a perfect square is only of the form 5q, 5q+1 or 5q+2


text:
Q: Firebase Hosting deploy only for auth users Is it somehow possible to deploy my app using firebase hosting, and there use a an under construction template and a login email and password.
Once user sign's in and the email is known email as admin for example, let them see the entire public directory otherwise if the email is not an admin email set in database for example then just show them a message that we will email them once site is public.
How can I do something like this ?


text:
Q: Backslash escape in indexOf Why does n give 0 in the following instance :
var str = '\\nvga032.bmwgroup.net\QXE7868\Daten\IE\3_bookmarks.zzz'

var n = str.indexOf("\\");

alert(n) //0

Surely the escape character for a backslash is

'\\'

Am I missing something? I am looking for a single backslash at the last position. I tried lastIndexOf as well, and that also gives zero. Are the two '.'s messing things up?

A: indexOf matches on the string not the JavaScript source code used to create it.
A \ character starts an escape sequence.
\\ is the escape sequence for "A backslash".
The string assigned to str starts with \\ which puts a backslash in position 0 in the data.
The string passed to indexOf consists entirely of \\ which matches the first backslash in the data.

If you wanted to describe an escape sequence in a string you would use \\\\ (i.e. the escape sequence for a backslash followed by another escape sequence for a backslash resulting in data consisting of two backslashes).

A: "\\" will be parsed down to a single blackslash. And then indexOf will look for that single backslash, which happens to be at the start of the string (n=0).
If you want to search for TWO backslashes, you'll have to indexOf("\\\\") (FOUR backslashes, which will be parsed down to two literal backslashes).

A: Your "str" variable most probably doesn't contain what you expected. Write instead:
var str = '\\\\nvga032.bmwgroup.net\\QXE7868\\Daten\\IE\\3_bookmarks.zzz'
var n = str.lastIndexOf("\\");


text:
Q: Find all users with specific role using rolify How can i get all users with specific role when using rolify? I've tried the following but it didn't help:
User.with_role :admin

I get the following error:
NoMethodError: undefined method `with_role' for #<Class:0x0000000743f9c0>

Couldn't find any way to do this.

A: I'd ask the role for it's users
admins = Role.find_by_name('admin').users

the with_role method is for a particular user instance, not at the class-level for all users. If you want to implement that you'd have to do something like this:
#not 100% on this code, haven't tested it, but you get the idea.
User < ActiveRecord::Base
  def self.with_role(role)
     my_role = Role.find_by_name(role)
     where(:role => my_role)
  end
end

A: You can use the with_role method with a User class to find all users who has a role in version 3.1.0.
User.with_role :admin

A: Have you mentioned resourcify in the models in order to put roles on
class User < ActiveRecord::Base
  resourcify
end

With this you can use with_role and find_roles class methods.

A: if you need an aditional "where"
@courriers = User.where.not(latitude: nil, longitude:nil ).with_role :Courrier

A: If you need to use joins, try this:
User.with_role(:admin).joins(:other_table).(other_table:{some_field: true})


text:
Q: Web Scraping with BeautifulSoup with python I'm scraping with BeutifulSoup via python on :
i woud like to extract the title name "Don Ḳarlos: gresṭe drama der ṿelṭ"
i get this as ouptput: "Don Ḳarlos: gresá¹e drama der ṿelá¹"
my code:
resp = requests.get(url)
tree = html.fromstring(resp.content)
element = tree.xpath('/html/body/div[1]/div[7]/div[2]/text()')
t = element[1]
print(t)

the html:

Title
Don Ḳarlos: gresṭe drama der ṿelṭ
Additional title: Don Ḳarlos

Thanks


text:
Q: PHP url rewrites not working (maybe due to Apache rewrites) I am developing a php website and am trying to get rid of the .html extension from the URL. Right now I am on the staging server.
Here is how the server is setup by a remote IT team:

*

*The server is called int-dev.mydomain.com.

*The URL for the website is staging.mydomain.com/dev/home.html.

When the server receives a request for staging.mydomain.com/dev/ it basically forwards it to dev.mydomain.com; this is done through Apache. Per my understanding, staging.mydomain.com/dev/ is not the same domain as staging.mydomain.com, but more like a vanity URL.
Now, I added a .htaccess file with the following code:
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.html -f
RewriteRule ^(.*)$ $1.html

It is not working when I try to access the URL without .html extension.
Any ideas/suggestions what could be the problem and what can I do about it?
Thanks.

A: Im using this with PHP and it's working fine for me
RewriteRule ^about$ about.php [L]

Try it like this
RewriteRule ^page_name$ page_name.html [L]

With this you have to specify all pages with your script


text:
Q: data insertion works but not showing alertbox message i have tried below code to execute validation function and the data insertion operation the followed code runs correctly on chrome but firefox not showing the message of succesfully insertion..
<input type="submit" onclick="chk()";/>//chk() contains validations
<?
  php

  if(isset($_POST["submit"]))
  {
     data insertion code

    if(true)
    {
     <script language="javascript">alert " Adverties    added";window.location="adverties.php";</script>
    }

  }
?>

A: *

*Put JS in echo:

echo '.. script ... JS code';

*I don't know if it's stackoverflow mistake, but " Adv.. " text is not in ( )
So it should be:
if(true)
{
 echo '<script language="javascript">alert(" Adverties    added");window.location="adverties.php";</script>';
}

A: I think I got it working.
<form action="[name of the page]" method="post">
    <input name="submit" type="submit" onclick="chk()"/>
</form>

<?php
if(isset($_POST["submit"])){
    if(true){
        echo'<script> alert("Adverties added");window.location = "adverties.php";</script >';
    }
}
?>

so I put the <input> inside a <form> that redirects you to the current page and used the POST method.
You also have to use the name property inside of the input tag inorder for $_POST["submit"] to work, I also added the echo to print the JavaScript correctly.
I hope this solves your problems.
p.s. sorry for my bad enlish :)


text:
Q: Identyfing the namespace of an inner XML element Suppose I have such elements in my XML document:
<xs:appinfo>
  <CustomXML>
    <Something>something</Something>
  </CustomXML>
</xs:appinfo>

"xs" is declared as the default schema namespace. My question is: how would a parser interpret the inner elements of xs:appinfo? In which namespace do they belong?
I ask because I'm parsing the code in C# and it keeps adding "xmlns="" " to the CustomXML element, which makes me assume that otherwise it'd treat these elements as schema elements.

A: According to §6.2 Namespace Defaulting of Namespaces in XML 1.0 (Third Edition):

The scope of a default namespace declaration extends from the beginning of the start-tag in which it appears to the end of the corresponding end-tag, excluding the scope of any inner default namespace declarations. […]
A default namespace declaration applies to all unprefixed element names within its scope.

That means that elements with no namespace prefix are interpreted as being in the default namespace. Default namespace is usually defined on the first element of the document and look like this:
<element xmlns="namespace-uri">

The library redefines the default namespace when it's necessary, that is, when you add an element to the document with no namespace. In other words, such element is not in the default namespace, so the library solves this by adding xmlns="" to that element, which redefined the default namespace for this element and all its descendants to "no namespace".
If you want to add element that is in the default namespace, you have to specify it explicitly. For example, in LINQ to XML:
XDocument doc = …;

var ns = doc.Root.GetDefaultNamespace();

var newElement = new XElement(ns + "foo"));


text:
Q: Static UITableView created in IB/Storyboarding With dynamic content? I'm wondering if I could make a basic UITableView and statically set up everything using IB/Storyboarding in Xcode 4.2 but just one of the cells I want to display the current app version. (I'm making an about view) and I don't want to hardcode the app version because I know I'll forget to update it down the road. Is there any way to have that one cell get its data from the dataSource? I tried implementing
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}

// Configure the cell...
if (indexPath.section == 0 & indexPath.row == 0) {
    cell.textLabel.text = [self appVersion];
}

return cell;
}

I've tried setting the cellIdentifier on all cells to @"Cell" as well as just setting it on the cell I care about modifying.
and only for that cell returning the app version but that wipes out the content of all the other cells.

A: If you are using a Static table in Storyboards the static table is the data source.
With a Static Table in Storyboard you would put a UILabel in the cell in question. Than setup a IBOutlet property in your View Controller and hook up the label to the outlet.
Then just update the label to your version number. You can hook up as many outlets as you want to different cells in a static table. Static table just means there is a fixed number of cells , you can still dynamically change the content of those fixed number of cells.

A: Use different ID for the first row.


text:
Q: Fixed differential field by a subgroup of a differential Galois group I am currently reading the book "Differential Galois Theory" by Springer and Van der Put. In the process of establishing that the field fixed by the differential galois group of a picard vessiot extension is the base field, the authors remark that:
If $G$ is a differential galois group for a Picard-Vessiot extension of fields associated to a differential equation over the base field and $H$ be a subgroup of the differential Galois group, then $L^{H}= L^{\overline{H}}$, where $\overline{H}$ is the Zariski closure.
Can anyone help me to see why this is very obvious, as that is what the authors have remarked.
Thanks.


text:
Q: How do I figure out month and year of birth from data that includes multiple observations and age in R I have data that includes multiple observations of the 1000's of people over many years. These data include the age at the time of observation. The data looks like this:
Person A | 2016-01-0 | 35
Person A | 2016-01-3 | 35
Person A | 2016-01-8 | 36

In this case, you'd be able to tell that Person A was born between 1980-01-04 and 1980-01-08 I'd like to be able to capture the date of birth (the month and year of birth will also do - even just the year of birth is fine) for all people in the data. Not sure, however, how to go about doing this without manually looking through and seeing where the age changes and taking note of the corresponding date.
Any help is greatly appreciated.

A: Each row gives us one possible range for that person. If you take the latest "min_DOB" and the earliest "max_DOB" of those rows for each person, you can get the kind of narrowed-down range you described.
library(dplyr); library(lubridate)
df %>%
  mutate(min_DOB = V2 %>% ymd - years(V3) - 365, # dragons b/c leap years;
         max_DOB = V2 %>% ymd - years(V3)) %>%
  group_by(V1) %>%
  summarize(min_DOB = max(min_DOB),
            max_DOB = min(max_DOB))

# A tibble: 1 x 3
  V1       min_DOB    max_DOB
  <chr>    <date>     <date>
1 Person A 1980-01-04 1980-01-08

data
df <- data.frame(
  stringsAsFactors = FALSE,
                V1 = c("Person A", "Person A", "Person A"),
                V2 = c("2016-01-01", "2016-01-03", "2016-01-08"),
                V3 = c(35L, 35L, 36L)
)

A: You may extract the year by removing everything after the first - and subtract the age from it.
df <- transform(df, yob = as.numeric(sub('-.*', '', V2)) - V3)

#        V1        V2 V3  yob
#1 Person A 2016-01-0 35 1981
#2 Person A 2016-01-3 35 1981
#3 Person A 2016-01-8 36 1980

data
df <- structure(list(V1 = c("Person A", "Person A", "Person A"), V2 = c("2016-01-0",
"2016-01-3", "2016-01-8"), V3 = c(35L, 35L, 36L)),
row.names = c(NA, -3L), class = "data.frame")


text:
Q: Angular promise should call other promises I have a state which resolves as :
resolve: {
              accounts: function(utils) {
                return utils.getAccounts();
              },
              data: function(utils) {
                return utils.getData();
              },
              termsData: function(utils) {
                return utils.getTerms();
              }
            }

I need to make sure that data and termsData are called only after accounts is returned in angular resolve.
getAccounts function looke like :
 function getAccounts() {
            var deferred = $q.defer();
            Restangular.setBaseUrl(baseUrl());
            var accountsService = Restangular.all(accountsUrl);
            accountsService.post({headers}).then(function(data) {
              deferred.resolve(data);
            }, function(ex) {
              deferred.reject(ex);
            });
            return deferred.promise;
          }

A: You could add accounts as a dependency the same way like I suppose you do in controller:
resolve: {
          accounts: function(utils) {
            return utils.getAccounts();
          },
          data: ['accounts', 'utils', function(accounts, utils) {
              accounts.then(function(data){
                 return utils.getData();
              }, function(data){
                 return $q.reject();
              });
          }]
        }
}

A: You could do call other two once getAccounts function promise get resolved and then do return data with getData & getTerms promise with $q.all.
resolve: {
    accounts: function(utils, $q) {
        return utils.getAccounts().then(function(accounts){
            return $q.all([accounts, utils.getData(), utils.getTerms()])
        });
    }
}

Controller
app.controller('mainCtrl', function($q, $scope, accounts){
    console.log("accounts", accounts[0])
    console.log("getData Response", accounts[1])
    console.log("getTerms Response", accounts[2])
})

A: Assuming you need to get all your data asynchronously you can simply restructure your code to take advantage of the promise pattern.
var getAccounts = function(...) {
  return new Promise(resolve, reject) {
    ... do something and resolve or reject
  };
};

var getTermsData = funciton= function(...) {
  return new Promise(resolve, reject) {
    ... do something and resolve or reject
  };
};

var getData = = function(...) {
  return new Promise(resolve, reject) {
    ... do something and resolve or reject
  };
};

getAccounts.then(function(accounts) {
  return getTermData();
}.then(function(termData) {
  return getData(data);
}.catch(function() {
  // something went wrong!
}


text:
Q: How to load a WPF FormattedText object (from RTF or RichTextBox) My WPF app displays lots of text snippets at various places on a large canvas (a kind of post it note app)
I am currently rendering the text using FormattedText objects and 'drawing them' straight into Visual objects (for speed/efficiency)
Challenge I have is how to load/save/edit that rich text. I'd like to use a RichTextBox to edit the text - but I can't find a way to get the text out of the text box and into a FormattedText object (or visa versa)
Anyone know how this might be achieved? Only way I can think is to have some kind of 'serialise to/from RTF' capability on the FormattedText object - but that doesn't seem to exist.
Thanks

A: You can iterate through all of the inline objects inside of the RichTextBox.Document, Get all the dependency properties you are interested in, and then set them on a new FormattedText object.
var formattedTextToDraw = new List<FormattedText>();

foreach (var paragraph in RichTextBox.Document.OfType<Paragraph>())
{
    foreach(var inline in paragraph)
    {
        formattedTextToDraw.Add(new FormattedText(
            inline.Text, //Text
            inline.FontSize, //Fontsize
            inline.Foreground, //Color
            etc....) //Other properties for FormattedText constructor
    }
}

A: The link posted by Clemens above http://www.wpfmentor.com/2009/01/how-to-transfer-rich-text-from.html addresses my issue.
Similar to fooook's answer - iterate through the inline objects and apply their attributes to a FormattedText object.
Shame that FormattedText doesn't support images (like NSAttributedString on iOS/OSX)


text:
Q: How to make a div not break when resizing browser Guys I have three divs in this setup: I'm not sure if you're familiar with this bootstrap css but i should give it a try:

 A graph here

 A graph here

 A graph here

 Another graph here

 Another graph here

 Another graph here

span4 will make the three divs fit to the whole page proportionally. So the position is the three graphs will position each other to the top div side by side, and another three graphs below it.
My problem is, when i resize the browser window, the graphs will be under each other vertically, like they have their own container now. How to make those graphs, retain their side by side position?

A: you can do the following:

 A graph here

 A graph here

 A graph here

 Another graph here

 Another graph here

 Another graph here

and css:
.third{
float:left;
width:33.33%;
}

A: You need to put them in divs like so  -

    graph1

    graph2

    graph3

Each rows divs should add up to 12 to fill that row completely. Where the col-X is on your div class= represents when your divs will stack vertically instead of horizontally. So if you had col-sm-4 your divs would stack vertically on the bootstrap "small" resolution media query. By setting them as col-xs-4 each row will stay horizontal on the small resolutions.
Also check out these resources
Bootstrap official documentation
Understanding BootStrap grid system for beginners


text:
Q: Angular 7 http (post) with authorization headers -> Error 500 I've got a problem in implementing authorization in an Angular 7 app. I send data to an API (PHP) via HttpClient.post and without adding headers everything works fine. If I add any headers f.e.
headers = headers.set('authorization', 'Bearer ' + this.user.token);

the request is sent via OPTIONS instead of POST and the server responds with a 500-error. I've successfully tried a test with jQuery.ajax. There's a before-send handler for adding the headers.
I've also tried to use an Interceptor for the request, but the problem is the same. Does anyone has an idea, what I can try to solve this?

A: It must be with CORS settings. Add the following settings in the web service, where '*' includes OPTIONS, GET, POST & other HTTP verbs.
Access-Control-Allow-Headers: *
Access-Control-Allow-Methods: *


text:
Q: Rate transition matrix of a machine Given a machine that remains operating for a period of time is exponentially
distributed with a mean of $10$ days. When the machine fails, the failure is one of two types: If the failure is type-I, then the time to repair the machine is exponential with a mean of $1$ day. If the failure is type-II, then the time to repair is exponential with a mean of $4$ days. A failure is type-I with probability $0.8$ and type-II with probability $0.2$, independent of all else. A repaired machine is as good as new.
(a) Find the rate transition matrix $Q$.
(b) Give the transition matrix $P$ for the embedded Markov chain.
(c) What is the fraction of time the machine is operating?
(d) Suppose that the machine generates $100$ per day in revenue when working. Suppose that a type-I failure costs $150$ to repair. A type-II failure costs $1000$ to repair. What is the net rate of money (revenue minus cost) generated by the machine?
My attempted solution  We define $3$ states for our CTMC: (A) $= 0$ machine fails, (B) $= 1$ machine fails with type-I, (C) $= 1$ machine fails with type-II. Now the rate transition matrix is $$Q =\pmatrix{-0.1 & 0.08 & 0.02\\ 1 & -1 & 0 \\ 0.25 & 0 & -0.25}$$
(b) From part (a), we get: $$P =\pmatrix{0 & 0.8 & 0.2\\ 1 & 0 & 0\\ 1 & 0 & 0}$$
(c) We need to find $\pi_{0}$ for solving the equation: $\pi P=\pi$ with $\sum_{i=0}^{2} \pi_{i} = 1$. Solving this system of equations, we get: $\pi_{0} =\frac{1}{2}$, $\pi_{1} = 0.4$ and $\pi_2 = 0.1$.
(d) We have: Revenue $= 100\times \pi_{0} = 50$ (this is the part I'm skeptical, since the problem said 100 PER DAY).
Cost $= 150\times \pi_{1} + 1000\times \pi_{2} = 160$.
Thus net rate of money $= 50 - 160 = -110$ (the result seems not to make sense, as this would be a money-losing machine)
My question: Could someone please help me review the solution to part (a) + (d) above?


text:
Q: Nested while loop won't ask to run program again correctly Well I have this hw problem where I have to use only nested while loops no do whiles at all.So basically I have the code down, but it wont run parts of the loop it keeps saying yes or no. Its suppose to go like this
Guess the secret number.
Enter maximum value for secret number: 10
A new secret number has been chosen.
Enter guess: 3
Too low; try again.
Enter guess: 8
Too low; try again.
Enter guess: 9
Too low; try again.
Enter guess: 10
You won in 4 guesses!
Play again? (Y/N) y
A new secret number has been chosen.
Enter guess: 7
Too high; try again.
Enter guess: 3 Too low; try again.
Enter guess: 5
You won in 3 guesses!
Play again? (Y/N) n
 public static void main(String arg[])
{
    int guess = 0,max,guesses = 0;
    String response;
    Scanner input= new Scanner(System.in);
    System.out.println("Guess the secret number\n");
    System.out.println("Enter maximum value for secret number: ");
    max=input.nextInt();
    int numbers=(int) (Math.random()* max) + 1;
    while(true)
    {
        System.out.println("A new secret number has been chosen.");

        while (guess!=numbers)
        {
            System.out.println("Enter guess");
            guess=input.nextInt();
            guesses++;

            if (guess<numbers)
            {
                System.out.println("Two low; Try again ");
            }
            else if (guess>numbers)
            {
                System.out.println("To high; Try again");
            }

        }
        System.out.println("You won in " + guesses + "!");
        System.out.print("\nPlay again? (Y/N)");
        response = input.next();
        if(response.equalsIgnoreCase("y"))
        {
            continue;
        }
        else
        {
            break;
        }

    }
    input.close();
}

(this is what I get )
Enter maximum value for secret number:
  5
A new secret number has been chosen.
Enter guess
4
To high; Try again
Enter guess
3
You won in 2!
Play again? (Y/N)y
A new secret number has been chosen.
You won in 2!
Play again? (Y/N)y
A new secret number has been chosen.
You won in 2!
Play again? (Y/N)
(so the loop won't call in to guess again)

A: You need to reinitialize guess and numbers to start a new round of the game.
Move these two lines down, inside the outer while loop:
int numbers=(int) (Math.random()* max) + 1;
int guess = 0, guesses = 0;

A: You are close, but you need to reset your important values after each time you win. You can do this by simply moving them into your outer nest loop so that each time the inner loop breaks, they get reset to what you want them to be before each round of the guessing game. See here:
 public static void main(String arg[])
{
    Scanner input= new Scanner(System.in);

    while(true)
    {
        int guess = 0,max,guesses = 0;
        String response;
        System.out.println("Guess the secret number\n");
        System.out.println("Enter maximum value for secret number: ");
        max=input.nextInt();
        int numbers=(int) (Math.random()* max) + 1;
        System.out.println("A new secret number has been choosen.");

        while (guess!=numbers)
        {
            System.out.println("Enter guess");
            guess=input.nextInt();
            guesses++;

            if (guess<numbers)
            {
                System.out.println("Two low; Try again ");
            }
            else if (guess>numbers)
            {
                System.out.println("To high; Try again");
            }

        }
        System.out.println("You won in " + guesses + "!");
        System.out.print("\nPlay again? (Y/N)");
        response = input.next();
        if(response.equalsIgnoreCase("y"))
        {
            continue;
        }
        else
        {
            break;
        }

    }
    input.close();
}


text:
Q: Different fields for every user on a view in asp.net mvc I am going to make an application in which every user have its own specification .
Suppose i have a table which have following fields
Data
    Id
    Name
    Date
Now one user say that i need a description field where i can put my description
other user comes and says that i need two new fields IsVerified , IsLocal .
Now my question is that how peoples manage this kind of applications .
At view side how can we determine that which fields should be rendered for current visiting user .
and how to manage same scenario in database .
What i think for database end , we can put all possible fields in table but don't know that is this apparoach is good or not
So please give me idea how to manage that type of application and it will be very helping if anyone gives a link to example .
Thanks in advance .

A: Create seperate table for user & fields like
Table: User
UserId Name Date

Table: Field
FieldId UserId Name Value

here Field table contains all user fields, we can get perticuler user field by UserId.
may this help to you..

A: In an asp.net setting, I would use the profile provider for this kind of needs.
You can implement your own by inheriting from ProfileBase.
Documentation and examples (scroll down) here:
http://msdn.microsoft.com/en-us/library/system.web.profile.profilebase.aspx
For your particular need, you could use a Hashtable, or even a dictionary, the user can store anything he/she wants, on any given key. Hashtables and Dictionaries needs to be serialized as binary.
[SettingsAllowAnonymous(false), SettingsSerializeAs(SettingsSerializeAs.Binary)]
[ProfileProvider("AspNetSqlProfileProvider")]
public Hashtable Fields
{
get
{
return base["Fields"] as Hashtable;
}
set
{
base["Fields"] = value;
Save();
}
}


text:
Q: htaccess rewrite with a cookie which is equal to a php script that returns a variable I have a folder that's located under my root file , I'm trying to restrict access to that folder by using cookies
What I want is to rewrite a redirect based on a cookie value ,
For example in my htaccess I have this
 RewriteEngine On
 // check if cookie is set and is equal to script.php
 RewriteCond %{HTTP_COOKIE} ^(.*)mycookie=[script.php]  [NC]
 // allow access if above condition is met [ which i cant figure out how to implement]
 RewriteRule ^ http://example.com/folder/index.html [NC,L]
 // or if the conditions above are not met rewrite somewhere else

Now here is how I want it work
When user clicks this url.. http://example/contents/folder/index.html , Server should check if the mycookie isset and is equal to a variable returned with script.php file , then if condition is met let them in or rewrite to another url
The script.php returns a variable that is in the database
This variable is generated every time user signs in and updates a row field in the database to prevent reuse of cookie variable . meaning one wont be able to manipulate cookie by either setting their own variable or copying and reuse them somewhere else .
Everything in the script.php is taken care my problem is with htaccess file .
Please help

A: What I'm suggesting in my comments is that your .htaccess would simply intercept and forward the request to the script.php file. It's then your script who is responsible for both verifying the cookie as well as what finally gets displayed.
RewriteRule ^folder/index\.html$ /folder/script.php [NC,L]

Now, in you php, verify the cookie and include or redirect accordingly.
<?php
    if (isset($_COOKIE["myCookie"]) && verifyCookie($_COOKIE["myCookie"])) {
        include 'index.html';
    } else {
        header ("Location: http://domain.com/some/other/page.php");
    }
?>


text:
Q: Forms authentication in web.config I am using MVC3 and have put the user authentication in the web.config file. This is to bypass sqlserver authentication.
code as below in web.config:
<authentication mode="Forms">
      <forms loginUrl="~/Account/LogOn" timeout="2880" >
        <credentials passwordFormat="Clear">
          <user name="test123" password="test123" />
        </credentials>
      </forms>
</authentication>

I tried login with the mentioned user id and password, I am getting error in the page as
Login was unsuccessful. Please correct the errors and try again.
* The user name or password provided is incorrect.

when I debug into the AccountController.cs file, failing at the MembershipService.ValidateUser(model.UserName, model.Password) method.

A: If you examine standard ASP.NET MVC 3 AccountController.cs and AccountModels.cs files you'll learn what MembershipProvider.ValidateUser method is used internally (via Membership.Provider). If you want to store password in web.config you should use FormsAuthentication.Authenticate method instead.
For example:
public class AuthorizationController : Controller
{
    public ActionResult LogOn()
    {
        return View("LogOn");
    }

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult LogOn(string userName, string password,
        bool rememberMe, string returnUrl)
    {
        if (!ValidateLogOn(userName, password))
            return View("LogOn");

        FormsAuthentication.SetAuthCookie(userName, rememberMe);

        if (!string.IsNullOrEmpty(returnUrl))
            return Redirect(returnUrl);
        else
            return RedirectToAction("Index", "News");

    }

    private bool ValidateLogOn(string userName, string password)
    {
        if (string.IsNullOrEmpty(userName))
            ModelState.AddModelError("username", "User name required");

        if (string.IsNullOrEmpty(password))
            ModelState.AddModelError("password", "Password required");

        if (ModelState.IsValid && !FormsAuthentication.
            Authenticate(userName, password))
            ModelState.AddModelError("_FORM", "Wrong user name or password");

        return ModelState.IsValid;
    }

    public RedirectToRouteResult LogOff()
    {
        FormsAuthentication.SignOut();

        return RedirectToAction("LogOn");
    }
}


text:
Q: Launchbar + panel overlaps when showing a dialog box in fullscreen I'm developing a program for 12.04 that will run on full-screen, so I would like to have full control of what appears on the screen.
However, when I show another window (possibly a dialog/message box), the Unity Panel and Launcher appears on the top and left side of the screen. I've experienced this behavior with other applications (Firefox, Gnubg) as well when in full-screen mode.
I tried to play with the settings, now my dialog box is hidden from the the taskbar, set to float on it's parent, which is my full screen window. The problem still exists.
Is there a way to prevent these panels from showing up, when the new window isn't shown in taskbar, or it's parent is a full-screen window? Or do I need to completely disable them?

A: This is a bug in Ubuntu that I've noticed.
It could possibly be related to this:
https://bugs.launchpad.net/ubuntu/+source/unity/+bug/748539


text:
Q: Render data from DataTables to lowercase I need to render data returned by dataTables to lowercase. I've search the net but can't find any post on the subject. Convert "ImageName" content to lowercase before displaying. My code is:
{ data: 'ImageName',  "sWidth": "20%",  render : function (data, type)
    { return '<img src="' + imagepath + '' +data+'" class="WayfinderSignageImage"/>'; }
},


text:
Q: Backbone.js change event not firing after set() call similar to a succesful one I am changing my MyModel's longitude and latitude attributes in two cases, but my MyView only notices one of them:

*

*When FAKE_LOCATION == true, I set (lat,long) in update and no change event is fired.

*When FAKE_LOCATION == false, I set (lat, long) in the callback of navigator.geolocation.getCurrentPosition: success and change event is fired.

var MyModel = Backbone.Model.extend({
    initialize: function() {
        _.bindAll(this,'success','update');
        this.update();
    },

    update: function() {
        if(!FAKE_LOCATION){
            if(navigator.geolocation)
                navigator.geolocation.getCurrentPosition(this.success);
        }else{
            this.set({
                latitude : 37,
                longitude : -122
                                    //previously, I was using constants here
            });
        }
    },

    success: function(position) {
        this.set({
            latitude : position.coords.latitude,
            longitude : position.coords.longitude
        });
    }
});

var MyView = Backbone.View.extend({
    initialize: function(){
        this.listenTo(this.model,'change', this.render);
    }
});

var myModel = new MyModel();
var myView = new MyView({ model : myModel });

A: Assuming FAKE_LOCATION_LAT and FAKE_LOCATION_LONG are constants, then you set latitude and longitude during initialization in the .initialize() method. Subsequent calls to .set() won't actually change the value, so no change takes place, and no change events are triggered.
Add this to your code to make sure the values actually change:
}else{
    this.set({
        latitude : 37 + Math.random(),
        longitude : -122
    });
}


text:
Q: Why can't mv preserve permissions when moving between Android SD cards? After mounting both SD cards on an Android phone using the "USB mass storage" mode I keep getting these messages when moving files between them:
mv: failed to preserve ownership for '/.../foo': Function not implemented
mv: preserving permissions for '/.../foo': Function not implemented

Is this a problem in any way? And is it simply because of the possibly unusual combination of file systems?
$ mount | grep /run/media
/dev/sdc on /run/media/... type fuseblk (rw,nosuid,nodev,relatime,user_id=0,group_id=0,allow_other,blksize=4096)
/dev/sdb on /run/media/... type vfat (rw,nosuid,nodev,relatime,uid=1000,gid=100,fmask=0022,dmask=0077,codepage=437,iocharset=iso8859-1,shortname=mixed,showexec,utf8,flush,errors=remount-ro,uhelper=udisks2)

A: type vfat

There's your problem.  vfat knows nothing about Linux permissions.  It's not an issue of USB mounts, but of file-systems used.
Oh: and to answer your question - no, it's not a problem.


text:
Q: как каждый элемент серии перевести в двоичную систему из шестнадцатиричной подскажите, пожалуйста, как из 16й системы можно быстро перевести в двоичную.
Если по одному числу записывать, то всё ок, работает.
a = int('0x3AF4580', 16)
b = bin(a)

(где 3AF4580 число в 16й системе)
К серии применить не получается. В руку так перебирать 190 тыс шт. долго. Подскажите, пожалуйста, как ускорить процесс.

A: ну так пишите не по одному, а на все серию:
вот у вас есть pandas.Series s:
     0
0   16
1   22
2  512
3    1
4   69
5   86

далее просто делаете:
s = s.apply(bin)

теперь s:
              0
0       0b10000
1       0b10110
2  0b1000000000
3           0b1
4     0b1000101
5     0b1010110

Если же у вас серия с явной шестнадцатиричгой записью:
      0
0   0xa
1  0x10
2  0xc8
3   0x1
4  0x2d
5  0x38

то перевести в двоичную можно так:
s = s.apply(int, base=16).apply(bin)

получаете s:
            0
0      0b1010
1     0b10000
2  0b11001000
3         0b1
4    0b101101
5    0b111000


text:
Q: How can I create thousands of images and pixels in the screen at the same time? using Python For a simulation project, I need to create and manage a huge number of individual pixels and small gifs in a graphics environment under python.
I tried "graphics.py". But, it crashes after adding around 3000 objects. The error code is not self-explanatory:
"Python has stopped working" Problem signature: Problem Event Name: APPCRASH Application Name: python.exe Application Version: 3.5.1150.1013 Application Timestamp: 576eff6a Fault Module Name: tcl86t.dll
Do you have any idea what is the problem? Even, is "graphics.py" suitable for handling a great number of objects?
Thanks
ADDED:
Here is a sample of when I instantiate a new object or move it:
...
    self.image__ = Image(Point(self.x_, self.y_), 1, 1)

           #shaping image with some pixels
    self.shape_single_cell()

           #sending image to the screen
    CreatureSingleCell.world_handle__.draw_image(self.image__)

...
    #moving the image to a new spot in the screen
def action_single_cell_moving(self, dx, dy):
     self.image__.move(dx, dy)

A: Not a final answer yet, but just so you have something to look at for the meantime, I created a simulation where I have 1000 squares which randomly twitch around. Using the simple but slow techniques involving glBegin that I mentioned in my comments, I still get about 60 fps, while at 10000 objects, it drops to 7 fps. No texturing or object birth/death at the moment, but I thought it might be a good start. Is this a reasonable representation of your evolution simulation? Also let me know what performance you get on your computer and if this is sufficiently fast for your simulation purposes or if it needs to switch to more complicated/advanced techniques.
from OpenGL.GL import *
from OpenGL.GL import shaders
from OpenGL.GLU import *
import math
import pygame
import random
import sys
import time

class Creature(object):
    def __init__(self):
        self.size = 10
        self.x = 0
        self.y = 0

    def move(self, dx, dy):
        self.x += dx
        self.y += dy

    def set_pos(self, x, y):
        self.x = x
        self.y = y

class Simulation(object):
    def __init__(self, world_size, num_creatures=1000, max_move=1):#not really max by pythagorean theorem
        self.width, self.height = world_size
        self.max_move = max_move
        self.creatures = self.setup(num_creatures)

    def setup(self, num_creatures):
        creatures = []
        for i in range(num_creatures):
            x = int(random.random()*self.width)
            y = int(random.random()*self.height)
            creature = Creature()
            creature.set_pos(x, y)
            creatures.append(creature)
        return creatures

    def update(self):
        for creature in self.creatures:
            dx = int(round(random.uniform(-self.max_move, self.max_move)))
            dy = int(round(random.uniform(-self.max_move, self.max_move)))
            creature.move(dx, dy)

if __name__ == "__main__":
    width = 800
    height = 600
    title = "Random Simulation"
    target_fps = 60
    pygame.init()
    size = (width, height)
    flags = pygame.DOUBLEBUF|pygame.OPENGL
    pygame.display.set_mode(size, flags)
    pygame.display.set_caption(title)

    c = Creature()
    sim = Simulation(size)

    prev_time = time.time()
    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()
                pygame.quit()

        sim.update()
        glClear(GL_COLOR_BUFFER_BIT)
        glMatrixMode(GL_PROJECTION)
        glLoadIdentity()
        glOrtho(0, width, height, 0, -1, 1)
        glMatrixMode(GL_MODELVIEW)
        glLoadIdentity()

        for i in sim.creatures:
            glBegin(GL_QUADS)
            glVertex(i.x - i.size/2.0, i.y - i.size/2.0)
            glVertex(i.x + i.size/2.0, i.y - i.size/2.0)
            glVertex(i.x + i.size/2.0, i.y + i.size/2.0)
            glVertex(i.x - i.size/2.0, i.y + i.size/2.0)
            glEnd()
        pygame.display.flip()

        curr_time = time.time()
        diff = curr_time - prev_time
        delay = max(1.0/target_fps - diff, 0)
        time.sleep(delay)
        fps = 1.0/(delay + diff)
        prev_time = curr_time
        pygame.display.set_caption("{0}: {1:.2f}".format(title, fps))


text:
Q: How to replace a character by regex in ruby How to replace a letter 'b' to 'c' after a duplicate letter 'a' base on 2 times?
for example  :
ab => ab
aab => aac
aaab => aaab
aaaab => aaaac
aaaabaaabaab => aaacaabaac

A: You should check groups of aa followed by b and then replace captured groups accordingly.
Regex: (?<!a)((?:a{2})+)b
Explanation:
(?<!a) checks for presence of an odd numbered a. If present whole match fails.
((?:a{2})+)b captures an even number of a followed by b. Outer group is captured and numbered as \1.
Replacement: \1c i.e first captured group followed by c.
Test String:
ab
aab
aaab
aaaab
aaaabaaabaab

After replacement:
ab
aac
aaab
aaaac
aaaacaaabaac

Regex101 Demo


text:
Q: Get triggered custom UIButton on UITableView and avoid tapping on the table row I've a UITableView with a custom UIButton.
I want to know how can I know which UIButton tapped and then pass data to void function.
My code is:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];

    if (cell == nil)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }

    // Configure the cell...
    tableView.backgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"row320x63.png"]];

    // Cell text
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(65, 20, 220, 21)];
    label.text = [self.arrayOfAlarmSound objectAtIndex:indexPath.row];
    label.backgroundColor = [UIColor clearColor];
    label.textColor = [UIColor whiteColor];
    label.font = [UIFont fontWithName:kFONT_NAME size:kFONT_SIZE];
    label.textAlignment = NSTextAlignmentLeft;
    [cell.contentView addSubview:label];

    // Play button
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button addTarget:self action:@selector(playMusicWithIndex:) forControlEvents:UIControlEventTouchDown];
    [button setImage:[UIImage imageNamed:@"play_off"] forState:UIControlStateNormal];
    [button setImage:[UIImage imageNamed:@"play_on"] forState:UIControlStateHighlighted];
    button.frame = CGRectMake(265, 13, 35, 35);
    [cell.contentView addSubview:button];

    return cell;
}

- (void)playMusicWithIndex:(NSNumber *)alarmSoundIndex
{
    NSLog(@"Play Music");
    NSInteger fileIndex = [alarmSoundIndex integerValue];

    NSString *path;
    // Get the filename of the sound file
    switch (fileIndex)
    {
        case kALERT:
            path = [NSString stringWithFormat:@"%@%@", [[NSBundle mainBundle] resourcePath], @"/ring.wav"];
            break;
        case kMAROKAEI:
            //
            break;
        default:
            break;
    }

    // Declare a sound id
    SystemSoundID soundID;

    // get a URL for the sound file
    NSURL *filepath = [NSURL fileURLWithPath:path isDirectory:NO];

    // Use audio services to create sound
    AudioServicesCreateSystemSoundID((__bridge CFURLRef) filepath, &soundID);

    // Use audio services to play the sound
    AudioServicesPlaySystemSound(soundID);
}

How can I pass the indexPath.Row to playMusicWithIndex:alarmSoundIndex?
When I use this code:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    [self performSelectorOnMainThread:@selector(playMusicWithIndex:) withObject:[NSNumber numberWithInteger:indexPath.row] waitUntilDone:NO];
}

Tapping a row in the table play the audio file, but thats not what I want, I want to play the audio file only when tapping the custom UIButton.
I hope I was clear.

A: There are some different ways to do this. One way is using tag property of the button:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ...

    // Play button
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.tag = indexPath.row;
    [button addTarget:self action:@selector(tap:) forControlEvents:UIControlEventTouchDown];
    [button setImage:[UIImage imageNamed:@"play_off"] forState:UIControlStateNormal];
    [button setImage:[UIImage imageNamed:@"play_on"] forState:UIControlStateHighlighted];
    button.frame = CGRectMake(265, 13, 35, 35);
    [cell.contentView addSubview:button];

    return cell;
}

- (void)tap:(UIButton *)sender
{
    [self playMusicWithIndex:[NSNumber numberWithInteger:sender.tag]];
}


text:
Q: Stm32CubeProgrammer not connecting (no error msg) using ST-LINK V2 dongle and Lora E5 mini board I've tried countless settings in an attempt to program my stm32 board. The main tutorial I followed is https://wiki.seeedstudio.com/LoRa_E5_mini/.
I have connected a USB st-link v2 dongle to my laptop with pins SWDIO, SWCLK, GND correctly wired to the STM32 board.
For power the board is also connected to a usb port via its type c connector.
Serial comms over usb work, updating the st link firmware works and stm32cube programmer finds the st link device:

I now press the reset button, hold it, click on Connect, release the reset button after 3 seconds and then.. absolutly nothing happens and no error message appears.
I've tried the same thing with ST-LINK utility. When holding the reset button the LED on the  st link dongle starts flashing, but whenever I release the button I get this:

I was not able to find the same issue on google, since everyone else is getting error messages if it doesn't work.
Has anyone run into the same problem? What part could be the issue?

A: The solution for me (my own custom board) was to enable "Shared" option.
Symply after enabling the feature the serial number appears instead of "G".
Hope it's your same problem.

A: You probably have a fake chip (no ST chip). Look at the picture.

I have the same problem. In my case the serial number is E and the trick with Shared enable does not work. Installing the old programmer   STM32 ST-LINK Utility helped me. Also using this program the full serial number is visible.

A: You can try the following suggestions. Some ST devices are a lot more sensitive than others when it comes to programming. I have had some ST devices programming without issues and then using practically the same setup on other devices it just won't work.

*

*Place a 22ohm resistor in series on the SWDIO and SWCLK lines. This link suggests only placing it on the SWDIO line but I found that I needed it on the SWCLK line as well. Typical SWD Circuit

*For the ST Link Settings try using these:

*

*Reduce the frequency from 4MHz to a lower frequency

*Use SWD

*Use connect under reset

*Don't use an external pull-up on the NRST line. I have also found that using a 100nF Cap on the NRST line might affect the programming. Try programming without a NRST capacitor.

*Make sure that your programming wires between the ST-LINK and the target board are as short as is conveniently possible.

*(This one I must stress as being important) Make sure that your processor's ground pins are all connected very closely together (i.e. the tracks between them are as short as possible) and that very importantly your programmer ground is also connected to the same ground pins very closely.- At high programming speeds a thin or long unbalanced (different length) ground track to the processor can cause a problem with some devices.

*Whatever you are using to supply power to the processor must have a supply with a similar voltage as the ST-LINK (mine is 3V) - (although I have found that if the processor supply is 3.3V programming seems to still work most of the time.) (Remember the original ST-Link does not supply power only reads the power level.)

*A dodgy programming setup can accidentally set the protection to LEVEL 2 bricking your device - so if you have been trying and not getting any further, it might be time to replace your IC.

*Prior to changing / erasing a device that had been programmed to LEVEL 1, you might need to first enable the PCROP_RDP option byte. - Once enabled, you should be able to change from LEVEL 1 to LEVEL 0 that will automatically erase the device.

*Some people have suggested holding the device in reset until just after pressing the erase button to enable erasing it.
I hope these suggestions help...

A: I just wanted to chime in for the next person who comes along with this problem.  @Jarek's solution is what worked for me.  In my case, I have two St-Link V2 USB dongles, and both have a Geehly chip instead of an ST chip inside.  I updated the firmware on both using ST's Firmware upgrade utility and tried every possible combination of settings in STM32CubeProgrammer but was unable to get anything to happen upon clicking 'Connect'.  This includes not getting any error messages.  The serial number for both of my dongles was a single letter ("A" and "D").  I never managed to get them working with STM32CubeProgrammer, but was able to use them with the deprecated STM32 ST-LINK Utility as well as using them as a debugger with IAR.
It seems like this is a bug with STM32CubeProgramer which will hopefully be resolved in the future.

A: Feel you, i did exactly the same stuff, with the same hardware, and nada. got it writing CCCCCC fine to putty though.


text:
Q: Induction Using Multi-Index Does anyone know how to use induction in the context of multi-indices?
I know the induction is done on the multi-index length, the main problem is how to split a multi-index of length $n+1$ into one of length $n$ and another of length $1$.
For example, I have the following problem: Prove that $|x^\alpha|\leq |x|^{|\alpha|}$ for all $\alpha\in\mathbb N^n$ and $x\in\mathbb R^n$.
The first inductive step is using $\alpha=e_j$: $|x^\alpha|=|x_j|\leq |x|=|x|^{|\alpha|}$. Now I suppose $|x^\alpha|\leq |x|^{|\alpha|}$ for every multi-index of length $n$. Now how to prove the result is true for $\alpha$ of length $n+1$?

A: Let $\alpha$ be a multi-index of length $n+1$ so that there exists a multi-index $\beta$ of length $n$ and an index $j$ with $\alpha = \beta + e_j$. Then $$x^\alpha = x^{\beta + e_j} = x^\beta x_j.$$ Now invoke the induction hypothesis: $$|x^\alpha| = |x^\beta x_j| = |x^\beta||x_j| \le |x|^{|\beta|}|x_j|.$$ Since $|x_j| \le |x|$ you get $|x^\alpha| \le |x|^{|\beta| + 1} = |x|^{|\alpha|}$.


text:
Q: Wants to open html file in modal pop up from @Html.ActionLink I want to open html file in modal pop up from @Html.ActionLink. I have path given in ExampleUrl  which I am getting from the database. I have written JQuery to do this but FileName getting undefined. Anyone please guide me.
 //My code

 @Html.ActionLink("Example", "#", new { FileName = item.ExampleUrl }, new { @data_toggle = "modal", @data_target = "#myModal" })

//JQuery
$('#myModal').on('show.bs.modal', function (e) {
            debugger;
            var dataURL = $(this).attr('data-FileName');
            $('.modal-body').load(dataURL, function () {
                $('#myModal').modal({ show: true });
            });

        });

My modal

Modal title

                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    ×
                </button>

               ...

                <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>

A: I don't know why you are using the @Html.ActionLink to open model popup. it's better to use the normal button and avoid some addition code to call server side method like below.
Trigger the modal with a button
   <button type="button" class="btn btn-success openBtn" data-url="@item.ExampleUrl">Open Modal</button>

Modal

                    <button type="button" class="close" data-dismiss="modal">×</button>

Modal with Dynamic Content

                    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

Now load the content from an external URL in Bootstrap modal popup.

EDIT: If you want to put the files in View folder just place the following code in web.config file that allow you to access the static resources like js and html.
<system.webServer>
<handlers>
  <add name="JavaScriptHandler" path="*.js" verb="*"
     preCondition="integratedMode" type="System.Web.StaticFileHandler" />
  <add name="HtmlScriptHandler" path="*.html" verb="*"
     preCondition="integratedMode" type="System.Web.StaticFileHandler" />
  <remove name="BlockViewHandler"/>
  <add name="BlockViewHandler" path="*" verb="*" preCondition="integratedMode" type="System.Web.HttpNotFoundHandler" />
</handlers>


text:
Q: Override final method Final methods can not be overridden in a subclass. But with the magic of Scala it seems as this is possible.
Consider the following example:
trait Test {
  final def doIt(s: String): String = s
}

object TestObject extends Test {
  def doIt: String => String = s => s.reverse
}

The method doIt in the object TestObject has not the same signature as doIt in trait Test. Thus doIt is overloaded instead of overridden. But a normal call to doIt always calls the method in TestObject:
val x = TestObject.doIt("Hello")                //> x  : String = olleH

Question:
How can I call the original method doIt on the TestObject. Is this possible or is this method "sort of overridden"?

A: Another a little bit hackisch way is to call doIt with named parameter like this:
val x = TestObject.doIt(s = "Hello")

A: You can use TestObject as Test like this:
(TestObject: Test).doIt

A: Try this:
TestObject.asInstanceOf[Test].doIt("Hello")


text:
Q: XSLT sum function I need to generate an item that accumulates a total for a given XML input.
The XML input is:
<item id="15117180817160" amount="1441.63"/>
<item id="15117180817161" amount="300.10"/>

This is my XSLT:

   Nro. de Reclamo
   Monto $

 <xsl:for-each select="item">

          <xsl:value-of select="@item" />

          <xsl:value-of select="@amount" />

 </xsl:for-each>

      Total:

      <xsl:value-of select="sum(/item/@amount)"/>

And this is my output:

    id
    amount

    15117180817160
    1441.63

    15117180817161
    300.10

Total: 0

The result should be Total = 1741,73
How can I implement a sum function that returns the correct total value?
Best Regards
Jorge

A: Instead of doing this...
 <xsl:value-of select="sum(/item/@amount)"/>

Do this...
 <xsl:value-of select="sum(item/@amount)"/>

The initial / in the first expression represents the document node, so it would only work if the child root element called item. You haven't showed it in your XML sample, but as you have multiple item elements, they must be contained within a parent element.


text:
Q: What is the correct way to propagate errors? I'm trying to learn Rust, but I am faced with a difficulty when I implement the fmt::Display trait for one of my types. I want to do something like this:
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
    write!(f, "(");
    some_helper_function(self.t1, self.ctx, f);
    write!(f, " ");
    some_helper_function(self.t2, self.ctx, f);
    write!(f, ")")
}

All of these functions return fmt::Result, but this will be ignored. What is correct way for propagating the error result upward?

A: For every function call you check if the return is an Err object or not. If it's an Err object you return from the function, if not you continue.
There's a convenient macro in the standard library, called try! which does exactly this.
So your code would become something like this:
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
    try!(write!(f, "("));
    try!(some_helper_function(self.t1, self.ctx, f));
    try!(write!(f, " "));
    try!(some_helper_function(self.t2, self.ctx, f));
    try!(write!(f, ")"))
}

A: Andrea P's answer is spot on for how to fix this. I wanted to add on to this part though:

All of these functions return fmt::Result, but this will be ignored.

Note that the compiler tries really hard to help you here:
fn important() -> Result<u8, ()> {
    Err(())
}

fn main() {
    important();
}

Will produce this warning by default:
warning: unused result which must be used, #[warn(unused_must_use)] on by default
     important();
     ^~~~~~~~~~~~

You can even make it so that all warnings become errors by adding this to your crate:
#![deny(unused_must_use)]


text:
Q: How to put data of each month in its respective monthly column I'm still learning, please help me
I have this code that will show monthly statistics. How do I put each data of each month in its respective column?
This is what I got so far.
$result= $myDB->query("SELECT * FROM ".$myDB->prefix("statistics")." WHERE year='2017'") or die(mysql_error());
while($row = $myDB->fetchArray($result))
{
$id=$row['id'];
$year=$row['year'];
$sum=$row['sum'];
$january=$row['january'];
$february=$row['february'];
$march=$row['march'];
$april=$row['april'];
$may=$row['may'];
$june=$row['june'];
$july=$row['july'];
$august=$row['august'];
$september=$row['september'];
$october=$row['october'];
$november=$row['november'];
$december=$row['december'];
}

echo "

";

echo "Year	";
for($m=1; $m<=12; ++$m){
    $monthName=date('M', mktime(0, 0, 0, $m, 1)).'
';
echo "$monthName	";
}
echo "

";

echo "
";
echo "$year	";

for($m=1; $m<=12; ++$m){
echo " data 	";
}

echo "
";

echo "
";

A: As you are storing data in month name vaiable you can get it using $$ try this:
echo "

";

echo "Year	";
for($m=1; $m<=12; ++$m){
    $monthName=date('M', mktime(0, 0, 0, $m, 1));
echo "$monthName	";
}
echo "

";

echo "
";
echo "$year	";

for($m=1; $m<=12; ++$m){
    $monthName=strtolower(date('F', mktime(0, 0, 0, $m, 1)));
echo "".$$monthName." 	";
}


text:
Q: Why won't my tweet button appear on my page? My tweet button suddenly stopped appearing on my page. I am using one inside of the bootstrap grid system. There are no CSS styles attached to the tweet button apart from the default styles set by twitter.
My HTML:

            Tweet

tweet-list is populated with tweets from the Standard Search API programatically through JS and does not affect the tweet button.
Any help is much appreciated :)
Image of Button

Tweet

A: It turns out that the Tweet button doesn't work in Opera. I'm not sure why, but the tweet button appears in other popular browsers.


text:
Q: Writing .txt files to GCS from Spark/Dataproc: How to write only one large file instead of it automatically splitting in to multiple? I use Dataproc to run a Pyspark script that writes a dataframe to text files in google cloud storage bucket. When I run the script with big data, I automatically end up with a large number of text files in my output folder, but I want only one large file.
I read here Spark saveAsTextFile() writes to multiple files instead of one I can use .repartition(1) before .write() to get one file but I want it to run fast (of course) so I don't want to go back to one partition before performing the .write().
df_plain = df.select('id', 'string_field1').write.mode('append').partitionBy('id').text('gs://evatest/output', compression="gzip")

A: Don't think of GCS as a filesystem.  The content of a GCS bucket is a set of immutable blobs (files).  Once written, they can't be changed.  My recommendation is to let your job write all the files independently and aggregate them at the end.  There are a number of ways to achieve this.
The easiest way to achieve this is through the gsutil compose command.
References:

*

*How to concatenate sharded files on Google Cloud Storage automatically using Cloud Functions

*compose - Concatenate a sequence of objects into a new composite object.

*Google Cloud Storage Joining multiple csv files


text:
Q: Instant Article Builder - How do I add width and height in AdRules? I need to add fixed values in the ad rule. It's possible? or other way?
I'm trying this way, but the width and height don't work. I also tried using 'constant' and 'value' for the width and height, worked only for the url
    {
    "generator_name": "facebook-instant-articles-builder",
    "generator_version": "0.2.0",
    "rules": [
        {
            "class": "TextNodeRule"
        },
        {
            "class": "GlobalRule",
            "selector": "html",
            "properties": {
                "article.title": {
                    "attribute": "content",
                    "selector": "span i",
                    "type": "element"
                },
                "article.publish": {
                    "format": "Y-m-d\\TH:i:s",
                    "selector": "[ia-date]",
                    "type": "date"
                },
                "author.name": {
                    "selector": "[ia-author]",
                    "type": "string"
                },
                "image.url": {
                    "attribute": "content",
                    "selector": "[property=\"og:image\"]",
                    "type": "string"
                },
                "article.body": {
                    "selector": ".text",
                    "type": "element"
                },
                "article.canonical": {
                    "attribute": "href",
                    "selector": "link[rel=canonical]",
                    "type": "string"
                }
            }
        },
        {
            "class": "EmphasizedRule",
            "selector": "em"
        },
        {
            "class": "BoldRule",
            "selector": "b, strong"
        },
        {
            "class": "ImageRule",
            "selector": "img",
            "properties": {
                "image.url": {
                    "attribute": "src",
                    "selector": "img",
                    "type": "string"
                },
                "image.caption": {
                    "attribute": "src",
                    "selector": "img",
                    "type": "element"
                }
            }
        },
        {
            "class": "AdRule",
            "selector": "[ia-ad-url]",
            "properties": {
                "ad.url": {
                    "attribute": "ia-ad-url",
                    "selector": "[ia-ad-url]",
                    "type": "string"
                },
                "ad.width": {
                    "attribute": "ia-ad-width",
                    "selector": "[ia-ad-width]",
                    "type": "int"
                },
                "ad.height": {
                    "attribute": "ia-ad-height",
                    "selector": "[ia-ad-height]",
                    "type": "int"
                }
            }
        },
        {
            "class": "PassThroughRule",
            "selector": ".summary-content,.summary-news,.slot-g,.text,.youtube-embed,.related-content-hyperlink"
        }
    ]
}

https://developers.facebook.com/docs/instant-articles/sdk/transformer/
https://developers.facebook.com/docs/instant-articles/builder


text:
Q: Returning Elements Doesn't Work - JS I was creating an each function that handles different kind of callbacks such as

*

*iterateCollection  - w/c just returns/print the array or object items

*returnEvenElements - w/c returns even elements of an array

*returnKeyDivisbleBy3 - w/c returns elements of an array that aredivisible by 3

*returnKeyWithArrayValue - w/c returns the key or    property of an
object with an array value.
Here's what I mean:

var myArray = [1, 2, 3, 4, 5];

var myObject = {
  num1: 1,
  num2: 2,
  num3: [1, 2, 3]
};

function each(collection, callback) {
  if (collection instanceof Array) {
    for (var i = 0, l = collection.length; i < l; i++) {
      callback(collection[i]);
    };
  } else if (collection instanceof Object) {
    for (var prop in collection) {
      callback(collection[prop]);
    };
  }
}

function returnKeyWithArrayValue(collection, prop) {
  return collection[prop] instanceof Array;
}

function returnKeyDivisbleBy3(collection, prop) {
  return collection[prop] % 3;
}

function returnEvenElements(collection) {
  return (typeof collection === 'number') && !(collection % 2);
}

function iterateCollection(collection) {
  return collection;
}

var output1 = each(myArray, returnEvenElements);
console.log(output1);

var output2 = each(myArray, iterateCollection);
console.log(output2);

var output3 = each(myObject, returnKeyWithArrayValue);
console.log(output3);

var output4 = each(myArray, returnKeyDivisbleBy3);
console.log(output4);

But upon passing the context, it doesn't return anything even one of these doesn't work. I used the 'return' keyword to return the elements but nothign print them on screen or logs them.
Wondering if I am missing something? Please help!

A: The problem is that you aren't setting the callbacks to any value to return.  Set the callbacks into an array and then return that value out of the each function.
I slimmed down the code and gave an example fo returnEvenElements.  Hope this helps.
I was able to get [2, 4, 6] as a result with the code.
var myArray=[1,2,3,4,5, 6];

function each(collection, callback){
  const returnArray = [];  // <- create array to capture values
  if(collection instanceof Array) {
    for(var i=0, l=collection.length; i<l; i++){
      if (callback(collection[i])){ // <- check if condition is true
        returnArray.push(collection[i]); // <- set values in array
      }
    };
  }
  return returnArray; <- return the value
}

function returnEvenElements(collection){
  return (typeof collection === 'number') && !(collection % 2);
}

var output1 = each(myArray, returnEvenElements);
console.log(output1);

PS - Try looking into map, filter and reduce.  You can get the even numbers with -
const evens = myArray.filter(value => (value % 2 === 0));


text:
Q: Deal with huge amount of data in Firestore in flutter project Normally, we use StreamProvider to deal with the data from FireStore in Flutter project like this:
  // I have a collection of Customer in my DataService
  Stream<List<Client>> streamCustomers() {
    return Firestore.instance.collection('customers').snapshots().map((list) =>
      list.documents.map((doc) => Customer.fromMap(doc.data, doc.documentID)).toList());
  }

This is the Provider of stream data:
Expanded(
  child: StreamProvider<List<Customer>>.value(
    value: _dataSvc.streamCustomers(),
    child: CustomerListWidget(),
  ),
);

This is where the stream data consumed:
final _customers = Provider.of<List<Customer>>(context);
return Container(
  child: _customers == null? Text('Loading...') : _buildList(context, _customers),
);

I'll show all the customer data in CustomerListWidget. Because the data of Customer collection is very big (more the 10,000 - 50,000 records). Apparently this is not efficient solution. I'm wondering normally what kind of the practical solutions are used to deal with this scenario in Flutter/Firestore project?
P.S.: Pagination is definitely one of my possible choice. But there are some issues because I'll apply some filters to the data. For example, I have to query to Firestore every time when the filter criterio has been changed which will cause the data usage increased. And also it seems I can only use getDocuments() instead of snapshot to get the Stream data.

A: I think using Pagination is which better fits for you. Implementing pagination in Flutter using Firebase Cloud Firestore database can improve your app performance and reduce bandwidth usage (which is one of your biggest concerns). There are some articles about this.


text:
Q: Email Scheduler for Salesforce Would like to have an option where in an email is send on a particular date by clicking the Date?
Clicking the Date  means there will be a date field called Send email to CLient. This will send the email to the client on the specified date.
And the Record is stored in the Activity History.
For example: If a clients birthday is on Sunday and Today is Tuesday. We will write an email today saying Happy Birthday, then click the date field on Sunday.
The email will automatically send the email on that particular Date, like Sunday. Once the client receives the email, the Email will be stored in the Activity History.

A: Well, the out of the box way to implement it will be to create a workflow/ lightning process to automatically schedule sending email on a specific date to client (time based workflow actions). But

*

*Currently salesforce doesn't allow emails sent via workflows to be automatically recorded as activities (refer idea : https://success.salesforce.com/ideaview?id=087300000006povAAA)

*You'll have to use a predefined email template (Can possibly embed content from some custom fields)

Alternatively, you can store custom message in some field and create a custom apex scheduler to run daily and send email using the custom message stored for client. Scheduler will run daily and consider either today's or next day's date to send email.


text:
Q: Java handling exceptions functional programming I have this piece of code:
private void handleReceivedMessage(String m) throws IOException {
    switch(m) {
        case "ping":
            // code block
            ping();
            break;
        default:
            System.out.println("message not understood");
    }

}
public DataServer(int port) throws IOException {
        server = new Server(port, this::handleReceivedMessage);
        server.acceptClient();
}

now I get the error at the line this::handleReceivedMessage:
Unhandled exception: java.io.IOException
How do I solve this? It's clear that the handleReceivedMessage functions does throw an IOException

A: Without knowing more, I'd try using a try/catch statement specifically to catch the exception being thrown as Olivier is suggesting. If may I ask, why aren't you using try/catch for error checking?


text:
Q: Unable to read StringIO object created by json.dump() I am trying to write a list of dictionaries to a StringIO object with json.dump() in Python 3. The objective is to create a pandas dataframe from a JSON "file" without actually saving it to disk. I can't seem to read anything from the StringIO object. My code is as follows:
import json
from io import StringIO

errors = [{'dateTime': '05/06/2021, 05:00PM', 'cs-username': '-', 'sc-substatus': '0', 'sc-win32-status': '0', 'sc-bytes': '34255', 'time-taken': '218', 'serverIP': '209.213.12.24', 'method': 'GET', 'file': '/ads.txt', 'errorMessage': "404;https://www.fudge.com:443/ads.txt|49|800a01a8|Object_required:_'xmlDocTemp.documentElement'", 'port': '443', 'clientIP': '66.69.69.145', 'userAgent': 'Mozilla/5.0+(compatible;+Googlebot/2.1;++http://www.google.com/bot.html)', 'cookie': '-', 'referer': '-', 'statusCode': '500', 'errorHash': 'd5228f90df950647d0acdaa03ce5dc60b970a1ab0d8287ed611d6e3214d91667', 'absoluteHash': '538d59226642d818723f0f9cf1e465b9c01061daafdd79c7cbd897bceefcac1c', 'errorLogLine': 1, 'queryParams': '-'}, {'dateTime': '05/06/2021, 05:00PM', 'cs-username': '-', 'sc-substatus': '0', 'sc-win32-status': '0', 'sc-bytes': '34255', 'time-taken': '156', 'serverIP': '209.213.12.24', 'method': 'GET', 'file': '/ads.txt', 'errorMessage': "404;https://www.crap.com:443/ads.txt|49|800a01a8|Object_required:_'xmlDocTemp.documentElement'", 'port': '443', 'clientIP': '69.69.69.69', 'userAgent': 'Mozilla/5.0+(compatible;+Googlebot/2.1;++http://www.google.com/bot.html)', 'cookie': '-', 'referer': '-', 'statusCode': '500', 'errorHash': 'd5228f90df950647d0acdaa03ce5dc60b970a1ab0d8287ed611d6e3214d91667', 'absoluteHash': '6763ca746c468193c53a84a4c95039e672b5592d8808b702ec3b8552b72c54eb', 'errorLogLine': 2, 'queryParams': '-'}, {'dateTime': '05/06/2021, 05:02PM', 'cs-username': '-', 'sc-substatus': '0', 'sc-win32-status': '0', 'sc-bytes': '597', 'time-taken': '187', 'serverIP': '209.212.247.227', 'method': 'HEAD', 'file': '/https:/www.shuckydarn.com/', 'errorMessage': "404;https://www.fatfool.com:443/https:/www.goshdarnit.com/|49|800a01a8|Object_required:_'xmlDocTemp.documentElement'", 'port': '443', 'clientIP': '72.54.211.17', 'userAgent': 'Test+Certificate+Info', 'cookie': '-', 'referer': '-', 'statusCode': '500', 'errorHash': '2c0b5cac5730c90c5fd73f401f9196061deb59319782bf67c0f7605408fb66e0', 'absoluteHash': 'e7ea762b3a23ea79ce84c2f1c6fdb5ae4248fc7090a783a02735e42b70084689', 'errorLogLine': 3, 'queryParams': '-'}, {'dateTime': '05/06/2021, 05:03PM', 'cs-username': '-', 'sc-substatus': '0', 'sc-win32-status': '0', 'sc-bytes': '34303', 'time-taken': '187', 'serverIP': '209.213.12.24', 'method': 'GET', 'file': '/ads.txt', 'errorMessage': "404;https://www.supbro.com:443/ads.txt|49|800a01a8|Object_required:_'xmlDocTemp.documentElement'", 'port': '443', 'clientIP': '54.197.11.69', 'userAgent': 'Mozilla/5.0+(compatible;+proximic;++http://www.proximic.com/info/spider.php)', 'cookie': '-', 'referer': '-', 'statusCode': '500', 'errorHash': 'd5228f90df950647d0acdaa03ce5dc60b970a1ab0d8287ed611d6e3214d91667', 'absoluteHash': '495a2444a27222883e868f1c9d410b6197f04ce4be43af85f632c35113f8b351', 'errorLogLine': 4, 'queryParams': '-'}]
fp = StringIO()
json.dump(errors, fp, indent=2)

print(fp.read())

I expect it to print something like this:
[
  {
    "dateTime": "05/06/2021, 05:00PM",
    "cs-username": "-",
    "sc-substatus": "0",
    "sc-win32-status": "0",
    "sc-bytes": "34255",
    "time-taken": "218",
    "serverIP": "209.213.12.24",
    "method": "GET",
    "file": "/ads.txt",
    "errorMessage": "404;https://www.fudge.com:443/ads.txt|49|800a01a8|Object_required:_'xmlDocTemp.documentElement'",
    "port": "443",
    "clientIP": "66.69.69.145",
    "userAgent": "Mozilla/5.0+(compatible;+Googlebot/2.1;++http://www.google.com/bot.html)",
    "cookie": "-",
    "referer": "-",
    "statusCode": "500",
    "errorHash": "d5228f90df950647d0acdaa03ce5dc60b970a1ab0d8287ed611d6e3214d91667",
    "absoluteHash": "538d59226642d818723f0f9cf1e465b9c01061daafdd79c7cbd897bceefcac1c",
    "errorLogLine": 1,
    "queryParams": "-"
  },
  {
    "dateTime": "05/06/2021, 05:00PM",
    "cs-username": "-",
    "sc-substatus": "0",
    "sc-win32-status": "0",
    "sc-bytes": "34255",
    "time-taken": "156",
    "serverIP": "209.213.12.24",
    "method": "GET",
    "file": "/ads.txt",
    "errorMessage": "404;https://www.crap.com:443/ads.txt|49|800a01a8|Object_required:_'xmlDocTemp.documentElement'",
    "port": "443",
    "clientIP": "69.69.69.69",
    "userAgent": "Mozilla/5.0+(compatible;+Googlebot/2.1;++http://www.google.com/bot.html)",
    "cookie": "-",
    "referer": "-",
    "statusCode": "500",
    "errorHash": "d5228f90df950647d0acdaa03ce5dc60b970a1ab0d8287ed611d6e3214d91667",
    "absoluteHash": "6763ca746c468193c53a84a4c95039e672b5592d8808b702ec3b8552b72c54eb",
    "errorLogLine": 2,
    "queryParams": "-"
  },
  {
    "dateTime": "05/06/2021, 05:02PM",
    "cs-username": "-",
    "sc-substatus": "0",
    "sc-win32-status": "0",
    "sc-bytes": "597",
    "time-taken": "187",
    "serverIP": "209.212.247.227",
    "method": "HEAD",
    "file": "/https:/www.shuckydarn.com/",
    "errorMessage": "404;https://www.fatfool.com:443/https:/www.goshdarnit.com/|49|800a01a8|Object_required:_'xmlDocTemp.documentElement'",
    "port": "443",
    "clientIP": "72.54.211.17",
    "userAgent": "Test+Certificate+Info",
    "cookie": "-",
    "referer": "-",
    "statusCode": "500",
    "errorHash": "2c0b5cac5730c90c5fd73f401f9196061deb59319782bf67c0f7605408fb66e0",
    "absoluteHash": "e7ea762b3a23ea79ce84c2f1c6fdb5ae4248fc7090a783a02735e42b70084689",
    "errorLogLine": 3,
    "queryParams": "-"
  },
  {
    "dateTime": "05/06/2021, 05:03PM",
    "cs-username": "-",
    "sc-substatus": "0",
    "sc-win32-status": "0",
    "sc-bytes": "34303",
    "time-taken": "187",
    "serverIP": "209.213.12.24",
    "method": "GET",
    "file": "/ads.txt",
    "errorMessage": "404;https://www.supbro.com:443/ads.txt|49|800a01a8|Object_required:_'xmlDocTemp.documentElement'",
    "port": "443",
    "clientIP": "54.197.11.69",
    "userAgent": "Mozilla/5.0+(compatible;+proximic;++http://www.proximic.com/info/spider.php)",
    "cookie": "-",
    "referer": "-",
    "statusCode": "500",
    "errorHash": "d5228f90df950647d0acdaa03ce5dc60b970a1ab0d8287ed611d6e3214d91667",
    "absoluteHash": "495a2444a27222883e868f1c9d410b6197f04ce4be43af85f632c35113f8b351",
    "errorLogLine": 4,
    "queryParams": "-"
  }
]

But instead it prints nothing. Why can't I read the data from json.dump() with fp.read()? It's probably something simple that I'm missing. Any help is appreciated!

A: You need to use fp.getvalue() instead of read(). Note that your errors dictionary is already JSON-like so calling json.dump() somewhat clobbers the output format
Try:
import json
from io import StringIO

errors = [{'dateTime': '05/06/2021, 05:00PM', 'cs-username': '-', 'sc-substatus': '0', 'sc-win32-status': '0', 'sc-bytes': '34255', 'time-taken': '218', 'serverIP': '209.213.12.24', 'method': 'GET', 'file': '/ads.txt', 'errorMessage': "404;https://www.fudge.com:443/ads.txt|49|800a01a8|Object_required:_'xmlDocTemp.documentElement'", 'port': '443', 'clientIP': '66.69.69.145', 'userAgent': 'Mozilla/5.0+(compatible;+Googlebot/2.1;++http://www.google.com/bot.html)', 'cookie': '-', 'referer': '-', 'statusCode': '500', 'errorHash': 'd5228f90df950647d0acdaa03ce5dc60b970a1ab0d8287ed611d6e3214d91667', 'absoluteHash': '538d59226642d818723f0f9cf1e465b9c01061daafdd79c7cbd897bceefcac1c', 'errorLogLine': 1, 'queryParams': '-'}, {'dateTime': '05/06/2021, 05:00PM', 'cs-username': '-', 'sc-substatus': '0', 'sc-win32-status': '0', 'sc-bytes': '34255', 'time-taken': '156', 'serverIP': '209.213.12.24', 'method': 'GET', 'file': '/ads.txt', 'errorMessage': "404;https://www.crap.com:443/ads.txt|49|800a01a8|Object_required:_'xmlDocTemp.documentElement'", 'port': '443', 'clientIP': '69.69.69.69', 'userAgent': 'Mozilla/5.0+(compatible;+Googlebot/2.1;++http://www.google.com/bot.html)', 'cookie': '-', 'referer': '-', 'statusCode': '500', 'errorHash': 'd5228f90df950647d0acdaa03ce5dc60b970a1ab0d8287ed611d6e3214d91667', 'absoluteHash': '6763ca746c468193c53a84a4c95039e672b5592d8808b702ec3b8552b72c54eb', 'errorLogLine': 2, 'queryParams': '-'}, {'dateTime': '05/06/2021, 05:02PM', 'cs-username': '-', 'sc-substatus': '0', 'sc-win32-status': '0', 'sc-bytes': '597', 'time-taken': '187', 'serverIP': '209.212.247.227', 'method': 'HEAD', 'file': '/https:/www.shuckydarn.com/', 'errorMessage': "404;https://www.fatfool.com:443/https:/www.goshdarnit.com/|49|800a01a8|Object_required:_'xmlDocTemp.documentElement'", 'port': '443', 'clientIP': '72.54.211.17', 'userAgent': 'Test+Certificate+Info', 'cookie': '-', 'referer': '-', 'statusCode': '500', 'errorHash': '2c0b5cac5730c90c5fd73f401f9196061deb59319782bf67c0f7605408fb66e0', 'absoluteHash': 'e7ea762b3a23ea79ce84c2f1c6fdb5ae4248fc7090a783a02735e42b70084689', 'errorLogLine': 3, 'queryParams': '-'}, {'dateTime': '05/06/2021, 05:03PM', 'cs-username': '-', 'sc-substatus': '0', 'sc-win32-status': '0', 'sc-bytes': '34303', 'time-taken': '187', 'serverIP': '209.213.12.24', 'method': 'GET', 'file': '/ads.txt', 'errorMessage': "404;https://www.supbro.com:443/ads.txt|49|800a01a8|Object_required:_'xmlDocTemp.documentElement'", 'port': '443', 'clientIP': '54.197.11.69', 'userAgent': 'Mozilla/5.0+(compatible;+proximic;++http://www.proximic.com/info/spider.php)', 'cookie': '-', 'referer': '-', 'statusCode': '500', 'errorHash': 'd5228f90df950647d0acdaa03ce5dc60b970a1ab0d8287ed611d6e3214d91667', 'absoluteHash': '495a2444a27222883e868f1c9d410b6197f04ce4be43af85f632c35113f8b351', 'errorLogLine': 4, 'queryParams': '-'}]
fp = StringIO()
json.dump(errors, fp, indent=2)

print(fp.getvalue())

Outputs:
'[\n  {\n    "dateTime": "05/06/2021, 05:00PM",\n    "cs-username": "-",\n    "sc-substatus": "0",\n    "sc-win32-status": "0",\n    "sc-bytes": "34255",\n    "time-taken": "218",\n    "serverIP": "209.213.12.24",\n    "method": "GET",\n    "file": "/ads.txt",\n    "errorMessage": "404;https://www.fudge.com:443/ads.txt|49|800a01a8|Object_required:_\'xmlDocTemp.documentElement\'",\n    "port": "443",\n    "clientIP": "66.69.69.145",\n    "userAgent": "Mozilla/5.0+(compatible;+Googlebot/2.1;++http://www.google.com/bot.html)",\n    "cookie": "-",\n    "referer": "-",\n    "statusCode": "500",\n    "errorHash": "d5228f90df950647d0acdaa03ce5dc60b970a1ab0d8287ed611d6e3214d91667",\n    "absoluteHash": "538d59226642d818723f0f9cf1e465b9c01061daafdd79c7cbd897bceefcac1c",\n    "errorLogLine": 1,\n    "queryParams": "-"\n  },\n  {\n    "dateTime": "05/06/2021, 05:00PM",\n    "cs-username": "-",\n    "sc-substatus": "0",\n    "sc-win32-status": "0",\n    "sc-bytes": "34255",\n    "time-taken": "156",\n    "serverIP": "209.213.12.24",\n    "method": "GET",\n    "file": "/ads.txt",\n    "errorMessage": "404;https://www.crap.com:443/ads.txt|49|800a01a8|Object_required:_\'xmlDocTemp.documentElement\'",\n    "port": "443",\n    "clientIP": "69.69.69.69",\n    "userAgent": "Mozilla/5.0+(compatible;+Googlebot/2.1;++http://www.google.com/bot.html)",\n    "cookie": "-",\n    "referer": "-",\n    "statusCode": "500",\n    "errorHash": "d5228f90df950647d0acdaa03ce5dc60b970a1ab0d8287ed611d6e3214d91667",\n    "absoluteHash": "6763ca746c468193c53a84a4c95039e672b5592d8808b702ec3b8552b72c54eb",\n    "errorLogLine": 2,\n    "queryParams": "-"\n  },\n  {\n    "dateTime": "05/06/2021, 05:02PM",\n    "cs-username": "-",\n    "sc-substatus": "0",\n    "sc-win32-status": "0",\n    "sc-bytes": "597",\n    "time-taken": "187",\n    "serverIP": "209.212.247.227",\n    "method": "HEAD",\n    "file": "/https:/www.shuckydarn.com/",\n    "errorMessage": "404;https://www.fatfool.com:443/https:/www.goshdarnit.com/|49|800a01a8|Object_required:_\'xmlDocTemp.documentElement\'",\n    "port": "443",\n    "clientIP": "72.54.211.17",\n    "userAgent": "Test+Certificate+Info",\n    "cookie": "-",\n    "referer": "-",\n    "statusCode": "500",\n    "errorHash": "2c0b5cac5730c90c5fd73f401f9196061deb59319782bf67c0f7605408fb66e0",\n    "absoluteHash": "e7ea762b3a23ea79ce84c2f1c6fdb5ae4248fc7090a783a02735e42b70084689",\n    "errorLogLine": 3,\n    "queryParams": "-"\n  },\n  {\n    "dateTime": "05/06/2021, 05:03PM",\n    "cs-username": "-",\n    "sc-substatus": "0",\n    "sc-win32-status": "0",\n    "sc-bytes": "34303",\n    "time-taken": "187",\n    "serverIP": "209.213.12.24",\n    "method": "GET",\n    "file": "/ads.txt",\n    "errorMessage": "404;https://www.supbro.com:443/ads.txt|49|800a01a8|Object_required:_\'xmlDocTemp.documentElement\'",\n    "port": "443",\n    "clientIP": "54.197.11.69",\n    "userAgent": "Mozilla/5.0+(compatible;+proximic;++http://www.proximic.com/info/spider.php)",\n    "cookie": "-",\n    "referer": "-",\n    "statusCode": "500",\n    "errorHash": "d5228f90df950647d0acdaa03ce5dc60b970a1ab0d8287ed611d6e3214d91667",\n    "absoluteHash": "495a2444a27222883e868f1c9d410b6197f04ce4be43af85f632c35113f8b351",\n    "errorLogLine": 4,\n    "queryParams": "-"\n  }\n]'

UPDATE:
If your goal is a dataframe from errors just do this:
df = pd.DataFrame(errors)


text:
Q: Try Catch Not Working - Why? In the below code, I am trying to implement a try-catch on an input. This works as a standalone, when the while loop isn't in use. That doesn't achieve what I'm trying to do, so I tried the loop. This then creates an infinite loop, which I don't really understand why.
public static void AllIn() {
    System.out.println("Please select your menu option: ");
    while(true) {
        try {
            MenuSelect = Input.nextInt();
        }
        catch (InputMismatchException e) {
            System.out.println("That's not a valid number!");
        }
    }

 }

Another solution I thought might work was calling this method through another method in the catch block. This created a loop that ended in a StackOverflowError being returned. Does anyone have a suggestion for how to get this to work?
My variables that I'm working with for this are:
private static Scanner Input = new Scanner(System.in);
private static int MenuSelect;

And yes, I am aware that I shouldn't be using private statics to do this, but I couldn't really think of an alternative.

A: Your while loop does not have any break or return in it, so the only way it can finish is if its condition is false. But its condition is true so it can't be false. This creates an infinite loop.
There's another reason as well. When the scanner reads an invalid int, it does not go past those characters. This means that the next time the scanner tries to read it, the invalid int is still there and it will try to read that, which it fails at, and this goes on and on.
One solution is to break if the input is alright, and also consume the int if it fails:
System.out.println("Please select your menu option: ");
while(true) {
    try {
        MenuSelect = Input.nextInt();
        break;
    }
    catch (InputMismatchException e) {
        System.out.println("That's not a valid number!");
        Input.nextLine(); // consumes the invalid int.
    }
}
// do stuff with the input here...

A: public static void AllIn() {
    System.out.println("Please select your menu option: ");
    while(true) {
        try {
            MenuSelect = Input.nextInt();
        }
        catch (InputMismatchException e) {
            System.out.println("That's not a valid number!");
            // added this line to make Scanner omit last newline
            Input.nextLine();
        }
    }

 }


text:
Q: iPhone 7 not letting me update to ios11 My iPhone still isn't offering me the option to update to iOS 11. Why is this? What can I do to let me update?
I have no clue what to try next any sugustions?

A: I would take the device to a computer that runs iTunes and update off the air. Check your backups too in case you need to restore instead of upgrade.


text:
Q: Calculation of $\int_a^b f(x)\,dx$ Let $f:\Bbb R\to \Bbb R$ a continous function and $a,b\in \Bbb R,a<b$. Calculate $\int_a^b   f(x)\,dx$ if $f(tx)\ge f(x)$ for any $t>0$ and $x\in \Bbb R$
I obtained just that $f(x)\ge f(0)$ but I do not think it is helpful.

A: Put $t=\frac y x$ to get $f(y) \geq f(x)$ for all $x,y>0$. Can you show now that $f$ is a constant on $(0,\infty)$? A similar argument would show that $f$ is  a constant on $(-\infty,0)$. By continuity, $f$ is a constant.

A: Take $x,y \in \mathbb{R^+}$. You have that $f(x)=f(\frac{x}{y}y) \geq f(y)$ and $f(y)=f(\frac{y}{x}x) \geq f(x)$. So $f$ is constant on $\mathbb{R^+}$. In the same way you obtain that $f$ is constant on $\mathbb{R^-}$. Since $f$ is continuos $f(x)=k \;\; \forall x \in \mathbb{R}$. So you have that $\int_a^bf(x) dx=k(b-a)$