text:
Q: Fastest Matrix Inverse Excel VBA I have many equations with many unknowns (my data is in Excel) and currently I am using matrix method to solve them.
I use inbuilt MMULT (matrix multiply) and MINVERSE (matrix inverse) in following form :- Result = MMULT (MINVERSE(matrix1),matrix2)
Here lies the problem, my matrices are of the order of 2000 x 2000 or more, and Excel takes lot of time in doing inverse (matrix multiplication is very fast).
What is the best way for me to speed up the process? I don't mind exporting data to any external 3rd party program (compatible with Excel) and then importing the inversed matrix back to Excel.
I don't know much C / C++, but I feel if we compile the Matrix Inverse Function into a DLL and then use the same from excel VBA, maybe the speed will improve. Please help.
Please see following link :
Why is MATLAB so fast in matrix multiplication?
It is found that MATLAB has highest speed for matrix calculations. Can we use any such library in Excel / VBA ?
I have found certain libraries such as LAPACK, ARMADILO etc which are in C / C++ / C# or .NET. How can I use compiled versions of these libraries in my Excel VBA?

A: I am the author of the blog linked by John Coleman.  There are quite a few options available, depending on your familiarity with compiling and linking to different languages.  I'd say the main options are (in order of ease of implementation):

*

*Use the Python Numpy and Scipy libraries with ExcelPython or xlwings (which now includes ExcelPython).  The most recent post on the subject at my blog (including free downloads) is:
https://newtonexcelbach.wordpress.com/2016/01/04/xlscipy-python-scipy-for-excel-update-with-new-functions/
Advantages:
Free
Easy to implement (especially using Anaconda Python, which now includes xlwings).
No compilation required.
The Scipy code is fast, and includes packages for sparse matrices, which where applicable makes a huge difference to solving time, and the maximum size of matrix that can be handled.
Free and open-source spreadsheet implementation available on my blog.
Disadvantages:
The overhead in transferring large data sets from VBA to Python can be significant, in fact for small to medium sized matrices it is often greater than the solution time.

*Use the Python version of the Alglib library.  Search my blog for Alglib for recent examples using Python, and older examples using C++ and C#.

