Q:

Sockets on a private network

I'm developing a two part product. One part is a C# app on a single board computer running Windows Embedded Standard. The other piece is an embedded device running an RTOS with a TCP/IP stack. The two devices need to communicate via an Ethernet cable. It's a point to point connection. Nothing is connected to any outside network.
I'm a bit of a network programming novice, so I'm looking for best practices. I'm making the assumption that TCP sockets is the most straightforward approach. I figured I'd get some advice before writing any code and getting lost.
The one thing that is guaranteed is that the embedded device will maintain a static IP address of 169.254.1.1. That's about all I know. So what do I need to know to get these guys connected? I know there are issues with subnets... but that's where my knowledge is falling short. Which should be the client, which is the server, port numbers etc.
Little more info per request: The two ends are going to be exchanging a pretty simple binary protocol. That part is already defined and it working over an RS-232 link. But the RS-232 port is going away. I want to use TCP to basically carry this information, plus give me all the the good stuff like retries and error checking. Either end of the system can initiate a transfer.

A:

You might want to look into some introduction to socket programming, like http://beej.us/guide/bgnet.
The windows node will have to configure a network interface in the same
subnet as the rtos device and choose a (different) ip address from that
subnet.
Which device is the server and waits for a connection depends on your
application, maybe also on the boot order of the two nodes. For example,
if the RTOS device has booted first, it might wait for a TCP connection
until the other side is ready.
Of course, you'll need some protocol inside the tcp stream. Possibly UDP
might also be an option, if you don't need the features TCP provides. This
might also reduce the memory footprint on the RTOS side.
If the two sides can reboot (or crash :-) indenpedently from each other without
some hardware watchdog taking note, be sure that the other side recognizes the
reboot (e.g. with the tcp keepalive feature), so that you can reestablish the
connection.
With TCP you'll get the reliable connection, but depending on you application,
you might discover that the Nagle algorithm keeps your message latency higher
than what the RS232 setup had. Use the NO_DELAY option on the socket to avoid
this.


Q:

How to properly pass sprites to a std::vector without destroying the sprite's texture in SFML?

From the official SFML tutorials, The White Box Problem:-
"When you set the texture of a sprite, all it does internally is store a pointer to the texture instance. Therefore, if the texture is destroyed or moves elsewhere in memory, the sprite ends up with an invalid texture pointer." Thus you will see a sprite without a texture.
I have a class called World. In this class I made a 2d integer array called level and a vector of type Block called blocks. Now I wanted to store the 'Block' objects inside the vector whenever level[ i ][ j ] = 1.
header file of the 'World' class:-
#ifndef WORLD_H
#define WORLD_H
#include <vector>
#include "Block.h"
#include "Grass.h"
#include <SFML/Graphics.hpp>

using namespace std;

class World
{
    public:
        World();
        void draw(sf::RenderWindow *window);
        vector<Block> blocks;

    private:
        int level[12][16];
        int wd;
        int hi;
};

#endif // WORLD_H

cpp file of the 'World' class :-
#include "World.h"
#include "Grass.h"
#include "Block.h"
#include <iostream>
#include <SFML/Graphics.hpp>

using namespace std;

World::World() : level{
        {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
        {1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1},
        {1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1},
        {1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1},
        {1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1},
        {1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1},
        {1, 0, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 1, 0, 0, 1},
        {1, 0, 1, 0, 1, 1, 0, 1, 1, 0, 1, 0, 0, 0, 0, 1},
        {1, 0, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1},
        {1, 0, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1},
        {1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1},
        {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}
    }
{
    wd = 16;
    hi = 12;
    int count = 1;
    //make a 'Block' object and pass it in the vector when level[ i ][ j ] = 1.
    for(int i = 0; i<hi; i++)
    {
        for(int j = 0; j<wd; j++)
        {
            if(level[i][j] == 1)
            {
                Block block(j*50, i*50);
                blocks.push_back(block);
            }
        }
    }
}
void World::draw(sf::RenderWindow *window)
{
    for(unsigned int i = 0; i<blocks.size(); i++)
    {
        blocks[i].draw(window);
    }
}

The 'Block' class has two members - sf::Texture blockT and sf::Sprite block. It also has a draw(RenderWindow *window) method. This is how the 'Block' class is made :-
header file for block class
#ifndef BLOCK_H
#define BLOCK_H
#include <iostream>
#include <SFML/Graphics.hpp>

using namespace std;

class Block
{
    public:
        Block(float x, float y);
        void draw(sf::RenderWindow *window);

    private:
        sf::Texture blockT;
        sf::Sprite block;
};

#endif // BLOCK_H

cpp file for 'Block' class
#include "Block.h"
#include <iostream>
#include <SFML/Graphics.hpp>

using namespace std;

Block::Block(float px, float py)
{
    if(!(blockT.loadFromFile("textures/block.png")))
    {
        cout<<"Could not load block texture."<<endl;
    }
    block.setTexture(blockT);
    block.setPosition(sf::Vector2f(px, py));
    cout<<px<<endl;
    cout<<py<<endl;
}

void Block::draw(sf::RenderWindow *window)
{
    window->draw(block);
}

When I run the program, in place of blocks, only white box is shown. I don't understand how the texture is getting destroyed. This is what the output looks like :-

As you can see, the white places are sprites each of size 50*50 without any texture.
Edit: The Main Function :-
int main()
{
    sf::RenderWindow window(sf::VideoMode(800, 600), "Untitled game");
    window.setVerticalSyncEnabled(true);
    Player player;
    World world;

    //variables

    while(window.isOpen())
    {
        //event handling

        //updating

        //drawing
        window.clear(sf::Color::Black);
        world.draw(&window);
        window.display();
    }

    return 0;
}

A:

When I asked this question I didn't knew much about sprites and textures, but then I learned quite a lot from the internet and sfml tutorials. Actually what I was doing in the program was not correct. I was storing the texture in a local scope which was getting destroyed at the end of the scope. Textures should be stored at a global scope.
In fact, one should use vertex array and map texture coordinates to its vertices, instead of making thousands of sprites,  as it is  faster and more convenient for the graphics card. The lesser the number of calls to the 'draw' function, the better is the performance of the game. So a million sprite objects means a million calls to the 'draw()' function of your application which reduces performance.
Tutorials about the use of vertex arrays in sfml can be found in sfml's website, in the tutorials section.
 http://www.sfml-dev.org/


Q:

Short story about amnesiac man sent to a prison planet

Plot Summary/Details
The protagonist appears in a teleportation station, apparently very sick.  His first thoughts are about a mishap in the teleportation process, and is trying to recall the steps you're supposed to take to keep it together until the worst of it passes.  The man recovers shortly, but realizes he's not in the teleportation station near his home, but in a completely foreign place. He also sees there is no return teleporter. Completely unaware of how he got to this place, or why he's there, he exits the station and tries to find help in the town outside.
The man asks passersby for help, but is ignored at best, and treated roughly at worst.  It is a very unfriendly place.  Parched with thirst, he approaches a woman who has a mug or cup of something.  He asks her for a drink, but she clutches the drink to her chest, saying something like "mine, mine.  I carried wood for my share." She sullenly directs him to a large structure where he can get water instead.
I'm a little fuzzy on how the next part of the story goes.  At some point, he meets a seasoned old man, who has been living on the planet for some time.  I believe this man explains to the protagonist he is on a planet used exclusively as a prison for "the worst of the worst", or something like that.  The idea behind it being, it was a foolproof way for society to deal with the worst offenders, in a way that cost little and represented no risk.  There is no way off the planet, which is uninhabited, outside of the town/city the prisoners call home.   The only non-prisoners are the staff inside the structure where the protagonist was told to get water.  There is a water and food dispenser set into the outside wall, and a small chamber a seriously ill or injured prisoner can submit themselves for treatment.  There is no other way to access the structure.
The protagonist, now horrified that he's been put on a planet with hardened criminals, wants nothing more than to see one of the staff and try to explain to them that a terrible mistake has been made.  He enters the chamber, but the computer scanners detect that there is nothing physically wrong with him, and he is put back outside the structure.  The older man has a sort of "I told you so" attitude, but  takes the despondent protagonist under his wing.
We learn that the older man is a serial murderer, who poisoned a number of people before being caught.  His skills with chemistry also make him a skilled brewer, though, and thus popular.  The prisoners figured out long ago how to ferment and distill a local plant into a rough, but potent alcohol.  This is what the woman in the first part of the story was carrying in her mug.  The older man jokes he knows a few tricks that would make it taste more palatable, but his history as a poisoner make people wary of his "additions."
The older man treats the protagonist to a mug or two of the beverage, and tries to get him acclimated to his surroundings and some of the other prisoners.  Despite this, the protagonist becomes increasingly desperate, and finally seizes upon the idea of injuring himself so he can gain access to the staff.  He asks the older man to cut off a joint of one of his fingers.  The older man complies, but his sadistic nature kicks in during the process, and he gleefully hacks off two entire fingers.
The protagonist again lies down in the chamber, and this time is accepted into the structure.  He wakes to find himself strapped to a table, with a doctor working on him, and several well-armed security personnel in close proximity.  The protagonist pleads his case, and asks the doctor to search his records to see the mistake that has been made.  The doctor, moved by the protagonist's plea, does so.   It is then that we learn the protagonist is not there by mistake.   He brutally murdered his own wife, and was sentenced to the planet justly.  He simply has forgotten due to whatever trauma he suffered when he was teleported to the surface.
The story closes with the protagonist being treated and returned to the outside world.  The story closes with the protagonist, still unable to remember his crimes and in total denial, saying something to the effect of "how am I ever going to get home to see my wife now?"
Publication timeframe
I think this one is late 2000's, or even 2010's.  I'm pretty sure I read it in a sci-fi magazine (can't remember which one, obviously), and not an anthology or other collection.

A:

"Waiting Place", a short story by Harry Harrison in his Matter Transmitter series; originally published in Galaxy Magazine, June 1968; previously identified as part of the answer to this question. The ending:

The metal coffin lid opened, and Jomfri sat up, dizzy. They had drugged him; he was hazy; they had tended his wounds.
"But they wouldn't help me. They wouldn't even look in the records to prove my innocence. A mistake. A fault in the matter transmitter, and I am condemned because of it."
He looked at the bloodstained bandages, and something hurt in his head.
"Now I'll never get home to my wife," he sobbed.


Q:

Is there a way to make the active selection more noticeable?

