text:
Q: CakePHP - Web page try to load all the js files in the webroot I have a big project using CakePHP. I have a web page and I only want it to load the js files in a subfolder of webroot but it seems like loading all the js files in the webroot
I want files in this directory
/webroot/js/signaturepad

and in my code I wrote:
echo $this->Html->script(array(
                '/js/signaturepad/TopazSignature',
                '/js/signaturepad/SigWebTablet'
            ), array('inline' => false));

So it supposes to read these two js files only while in the page source I can see tons of js files in the webroot been loaded. And my js functions are not working at all.

A:
I want files in this directory
/webroot/js/signaturepad

start paths without slash '/' and 'js' folder name, like:
echo $this->Html->script(array(
         'subfolder/your_js_file_name_here',
         'subfolder/your_js_file_name_here.min'
     ), array('inline' => false));

This generate path like example.com/js/subfolder/your_js_file_name_here.js
If you want use other folder inside webroot folder, for example: 'frontend' then start path with slash '/'.
echo $this->Html->script(array(
         '/frontend/your_js_file_name_here',
         '/forntend/your_js_file_name_here.min'
     ), array('inline' => false));

This generate path like example.com/frontend/your_js_file_name_here.js


text:
Q: Order a column by pair of values I have 2 simple columns:
one column is simply an ID column and the other column is some sort of boolean type column.
ID   V
0    1
1    0
2    0
3    1
4    1
5    0

I want to order the rows by pair of values (0,1) of column V
(while still keeping the ID as minimal as possible):
ID   V
1    0
0    1
2    0
3    1
5    0
4    1

How do I do that ?

A: Seems you want get rows for 0 and 1 in turn:
select id, v
from tab
order by
   row_number()
   over (partition by v
         order by id)
  ,v

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to add serializer for fields only and not for the class itself I have a base JPA entity called AbstractEntity with property code and I also have a ton of other JPA entities (ProductEntity, CategoryEntity, UserEntity, etc), each of which extend from AbstractEntity.
Now some of the entities have references to other entities, for example CategoryEntity has an attribute called parentCategory or ProductEntity has a Collection of categories (categories).
Now I want with jackson to serialize a ProductEntity, but whenever an attribute is of type AbstractEntity I want it to print only the code and nothing else.
My solution was to add a custom Serializer for AbstractEntity, but as you may guess the ProductEntity is also an AbstractEntity so whenever I say objectMapper.writeValueAsString(product) I get just the code. And instead what I want is:
{
 code: 'abc',
 category : 'categoryA',
 price : '12 $',
 active : true
}

Is there a way to tell jackson to use my custom serializer only for the fields and not for the object itself?
BTW I can't really use annotations as I don't have access to the code and like I said the classes are really a lot.


text:
Q: Does Fubini's Theorem hold when an unbounded linear operator is used in the integrand? According to Fubini's Theorem we may (under "normal" circumstances) assert that:
$$
\int_{X \times Y} f(x, y) \mathrm{d}(x, y)=\int_{X}\left(\int_{Y} f(x, y) \mathrm{d} y\right) \mathrm{d} x=\int_{Y}\left(\int_{X} f(x, y) \mathrm{d} x\right) \mathrm{d} y
$$
which, when applied in the context of function multiplication within the integrand presumably implies:
$$
\int_Y \left ( \int_X f(x) \mathrm{d}x \right) g(y) \mathrm{d}y = \int_X \left( \int_Y g(y) \mathrm{d}y \right) f(x) \mathrm{d}x
$$
Problem: Apparently (see below) this is not the case if we insert an unbounded linear operator into the integrand:
$$
\int_Y \left ( \int_X U(f(x)) \mathrm{d}x \right) g(y) \mathrm{d}y = \int_X \left( \int_Y g(y) \mathrm{d}y \right) U(f(x)) \mathrm{d}x \color{red}{\text{ (fails to hold)}}
$$
where the condition for linear operator $L$ to be unbounded is that there does not exist some $M \ge 0$ such that for all vectors $x$
$$
\|Lx\| \leq M \|x\|,\,
$$
But is this true? And if so, why?
Context. This question arose as the result of another question from the area of quantum mechanics (which I offered 2 bounties on, but never felt I got a satisfactory answer). A couple of the answers offered asserted the result above, but I didn't feel were given any sort of justification, so I'm trying to understand with a new post.


text:
Q: How to make HTML text field readonly, but also scrollable? I've got an HTML text field that I have made READONLY. Thing is though, that say the field is only a 100 pixels wide. And I have a sentence for example that doesn't get displayed in that 100 pixels. Since it's READONLY it't not  scrollable.
In other words. How can I still have the field not editable. But also make is so that longer strings that does not fit in the field, be viewable?
thanks!

A: There's some JavaScript you can use. Unless you're using a framework, it'd look pretty ugly though, because it isn't trivial.
The JavaScript keypress event triggers when a key is pressed, but it doesn't trigger for the cursor keys (for some reason). This is quite handy, because if you use JavaScript to prevent the default action, you're sorted.
So ideally, this would be what you need:
// get all readonly inputs
var readOnlyInputs = document.querySelectorAll('input[readonly]');

// Function to fire when they're clicked
// We would use the focus handler but there is no focus event for readonly objects
function readOnlyClickHandler () {
    // make it not readonly
    this.removeAttribute('readonly');
}
// Function to run when they're blurred (no longer have a cursor
function readOnlyBlurHandler () {
    // make it readonly again
    this.setAttribute('readonly');
}
function readOnlyKeypressHandler (event) {
    // The user has just pressed a key, but we don't want the text to change
    // so we prevent the default action
    event.preventDefault();
}
// Now put it all together by attaching the functions to the events...

// We have to wrap the whole thing in a onload function.
// This is the simplest way of doing this...
document.addEventListener('load', function () {
    // First loop through the objects
    for (var i = 0; i < readOnlyInputs.length; i++) {
        // add a class so that CSS can style it as readonly
        readOnlyInputs[i].classList.add('readonly');
        // Add the functions to the events
        readOnlyInputs[i].addEventListener('click', readOnlyClickHandler);
        readOnlyInputs[i].addEventListener('blur', readOnlyBlurHandler);
        readOnlyInputs[i].addEventListener('keypress', readOnlyKeypressHandler);
    }
});

Just copy and paste this and it should work fine in Firefox or Chrome. The code is standards compliant, but Internet Explorer isn't. So this won't work in IE (except maybe versions 9 and 10... not sure about that). Also, the classList.add bit won't work in all but a few of the most recent versions of browsers. So we have to change these bits. First we'll adapt the readOnlyKeypressHandler function, because event.preventDefault() doesn't work for every browser.
function readOnlyKeypressHandler (event) {
    if (event && event.preventDefault) {
        // This only runs in browsers where event.preventDefault exists,
        // so it won't throw an error
        event.preventDefault();
    }
    // Prevents the default in all other browsers
    return false;
}

Now to change the classList bit.
    // add a class so that CSS can style it as readonly
    if (readOnlyInputs[i].classList) {
        readOnlyInputs[i].classList.add('readonly');
    } else {
        readOnlyInputs[i].className += ' readonly';
    }

Annoyingly, addEventListener isn't supported in IE either, so you need to make a function to handle this separately (add it above the for loop)
function addEvent(element, eventName, fn) {
    if (element.addEventListener) {
        element.addEventListener(eventName, fn, false);
    } else if (element.attachEvent) {
        // IE requires onclick instead of click, onfocus instead of focus, etc.
        element.attachEvent('on' + eventName, fn);
    } else {
        // Much older browsers
        element['on' + eventName] = fn;
    }
}

Then change the adding events bit:
    addEvent(readOnlyInputs[i], 'click', readOnlyClickHandler);
    addEvent(readOnlyInputs[i], 'blur', readOnlyBlurHandler);
    addEvent(readOnlyInputs[i], 'keypress', readOnlyKeypressHandler);

And give the document load function a name instead of calling it in addEventListener:
function docLoadHandler () {
    ...
}

And call it at the end
addEvent(document, 'load', docLoadHandler);

And once you've done that, it should work in all browsers.
Now just use CSS to style the readonly class to take away the outline in browsers which show one:
.readonly:focus {
    outline: none;
    cursor: default;
}

A: Do not make the textarea readonly. This is what I did:
<textarea id="mytextarea" wrap="off" style="overflow:auto"></textarea>

,then in your JavaScript, using jQuery:
$('#mytextarea').keypress(function(event){
    event.preventDefault();
});

A: if http://jsfiddle.net/msmailbox/jBGne/ this is what you needed then you can try this with div.

sfbskdgksfbgkjsfngndflgndfgldfngldfgldfg

with css
#alo
{
    width:100px;
    overflow-x:scroll;
    overflow-y:hidden;
}

A: The CSS property overflow sets the scroll behaviour, and for example overflow: auto only display scrollbars when the content extends beyond the area. With overflow: scroll you get the scrollbars every time.

A: Use a Textarea instead of a input textfield. U cant add scroll to a textfield
<textarea cols="50" rows="5" ></textarea>

A: Define height for your container div of text and use overflow:auto something like below css code.
.yoruclass{
width:100px;
height:100px;/* stop text to go beyond the define height */
overflow:hidden;/* making text div scrollable */
}


text:
Q: Displaying contact details like android's native app I am making an app that displays a list of people in a listview. When tapped, the app should transition to another screen displaying the contact details of that person loaded from a Person object i have retrieved from the DB. My question is how to display these details. In iOS, there was a ABUnknownPersonViewController that would mimic the native iOS addressbook entry to let me display the contact details in a clean and easy way. Is there anything similar for android that would let me use the People app's view or api to basically create and display a record exactly as android displays in its own People app?

A: your exact answer is contained here:
Open Contacts
The method described in the above link opens native contacts app and lets the user pick a contact. Then onActivityResult() comes into picture, here you can process the contact as per your requirement.
If you want to customize the look and feel you need to check here
You can retrieve the list and customize the UI.
If you just want to display a single contact's details. you can use this code. (contactId is the contactId of the contact that user picked)
Intent contactIntent = new Intent(Intent.ACTION_VIEW);
Uri uri = Uri.withAppendedPath(
ContactsContract.Contacts.CONTENT_URI,
                    String.valueOf(contactId));
contactIntent.setData(uri);
startActivity(contactIntent);

Hope this helps.

A: No.  You can look through the AOSP and see if the contacts app was released as open source, and if so use it.  But remember that the contact app on all phones isn't the same, Samsung for example uses several different apps of their own.  And some people download their own contact apps.  So its impossible to have the native feel for everyone, unless you launch the contact app via an intent.


text:
Q: Classes whose members pointing to each other There is a Square which points to four Faces. Also each Face points to two Squares. Since one of the classes is defined first, compiler will complain. So how can I solve this problem? The aim of using pointers is that if I make a change in a face I will not need to make any changes for squares. In that case, this will be done automatically.
class Square
{
    Face* faces[4];
};

class Face
{
    Square* squares[2]
};

A: Just forward declare one class;
class Face;
class Square{
 Face* faces[4];
};

class Face{
 Square* squares[2]
};