Advantages and disadvantages:
As for Numpy and Scipy, except there is a commercial version available as well, which may offer performance advantages (I haven't tried it).

*Use Numpy/Scipy with Pyxll.
https://newtonexcelbach.wordpress.com/2013/09/10/python-matrix-functions-using-pyxll/ for sample spreadsheet.

Advantages:
The data transfer overhead should be much reduced.
More mature and documentation is better than the current xlwings.
Disadvantages:
Commercial package (but free for evaluation and non-commercial use)
Not open source.

*Use open source C++ or Fortran packages with Visual Studio or other compiler, to produce xll based functions.

Advantages:
Potentially the best all-round performance.
Disadvantages:
More coding required.
Implementation more difficult, especially if you want to distribute to others.
32 bit/ 64 bit issues likely to be much harder to resolve.
As mentioned in the comments, matrix inversion is much slower than other matrix solution methods, but even allowing for that, the built in Excel Matrix functions are very slow compared with alternative compiled routines, and the advantages of installing one of the alternatives listed above is well worth the effort.


text:
Q: How to avoid GZip compressed assets getting modified every time running rake assets:precompile We are using Rails' asset pipeline feature in v3.2. We are pre-compiling all assets locally and committing the pre-compiled assets into our Git repository. Every time we run rake assets:precompile all the GZip compressed versions of the generated assets in public/assets/ are marked as modified. I suspect this is because the GZip file format contains a header which includes a version number and a timestamp.
What's the best way to avoid this issue?
We have considered:

*

*Using the turbo-sprockets gem to compile only assets that have changed. This seems the best option so far.

*Precompiling on the target servers instead of locally. Makes deployments take significantly longer, esp. with frequent deployments and infrequently changing assets.

*Not precompiling the GZip compressed assets and instead having the web server compress the static assets on the fly. Adds extra load on the web server and also Sprockets is supposed to use a higher compression factor than the web server leading to longer downloads.

Any other options?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Haskell: No instance for (Eq a) arising from a use of `==' In the expression: (b == c) So, im on my first steps on haskell, and i was asked on class to define the "elem" function. This was my first idea:
elemento :: a -> [a] -> Bool
elemento b listab = foldl (||) False (map (esIgual b) listab)

esIgual :: a -> a -> Bool
esIgual b c = (b == c)

Wich results in

elem (parcialito).hs:5:18:
      No instance for (Eq a)
        arising from a use of =='
      In the expression: (b == c)
      In an equation foresIgual': esIgual b c = (b == c)

I think it´s something related to b and c not being recognized as a "Eq a" type or something like that, but as i said, im on baby steps here yet. Any ideas?

A: I won't get into an explanation of type classes (you should read some haskell tutorials to find out about that) but the basic idea is that, as you said, in order to use the function == on b and c, which are both of type a, you need some guarantee that there is an implementation of the == function for that type. In haskell we call that a "type constraint" and we write it as:
esIgual :: Eq a => a -> a -> Bool
esIgual b c = (b == c)

Note that you could have omitted the type annotation for esIgual and the compiler would have inferred it for you. Try to write only
esIgual b c = (b == c)

then load the file into GHCI and type:
:t esIgual

You will also need to add a constraint in elemento since it is using isIgual:
elemento :: Eq a => ...

Check this out: http://learnyouahaskell.com/types-and-typeclasses#typeclasses-101 :) The first example is precisely about ==.

A: esIgual currently promises to return a Bool for any two objects of the same type a, with no requirements at all on what type that is. But it uses == to do that, and == only works of a is an instance of Eq, the typeclass that lets you compare objects for equality. That requirement needs to be reflected in the type signature of esIgual, like:
esIgual :: Eq a => a -> a -> Bool

Then that needs to propagate out to elemento as well:
elemento :: Eq a => a -> [a] -> Bool

A: You need to declare esIgual to require arguments of types from the typeclass Eq:
esIgual :: Eq a => a -> a -> Bool
esIgual b c = (b == c)

Otherwise there's no way for Haskell to apply the == operator to the arbitrary type a.
(Or, as Aegis points out, just skip the declaration altogether)


text:
Q: Querying data from a table are missing $items = '';
$sql = "select items from bplus where pos = 'home-01' limit 1";
$st = $db->query($sql);
$res = $st->fetchColumn();
$arr = explode("\n", $res);
foreach ($arr as $el){
//echo $el . "
"; // as a test - it's ok - four images.
$sqlb = "select * from banners where fname = '" . $el . "'";
    $stb = $db->query($sqlb);
    $row = $stb->fetch();
    $items .= "\n";
}
echo $items;

Final result:

Why are the first three images without any data?
In the table all images has its data.

A: You need to check the results of your inner query
$sqlb = "select * from banners where fname = '" . $el . "'";
$stb = $db->query($sqlb);
$row = $stb->fetch();

if(!$row) throw new Exception("missing row [$el]");

$items .= "\n";

For the items I would add this (outside the loop)
$createData = function($k, $v){
    return 'data-'.$k.'="'.$v.'"';
};

Then in the loop after checking row
if(!$row) throw new Exception("missing row $el");

$data = implode(' ',array_map($createData, array_keys($row), $row));

$items .= ''.PHP_EOL;

This way it dynamically creates the data- based of what's in the query, then if you change "stuff" it is less code to maintain.
You can test it here
https://3v4l.org/Lo9Vf
One last thing is you can rename the columns in the query if they don't match, for example say in the DB the w is actually width then you can rename it like this
$sqlb = "select width AS w, first AS fname from banners ....;

And so on, I mention it because latter if you add a column to the data you only need to change the query and your all set, you don't have to change how the HTML is built, but that is up to you.  It's just how I would do it.
UPDATE
The bigger issue here is you Database model is not really correct, which gives rise to this issue an other complications.
Basically you have a many to relationship between the two tables and you are severely limiting what you can do by not molding the data correctly.  Currently you have
//table bplus
items
1,2,3,4

//table banners
 fname
 1
 2
 3
 4

Don't worry about the numbers the actual data in there is pretty much irrelevant.
What you need is something like this
//table bplus
 //other fields

//table banners
fname bplus_id
1       1
2       1
3       1
4       1

Honestly I would need more information about the database to really help more.  But I suggest looking into Many to One relationships.  As you can eliminate continuously calling the DB inside the loop, which can get expensive, and probably simplify a lot of things.

A: It looks like your $el variable contains spaces which cause the issue. So trim this data then get data from db
$sqlb = "select * from banners where fname = '" . trim($el) . "'";
    $stb = $db->query($sqlb);
    $row = $stb->fetch();
    $items .= "\n";
}
echo $items;


text:
Q: What color conversion (or other operation) does imshow perform on this image I made a very simple program that reads an image, evaluates the sobel filter and then presents it with imshow.
import cv2
img = cv2.imread("/home/alex/imagens/train_5.jpg")

sobelx = cv2.Sobel(img, cv2.CV_64F, 1, 0, ksize=3)  # x
sobely = cv2.Sobel(img, cv2.CV_64F, 0, 1, ksize=3)
norm = cv2.magnitude(sobelx, sobely)

normUint8 = norm.astype('uint8')

cv2.imshow("img", img)
cv2.imshow("norm", norm)
cv2.imshow("normUint8", normUint8)

print "img=" + str(img.dtype) + ", sobel=" + str(norm.dtype) + ", normUint8=" + str(normUint8.dtype)

cv2.waitKey(0)
cv2.destroyAllWindows()

Here I attach the result.
I expected the result from showing the norm and the normUint8 would be the same or much similar, because their values differ less than 1 at each pixel.
Thus, I believe opencv is performing some operation, before presenting it, when I use an CV_64FC3 image.
I am interested in finding this operation in order to use it.
Can anyone help with it?
Here I attach the original image I used.

Thanks.

A: You're feeding a 64FC3 (3 channel, 64bit floats) image to imshow. The documentation for this function states:

The function may scale the image, depending on its depth:

*

*If the image is 8-bit unsigned, it is displayed as is.

*If the image is 16-bit unsigned or 32-bit integer, the pixels are divided by 256. That is, the value range [0,255*256] is mapped to [0,255].

*If the image is 32-bit floating-point, the pixel values are multiplied by 255. That is, the value range [0,1] is mapped to [0,255].

Even though 64-bit floating-point is not mentioned, we can make a decent assumption that they are handled in the same way as 32-bit floats. If we look at the source code, we find out that the conversion is done by function cvConvertImage. Specifically, on line 622
double scale = src_depth <= CV_8S ? 1 : src_depth <= CV_32S ? 1./256 : 255;

To explain this for those not familiar with the order of the type enums, it's 8U, 8S, 16U, 16S, 32S, 32F, 64F. Hence, bytes get no scaling, other integers division, the rest (floats) multiplication.
Since for display we need an 8bit image, it's important to note that the scaling will be done with saturation (in this case anything over 255 becomes 255, anything below 0 becomes 0).

Now that it's clear what kind of transformation imshow does, let's have a look at why you see those patches of colour in a sea of white.
Since a simple cast of norm to uint8 gives you an image which is not all black, we can safely assume the values of norm are not in range [0.0-1.0]. When the values are scaled by 255, anything greater or equal to 1.0 will become 255 (white). Due to being a 3 channel image, we can end up with places where only some of the channels are unsaturated, and thus we see various patches of colour.
We can simulate this behaviour by the following script:
b,g,r = cv2.split(norm)

r = np.uint8(np.where(r < 1.0, 0, 255))
g = np.uint8(np.where(g < 1.0, 0, 255))
b = np.uint8(np.where(b < 1.0, 0, 255))

cv2.imwrite('sobel_out.png', cv2.merge([b,g,r]))

We set pixels to black for values < 1.0, everything else gets white. When we combine the planes, we get the following image:

Looks familiar?

Note: I suspect the square pattern comes from the JPEG compression you used for your input.

A: Dan's answer is excellent and describes why a float image can have unintended display properties. Images need a minimum and maximum to know what is black and white, and this isn't always precisely defined for float images.
For instance, you could use a float image that still has values strictly between 0 and 255 just for calculation precision, to be later rounded to int for display. But it's typical in literature to use 0 and 1 as the minimum and maximum, respectively, for image values, as it makes the math that much simpler; and since you need float values to represent values between 0 and 1, it's simply common that float images use the range 0 to 1. So, OpenCV sticks to this for displaying a float image. It saturates the image in the range 0 to 1 for a float, meaning that it truncates values above and below.
Now if you read in an image, it gets read by default as 8-bit unsigned integers (CV_U8C3 for a 3-channel image). When you apply the Sobel operator, you specified that you wanted in return a float image. This is totally fine, but know that the Sobel operator is a convolution which multiplies multiple values and sums them up, so this operation can give you values larger than what the original image started with. If you used a different return type, then it's possible that these values would get saturated. However, with a float, they won't get saturated until display time. And this is very much on purpose; the Sobel operator can be used on arbitrary matrices, so saturating the values wouldn't always be wanted.
In order to display the image without strange artifacts, you would need to scale the image, either manually like the Stack Overflow answer linked above or by using cv2.normalize(). Or you can just straight cast to another type like you did, saturating the values at their high end.


text:
Q: WordPress website hides all  elements on homepage I'm working on a website that was created using WordPress. WordPress (or possibly a plugin, theme, or something else) is inserting the following CSS into the homepage:
<style type="text/css"> iframe { visibility: hidden; opacity: 0; } </style>

The above code is included as part of the original HTTP response received after a request for the homepage (I confirmed this using curl from my terminal).
I imagine the above code is part of a mechanism either to:

*

*display the other content on the page as fast as possible and only display the  elements after everything else has been displayed; or

*display the  elements only after dynamically setting their width, height, position, etc.

In Safari v9.1, the  elements eventually get displayed. However, Firefox v47.0.1 failed to ever display the  elements.
I can't provide a link to the actual website for privacy reasons.
Does anyone know what's going on? If not, does anyone have any suggestions about how I can find the Javascript code that is supposed to unhide the  elements?


text:
Q: Google DLP - Can I use a delimiter to instruct DLP infotype detectors to search only inside that for sensitive text? I have an issue while trying to deidentify some data with DLP using an object mapper to parse the object into string - send it to DLP for deidentification - getting back the deidentified string and using the object mapper to parse the string back to the initial object. Sometimes DLP will return a string that cannot be parsed back to the initial object (it breaks the json format of the object mapper)
I use an objectMapper to parse an Address object to string like this:
Address(
val postal_code: String,
val street: String,
val city: String,
val provence: String
)

and my objectmapper will transform this object into a string eg: "{\"postal_code\":\"123ABC\",\"street\":\"Street Name\",\"city\":\"My City\",\"provence\":\"My Provence\"}" which is sent to DLP and deidentified (using LOCATION or STREET_ADDRESS detectors).
The issue is that my object mapper would expect to take back the deidentified string and parse it back to my Address object using the same json format eg:
"{\"postal_code\":\"LOCATION_TOKEN(10):asdf\",\"street\":\"LOCATION_TOKEN(10):asdf\",\"city\":\"LOCATION_TOKEN(10):asdf\",\"provence\":\"LOCATION_TOKEN(10):asdf\"}"
But there are a lot of times that DLP will return something like
"{"LOCATION_TOKEN(25):asdfasdfasdf)\",\"provence\":\"LOCATION_TOKEN(10):asdf\"}" - basically breaking the json format and i am unable to parse back the string from DLP to my initial object
Is there a way to instruct DLP infotype detectors to keep the json format, or to look for sensitive text only inside \" * \"?
Thanks

A: There are some options here using a custom regex and a detection ruleset in order to define a boundary on matches.
The general idea is that you require that findings must match both an infoType (e.g. STREET_ADDRESS, LOCATION, PERSON_NAME, etc.) and your custom infoType before reporting as a finding or for redaction.  By requiring that both match, you can set bounds on where the infoType can detect.
Here is an example.
{
  "item": {
    "value": "{\"postal_code\":\"123ABC\",\"street\":\"Street Name\",\"city\":\"My City\",\"provence\":\"My Provence\"}"
  },
  "inspectConfig": {
    "customInfoTypes": [
      {
        "infoType": {
          "name": "CUSTOM_BLOCK"
        },
        "regex": {
          "pattern": "(:\")([^,]*)(\")",
          "groupIndexes": [
            2
          ]
        },
        "exclusionType": "EXCLUSION_TYPE_EXCLUDE"
      }
    ],
    "infoTypes": [
      {
        "name": "EMAIL_ADDRESS"
      },
      {
        "name": "LOCATION"
      },
      {
        "name": "PERSON_NAME"
      }
    ],
    "ruleSet": [
      {
        "infoTypes": [
          {
            "name": "LOCATION"
          }
        ],
        "rules": [
          {
            "exclusionRule": {
              "excludeInfoTypes": {
                "infoTypes": [
                  {
                    "name": "CUSTOM_BLOCK"
                  }
                ]
              },
              "matchingType": "MATCHING_TYPE_INVERSE_MATCH"
            }
          }
        ]
      }
    ]
  },
  "deidentifyConfig": {
    "infoTypeTransformations": {
      "transformations": [
        {
          "primitiveTransformation": {
            "replaceWithInfoTypeConfig": {}
          }
        }
      ]
    }
  }
}

Example output:
  "item": {
    "value": "{\"postal_code\":\"123ABC\",\"street\":\"Street Name\",\"city\":\"My City\",\"provence\":\"My [LOCATION]\"}"
  },

By setting "groupIndexes" to 2 we are indicating that we only want the custom infoType to match the middle (or second) regex group and not allow the :" or " to be part of the match.  Also, in this example we mark the custom infoType as EXCLUSION_TYPE_EXCLUDE so that it does not report itself:
"exclusionType": "EXCLUSION_TYPE_EXCLUDE"

If you remove this line, anything matching your infoType could also get redacted.  This can be useful for testing though - example output:
  "item": {
    "value": "{\"postal_code\":\"[CUSTOM_BLOCK]\",\"street\":\"[CUSTOM_BLOCK]\",\"city\":\"[CUSTOM_BLOCK]\",\"provence\":\"[CUSTOM_BLOCK][LOCATION]\"}"
  },
...

Hope this helps.


text:
Q: how to move styling from HTML to CSS? how do i move all my styling in html to css? When i copy and paste it, it's not working properly.
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>

                Country
                OrderID
                Order Amount

                USA
                1000
                $1,300

                USA
                1001
                $700

                CA
                1002
                $2,000

                CA
                1003
                $1,000

                Total
                $5,000

A: i just link .css file within header

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="mystyles.css">
    <title>Document</title>

                Country
                OrderID
                Order Amount

                USA
                1000
                $1,300

                USA
                1001
                $700

                CA
                1002
                $2,000

                CA
                1003
                $1,000

                Total
                $5,000

and your mystyles.css is like

 table,
        td,
        th {
            border-bottom: 1px solid #c4dcf3;
            border-collapse: collapse;
            padding: 5px;
        }

        tfoot {
            text-align: left;
        }

        tbody tr:nth-child(odd) {
            background-color: #eef7ff;
        }


text:
Q: Laravel 5 multi language not working I tried to localization my app, but seems like I'm missing something.  I don't have any previous knowledge about this and therefore it's pretty hard to get started. Here is my routes.php
Route::get('/lang/{lang}', 'LangController@index');

And here is my LangController.php
 public function index($lang)

{
    $langs =['en', 'de'];
    if(in_array($lang, $langs)){
        Session:set('lang', $lang);
        return Redirect::back();
    }
}

I set in middleware:(Lang.php)
 public function handle($request, Closure $next)

{

    if($lang = Session::get('lang')){
        \Lang::setLocale($lang);
    }

    return $next($request);
}

Enable it in Http\Kernel.php:
  protected $middleware = [

   \App\Http\Middleware\Lang::class,
        \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
    \App\Http\Middleware\EncryptCookies::class,
    \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
    \Illuminate\Session\Middleware\StartSession::class,
    \Illuminate\View\Middleware\ShareErrorsFromSession::class,
    \App\Http\Middleware\VerifyCsrfToken::class,

    ];

In my blade.php
 {{ Lang::get('home.hello')}}
   CURRENT: {{ Lang::getLocale() }}

 Germany | English

Please help.I do not see what I missing...
In field CURRENT when press Germany it shoul be 'de' and when press English it shoul be 'en' but when press Germany it still stay 'en'... (default is 'en' config/app.php ->  'locale' => 'en',)

A: Because you are using the session in your middleware, the values you need will not be available until the StartSession middleware sets up the session.
So you should add your middleware somewhere after that, like so:
protected $middleware = [
    \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
    \App\Http\Middleware\EncryptCookies::class,
    \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
    \Illuminate\Session\Middleware\StartSession::class, // Init session
    \App\Http\Middleware\Lang::class, // Set locale
    \Illuminate\View\Middleware\ShareErrorsFromSession::class,
    \App\Http\Middleware\VerifyCsrfToken::class,
];

Aside from that you also have a small syntax error in your controller code. You forgot to add the second colon (:) for the scope resolution operator, when assigning the value to the session in your index controller method. So this:
Session:set('lang', $lang);

Should be this:
Session::set('lang', $lang);


text:
Q: Why does a custom post type need the ''hierarchical' args setting? I'm struggling with understanding some things about CPTs and and could do with some help. I can see that taxonomies often need to be hierarchical, but can't see how/when a custom post type would be?
i.e I have a CPT called 'projects'. There is a taxonomy registered for this posttype called 'fields'. Under 'fields' I have lots of sub-items like:

*

*'Documentaries'

*'Documentaries' > 'Self Commisions'

*'Documentaries' > 'Classic'

*'Corporate'

*'Corporate' > 'Digital Marketing'

*etc...

So to view a project in 'Documentaries' > 'Classic' I use this URL:
mydomain.com/field/classic/
This is where I actually have about 30 questions :) but will just ask the two most pressing:

*

*Why and how would the 'projects' CPT ever be hierarchical?

*Is it possible to view items in the 'classic' field like so: mydomain.com/projects/classic (mydomain.com/projects shows all items, but drilling any further breaks it)

Any and all help appreciated, I've spent about 3 hours playing with this and reading and can't get my head around it!
Thanks!
Below is my (cropped) code for reference:
function register_cpt_projects() {
$labels = array(
    'name' => _x('Projects', 'projects'),
    // all other labels etc..
);

$args = array(
    'labels' => $labels,
    'hierarchical' => true,
    'supports' => array('title', 'editor', 'author', 'thumbnail'),
    'taxonomies' => array('field'),
    'public' => true,
    'show_ui' => true,
    'show_in_menu' => true,
    'show_in_nav_menus' => true,
    'publicly_queryable' => true,
    'exclude_from_search' => false,
    'has_archive' => true,
    'query_var' => true,
    'can_export' => true,
    'rewrite' => true,
    'capability_type' => 'post'
);
register_post_type('projects', $args);
}

add_action('init', 'register_cpt_projects');

function create_projects_tax(){
    register_taxonomy('field', 'projects', array(
       'hierarchical' => true,
       'label' => 'Fields'
    ));
}
add_action('init', 'create_projects_tax');

A: When you have two content objects with a similar interface or shared properties, you have a good candidate for hierarchical post types.
Take places as an example (see this answer):

*

*Asia

*Europe

*

*Germany

*

*Berlin

*Austria

*

*Vienna

Each place has similar meta data: population, geo coordinates, spoken languages. You just can reuse the same interface.
Plus, if you create a separate custom post type for each kind of place you'll run into WordPress' missing post-to-post relationship table.

A: A custom post type only needs the hierarchical setting if you want the post type to behave like pages.
If you want to be able to choose a parent and have the menu order metabox you also need to add 'page-attributes' to the supports array.
The hierarchical argument also allows you to treat hierarchical post types different than others by using the is_post_type_hierarchical() conditional tag.  It supports post object, post type name, or post ID as its single parameter.

Is it possible to view items in the 'classic' field like so:
  mydomain.com/projects/classic (mydomain.com/projects shows all items,
  but drilling any further breaks it)

You can use the rewrite argument to define how single post type urls appear:
slug: The slug you'd like to prefix your posts with.
with_front: Whether your post type should use the front base from your permalink settings.
'rewrite' => array( 'slug' => 'classic', 'with_front' => false ),
would make your urls for single project posts look like:
yoursite.com/classic/post-name
If you want to make your archive urls: mydomain.com/projects/classic you will need to apply similar rewrite rules to your register_taxonomy arguments.
You would need to set the rewrite slug to projects and with_front to false.  Also to note is that the register_taxonomy rewrite array also supports: 'hierarchical' - true or false allow hierarchical urls This allows you to use the full hierarchy on the taxonomy terms in your urls:


text:
Q: ¿Cómo puedo escoger los 2 términos mayores en python? Si tengo varias variables de tipo float y quiero escoger las 2 de mayor valor, ¿Cómo puedo hacer? En lenguaje Python

A: Si tienes varias variables, ponlas en una lista:
variables = [1., 6., 3., 4., 5., 2.]

luego la ordenas usando sorted, que te devuelve la lista ordenada de menor a mayor, por lo que tomamos los dos últimos elementos:
print(sorted(variables)[-2:])

produce:
[5.0, 6.0]


text:
Q: How do I set a default value that is invalidated by property setter checking? I have two fields with matching properties, each with data validation in the setter. I want the default values to be flagrantly incorrect. Thus, I am default initializing them to '\0' and -1.
private char _zoneLetter = '\0';
private short _zoneNumber = -1;

This is so that the only way these values can possibly exist is if they were never set, as I have an exception thrown in the setters.
public char ZoneLetter
{
    get { return _zoneLetter; }
    private set
    {
        if (!char.IsLetter(value)) throw new ArgumentException("No special characters are allowed.");
        _zoneLetter = value;
    }
}

public short ZoneNumber
{
    get { return _zoneNumber; }
    private set
    {
        if (!Enumerable.Range(1, 60).Contains(value)) throw new ArgumentException("Must be an integral value in the range [1,60].");
        this._zoneNumber = value;
    }
}

The trouble is that when I enter perfectly valid data, the exception is still thrown, telling me that the value '\0' is incorrect, even when 'a' is entered into the constructor parameter.
public UtmEvent(double unixTime, double easting, double northing, short zoneNumber, char zoneLetter)
    : base(unixTime)
{
    this.Easting = easting;
    this.Northing = northing;
    this.ZoneNumber = zoneNumber;
    this.ZoneLetter = ZoneLetter;
}

When I change the default values to something valid such as 'a' and 30, my test checking that no exceptions are thrown passes. Please tell me what I'm missing. I'm new to .Net and have no idea what is going on, haha.

A: You have a capitalization error,
this.ZoneLetter = ZoneLetter;

should be
this.ZoneLetter = zoneLetter;

A: My eyes missed the this.ZoneLetter = ZoneLetter; line in the constructor. I was trying to assign the property to itself, resulting in the getter grabbing the default value of '\0' and feeding it back into the setter's validation condition. Let this be a lesson that indicates the importance of not choosing shitty parameter names. Note to self: should not be the exact same as property or field names, with only the capitalization differing.
Oh, the humiliation.


text:
Q: why are there 3 different names for an Ember initializer When you generate a service with Ember CLI you get something like this:
export function initialize(container, application) {
  application.inject('route', 'geoService', 'service:geo');
  application.inject('component', 'geoService', 'service:geo');
}

export default {
  name: 'geo-service',
  initialize: initialize
};

You will notice that includes 3 different name formats for the service - geoService, service:geo and geo-service. Why is this needed and what is each of them? It's pretty confusing this way.

A: export function initialize(container, application) {
  /* service:geo is the factory name for a GeoService object
     the container keeps track of all the factories using this format.
  */

  // inject to every route the GeoService and
  // make it available through the property geoService
  application.inject('route', 'geoService', 'service:geo');

  // inject to every component the GeoService and
  // make it available through the property geoService
  application.inject('component', 'geoService', 'service:geo');
}

export default {
  /*
    The name of your service is geo, but by convention
    all objects are suffixed with the object type name,
    ex:
    ClientsView
    ClientsRoute
    ClientsController
    GeoService

    In Ember CLI The dashed format is the convention
    for file names and names in general.
  */
  name: 'geo-service',
  initialize: initialize
};

Ember Data does something like this, so you can use:
this.get('store');

With your service you can now do:
this.get('geoService');


text:
Q: php unset multidimensional array element which key value is match I have one multidimensional array:
Array
(
    [0] => stdClass Object
        (
            [user_type] => U
            [user_id] => 156
            [property_id] => 1201
        )

    [1] => stdClass Object
        (
            [user_type] => U
            [user_id] => 156
            [property_id] => 1200
        )

    [2] => stdClass Object
        (
            [user_type] => U
            [user_id] => 156
            [property_id] => 1196
        )

    [3] => stdClass Object
        (
            [user_type] => U
            [user_id] => 156
            [property_id] => 1193
        )
)

and I want to remove array which values are match with property_id:
Array
(
    [0] => 1201
    [1] => 1200
    [2] => 1193
)

and I want this result:
Array
(
    [0] => stdClass Object
        (
            [user_type] => U
            [user_id] => 156
            [property_id] => 1196
        )
)

I am sharing my code for what i have done:
for($b=0; $b<count($beBounceResults); $b++){
    $beBounceProID[] = $beBounceResults[$b]->property_id;
}
// Getting thus array in this variable $beBounceProID
Array
(
    [0] => 1201
    [1] => 1200
    [2] => 1193
)

$counter = "0";
foreach ($results as $key => $value){
    if($results[$key]->property_id == $beBounceProID[$counter]){
        unset($results[$key]);
    }
    $counter++;
}

but after that I am getting Notice: Undefined offset:
Any idea what I am doing wrong.
Thanks.

A: try this
foreach ($results as $key => $value){
    if(in_array($results[$key]->property_id , $beBounceProID) )
    {
        unset($results[$key]);
    }
}

A: Another approach is just to filter the arrays which you don't want out like this:
$arr = array_filter($arr, function($v)use($property_id){
    return !in_array($v->property_id, $property_id);
});


text:
Q: how to display years in date select descendingly? How do you display the year in descending order? At the moment, I have this:
<%= f.input :year_started, as: :date, label: "Date started", start_year: Date.today.year - 100, end_year: Date.today.year, discard_day: true, order: [:month, :year], include_blank: true, default: nil, :input_html => { :class => 'profile-date' } %>

The drop down year displays like this:
1900
1901
1902
....
2015

I want the opposite, How do you do it?:
2015
2014
2013
....
1900

Thanks.

A: I think it's as simple as swapping start_year and end_year.
Try:
<%= f.input :year_started, as: :date, label: "Date started", start_year: Date.today.year, end_year: Date.today.year - 100, discard_day: true, order: [:month, :year], include_blank: true, default: nil, :input_html => { :class => 'profile-date' } %>

It's actually in the API-docs: http://apidock.com/rails/ActionView/Helpers/DateHelper/date_select#190-Get-year-to-show-in-descending-order-Today-to-192-for-example-


text:
Q: C# Regex Issue Getting URLs To explain briefly, I'm trying to search Google with a keyword, then get the URLs of the top 10 results and save them.
This is the stripped down command line version of the code. It should return 1 result at least. If it works with that, I can apply it to my full version of the code and get all the results.
Basically the code I have right now, it fails if I try to get the entire source of Google. If I include a random section of code from Google's HTML source, it works fine. To me, that means my Regex has an error somewhere.
If there is a better way to do this aside from Regex, please let me know. The URLs are between
<a href=" and " class=l onmousedown="return clk(this.href
I got this Regex code from a generator, but it's really hard for me to understand Regex, Since nothing I've read explains it clearly. If someone could pick out what's wrong and explain why, I'd greatly appreciate it.
Thanks,
Kevin
using System;
using System.Text.RegularExpressions;
using System.Net;

namespace ConsoleApplication1
{
    class Program
    {
    static void Main(string[] args)
    {
        WebClient wc = new WebClient();
        string keyword = "seo nj";

        string html = wc.DownloadString(String.Format("http://www.google.com/search?q={0}", keyword));

        string re1 = "(<)"; // Any Single Character 1
        string re2 = "(h3)";    // Alphanum 1
        string re3 = "(\\s+)";  // White Space 1
        string re4 = "(class)"; // Variable Name 1
        string re5 = "(=)"; // Any Single Character 2
        string re6 = "(\"r\")"; // Double Quote String 1
        string re7 = "(>)"; // Any Single Character 3
        string re8 = "(<)"; // Any Single Character 4
        string re9 = "([a-z])"; // Any Single Word Character (Not Whitespace) 1
        string re10 = "(\\s+)"; // White Space 2
        string re11 = "((?:[a-z][a-z]+))";  // Word 1
        string re12 = "(=)";    // Any Single Character 5
        string re13 = ".*?";    // Non-greedy match on filler
        string re14 = "((?:http|https)(?::\\/{2}[\\w]+)(?:[\\/|\\.]?)(?:[^\\s\"]*))";   // HTTP URL 1
        string re15 = "(\")";   // Any Single Character 6
        string re16 = "(\\s+)"; // White Space 3
        string re17 = "(class)";    // Word 2
        string re18 = "(=)";    // Any Single Character 7
        string re19 = "(l)";    // Any Single Character 8
        string re20 = "(\\s+)"; // White Space 4
        string re21 = "(onmousedown)";  // Word 3
        string re22 = "(=)";    // Any Single Character 9
        string re23 = "(\")";   // Any Single Character 10
        string re24 = "(return)";   // Word 4
        string re25 = "(\\s+)"; // White Space 5
        string re26 = "(clk)";  // Word 5

        Regex r = new Regex(re1 + re2 + re3 + re4 + re5 + re6 + re7 + re8 + re9 + re10 + re11 + re12 + re13 + re14 + re15 + re16 + re17 + re18 + re19 + re20 + re21 + re22 + re23 + re24 + re25 + re26, RegexOptions.IgnoreCase | RegexOptions.Singleline);
        Match m = r.Match(txt);
        if (m.Success)
        {
            Console.WriteLine("Good");
            String c1 = m.Groups[1].ToString();
            String alphanum1 = m.Groups[2].ToString();
            String ws1 = m.Groups[3].ToString();
            String var1 = m.Groups[4].ToString();
            String c2 = m.Groups[5].ToString();
            String string1 = m.Groups[6].ToString();
            String c3 = m.Groups[7].ToString();
            String c4 = m.Groups[8].ToString();
            String w1 = m.Groups[9].ToString();
            String ws2 = m.Groups[10].ToString();
            String word1 = m.Groups[11].ToString();
            String c5 = m.Groups[12].ToString();
            String httpurl1 = m.Groups[13].ToString();
            String c6 = m.Groups[14].ToString();
            String ws3 = m.Groups[15].ToString();
            String word2 = m.Groups[16].ToString();
            String c7 = m.Groups[17].ToString();
            String c8 = m.Groups[18].ToString();
            String ws4 = m.Groups[19].ToString();
            String word3 = m.Groups[20].ToString();
            String c9 = m.Groups[21].ToString();
            String c10 = m.Groups[22].ToString();
            String word4 = m.Groups[23].ToString();
            String ws5 = m.Groups[24].ToString();
            String word5 = m.Groups[25].ToString();
            //Console.Write("(" + c1.ToString() + ")" + "(" + alphanum1.ToString() + ")" + "(" + ws1.ToString() + ")" + "(" + var1.ToString() + ")" + "(" + c2.ToString() + ")" + "(" + string1.ToString() + ")" + "(" + c3.ToString() + ")" + "(" + c4.ToString() + ")" + "(" + w1.ToString() + ")" + "(" + ws2.ToString() + ")" + "(" + word1.ToString() + ")" + "(" + c5.ToString() + ")" + "(" + httpurl1.ToString() + ")" + "(" + c6.ToString() + ")" + "(" + ws3.ToString() + ")" + "(" + word2.ToString() + ")" + "(" + c7.ToString() + ")" + "(" + c8.ToString() + ")" + "(" + ws4.ToString() + ")" + "(" + word3.ToString() + ")" + "(" + c9.ToString() + ")" + "(" + c10.ToString() + ")" + "(" + word4.ToString() + ")" + "(" + ws5.ToString() + ")" + "(" + word5.ToString() + ")" + "\n");
            Console.WriteLine(httpurl1);
        }
        else
        {
            Console.WriteLine("Bad");
        }
        Console.ReadLine();
    }
}
}

A: You're doing it wrong.
Google has an API for doing searches programmatically. Don't put yourself through the pain of trying to parse HTML with regexes, when there's already a published, supported way to do what you want.
Besides, what you're trying to do -- submit automated searches through Google's Web site and scrape the results -- is a violation of section 5.3 of their Terms of Service:

You specifically agree not to access (or attempt to access) any of the Services through any automated means (including use of scripts or web crawlers)

A: using RegEx to parse HTML is sado-masochism.
Try using the HTML Agility Pack instead.  It will allow you to parse HTML.  See this question for an example of using it.


text:
Q: Can I launch a lower version to App Store than previously? I inherited an iOS application where the version is 20.0.0 (Looks like launched with a typo).  I was wondering if I can lower the version down to 3.0.0?

A: In a word, no. Version numbers can only go up. If you attempt to upload a binary with a lower version number, iTunes Connect will balk.


text:
Q: Applying DivisorSigma to each element in a list Take a simple Table
table = Table[n^2, {n, 1, 10}]

{1, 4, 9, 16, 25, 36, 49, 64, 81, 100}

I want to apply the function DivisorSigma[1, #] to each element of table to create a new list / table with 10 entries. (The 1 specifies the sum-of-divisors function; I'm using # in a non-literal way, just to signify that I want to apply the function to each element of table separately.)
I assume I need to use either Map or Apply, or a combination of both. But because DivisorSigma requires two arguments, I'm not sure how to proceed.

A: table = Table[n^2, {n, 1, 10}]

A couple of ways. Note that # only applies to the numbers included in table. The second argument to DivisorSigma is fixed.
Map[DivisorSigma[1, #] &, table]
(* {1, 7, 13, 31, 31, 91, 57, 127, 121, 217} *)

I frequently like to use Table rather than Map as it is more readable.
Table[DivisorSigma[1, it], {it, table}]
(* {1, 7, 13, 31, 31, 91, 57, 127, 121, 217} *)


text:
Q: Passing javascript variables to webpack from htm page Lets say I have a index.htm file which includes my webpack bundle.js.
But before the bundle.js is added I have a variable setup...
  myVar = 'test';

Now if I reference this var in my entry.js which is included in the bundle.js... it says it is undefined... How do I get a variable from my htm page into webpack?

A: As you defined it, myVar is global.
You could use window.myVar in entry.js without a problem.


text:
Q: How to disable RocksDB database debug logging? RocksDB writes detailed database debug logs:

Database Debug Logs
RocksDB writes detailed logs to a file named LOG*. These are mostly used for debugging and analyzing a running system. This LOG may be configured to roll at a specified periodicity.

In my Rust application, which interfaces with RocksDB via the rust-rocksdb crate, I tried to set keep_log_file_num to 0, via:
let mut opts = Options::new();
opts.set_parsed_options("keep_log_file_num=0")?;

But this causes my application to abort with an out of range error.
terminate called after throwing an instance of 'std::out_of_range'
  what():  vector::_M_range_check: __n (which is 1) >= this->size() (which is 1)

Thread 1 "client" received signal SIGABRT, Aborted.
__GI_raise (sig=sig@entry=6) at ../sysdeps/unix/sysv/linux/raise.c:58
58  ../sysdeps/unix/sysv/linux/raise.c: No such file or directory.
(gdb) bt
#0  __GI_raise (sig=sig@entry=6) at ../sysdeps/unix/sysv/linux/raise.c:58
#1  0x00007ffff7a4737a in __GI_abort () at abort.c:89
#2  0x00007ffff771956d in __gnu_cxx::__verbose_terminate_handler() () from /usr/lib/x86_64-linux-gnu/libstdc++.so.6
#3  0x00007ffff7717316 in ?? () from /usr/lib/x86_64-linux-gnu/libstdc++.so.6
#4  0x00007ffff7717361 in std::terminate() () from /usr/lib/x86_64-linux-gnu/libstdc++.so.6
#5  0x00007ffff7717579 in __cxa_throw () from /usr/lib/x86_64-linux-gnu/libstdc++.so.6
#6  0x00007ffff7741317 in std::__throw_out_of_range_fmt(char const*, ...) () from /usr/lib/x86_64-linux-gnu/libstdc++.so.6
#7  0x0000555558a1ce9a in std::vector<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::allocator<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > > >::_M_range_check (this=0x7ffffffe2420, __n=1)
    at /usr/include/c++/6/bits/stl_vector.h:804
#8  0x0000555558a11aef in std::vector<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::allocator<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > > >::at (this=0x7ffffffe2420, __n=1)
    at /usr/include/c++/6/bits/stl_vector.h:825
#9  0x00005555589f1a2f in rocksdb::DBImpl::PurgeObsoleteFiles (this=0x7ffff5fabe00, state=..., schedule_only=false) at rocksdb/db/db_impl.cc:1094
#10 0x00005555589f201a in rocksdb::DBImpl::DeleteObsoleteFiles (this=0x7ffff5fabe00) at rocksdb/db/db_impl.cc:1128
#11 0x0000555558a0aad3 in rocksdb::DB::Open (db_options=..., dbname="/tmp/client-0002/chains/main/db/906a34e69aec8c0d/overlayrecent/db", column_families=std::vector of length 1, capacity 1 = {...}, handles=0x7ffffffe2e60, dbptr=0x7ffffffe3490)
    at rocksdb/db/db_impl.cc:5771
#12 0x0000555558a09e45 in rocksdb::DB::Open (options=..., dbname="/tmp/client-0002/chains/main/db/906a34e69aec8c0d/overlayrecent/db", dbptr=0x7ffffffe3490) at rocksdb/db/db_impl.cc:5662
#13 0x00005555589d48ad in rocksdb_open (options=0x7ffff57ff800, name=0x7ffff5f086e0 "/tmp/client-0002/chains/main/db/906a34e69aec8c0d/overlayrecent/db", errptr=0x7ffffffe38d8) at rocksdb/db/c.cc:408
#14 0x00005555589ca4de in rocksdb::rocksdb::DB::open_cf (opts=0x7ffffffe3ea0, path=..., cfs=..., cf_opts=...) at /home/user/.cargo/git/checkouts/rust-rocksdb-9e499ea8a4c2fa74/4364cae/src/rocksdb.rs:317
#15 0x000055555889b42c in ethcore_util::kvdb::Database::open (config=0x7ffffffe5700, path=...) at util/src/kvdb.rs:537
#16 0x0000555557b8e288 in ethcore::service::ClientService::start (config=..., spec=0x7ffffffeb548, client_path=0x7ffff5e5bfc0, snapshot_path=0x7ffff5e5c6e0, ipc_path=0x7ffff5a307a0, miner=...) at ethcore/src/service.rs:91
#17 0x000055555646d742 in client::run::execute (cmd=..., can_restart=false, logger=...) at client/run.rs:547
#18 0x0000555556484ea6 in client::execute (command=..., can_restart=false) at client/main.rs:159
#19 0x0000555556486720 in client::start (can_restart=false) at client/main.rs:185
#20 0x0000555556487518 in client::main_direct (can_restart=false) at client/main.rs:286
#21 0x0000555556488a71 in client::main () at client/main.rs:367

Setting it to 1 works fine, but I want to get rid of it completely.
I assume setting the maximum log file number to 0 is not the way to go, but I'm running out of ideas. How do I disable RocksDB database debug logging? I want to gain control of that behavior.


text:
Q: Access IFf Query I'm new and just starting out at creating databases so I apologise if noob question.
What I am trying to do is update my Staff table to show that "Sarah Avon" has married and her new last name is changed to "Tyne"

I have used in SQL view the following code to do this.

However when running the query it leaves all cells blank as shown below. What I wish to happen is Sarah's last name is updated from Avon to Tyne.

Can anyone bring some light on the subject as to where I have gone wrong?
Thank you all for your time.

A: I don't know much of T-SQL but I believe that to compare strings you need the logical operator AND. Try this:
UPDATE StaffCopy SET StaffCopy.LastName=IIF(([LastName]='Avon' AND [FirstName]='Sarah'), 'Tyne', [LastName]);


text:
Q: Allow www-data user to mount root as RW I am running a system that has the root partition (/) mounted as 'ro' (read-only) for most of the time. However, I need to make it so that the 'www-data' user can make it 'rw'.
To make it 'rw', I use the command sudo mount -o remount,rw /. This works.
However, when a PHP script ('www-data' user) executes the same command, it fails.
I have created a file in /etc/sudoers.d/ folder with the following content:
www-data ALL=(ALL) NOPASSWD: ALL

And I can confirm that it works because I can execute the /usr/bin/sudo /sbin/reboot command in PHP. However, the /bin/mount command does not work. Do I need to do something else?
I will make the sudoers file more specific so only that particular command can be executed, but for now I am just trying to make it work.
Looking at the logs. After manually executing the command:
2020-10-22T19:37:19+0000 d0-14-11-00-00-03 sudo[18582]:       pi : TTY=serial1 ; PWD=/home/pi ; USER=root ; COMMAND=/bin/mount -o remount,rw /
2020-10-22T19:37:20+0000 d0-14-11-00-00-03 sudo[18582]: pam_unix(sudo:session): session opened for user root by (uid=0)
2020-10-22T19:37:20+0000 d0-14-11-00-00-03 kernel: EXT4-fs (mmcblk0p2): re-mounted. Opts: (null)
2020-10-22T19:37:20+0000 d0-14-11-00-00-03 sudo[18582]: pam_unix(sudo:session): session closed for user root

After executing command via the PHP script:
2020-10-22T19:38:26+0000 d0-14-11-00-00-03 sudo[18703]: www-data : TTY=unknown ; PWD=/var/www/web ; USER=root ; COMMAND=/bin/mount -vo remount,rw /
2020-10-22T19:38:27+0000 d0-14-11-00-00-03 sudo[18703]: pam_unix(sudo:session): session opened for user root by (uid=0)
2020-10-22T19:38:27+0000 d0-14-11-00-00-03 sudo[18703]: pam_unix(sudo:session): session closed for user root
2020-10-22T19:38:27+0000 d0-14-11-00-00-03 kernel: EXT4-fs (mmcblk0p2): re-mounted. Opts: (null)

Solved
Solved using solution from here:
Remount root file-system via PHP and apache2 doesn't work before execute mount via shell


text:
Q: PSCP automatic upload newest file I am trying to make a bat script that uploades the newest file from a folder to the public html. How to do this? I got this to work at the moment.
c:pscp -pw password c:\index.html user@host:public_html/index.html

A: Got it:
set source="C:\dir"
FOR /F "delims=|" %%I IN ('DIR %source% /B /O:D') DO SET NewestFile=%%I

c:pscp -pw password %source%\%NewestFile% user@host:public_html/%NewestFile%

pause


text:
Q: Riemann Integrator Sum Issue Here is my code for the Riemann Integrator:
public class RiemannIntegrator {

    public static void main (String [] args)
    {
        double lower = Double.parseDouble(args[args.length -2]);
        double higher = Double.parseDouble(args[args.length -1]);

        double[] coefficients = new double[args.length - 3];

        if (args[0].equals("poly"))
        {
            for (int i = 1; i < args.length - 2; i++)
            {
                coefficients[i-1] = Double.parseDouble(args[i]);
            }

            System.out.println(integral("poly", coefficients, lower, higher));
        }
    }

    private static double integral(String s, double[] function, double lowBound, double highBound)
    {

        double area = 0; // Area of the rectangle
        double sumOfArea = 0; // Sum of the area of the rectangles
        double width = highBound - lowBound;

            if (s.equals("poly"))
            {
                for (int i = 1; i <= ((highBound - lowBound) / width); i++) // Represents # of rectangles
                {
                    System.out.println("Rectangles:" + i);
                    for (int j = 0; j < function.length; j++) // Goes through all the coefficients
                    {
                        area = width * function[j] * Math.pow ( (double)( (i * width + lowBound + (i -1.0) * width + highBound) / 2.0 ),function.length- 1- j);
                        /*Above code computes area of each rectangle */

                        sumOfArea += area;
                    }
                }
            }
            width = width / 2.0;
            System.out.println("polynomial, function (of any length), lower boundary, higher boundary.");
            function.toString();
            System.out.println("Lower Bound:" + lowBound + ", Higher Bound: " + highBound + ".");
            System.out.println("The integral is:");
            return sumOfArea;
    }

}

It works for the most part, however, the math is wrong more often than not, and I don't know where I went wrong. For example, if I want to find the sum of the function of x^3+2x^2+3x, I get 2.416667 on my calculator, and on Wolfram Alpha. But, in my program, it tells me that I get 6. I think it may have something to do with the number of rectangles, because it always tells me I get one rectangle. Can anyone help?

A: You need another loop, something along the lines of
double width = highBound - lowBound;
double epsilon = .001; // This determines how accurate you want the solution to be, closer to zero = more accurate
double prevValue = -1.0;
double curValue = -1.0; // initialize curValue to a negative value with greater magnitude than epsilon - this ensures that the while loop evaluates to true on the first pass
do {
    ... // this is where your for loop goes
    prevValue = curValue;
    curValue = sumOfArea;
    width /= 2.0;
} while(Math.abs(prevValue - curValue) > epsilon);

The idea is that you keep decreasing the rectancles' width until the sumOfArea with width = w is more-or-less the same (i.e. within epsilon) as the sumOfArea with width = 2w.
There are faster + more accurate integration algorithms out there e.g. Newton-Cotes, but I'm assuming you don't have a choice in the matter.


text:
Q: Path not found within XSL transformation This is a follow up question. I have copied the original question below.
I made the mentioned changes but it seems that xsltproc doesn't find b.xml though a.xml and b.xml are in the same folder. I call xsltproc right from the same folder. Maybe my call is incorrect. I used
xsltproc -v --debug -o output.xml merge3.xsl a.xml

where merge3.xsl is your (adapted) example. I know that --debug and -v are not necessary but I wanted to see what xsltproc is doing.
Unfortunately output.xml is an exact copy of a.xml.
What does the "ns1" in an XSLT mean? I wonder if my paths are set correctly. I suppose that ns1 is a parameter of my call. But which one?
Even if I use  full paths to all of the files I only get a copy of a.xml. Where is the mistake?
This is merge3.xsl:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:ns1="http://tempuri.org/List.xsd">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>

<xsl:param name="doc2" select="'b.xml'" />

<!-- identity transform -->
<xsl:template match="@*|node()">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="ns1:Record_Count">
    <xsl:copy>
        <xsl:value-of select=". + document($doc2)/ns1:List/ns1:publshInformation/ns1:Record_Count" />
    </xsl:copy>
</xsl:template>

<xsl:template match="ns1:List">
    <xsl:copy>
        <xsl:apply-templates select="*|document($doc2)/ns1:List/ns1:Entry">
            <xsl:sort select="ns1:uid" data-type="text" order="ascending"/>
        </xsl:apply-templates>
    </xsl:copy>
</xsl:template>

</xsl:stylesheet>

This was the original question:
I've searched for a solution for my problem. I found some similar questions and answers but none of them fitted to my problem.
I'm an XML newbie and never used XSLT before. I have Linux and could use xsltproc or xmllint (or whatever would be best).
The problem is rather easy. I have to XML files with identical layout. At the beginning is a counter for the nodes included in one file. I just need the counters of both files added and then all nodes from both files as a single list. (Sorted would be even better.)
Example:
a.xml
<?xml version="1.0" standalone="yes"?>
<List xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://tempuri.org/List.xsd">
  <publshInformation>
    <Publish_Date>12/17/2014</Publish_Date>
    <Record_Count>115</Record_Count>
  </publshInformation>
  <Entry>
    <uid>9639</uid>
    <firstName>Bob</firstName>
....
  </Entry>
</List>

b.xml
<?xml version="1.0" standalone="yes"?>
<List xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://tempuri.org/List.xsd">
  <publshInformation>
    <Publish_Date>12/17/2014</Publish_Date>
    <Record_Count>100</Record_Count>
  </publshInformation>
  <Entry>
    <uid>4711</uid>
    <firstName>John</firstName>
....
  </Entry>
</List>

Result:
out.xml
<?xml version="1.0" standalone="yes"?>
<List xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://tempuri.org/List.xsd">
  <publshInformation>
    <Publish_Date>12/17/2014</Publish_Date>
    <Record_Count>215</Record_Count>
  </publshInformation>
  <Entry>
    <uid>4711</uid>
    <firstName>John</firstName>
....
  </Entry>
  <Entry>
    <uid>9639</uid>
    <firstName>Bob</firstName>
....
  </Entry>
</List>

How can I manage that? I don't post my XSLTs here because they are not working and that's because of my limited skills. Thanks for any suggestions!


text:
Q: Service's promise in AngularJS controller with as syntax I have problem with below code. I prefer controller as controller syntax and assigning data to this instead of $scope. Problem is that it does not work in below case, everything is fine with $scope.user, but this.user doesn't show anything in template. Did I anything wrong or do I need to use $scope in this case?
angular.module('services', [])
    .factory('current_user', ['$http', '$q', function($http, $q){
        var deferred = $q.defer();
        $http.get('/api/user').success(function(data){
            deferred.resolve(data);
        });
        return deferred.promise;
    }]);

angular.module('controllers', [])
    .controller('myUser', ['current_user', '$scope', function(current_user, $scope){
        current_user.then(function(data){
            this.user = data; #does not work
            $scope.user = data; #works fine
        })
    }]);

Current user: {{ user }}

Current user: {{ myUser.user }}

A: When passing a callback into a function like that, you can't be guaranteed that the context (i.e. this) is what you expect. In this case, this is likely to point to the Promise itself.
To work around this, you can either capture a reference to your controller using var ctrl = this outside of your callback:
angular.module('controllers', [])
    .controller('myUser', ['current_user', function(current_user){
        var ctrl = this;
        current_user.then(function(data){
            ctrl.user = data;
        });
    }]);

The above also is why attaching the property to $scope works, because it's always going to be a reference to your controller in that context.
Or else you can use bind to force the context of your promise callback to be your controller:
angular.module('controllers', [])
    .controller('myUser', ['current_user', function(current_user){
        current_user.then(function(data){
            this.user = data;
        }.bind(this));
    }]);


text:
Q: Shutdown problems and wi fi not working on Acer Extensa 5220 Just installed Ubuntu 14.04LTS on an Acer Extensa 5220 laptop
After install I downlaoded all the updates suggested.
Two problems:
The in built wi fi does not work at all. I can connect to the network via a wired ethernet connection but the wireless network is not mentioned anywhere.
Second problem, on shutting down the screen goes blank, HDD activity stops but power remains on. Have to then press and hold the power button to turn off.
If I try going to suspend, the screen goes blank for a while, power stays on, then after a short while the screen comes back on inviting me to log in again.
sudo lshw -c video returns:
*-display:0
description: VGA compatible controller
product: Mobile GM965/GL960 Integrated Graphics Controller (primary)
vendor: Intel Corporation
physical id: 2
bus info: pci@0000:00:02.0
version: 03
width: 64 bits
clock: 33MHz
capabilities: msi pm vga_controller bus_master cap_list rom
configuration: driver=i915 latency=0
resources: irq:44 memory:fc000000-fc0fffff memory:d0000000-dfffffff
ioport:1800(size=8)
*-display:1 UNCLAIMED
description: Display controller
product: Mobile GM965/GL960 Integrated Graphics Controller (secondary)
vendor: Intel Corporation
physical id: 2.1
bus info: pci@0000:00:02.1
version: 03
width: 64 bits
clock: 33MHz
capabilities: pm bus_master cap_list
configuration: latency=0
resources: memory:fc100000-fc1fffff

In the mean time sudo shutdown -h now stops any hdd activity but leaves power on with a screen saying UBUNTU and scrolling red / white dots under it.
I have tried using the software centre so search for driver. it says "no additional drivers found"
I did find in the software centre "Windows wireless drivers" which claims to be an easy way to install windows wireless drivers. but beg my ignorance, having downloaded it, I can;t find where it has put it to actually run it?


text:
Q: How to serve static files in pycharm when running a server If I wan't static files to be served when debugging or testing my application when I'm starting the server from terminal I would just add --insecure to runserver command.
But How to do that in the right way in PyCharm?

A: Add the flag to "Additional options:" field when you edit the configuration for you project.


text:
Q: 64bit version of Octave on Windows Does anybody know how to build Octave for x64 Windows?  The 2GB data limitation for x32 is too limiting for many problems that require analysis on large data sets.

A: http://wiki.octave.org/Octave_for_Microsoft_Windows has information on installing Octave on Windows and links to building it from source using different methods.

GNU Octave is primarily developed on GNU/Linux and other POSIX conformal systems. The ports of GNU Octave to Windows use different approaches to get most of the original Octave and adapt it to Microsoft Windows idiosyncrasies...

Windows support is experimental.
According to http://www.gnu.org/software/octave/doc/interpreter/Compiling-Octave-with-64_002dbit-Indexing.html

To use arrays larger than 2 GB, Octave has to be configured with the option --enable-64. This option is experimental...

Compiling Octave for 64 bit is experimental on Linux. It might cause a lot of headache to try an experimental feature in a port of the software. It would be better to use a true Linux installation for now. If you feel adventurous, try compiling it in http://www.cygwin.com/

A: I have installed Octave-4.0.0 into windows 7,8 and 10 in x64 platforms. All works perfectly well.
Just follow these steps

*

*Download Octave-4.0.0_0-installer.exe from https://ftp.gnu.org/gnu/octave/windows/

*Install the same - just follow the steps in the installer.

*Find the build_packages.m file in C:\Octave\Octave 4.0.0\src

*Open it in Octave and find
try install general-1.3.4.tar.gz, and try install signal-1.3.1.tar.gz, the versions are wrong.
Replace with 2.0.0 and 1.3.2 respectively.

*In the build_packages.m file find
pkg ('install', pkgname, '-noauto').
Change it to
pkg ('install', pkgname).
Skip this and you will have to load the packages you require every time you use Octave. Lesser load for octave though. Sometimes it may take a while for the packages to get installed, kindly wait.

*Run build_packages.m

*load the packages
e.g. to load the general package - pkg load general
Note that the signal package is dependent on the control package.

*I found that the plot function got octave stuck. The answer for the same is to type in at the command window
pkg rebuild -noauto oct2mat
Found this solution in Plot window not responding
Hope this works for u too. :)

A: I found Sreepad's ans is CORRECT.  I use octave on win 10  64-bit OS.
octave 4.0.0 is ok as Sreepad said,  But Octave 4.2.1 is not OK on Win 10 64-bit OS.


text:
Q: Beamer bibliography over EXACTLY two pages, no matter how many references? I have a requirement to output the bibliography for a beamer over exactly two pages, no matter how many references (output will be infinitely zoomable .pdf).
\documentclass[8pt, xcolor=table]{beamer}
\usepackage[american]{babel}
\usepackage{csquotes}
\usepackage[style=apa]{biblatex}
\addbibresource{bibliography.bib}

\begin{document}

\begin{frame}
  \frametitle{Bibliography}
\printbibliography
\end{frame}

\end{document}


text:
Q: Getting a bmp file into a RichTextBox: resizing without losing quality + dealing with windows scaling Goal:
My goal is to get a picture (a bmp file) into a RichTextBox, at a size I choose, say 400 pixels high, and width scaled to match, without it being ruined by Windows Scaling (125%, 150%, 200% etc.), or losing quality.
Here's my code:
<DllImport("user32.dll", EntryPoint:="OpenClipboard")> Private Shared Function OpenClipboard(ByVal hWnd As IntPtr) As Boolean
End Function
<DllImport("user32.dll", EntryPoint:="EmptyClipboard")> Private Shared Function EmptyClipboard() As Boolean
End Function
<DllImport("user32.dll", EntryPoint:="SetClipboardData")> Private Shared Function SetClipboardData(ByVal uFormat As Integer, ByVal hWnd As IntPtr) As IntPtr
End Function
<DllImport("user32.dll", EntryPoint:="CloseClipboard")> Private Shared Function CloseClipboard() As Boolean
End Function
<DllImport("gdi32.dll", EntryPoint:="CopyEnhMetaFileA")> Private Shared Function CopyEnhMetaFile(ByVal hemfSrc As IntPtr, ByVal hNULL As IntPtr) As IntPtr
End Function
<DllImport("gdi32.dll", EntryPoint:="DeleteEnhMetaFile")> Private Shared Function DeleteEnhMetaFile(ByVal hemfSrc As IntPtr) As Boolean
End Function

Private Sub PasteMeta(imgPathName As String)
    'Create a bitmap of the image you want to draw to the metafile
    Dim bm As New Bitmap(imgPathName)

    'Create a graphics object of the Form and get its hdc handle
    Dim me_grx As Graphics = Me.CreateGraphics()
    Dim me_hdc As IntPtr = me_grx.GetHdc()
    Dim scale = 400 / bm.Height
    'Create a new metafile the same size as the image and create a graphics object for it
    Dim emf As New Imaging.Metafile("Tmp.emf", me_hdc, New Rectangle(0, 0, bm.Width * scale, 400), Imaging.MetafileFrameUnit.Point)
    Dim emf_gr As Graphics = Graphics.FromImage(emf)

    emf_gr.DrawImage(bm, 0, 0, CInt(bm.Width * scale) * _windowsScaling, CInt(bm.Height * scale) * _windowsScaling)

    'Dispose the bitmap and the metafile graphics object
    emf_gr.Dispose()
    bm.Dispose()

    PutEnhMetafileOnClipboard(Me.Handle, emf)
    'Paste the new metafile in the RichTextBox
    JournalRichTextBox.Paste()
    'Dispose the rest of the objects we created
    me_grx.ReleaseHdc(me_hdc)
    me_grx.Dispose()
    emf.Dispose()
End Sub

Private Shared Function PutEnhMetafileOnClipboard(ByVal hWnd As IntPtr, ByVal mf As Imaging.Metafile) As Boolean
    Dim bResult As New Boolean()
    bResult = False
    Dim hEMF, hEMF2 As IntPtr
    hEMF = mf.GetHenhmetafile() ' invalidates mf
    If Not hEMF.Equals(New IntPtr(0)) Then
        hEMF2 = CopyEnhMetaFile(hEMF, New IntPtr(0))
        If Not hEMF2.Equals(New IntPtr(0)) Then
            If OpenClipboard(hWnd) Then
                If EmptyClipboard() Then
                    Dim hRes As IntPtr
                    hRes = SetClipboardData(14, hEMF2)    ' 14 == CF_ENHMETAFILE
                    bResult = hRes.Equals(hEMF2)
                    CloseClipboard()
                End If
            End If
        End If
        DeleteEnhMetaFile(hEMF)
    End If
    Return bResult
End Function

Here's what happens to the RTB when I run the sub:
https://i.imgur.com/rqChD4Q.png
Background and what I've tried:
My first go was to just use the bitmap size property, but that really ruins the quality - it's completely useless.
Then I found this magical way that sorted the quality. To be brief, it's the top answer here: https://social.msdn.microsoft.com/Forums/vstudio/en-US/355bfc59-cd0a-4e81-984e-9f066fd3a897/richtextbox-images-quality-loss?forum=vbgeneral
In summary, it makes a metafile and graphic, does the resizing with it and puts it into the clipboard and then pastes that into the richtextbox.
I got that working nicely. However, I have my 4K screen scaled at 200% and that means that the picture is the right size but the metafile it is put in is twice the size.
I have spent about 4 hours googling and trying everything I could find to work around this. No matter what I do, the DPI I get for the form, or controls within it, is always 96, so I can't use one of the DpiX solutions.
If I add:
<DllImport("User32.dll")>
Private Shared Sub SetProcessDPIAware()
End Sub

Public Sub New()
    SetProcessDPIAware()
    InitializeComponent()
End Sub

It just makes the form unscaled (some buttons and labels still are scaled though - weird!)
Trying to override the scalecontrol event always returns a factor.X, factor.Y = 1, never anything else.
What I'd like if possible:
Please note that the BEST solution would be to just get a number for the scale factor. 125% = 1.25, 150% = 1.5 etc. If I have that number, I can just multiply the dimensions of the graphic by it and it fits perfectly (for example)
I think my main problem is I've got this working using too much code that I just don't understand. I would really appreciate you could bare that in mind when answering, I might not understand your answer if it's giving me too much doubt-benefit. I think the solution might be here: https://msdn.microsoft.com/en-us/library/cc250585.aspx
But that's way over my head at the mo. So any help or advice would be REALLY appreciated.
FYI I am targeting 3.5 and would like to stick to that if possible.


text:
Q: Http request header HTTP_ACCEPT is different when the request originates out of an iframe I noticed that when I initiate the same server request, once from a script tag, and the other from within an iframe, the request header's HTTP_ACCEPT section is different.
These are the html page I run:
Request from within an Iframe:

<!DOCTYPE html>

Request from a script block:

<!DOCTYPE html>

You'd notice that the request headers are different between the 2 requests. While the script request's HTTP_ACCEPT equals "/", HTTP_ACCEPT of the request which was generated from an iframe may vary from "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,/;q=0.8" to "application/x-ms-application, image/jpeg, application/xaml+xml, image/gif, image/pjpeg, application/x-ms-xbap, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, /", depending on the browser is't being ran on.
Do you know if this kind of behavior is persistent and what causes it? I realize that this section of the header is being generated automatically by the browser, but I didn't manage to find any information regarding the possible differences between requests from Iframe and from within a script block.
Thank you in advance!


text:
Q: How to slice a dataframe by selecting a range of columns and rows based on names and not indexes? This is a follow-up question of the question I asked here. There I learned a) how to do this for columns (see below) and b) that the selection of rows and columns seems to be quite differently handled in R which means that I cannot use the same approach for rows.
So suppose I have a pandas dataframe like this:
import pandas as pd
import numpy as np

df = pd.DataFrame(np.random.randint(10, size=(6, 6)),
                  columns=['c' + str(i) for i in range(6)],
                  index=["r" + str(i) for i in range(6)])

    c0  c1  c2  c3  c4  c5
r0   4   2   3   9   9   0
r1   9   0   8   1   7   5
r2   2   6   7   5   4   7
r3   6   9   9   1   3   4
r4   1   1   1   3   0   3
r5   0   8   5   8   2   9

then I can easily select rows and columns by their names like this:
print df.loc['r3':'r5', 'c1':'c4']

which returns
    c1  c2  c3  c4
r3   9   9   1   3
r4   1   1   3   0
r5   8   5   8   2

How would I do this in R? Given a dataframe like this
df <- data.frame(c1=1:6, c2=2:7, c3=3:8, c4=4:9, c5=5:10, c6=6:11)
rownames(df) <- c('r1', 'r2', 'r3', 'r4', 'r5', 'r6')

   c1 c2 c3 c4 c5 c6
r1  1  2  3  4  5  6
r2  2  3  4  5  6  7
r3  3  4  5  6  7  8
r4  4  5  6  7  8  9
r5  5  6  7  8  9 10
r6  6  7  8  9 10 11

Apparently, if I know the indexes of my desired rows/columns, I can simply do:
df[3:5, 1:4]

but I might delete rows/columns throughout my analysis so that I would rather select by name than by index. From the link above I learned that for columns the following would work:
subset(df, select=c1:c4)

which returns
  c1 c2 c3 c4
r1  1  2  3  4
r2  2  3  4  5
r3  3  4  5  6
r4  4  5  6  7
r5  5  6  7  8
r6  6  7  8  9

but how could I also select a range of rows by name at the same time?
In this particular case I could of course use grep but how about columns that have arbitrary names?
And I don't want to use
df[c('r3', 'r4' 'r5'), c('c1','c2', 'c3', 'c4')]

but an actual slice.

A: You can use which() with rownames:
subset(df[which(rownames(df)=='r3'):which(rownames(df)=='r5'),], select=c1:c4)

   c1 c2 c3 c4
r3  3  4  5  6
r4  4  5  6  7
r5  5  6  7  8

A: Use match to find the position of specific row names.
df[match("r3", rownames(df)):match("r5", rownames(df)), match("c1", colnames(df)):match("c4", colnames(df))]

   c1 c2 c3 c4
r3  3  4  5  6
r4  4  5  6  7
r5  5  6  7  8

A: You can write a function that will kinda give you the same behavior
'%:%' <- function(object, range) {
  FUN <- if (!is.null(dim(object))) {
    if (is.matrix(object)) colnames else names
  } else identity
  wh <- if (is.numeric(range)) range else which(FUN(object) %in% range)
  FUN(object)[seq(wh[1], wh[2])]
}

df <- data.frame(c1=1:6, c2=2:7, c3=3:8, c4=4:9, c5=5:10, c6=6:11)
rownames(df) <- c('r1', 'r2', 'r3', 'r4', 'r5', 'r6')

Use it like
df %:% c('c2', 'c4')
# [1] "c2" "c3" "c4"

rownames(df) %:% c('r2', 'r4')
# [1] "r2" "r3" "r4"

For your question
df[rownames(df) %:% c('r3', 'r5'), df %:% c('c1', 'c5')]
#    c1 c2 c3 c4 c5
# r3  3  4  5  6  7
# r4  4  5  6  7  8
# r5  5  6  7  8  9


text:
Q: Use of fmin in python I'm trying to use fmin to minize my function:
def minim(self,x_r,x_i):
    self.a=complex(3,4)*(3*np.exp(1j*self.L_ch))
    x = x_r + x_i
    self.T=np.array([[0.0,2.0*self.a],[(0.00645+(x_r)^2), 4.3*x_i^2]])
    return self.T

part_real=0.532
part_imag=1.2
R_0 = fmin(A.minim,part_real,part_imag)

but i got this error:
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/scipy/optimize/optimize.py", line 268, in function_wrapper
    return function(x, *args)
TypeError: minim() argument after * must be a sequence, not float

I tried to use something else like minimize but the same error appear. Thank you.

A: You are not using fmin correctly.
scipy.optimize.fmin(func, x0, args=(), xtol=0.0001, ftol=0.0001, maxiter=None, maxfun=None, full_output=0, disp=1, retall=0, callback=None). If you want to optimize for both x_r and x_i, you should pass them together as x0. The way you are doing it now passes part_imag as args, which should be a sequence, not a scalar. That's why your get an exception
Without an reproducible example, I guess you need to change your code to:
def minim(self,p):
    x_r=p[0]
    x_i=p[1]
    self.a=complex(3,4)*(3*np.exp(1j*self.L_ch))
    x = x_r + x_i
    self.T=np.array([[0.0,2.0*self.a],[(0.00645+(x_r)^2), 4.3*x_i^2]])
    return self.T

part_real=0.532
part_imag=1.2
R_0 = fmin(A.minim,[part_real,part_imag])

And see if it works.
Also your x seems never get used.


text:
Q: Using starlight to create a fire It is easily experimentally demonstrated that a focussed image of the Sun can be used to start a fire. Furthermore, by thermodynamic considerations or the conservation of étendue, it can be shown that moonlight cannot be focussed such that a fire can be created. However, it is theoretically possible to magnify starlight enough to create a fire, as the surface temperature of a distant star is still above the ignition temperature of tinder.
According to this article, there was a paper published in 2002 that included a design for a telescope capable of this. Does anyone know what the paper was? I've tried searching on Google Scholar and have found nothing relevant so far. My back of the envelope calculations suggest that in order to magnify Betelguese such that it had the apparent diameter of the Sun would require a magnification of at least 36,000 times. Assuming we were then going to focus this image to a small disk using a microscope objective, this would suggest we need an aperture of the order of 100s of metres in diameter... I'd be interested to see if there's a trick around this.

A: Listening to the recording that the article was derived from, it appears that the article is:
Donald Lynden-Bell. Exact Optics : A unification of optical telescope design. Mon. Not. R. Astron. Soc. (2002)


text:
Q: Matlab "Index exceeds the number of array elements." error I have this matlab code, and it it supposed to take user input of a function, a limit, and threshold error. Then it uses the formula |f(n) - L| < error, and counts how many iterations of n is needed in order to hold that formula true. this is my code, but I keep getting this error:
Warning: Too many FOR loop iterations. Stopping after 9223372036854775806 iterations.

In untitled (line 13)

Index exceeds the number of array elements. Index must not exceed 2.
Error in untitled (line 14)
if (abs(f(n) - L) <= err)
This is my code:
prompt = "input a function: ";
f = input(prompt,"s");
prompt = "input a limit: ";
L = input(prompt);
prompt = "input the error threshold: ";
err = input(prompt);

 for n = 1:inf
     if (abs(f(n) - L) <= err)
       break;
    end
end

 disp(n)

I tried figuring out what the problem is, but I am not really sure, if anyone could help me understand, that would be great.


text:
Q: A proper replacement for the `logname` utility? The logname utility became unusable a while ago for many users, since it relies on something that has been broken intentionally due to security concerns, as discussed here. As I read the discussion, it is unlikely that the functionality is going to come back.
I lived with workarounds for a while, but now I feel that they start to fall on my feet, so I'm in search for a proper long-term solution and I'm surprised to see, that there does not seem to be much.
The solution most commonly linked to is presented here, but it originates from here where also a hint is present, that the proposed solution via the environment variable SUDO_USER is not portable.
Another proposed solution is to create a file containing the username and to write a bash alias or similar to emulate the logname functionality, but I wouldn't call this a proper replacement, at least since it assumes an amount of controllability regarding the environment that might not always be possible, better to say, in the least of cases.
The solution via who from here is interesting, but I could not find any information about if there are relevant reliability or portability limitations.
Apart from those approaches, the air is getting thin fast in this area, so I decided to ask here in hope for some new input regarding the topic and my thoughts so far.

A: TL,DR: you probably want /proc/PID/loginuid, even though its behavior doesn't always match logname. But it doesn't work out of the box on all distributions. Note that my answer assumes Linux, it does not apply to other Unix variants.
I don't think you'll find a fully satisfactory answer because you don't have clear expectations from what logname does. On the one hand, you're currently using logname, which is based on utmp records — records that associate a user with a terminal, and which are updated at the good will of the terminal emulator (many don't). On the other hand, you expect that "the possibility to change the username should be limited to the superuser". This is not the case with utmp records! As explained in the very comment thread you cite, utmp records work most of the time, but they can be faked.
Defining "the username that was used to log into the console" is problematic. It's clear enough in nominal cases, but there are many complicated cases. What happens if a user calls su and attaches to another user's screen session? What happens if a user attaches to another user's X11 or VNC session? How do you trace processes to terminals — what do you do about processes that have no controlling terminal?
Linux actually does have a concept of "login UID". It's visible for each process as /proc/PID/loginuid. This information is tracked by the kernel, but it's up to userland to let the kernel know when a login takes place. This is normally done via pam_loginuid. Under the hood it's done by writing to /proc/self/loginuid. Linux's login UID follows process ancestry, which is not always the right definition but has the benefit of being simple.
Beware that if a process's login UID is 4294967295 then the process may change it. Init starts with the login UID 4294967295 (equal to -1 as a 32-bit value); this normally indicates a process that's not part of any login session. As long as the login process sets the login UID correctly (just before it sets the real UID from root to the user who's logging in), that's fine. But if there's a way to log in without the login UID set then the user may declare any login UID of their choice. So this information is reliable only if all the ways to run a process on the system go through a step of setting the login UID — forget one and the information becomes useless.
Experimentally, on a Debian jessie machine, all my long-running processes whose login UID is -1 are system services. But there are ways to run a process with login UID of -1, for example via incron. I don't know how many other ways there are; incron was the first I tried and it worked. On Ubuntu 16.04 machine, the pam_loginuid entry for lightdm is commented out, I haven't investigated why. Maybe Ubuntu's lightdm and incron should be considered security bugs, but the fact is that today you can't rely on the login UID working out of the box in major distributions.
See also Loginuid, should be allowed to change or not (mutable or not)?, which is about a kernel option to prevent root from changing the login UID. But beware that it's only effective after the login UID has been set to a proper value; if a user gets to run a process with the login UID still set to -1 then they can set it to whatever they want. It would in fact be safer to make init switch to a different value, say -2, and have pam_loginuid override that value; then -1 would never happen and -2 would indicate "unknown".


text:
Q: NSXML Parser parsing node by node I have an XML like this,
<?xml version="1.0" standalone="yes"?>
<user id="1" name=""><class id="1" name=""><subjects id="1" name=""><books id="1" name="">
<chapters id="1" name="">
<pages id="0" name="" url="http://172.16.33.25/casa/admin/uploads/mathematic/Page001.html"/>
<pages id="1" name="" url="http://172.16.33.25/casa/admin/uploads/mathematic/Page002.html"/>
</chapters></books></subjects></class></user>

Here i need the url values in array, i'm using NSXML Parser. How can i parse this.?

A: Try
-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
    if([elementName isEqualToString:@"pages"])
    {
        NSString *urlValue=[attributeDict valueForKey:@"url"];
        [arr addObject:urlValue];
    }
}


text:
Q: how to transform a nested mongodb table into spark dataframe i have a nested mongodb talbe and its document structure like this:
{
    "_id" : "35228334dbd1090f6117c5a0011b56b0",
    "brasidas" : [
        {
            "key" : "buy",
            "value" : 859193
        }
    ],
    "crawl_time" : NumberLong(1526296211997),
    "date" : "2018-05-11",
    "id" : "44874f4c8c677087bcd5f829b2843e66",
    "initNumber" : 0,
    "repurchase" : 0,
    "source_url" : "http://query.sse.com.cn/commonQuery.do?jsonCallBack=jQuery11120015170331124618408_1526262411932&isPagination=true&sqlId=COMMON_SSE_SCSJ_CJGK_ZQZYSHG_JYSLMX_L&beginDate&endDate&securityCode&pageHelp.pageNo=1&pageHelp.beginPage=1&pageHelp.cacheSize=1&pageHelp.endPage=1&pageHelp.pageSize=25",
    "stockCode" : "600020",
    "stockName" : "ZYGS",
    "type" : "SSE"
}

i want to transform it into spark dataframe,and extract the title "key"and "value " of "brasidas"  as single column respectively.just like follows:
initNumber  repurchase  key  value   stockName    type    date
    50000      50000    buy  286698    shgf       SSE   2015/3/30

but there is a problem with the form of  title "brasidas",it have three forms:
  [{ "key" : "buy", "value" : 286698 }]

  [{ "value" : 15311500, "key" : "buy_free" }, { "value" : 0, "key" : "buy_limited" }]

  [{ "key" :    ""buy_free" " }, { "key" : "buy_limited" }]

so when i use scala to define a StructType, it's not suitable for every document,i can only take "brasidas" as a single column and failed to divide it by the "key" .this is what i get:
 initNumber   repurchase     brasidas     stockName    type   date
  50000        50000    [{ "key" : "buy", "value" : 286698 }]   shgf    SSE 2015/3/30

This is the code for getting mongodb document:
val readpledge =ReadConfig(Map("uri"-> (mongouri_beehive+".pledge")))
val pledge = getMongoDB.readCollection(sc, readpledge,"initNumber","repurchase","brasidas","stockName","type","date")
                   .selectExpr("cast(initNumber as int) initNumber", "cast(repurchase as int) repurchase","brasidas","stockName","type","date")

A: If you try to df.printSchema() you'll probably be able to observe that brasidas got ArrayType.  Most likely (array of map).
So, I'd suggest to implement some sort of UDF function that get Array as parameter and transform it in a way you need.
def arrayProcess(arr: Seq[AnyRef]): Seq[AnyRef] = ???


text:
Q: Negative Voltage Shift from Blocking Cap for Amplifier Recently I have been working with the Analog Devices AD797 op-amp in LTspice, and have been getting poor performance from the amplifier when using a low-amplitude signal. This is my circuit in LTspice:
The voltage source I am using is a sine wave at 40KHz with amplitude of .125 V, parallel capacitance of 3.4nF and series resistance of 4KΩ. I am trying to mimic the hydrophone that this circuit will eventually be an amplifier for, so these numbers aren't random. Also, I have set the gain of the amplifier so high because this circuit will eventually need to amplify voltages much lower than .125 V. I believe my problem is with the blocking capacitor / highpass filter I use on the output of the voltage source. Vin is consistently lower than the amplitude of the voltage source and V2 looks identical to Vin, except it has been shifted negatively by a few millivolts. The following screenshots are what I see in LTspice when simulating the circuit.

The second image include the output of the amplifier, which reflects this negative shift of the input signal. I am a relative beginner, and my understanding of reactive circuits is shaky. Any help with eliminating / minimizing this negative shift between Vin and V2 would be much appreciated. Thanks
Here is a link to the AD797 datasheet. http://www.analog.com/media/en/technical-documentation/data-sheets/AD797.pdf

A: The voltage offset of this amplifier is 80uV max (for the A grade part), if you have a gain of 500 I would expect 40000uV or 40mV. The B grade part is 60uV max for a total of 30000uV or 30mV which would be right on par for your simulation. If this is not acceptable, then maybe another part might be better. Or typically with gains like this an amp like this can serve as a pre-amp with a follower stage to pick up the rest of the gain.

Another thing that might be useful is an inverting configuration with trim adjustment.

Source: https://wiki.analog.com/university/courses/electronics/text/chapter-3

A: I see 2 major problems, somewhat related. First of all 501 x .125 = 62.625. That is equal to 62.625 volts (sine) at the output. Not going to happen with +/-9 volts for power. You MUST divide gain by 10 to get a more rational 6.2625 volts at the output.
The clipped waveform is due to a saturated output. It is being over driven by your current gain setting.
Second thing I do not see is bypass capacitors for the power supply. You need to have 100nF smd capacitors at the IC power pins to the ground plane, along with 47uF capacitors within 1" or 25mm of the IC. It will ring and oscillate without proper bypass capacitors. They are cheap so cost is not an issue.
Correct any DC offsets after you have fixed these other problems.

A: You could have potentially up to 3uA of bias current.  For simplicity, we'll assume 1uA.
The negative input, with its 1k to ground, will see a 1mV offset inspired by the bias current.  The positive input, with 100K to ground, will see 100mV, for a difference of 99mV.
With your gain of 500, that 99mV offset on the input becomes 49.5V on the output.
Try replacing R1 with a 1K and it should be better.  This will give you a high-pass corner of about 160Hz unless you increase C1.


text:
Q: Launch Screen image only showing on iPhone 4s, 5s, and 6s For some reason, as the title states, the launch screen image only seems to be working on the iPhone 4s, 5s, 6s (But not the 6s Plus) for some reason.  Otherwise the screen would just be blank. At first, I thought that it could've been a resolution problem.  As far as I know, the 5s and 5 both have the same resolution, so I really can't pinpoint a problem.
Here are some things that I've tried

*

*Adding all device resolutions to the launch image asset folder (Including iPads)

*Left the "Launch Screen File" field blank

*Double checked the resolutions of all the pictures being used for the launch screens

In the launch image assets folder I'm using the current resolutions, all with their proper resolutions.

*

*iPhone Portrait iOS 8,9

*

*Retina HD 5.5

*Retina HD 4.7

*iPhone Portrait iOS 7-9

*

*Retina 4

*2x

All portraits of course, the application will not be using the landscape view.
Thanks for any help, ask me if you need anymore information.


text:
Q: Run sed as a one-off ssh command I would like to substitute a string with another in a file on a server of mine. I've tried doing this:
ssh $REMOTE_HOST sed 's|export ${KEY}=${VAL}|export ${KEY}=${NEW_VAL}|' "$ENV_FILE"

And a bunch of variants with different types of quoting, but I just can't make it work. The sed command works when I manually substitute the variables with the values and run it on the server.
The command above gives the following error:
bash: {env_file_redacted}: Permission denied
bash: line 0: export: `=': not a valid identifier
bash: line 0: export: `=': not a valid identifier
sed: -e expression #1, char 1: unterminated `s' command

Like I said, the command works when I ran it on the server so it's not a permissions problem.
What is the problem here?

A: If all variables (apart from $REMOTE_HOST) are available in the environment on your remote server you can try:
ssh $REMOTE_HOST 'echo sed "s|export ${KEY}=${VAL}|export ${KEY}=${NEW_VAL}|" "$ENV_FILE"'

And if everything looks fine, remove echo.
Update
With local variables:
ssh $REMOTE_HOST "echo sed \"s|export ${KEY}=${VAL}|export ${KEY}=${NEW_VAL}|\" \"$ENV_FILE\""

And if everything looks fine, remove echo.


text:
Q: Assembly How to translate opcode DIV to C Code Hey I know I been asking alot of questions.. but not much resources on this on google so hopefully this will help future people who attempt to do similar projects, I always google solutions as well, but I never search passed first page.
I looked at that Intel manual Alex posted, seems pretty alien to me
http://www.intel.com/content/www/us/en/architecture-and-technology/64-ia-32-architectures-software-developer-vol-2a-2b-instruction-set-a-z-manual.html
So I thought I knew how a simple DIV opcode worked. Since it's just divide after all.
I had no difficulty adding ADD,SUB, of course IMUL had problems you guys helped me out on that one. Seems DIV falls into the same category as IMUL in terms of difficulty.
Well without using the manual just doing self debugging tests with OllyDbg.
I found out answer of division is always stored in EAX. Figured out the remainder is also kept who knew, stored in EDX.
Which from studying this algorithm is extremely important who knew, someone would use the remainder of a random number division to generate a switch from 0-10 pretty clever.. But still my question.
It's already strange I never thought of hexadecimal numbers of being divided would have remainders decimal points don't even belong in them.
DIV ECX

would be like
regs.d.eax /= regs.d.ecx;
regs.d.edx = regs.d.eax % regs.d.ecx;

I was thinking maybe getting remainder first.. will simply things.
regs.d.edx = regs.d.eax % regs.d.ecx;
regs.d.eax /= regs.d.ecx;

Okay I hardly work with mathematical programming so it's a bit confusing for me. I'm more of a guy that would store the result in a string then split it by decimal point and that's how I would get the remainder yeah I know it's slow and it's taking the easy path out.. and I myself am against using string operations in a mathematical code.
Ok well.. looking at that C code I put there.. probably have to store both EAX and ECX before division happens in temporary variables.. or do the remainder code first.. then division code second. I don't know.
Well I'll see maybe you guys can provide me with a better answer perhaps it cannot be done in one line but maybe I made a few mistakes.. I can't really test the things I do right now due to many other things I have to fix before I can even compile the software.

A: The manuals are no easy reading, true, but they have all the answers to your questions (well, most of them, there are occasional omissions and mistakes in the docs).
One thing you're missing in your guessed algorithm is that DIV typically divides 2N bits by N bits, that is, when you do DIV ECX you divide a 64-bit unsigned value contained in EDX:EAX by a 32-bit unsigned value in ECX. The quotient is then stored in EAX and the remainder in EDX.
You should also remember about the possibility of a division overflow (in this case EDX>=ECX is the condition for it) and flags that the instruction modifies in the EFLAGS register.

A: I think a reasonably fair translation would be:
  int16_t a=42,b=7;
  int16_t div = a/7;
  int16_t remainder = a - (div*b);

In practice, this may, or may not be equivalent to remainder = a % b (I'd need to look up the standard specs). It gets more interesting if you consider carefully what happens with negative numbers.
All that said, the decimal point never comes into play, so I don't see why you mention it in the post.

perhaps it cannot be done in one line [...]

I highly suspect the compiler will pick up on the reuse of subexpressions, and automatically use the remainder from (E)DX when applicable. (this is rather trivial optimization for a compiler)