I'd like to make the active selection color different because I can barely see it when I'm selecting faces. I have an object that I'm trying to UV map, and there are some tiny faces that haven't unwrapped the way I expected, which I can see in the UV map editor, but can't find in 3D view because the active selection is too hard to see.

A:

Switch you view to user preferences. Select 3D View from the left.  You will find what you need
Consider Zooming.  Number Pad (.) period then you can zoom at center.
User preferences allows you increase the size of the outline and vertex dots


Q:

Set an environment variable in .htaccess and retrieve it in PHP

I am trying to set an environment variable in an .htaccess file and retrieve it in PHP. I've looked through a bunch of other threads here on SO but everything I've tried so far has failed.
I've added this line to the .htaccess file:
SetEnv SPECIAL_PATH /foo/bin

I have tried retrieving this value using the getenv() PHP function:
<?php $specialPath = getenv('SPECIAL_PATH'); ?>

I have runned phpinfo() to see the list of available environment variables, SPECIAL_PATH is not there. I am puzzled as to why this is not working.
Thank you!

A:

Assuming your configuration has AllowOverrides with .htaccess, you must enable mod_env in Apache for this to work.
Apache - mod_env

A:

Apache Docs custom-error.html covers environment variables passed to error handling pages
Says "REDIRECT_ environment variables are created from the environment variables which existed prior to the redirect. They are renamed with a REDIRECT_ prefix, i.e., HTTP_USER_AGENT becomes REDIRECT_HTTP_USER_AGENT."
Says "None of these will be set if the ErrorDocument target is an external redirect (anything starting with a scheme name like http:, even if it refers to the same host as the server)."
Says about SetEnv: "The internal environment variables set by this directive are set after most early request processing directives are run, such as access control and URI-to-filename mapping. If the environment variable you're setting is meant as input into this early phase of processing such as the RewriteRule directive, you should instead set the environment variable with SetEnvIf."
On some servers, user-declared environment variables must start with 'HTTP_' for security purposes, e.g.:  SetEnv HTTP_MY_VARIABLE "my value"
Here are some .htaccess ways of setting and using server environment variables, taken from my modifying the Perishable Press 5G Blacklist/Firewall http://perishablepress.com/5g-blacklist-2013/ to use environment variable reporting:
SetEnv myServerName %{SERVER_NAME}

RewriteCond %{QUERY_STRING} (base64_encode|localhost|mosconfig|open_basedir) [NC,OR]
RewriteCond %{QUERY_STRING} (boot\.ini|echo.*kae|etc/passwd) [NC,OR]
RewriteCond %{QUERY_STRING} (GLOBALS|REQUEST)(=|\[|%) [NC]
RewriteRule .* - [E=badQueryString:%0--%1--%2,F,L]

SetEnvIfNoCase User-Agent ^$ noUserAgent
SetEnvIfNoCase User-Agent (binlar|casper|cmsworldmap|comodo|diavol|dotbot|feedfinder|flicky|ia_archiver|jakarta|kmccrew|nutch|planetwork|purebot|pycurl|skygrid|sucker|turnit|vikspider|zmeu) badUserAgent=$1

<limit GET POST PUT>
  Order Allow,Deny
  Allow from all
  Deny from env=badUserAgent
</limit>

Notice the use of paramters, e.g. $0--%1--%2. %0 gives the full string, %1 gives the match from the 1st parenthesized statement, %2 the 2nd. The hyphens are literal display characters, to visually separate parameter results (don't think is any way to put spaces in there).

Here are some PHP methods of accessing the environment variables (in my case from 403.php and 404.php).
Note that you don't look in phpinfo(), but in $SERVER, and that your variables get prefixed with REDIRECT
Note also that with a 403/404 redirect, the QUERY_STRING becomes REDIRECT_QUERY_STRING
This is stuff that could easily be server dependent, so check $_SERVER for your actual values. For example,
if (getenv("HTTP_REFERER") !== FALSE) {
    $httpref = getenv("HTTP_REFERER");
} else {
    $httpref = '';
}
if (isset($_SERVER['REDIRECT_STATUS'])) {
    $status = $_SERVER['REDIRECT_STATUS'];
} else {
    $status = '';
}
if (isset($_SERVER['REMOTE_HOST'])) {
    $remoteHost = $_SERVER['REMOTE_HOST'];
} else {
    $remoteHost = '';
}

if (isset($_SERVER['REDIRECT_QUERY_STRING'])) {
    $querystring = $_SERVER['REDIRECT_QUERY_STRING'];
} else {
    $querystring = '';
}

if (isset($_SERVER['REDIRECT_noUserAgent']) ) {
    $htaccessErrors[] = 'NoUserAgent';
}
if (getenv("REDIRECT_badQueryString") !== FALSE) {
/* must exactly match what shows up in $_SERVER, is case sensitive (e.g. badQueryString not BadQueryString) */
    $htaccessErrors[] = 'badQueryString:'.getenv("REDIRECT_badQueryString");
}

I cover in some depth in http://lcblog.lernerconsult.com/2013-server-alert-you-file-not-found-errors/


Q:

GestureDetector / Inkwell inside Overlay misaligned on iPhones that have a bottom notch

I have a full screen Overlay that hosts a Minimize / Maximize button, and this button works perfectly on Android and iOS phones that don't have a bottom notch.
Examples of working devices:

Pixel 3 (emulator)
iPhone 8 (emulator)

Examples of problematic devices:

iPhone 11

When the Overlay is "maximized", the hit detection is spot on. When "minimized", the hit detection is offset downwards. The "MinMax" FlatButton (see below) needs to be tapped at a very specific spot under the text of the button.
Futhermore, the missed hit detection doesn't offset gradually as the size of the Overlay gets smaller. You can see this by increasing the minimized size from 0.08. Any change in size at all causes the hit detection to miss at the same spot.
The following minimal repro demonstrates the issue:
import 'dart:async';

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  bool _isMinimized = false;
  StreamController<bool> _isMinimimizedController = StreamController<bool>();
  OverlayEntry _activeOverlay;

  Widget _buildOverlay() {
    return Scaffold(
      body: SafeArea(
          top: !_isMinimized,
          bottom: _isMinimized,
          child: Column(
            children: <Widget>[
              _buildOverlayHeader(),
              Expanded(
                child: Container(
                  color: Colors.red,
                ),
              ),
            ],
          )),
    );
  }

  Widget _buildOverlayHeader() {
    return Container(
      decoration: BoxDecoration(color: Colors.green),
      child: Padding(
        padding: EdgeInsets.all(10),
        child: Row(
          children: <Widget>[
            Expanded(
              child: Container(),
            ),
            FlatButton(
              child: Text('MinMax'),
              onPressed: () {
                _isMinimized = !_isMinimized;
                _isMinimimizedController.sink.add(_isMinimized);
              },
            ),
          ],
        ),
      ),
    );
  }

  void openOverlay() {
    if (_activeOverlay != null || context == null) {
      return;
    }

    _activeOverlay = OverlayEntry(builder: (context) {
      return StreamBuilder<bool>(
          stream: _isMinimimizedController.stream,
          initialData: false,
          builder: (context, snapshot) {
            final mediaQuery = MediaQuery.of(context);

            var height = mediaQuery.size.height;
            var top = 0.0;

            if (_isMinimized) {
              height = height * 0.08;
              top = mediaQuery.size.height - height;
            }

            return AnimatedPositioned(
              duration: Duration(milliseconds: 300),
              curve: Curves.easeInOutQuart,
              width: mediaQuery.size.width,
              height: mediaQuery.size.height,
              top: top,
              left: 0,
              // Child navigator is necessary to show modals on top of the overlay
              child: Navigator(onGenerateRoute: (RouteSettings settings) {
                var builder = (BuildContext context) => _buildOverlay();
                return MaterialPageRoute(
                    builder: (builder), settings: settings);
              }),
            );
          });
    });

    Overlay.of(context).insert(_activeOverlay);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: openOverlay,
        tooltip: 'Open',
        child: Icon(Icons.add),
      ),
    );
  }
}

What is causing the hit detection miss?

A:

Turns out the problem was with how I was toggling the SafeArea's top and bottom properties here:
      body: SafeArea(
          top: !_isMinimized,
          bottom: _isMinimized,

The solution was to remove the "top" and "bottom" lines so that they always defaults to true. I then calculate the minimized height of the header manually.


Q:

Change youtube API developer key for app transfer to another GooglePlay account?

I have an already published Android app which uses the youtube APIv3. This app shall be transferred to another Google Play dev account which I would own, too.
Do I have to change the youtube API developer key in the app source code? And do I have to make adjustments in the youtube dev account where I got the developer key etc.?
The app identifier/ package name as well as the app signing certificate would remain the same for future app updates. I would just have to change the Google Play developer account and transfer the app to the new account.
I suppose that it is not urgently necessary to make changes in the youtube API account or to change the developer key, but I would be interested in knowing your opinion.
Would look forward to feedback.

A:

The Google Play developer account is unrelated to the account that you use to register for YouTube APIs.
Hence, no, you do not have to change anything (if you don't want to, of course).


Q:

Load Parse.File url into EJS template

I'm trying to rendering out an html template using EJS, Express and Parse.com. Basically whenever I try to reference a Parse.Files url() call from within my EJS template it errors and nothing gets returned. These images are hosted on Parses cloud, not in the public directory.

        <% reviews.forEach(function(review,index) { %>

<img class="profile-img" src="<%= review.get('createdBy').get('pictureThumbnail').url() %>" width="35" height="35"/>Test

        <% }) %>

I've run a console.log() on review.get('createdBy').get('pictureThumbnail').url() and I get back a simple url string. But if I put it in the template I get nothing.
I've tried using <%- <%= <%, but nothing seems to work.

A:

So, the issue was that I wasn't checking to make sure that the file actually existed and there were two items that had no images associated with them, this was causing the whole thing to error, but since I wasn't getting an error in the terminal I really had no idea what was happening.
So lesson learned, always make sure you are checking for empty objects in EJS.


Q:

Form processing issue while generating a dynamic form and preparing via API calls directly

How can I fix the processing and submission of forms that I am preparing and rendering dynamically via API calls.
function drupal_set_confirmation($message, array $options, array $escape=array(), $type='warning', $details=NULL){
    $form = array();

    $form['title'] = array(
    '#markup' => '<h3>' . t($message) . '</h3>'
    );

    if (!empty($details)) {
        switch(gettype($details))   {
            case 'string':
                $form['details'] = array(
                    '#markup' => $details,
                );
            break;
            case 'array':
                $form['details'] = $details;
            break;
        }
    }

    if (!empty($options)) {
        $form['options'] = array(
            '#type' => 'container',
            '#attributes' => array('class' => array('user-confirmation-options')),
        );

        foreach($options as $key => $option) {
            $form['options'][$key] = array(
                '#submit' => array($option['callback']),
                '#type' => 'submit',
                '#value' => $option['title'],
                '#attributes' => $option['attributes'],
            );
        }

        if (!empty($escape)) {
            $form['options']['escape'] = array(
                '#markup' => l($escape['title'], $escape['path']),
            );
        } else {
            $form['options']['escape'] = array(
                '#markup' => l(t('Cancel'), current_path()),
            );
        }
    }

    $form_state = form_state_defaults();
    $form_id = 'form_user_confirmation';

    drupal_prepare_form($form_id, $form, $form_state);
    // I do not see any reason to call drupal_process_form while serving the form.
    //drupal_process_form($form_id, $form, $form_state);
    $rendered_form = drupal_render($form);
    return drupal_set_message($rendered_form, $type);
}

And it works greatly to show a dialog form of my own choice by calling.
drupal_set_confirmation(t('Do you really want to suicide?'), array(
        'okay' => array(
        'callback' => '_yes_kill_me',
        'title' => t('Yes'),
        'attributes' => array('class' => array('button', 'tiny')),
    ),
    ), array(
        'title' => t('No'),
        'path' => current_path(),
    ));

And callback function as #submit handler for a particular element is not invoked.
How can I fix the form processing and submission issue using this approach to work?

A:

I fixed it this way, it started to invoke form submit handlers.
function MODULE_init() {
    if (!empty($_POST) && $_POST['form_id'] == 'form_user_confirmation') {
        $form_state = form_state_defaults();
        $form_id = 'form_user_confirmation';
        drupal_build_form($form_id, $form_state);
    }
}


Q:

Update a DataGridView column value in C#

I have created a grid with 6 columns all are of type string now my requirement is when the user double clicks on the 6th column a new form will open and return the value from the selected record in id, name variables.
It is opening the form and getting the values but when executing the following line
grdItemDetail.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = id;

it is not updating the field give the error and close how to update the value for this column please help. The full code is as follows.
private void grdItemDetail_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
{
        if (e.ColumnIndex == 6)
        {
            frmWarehouseList frmWarehouseList = new frmWarehouseList();
            frmWarehouseList.ShowDialog();
            string id = frmWarehouseList.SelectedWarehouseID;
            string name = frmWarehouseList.SelectedWarehouseName;
            //MessageBox.Show(grdItemDetail.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString());
            grdItemDetail.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = id;
        }

A:

The column index is zero based, so if you have six columns, the highest index is five.
Quick fix:
if (e.ColumnIndex == 5)
{
  // etc
}


Q:

Could medieval European merchants travel through the Islamic world?

I've heard that the Islamic world was closed to European merchants in the Middle Ages.  Is this true?  If so, when did it close and when did it open again?

A:

It's difficult to give a proper answer, because during any century of Middle Ages there could be many reasons for closing trading routes for European merchants as outsiders in various parts of Islamic world (which is huge). And it didn't need to have anything in common with religion - it could be the level of civilization (early medieval Europe), an economic matter in the particular case, or just a result of war.
But let's try to clarify few things.
First of all, Islamic world, in fact, wasn't that closed to Europeans as we think. Jews and Christians could live at Muslim lands if they paid special tax. The same with merchants from Europe. What's more, some Christians could even serve to Muslim rulers at important positions, such as revenue collectors or administrators of various types.
It's nicely described in the book "Daily Life In The Medieval Islamic World" by James E. Lindsay. You can find it's full text in the link, look for pages 120-121.
Also there's a good source for that in "Europe and the Islamic World: A History" by John Tolan, Henry Laurens and Gilles Veinstein, at pages 80-81. Unfortunately in both cases I'm not able to copy-paste it.
I believe that a bit about the overall history of the trade between Christians and Muslims during Middle Ages could help you solve the problem. I'll quote Jihoon Ko and his article "Economic Impact the Islamic World Had on Christian Europe (11th ~14th century)".

The conquest of Muslims of various regions of Europe had actually
  ceased the major long-distance trade of the Christian Europeans
  overseas for a while and the commerce of Christian Europe had been
  limited to the local ones. But the regions which were under Islamic
  rules were included in the commercial sphere of the Muslims—who were
  the most active adventurers and entrepreneurs at the time—saw the rise
  of international and complicated commercial activities. The
  international trades in Christian regions were late to appear. The
  crusade created a large influx of Eastern goods and luxuries into the
  Christian Europe. This created a large interest among rich Europeans
  for the Eastern goods, and the Christian merchants saw this to be an
  opportunity for a dramatic profit. As the merchants began to actively
  engage in the trade with the Islamic world, the trade of the Christian
  states overseas began to flourish. The leading states of the trade
  with the East were Italian city-states, most notably Genoa and Venice.
  The extent of the international trades before the 11th century,
  however, was nothing compared with those of the Muslim world. The case
  of Al-Andalus indicates how well established was the Andalusi
  merchants’ trades compared with the Europeans in the same era.

This way first, European (Christian) international trade wasn't well developed until 11th century, mainly due to the fall of ancient culture. It took European civilization a lot of time to get up after that.
But there were some smart merchants who made a fine business by initiating contacts between both worlds. They were, of course, Jews.

There were some global commercial activities going on in the Christian
  world, however, before the Christians began to trade over long
  distance, by the Jewish merchants. The Jews were also the first
  merchants in the Middle Ages to introduce goods from the East to the
  Christian Europeans. They supplied goods from the Islamic world as
  soon as the Carolingian era. The Jews could travel to Europe with
  relative ease. Some of them settled in Italy, but majority of them
  were those who based their commerce in the Muslim countries. The Jews
  from the Muslim world reached Western and Northern Europe through
  Spain. At first, they exclusively traded spices, pepper, manufactured
  goods, and other precious stuffs from Egypt, Syria, and Maghrib. They
  provided the goods to the churches which used the goods to make
  incense for religious activities, and to the selected nobility.

When European trade market became more international, the crusades started. One could imagine that it made the trade more difficult, from the most obvious reason which is "you don't go trading with your enemy if you don't want to be killed".
Somehow, in fact it helped to open both markets on each other.

The crusades, in turn, helped to change the economic activity of
  Christian Europe. The crusades “enabled Western Europe to monopolize
  the whole trade from the Bosphorus and Syria to the Straits of
  Gibraltar.”[10] Even if they failed to take the holy place from the
  hands of Muslims, they politically weakened the powers of the Islamic
  states and Byzantine Empire. The Byzantine Empire’s maritime power was
  weakened seriously and their merchants now could not compete with the
  Italian rivals, which now controlled the Byzantine Empire’s export and
  import trades. The crusades also caused the large influx of Eastern
  luxuries into Christian Europe, thus stimulating the interest of
  people for the trade with the Islamic world. So, it is no exaggeration
  to say that the crusades were crucial factor in the revival of
  extensive economic activities of Medieval Christian Europe.

As it's described later, the main European ports that were trading with Islamic World were Genoa and Venice. And even if there were some difficulties, a business is still a business.

The trades with the Islamic world at first time were limited because
  of religious reason, and because of technical reasons, but gradually
  the Italian merchants began to seek profits and the economic
  incentives were large enough to overcome religious obstacles for
  greater incomes. As a result, the Italian city-states rose as major
  maritime commercial centers from 11th century, and the scope of their
  trades even exceeded that of the Muslim ports.

I'll quote only two paragraphs more and I'll leave the rest to you, if you're more interested in the trade with Islamic World in overall, not only from the point of it's connection to religious problematic.

Christians and Muslims have been enemies by principles. Moreover, as
  the Middle Age was the time when the religion affected the lives of
  Christians most significantly, the Muslims were considered evil by
  Christians. This aversion of Christians toward Muslims, however, could
  not stop the economic interest of the Christian merchants, and the new
  pattern of global trade appeared.
The Muslim world indeed acted as an important trade partner of Europe
  in the Late Middle Age. They facilitated the European trade and thus
  strengthened its economy. Also, they provided the goods that were not
  available in Europe, and this fact made Europe a favorite place for
  European merchants. The religious principle could not separate the
  two. The trades between Europe and the Muslim World sometimes stopped
  because of political situations, and were greatly reduced when the
  Turkish soldiers occupied Constantinople and destroyed Byzantine
  Empire. However, it is evident that the two had long-time economic
  connections, and such connectivity helped the European economy a lot.


Q:

IDENT_CURRENT value is higher than max(id)

Error:
Arithmetic overflow error converting IDENTITY to data type int.
Arithmetic overflow occurred.
Debugging:
id = my Identity column, datatype INT. Increment=1, Seed=1
select max(id) as max, min(id) as min from eventlogreport
    Result: 6728550 1

select count(*) from eventlogreport
    Result: 6728550

So far soo good. It looks like we have plenty of room for more rows. But inserting 600 000 more rows gives the overflow error. More debugging.
SELECT IDENT_CURRENT ('EventLogReport') AS Current_Identity;
    Result: 2147483647

Questions:

How can the current identity value be so high when the table doesn't
contain the same amount of rows, and there are no ids that has been
skipped?
How can I safely set the IDENT_CURRENT to the same number as max(id)? Or maybe it's easier to reseed, as long as the id columns isn't references?

A:

Identity values don't participate in transactions - so if you've had a large number of attempted inserts (after all current rows were added) that have subsequently been rolled back, then IDENT_CURRENT can be much higher than the highest observed value in the table.
Similarly, if you'd actually inserted 2147483647 rows but then deleted all rows with an ID greater than 6728550, you'd observe the same situation.
Thirdly, someone may have reseeded the identity to be 2147483647.
So there are many ways you may have reached this situation. It's impossible for us to know how it came about.

To set the identity value to be appropriate for the next insert, use DBCC CHECKIDENT twice:
DBCC CHECKIDENT(Table,RESEED,1)
DBCC CHECKIDENT(Table,RESEED)

The first sets the next value to use as 2. The second then invokes this part:

If the current identity value for a table is less than the maximum identity value stored in the identity column, it is reset using the maximum value in the identity column. See the 'Exceptions' section that follows.


Q:

Run a script (or set stringsAsFactors = FALSE) while loading a package in R

I previously used Rprofile.site to set options(stringsAsFactors = FALSE). However, numerous sources state using Rprofile.site for this purpose makes code less portable. My solution has been to run source('C:/...startup.script.R') every time I load R. This startup script sets stringsAsFactors = FALSE (along with accomplishing other tasks). This works, but in order to share my scripts with others I would have to share the script of interest and my startup.script.R script.
I am creating a custom package that will allow me to share my custom functions. I plan to put require(MyCustomFunctionsPackage) (or something to that effect) at the beginning of all of my scripts in order to load my custom functions. I want to embed source('C:/...startup.script.R') (or something to that effect) and the startup.script.R file in the MyCustomFunctionsPackage package such that, when I share my scripts, I will only need to share the script of interest with a call to devtools::install_github('MyCustomFunctionsPackage','github_username') and all of my custom functions and settings will be loaded. Is there a way to do this? I'm sure the answer is in Hadley's book or the CRAN literature somewhere, but I'm not sure what keywords to search.

A:

You can supply a function named .onLoad() that will be called whenever the package is loaded. Here's a simple reproducible example showing how it can be used:
## Create and install a package containing a function `.onLoad()`
library(pkgKitten)
kitten("myopts")
cat(
".onLoad <- function(libname, pkgname) {
    options(stringsAsFactors = FALSE)
}
", file = "myopts/R/zzz.R")

devtools::install("myopts")

## Confirm that loading the package sets stringsAsFactors
options('stringsAsFactors')
## $stringsAsFactors
## [1] TRUE

library(myopts)
options('stringsAsFactors')
## $stringsAsFactors
## [1] FALSE


Q:

django-rest ModelSerializer select fields to display in nested relationship

I'm going to reference the django-rest-framework API example on this. Lets say we have two serializers defined as below.
class TrackSerializer(serializers.ModelSerializer):
    class Meta:
        model = Track
        fields = ['order', 'title', 'duration']

class AlbumSerializer(serializers.ModelSerializer):
    tracks = TrackSerializer(many=True, read_only=True)

    class Meta:
        model = Album
        fields = ['album_name', 'artist', 'tracks']

Now if i do a GET request and retrieve an Album instance, it will return me a response with a list of Track instances inside it where each instance contains all the fields of Track. Is there a way to return only a selected subset of the fields in the Track model? For example to only return the title and duration field to the client but not the 'order' field.

A:

You can make a specific TrackSerializer for your Album, like:
class TrackSerializer(serializers.ModelSerializer):
    class Meta:
        model = Track
        fields = ['order', 'title', 'duration']

class TrackForAlbumSerializer(serializers.ModelSerializer):
    class Meta:
        model = Track
        fields = ['title', 'duration']

class AlbumSerializer(serializers.ModelSerializer):
    tracks = TrackForAlbumSerializer(many=True, read_only=True)

    class Meta:
        model = Album
        fields = ['album_name', 'artist', 'tracks']
You do not have to define a single serializer per model, you can define multiple serializers you each use for a dedicated task.


Q:

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xa0 in position 8

I am trying to read a CSV using pd.read_csv, but I get an error:

UnicodeDecodeError                        Traceback (most recent call
  last) pandas_libs\parsers.pyx in
  pandas._libs.parsers.TextReader._convert_tokens()
pandas_libs\parsers.pyx in
  pandas._libs.parsers.TextReader._convert_with_dtype()
pandas_libs\parsers.pyx in
  pandas._libs.parsers.TextReader._string_convert()
pandas_libs\parsers.pyx in pandas._libs.parsers._string_box_utf8()
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xa0 in
  position 8: invalid start byte
During handling of the above exception, another exception occurred:
UnicodeDecodeError Traceback (most recent call last)
  ipython-input-84-c0272ccf19e6 in module

Sample of my data:
Time,Type,Instrument,Product,Qty.,Avg. price,Status
3/27/2019 13:46,BUY,MFSL,MIS,1600,115.25,COMPLETE
3/27/2019 13:46,BUY,MFSL,MIS,500,115.3,COMPLETE

i have already tried checking if there is an invalid character (using Notepad++). "Show all characters"
I couldn't find any difference when comparing this file with a similar one that could be loaded.
Just Need help Troubleshooting the above, If someone can point me in the right direction.

A:

The data you posted works fine for me, but it's several degrees removed from your source. Specifying an encoding when opening the file may fix the problem. You can do this a couple of ways: use the codecs package to open the file and let that decide the encoding, or specify the encoding in csv_read()
    import codecs

doc = codecs.open('document','rU','UTF-16') #open for reading with "universal" type set

df = pandas.read_csv(doc, sep=',')

You also might want to sanitize your column names, as spaces and decimals can cause problems in referencing.
df.columns = df.columns.str.strip().str.lower().str.replace(' ', '_').str.replace('(', '').str.replace(')', '').str.replace('.', '')


Q:

Adding back layer heading in ArcMap?

I deleted the layer heading thinking that I didn't need it. But after doing some refactoring, it turns out that I do need it but I can't figure out any way to add it back.
How do I add it back?
I'm using ArcMap 10.6.

A:

It is called the layer heading.
Go to symbology.
Change the value field to something else.
Change it back.
It should reappear.
The proper way is
Make sure the layer has headings. ...
Double-click the legend to open the Legend Properties dialog box and select the Items tab.
Click Style.
Click Properties.
Select the General tab.
Choose a heading from the 'Only show classes from this heading' dropdown list.
https://support.esri.com/en/technical-article/000002820


Q:

Nginx only serving first 72kbs of my JS files

Nginx appears to only be loading the first 72kbs of my javascript files. I've searched all around  my nginx config files and cannot see this setting anywhere. I've added things like
location / {
    ...
    proxy_max_temp_file_size 1m;
    ...
}

and
location / {
    ...
    sendfile on;
    sendfile_max_chunk 1m;

    ...
}

But still I'm unable to overwrite this weird setting that is only allowing first part of the file to load.
The connection uses nginx proxy_pass to foward port 80 to kibanas port '5601'. I feel like there could be a setting that limits file transfer over proxy? Just not sure where to find it.
proxypass connection looks like:
server {
    listen 80;

    server_name logs.mydomain.com;

    auth_basic "Restricted Access";
    auth_basic_user_file /etc/nginx/htpasswd.users;

    location / {
        proxy_pass http://localhost:5601;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
    }
}

And my default nginx settings is posted here:

http://www.heypasteit.com/clip/OEKIR

A:

Would appear when disk space is low NGINX defaults to minimal safe settings.
When I checked the VMs health I noticed that the disk drive was full. Elasticsearch was logging a couple of GBs worth of text in to error logs each day. I still Have not fully identified why elastic search is flooding the error logs.
But I think excessive disk space usage has contributed to this error. Nginx could be detecting this and switching over to minimal safe configuration which would only allow 72kbs of data to be served per file.
Once I cleared out the excessive logs, Nginx began serving the full JS files again without needing to restart nginx or kibana.


Q:

Add data to a generic collection in java

Is there any way i can add data to a generic collection in Java.
For eg:-
import java.util.List;
import java.util.Vector;

public class testGenerics {
    public static void main(String args[]) {
        Vector<? extends Number> superNumberList = null;

        // I can do this
        Vector<Integer> subList = new Vector<Integer>();
        subList.add(2);
        superNumberList = subList;

        // But i cannot do this
        // Gives the below compilation error.
        //The method add(capture#2-of ? extends Number) in the type
        //Vector<capture#2-of ? extends Number> is not applicable for the arguments (Integer)
        superNumberList = new Vector<Integer>();
        superNumberList.add(new Integer(4));

        superNumberList = new Vector<Float>();
        superNumberList.add(new Float(4));
    }

}

As mentioned in my comments i have compilation errors when i try to add an Integer or Float data to superNumberList.
I am able to do it , the first way , but would like to do it the second way and not sure why Java does not allow me to do it the second way.
I have a suitation where i have a super class which has this superNumberList and all the subclasses are trying to use this same variable but has different data types in this collection like Integer , Float etc.

A:

A Vector<? extends Number> is a Vector of an unknown Number type. As such, you cannot add anything into it.
It could be a Vector<Float>. So you cannot add an Integer.
But it could also be a Vector<Integer>. So you cannot add a Float.
The only thing you know about it is that whatever you pull out of the Vector will be a Number.

If you have a superclass that has subclasses for Integer, Float and so on, you should make the superclass generic:
class SuperClassWithVector<T extends Number>{
    protected Vector<T> myVector;
}

class FloatSubClass extends SuperClassWithVector<Float>{
   // here myVector takes Float
}

If you want a Vector that can take both Integer and Float (not sure if that is what you want), then you can use a Vector<Number>.


Q:

Are there other filter models besides IIR and FIR for processing digital signals?

I am very familiar with IIR and FIR filters for processing digital signals (audio is my main interest). I am keen to know if there are alternative filters based on different mathematical models to IIR and FIR?
I have a degree in maths but learning about DSP is just a hobby (I didn't study it at university) so I haven't a clue whether this is a stupid question or not :-)

A:

FIR and IIR filters are discrete-time linear time-invariant (LTI) filters. There are also (linear) time-varying systems, which could be implemented just like FIR or IIR filters, but with time-varying coefficients. Audio effects like chorus, flanger, or phaser are time-varying filters.
Of course there are also non-linear filters, the most well-known of which is probably the median filter, which is very useful for removing impulsive noise. Many different types of non-linear filters are used in image processing.
Note that none of the above mentioned filters can be characterized by their impulse response or, equivalently, by their frequency response. This is only possible for LTI systems.


Q:

Gmail call, available or not?

I tried the new Gmail call feature  and it worked fine the first time. I have 2 Gmail accounts. At first, the call button was only showing in one account. Now it isn't showing in either.
Any idea why?

A:

Google generally does phased roll outs, so there are often some people with a new feature and others waiting.  I would wait a few days and see if it appears.

A:

I read on the BBC news that Google announced this feature and mistakenly enabled it for every user, only to then remove it from non US accounts later that day:

"Unintentionally we briefly made the service available to non-US English users," a spokesperson said. "We do hope to bring it to our international users soon."
When it rolls out the product link will appear on the left hand of the Gmail page within the "chat" window. A "call phone" option will pop up along with a number pad to let you dial the number of the person you want to talk to.

If your account is not US based, it may explain why you could do it but now cannot.


Q:

Scala Reads: How to handle Option[Map[String, Any]]

I cannot wrap my head around why it throws an error on the following line:
val anyReads = Reads[Any](m => metaValueToJsValue(m))

Error Message:  type mismatch; found : play.api.libs.json.JsValue required: play.api.libs.json.JsResult[Any] Note: implicit value readsMap is not applicable here because it comes after the application point and it lacks an explicit result type
I've pasted my code below.
Any help is appreciated! Thanks!
import play.api.libs.json._
import play.api.libs.json.util._
import play.api.libs.functional.syntax._

case class TempClass(
  metaValue: Option[Map[String, Any]])

object TempClass {

  val anyReads = Reads[Any](m => metaValueToJsValue(m))

  def metaValueToJsValue(m: Any): JsValue = {
    m match {
      case s: String => JsString(s)
      case n: Int => JsNumber(n): JsValue
      case n: Long => JsNumber(n): JsValue
      case n: Double => JsNumber(n): JsValue
      case n: BigDecimal => JsNumber(n): JsValue
      case b: Boolean => JsBoolean(b)
      case l: Seq[Any] => JsArray(l.map(metaValueToJsValue)): JsValue
    }
  }

  implicit val readsMap = Reads[Map[String, Any]](m => Reads.mapReads[Any](anyReads).reads(m))
  implicit val reads = Json.reads[TempClass]
}

A:

Looks like you are doing something really wrong here.

val anyReads = Reads[Any](m => metaValueToJsValue(m))

Reads takes as argument a function which accepts JsValue and returns JsResult[A] but you are passing a function which takes Any and return JsValue.
So the signature of def metaValueToJsValue(m: Any): JsValue = { should be like this
def metaValueToJsValue(m: JsValue): JsResult[Any] = {

NOTE: Generally frameworks doesn't provide default serializers for Polymorphic Maps (Map[String, Any]) because the Any can again be Maps/Lists and can go to any level. So application should have knowledge of the incoming JSON structure. In the below code i have made an assumption of one level ie, Json attribute values themselves can't be Json objects/arrays
Please refer to the code below:
object TempClass {

    implicit val readsMap = Reads[Map[String, Any]](m => Reads.mapReads[Any](anyReads).reads(m))
    implicit val reads = Json.reads[TempClass]
    val anyReads = Reads[Any](m => metaValueToJsValue(m))

    def metaValueToJsValue(m: JsValue): JsResult[Any] = {
      m match {
        case JsObject(m) => {
          val m1 = m.map(f => (f._1, convert(f._2))).toMap
          JsSuccess(m1)
        }
        case JsString(s) => JsSuccess(s)
        case JsNumber(n) => JsSuccess(n)
        case JsBoolean(b) => JsSuccess(b)
        case JsArray(arr) => {
          val list = arr.map(convert)
          JsSuccess(list)
        }
      }
    }

    def convert(m: JsValue): Any = {
      m match {
        case JsString(s) => s
        case JsNumber(n) => n
        case JsBoolean(b) => b
      }
    }

    def main(args: Array[String]) {
      val json = """{"metaValue" : {"name":"John", "age":30}}"""
      val tmpClass = Json.parse(json).as[TempClass]
      println(tmpClass)
    }

  }


Q:

What is this succulent with pointy leaves that seeds constantly fall from?

I'm trying to identify this succulent I got from a friend. It spreads in two ways:
- Sometimes a stalk will tip to the side, and then sprout roots downward to creep along. One of the photos below documents this.
- More often, though, seeds form along the edge of the leaf, drop to the ground, and start new plants.
From my findings so far, the best I can figure is that it's some sort of kalanchoe - but I'm not entirely sure about that.
Other info:
- Leaf parings alternate: one pair will be front and back, and the next will be left and right
- the leaf edges are serrated, and bear a thin red line along them
- I'm growing it inside, in a pot. It loves direct sunlight most of the day, and is thriving near windows
- I water it weekly, allowing it to completely dry between waterings. It seems quite happy with this arrangement.

A:

From your description of 'seeds' falling from the edges of the leaves, and the plant's general appearance, its likely Kalanchoe daigremontiana (now called Bryophyllum daigremontianum), image here
http://davesgarden.com/guides/pf/showimage/166243/
Common names include Mother of Thousands, Mother of Hundreds, Mexican Hat plant. Care information here
http://www.gardeningknowhow.com/houseplants/kalanchoe/growing-mother-of-thousands.htm


Q:

Массив. Помогите с ошибками в коде

#include <stdio.h>
#include <time.h>
#include <stdlib.h>

#define N 12

int main()
{
    int min, i_min = 0;
    double Z[N], aver = 0;
    srand(time(0));
    for (unsigned i = 0; i < N; ++i)
        Z[i] = rand() % 201 - 100;

    for (unsigned i = 0; i < N; ++i)
    {
        if (Z[i] < Z[i_min])
            i_min = i;
        if (Z[i] < 0)
            aver += Z[i];
    }
    aver = -aver / N;

    printf("minimal element = %.2lf\nabsolute value of average by negative elements = %.2lf\n\nZ array = [", Z[i_min], aver);
    for (unsigned i = 0; i < N; ++i)
        printf("%.2lf  ", Z[i]);
    printf("]\n\nResult array = [");

    Z[i_min] = aver;
    for (unsigned i = 0; i < N; ++i)
        printf("%.2lf  ", Z[i]);
    printf("]\n");

    getchar();

    return 0;
}

Минимальный элемент заданного массива Z (12) заменить абсолютному значению среднего арифметического всех отрицательных элементов этого массива. вывести минимальный элемент, среднее арифметическое, начальный и превращен массивы.

Сделал на DevC++, нужно написать на обычной Си
Выдает такие ошибки
[Error] subscripted value is neither array nor pointer nor vector [Error] conflicting types for 'i' [Note] previous declaration of 'i' was here [Error] 'for' loop initial declarations are only allowed in C99 or C11 mode

A:

Судя по ошибке, у вас старый стандарт C, когда ещё переменные нормально в цикле объявить нельзя было. Если это ожидаемо, то уберите unsigned из циклов и в самом начале программы добавьте unsigned i = 0;, если же нет, то найдите в DevC++ настройку, изменяющую флаги компиляции, и используйте стандарт C11. Вот тут есть с картинками, как это сделать https://stackoverflow.com/q/16951376/13970074 (только вместо стандартов С++ выбирайте С стандарты)


Q:

Use of main.rs and lib.rs in single project, can not import modules in library without lib folder

Although there are some questions related to this but all seems confusing to me.
I have a project with below structure.

When import cli module in main.rs it works properly but when I tried to do same in lib.rs I get below error
  = help: name the file either lib/cli.rs or lib/cli/mod.rs inside the directory "src"

but I want to keep it inside cli folder because I will have to add more code in cli folder.
why is cargo asking me to create lib folder ?
below is my toml file.
[package]
name = "feline"
version = "0.0.1"
license = "MIT"
authors = ["Akshay Naik <inbox.akshaynaik@gmail.com>"]
edition = "2018"

[dependencies]
smol = { version = "0.1", features = ["tokio02"] }
futures = "0.3.4"
clap = "~2.27.0"

Update: Thea goal is move all logic to lib.rs and call single function  from main.rs
Code:
https://github.com/nakshay/feline/tree/lib-use/src

A:

removing line mod lib; and calling feline::start() solved the issue,
I got my answer on rustlang forum. the line.
"When you use the mod keyword, you are creating a module, not importing a module" was an eye opener.
see the full answer by visiting below link.
https://users.rust-lang.org/t/main-rs-and-lib-rs-at-same-level/42499


Q:

Android AlertDialog.Builder justify text

Is there a way to justify the text in an AlertDialog?
Something like this for a TextBox since Oreo:
textView.setJustificationMode(JUSTIFICATION_MODE_INTER_WORD);

I need same behaviour for a typical dialog like this:
AlertDialog.Builder builder = new AlertDialog.Builder(Context);
builder.setMessage("Long text to be justified");
builder.setPositiveButton("OK", null);
Dialog d = builder.create();
d.show();

A:

Here is a trick to justify text in textview
Use a custom dialog
then use this custom textview in in your dialog xml
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.text.Layout;
import android.text.StaticLayout;
import android.text.TextPaint;
import android.util.AttributeSet;
import android.widget.TextView;

/**
 * @author ccheng
 * @Date 3/18/14
 */
public class JustifyTextView extends TextView {

    private int mLineY;
    private int mViewWidth;
    public static final String TWO_CHINESE_BLANK = "  ";

    public JustifyTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        TextPaint paint = getPaint();
        paint.setColor(getCurrentTextColor());
        paint.drawableState = getDrawableState();
        mViewWidth = getMeasuredWidth();
        String text = getText().toString();
        mLineY = 0;
        mLineY += getTextSize();
        Layout layout = getLayout();

        // layout.getLayout()在4.4.3出现NullPointerException
        if (layout == null) {
            return;
        }

        Paint.FontMetrics fm = paint.getFontMetrics();

        int textHeight = (int) (Math.ceil(fm.descent - fm.ascent));
        textHeight = (int) (textHeight * layout.getSpacingMultiplier() + layout.getSpacingAdd());

        for (int i = 0; i < layout.getLineCount(); i++) {
            int lineStart = layout.getLineStart(i);
            int lineEnd = layout.getLineEnd(i);
            float width = StaticLayout.getDesiredWidth(text, lineStart, lineEnd, getPaint());
            String line = text.substring(lineStart, lineEnd);
            if (needScale(line) && i < layout.getLineCount() -1) {
                drawScaledText(canvas, lineStart, line, width);
            } else {
                canvas.drawText(line, 0, mLineY, paint);
            }
            mLineY += textHeight;
        }
    }

    private void drawScaledText(Canvas canvas, int lineStart, String line, float lineWidth) {
        float x = 0;
        if (isFirstLineOfParagraph(lineStart, line)) {
            String blanks = "  ";
            canvas.drawText(blanks, x, mLineY, getPaint());
            float bw = StaticLayout.getDesiredWidth(blanks, getPaint());
            x += bw;

            line = line.substring(3);
        }

        int gapCount = line.length() - 1;
        int i = 0;
        if (line.length() > 2 && line.charAt(0) == 12288 && line.charAt(1) == 12288) {
            String substring = line.substring(0, 2);
            float cw = StaticLayout.getDesiredWidth(substring, getPaint());
            canvas.drawText(substring, x, mLineY, getPaint());
            x += cw;
            i += 2;
        }

        float d = (mViewWidth - lineWidth) / gapCount;
        for (; i < line.length(); i++) {
            String c = String.valueOf(line.charAt(i));
            float cw = StaticLayout.getDesiredWidth(c, getPaint());
            canvas.drawText(c, x, mLineY, getPaint());
            x += cw + d;
        }
    }

    private boolean isFirstLineOfParagraph(int lineStart, String line) {
        return line.length() > 3 && line.charAt(0) == ' ' && line.charAt(1) == ' ';
    }

    private boolean needScale(String line) {
        if (line == null || line.length() == 0) {
            return false;
        } else {
            return line.charAt(line.length() - 1) != '\n';
        }
    }

}


Q:

Inequality : $\sum_{cyc}\Big(\frac{x^4}{8x^3+5y^3}\Big)^3\geq \frac{x^3+y^3+z^3}{13^3}$

It's related to this Olympiad Inequality $\sum\limits_{cyc} \frac{x^4}{8x^3+5y^3} \geqslant \frac{x+y+z}{13}$:

$x,y,z >0$, prove
  $$\Big(\frac{x^4}{8x^3+5y^3}\Big)^3+\Big(\frac{y^4}{8y^3+5z^3}\Big)^3+\Big(\frac{z^4}{8z^3+5x^3}\Big)^3 \geqslant \frac{x^3+y^3+z^3}{13^3}$$

The inequality is equivalent to :
$$x^3\Big(\frac{1}{8+5(\frac{y}{x})^3}\Big)^3+y^3\Big(\frac{1}{8+5(\frac{z}{y})^3}\Big)^3+z^3\Big(\frac{1}{8+5(\frac{x}{z})^3}\Big)^3 \geqslant \frac{x^3+y^3+z^3}{13^3}$$
Or :
$$\frac{x^3\Big(\frac{1}{8+5(\frac{y}{x})^3}\Big)^3+y^3\Big(\frac{1}{8+5(\frac{z}{y})^3}\Big)^3+z^3\Big(\frac{1}{8+5(\frac{x}{z})^3}\Big)^3}{x^3+y^3+z^3} \geqslant \frac{1}{13^3}$$
Now we apply the Jensen's inequality to the function $f(x)=\frac{1}{(8+5x)^3}$ wich is clearly convex we get :
$$\frac{x^3 f((\frac{y}{x})^3)+y^3 f((\frac{z}{y})^3)+z^3 f((\frac{x}{z})^3)}{x^3+y^3+z^3} \geqslant f\Big(\frac{x^3 (\frac{y}{x})^3+y^3 (\frac{z}{y})^3+z^3 (\frac{x}{z})^3}{x^3+y^3+z^3}\Big)=\frac{1}{13^3}$$
And we are done .
My question is have you an nice alternative proof ?
Thanks a lot for your time .

A:

By Holder
$$\sum_{cyc}\left(\frac{x^4}{8x^3+5y^3}\right)^3\left(\sum_{cyc}(8x^3+5y^3)\right)^3\geq(x^3+y^3+z^3)^4.$$
Thus, it's enough to prove that
$$(x^3+y^3+z^3)^4\geq\frac{x^3+y^3+z^3}{13^3}\cdot\left(\sum_{cyc}(8x^3+5y^3)\right)^3,$$ which is an equality.


Q:

Creating a has_and_belongs_to_many relationship in Rails

I have a User model which is designed after the Michael Hartl RoR tutorial and I am trying to create a new Teacher model. I would like the teacher to have many users but each user to have only one teacher. I created the teacher model with
class CreateTeachers < ActiveRecord::Migration
  def change
    create_table :teachers do |t|
      t.string :name
      t.string :email
      t.string :phone
      t.references :user, index: true, foreign_key: true

      t.timestamps null: false
    end
  end
end

and added has_one :teacher to user.rb. Here is the teachers.rb model
class Teacher < ActiveRecord::Base
  has_and_belongs_to_many :users
  validates :user_id, presence: true
  before_save   :downcase_email
  validates :name, presence: true,
                 length: { maximum: 50 }
  VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-]+(\.[a-z\d\-]+)*\.[a-z]+\z/i
  validates :email, presence:   true,
                    length: { maximum: 255 },
                    format:     { with: VALID_EMAIL_REGEX },
                    uniqueness: { case_sensitive: false }
  private

    # Converts email to all lower-case.
    def downcase_email
      self.email = email.downcase
    end
end

However in my teacher_test.rb test file, things get a little fuzzy. I try this
def setup
  @user = users(:michael)
  @user2 = users(:archer)
  @user3 = users(:lana)
  @user4 = users(:mallory)

  @teacher = Teacher.new(name: "Phred Willard",
                         email: "pwillard@test.com",
                         phone: "1234567890",
                         user_id: [@user.id,
                                   @user2.id,
                                   @user3.id,
                                   @user4.id])
end

test "should be valid" do
  assert @uac.valid?
end

but that fails outright. Did I set my relationship up correctly? I obviously am not adding users correctly since the model fails a validity test. How would I add more users to that teacher? Thanks in advance.

A:

I would like the teacher to have many users but each user to have only one teacher

You only need has_many / belongs_to...
#app/models/user.rb
class User < ActiveRecord::Base
   belongs_to :teacher
end

#app/models/teacher.rb
class Teacher < ActiveRecord::Base
   has_many :users
end

You'll need to add a teacher_id column in your users table (the opposite of what you have now):
class UpdateUsers < ActiveRecord::Migration
  def change
    change_table :users do |t|
      t.references :teacher, index: true, foreign_key: true #-> teacher_id
    end
  end
end

--
The error you have is that you're calling user_id on teacher; it should be teacher_id on user:
@teacher = Teacher.new(name: "Phred Willard",
                     email: "pwillard@test.com",
                     phone: "1234567890",
                     user_ids: [@user.id,
                               @user2.id,
                               @user3.id,
                               @user4.id])

This should associate @teacher with the defined @users you've listed.
You'll also want to look at collection_singular_ids for the has_many association, which is why your test is failing.


Q:

javascript SOAP xmlhttprequest issue mobile

All right, so previously I asked...
SOAP Prototype AJAX SOAPAction Header Question (can't hyperlink it unfortunately, not enough rep for "2" links... see below)
Which never worked out.  I think it has something to do with Prototype, it will return a 0 as onSuccess.  I can't figure out the Content-type utf-8 formatting.  Now if I go back to straight javascript and use xmlhttprequest
<html xmlns="http://www.w3.org/1999/xhtml">

    function getUVIndex() {
        // In Firefox, we must ask the user to grant the privileges we need to run.
        // We need special privileges because we're talking to a web server other
        // than the one that served the document that contains this script. UniversalXPConnect
        // allows us to make an XMLHttpRequest to the server, and
        // UniversalBrowserRead allows us to look at its response.
        // In IE, the user must instead enable "Access data sources across domains"
        // in the Tools->Internet Options->Security dialog.
        if (typeof netscape != "undefined") {
            netscape.security.PrivilegeManager.
                    enablePrivilege("UniversalXPConnect UniversalBrowserRead");
        }
        // Create an XMLHttpRequest to issue the SOAP request. This is a utility
        // function defined in the last chapter.
        var request = new XMLHttpRequest();
        // We're going to be POSTing to this URL and want a synchronous response
        request.open("POST", "http://iaspub.epa.gov/uvindexalert/services/UVIndexAlertPort?wsdl", false);

        request.onreadystatechange=function() {
                if (request.readyState==4) {
                    var index = request.responseXML.getElementByTagName('index')[0].firstChild.data;
                    alert(request.responseText);
                }
            }
        // Set some headers: the body of this POST request is XML
        request.setRequestHeader("Content-Type", "text/xml");
        // This header is a required part of the SOAP protocol
        request.setRequestHeader("SOAPAction", '""');
        // Now send an XML-formatted SOAP request to the server
        request.send(
            '<?xml version="1.0" encoding="utf-8"?>' +
            '<soap:Envelope' +
            ' xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"' +
            ' xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/"' +
            ' xmlns:tns="urn:uvindexalert" xmlns:types="urn:uvindexalert/encodedTypes"' +
            ' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"' +
            ' xmlns:xsd="http://www.w3.org/2001/XMLSchema">' +
            '  <soap:Body soap:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">' +
            '    <tns:getUVIndexAlertByZipCode>' +
            '       <in0 xsi:type="xsd:string">12306</in0>' +
            '   </tns:getUVIndexAlertByZipCode>' +
            '  </soap:Body>' +
            '</soap:Envelope>'

            );
        // If we got an HTTP error, throw an exception
        if (request.status != 200) throw request.statusText;

        //return request.responseXML.childNodes[0].childNodes[1].childNodes[3].childNodes[5].textContent;
    }

    getUVIndex();
</script>

This never calls the onreadystatechange.  If you uncomment the
return request.responseXML.childNodes[0].childNodes[1].childNodes[3].childNodes[5].textContent;
It will retrieve the value needed and if you are in Firebug you will see the readyState == 4 and status == 200 (not that I check for that).  I usually never need to be spoon fed but I just don't understand why I am not getting the values back I need from the listener, or why it is never called.  Also, not that this should matter really but I am approving the request on Firefox to be cross-domain, it is really for mobile so the call will not need to be have a confirmation of cross-domain, it will do that automatically.
I hope someone can look at this and see what I overlooked.  Thanks!

A:

onreadystatechange will only be called for asynchronous requests to the server, your code is sending a synchronous request.
Set the third parameter on the open call to true (or remove the third parameter as default is true).
request.open("POST", "http://iaspub.epa.gov/uvindexalert/services/UVIndexAlertPort?wsdl", true);

http://msdn.microsoft.com/en-us/library/ms536648(VS.85).aspx


Q:

What is the topology of $[0,1]$ in the definition of homotopy?

Here I am not asking that it is the subspace topology which it gets from real line. My main question is that what is the topology on real line (usual, discrete, ...) which gives a subspace topology on $[0,1]$.
In my view it should be discrete in the case of homotopy as each function at some particular "$t$" (singleton) is continuous, which is open in only discrete topology.
Please explain with some examples.

A:

In the definition of homotopy, the topology on $[0,1]$ is the usual topology.  If
$$
H:X \times [0,1] \to Y
$$
is a continuous map, then the maps $H(\cdot ,t)$ for fixed values $t \in [0,1]$ are necessarily continuous.  To see that this is the case, note that under the usual topology on $[0,1]$ and the usual product topology on $X \times [0,1]$, the "inclusion" $\iota_t: X \to X \times [0,1]$ defined by $\iota_t(x) = (x,t)$ is continuous for any $t \in [0,1]$.  As such, $p_t(x) = H(x,t)$ defines a continuous map from $X$ to $Y$ since it can be written as the composition
$$
p_t = H \circ \iota_t.
$$


Q:

Javascript how to do substring global replacement with specific rule applied

I want a function which can replace substring in a big string with specific rule.
for example, I want every digit for pageX in the string increase by 10.
function replace(str, increment){}

doreplace("pageX : 100, pageY: 200,......pageX : 120...", 10)
will get "pageX : 110, pageY: 200,......pageX : 130..."
I know that like string.replace(/pageX :/g,someStr) can do replaceAll, but no rule can be applied.
How can I get that?

A:

How about using replace function callback:
var string = "pageX : 100, pageY: 200,......pageX : 120...";
string = string.replace(/(\d+)/g, function(match, contents) {
    return (+contents + 10);
});
console.log(string);

DEMO: http://jsfiddle.net/ytptN/


Q:

How to convert multiple lists to dictionaries in python?

['*a*', '*b*', '*c*', '*d*', '*f*','*g*']
['11', '22', '33', '44', '', '55']
['66', '77', '88', '', '99', '10']
['23', '24', 'sac', 'cfg', 'dfg', '']

need to put in dictionary as:
{a : ('11','66','23'),b : ('22','77','24'),c : ('33','88','sac'),d :('44','','cfg')}

The rows are read from a CSV file:
import csv
csvFile = csv.reader(open("sach.csv", "rb"))
for row in csvFile:
    print row

code which is tried shown above,
The output of row is shown above which has many lists.
please help me to put it in dictionary format as shown above.

A:

Zip the rows:
with open("sach.csv", "rb") as csv_infile:
    reader = csv.reader(csv_infile)
    yourdict = {r[0].replace('*', ''): r[1:] for r in zip(*reader)}

The zip() function does the pairing for you, by passing in the reader object with the * argument Python will loop over the CSV rows and pass each row as a separate argument to zip().


Q:

How to add icon_date and icon_time?

How do I add icon_date and icon_time like in the transaction SM37 (selection screen in block job start condition)
I am trying this
    SELECTION-SCREEN BEGIN OF BLOCK blk_1 WITH FRAME TITLE text-001.
    SELECTION-SCREEN BEGIN OF LINE.
    SELECTION-SCREEN COMMENT 1(8) G_DATE FOR FIELD p_sdate .
    SELECTION-SCREEN POSITION 25.
    PARAMETERS: p_sdate      TYPE sy-datum.
    SELECTION-SCREEN END OF LINE.
    SELECTION-SCREEN END OF BLOCK blk_1.

    ////////////////////////////////////////////
    INITIALIZATION.
     CONCATENATE TEXT-003 ICON_TIME INTO G_TIME
                    SEPARATED BY SPACE.                    " Text-003 = 'Date'

//////////////////////////////////////////////
Output => To @1T@

A:

There are a number of issues in your code:

Your comment variable is named G_DATE, but you're writing to G_TIME.
You're trying to assemble the text for yourself instead of using the standard function.
Your variable G_DATE is too short to store the complete formatted icon and text.

Try this:
SELECTION-SCREEN BEGIN OF LINE.
SELECTION-SCREEN COMMENT 1(60) g_date FOR FIELD p_sdate VISIBLE LENGTH 8.
SELECTION-SCREEN POSITION 25.
PARAMETERS p_sdate TYPE sy-datum.
SELECTION-SCREEN END OF LINE.

INITIALIZATION.
  CALL FUNCTION 'ICON_CREATE'
    EXPORTING
      name       = 'ICON_DATE'
      text       = 'Date'
      info       = 'da date, man'
      add_stdinf = ' '
    IMPORTING
      result     = g_date.


Q:

How to find url parameter # with value in javascript

I need to find url parameter # with value in javascript.
my url is like:

http://rohitazad.com/wealth/tax/how-to-file-your-income-tax-return/newslist/34343443.cms?intenttarget=no&utm_source=newsletter&utm_medium=email&utm_campaign=ETwealth&type=wealth#sid53239948&ncode=23432kjk#%kjimwer

i want to find this value #sid53239948
I find this How can I get query string values in JavaScript?
but how to find this value in url?

A:

EDIT:
This will filter the sid into the sid-variable wherever you put your hash.
var url_arr = window.location.hash.split('&'),
    sid = '';

url_arr.filter(function(a, b) {
    var tmp_arr = a.split('#')
    for (var i in tmp_arr)
        if (tmp_arr[i].substring(0, 3) == 'sid')
            sid = tmp_arr[i].substring(3, tmp_arr[i].length)
});

console.log(sid) // Will output '53239948'

Old answer:
var hash_array = window.location.hash.split('#');
hash_array.splice(0, 1);
console.log(hash_array);


Q:

HABTM - uniqueness constraint

I have two models with a HABTM relationship - User and Role.

user - has_and_belongs_to_many :roles
role - belongs_to :user

I want to add a uniqueness constraint in the join (users_roles table) that says the user_id and role_id must be unique.  In Rails, would look like:
validates_uniqueness_of :user, :scope => [:role]

Of course, in Rails, we don't usually have a model to represent the join relationship in a HABTM association.
So my question is where is the best place to add the constraint?

A:

You can add uniqueness to join table
add_index :users_roles, [ :user_id, :role_id ], :unique => true, :name => 'by_user_and_role'

see In a join table, what's the best workaround for Rails' absence of a composite key?
Your database will raise an exception then, which you have to handle.
I don't know any ready to use rails validation for this case, but you can add your own validation like this:
class User < ActiveRecord::Base
has_and_belongs_to_many :roles, :before_add => :validates_role

I would just silently drop the database call and report success.
def validates_role(role)
  raise ActiveRecord::Rollback if self.roles.include? role
end

ActiveRecord::Rollback is internally captured but not reraised.
Edit
Don't use the part where I'm adding custom validation. It kinda works but there is better alternatives.
Use :uniq option on association as @Spyros suggested in another answer:
class Parts < ActiveRecord::Base
  has_and_belongs_to_many :assemblies, :uniq => true, :read_only => true
end

(this code snippet is from Rails Guides v.3). Read up on Rails Guides v 3.2.13 look for 4.4.2.19 :uniq
Rails Guide v.4 specifically warns against using include? for checking for uniqueness because of possible race conditions.
The part about adding an index to join table stays.

A:

In Rails 5 you'll want to use distinct instead of uniq
Also, try this for ensuring uniqueness
has_and_belongs_to_many :foos, -> { distinct } do
  def << (value)
    super value rescue ActiveRecord::RecordNotUnique
  end
end

A:

I think that using :uniq => true would ensure that you get no duplicate objects. But, if you want to check on whether a duplicate exists before writing a second one to your db, i would probably use find_or_create_by_name_and_description(...).
(Of course name and description are your column values)


Q:

Unhandled exception in my modified code

I am writing a POS system for HW, and I had to take my first code which used hundreds of variables and change it into a more compact program using arrays. This is my new code:
    #include <stdlib.h>
    #include <stdio.h>
    #include <conio.h>

//---------------------------------------------------------------------------------------------------------
//---------------------------------------------------------------------------------------------------------
//------------------------------------------Declaring-Variables--------------------------------------------
//---------------------------------------------------------------------------------------------------------
//---------------------------------------------------------------------------------------------------------

//Discount Variables
int iPerPurchaseDiscountPercent = 0; //enter a number which will be later changed to a percentage
int iFinalPurchaseDiscountPercent = 0;//enter a number which will be later changed to a percentage
float fPerPurchaseDiscountPercent = 0;//the percentage value of discount per item
float fFinalPurchaseDiscountPercent = 0;//percentage value of final dicount
float fPerPurchaseDiscountPrice = 0;//price at which discounts will be applied
float fFinalPurchaseDiscountPrice = 0;//price at which the final shop discount will be appled

//Array values for math
float fItemPrice[100] = { 0 }; //Price of Item
int   iItemQuantity[100] = { 0 }; //Quantity of that Item
float fBundleCost[100] = { 0 }; //Price before Discounts (fItemPrice[N] * fItemQuantity[N])
float fDiscountPerItem[100] = { 0 }; //What discount is recieved per item (fItemPrice[N] * iPerPurchaseAmount)
float fItemTotalDiscountRecieved[100] = { 0 }; //Total discount recieved on multiple items of same type (fDicountPerItem * iItemQuantity)
float fDiscountPrice[100] = { 0 };//Price for item after all discounts (fBundleCost - fDiscountRecieved)

//Values for while loop
bool bStillShopping = true;
int iItemCount = 0;
char cExitQuestion = 'y';

//---------------------------------------------------------------------------------------------------------
//---------------------------------------------------------------------------------------------------------
//-----------------------------------------------Prototyping-----------------------------------------------
//---------------------------------------------------------------------------------------------------------
//---------------------------------------------------------------------------------------------------------

//---------------------------------------------------------------------------------------------------------
//---------------------------------------------------------------------------------------------------------
//------------------------------------------------Main-Loop------------------------------------------------
//---------------------------------------------------------------------------------------------------------
//---------------------------------------------------------------------------------------------------------
int main(void)
{
printf("Welcome to Blacketts bookstore!\t\t\t\t\t\tPOS V2\n");

//Taking values for the per item discounts
printf("Please enter the price that discounts per item will be applied: ");
flushall();
scanf("%f", &fPerPurchaseDiscountPrice); //takes the value at which items will be discounted
printf("Please enter the percentage to be applied at this price: ");
flushall();
scanf("%d", &iPerPurchaseDiscountPercent); //takes a value eg 10 to be later changed to .1 for 10%
fPerPurchaseDiscountPercent = iPerPurchaseDiscountPercent/100; //changes the int to a float and makes it appropriate for percentage calculations

//Taking values for the final purchase discount
printf("Please enter the price that end of sale discounts will be applied to: ");
flushall();
scanf("%f", &fFinalPurchaseDiscountPrice); //takes the value at which the whole docket will be discounted by
printf("Please enter the percentage to be applied at this price: ");
flushall();
scanf("%d", &iFinalPurchaseDiscountPercent);//takes a value eg 5 to be later changed to .05 for 5%
fFinalPurchaseDiscountPercent = iFinalPurchaseDiscountPercent/100; //changes the int to a float and make it appropriate for percentage calculations

//While loop to take values and input them into appropriate places
while(bStillShopping == true)
{
    iItemCount = 1; // Counting how many items are being purchased, 0 = 1st item. therefore Total quantity Items must equal iItemCount+1

    printf("\nPlease enter the price of the first item to be purchased: "); //enter price of item
    flushall();
    scanf("%.2f", fItemPrice[iItemCount]);

    printf("Please enter the quantity of that item: "); //enter quantity
    flushall();
    scanf("%d", iItemQuantity[iItemCount]);

    printf("\nWould you like to enter any more Items? (y/n): "); //ask to continue
    flushall();
    scanf("%c", &cExitQuestion);

    if(cExitQuestion == 'n')
    {
        bStillShopping = false; //if dont want to continue exit the loop
    }
    else
    {
        iItemCount++; //if do continue increment item loop and ask for more variables
    }
}

getch();
}

When I get to inputting the quantity at iItemQuantity[iItemAmout] it will crash the program with an unhandled exception. I also did some debugging print statements inbetween code to see where it gets to and output what variables I inputed and the returned values did not match up, all I received were 0.00.
Help would be much appreciated and I hope I am not asking an already answered question somewhere else. Still don't really know how to navigate the site.
I know the code does not do anything else at present time but I do not see the point in continuing until the first problems are corrected.

A:

The problem is that scanf expects pointers to the values, not the actual values themselves. You do it correctly before the loop, but not for the input inside the loop.
Change e.g.
scanf("%.2f", fItemPrice[iItemCount]);

to
scanf("%.2f", &fItemPrice[iItemCount]);

or
scanf("%.2f", fItemPrice + iItemCount);

Do the same for all input.


Q:

Is Selenium the right tool for browser compatibility testing?

I have been seeing a lot of customers pushing for browser compatibility testing using Selenium. Was wondering whether this is really necessary. The push is mostly due to Selenium grid supporting multi browser test execution in parallel.
As per my knowledge, Selenium is mostly a functional testing tool. So any issue that you find using Selenium will be across all the browsers. What additional value does it have if we find that the same issue exists in multiple browsers?
Or is there a better way in which Selenium can be used for compatibility testing?

A:

Selenium solves a large part of cross browser testing. 90% I would say. Selenium is good for web testing across browsers. For UI related stuff adhoc manual checks are sufficient. I used to do manual checks to verify look and feel of UI (Text Sizes appearing small in a browser, Alignment Issues)
Functional UI testing in selenium across browsers verifies Id's exists in the UI, workflows-functionality are fine across browsers. Selenium cannot detect layout issues. You can custom code in selenium to detect java script errors.
There were few tools that I got based on my earlier question on layout bugs. Below tools you can use for Layout related checks and adhoc UI testing

Free Google tool: Fighting Layout Bugs
Useful Tools for Testing Cross Browser Compatibility
Browsera is dedicated provider dealing with cross browser testing
Top 10 Free Web Apps to Test Cross-Browser Compatibility

A:

Selenium is mostly a functional testing tool. So any issue that you find using selenium will be across all the browsers

No, that's not actually the case. Some functionality can be broken in some browsers while working in others.
For example, for one of the apps I test, I've seen significant functionality issues going from IE 6 to IE 7 to IE 8.

A:

Automated, parallelized, cross-browser testing is a seductive idea, but in my experience, the cost may not justify the benefit.  I do not know whether your customer requests are based on actual experience or the advice of a trusted professional or the unfounded claims of someone in an elevator.
You may spend a lot of time maintaining your cross-browser tests.  Even if you do not change your product, today's tests may work with today's browsers and break with next week's browsers.  If you decide to leverage Selenium Grid, expect to spend a significant amount of time upgrading to new versions of Selenium and diagnosing whether the latest bug is in your test, in Selenium, or in your product.  (Of course the bug may also be in the browser, but that is outside of your control.)
As @Siva mentioned, even if your functional tests run perfectly, you still have not verified browser-compatibility.  No matter what, you still need to test manually.
You have a limited testing budget.  The time you spend maintaining your cross-browser tests is time you cannot spend testing in other ways.
Still, your experience may be different from mine.  I recommend approaching automated cross-browser tests as a limited-scope pilot project.  Automate just part of the app and observe how much effort you spend keeping it running as the product changes and new browser versions are released.  If you are satisfied with the expense, you can leverage technology more aggressively; or if you decide the benefit just not justify the cost, you can throw it away and think about something else.


Q:

How can i convert for loop to AngularJs forEach?

I am new to JavaScript world just want to clarify this because i am using AngularJs client side.Below code is working as expected but question is,Is there a way to achieve below result with Angular loop forEach ?
ctrl.js
for (var i = 0; i < selectedOwners.length; i++) {
    if (selectedOwners[i].workerKey === obj.workerKey) {
        selectedOwners.splice(i, 1);
        break;
    }
}

A:

This should work:
angular.forEach(selectedOwners, function(owner, $index) {
    if (owner.workerKey === obj.workerKey) {
        selectedOwners.splice($index, 1);
        break;
    }
});


Q:

Fast array as argument passing in MATLAB

I have a matrix I, and I want to accumulate in an array A, for each value in I, an interval accordingly to those values in I lets call them i and j.
function acc(i,j)
  global A
  A(i:j) = A(i:j)+1;
end

However, passing and returning the arrays take too much time, because I execute the function many times, and it is not as simple as that example.
Is there any way of speeding it up? How can I pass an return those values without global?

A:

The link in the comments proposes using a nested function as a solution.  If the function you're using has use in several different places you may not want to nest in each place.  It that case, I'd try to make the function modify in place.
http://blogs.mathworks.com/loren/2007/03/22/in-place-operations-on-data/
function A = acc(A,i,j)
  A(i:j) = A(i:j)+1;
end

This should not need to make a copy provided you meet the requirements set forth in Loren's blog post.


Q:

Forward of declarations not fixing incomplete type

Despite many questions similar to this I'm unable to find one that can answer such a simple query - however due to the volume you'll have to forgive me if I have missed it.
Within the following code, the following error is produced (using G++): 'error: field 'CompoundField' has incomplete type':
class SimpleClass;
class CompoundClass;

class CompoundClass{
    public:
    SimpleClass CompoundField;
};

class SimpleClass{
    public:
    unsigned int SimpleField;
};

int main(){
    CompoundClass obj;
    obj.CompoundField.SimpleField=5;
    return 0;
}

Why is this when both classes have been forward-declared? A straight forward solution is to just move the CompoundClass to after the SimpleClass, or make CompoundField a pointer to SimpleClass but that doesn't help explain the underlying issue here.
To be more precise, other answers indicate this is due to the compiler not knowing the size of the child class (i.e. SimpleClass), why is this when the size of SimpleClass could be found with relative ease?

A:

The compiler sees this
class SimpleClass;
class CompoundClass;

class CompoundClass{
    public:
    SimpleClass CompoundField;
};

It needs to figure out how much memory a CompoundClass requires (has not got a clue aboutSimpleClass memory requirement).
As it does not know how many ints, strings etc.. to make space for - it throws its hands up.
But if you did
class SimpleClass;
class CompoundClass;

class CompoundClass{
    public:
    SimpleClass *CompoundField;
};

Then it would know - just need a pointer (void * will suffice for all eventualities!)


Q:

scrapy - parsing multiple times

I am trying a parse a domain that whose contents are as follows

Page 1 - contains links to 10 articles
Page 2 - contains links to 10 articles
Page 3 - contains links to 10 articles  and so on...
My job is to parse all the articles on all pages.
My thought - Parse all the pages and store links to all the articles in a list and then iterate the list and parse the links.
So far I have been able to iterate through the pages, parse and collect links to the articles. I am stuck on how to start parsing this list.
My Code so far...
import scrapy

class DhoniSpider(scrapy.Spider):
    name = "test"
    start_urls = [
            "https://www.news18.com/cricketnext/newstopics/ms-dhoni.html"
    ]
    count = 0
    def __init__(self, *a, **kw):
        super(DhoniSpider, self).__init__(*a, **kw)
        self.headers= {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:48.0) Gecko/20100101 Firefox/48.0'}
        self.seed_urls = []

    def start_requests(self):
        for url in self.start_urls:
            yield scrapy.Request(url, headers=self.headers, callback=self.parse)

    def parse(self, response):
        DhoniSpider.count += 1
        if DhoniSpider.count > 2 :
            # there are many pages, this is just to stop parsing after 2 pages
            return
        for ul in response.css('div.t_newswrap'):
            ref_links = ul.css('div.t_videos_box a.t_videosimg::attr(href)').getall()
            self.seed_urls.extend(ref_links)

        next_page = response.css('ul.pagination li a.nxt::attr(href)').get()
        if next_page is not None:
            next_page = response.urljoin(next_page)
            yield scrapy.Request(next_page, headers=self.headers, callback=self.parse)

    def iterate_urls(self):
        for link in self.seed_urls:
            link = response.urljoin(link)
            yield scrapy.Request(link, headers=self.headers, callback=self.parse_page)

    def parse_page(self, response):
        print("called")

how to iterate my self.seed_urls list and parse them? From where should I call my iterate_urls function?

A:

Usually in this cases there is no need to make external function like your iterate_urls:
def parse(self, response):
    DhoniSpider.count += 1
    if DhoniSpider.count > 2 :
        # there are many pages, this is just to stop parsing after 2 pages
        return
    for ul in response.css('div.t_newswrap'):
        for ref_link in ul.css('div.t_videos_box a.t_videosimg::attr(href)').getall():
            yield scrapy.Request(response.urljoin(ref_link), headers=self.headers, callback=self.parse_page, priority = 5)

    next_page = response.css('ul.pagination li a.nxt::attr(href)').get()
    if next_page is not None:
        next_page = response.urljoin(next_page)
        yield scrapy.Request(next_page, headers=self.headers, callback=self.parse)

def parse_page(self, response):
    print("called")


Q:

Migration from PostreSQL to MySQL using MySQL Workbench trows errors

I am trying to migrate a PostreSQL database to a local MySQL server using MySQL Workbench. I have set both connections, tested them and succeded, selected schemas to migrate and clicked next.
However, it always ends up at Reverse engineer selected schemas, where it keeps getting some errors. The image(s) below shows them all.
I have found some suggestions to edit some files (db_postgresql_re_grt.py), but none of them worked (even after restarting MySQL Workbench).
PostgreSQL version is 8.1.23

Complete message log:

A:

It seems you found a bug in migration wizard. Please fill bug report, and (if you can) attach your database to it (you can make it private, that only Oracle employees can see it).