Note:  by forward declaration, you can only use pointer/reference (as you are using now). But you can not use like Face faces[4]; in Square. Because it is a declaration, not definition. To use an object, compiler must know the definition of the object.


text:
Q: bootstrapping ZF2 with Behat I have an issue bootstapping zf2 and hooking it into behat
I have the following snippets that fails
/** @BeforeSuite */

public static function setup(SuiteEvent $event) {
    chdir(dirname(dirname(dirname(dirname(__DIR__)))));
    require 'init_autoloader.php';
    $app = Zend\Mvc\Application::init(require 'config/application.config.php');
}

This has been a way of bootstrapping a zf2 app and I really can't figure out what to do.
Will really be grateful for any help

A: To init() the application means to init the MVC procedure. You don't want to run any controllers, you just want to bootstrap the Service Manager.
This class by Marco Pivetta will come in handy:
<?php
/*
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * This software consists of voluntary contributions made by many individuals
 * and is licensed under the MIT license.
 */

namespace CommonTest;

use Zend\ServiceManager\ServiceManager;
use Zend\Mvc\Service\ServiceManagerConfig;

/**
 * Utility used to retrieve a freshly bootstrapped application's service manager
 *
 * @author  Marco Pivetta <ocramius@gmail.com>
 */
class ServiceManagerFactory
{
    /**
     * @var array
     */
    protected static $config;

    /**
     * @param array $config
     */
    public static function setConfig(array $config)
    {
        static::$config = $config;
    }

    /**
     * @static
     * @return array
     */
    public static function getConfiguration()
    {
        return static::$config;
    }

    /**
     * Builds a new service manager
     */
    public function getServiceManager()
    {
        $serviceManager = new ServiceManager(new ServiceManagerConfig(
            isset(static::$config['service_manager']) ? static::$config['service_manager'] : []
        ));
        $serviceManager->setService('ApplicationConfig', static::$config);
        $serviceManager->setFactory('ServiceListener', 'Zend\Mvc\Service\ServiceListenerFactory');

        /** @var $moduleManager \Zend\ModuleManager\ModuleManager */
        $moduleManager = $serviceManager->get('ModuleManager');
        $moduleManager->loadModules();

        return $serviceManager;
    }
}

Put this class under your tests' namespace and make sure it is available via the autoloader.
In your setup() method, you need to set the SM config, like this:
public static function setUp() {
    $file = '/path/to/your/application.config.php';
    \CommonTest\ServiceManagerFactory::setConfig($file);
}

Then, if you need the Service Manager, anywhere in your tests just call $sm = \CommonTest\ServiceManagerFactory::getServiceManager() to get it.

A: If you need to use the ServiceManager inside yout Context you might be interested in this extension https://github.com/mvlabs/zf2behat-extension.


text:
Q: JS filter array by array within I have an array as following
  [{
    "id": 68,
    "proffesional_photo": "",
    "top_image": "https://sampleimage.jpg",
    "ratings": "1",
    "price": 690,
    "description": null,
    "type": true,
    "promo": 0,
    "status": true,
    "item": {
      "Item_name": "Dark Chocolate Latte"
    },
    "restaurant_dish_menus": [
      {
        "id": 1,
        "res_dish_id": 1318,
        "menu_id": 4,
        "createdAt": "2018-11-13T04:28:17.000Z",
        "updatedAt": "2018-11-13T04:28:17.000Z"
      },
      {
        "id": 1,
        "res_dish_id": 1318,
        "menu_id": 3,
        "createdAt": "2018-11-13T04:28:17.000Z",
        "updatedAt": "2018-11-13T04:28:17.000Z"
      }
     ]
  },
  {
    "id": 69,
    "proffesional_photo": "",
    "top_image": "https://sampleimage2.jpg",
    "ratings": "1",
    "price": 700,
    "description": null,
    "type": true,
    "promo": 0,
    "status": true,
    "item": {
      "Item_name": "Latte"
    },
    "restaurant_dish_menus": [
      {
        "id": 1,
        "res_dish_id": 1318,
        "menu_id": 3,
        "createdAt": "2018-11-13T04:28:17.000Z",
        "updatedAt": "2018-11-13T04:28:17.000Z"
      }
     ]
  }
  ],

And when the user select a certain menu it needs to be filtered through it,
Each dish objects may have more than one menu_id,
i attempted using array.filter but i am having trouble figuring out how to filter from the Dish array through the sub array within.
the code i attempted (filterBy = 4)
let result = data.filter(function(row) {
  row.restaurant_dish_menus.filter(function(i) {
    return i.menu_id == filterBy;
  });
});

console.log(result) gives me an empty array.
if filterBy is = 4 the expected output is
{
    "id": 68,
    "proffesional_photo": "",
    "top_image": "https://sampleimage.jpg",
    "ratings": "1",
    "price": 690,
    "description": null,
    "type": true,
    "promo": 0,
    "status": true,
    "item": {
      "Item_name": "Dark Chocolate Latte"
    },
    "restaurant_dish_menus": [
      {
        "id": 1,
        "res_dish_id": 1318,
        "menu_id": 4,
        "createdAt": "2018-11-13T04:28:17.000Z",
        "updatedAt": "2018-11-13T04:28:17.000Z"
      },
      {
        "id": 1,
        "res_dish_id": 1318,
        "menu_id": 3,
        "createdAt": "2018-11-13T04:28:17.000Z",
        "updatedAt": "2018-11-13T04:28:17.000Z"
      }
     ]
  }

And if it filterBy is 3 then both objects should be the output

A: how about this
var data =   [{
    "id": 68,
    "proffesional_photo": "",
    "top_image": "https://sampleimage.jpg",
    "ratings": "1",
    "price": 690,
    "description": null,
    "type": true,
    "promo": 0,
    "status": true,
    "item": {
      "Item_name": "Dark Chocolate Latte"
    },
    "restaurant_dish_menus": [
      {
        "id": 1,
        "res_dish_id": 1318,
        "menu_id": 4,
        "createdAt": "2018-11-13T04:28:17.000Z",
        "updatedAt": "2018-11-13T04:28:17.000Z"
      },
      {
        "id": 1,
        "res_dish_id": 1318,
        "menu_id": 3,
        "createdAt": "2018-11-13T04:28:17.000Z",
        "updatedAt": "2018-11-13T04:28:17.000Z"
      }
     ]
  }];

  var result = data.filter(function(m) {
    return m.restaurant_dish_menus.some(function(d) {
      return d.menu_id === 4;
    });
  })

A: .filter expects the function passed to return a boolean. In your case, the function returns nothing (or undefined) which is always falsy.
One option is to use .find in the nested filter, and return a boolean depending on whether the result is undefined.
Here's a snippet.

let data = [{
  "id": 68,
  "proffesional_photo": "",
  "top_image": "https://sampleimage.jpg",
  "ratings": "1",
  "price": 690,
  "description": null,
  "type": true,
  "promo": 0,
  "status": true,
  "item": {
    "Item_name": "Dark Chocolate Latte"
  },
  "restaurant_dish_menus": [{
      "id": 1,
      "res_dish_id": 1318,
      "menu_id": 4,
      "createdAt": "2018-11-13T04:28:17.000Z",
      "updatedAt": "2018-11-13T04:28:17.000Z"
    },
    {
      "id": 1,
      "res_dish_id": 1318,
      "menu_id": 3,
      "createdAt": "2018-11-13T04:28:17.000Z",
      "updatedAt": "2018-11-13T04:28:17.000Z"
    }
  ]
}, {
  "id": 69,
  "proffesional_photo": "",
  "top_image": "https://sampleimage.jpg",
  "ratings": "1",
  "price": 690,
  "description": null,
  "type": true,
  "promo": 0,
  "status": true,
  "item": {
    "Item_name": "Dark Chocolate Latte"
  },
  "restaurant_dish_menus": [{
      "id": 1,
      "res_dish_id": 1318,
      "menu_id": 6,
      "createdAt": "2018-11-13T04:28:17.000Z",
      "updatedAt": "2018-11-13T04:28:17.000Z"
    },
    {
      "id": 1,
      "res_dish_id": 1318,
      "menu_id": 5,
      "createdAt": "2018-11-13T04:28:17.000Z",
      "updatedAt": "2018-11-13T04:28:17.000Z"
    }
  ]
}, ]

let filterBy = 4;

let result = data.filter(function(row) {
  return row.restaurant_dish_menus.find(function(i) {
    return i.menu_id == filterBy;
  }) !== undefined;
});

console.log(result);

A: You can use "filter" as below

var data = [{
    "id": 68,
    "proffesional_photo": "",
    "top_image": "https://sampleimage.jpg",
    "ratings": "1",
    "price": 690,
    "description": null,
    "type": true,
    "promo": 0,
    "status": true,
    "item": {
      "Item_name": "Dark Chocolate Latte"
    },
    "restaurant_dish_menus": [
      {
        "id": 1,
        "res_dish_id": 1318,
        "menu_id": 4,
        "createdAt": "2018-11-13T04:28:17.000Z",
        "updatedAt": "2018-11-13T04:28:17.000Z"
      },
      {
        "id": 1,
        "res_dish_id": 1318,
        "menu_id": 3,
        "createdAt": "2018-11-13T04:28:17.000Z",
        "updatedAt": "2018-11-13T04:28:17.000Z"
      }
     ]
  },
  {
    "id": 69,
    "proffesional_photo": "",
    "top_image": "https://sampleimage2.jpg",
    "ratings": "1",
    "price": 700,
    "description": null,
    "type": true,
    "promo": 0,
    "status": true,
    "item": {
      "Item_name": "Latte"
    },
    "restaurant_dish_menus": [
      {
        "id": 1,
        "res_dish_id": 1318,
        "menu_id": 3,
        "createdAt": "2018-11-13T04:28:17.000Z",
        "updatedAt": "2018-11-13T04:28:17.000Z"
      }
     ]
  }
  ]

function filterBy(f) {
    return data.filter(d => d.restaurant_dish_menus.some(({ menu_id }) => menu_id == f))
}

console.log(filterBy(4))

console.log(filterBy(3))

A: You can also use grep function
var menus=  {
    "id": 68,
    "proffesional_photo": "",
    "top_image": "https://sampleimage.jpg",
    "ratings": "1",
    "price": 690,
    "description": null,
    "type": true,
    "promo": 0,
    "status": true,
    "item": {
      "Item_name": "Dark Chocolate Latte"
    },
    "restaurant_dish_menus": [
      {
        "id": 1,
        "res_dish_id": 1318,
        "menu_id": 4,
        "createdAt": "2018-11-13T04:28:17.000Z",
        "updatedAt": "2018-11-13T04:28:17.000Z"
      },
      {
        "id": 1,
        "res_dish_id": 1318,
        "menu_id": 3,
        "createdAt": "2018-11-13T04:28:17.000Z",
        "updatedAt": "2018-11-13T04:28:17.000Z"
      }
     ]
  };

var found_names = $.grep(menus.restaurant_dish_menus, function(v) {
    return v.menu_id ===4;
});

console.log(found_names);

http://jsfiddle.net/ejPV4/

A: Your question a bit unclear of final goal, but if you want to filter top level objects, i.e. if top level object has to be present if and only if it has dish with menu_id === filterBy, then:
let result = data.filter(row => {
  return row.restaurant_dish_menus.some(({menu_id}) => menu_id === filterBy);
});

Above will only filter your rows if restaurant_dish_menus has items with menu_id === filterBy. But restaurant_dish_menus, of such objects remain unfiltered.
Result:
[{
  "id": 68,
  // skipped
  "item": {
    "Item_name": "Dark Chocolate Latte"
  },
  "restaurant_dish_menus": [
    {
      "id": 1,
      "res_dish_id": 1318,
      "menu_id": 4,
      // skipped
    },
    {
      "id": 1,
      "res_dish_id": 1318,
      "menu_id": 3,
      // skipped
    }
  ]
}]

But if you want to filter top level and filter restaurant_dish_menus also, i.e. modify top level object, then:
let result = data.filter(row => {
  return row.restaurant_dish_menus.some(({menu_id}) => menu_id === filterBy);
}).map(row => {
  return {...row, restaurant_dish_menus: row.restaurant_dish_menus.filter(i => i.menu_id === filterBy)};
});

This will first filter the row objects which has menu_id === filterBy, and then also filter restaurant_dish_menus, to include only once menu_id === filterBy, effectively modifying the row object, i.e. map.
Result:
[{
  "id": 68,
  // skipped
  "item": {
    "Item_name": "Dark Chocolate Latte"
  },
  "restaurant_dish_menus": [
    {
      "id": 1,
      "res_dish_id": 1318,
      "menu_id": 4,
      // skipped
    }
  ]
}]


text:
Q: How can I keep this toolbar and text field above the keyboard? I have a UIView that contains a UITableView and a toolbar with a UITextField
When I tap the text field, the keyboard covers it over.
I want to keep the toolbar above the keyboard, just like in the native Messages app. Is it better to add this toolbar as the last cell in the TableView or animate the toolbar's Y position to move up and down when it's TextField becomes first responder?
Any advice appreciated.

A: The tableView should scroll to display the footer if it is firstResponder, so that might be a good place to tuck the toolbar.
Otherwise if you are manually moving your toolbar you can use notifications to manage the appearance. Here is from the Xcode docs:
Keyboard Notifications
When the system shows or hides the keyboard, it posts several keyboard notifications. These notifications contain information about the keyboard, including its size, which you can use for calculations that involve moving views. Registering for these notifications is the only way to get some types of information about the keyboard. The system delivers the following notifications for keyboard-related events:
UIKeyboardWillShowNotification
UIKeyboardDidShowNotification
UIKeyboardWillHideNotification
UIKeyboardDidHideNotification
The tableView footer is probably less code.
Good luck,
Damien

A: For make toolbar above your keyboard here is the most easy way..


text:
Q: Composition of logarithm functions I am a little confused about composition of logarithms, I am given $f(x)=5^{2+5x}$ and $g(x)=\log_5 x$ and I am supposed to find $f(g(x))$. Here is what I have done so far,
$$5^{2+5(\log_5 x)}$$
$$5^{2+5\log_x 5}$$
I am stuck on this step because I don't know how to cancel the log in the exponent. Since it's $5\log_5 x$ and not $5^{\log_5 x}$. Could anyone explain how I would simplify this problem?

A: If you recall, there are several important properties of logarithm. One of them, which your class should have mentioned, is that $p \log_b{x} = \log_b(x^p)$ for any choices of $x > 0$, real number $p$, and base $b$. This should allow you to simplify your problem in the following way:
$$5^{2 + 5 \log_5{x}} = 5^{2 + \log_5{x^5}}$$
Now, remember that whenever we have $x^{a + b}$, we can break it up into $x^{a+b} = (x^a)(x^b)$.


text:
Q: Validate input and repeat input if it was invalid Using Visual Studio, its an exercise, I need to add other students in, which isn't a problem. My main question is: I want the code to jump back to the input question if the value is above 100 or below 0 included, but I don't know the code that checks(validates) the user-input, any help would be very helpful and I would be incredibly grateful.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Student_Marks_For_Statement
{
    class Program
    {
        static void Main(string[] args)
        {
            char moreData;
            double total = 0;
            double secondTotal = 0;
            for (double student1 = 0; student1 == 0; student1++)
            {
                Console.Write("Enter mark for student 1: ");
                student1 = Convert.ToDouble(Console.ReadLine());
                total += student1;

                Console.WriteLine("Any more data? Enter 'y' or 'n' then return");
                moreData = Convert.ToChar(Console.ReadLine());

                if (moreData == 'n')
                {
                    ;
                }
                if (moreData == 'y')
                {
                    Console.Write("Enter Value :");
                    secondTotal = Convert.ToDouble(Console.ReadLine());
                    total += secondTotal;
                }

                for (double student2 = 0; student2 == 0; student2++)
                {
                    Console.Write("Enter mark for student 2: ");
                    student2 = Convert.ToDouble(Console.ReadLine());
                    total += student2;
                    student2++;

                    Console.WriteLine("Any more data? Enter 'y' or 'n' then return");
                    moreData = Convert.ToChar(Console.ReadLine());

                    if (moreData == 'n')
                    {
                        ;
                    }
                    if (moreData == 'y')
                    {
                        Console.Write("Enter Value :");
                        secondTotal = Convert.ToDouble(Console.ReadLine());
                        total += secondTotal;
                        student2++;

                    } Console.WriteLine("Total marks = : {0}", total);

                }
            }
        }
    }
}

A: You can try something like this. I just followed your code and organized them within methods.
public class Program
{
    public static char DecisionSign = ' ';
    public static double TotalMarkOfFirstStudent = 0;
    public static double TotalMarkOfSecondStudent = 0;
    public static double inputValue = 0;

    public static void Main(string[] args)
    {

        Console.WriteLine("Enter mark for student 1: ");
        while (DecisionSign != 'n')
        {
            CalculateFirstStudentResult();
        }

        DecisionSign=' ';
        Console.WriteLine("Enter mark for student 2: ");
        while (DecisionSign != 'n')
        {
            CalculateSecondStudentResult();
        }

        Console.WriteLine("Student 1 got total : " + TotalMarkOfFirstStudent);
        Console.WriteLine("Student 2 got total : " + TotalMarkOfSecondStudent);

        Console.ReadKey();
    }

    public static char CalculateFirstStudentResult()
    {
        DecisionSign = ' ';
        Console.WriteLine("Enter Value : ");
        inputValue = Convert.ToDouble(Console.ReadLine());
        if (inputValue >= 0 && inputValue <= 100)
        {
            TotalMarkOfFirstStudent += inputValue;
            Console.WriteLine("Any more data? Enter 'y' or 'n' then return");
            DecisionSign = Convert.ToChar(Console.ReadLine());
        }
        else
        {
            CalculateFirstStudentResult();
        }
        return DecisionSign;
    }

    public static char CalculateSecondStudentResult()
    {
        DecisionSign = ' ';
        Console.WriteLine("Enter Value : ");
        inputValue = Convert.ToDouble(Console.ReadLine());
        if (inputValue >= 0 && inputValue <= 100)
        {
            TotalMarkOfSecondStudent += inputValue;
            Console.WriteLine("Any more data? Enter 'y' or 'n' then return");
            DecisionSign = Convert.ToChar(Console.ReadLine());
        }
        else
        {
            CalculateSecondStudentResult();
        }
        return DecisionSign;
    }
}

A: Here's some psuedo-code that will continue to accept user input until they enter "n", and validate that the user input is between 0 and 100 (inclusive):
moredata = "y"

while moredata = "y"
   Prompt for score
   Convert score to double

   if score <= 0 or score >= 100
      Tell user score must be betwen 0 and 100
      moredata = "y"
   else
      Add score to total
   end if

   ask user if they have more data

   show total score
 end while

The while loop will continue to prompt the user for information until they enter "n". If the score is less than 0 or greater than 100 it will tell the user the score is out of bounds and they'll be prompted to input data again.  Otherwise, it will add the score to the total, show the running total and then ask if the user has more data.
I would recommend using double.TryParse on the conversion to avoid errors (for example, what if the user enters a string?).
Also, your for loops will only execute one time, which makes them non-useful in this scenario.


text:
Q: How to import pytaxonomy==1.1? Hi I tried to install pytaxonomy==1.1.
pip install pytaxonomy==1.1

The installation was successful
when I tried to import,
import pytaxonomy

It says ... '

ModuleNotFoundError                       Traceback (most recent call last)
Input In [18], in <cell line: 1>()
----> 1 import pytaxonomy
ModuleNotFoundError: No module named 'pytaxonomy'

How to overcome this?

A: Make sure you're installing pytaxonamy with same python version you're running the script with.
It's better to use environments in python, to prevent such errors.
venv


text:
Q: Duplicate all network traffic to an GCE instance Is it possible to duplicate all the traffic to and from the different GCE instances and send it to one instance?
So that instance can listen to all the network traffic

A: Use a proxy instance with NAT enabled and configure IPTables in that instance accordingly to your needs. Currently this is the only way for an instance to have a look at another one's traffic, as GCE virtual network doesn't implement a shared medium a promiscuous interface can hear to. See Configuring a NAT gateway at GCE public documentation for more details.


text:
Q: High school equations and inequalities question
I've arrived at the condition that $-2<k-m<2$, but am unsure how to proceed. Any help will be appreciated!

A: Rearrange your inequalities to get $-2+m < k < 2 +m$. What can you conclude about the possible values of $m$ given that $4 < k <8$.

A: $$x^2+kx=mx-1\iff x^2+(k-m)x+1=0\implies \Delta=(k-m)^2-4$$
Now, notice that for no real roots, we must have $\Delta\lt 0$
Note: $\Delta$ denotes the discriminant.

Now, we know that $(k-m)^2\lt 4$ and $4\lt k\lt 8$.
Then, equivalently, by the reverse triangle inequality, $||k|-|m||\leq |k-m|\lt 4$, or equivalently, $$-4\lt |k|-|m|\lt +4\implies\begin{cases} |m|\lt |k|+4\lt 8+4=12\\ |m|\gt |k|-4\gt 4-4=0 \end{cases}$$


text:
Q: Refactor Python script into an isolatable method Is it possible to refactor this script such that it exists as a completely independent method?
import json
import requests
from collections import defaultdict
from pprint import pprint

def hasNumbers(inputString):
    return any(char.isdigit() for char in inputString)

# open up the output of 'data-processing.py'
with open('job-numbers-by-location.txt') as data_file:

    # print the output to a file
    with open('phase_ii_output.txt', 'w') as output_file_:
        for line in data_file:
            identifier, name, coords, number_of_jobs = line.split("|")
            coords = coords[1:-1]
            lat, lng = coords.split(",")
            # print("lat: " + lat, "lng: " + lng)
            response = requests.get("http://api.geonames.org/countrySubdivisionJSON?lat="+lat+"&lng="+lng+"&username=s.matthew.english").json()

            codes = response.get('codes', [])
            for code in codes:
                if code.get('type') == 'ISO3166-2':
                    country_code = '{}-{}'.format(response.get('countryCode', 'UNKNOWN'), code.get('code', 'UNKNOWN'))
                    if not hasNumbers( country_code ):
                        # print("code: " + country_code + ", jobs: " + number_of_jobs)
                        output_file_.write("code: " + country_code + ", jobs: " + number_of_jobs)
    output_file_.close()

I've been trying to make it so that I can include it as a component of a much larger process.

A: There are a couple of things you can do. You might want to break each step of the script into separate methods each with their own exception handling, and logging to indicate where the job has failed. Also, I have not mentioned the return parameter here. You can return a True/False to suggest whether the processing has passed/failed.
You can then import the process_file method in other places, and pass it the 2 files that it needs to process.
import json
import requests
from collections import defaultdict
from pprint import pprint

def hasNumbers(inputString):
    return any(char.isdigit() for char in inputString)

def handle_get(url, params)
    try:
        response = requests.get(url, params=urlencode(params))
    except requests.exceptions.RequestException as e:  # This is the correct syntax
        print e
        # sys.exit(1)
        response = None

    return response

def process_file(data_file_path, output_file_path)
    # open up the output of 'data-processing.py'
    with open(data_file_path) as data_file:

        # print the output to a file
        with open(output_file_path, 'w') as output_file_:
            for line in data_file:
                identifier, name, coords, number_of_jobs = line.split("|")
                coords = coords[1:-1]
                lat, lng = coords.split(",")
                params = OrderedDict([('lat', lat), ('lng', lng), ('username', 's.matthew.english')])
                url = "http://api.geonames.org/countrySubdivisionJSON"
                response = handle_get(url, params)
                if response:
                    json_response = response.json()
                else:
                    print('Something bad happened')
                    sys.exit(1)

                codes = response.get('codes', [])
                for code in codes:
                    if code.get('type') == 'ISO3166-2':
                        country_code = '{}-{}'.format(response.get('countryCode', 'UNKNOWN'), code.get('code', 'UNKNOWN'))
                        if not hasNumbers( country_code ):
                            # print("code: " + country_code + ", jobs: " + number_of_jobs)
                            output_file_.write("code: " + country_code + ", jobs: " + number_of_jobs)


text:
Q: Rails cannot run remove_index I accidentally added indexes as so:
class AddRandomIndices < ActiveRecord::Migration[5.0]
  def change
    add_index :charges, :pp_charge_id
    add_index :new_refunds, :pp_refund_id
    add_index :inventory_items, :product_id, unique: true
    add_index :prestock_items, :product_id, unique: true
  end
end

Here's the result in schema:
create_table "charges", force: :cascade do |t|
  ...
  t.index ["pp_charge_id"], name: "index_charges_on_pp_charge_id", using: :btree
end

create_table "new_refunds", force: :cascade do |t|
  ...
  t.index ["pp_refund_id"], name: "index_new_refunds_on_pp_refund_id", using: :btree
end

create_table "prestock_items", force: :cascade do |t|
  ...
  t.index ["product_id"], name: "index_prestock_items_on_product_id", unique: true, using: :btree
end

create_table "inventory_items", force: :cascade do |t|
  ...
  t.index ["product_id"], name: "index_inventory_items_on_product_id", unique: true, using: :btree
end

Here's remove file I tried to run:
class RemoveIndex < ActiveRecord::Migration[5.0]
  def change
    remove_index :charges, :pp_charge_id
    remove_index :new_refunds, :pp_refund_id
    remove_index :inventory_items, :product_id
    remove_index :prestock_items, :product_id
  end
end

Here's the error
> rake db:migrate
== 20220515045335 RemoveIndex: migrating ======================================
-- remove_index(:charges, :pp_charge_id)
rake aborted!
StandardError: An error has occurred, this and all later migrations canceled:

No indexes found on charges with the options provided.

In this other SO answer: How to remove index in rails, there are lots of suggested options... none of them worked.
Here I try to run a file where the column and name are explicitly specified
class RemoveIndex < ActiveRecord::Migration[5.0]
  def change
    remove_index :charges, column: :pp_charge_id, name: :index_charges_on_pp_charge_id
    remove_index :new_refunds, column: :pp_refund_id, name: :index_new_refunds_on_pp_refund_id
    remove_index :inventory_items, column: :product_id, name: :index_prestock_items_on_product_id
    remove_index :prestock_items, column: :product_id, name: :index_inventory_items_on_product_id
  end
end

Same error:
> rake db:migrate
== 20220515045335 RemoveIndex: migrating ======================================
-- remove_index(:charges, {:column=>:pp_charge_id, :name=>:index_charges_on_pp_charge_id})
rake aborted!
StandardError: An error has occurred, this and all later migrations canceled:

No indexes found on charges with the options provided.

And then I tried to run the file with just names, no columns
class RemoveIndex < ActiveRecord::Migration[5.0]
  def change
    remove_index :charges, name: :index_charges_on_pp_charge_id
    remove_index :new_refunds, name: :index_new_refunds_on_pp_refund_id
    remove_index :inventory_items, name: :index_prestock_items_on_product_id
    remove_index :prestock_items, name: :index_inventory_items_on_product_id
  end
end

Different error:
> rake db:migrate
== 20220515045335 RemoveIndex: migrating ======================================
-- remove_index(:charges, {:name=>:index_charges_on_pp_charge_id})
rake aborted!
StandardError: An error has occurred, this and all later migrations canceled:

PG::UndefinedObject: ERROR:  index "index_charges_on_pp_charge_id" does not exist
: DROP INDEX  "index_charges_on_pp_charge_id"

I've tried passing strings as well, and will spare the continued copy/pasting...
What is happening??!

A: The syntax you are using is correct to remove the indexes, not sure what would have happened but it is good to check if the indexes actually exist in the database or not using a SQL query, you can find it here: How to list indexes created for table in postgres
The schema synchronizes with the database automatically but in your case, you have a migration that is throwing an error that is why it is not being updated so you can try deleting the migrations which are throwing errors and then running rails db:migrate, if the indexes don't exist in the database they will be removed from the schema too.
Usually, if you have added some migration by mistake and not pushed it yet to version control or have not shared it with anyone else then you can run rails db:rollback if it is the last migration or run rails db:migrate:status to get the version number of migration you want to rollback and then run rails db:migrate:down VERSION=20220515045335 (this will run only if the migration status is up) which will rollback the migration and then you can safely delete the file.


text:
Q: iOS -touch events in a UITableViewController I have a UITableViewController with a number of rows. When selecting a row, it expands/collapses, by increasing the height of the row.
Now my question is, how do I only make the 'select' action apply to a certain rect? For example, if each row in my tableview is 70, and then for each sub-element in the row I expand the total row hieght by 60 * number of subelements - I only want height 0 - 70 to be 'selectable', the sub-members of the row should not be. How do you do this?
Thanks

A: It can be done using touch events, but as you are already using UITableView it seems easier (and more iPhonish) to use what tables provides you:
reloadRowsAtIndexPaths:withRowAnimation:
insertRowsAtIndexPaths:withRowAnimation:
deleteRowsAtIndexPaths:withRowAnimation:
etc.

Search a sample called "Table View Animations and Gestures" in the documentation. Just load the reference for UITableView and you'll see it on the bottom left corner sidebar.
To make non-selectable rows just change its cell selectionStyle to UITableViewCellSelectionStyleNone.


text:
Q: JSON link from google developer tools not working in Python (or in browser) I am trying to extract the data in the table at https://www.ecoregistry.io/emit-certifications/ra/10
Using the google developer tools>network tab, I am able to get the json link where the data for this table is stored: https://api-front.ecoregistry.io/api/project/10/emitcertifications
I am able to manually copy this json data and extract the information using this code I've written:
import json
import pandas as pd
data = '''PASTE JSON DATA HERE'''
info = json.loads(data)
columns = ['# Certificate', 'Carbon offsets destination', 'Final user', 'Taxpayer subject','Date','Tons delivered']
dat = list()
for x in info['emitcertifications']:
dat.append([x['consecutive'],x['reasonUsingCarbonOffsets'],x['userEnd'],x['passiveSubject'],x['date'],x['quantity']])
df = pd.DataFrame(dat,columns=columns)
df.to_csv('Data.csv')

I want to automate it such that I can extract the data from the json link: https://api-front.ecoregistry.io/api/project/10/emitcertifications directly instead of manually pasting json data in:
data = '''PASTE JSON DATA HERE'''

The link is not working in python or even in browser directly:
import requests
import json
url = ('https://api-front.ecoregistry.io/api/project/10/emitcertifications')
response = requests.get(url)
print(json.dumps(info, indent=4))

The error output I get is:
{'status': 0, 'codeMessages': [{'codeMessage': 'ERROR_401', 'param': 'invalid', 'message': 'No autorizado'}]}
When I download the data from the developer tools then this dictionary has 'status':1 and after that all the data is there.
Edit: I tried adding request headers to the url but it still did not work:
import requests
import json
url = ('https://api-front.ecoregistry.io/api/project/10/emitcertifications')
hdrs = {"accept": "application/json","accept-language": "en-IN,en;q=0.9,hi-IN;q=0.8,hi;q=0.7,en-GB;q=0.6,en-US;q=0.5","authorization": "Bearer null", "content-type": "application/json","if-none-match": "W/\"1326f-t9xxnBEIbEANJdito3ai64aPjqA\"", "lng": "en", "platform": "ecoregistry","sec-ch-ua": "\" Not A;Brand\";v=\"99\", \"Chromium\";v=\"100\", \"Google Chrome\";v=\"100\"", "sec-ch-ua-mobile": "?0", "sec-ch-ua-platform": "\"Windows\"", "sec-fetch-dest": "empty","sec-fetch-mode": "cors", "sec-fetch-site": "same-site" }
response = requests.get(url, headers = hdrs)
print(response)
info = response.json()
print(json.dumps(info, indent=4))

print(response) give output as '<Response [304]>' while info = response.json() gives traceback error 'Expecting value: line 1 column 1 (char 0)'
Can someone please point me in the right direction?
Thanks in advance!

A: Posting comment as an answer:
The headers required for that api in order to retrieve data
is platform: ecoregistry.
import requests as req
import json
req = req.get('https://api-front.ecoregistry.io/api/project/10/emitcertifications', headers={'platform': 'ecoregistry'})
data = json.loads(data)
print(data.keys())
# dict_keys(['status', 'projectSerialYear', 'yearValidation', 'project', 'emitcertifications'])
print(data['emitcertifications'][0].keys())
# dict_keys(['id', 'auth', 'operation', 'typeRemoval', 'consecutive', 'serialInit', 'serialEnd', 'serial', 'passiveSubject', 'passiveSubjectNit', 'isPublicEndUser', 'isAccept', 'isCanceled', 'isCancelProccess', 'isUpdated', 'isKg', 'reasonUsingCarbonOffsetsId', 'reasonUsingCarbonOffsets', 'quantity', 'date', 'nitEnd', 'userEnd'])


text:
Q: Acquiring keysym from keycode in python I am currently working on a python project to enable the detection and interpretation of key events as characters/names across platforms. I have been working with python-xlib to provide support on X11 but I have recently run into difficulty in the process of converting the keycodes of key events to their appropriate keysyms.
A snapshot of my code is here: https://gist.github.com/SavinaRoja/7306962
The trouble arises specifically in the use of the PyKeyboardEvent class, where I am capable of retrieving the event data for key events, but not interpreting their keycodes to keysyms. Xlib.display's keycode_to_keysym function does not work appropriately.
In reading about X11, and confirmed by the xev utility source code, it seems that the appropriate Xlib function to utilize is XLookupString. Were I coding in C (a language I am only beginning to learn) using this function would be simple, however I am currently stumped with regards to employing the function from python. I have considered two options: I may attempt to utilize and extend python-xlib's protocol to call XLookupString, or I might try to use ctypes to call XLookupString. My code includes an attempt at the latter (not functional, but shows where I am at currently):
from ctypes import *
XLookupString = cdll.LoadLibrary('libX11.so').XLookupString

char_buffer = create_string_buffer(257)
keysym = c_int()  # the important value
count = XLookupString(byref(event),  # TypeError, not a ctypes instance
                      byref(char_buffer),
                      len(char_buffer),
                      keysym,
                      None)

I suspect that what I am missing is the ability to convert the event class from python-xlib to an appropriate C struct for XLookupString, or the ability to interpret the data received from the X server (which python-xlib parses into the event instance) into such a struct. Am I correct in this suspicion? If so, what tools do I need to learn?
At this point I am probably missing a lot of basic information and skill regarding the interface between python and C, so I devoting time to fixing this gap in my general education. If anyone has insight in to my problem specifically or how I should conduct my research on relevant topics, I would love to hear it.

A: If you look at the source code to python-xlib, it's actually not using xlib at all; it's a pure-Python implementation of the Xlib socket protocols. You event object is a wrapper around one of the types defined in the rq module (or a subclass defined in event or elsewhere), which is an object that knows how to struct.pack itself.
The simplest thing to do is probably to pack the value into a byte string, then cast it to a ctypes.Structure.
But note that the xlib that ctypes will be entirely independent of your python-xlib; in particular, you'll be using a different X connection (which means you may have to auth separately, repeat any setup, etc.). It would probably be a lot cleaner to do everything one way or the other, not mix and match.

Downloading the libX11 source, it looks like XLookupString is not a protocol function, but rather a wrapper (in the file KeyBind.c) that runs at least partially on the client side. Assuming USE_OWN_COMPOSE is not defined, it effectively calls XTranslateKey to get the keysym result, then calls XTranslateKeySym to fill the string buffer. Those functions are themselves mostly local functions. But they ultimately call XKeyInitialize, which calls at least one server-side function, XGetKeyboardMapping—which python-xlib does support.
That implies that using a separate Xlib instance through ctypes is not necessarily going to get the right keyboard mapping, unless you can ensure that the two connections have identical setup.
That also implies that you may have to port all of that local C code in order to get the functionality of XLookupString.


text:
Q: Understand the reason for calculating the MSE Im following an introduction course into R-machine Learning. Im doing the following:

*

*Load the faithful dataset (standard in R)

*Creating a model that predicts waiting time -> eruptions of the first 136 items of the dataframe.
mymodel = glm(data=faithful[1:136,], waiting ~ eruptions)

*Calculate the mean standard error on the second half of the data.
mean((faithful$waiting - predict(mymodel, faithful[137:272, ])), ^2)
The way I see it you take the mean of all waitingtimes - the predicted values (using the glm model) and do exponent^2.
I do not understand however why exactly this is done? Could anybody explain this to me in plain English?

A: Using mean squared error can be seen as a special case of the maximum likelihood parameter estimation. One wants to choose the model such that the likelihood of the observation is maximal for the selected model. The likelihood is:
$$
{\cal L} = p(z_1|y_1) \cdot \ldots \cdot p(z_N|y_N)
$$
where p(z|y) is the probability of the observed value z when the model predicts value y.
So 'fitting' a model is done by maximizing L or equivalently minimizing
$$
    - \log({\cal L})
$$
If you assume a Normal distribution centered at the y_i for the p's and you assume that all p's have the same width parameter sigma (set to one for convenience), you'll get:
$$
    - \log ({\cal L}) = constant - \log ( e^{-\frac{1}{2} \cdot (y_1-z_1)^2} ) - \ldots - \log ( e^{-\frac{1}{2} \cdot (y_N-z_N)^2} )
$$
Setting the width parameter of all Gaussians to the same value means that all your measurements have the same uncertainty (i.e. the same precision).
where the log and exp cancel each other and you'll end up with:
$$
    - \log ({\cal L}) = constant + \frac{1}{2} \cdot (y_1-z_1)^2 + ... + \frac{1}{2} \cdot (y_N-z_N)^2
$$
For the purposes of minimization, you can drop the constant and also the factors 0.5 and you'll end up with the mean (or summed) squared error.


text:
Q: Record and playback sound in AAC format I'm trying to record a sound using iPhone microphone and playing it on speakers (or headphones if they are plugged in).
Currently I use this settings and audio playback works... though it doesn't playback on the bottom (loud) speakers of the phone, instead it plays on the ear speaker near the front camera:
NSString *tempDir = NSTemporaryDirectory();
NSString *soundFilePath = [tempDir stringByAppendingPathComponent:@"sound.caf"];
NSURL *soundFileURL = [NSURL fileURLWithPath:soundFilePath];

NSDictionary *recordSettings = @{AVEncoderAudioQualityKey:  [NSNumber numberWithInt:AVAudioQualityMin],
                                 AVEncoderBitRateKey:       @16,
                                 AVNumberOfChannelsKey:     @2,
                                 AVSampleRateKey:           @44100.0};

NSError *error = nil;
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
[audioSession setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];
_audioRecorder = [[AVAudioRecorder alloc] initWithURL:soundFileURL settings:recordSettings error:&error];

I tried something like this: (changed file extension and added AVFormatIDKey to settings)
NSString *soundFilePath = [tempDir stringByAppendingPathComponent:@"sound.aac"];
NSURL *soundFileURL = [NSURL fileURLWithPath:soundFilePath];

// Set settings for audio recording
NSDictionary *recordSettings = @{AVFormatIDKey:             [NSNumber numberWithInt:kAudioFormatMPEG4AAC],
                                 AVEncoderAudioQualityKey:  [NSNumber numberWithInt:AVAudioQualityMin],
                                 AVEncoderBitRateKey:       @16,
                                 AVNumberOfChannelsKey:     @2,
                                 AVSampleRateKey:           @44100.0};

But then I get:
Error: The operation couldn't be completed. (OSStatus error 2003334207.)

If I change the file name extension to .caf it doesn't report errors but it doesn't playback anything.
This is the playback code:
NSError *error;
_audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:_audioRecorder.url error:&error];
_audioPlayer.delegate = self;
if (error)  NSLog(@"Error: %@", [error localizedDescription]);
else        [_audioPlayer play];

In short, how do I record and playback aac file using iPhone speaker (or headphones if plugged in)?
------------------ EDIT -----------------
Made it save to .aac file by using this settings:
NSDictionary *recordSettings = @{AVFormatIDKey: @(kAudioFormatMPEG4AAC),
        AVEncoderAudioQualityKey: @(AVAudioQualityMin),
        AVSampleRateKey: @16000.0,
        AVNumberOfChannelsKey: @1};

Now I just need to playback on the speakers so the user can actually hear what is recorded


text:
Q: Add an event observer after customer enters his shipping adress in checkout I want to add an event when a customer enters his shipping adress in checkout
I tried to create a module but it goes back to the cart
here is as follows
Observer.php:
class Mantel_Shippingredirect_Model_Observer
{
       public function controller_action_predispatch_checkout_onepage_saveBilling($observer)
        {
            $address = $observer->getCustomerAddress();
            if($address->getCountry() =='US'){
                              $observer->getRequest()->setParam('return_url','http://www.google.com/');
                             }

        }
}
?>

config.xml:
<?xml version="1.0"?>
<config>
    <modules>
        <Mantel_Shippingredirect>
            <version>0.1.0</version>    <!-- Version number of your module -->
        </Mantel_Shippingredirect>
    </modules>
    <frontend>
        <routers>
            <shippingredirect>
                <use>standard</use>
                <args>
                    <module>Mantel_Shippingredirect</module>
                    <frontName>shippingredirect</frontName>
                </args>
            </shippingredirect>
        </routers>
        </frontend>
        <global>
            <models>
              <mantelshippingredirect>
                <class>Mantel_Shippingredirect_Model</class>
              </mantelshippingredirect>
            </models>
            <events>
                <controller_action_predispatch_checkout_onepage_saveBilling>
                    <observers>
                        <shippingredirect>
                            <type>singleton</type>
                            <class>mantelshippingredirect/observer</class>
                            <method>controller_action_predispatch_checkout_onepage_saveBilling</method>
                        </shippingredirect>
                    </observers>
                </controller_action_predispatch_checkout_onepage_saveBilling>
            </events>
        </global>
</config>

and my Mantel_Shippingredirect.xml
<?xml version="1.0"?>
 <config>
  <modules>
    <Mantel_Shippingredirect>
    <active>true</active>
    <codePool>local</codePool>
    </Mantel_Shippingredirect>
  </modules>
 </config>

What is wrong? Please help me!!

A: Your observer is never be called because of the model declaration.
You need to replace:
<class>shippingredirect/observer</class>

With:
<class>mantelshippingredirect/observer</class>

Another problem with the class declaration, you need to replace:
<class>Shippingredirect_Model</class>

With:
<class>Mantel_Shippingredirect_Model</class>


text:
Q: Running one thing after another in jquery I have this code snippet from something i am developing
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script type="text/javascript">
    $(function(){
        $("#Submit").click(function(){
        var Count = document.frmOne.count.value
        for (i=1;i<=Count;i++)
        {
            $.ajax({
                url:"process.php",
                type:"get",
                data:$("form").serialize(),
                success:function(response){
                    var obj = jQuery.parseJSON( response );
                    var success = obj.success;
                    var actionsNumber = obj.number;
                    $("#result").html('There have been  '+actionsNumber+'  loops completed');

                }
            })
        }
                $.ajax({
                     url:"done.php",
                     type:"get",
                      })
        })
    })
</script>

and basically I need to have the whole for loop complete then have it run "done.php". But currently it seems to run done.php after about 2 loops in the for loop.
So lets see if i can explain this better. I have this whole js script run after someone clicks a submit button.  I have it run process.php for a user inputted amount of times, then i want it to run done.php after it finishes the for loop.  But it is currently running process.php about twice, then done.php, then continues with process.php.
How can i fix this?
Now i have tried this and it is not working still, any help please
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script type="text/javascript">
    $(function(){
        $("#Submit").click(function(){
        var Count = document.frmOne.count.value
        var b = 0
        for (i=1;i<=Count;i++)
        {
            $.ajax({
                url:"process.php",
                type:"get",
                data:$("form").serialize(),
                success:function(response){
                    var obj = jQuery.parseJSON( response );
                    var success = obj.success;
                    var actionsNumber = obj.number;
                    $("#result").html('There have been  '+actionsNumber+'  loops completed');
                    b++;

                }

            })
    if(Count == b)
            {
                $.ajax({
                    url:"done.php",
                    type:"get",

                      })
                      var b = 0
            }
        }

        })
    })
</script>

A: Short answer - you need to set the option async: false in the ajax requests inside your for loop.
Longer answer - Your success function which prints out the number of loops only executes when the requests make it back to you, not when they're sent.  Your loop actually finishes before the request to done.php is sent, but you can't control the order that your requests come back in.  You can verify this by moving this line:
$("#result").html('There have been  '+actionsNumber+'  loops completed');
to right before the ajax request in the loop.

A: Keep another count, increase that count in the first ajax call's success callback (inside the loop). Then call the second ajax call to done.php only when that count reaches Count.
$.ajax is asynchronous and so in your code it won't wait for all the calls inside the loop to finish before going to the done.php call. That's how AJAX works.

A: In your the looped ajax request success callback add the logic to check if it's the last ajax request callback if yes. Call the done.php call.
for(var i;i<=Count;i++)
    $.ajax({
    ...
    ,success:function(data){
       if(Count == i)
       {
          $.ajax({
          ..
          url:"done.php",
          ..
          });
       }

    },
    ..
    });
}


text:
Q: Injecting AuthenticationStateProvider into an API Controller in a Blazor Server app In a Blazor Server app, I have an api controller class that handles file uploads. It works fine (uploads succeed) until I try to inject a custom data service that relies on AuthenticationStateProvider.
I can declare a dummy service, register it with:
    builder.Services.AddScoped<MyService>();

and inject it into the api controller instead of the real data service no problem.
The custom data service's constructor looks like:
public CustomDataService(IConfiguration Configuration, AuthenticationStateProvider Asp)
{
    configuration = Configuration;
    asp = Asp;

    // Get user name and AspNetUserId for use in CRUD functions.
    var authState = asp.GetAuthenticationStateAsync().Result;
    .
    .
    .
}

This works fine when injected into Razor pages, but when injected into the api controller, the row in the data service constructor that calls:
    asp.GetAuthenticationStateAsync().Result;

is the last line to execute before a 500 error goes to the client.
I thought that maybe I needed to register the custom data service with a different resolver, but it's not the custom data service that fails to resolve. It's AuthenticationStateProvider that fails to resolve.
How can I get a valid resolution of AuthenticationStateProvider in this situation?

A: I found a workaround/solution.
I changed my services to use HttpContext instead of AuthenticationStateProvider as a way to get at the current UserName and AspNetUserId and this method appears compatible with both Blazor components and API Controllers.
New service class constructor:
    public CustomDataService(IConfiguration Configuration, IHttpContextAccessor HttpContextAccessor)
    {
        configuration = Configuration;

        _httpContextAccessor = HttpContextAccessor;

        userName = HttpContextAccessor.HttpContext.User.Identity.Name;
        aspNetUserId = HttpContextAccessor.HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value;
        .
        .
        .
    }

A: I also encountered this issue.
Here is my workaround in order to get the AuthenticationState value in a kind of "regular" fashion. You will need to provide the HttpContext object to the alternate method. This is a modified implementation of the default RevalidatingIdentityAuthenticationStateProvider with generic type :
public class RevalidatingIdentityAuthenticationStateProvider<TUser>
    : RevalidatingServerAuthenticationStateProvider where TUser : class
{
    private readonly IServiceScopeFactory _scopeFactory;
    private readonly IdentityOptions _options;

    public RevalidatingIdentityAuthenticationStateProvider(
        ILoggerFactory loggerFactory,
        IServiceScopeFactory scopeFactory,
        IOptions<IdentityOptions> optionsAccessor)
        : base(loggerFactory)
    {
        _scopeFactory = scopeFactory;
        _options = optionsAccessor.Value;
    }

    protected override TimeSpan RevalidationInterval => TimeSpan.FromMinutes(30);

    private ClaimsPrincipal GetAnonymousClaim()
    {
        var anonymous = new ClaimsIdentity();
        return new ClaimsPrincipal(anonymous);
    }

    /// <summary>
    /// A HttpContext compatible method to call GetAuthenticationStateAsync
    /// </summary>
    /// <param name="context"></param>
    /// <returns></returns>
    public async Task<AuthenticationState> GetAuthenticationStateAsync(HttpContext context)
    {
        //If anonymous
        if (context.User == null || context.User.Identity == null || context.User.Identity.IsAuthenticated == false)
        {
            return new AuthenticationState(GetAnonymousClaim());
        }

        var currentAuthState = new AuthenticationState(context.User);

        var cancellationToken = new CancellationToken();
        if (await ValidateAuthenticationStateAsync(currentAuthState, cancellationToken))
        {
            //If the current authstate is validated
            return currentAuthState;
        }

        //If any other case (invalid)
        return new AuthenticationState(GetAnonymousClaim());
    }

    protected override async Task<bool> ValidateAuthenticationStateAsync(
        AuthenticationState authenticationState, CancellationToken cancellationToken)
    {
        // Get the user manager from a new scope to ensure it fetches fresh data
        var scope = _scopeFactory.CreateScope();
        try
        {
            var userManager = scope.ServiceProvider.GetRequiredService<UserManager<TUser>>();
            return await ValidateSecurityStampAsync(userManager, authenticationState.User);
        }
        finally
        {
            if (scope is IAsyncDisposable asyncDisposable)
            {
                await asyncDisposable.DisposeAsync();
            }
            else
            {
                scope.Dispose();
            }
        }
    }

    private async Task<bool> ValidateSecurityStampAsync(UserManager<TUser> userManager, ClaimsPrincipal principal)
    {
        var user = await userManager.GetUserAsync(principal);
        if (user == null)
        {
            return false;
        }
        else if (!userManager.SupportsUserSecurityStamp)
        {
            return true;
        }
        else
        {
            var principalStamp = principal.FindFirstValue(_options.ClaimsIdentity.SecurityStampClaimType);
            var userStamp = await userManager.GetSecurityStampAsync(user);
            return principalStamp == userStamp;
        }
    }
}

Then in your controller you will just have to call:
var authState = await _authStateProvider.GetAuthenticationStateAsync(HttpContext);

Of course get your own AuthenticationStateProvider implementation through DI.
This can also be enhanced by managing your own logic through the GetAuthenticationStateAsync, as this method is overridable. The only downside, is that you would be have to manage yourself when you are in a regular (expected) Blazor logic and when you are in a controller and having to retrieve the HttpContext from somewhere else.
Of course there is the HttpContextAccessor option, but better to call your own implementation with the parameter, only when needed.


text:
Q: Link list URL fields do not display when using FieldRenderingControl I'm creating a custom New Form for a Link list. Depending on the view depends which columns are displayed.
 for(int i = 0; i < spView.ViewFields.Count; i++)
                {
                    string fieldName = spView.ViewFields[i];
                    if (fieldName.Contains("LinkTitle"))
                        fieldName = "Title";

                    SPField field = spList.Fields.GetFieldByInternalName(fieldName);

                    if (field == null || field.FieldRenderingControl == null || field.Hidden)
                        continue;
                    Control cntrl = GetSharePointControls(field, spList, itemId);
                    if(cntrl == null) continue;
                   //Add control to webpart.
               }

Now to create the control I use the following code.
 internal static Control GetSharePointControls(SPField field, SPList list, int itemId)
    {
        // check if the field is a buildIn field, or can be rendered by a SharePoint Control
        if (field == null || field.FieldRenderingControl == null || field.Hidden) return null;

        Control ctrl = null;
        SPControlMode mode = SPControlMode.Invalid;

        if (itemId > 0)
            mode = SPControlMode.Edit;
        else
            mode = SPControlMode.New;

        var controlContext = SPContext.GetContext(System.Web.HttpContext.Current, itemId, list.ID,
                                                  SPContext.Current.Web);

        SPContext.Current.FormContext.SetFormMode(mode, true);
        controlContext.FormContext.SetFormMode(mode, true);

        try
        {
                BaseFieldControl webControl = field.FieldRenderingControl;
                webControl.ListId = list.ID;
                webControl.ControlMode = mode;
                webControl.ItemId = itemId;
                webControl.FieldName = field.Title;
                webControl.ID = GetControlID(field);

                webControl.RenderContext = controlContext;
                webControl.ItemContext = controlContext;

                ctrl = webControl;

            return ctrl;
        }

Now if I add a URL to a generic list, then this code works out the field is a URL field and displays the control correctly on the page. However, when using a Link list, the URL field type is a calculated column, which doesn't end up rendering on the page. I also found it strange that webControl.Visible = false; and if you change it in code to true, it still remains false.
I have also tried converting directly to a ComputedField instead of BaseFieldControl, but I end up with the same result. Has anyone else encountered this, or can see a fix for me? I might have to add extra logic for link lists, so that the field name URL is converted to a URLField.

A: I've solved my own question. (I seem to do that a lot on here).
The problem was that the URL field read in from my view had the internal name of UrlwMenu, where I actually wanted the internal name URL. Therefore I wrote a line of code that if field read in was UrlwMenu, then replace it with the Url field instead.
Also the line webControl.FieldName = field.Title should be
webControl.FieldName = field.InternalName

I found that when using Title if a column was renamed differently to the internal name some controls threw error messages of Cast Exceptions.


text:
Q: Laravel Vapor file upload fails Following the Laravel Vapor documentation for file uploads (https://docs.vapor.build/1.0/resources/storage.html#file-uploads), I'm encountering the following error when I try to upload the file from localhost to S3:
POST http://localhost:8000/vapor/signed-storage-url 500 (Internal Server Error)

The laravel log states the following:
Unable to issue signed URL. Missing environment variables: AWS_BUCKET, AWS_DEFAULT_REGION, AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY at Http\\Controllers\\SignedStorageUrlController.php:107

All of those environment variables are defined in the .env file.
Any ideas on how to overcome this issue?

A: Laravel Vapor uses the $_ENV array to read the environment variables. Mine was empty:
dd($_ENV) = []

After some research, I found out that php.ini has to be set to allow/enable PHP to set the $_ENV variables from -env. My local php-fpm Docker development setup had this disabled by default. I just had to update the variables_order = "EGPCS" to allow this to happen and then Vapor works correctly.
 && sed -E -i -e "s/variables_order.*/variables_order = \"EGPCS\"/g" "$PHP_INI_DIR/php.ini"

I'm using Docker, but I assume if you enable or amend this in a local php.ini file you can get this working also.

A: Set AWS_BUCKET, AWS_DEFAULT_REGION, AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY inside secrets area of Vapor dashboard or cli.

A: You need to update your env.production or whatever environment you are using
vapor env:pull production // or staging etc

Add those aws values in there then
vapor env:push production

Then deploy to your environment and your environment variables will be used.
Your .env is only local

A: To use the S3 storage with vapor locally, you'll need to set the AWS environment variables into your .env.
These variables:
AWS_BUCKET, AWS_DEFAULT_REGION, AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY.
When running in the vapor, these variables are injected into your environment during execution time.


text:
Q: Django - How to make a model that when an instance of this model is created, that data is saved to a page that is unique to a user I'm making a website where you can post jobs to an 'explore page', and I was then wondering how I would go about making it so that when a job is posted to that 'explore page', that job will also be posted to a page where the person who posted the job can manage all of the jobs they have posted i.e. edit, delete. I can post jobs to the explore page but I need to find a way for the job to save to the 'employers' page
views.py
from django.shortcuts import render, redirect
from django.contrib.auth.decorators import login_required
from base.forms import JobForm

@login_required(login_url='login')
def manage_jobs(request):
    if request.user.is_employee:
        return redirect('home')
    else:
        form = JobForm(request.POST)
        if form.is_valid():
            form.save()
        context = {"form":form}
        return render(request, 'employer/manage-jobs.html', context)

urls.py
from django.urls import path
from . import views

urlpatterns = [
    path('', views.manage_jobs, name='manage-jobs'),
]

models.py
class Job(models.Model):
    company = models.CharField(max_length=40, null=True, verbose_name="Company/Employer")
    description = models.TextField(null=True)
    role = models.CharField(max_length=25)
    area_of_filming = models.CharField(max_length=50, verbose_name="Area Of Filming", default="")
    contact_email = models.EmailField(verbose_name='Contact Email', max_length=60, default='')
    created = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.company

class Account(AbstractBaseUser):
    email = models.EmailField(verbose_name='email', max_length=60, unique=True)
    name = models.CharField(max_length=45, unique=False)
    date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True)
    last_login = models.DateTimeField(verbose_name='last login', auto_now=True)
    is_admin = models.BooleanField(default=False)
    is_active = models.BooleanField(default=True)
    is_staff = models.BooleanField(default=False)
    is_superuser = models.BooleanField(default=False)
    is_employee = models.BooleanField(default=True, verbose_name='Are you using FilmLink as an employee?')

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['name', 'is_employee']

    objects = MyAccountManager()

    class Meta:
        permissions = [
            ("post_jobs", "Can post jobs"),
        ]

    def __str__(self):
        return self.name

    def has_perm(self, perm, obj=None):
        return True

    def has_perms(self, perm):
        return True

    def has_module_perms(self, app_label):
        return True

    @property
    def is_staff(self):
        return self.is_admin

manage-jobs.html

<button id="myBtn">Post A Job</button>

        &times
        <form action="" method="POST">
          {% csrf_token %}

Employer Name

{{form.company}}

Role (e.g. Actor, Director)

{{form.role}}

Area Of Production/Filming

{{form.area_of_filming}}

Contact Email

{{form.contact_email}}

Description Of Job

{{form.description}}

          <button type="submit" id="post-job">Publish Job</button>
        </form>

manage-jobs.js
var modal = document.getElementById("myModal");
var btn = document.getElementById("myBtn");
var span = document.getElementsByClassName("close")[0];
btn.onclick = function() {
  modal.style.display = "block";
}

span.onclick = function() {
  modal.style.display = "none";
}

window.onclick = function(event) {
  if (event.target == modal) {
    modal.style.display = "none";
  }
}

I hope I've given you enough information + code to answer my question. Sorry about the confusing wording of the title too, I struggled to put that sentence together.

A: The easiest way is to use ListView from django.views.generic.list.ListView
You may override get_queryset to get desired behaviour:
def get_queryset(self):
    qs = super().get_queryset()
    qs = qs.filter(user=self.request.user)
    return qs


text:
Q: How can I convert div that contains Dojox Gauge into image In my application I'm using Dojox Gauge. I need to convert that gauge into image. Dojo gauge is in div. I have tried so many ways. One way is convert html2canvas but than gauge is not visible after converting that div into canvas.
How to convert that component into image with JavaScript?


text:
Q: set width and height of text view dynamically How can I set the width and height of a textview dynamically
I have already tried
displaytext.setLayoutParams(new LinearLayout.LayoutParams(rlwidth-(rlwidth*5/100),rlheight-(rlheight*90/100)));

for which I have received this error
Java.lang.ClassCastException: android.widget.LinearLayout$LayoutParams cannot be cast to android.widget.RelativeLayout$LayoutParams

A: Try this-
displaytext.setLayoutParams(new RelativeLayout.LayoutParams(rlwidth-(rlwidth*5/100),rlheight-(rlheight*90/100)));

As per error logs, your TextView parent looks like RelativeLayout

A: It seems the "displaytext" for which you are dynamically setting the height nd width is of type relativelayout and you trying to cast into linearlayout.

        txtview = (TextView)findViewById(R.id.txtview);
        txtview.setTextColor(Color.parseColor("#53565a"));
        ViewGroup.MarginLayoutParams layoutParams_txtview =(ViewGroup.MarginLayoutParams) .getLayoutParams();
        layoutParams_txtview.topMargin = 8*y/100;
        txtview.setLayoutParams(layoutParams_txtview);
        txtview.getLayoutParams().height = 4*y/100;
        txtview.getLayoutParams().width = 30 * x / 100;
        txtview.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);
        txtview.setTypeface(typeface_regular);

U can use the code and modify according to ur requirements.

A: Thanks for the support, I got the answer for this. Its actually easier to set dimensions for a text view. This is the code I used.
displaytext.setWidth(rlwidth);
   displaytext.setHeight(rlheight*16/100);
   displaytext.setTextSize(rlheight*6/100);

Now its working perfectly.


text:
Q: Independent sampling from trajectories? I am having trouble understanding independent sampling from a stochastic process. The scenario I am interested in is a Markov chain, where we generate trajectories via random sampling.
Suppose we have a Markov chain, where the variables in the chain are determined by some function $f$, i.e. $X_{0}$ is a random variable and $X_{t+1} = f(X_{t}, W_{t})$, where the $W_{t}$ are independent and identically distributed random variables.
Now suppose we realize a trajectory of a specific length from the stochastic process, $\xi = \lbrace x_{0}, x_{1}, \ldots, x_{N} \rbrace$, $N \in \mathbb{N}$, and we specifically want to look at data pairs, i.e. $(x_{t}, x_{t+1})$, for instance to characterize the function $f$.
I have come across descriptions of sampling methods used where a sample $$\mathcal{S} = \lbrace (x_{0}, x_{1}), (x_{1}, x_{2}), \ldots, (x_{N-1}, x_{N}) \rbrace$$ is created using the trajectory $\xi$, i.e. the trajectory is simply "chopped up" into pairs. However, I think this sampling method may not be i.i.d., since $x_{1}$ depends on $x_{0}$, $x_{2}$ depends on $x_{1}$, and so on. I have not found a great discussion of this anywhere, but have seen some reference to "trajectory sampling" in some contexts that seems to suggest that since the increments of the process are independent, then the sample pairs from the trajectory may also be independent?
Could someone please explain whether the sample above is i.i.d., and if not, why?


text:
Q: Script to count files matching a pattern in subdirectories I wrote the following script for finding the number of pdf and tex files from the current directory, including the subdirectories and hidden files. The following code is able to find the number of pdf files upto 2 levels of subdirectories below, but after that it tells that there are no sub directories....
#!/bin/bash

touch t.txt

k=`find -type d |wc -l`
k1=`expr $k - 1`

echo $k1

message1="*.pdf *.tex"
count=`ls -al $message1|wc -l`
find -type d > t.txt

i=2

while [ $i -le $k ]
do
    kd=`head -$i t.txt|tail -1`
    echo $kd
    touch $kd/t.txt
    cp t.txt $kd/t.txt
    i=`expr $i + 1`
done

i=2
while [ $i -le $k ]
do
    nd=`head -$i t.txt|tail -1`
    set -x
    echo $nd
    set +x
    cd $nd
    j=`ls -al $message1|wc -l`
    count=`expr $count + $j`
    i=`expr $i + 1`
done
#set +x

echo $count

A: find works fine to me:
$ find . -name '*.pdf' -o -name '*.tex' | wc -l
75
$ find . -name '*.pdf' | wc -l
16
$ find . -name '*.tex' | wc -l
59
$ echo $((16+59))
75

Edit:
To handle special case: newline in filename
$ find . \( -name '*.pdf' -o -name '*.tex' \) -printf x | wc -c

A: You can do this in pure bash:
shopt -s nullglob dotglob globstar
set -- **/*.pdf **/*.tex
echo "$#"

set sets the positional parameters of the current shell to the result of the glob. $# then retrieves the number of these parameters set.
If you do use the positional parameters (unlike in the script in the inquirer's case),  then you can do the same using an array:
shopt -s nullglob dotglob globstar
files=(**/*.pdf **/*.tex)
echo "${#files[@]}"

A: I would recommend (if available) using locate instead of find. You would be querying a database and results would be instant and there is practically no load on the system. Though the database only gets updated when your system runs updatedb so if you wanted up to the second information you would have to make sure that you ran it first and it would put a load on the system but, it depends on how you intend to use your search.
You could use whatever regex meets your needs.
system1:/unix.stackexchange # locate *.tex *.pdf | grep unix.stack.*
   /unix.stackexchange/access_me/1/file.pdf
   /unix.stackexchange/access_me/1/file.tex


text:
Q: WinSCP C# first use I installed WinSCP on my PC and want to get a connection to another server through a C# Console Application.
 using WinSCP;
namespace WINSCP_SFTP
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                Console.WriteLine("test");
                SessionOptions sessionOptions = new SessionOptions
                {
                   Protocol = Protocol.Sftp,
                   HostName = "hostname",
                   UserName = "user",
                   Password = "password"
                 };

                 using (Session session = new Session())
                 {
                    session.ExecutablePath = @"C:\Program Files\WinSCP";
                    session.Open(sessionOptions);

                    Console.WriteLine(session.Opened);
                 }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            Console.ReadLine();
        }
    }
}

But if I run the .exe, the application crashs even before the first console.writeline appears.. Any ideas what I'm doing wrong?
Update:
An alert pops up which says: WINSCP_SFTP has stopped working.. then in the cmd line a text appears: Unhandled Exception.. I tried to make a try..catch around my whole code but it also doesn't catch the error
Error that occurs(Picture from web, not a screenshot of my application):

A: Try something more like this (this comes from a windows web service).
winscp.exe must be in the root directory of the application.
EDIT: see winscp.net/eng/docs/library_install "WinSCP .NET assembly interacts with WinSCP winscp.exe. By default it looks for the winscp.exe in the same folder, where the assembly is stored. For that reason, you should extract the package into the same folder, where you have WinSCP installed/extracted. You can also copy all binaries, winscp.exe and winscpnet.dll, into separate folder. " Try putting the .exe in your app folder.
To 'merge the winSCP dll into your exe have a read of Embedding DLLs in a compiled executable
using WinSCP;

try
{
    SessionOptions sessionOptions = new SessionOptions
    {
        Protocol = Protocol.Sftp,
        HostName = EdiConfiguration.FtpIpAddressOrHostName,
        UserName = EdiConfiguration.FtpUserName,
        Password = EdiConfiguration.FtpPassword,
        SshHostKeyFingerprint = EdiConfiguration.SshHostKeyFingerprint,
        PortNumber = EdiConfiguration.FtpPortNumber
    };

    using (Session session = new Session())
    {
        session.Open(sessionOptions);

        TransferOptions transferOptions = new TransferOptions();
        transferOptions.TransferMode = TransferMode.Binary;
        transferOptions.ResumeSupport.State = TransferResumeSupportState.Off;

        // Download the files in the OUT directory.
        TransferOperationResult transferOperationResult = session.GetFiles(EdiConfiguration.FtpDirectory, EdiConfiguration.IncommingFilePath, false, transferOptions);

        // Check and throw if there are any errors with the transfer operation.
        transferOperationResult.Check();

        // Remove files that have been downloaded.
        foreach (TransferEventArgs transfer in transferOperationResult.Transfers)
        {
            RemovalOperationResult removalResult = session.RemoveFiles(session.EscapeFileMask(transfer.FileName));

            if (!removalResult.IsSuccess)
            {
                eventLogUtility.WriteToEventLog("There was an error removing the file: " + transfer.FileName + " from " + sessionOptions.HostName + ".", EventLogEntryType.Error);
            }
        }
    }
}
catch (SessionLocalException sle)
{
    string errorDetail = "WinSCP: There was an error communicating with winscp process. winscp cannot be found or executed.";
    errorDetail += Environment.NewLine + "Message:" + sle.Message;
    errorDetail += Environment.NewLine + "Target Site:" + sle.TargetSite;
    errorDetail += Environment.NewLine + "Inner Exception:" + sle.InnerException;
    errorDetail += Environment.NewLine + "Stacktrace: " + sle.StackTrace;
    eventLogUtility.WriteToEventLog(errorDetail, EventLogEntryType.Error);
}
catch (SessionRemoteException sre)
{
    string errorDetail = "WinSCP: Error is reported by the remote server; Local error occurs in WinSCP console session, such as error reading local file.";
    errorDetail += Environment.NewLine + "Message:" + sre.Message;
    errorDetail += Environment.NewLine + "Target Site:" + sre.TargetSite;
    errorDetail += Environment.NewLine + "Inner Exception:" + sre.InnerException;
    errorDetail += Environment.NewLine + "Stacktrace: " + sre.StackTrace;
    eventLogUtility.WriteToEventLog(errorDetail, EventLogEntryType.Error);
}
catch (Exception ex)
{
    eventLogUtility.WriteToEventLog("Error in ProcessEdi() while downloading EDI files via FTP: Message:" + ex.Message + "Stacktrace: " + ex.StackTrace, EventLogEntryType.Error);
}

A: //Using WinSCP to upload and download files
using System;
using System.Configuration;`
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Text;

using log4net;
using log4net.Config;

using WinSCP;

namespace SynchSubscriptions
{
    public class Program
    {
        // Initialize logger
        private static readonly ILog Logger = LogManager.GetLogger(typeof(Program));

        public static void Main(string[] args)
        {
            Download();
            UploadFile();
        }

        public static void Download()
        {
            try
            {
                string ftpurl = ConfigurationManager.AppSettings["FTPUrl"];
                string ftpusername = ConfigurationManager.AppSettings["FTPUsername"];
                string ftppassword = ConfigurationManager.AppSettings["FTPPassword"];
                string ftpSSHFingerPrint = ConfigurationManager.AppSettings["SSHFingerPrint"];

                string ftpfilepath = ConfigurationManager.AppSettings["FtpFilePath"];
                string Download = ConfigurationManager.AppSettings["Download"];

                SessionOptions sessionOptions = new SessionOptions
                {
                    Protocol = Protocol.Sftp,
                    HostName = ftpurl,
                    UserName = ftpusername,
                    Password = ftppassword,
                    PortNumber = 22,
                    SshHostKeyFingerprint = ftpSSHFingerPrint
                };

                using (Session session = new Session())
                {
                    session.SessionLogPath = "";
                    session.Open(sessionOptions);
                    RemoteDirectoryInfo directory = session.ListDirectory("/Export/");
                    foreach (RemoteFileInfo fileInfo in directory.Files)
                    {
                    TransferOptions transferOptions = new TransferOptions();
                    transferOptions.TransferMode = TransferMode.Binary;
                    transferOptions.FilePermissions = null;
                    transferOptions.PreserveTimestamp = false;
                    transferOptions.ResumeSupport.State = TransferResumeSupportState.Off;
                    TransferOperationResult transferResult;
                    transferResult = session.GetFiles("/Export/" + fileInfo.Name, Download, false, transferOptions);
                    transferResult.Check();
                    }
                }
            }
            catch (Exception ex)
            {
            }
        }

        private static bool UploadFile()
        {
            bool success = false;
            string sourcefilepath = "Input File Path";
            try
            {
                string ftpurl = ConfigurationManager.AppSettings["FTPUrl"];
                string ftpusername = ConfigurationManager.AppSettings["FTPUsername"];
                string ftppassword = ConfigurationManager.AppSettings["FTPPassword"];
                string ftpSSHFingerPrint = ConfigurationManager.AppSettings["SSHFingerPrint"];

                string ftpfilepath = ConfigurationManager.AppSettings["FtpFilePath"];

                SessionOptions sessionOptions = new SessionOptions
                {
                    Protocol = Protocol.Sftp,
                    HostName = ftpurl,
                    UserName = ftpusername,
                    Password = ftppassword,
                    SshHostKeyFingerprint = ftpSSHFingerPrint
                };

                string filename = Path.GetFileName(sourcefilepath);
                string ftpfullpath = ftpurl + "/" + filename;

                using (Session session = new Session())
                {
                    // Connect
                    session.Open(sessionOptions);

                    // Upload files
                    TransferOptions transferOptions = new TransferOptions();
                    transferOptions.TransferMode = TransferMode.Binary;

                    TransferOperationResult transferResult = session.PutFiles(sourcefilepath, ftpfilepath, false, transferOptions);

                    // Throw on any error
                    transferResult.Check();

                    // Print results
                    foreach (TransferEventArgs transfer in transferResult.Transfers)
                    {
                        success = true;
                    }
                }

                // Delete the file after uploading
                if (File.Exists(sourcefilepath))
                {
                    File.Delete(sourcefilepath);
                }
            }
            catch (Exception ex)
            {
            }
            return success;
        }
    }
}


text:
Q: perl inline: autosplit does not splits ls command into @F array ls | perl -anle 'print $F[0]' -> file1\nfile2\nfile3\n ...

This prints all files of ls. But is shouldn't. I want to access to ar @F, and ls gives file separated by space, so each file should be one element of @F, according to this:
-a   turns on autosplit mode when used with a -n or -p.  An implicit
            split command to the @F array is done as the first thing inside the
            implicit while loop produced by the -n or -p.

So I would like to access only first element, because if I change to $F[1] in print statement, then no ouput. I would expect file2. How does -a work then? (yes I have read documentation)
Edit:
If I use l, then after pipe, output won't be separate by "\n", so I can do the prior command with l listing instead.

A: The output of ls is not separated by spaces but by line feeds (as if -1 had been used) when sending its output to something other than a terminal.
$ ls | cat
bar
foo

(See Output from ls has newlines but displays on a single line. Why? for more info.)
In order to populate an array with each line of input, I would use
perl -F\\n -0777ane'...'

or the more readable
perl -e'chomp(@F=<>); ...'

For example,
$ ls | perl -e'chomp(@F=<>); CORE::say "<$_>" for @F;'
<bar>
<foo>

Both of these solutions handles paths that contains spaces. (It only has problems with paths that contains line feeds.)
That said, using ls isn't really appropriate. One could use a call to glob to the list of files even more easily and without any downsides.
perl -e'@F=<*>; ...'

For example,
$ perl -e'@F=<*>; CORE::say "<$_>" for @F;'
<bar>
<foo>

A: The output of ls is not separated by space, but by newlines when ls is not connected to a tty.
See Output from ls has newlines but displays on a single line. Why?.
You can try using:
ls | perl -0777 -ane 'print "$F[0]\n"'

instead. This will set the input record separator to slurp the whole file, and then split that string on white space into @F.


text:
Q: How to make changes to a different git repository from a jenkins job I have two git repositories:

*

*myapp

*gitinitdeploy

Myapp contains my regular application code. The build on this repository produces and pushes a docker image. The docker image will be tagged with the git commit hash.
gitinitdeploy contains k8s descriptor to be applied by a gitinit pod.
At the end of the myapp deploy build I want to update the k8s descriptor in gitinitdeploy so it points to the new docker image. (This will then trigger the redployment in k8s).
I already have suitable ssh secret for a a github used in my jenkins secrets.
How do I use this secret in the myapp build to access the gitinitdeploy repository?

A: You would want to think about doing it the same way you would do it if you were doing it manually on your local machine.
Your job will need to clone the gitinitdeploy repo. Replace the text in your k8s descriptor (sed is probably the easiest way) and then commit and push it.
Depending on your Jenkins setup you can checkout to a subfolder in the workspace to avoid any overlap with your primary repo.


text:
Q: VSTO manifest misses Ribbon entry I developed a VSTO Excel add-in with a Ribbon containing a few buttons. When we build the add-in through our TFS build server, the ribbon isn't loaded, although the add-in itself is loaded without any errors (it's shown as active in Excel\Options\Add-Ins, I write log entries on Startup and Shutdown, which are written correctly to my log file etc.) If I use my developper machine built add-in files (.dll, .dll.manifest, .vsto) the add-in loads correctly.
After long searching, we found a difference in the manifest file created by my machine and the build server. The build server manifest file seems to be missing an entry for the ribbon.
Does anyone know if there's a way to influence what entries are contained in the manifest, or if there's a setting in VS, which influences the manifest creation?
The lines of the build server manifest with the ribbon look as follows:
           <vstov4:appAddIn application="Excel" loadBehavior="3" keyName="AVExport">
            <vstov4:friendlyName>AVExport</vstov4:friendlyName>
            <vstov4:description>AVExport</vstov4:description>
            <vstov4.1:ribbonTypes xmlns:vstov4.1="urn:schemas-microsoft-com:vsto.v4.1" />
          </vstov4:appAddIn>

The same lines from my developper machine manifest file look as follows:
          <vstov4:appAddIn application="Excel" loadBehavior="3" keyName="AVExport">
            <vstov4:friendlyName>AVExport</vstov4:friendlyName>
            <vstov4:description>AVExport</vstov4:description>
            <vstov4.1:ribbonTypes xmlns:vstov4.1="urn:schemas-microsoft-com:vsto.v4.1">
              <vstov4.1:ribbonType name="Publisuisse.Publiplan.Client.Offer.AddIn.AVRibbon, AVExport, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
            </vstov4.1:ribbonTypes>
          </vstov4:appAddIn>

As you can see, my manifest contains an additional line which references my ribbon.
I couldn't find any information on this behaviour neither via SO search nor through google.
Any help is appreciated!
Cheers
Dominik

A: I found the answer to my problem: Here you can find the reason the manifest didn't work anymore, and here the solution:
Override the function
using Microsoft.Office.Tools.Ribbon;
protected override IRibbonExtension[] CreateRibbonObjects()
{
    return new IRibbonExtension[] { new Ribbon1(), new Ribbon2() };
}

to load the ribbons manually. Case closed.