Q: Stream_get_contents() not working with Cron Job I have a script called index.php "public_html" folder in my host (see below for script content). A cronjob executes the "index.php" file once per minute.
$handle = fopen('example.com', 'r');
$source= stream_get_contents($handle);
echo $source;
fclose($handle);

The problem is every time "index.php" is executed using the cronjob, $source will be '' (an empty string)!
But when I manually execute index.php using Firefox and refreshing it's tab, $source will be a string including the html source codes of example.com
Is there any restriction settings in my web-host or somewhere else, preventing stream_get_contects() to log websites information?


Q: Windows Server 2003: Any disadvantages to moving website outside of wwwroot? My boss recently asked me if I could move our website outside of the wwwroot folder and place it into "C:\MySite", on windows server 2003.  I tried doing so, and setting this up in IIS 6, but had no luck.  The website wouldn't start up, so I placed the site back into wwwroot.
So I have 2 questions: One, is there any disadvantage to moving a website outside of the wwwroot folder?  I found it peculiar the site works fine in wwwroot, but won't start outside of it...and two, if there's no disadvantage, how can I get IIS to run the website properly if outside wwwroot?
Thanks.

A: Site can be anywhere, especially  on local machine. Check if

*

*you copied all files to new location

*you changed location of the root of the site in IIS Manager (Start->run->inetmgr)

*check event log for any errors

*check if accoutn app pool for the site runs under have permissions to read from new folder.

A: It is quite simple and easy. Follow the steps here: http://support.microsoft.com/kb/172138
or http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/5adfcce1-030d-45b8-997c-bdbfa08ea459.mspx?mfr=true


Q: In Rails, how do I output my date as a time in milliseconds in my CSV file? I'm using Rails 5.0.1.  I use the following code to output my table data to CSV form ...
  def self.to_csv(from_date, to_date)
    attributes = %w{index_date value} #customize columns here
    values = CryptoIndexValue.where('index_date >= ? and index_date <= ?', from_date, to_date)
                                     .order(index_date: :desc)

    CSV.generate(headers: true) do |csv|
      csv << attributes

      values.each do |value|
        csv << attributes.map{ |attr| value.send(attr) }
      end
    end
  end

The problem is, when my date (a PostGres 9.5 timestamp column) is output, it is output as
2017-08-01 20:00:09 UTC

I would like it to get output as the time in milliseconds.  How can I adjust the above to output my time as a time in milliseconds rather than the default date format?

A: You can simply call .to_i on a DateTime object:
timestamp = DateTime.now.to_i
# => 1501617998
DateTime.strptime(timestamp.to_s, '%s')
# => Tue, 01 Aug 2017 20:07:10 +0000

The timestamp is the seconds since Epoch. Multiply it by a thousand and you get milliseconds.
In your case, you must make a hook for this case:
attr_values = attributes.map do |attr|
  attr_value = value.send(attr)
  attr_value = attr_value.to_i * 1000 if attr_value.is_a?(DateTime)
  attr_value
end
csv << attr_values

This means everytime an attribute returns a DateTime object, it will be converted to a timestamp * 1000. If you want to filter only few attrs to convert DateTime -> Timestamp, test the attr with a whitelist instead of testing attr_value's class.


Q: what login should I keep for app (for appstore approval) I have created an app for Real estate where there are 4 sections.

*

*Home (where list of rent and sale are shown)

*Admin (admin can login and enter data)

*Search

*More
Now I will be uploading this app on the app store.
For Admin section, what username and password should I keep so that Apple team can login into those for review purpose. Once approved, I will delete that user.
Is there default username and password for Apple for review purpose?
I am asking as while submitting the app, I cannot write username and password anywhere so that we can tell to Review team.

A: You need to decide yourself what is the username and password you want Apple to use for review. When you submit the app or update the app, there is a section where you can supply those information, under App Review Information:


Q: Adding extenal library to compiler toolchain for ARM I have downloaded compiler tool chain for ARM Target.
My host machine: Linux
Target H/w : ARM7
But i need to add some additional library with that tool chain.
I need to know how to add new library to existing tool chain?
Thanks
Hari


Q: Custom Django field does not return Enum instances from query I have a simple custom field implemented to utilize Python 3 Enum instances. Assigning enum instances to my model attribute, and saving to the database works correctly. However, fetching model instances using a QuerySet results in the enum attribute being a string, instead of the respective Enum instance.
How do I get the below EnumField to return valid Enum instances, rather than strings?
fields.py:
from enum import Enum

from django.core.exceptions import ValidationError
from django.db import models

class EnumField(models.CharField):
    description = 'Enum with strictly typed choices'

    def __init__(self, enum_class, *args, **kwargs):
        self._enum_class = enum_class
        choices = []
        for enum in self._enum_class:
            title_case = enum.name.replace('_', ' ').title()
            entry = (enum, title_case)
            choices.append(entry)
        kwargs['choices'] = choices
        kwargs['blank'] = False  # blank doesn't make sense for enum's
        super().__init__(*args, **kwargs)

    def deconstruct(self):
        name, path, args, kwargs = super().deconstruct()
        args.insert(0, self._enum_class)
        del kwargs['choices']
        return name, path, args, kwargs

    def from_db_values(self, value, expression, connection, context):
        return self.to_python(value)

    def to_python(self, value):
        if value is None or isinstance(value, self._enum_class):
            return value
        else:
            return self._parse_enum(value)

    def _parse_enum(self, value):
        try:
            enum = self._enum_class[value]
        except KeyError:
            raise ValidationError("Invalid type '{}' for {}".format(
                value, self._enum_class))
        else:
            return enum

    def get_prep_value(self, value):
        if value is None:
            return None
        elif isinstance(value, Enum):
            return value.name
        else:
            msg = "'{}' must have type {}".format(
                value, self._enum_class.__name__)
            if self.null:
                msg += ', or `None`'
            raise TypeError(msg)

    def get_choices(self, **kwargs):
        kwargs['include_blank'] = False  # Blank is not a valid option
        choices = super().get_choices(**kwargs)
        return choices

A: After a lot of digging, I was able to answer my own question:
SubfieldBase has been deprecated, and will be removed in Django 1.10; which is why I left it out of the implementation above. However, it seems that what it does is still important. Adding the following method to replaces the functionality that SubfieldBase would have added.
def contribute_to_class(self, cls, name, **kwargs):
    super(EnumField, self).contribute_to_class(cls, name, **kwargs)
    setattr(cls, self.name, Creator(self))

The Creator descriptor is what calls to_python on attributes. If this didn't happen, querys on models would result in the EnumField fields in the model instances being simply strings, instead of Enum instances like I wanted.


Q: Flutter: How to draw a star I am trying to custom my container shape to look like this:

I tried to do it with customPaint but I don't know very well this widget so I need help.
How can I draw a shape like this? Is customPaint the right solution?

A: You can copy paste run full code below
modified code of package https://pub.dev/packages/flutter_custom_clippers 's
StarClipper https://github.com/lohanidamodar/flutter_custom_clippers/blob/master/lib/src/star_clipper.dart
code snippet
class StarClipper extends CustomClipper<Path>
 @override
   Path getClip(Size size) {
     ...
     double radius = halfWidth / 1.3;
...
Container(
      height: 200,
      width: 200,
      child: ClipPath(
        clipper: StarClipper(14),
        child: Container(
          height: 150,
          color: Colors.green[500],
          child: Center(child: Text("+6", style: TextStyle(fontSize: 50),)),
        ),
      ),
    ),

working demo

full code
import 'package:flutter/material.dart';
import 'dart:math' as math;

class StarClipper extends CustomClipper<Path> {
  StarClipper(this.numberOfPoints);

  /// The number of points of the star
  final int numberOfPoints;

  @override
  Path getClip(Size size) {
    double width = size.width;
    print(width);
    double halfWidth = width / 2;

    double bigRadius = halfWidth;

    double radius = halfWidth / 1.3;

    double degreesPerStep = _degToRad(360 / numberOfPoints);

    double halfDegreesPerStep = degreesPerStep / 2;

    var path = Path();

    double max = 2 * math.pi;

    path.moveTo(width, halfWidth);

    for (double step = 0; step < max; step += degreesPerStep) {
      path.lineTo(halfWidth + bigRadius * math.cos(step),
          halfWidth + bigRadius * math.sin(step));
      path.lineTo(halfWidth + radius * math.cos(step + halfDegreesPerStep),
          halfWidth + radius * math.sin(step + halfDegreesPerStep));
    }

    path.close();
    return path;
  }

  num _degToRad(num deg) => deg * (math.pi / 180.0);

  @override
  bool shouldReclip(CustomClipper<Path> oldClipper) {
    StarClipper oldie = oldClipper as StarClipper;
    return numberOfPoints != oldie.numberOfPoints;
  }
}

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      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> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Container(
              height: 200,
              width: 200,
              child: ClipPath(
                clipper: StarClipper(14),
                child: Container(
                  height: 150,
                  color: Colors.green[500],
                  child: Center(child: Text("+6", style: TextStyle(fontSize: 50),)),
                ),
              ),
            ),

          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}

A: I was trying to create Turkish flag for fun. Creating crescent was easy but creating star is not look easy. so I just tried to use my geometric and trigonometric knowledge to draw but no success. while continuing searching I encountered this link . Yeess I found what I look for. of course it was about different topic but functions was useful. so I reach my goal at the end of night.
So creating custom stars are possible with CustomPainter since now.  Because I m sleepy and tired of being awake whole night I share all of code block with no further explanation. You can adjust offsetts according to your need.  if any question. I m ready to answer. Enjoy coding.
 class TurkishFlagPaint extends CustomPainter {
      @override
      void paint(Canvas canvas, Size size) {
        // x and y coordinates of starting point

        final bx = 95;
        final by = 0;

        final paint = Paint();
        paint.color = Colors.white;
        final innerCirclePoints = 5; //how many edges you need?
        final innerRadius = 80 / innerCirclePoints;
        final innerOuterRadiusRatio = 2.5;
        final outerRadius = innerRadius * innerOuterRadiusRatio;

        List<Map> points =
            calcStarPoints(bx, by, innerCirclePoints, innerRadius, outerRadius);
        var star = Path()..moveTo(points[0]['x'], points[0]['y']);
        points.forEach((point) {
          star.lineTo(point['x'], point['y']);
        });

        canvas.drawPath(
          Path.combine(
            PathOperation.union,

            //this combine for crescent
            Path.combine(
              PathOperation.difference,
              Path()..addOval(Rect.fromCircle(center: Offset(-20, 0), radius: 80)),
              Path()
                ..addOval(Rect.fromCircle(center: Offset(2, 0), radius: 60))
                ..close(),
            ),
            star,// I also combine cresscent with star
          ),
          paint,
        );
      }

      //This function is life saver.
//it produces points for star edges inner and outer. if you need to //rotation of star edges.
// just play with - 0.3  value in currX and currY equations.

      List<Map> calcStarPoints(
          centerX, centerY, innerCirclePoints, innerRadius, outerRadius) {
        final angle = ((math.pi) / innerCirclePoints);
        var angleOffsetToCenterStar = 0;

        var totalPoints = innerCirclePoints * 2; // 10 in a 5-points star
        List<Map> points = [];
        for (int i = 0; i < totalPoints; i++) {
          bool isEvenIndex = i % 2 == 0;
          var r = isEvenIndex ? outerRadius : innerRadius;

          var currY =
              centerY + math.cos(i * angle + angleOffsetToCenterStar - 0.3) * r;
          var currX =
              centerX + math.sin(i * angle + angleOffsetToCenterStar - 0.3) * r;
          points.add({'x': currX, 'y': currY});
        }
        return points;
      }

      @override
      bool shouldRepaint(CustomPainter oldDelegate) => true;
    }

now you can use painter in a widget;
Center(
   child: CustomPaint(
       painter: TurkishFlagPaint(),
     ),
   ),

and the result will be like this :

A: Yes, CustomPaint is the right solution. You can calculate the Path (series of points around the Container) and then paint it with the drawPath method of the canvas.
For example, the path of a triangle would look like this:
return Path()
      ..moveTo(0, y)
      ..lineTo(x / 2, 0)
      ..lineTo(x, y)
      ..lineTo(0, y);

The Path starts at (0,y) (top-left), then a line to (x/2,0) (bottom-center) gets added and so on. This snipped was taken from this answer.

A: This code will help you build a centered star, to use it you just have to instantiate it in a ClipPath
import 'package:flutter/material.dart';
import 'dart:math' as math;

const STAR_POINTS = 5;

class StarClipper extends CustomClipper<Path> {
   @override
   Path getClip(Size size) {
   var centerX = size.width / 2;
   var centerY = size.height / 2;

   var path = Path();

   var radius = size.width / 2;
   var inner = radius / 2;
   var rotation = math.pi / 2 * 3;
   var step = math.pi / STAR_POINTS;

   path.lineTo(centerX, centerY - radius);

   for (var i = 0; i < STAR_POINTS; i++) {
    var x = centerX + math.cos(rotation) * radius;
    var y = centerY + math.sin(rotation) * radius;
    path.lineTo(x, y);
    rotation += step;

    x = centerX + math.cos(rotation) * inner;
    y = centerY + math.sin(rotation) * inner;
    path.lineTo(x, y);
    rotation += step;
  }

  path.lineTo(centerX, centerY - radius);
  path.close();

  return path;
 }

 @override
 bool shouldReclip(CustomClipper<Path> oldClipper) => false;
}

///  Instance
ClipPath(
 clipper: StarClipper(),
 child: Container(
    color: Colors.red,
    width: 80,
    height: 80,
    ),
)


Q: How to avoid file content repetition zipfile I need to compress multiple xml files and I achieved this with lxml, zipfile and a for loop.
My problem is that every time I re run my function the content of the compressed files are repeating (being appended in the end) and getting longer. I believe that it has to do with the writing mode a+b. I thought that by using with open at the end of the code block the files would be deleted and no more content would be added to them. I was wrong and with the other modes I do not get the intended result.
Here is my code:
def compress_package_file(self):
   bytes_buffer = BytesIO()
   with zipfile.ZipFile(bytes_buffer, 'w') as invoices_package:
       i = 1
       for invoice in record.invoice_ids.sorted('sin_number'):
           invoice_file_name = 'Invoice_' + invoice.number + '.xml'
           with open(invoice_file_name, 'a+b') as invoice_file:
               invoice_file.write(invoice._get_invoice_xml().getvalue())
               invoices_package.write(invoice_file_name, compress_type=zipfile.ZIP_DEFLATED)
           i += 1
   compressed_package = bytes_buffer.getvalue()
   encoded_compressed_file = base64.b64encode(compressed_package)

My xml generator is in another function and works fine. But the content repeats each time I run this function. For example if I run it two times, the content of the files in the compressed file look something like this (simplified content):
<?xml version='1.0' encoding='UTF-8'?>
<invoice xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="invoice.xsd">
    <header>
        <invoiceNumber>9</invoiceNumber>
    </header>
</facturaComputarizadaCompraVenta><?xml version='1.0' encoding='UTF-8'?>
<invoice xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="invoice.xsd">
    <header>
        <invoiceNumber>9</invoiceNumber>
    </header>
</facturaComputarizadaCompraVenta>

If I use w+b mode, the content of the files are blank.
How should my code look like to avoid this behavior?

A: I suggest you do use w+b mode, but move writing to zipfile after closing the invoice XML file.
From what you wrote it looks as you are trying to compress a file that is not yet flushed to disk, therefore with w+b it is still empty at time of compression.
So, try remove 1 level of indent for               invoices_package.write line (I can't format code properly on mobile, so can't post whole section).


Q: odbc_exec error with progress I am using Codeigniter Database Active Record (ODBC Driver). The application run well. But starting this day, there are error when trying to fetch data from Progress database (connected via odbc). The error message:

Severity: Warning  --> odbc_exec() [function.odbc-exec]: SQL error:
  [DataDirect][ODBC Progress OpenEdge Wire Protocol driver]Unexpected
  Network Error.  ErrNum = 10054, SQL state 08S01 in SQLExecDirect
  D:\xampp\htdocs\wavinet2-permana\system\database\drivers\odbc\odbc_driver.php
  153

Error is in odbc_exec command. When I try to fetch data without using Codeigniter Active Record, it work. Data fetched. Trying to var_dump($this->db_odbc->conn_id) it return Resource. Network error ? I try to set up LinkedServer on my SQLServer and run the query generated by ActiveRecord, it work, data fetched successfully.
I'm confuse, what is another posibilities that cause the error ?

A: First make  certain that you have started up your database properly. There is a fairly substantial thread that has what sounds like it may be your problem here: http://www.progresstalk.com/showthread.php?116855-102B-ODBC-connection-Problem
Also something else to look at if you are running over SSL:

Change the data source PacketSize setting. The correct setting is 32.
PacketSize=32
On Windows this will require a registry edit to make this change.

See: http://knowledgebase.progress.com/articles/Article/8500


Q: Windows XP USB HDD Failing to register MY sister's PC is failing to register the presence of USB HDD devices when connected to any USB socket. I'm debugging remotely, but apparently "nothing" happens.
She has connected iPods, printers, scanners, webcam, usb thumb drives, card readers, wireless network adapters all fine. Devices that draw power work from the rear sockets.
USB HDD not working from any socket.
The drives tried are borrowed (she wants to back up her work prior to re-formatting, borrowing drives off a friend) and work with no additional power supplies on other machines.
Any ideas where I should start debugging to find out what the problem is?
I have half a suspicion it's jut drive letter conflict, but, she isn't completely useless and says that no device detection bubbles appear or anything, everything else appears to work fine on the PC.
It's a home XPSP2 box, wondering if she's accidentally triggered an MS Security thing to stop people stealing data, but don't know where to start looking for that.
Thanks
Mike

A: The first thing I would do is ask her to try it on another computer to rule out a problem with the drive.
Also, check that the drive does not require an external power source in addition to the USB socket.


Q: How to avoid outside of request scope exception in silex application? After restructuring my silex1.2 application, I am now getting hit by:

exception 'RuntimeException' with message 'Accessed request service
  outside of request scope. Try moving that call to a before handler or
  controller.' in
  ../vendor/silex/silex/src/Silex/Application.php:150

I used to setup the appilcation's config this way:
$app = new Silex\Application();
$app->register(new ServiceControllerServiceProvider());
$app->register(new ConfigServiceProvider($configFile));
$fileFinder = new \Symfony\Component\Finder\Finder();
foreach ($fileFinder->in($configPath . 'country') as $file) {
   /* @var SplFileInfo $file */
    $app->register(new ConfigServiceProvider($file->getRealPath()));
}

I now wanted to replace the foreach loop by injecting a specific value which I get from the user's request. So I wanted to access $request->query->get('country'); yet I cannot since app['request'] is out of scope at that point.
I don't understand the error message, as in:

*

*When and why are request objects out of scope in silex?

*How am I supposed to move the call before handler and controllers when it is the very first thing I do on setting up my application?

Basically, I want to access request data early on on in order to get one value. How can I achieve that in order to bootstrap application accordingly?

A: You try to use Request before it is initialized, before $app->run().
You can manually initialize Request:
$app = new \Silex\Application();
$app['request'] = \Symfony\Component\HttpFoundation\Request::createFromGlobals();
.....
$app->run($app['request']);

or make lazy loading in service providers:
$app['object1'] = $app->share(function ($app) {
    return new Object1($app['request']->query->get('country'));
});
...

and somewhere in controller get these variable as $app['object1']


Q: Login page is not appearing when the session expires I have one project developed using codeigniter
In that when session expires I need to redirect to the login page.
controller file
//inherit the parent constructor
        parent::__construct();
    //check whether it is an ajax call or not
    if($this->input->is_ajax_request())
    {
        //check the session exist or not
        $status = $this->common_functions->verify_session('ajax_call');

        //if session doesnot exist
        if(! $status)
        {
            //return the json
            echo json_encode(array("session_timeout"=>"true", "msg"=>"
Session timed out.
 Please login once again."));

            //exit
            exit;
        }
    }
    else
    {
        //Initialize the private property
        $this->_section = '';

        //check the session exist or not
        $this->common_functions->verify_session();

    }

And in common function
I have the code to redirect into login page


Q: Google Auth Popup not working for React 17 App; Getting React warning is this why or how to fix? As shown in description, I am working on a React project and utilizing Firebase for Auth and popup is not firing but I think it might have to do with this warning from React. The warning I am getting from React is that Warning: Expected onClick listener to be a function, instead got a value of object type.
I have been researching this and trying to problem solve for 2 days. Any pointers would be greatly appreciated :) Thank you!!
Here is my Firebase Utils code for the auth:

const config = {
  My config info
};

firebase.initializeApp(config);

const provider = new firebase.auth.GoogleAuthProvider();
provider.setCustomParameters({ prompt: 'select_account' });
export const signInWithGoogle = () => auth.signInWithPopup(provider)
.then(function (result) {
}).catch(error => {
  console.log(error);
})

export default firebase;

Now my Custom Button Component in React 17

import React from 'react';
import './custom-button.styles.scss';

const CustomButton = ({children, isGoogleSignIn, ...otherProps}) => (
    <button
      className={`${isGoogleSignIn ? 'google-sign-in' : ''} custom-button`}
      {...otherProps}>
        {children}
    </button>
);

export default CustomButton;

Lastly my signin component in React

lass SignIn extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            email: '',
            password: ''
        }
    }

    handleSubmit = event => {
        event.preventDefault();

        this.setState({ email: '', password: '' })
    }

    handleChange = event => {
        const { value, name } = event.target;

        this.setState({ [name]: value })
    }

    render() {
        return (

I already have an account

            Sign in with your email and password

        <form onSubmit={this.handleSubmit}>
          <FormInput
            name='email'
            type='email'
            handleChange={this.handleChange}
            value={this.state.email}
            label='email'
            required
          />
          <FormInput
            name='password'
            type='password'
            value={this.state.password}
            handleChange={this.handleChange}
            label='password'
            required
          />

            <CustomButton type='submit'> Sign in </CustomButton>
            <CustomButton onClick={signInWithGoogle} isGoogleSignIn>
                Sign in with Google
            </CustomButton>

        </form>

    );
  }
}

export default SignIn;

A: I finally figured this out. The firebase config file should have had a .then and .catch for the promise. Once I added this, it works fine now. I researched 3 days to figure this out. Taking a course, and the guy who produced this course didn't add this, although it was two years ago maybe it wasn't required then, but it is now.


Q: Upload JAR to Nexus OSS 3 I have just installed Nexus OSS 3.0.1-01 on my server and I don't know how to upload artifacts to my maven repository. I need to upload JDBC and other dependencies to it, but I cannot find how!
It seems there is no section "Upload artifacts" as Nexus 2.


Q: In Grails, is "property" a reserved word? In Grails, is "property" a reserved word? That is, can I name a domain class Property and have its owner reference it by properties? Example:
class Thing {
    static hasMany = [properties: Property]
}

class Property {
    static belongsTo = [thing: Thing]
}

When I try to add a Property to a Thing I get the error:
Exception thrown: No signature of method: org.codehaus.groovy.grails.web.binding.DataBindingLazyMetaPropertyMap.add() is applicable for argument types: (Property) values: [Property : null]

groovy.lang.MissingMethodException: No signature of method: org.codehaus.groovy.grails.web.binding.DataBindingLazyMetaPropertyMap.add() is applicable for argument types: (Property) values: [Property : null]

    at ConsoleScript10.run(ConsoleScript10:3)

Is there a list of all Grails reserved words?

A: I'm not sure that Property is reserved, but properties is treated specially for domain classes since it's used for data binding. What happens when you change:
static hasMany = [properties: Property]

to something like
static hasMany = [myProperties: Property]

A: Grails is a web framework. In general, only languages really have reserved words. The reserved words of Groovy are all those reserved by Java, plus a few others. The complete list is shown here.
You'll notice that it does include "property", which was a big surprise to me, as I've no idea what it's used for, and I think/thought I know Groovy reasonably well. Perhaps it's reserved for future use?

A: While I cant find any file with the name Property in grails, it is wise not to use such a common word - who knows when it might become reserved in the future?
What would happen if you just prepended your classname with something, like BlahProperty?


Q: How to write to a file in assembly running under DOSBox I've made a procedure that writes to file, and made a label for writing into code, but the string i'm filling isn't being written to the file.
Write procedure:
proc WriteToFile
    mov ah,40h
    mov bx,[filehandle]
    mov cx,255
    lea dx,[WriteStr]
    int 21h
    ret
endp WriteToFile

Writing label:
WritingToFile:
    mov dx,offset w
    mov ah,9h
    int 21h
    mov dx,offset filenameStr
    mov bx,dx
    mov [byte ptr bx],13    ;8+1+3+1
    mov ah,0Ah
    int 21h
    mov dx,offset filenameStr + 2
    mov ah,9h
    int 21h
    mov [byte ptr filenameStr+2+8],0
    call OpenFile
    xor  bx,bx
    call WipeClean
    mov dx,offset filereaderline
    mov ah,9h
    int 21h
    mov dx,offset WriteStr
    mov bx,dx
    mov [byte ptr bx],100    ;8+1+3+1
    mov ah,0Ah
    int 21h
    call WriteToFile
    call CloseFile
    call DisplayWriteStr
    jmp GetCommandLetter

i've found out that on this procedure:
CreatingFile:
    mov dx,offset c
    mov ah,9h
    int 21h
    mov dx,offset filenameStr
    mov bx,dx
    mov [byte ptr bx],13    ;8+1+3+1
    mov ah,0Ah
    int 21h
    mov dx,offset filenameStr + 2
    mov ah,9h
    int 21h
    mov [byte ptr filenameStr+2+8],0
    call CreateFile
    ;

call WriteToFile -it wrote,an accident

    call DisplayFileName
    xor  bx,bx
    call CloseFile
    jmp GetCommandLetter

it wrote this in the file:
i $$$$$$$$$$$$$

HELP LIST:

-----------

Commands are:

 /e-Exit

 /h-help

 /1-Says: 'Hello World!'

$   Error

$file name consists of 4 letters MUST!! (dont forget to add '.txt' at the end of the name: 'xmpl.txt')$

/r/ $

/c/ $

/w/ $              i $$$$$$$$$$$$$

HELP LIST:

-----------

Commands are:

 /e-Exit

 /h-help

 /1-Says: 'Hello World!'

$   Error

$file name consists of 4 letters MUST!! (dont forget to add '.txt' at the end of the name: 'xmpl.txt')$

/r/ $

/c/ $

/w/ $              "

in the file it created, than i saw my variable for writing a file is:
 WriteStr db 105,0,13 dup("$")

it explains the duplicated $,i understood there is a problem with this variable mostly i suppose,how and to what can i change it so it would work?
Full code:
IDEAL
MODEL small
STACK 100h
DATASEG

szMsg1 db "Hi! What do you want to do?",10,13,10,13,"/h-help(see all the commands)",10,13,"/e-Exit",10,13,10,13,"$"
szHelloWorld db 10,13,"Hello World!",10,13,"$"
ErrorMsg db 10,13,"Illegal Command,Try again!",10,13,"$"
filenameStr db 13,0,13 dup("$")
WriteStr db 105,0,13 dup("$")
help db 10,13,"HELP LIST:",10,13,"-----------",10,13,"Commands are:",10,13," /e-Exit",10,13," /h-help",10,13," /1-Says: 'Hello World!'",10,13,"$"
filename db ?,0
filehandle dw 0
ErrorOpenMsg db 'Error',10,13,'$'
FileNameLength db "file name consists of 4 letters MUST!! (dont forget to add '.txt' at the end of the name: 'xmpl.txt')","$"
r db 10,13,"/r/ ","$"
c db ,10,13,"/c/ ","$"
w db ,10,13,"/w/ ","$"
fileString db 255 dup (0)
space db " ","$"
CommandMsg db 10,13,"Enter your command:",10,13,"Command: ","$",10,13
filereaderline db "file's text:","$"

CODESEG
proc Exitp
    mov ax, 4c00h
    int 21h
endp Exitp

proc WipeClean
     mov  [byte ptr fileString + bx], 0
     inc  bx
     cmp  bx, 255
     jb   WipeClean
     ret
endp WipeClean

proc OpenFile
;Open file
    mov ah,3Dh
    xor al,al
    lea dx,[filenameStr+2]
    int 21h
    jc openerror
    mov [filehandle],ax
    ret
openerror:
    mov dx,offset ErrorOpenMsg
    mov ah,9h
    int 21h
    ret
endp OpenFile

proc CreateFile
    mov ah,3ch
    mov cx,00000000b
    lea dx,[filenameStr+2]
    int 21h
    jc CreateError
    mov [filehandle],ax
    ret
CreateError:
    mov dx,offset ErrorOpenMsg
    mov ah,9h
    int 21h
    ret
endp CreateFile

proc ReadFile
    mov ah,3fh
    mov bx,[filehandle]
    mov cx,255
    lea dx,[fileString]
    int 21h
    ret
endp ReadFile

proc DeleteFile
    mov ah,41h
    lea dx,[filenameStr+2]
    int 21h
endp DeleteFile

proc DisplayFileString
    mov ah,09h
    lea dx,[fileString]
    int 21h
endp DisplayFileString

proc DisplayWriteStr
    mov ah,09h
    lea dx,[WriteStr]
    int 21h
endp DisplayWriteStr

proc DisplayFileName
    mov ah,09h
    lea dx,[filenameStr]
    int 21h
endp DisplayFileName

proc KeyStroke
    xor ax,ax
    int 16h
endp KeyStroke

proc WriteToFile
    mov ah,40h
    mov bx,[filehandle]
    mov cx,255
    lea dx,[WriteStr]
    int 21h
    ret
endp WriteToFile

proc CloseFile
    mov ah,3Eh
    mov bx,[filehandle]
    int 21h
    ret
endp CloseFile

start:
    mov ax, @data
    mov ds, ax

    mov ah,0
    mov al,2
    int 10h

    mov dx,offset szMsg1
    mov ah,9h
    int 21h
    jmp GetCommandLetter

PrintLine:
    mov dx, offset szHelloWorld
    mov ah, 9h
    int 21h
    jmp GetCommandLetter

_Error:

    mov dx,offset ErrorMsg
    mov ah,9h
    int 21h

GetCommandLetter:
    mov dx,offset CommandMsg
    mov ah,9h
    int 21h

    mov ah, 1h
    int 21h
    mov bl,al

    mov ah, 1h
    int 21h
    mov bh,al
compare:

    cmp bl,'/'
    jne _Error

    cmp bh,'h'
    je _help

    cmp bh,'H'
    je _help

    cmp  bh,'1'
    je PrintLine

    cmp bh,'e'
    je _Exitp

    cmp bh,'E'
    je _Exitp

    mov dx,offset space
    mov ah,9h
    int 21h
    mov dx,offset FileNameLength
    mov ah,9h
    int 21h

    cmp bh,'c'
    je CreatingFile

    cmp bh,'C'
    je CreatingFile

    cmp  bh,'r'
    je GetFileName

    cmp  bh,'R'
    je GetFileName

     cmp  bh,'w'
    je WritingToFile

    cmp  bh,'W'
    je WritingToFile

    jmp _Error

_Exitp:
call Exitp

_help:
    mov dx,offset help
    mov ah,9h
    int 21h
    jmp GetCommandLetter

GetFileName:
    mov dx,offset r
    mov ah,9h
    int 21h
    mov dx,offset filenameStr
    mov bx,dx
    mov [byte ptr bx],13    ;8+1+3+1
    mov ah,0Ah
    int 21h
    mov dx,offset filenameStr + 2
    mov ah,9h
    int 21h
    mov [byte ptr filenameStr+2+8],0
    call OpenFile
    xor  bx,bx
    call WipeClean
    call ReadFile
    mov dx,offset filereaderline
    mov ah,9h
    int 21h
    call DisplayFileString
    call CloseFile
    jmp GetCommandLetter

CreatingFile:
    mov dx,offset c
    mov ah,9h
    int 21h
    mov dx,offset filenameStr
    mov bx,dx
    mov [byte ptr bx],13    ;8+1+3+1
    mov ah,0Ah
    int 21h
    mov dx,offset filenameStr + 2
    mov ah,9h
    int 21h
    mov [byte ptr filenameStr+2+8],0
    call CreateFile
    call WriteToFile
    call DisplayFileName
    xor  bx,bx
    call CloseFile
    jmp GetCommandLetter

WritingToFile:
    mov dx,offset w
    mov ah,9h
    int 21h
    mov dx,offset filenameStr
    mov bx,dx
    mov [byte ptr bx],13    ;8+1+3+1
    mov ah,0Ah
    int 21h
    mov dx,offset filenameStr + 2
    mov ah,9h
    int 21h
    mov [byte ptr filenameStr+2+8],0
    call OpenFile
    xor  bx,bx
    call WipeClean
    mov dx,offset filereaderline
    mov ah,9h
    int 21h
    mov dx,offset WriteStr
    mov bx,dx
    mov [byte ptr bx],100    ;8+1+3+1
    mov ah,0Ah
    int 21h
    call WriteToFile
    call CloseFile
    call DisplayWriteStr
    jmp GetCommandLetter

exit:
    mov ax, 4c00h
    int 21h
END start

A: Found the error in your code : the file is been opened in READ ONLY mode, so you can't write it :
proc OpenFile
;Open file
    mov ah,3Dh
    mov al,2    ;<================== 0:READ ONLY, 1:WRITE ONLY, 2:READ/WRITE.
    lea dx,[filenameStr+2]
    int 21h
    jc openerror
    mov [filehandle],ax
    ret
openerror:
    mov dx,offset ErrorOpenMsg
    mov ah,9h
    int 21h
    ret
endp OpenFile


Q: can not add webpart to sharepoint page i create a website on my local machine but i can't add webpart to web page, it don't rise any error but th webpart don't display to the page. anyone help me.
Thanks

A: I know this is an old question, but it's ranking high in Google results, so I figured I'd answer it anyway.
Make sure you're not running any code in the layout page's codebehind that calls and then closes SPContext.Current.Web. I had this exact behavior and that was the culprit
To test, add a different web part to a default page layout. If it adds, then it's either your web part or your code behind. If you can't add any web parts to your custom layout, it's your code behind. If it's just your web part, it's your web part.
Remember, SPContext.Current.Web returns a reference to the current SPWeb object. SharePoint will close the object itself when it's done, and closing it early can cause "unpredictable behavior."

A: We had the same problem with Firefox some time ago, but the problem disappeared when we installed SP2 for SharePoint 2007. The only thing that surprises me is that you also have the problem with IE.


Q: Why does FolderBrowserDialog not allow the desktop as SelectedPath when RootFolder is MyComputer? This works:
FolderBrowserDialog dlg = new FolderBrowserDialog();
dlg.RootFolder = Environment.SpecialFolder.MyComputer;
dlg.SelectedPath = "C:\\Almo\\";
dlg.ShowDialog();

This does not:
FolderBrowserDialog dlg = new FolderBrowserDialog();
dlg.RootFolder = Environment.SpecialFolder.MyComputer;
dlg.SelectedPath = "C:\\Users\\Almo\\Desktop\\";
dlg.ShowDialog();

The first opens a fileselection dialog starting in C:\Almo, the second started at MyComputer. Is there a way to make this work? The issue is my Application's default save location is the Desktop, and I want the user to be able to select a different location, and I want the dialog to start wherever the current location is.

A: Try:
Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory)

A: Use :
dlg.SelectedPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop)

this gets you the path of the desktop for the user who is running the code.

A: Apparently, the Desktop in Win 7 doesn't actually exist at the path
c:\Users\username\Desktop
The system pretends it does at the command prompt and in windows explorer. But since it isn't there, the part of SelectedPath that requires its path to be under RootFolder disallows setting the path in that way.


Q: Good program structure when updating values in databound object I'm writing a Winforms based tool and could use some guidance on the structure. The program communicates with a piece of hardware over serial, and shows a GUI to display values. Most values are either set from the pc, or read from the device. There are some which are set from the pc and then confirmed by the device.

Currently I have an Model object with all the values the device can send or receive. It uses a PropertyChangedEvent with a databinding to show values on the Form. Additionally there is a encoder/decoder that listens on the event, which encodes changes and sends it to the serial port.
In the serial port receive function the message is decoded, and the correct value in the Model is updated. The problem I'm having is that this will cause another PropertyChangedEvent, which will send another serial message. I'm looking for a good way to replace that listener with something else? I'd like to maintain the databinding to the form, so that every form element doesn't need an event.
Most values are declared like this:
private bool _voltageVBatToggle;
public bool voltageVBatToggle
{
    get => _voltageVBatToggle;
    set
    {
        if (_voltageVBatToggle != value)
        {
            _voltageVBatToggle = value;
            OnPropertyChanged();
        }
    }
}


Q: Python only sends output interactvely When I run my python script (content irrelevant for this question, just uses print a couple of times) interactively, it sends the output straight away.
When I use it in a pipe to tee or in an output redirection (./script.py > script.log) there is no output. What am I doing wrong?

A: I suspect you're encountering output buffering, where it's waiting to get a certain number of bytes before it flushes.  You can look at the unbuffer command if that is undesirable for you.

A: As it turns out, Python detects whether or not you are using a tty, and increases its buffering when you are not. Several options on how to disable this can be viewed at this question.


Q: Saving a Date in Excel from Datepicker I am trying to save a date from a DatePicker on a Windows Form, into an existing Excel
Spreadsheet.
The following code assigns a string the ShortDate value of the DatePicker:
if (checkupCheck.Checked)
            {
                newCheckupDate = checkupPicker.Value.Date.ToShortDateString();
            }
            else
            {
                newCheckupDate = null;
            }

This value is then saved after being placed into a data grid with the following code:
for (int i = 0; i < dataGridView1.Rows.Count - 1; i++)
            {
                for (int k = 0; k < dataGridView1.Columns.Count; k++)
                {
                    worksheet.Cells[i + 2, k + 1] = dataGridView1.Rows[i].Cells[k].Value.ToString();
                }
            }
workbook.Save();

When looking at the value of the newCheckupDate string at a breakpoint, it appears as I would like it "dd/mm/yyyy"
When this is saved into Excel however, the cell will contain "dd/mm/yyyy 00:00:00". I do not want the time being added.
The cell is formatted as a date cell.
I have a feeling that Excel may be the cause of the problem here, but I don't know how to solve it.
Thanks in advance for any help!

A: Without delving into the why, you can simply format the cell in the loop :
for (int i = 0; i < dataGridView1.Rows.Count - 1; i++)
{
    for (int k = 0; k < dataGridView1.Columns.Count; k++)
    {
        worksheet.Cells[i + 2, k + 1] = dataGridView1.Rows[i].Cells[k].Value.ToString();
        worksheet.Cells[i + 2, k + 1].NumberFormat = "dd/mm/yyyy"
    }
}

workbook.Save();


Q: Typescript with Prisma I'm completely new to Typescript.
I've started to work with Prisma and, coming from Sequelize, I miss simply writing stuff e.g. user.update({ ... }). It seems that Prisma returns just plain objects, and not classes, so I came up with this:
import { Prisma, User as PrismaUser } from '@prisma/client';
import prisma from './path-to-prisma-instance';

class User {
  constructor(data: PrismaUser) {
    Object.assign(this, data);
  }

  update = async (props: Prisma.UserUpdateArgs) => {
    const data = await prisma.user.update({
      ...props,
      where: { id: this.id } // Property 'id' does not exist on type 'User'
    });
    return new User(data);
  };
}

I'm getting that Property 'id' does not exist on type 'User'.
How am I able to fix this?


Q: ZF2 - validation within a bootstrap modal I am using twitter bootstrap in a zf2 application. A bootstrap modal displays a form containing user details, which i would like to be edited and saved. This is fairly trivial if i just submit form in the dialog and reload the whole page, but i am looking for a way to validate the form without it being submitted, and ideally if the data is valid, for it to pass the new data back to the page when the modal dialog is closed.
How can i do this - would it need to be an ajax call? If so how would i structure that in my controller to return the form validation in a way that the errors can be rendered in the modal?
Edit 1:
Accepted answer below is spot on so far.
The only thing i'm having trouble understanding is how to pass the validation data from the controller back to the bootstrap modal.
So as a simple workflow - modal window opens loaded with an edit form bound to a User model, which shows the User data to be edited (all preloaded and assigned to the view already). The modal form is submitted, jquery hooks onto the form submit and sends the data as an ajax request to UserController::EditUserAction - where the form data is validated against the models inputfilter. If it turns out to be valid, the data is saved and the modal dialog is closed. If the data is invalid, say changing the email address to an address that already exists, the action returns a JsonModel with the form error(s) - how is this then passed to the bootstrap modal to highlight the field that produced the error, like the way that ZF does automatically when a form is typically submitted?

A: You would do this with ajax.  To understand what to do in your controller you have to understand the fundementals of an ajax call.  jQuery makes this pretty easy.
<script>
$(function() {
  jQuery.ajax({
    type: method,
    dataType: 'json',
    url: url,
    data: data,
    error: function(jqXHR, textStatus, errorThrown) {
      // Do something to handle the error
    },
    success: function(data, textStatus, jqXHR) {
      // Do something else on successful validation
    }
  });
});
</script>

The type is the HTTP method (eg. 'POST').
The url is the the route to get you to the controller which will give you a response.
The data is the form data to be sent.
More documentation is at https://api.jquery.com/jQuery.ajax/
The success function is executed if the HTTP response code is in the 200's.
If you send an HTTP response code in the 400's or 500's, the javascript in the error function will be executed.  This can be used to show an error in your modal dialog.
You can modify the HTTP response code in a controller by using the following code:
$this->getResponse()->setStatusCode(400);

where 400 is the HTTP response code (see http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html for more info about HTTP response codes)
Then, to send data back with the response, return a JsonModel in the controller instead of a ViewModel
return new JsonModel($array);

where $array is the data you want to send back to the browser.
If you end up doing this a lot, you might investigate the zf2 class \Zend\Mvc\Controller\AbstractRestfulController.

A: if you want try for validation before submit form (send data to server) . may be better use client side validation .
http://www.rayfaddis.com/blog/2013/05/27/jquery-validation-with-twitter-bootstrap


Q: Conditional expectation uniform distribution Let $ \xi $ $ \sim \operatorname{Uniform}[0, 1]$ ( continuous).
I need to find the meaning of an expression $ \mathbb{E}(\xi | \xi^2) $.
When we calc $ \mathbb{E}(\xi^2 | \xi) = \xi^2$ because $\xi^2$ sigma measurable $\xi$.
But how to calc in my case?

A: As pointed out by Andrew in the comments, $\xi$ is a function of $\xi^2$. Indeed, since $\xi$ takes non-negative values,
$$
\xi=\left\lvert \xi\right\rvert=\sqrt{\xi^2}.
$$
Consequently, $\mathbb{E}\left(\xi | \xi^2\right)=\xi$.


Q: Conflict between tensorflow/PIL/pillow and scikit-image? I am tying to rebuild my computer to run Spyder in a tensorflow environment for some image processing.  In the past this worked and I had scikit-image working fully in that environment, and accessible from Spyder.  Something has changed.  I have:
1) re-installed Anaconda
2) re-installed tensorflow in a conda environment
3) installed libraries as needed, including Spyder.
Then I start Spyder from the Conda navigator, in the tensorflow environment.  This seems to work, I can import tensorflow, keras, pandas, sklearn, etc.  But skimage only works partially.  for example:
    import skimage

works fine. But,
    import skimage.io as io

does not. The error comes out as 'from PIL import Image' Is this something about PIL/pillow not co-existing in the same environment?  Can this be fixed easily or should I just use opencv for image io?  I have tried other modules in skimage and they all import.  So using another package to open an image would not be the end of the world, but it would be nice to get the entirety of skimage working.
Thanks


Q: How to select begin and end dates independently with dc.js Is it possible to filter a chart by selecting a specific begin date and then an end date without one interfering with the other?
For example I'm using a barChart and I have a range like range: [01/02/2022 -> 17/02/2022] and my goal is to set a begin date and end date by selecting each one. I using crossFilter for filtering data but when I move the mouse or slide left or right both date are being set.
My JS:
  MyChart
        .width(width)
        .height(250)
        .margins({ top: 10, right: 20, bottom: 25, left: 70 })
        .dimension(moveMonths)
        .mouseZoomable(true)
        .transitionDuration(1)
        .x(d3.time.scale().domain([d3.min(data, function (d) {
            return d.dd;
        }), d3.max(data, function (d) {
            return d.dd;
        })]))
        .round(d3.time.month.round)
        .xUnits(d3.time.months)
        .title(function (p) {
            return p.key.getDate() + '/' + (p.key.getMonth() + 1) + '/' + p.key.getFullYear() + ' Total ' + formatDecimal(p.value, 2, ',', '.') + " €";
        })
        .elasticY(true)
        .renderHorizontalGridLines(true)
        .brushOn(false)
        .compose([
            dc.lineChart(DeptVariationChart)
                .group(moveMonthsGroup)
                .valueAccessor(function (d) {
                    return d.value;
                })
        ])
        .renderHorizontalGridLines(true)
        .yAxis().tickFormat(function (v) { return formatDecimal(v, 0, ',', '.') + " €"; });


Q: Problem with setting a environment variable I want to add Intellij Idea to be able to use ./idea.sh outside of my bin directory.
I edited my .bashrc to add export PATH=$PATH:/home/xenia/idea-IE-202.7319.78/bin at the bottom of my file.
Then, I typed source ~/.bashrc.
I closed and opened a terminal outside of /home/xenia/idea-IE-202.7319.78/bin and I typed ./idea.sh.
It doesn't work. I gives the error bash: ./idea.sh: No such file or directory  I have no idea why. Any help?

A: Prepending ./ tells the shell explicitly not to search your PATH, but to only look in the current directory ./
Just type idea.sh instead.


Q: Matching braces in ruby with a character in front I have read quite a few posts here for matching nested braces in Ruby using Regexp. However I cannot adapt it to my situation and I am stuck. The Ruby 1.9 book uses the following to match a set of nested braces
/\A(?<brace_expression>{([^{}]|\g<brace_expression>)*})\Z/x

I am trying to alter this in three ways. 1. I want to use parentheses instead of braces, 2. I want a character in front (such as a hash symbol), and 3. I want to match anywhere in the string, not just beginning and end. Here is what I have so far.
/(#(?<brace_expression>\(([^\(\)]|\g<brace_expression>)*\)))/x

Any help in getting the right expression would be appreciated.

A: Using the regex modifier x enables comments in the regex. So the # in your regex is interpreted as a comment character and the rest of the regex is ignored. You'll need to either escape the # or remove the x modifier.
Btw: There's no need to escape the parentheses inside [].


Q: const_cast and std::move to remove constness from non-reference I have an external library which I can not modify. The library declares a template function that for some reason returns const non-reference object:
template<class C>
const C foo();

I have another external library which I can not modify too. The library declares a class that is non-copyable and has a move constructor from a non-const object only:
struct bar {
    bar();
    bar(const bar&)=delete;
    bar(bar&&);
};

Now I need to use foo<bar>. A simple usage:
bar buz() {
    return foo<bar>();
}

fails with

main.cpp: In function 'bar buz()':
main.cpp:13:21: error: use of deleted function 'bar::bar(const bar&)'
     return foo<bar>();
                     ^
main.cpp:8:5: note: declared here
     bar(const bar&)=delete;
     ^~~

which makes sense, and no simple workaround make the code compile.
However, if I add some more complex workaround:
bar buz() {
    return const_cast<bar&&>(std::move(foo<bar>()));
}

it compiles and the whole code work as expected (not only the simplified example above, but my real code too).
However, it is safe, or am I running into some undefined behavior? Is there any better workaround?

I have read and I understand questions about returning const from functions (1, 2), and the common answer there seems to be that returning const objects is discouraged in modern C++, but my question is not about it, but about how can I workaround the situation when an external library returns const object.

A: Casting away the const will lead to undefined behavior if the move constructor for bar modifies anything.  You can probably work around your issue like this without introducing undefined behavior:
struct wrapped_bar {
    mutable bar wrapped;
};

bar buz()
{
    return foo<wrapped_bar>().wrapped;
}

Having the wrapped member be mutable means that the member is non-const even though the wrapped_bar object as a whole is const.  Based on how foo() works, you may need to add members to wrapped_bar to make it work more like a bar.

A: Technically speaking, you are exposing your program to undefined behavior. Since original object C (a temporary) was declared const, const-casting and modifying it is illegal and against the standard. (I assume, move constructor does some modifications to the movee).
That being said, it probably works in your environment and I do not see a better workaround.

A: As result of function call is by definition an R-Value itself, you do not need to apply std::move on it in return statement - const_cast<bar&&>(foo<bar>()) should be enough. That make code a little bit simpler to read.
Still - there is no standard guarantee that this will always work for all bar types. Even more - this might in some cases lead to undefined behavior.(Imagine some very intrusive optimization, which completely eradicates foo and makes its result an object in "static data" segment of memory - like if foo was a constexpr. Then calling moving constructor, which probably modifies its argument, might lead to access violation exception).
All you can do is either switch to different library (or, if possible, ask library maintainer to fix API) or create some unit test and include it in your build process - as long as test passes, you should be OK (remember to use same optimization settings as in "production" build - const_cast is one of those things which strongly depends on compilation settings).


Q: Range not Found Error on for Loop in Google Apps Script I'm looking to create templates using GAS -- all I need is to copy and paste variables into designated cells, push the data, then move to the next.
I had my script working great for a single template (the first set of variables).  I tried to set up a loop, and now I'm hitting a "Range not found" error I'm going crazy trying to figure out.
I had it working copying and pasting the variables out and generating the template, but struggling to get it to move to the next cell in each column.
I made a range for each column where the script should loop through, meaning:
Row 2 Col A, Row 2 Col B, Row 2 Col C, Row 2 Col D each go through the loop (variables get pasted, sheet gets created, etc), then we move onto Row 3 Col A, Row 2 Col B, so on so forth.
function CreateTemplates() {
   var templatesNeeded = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Test');
   var rundownSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Exclusive Template Creation');
   var tabname = templatesNeeded.getRange('A2').getValue();
   var pasteTemplate = rundownSheet.getRange('e1:l150').getValues();

    const row = 2;
  const ss = SpreadsheetApp.getActiveSpreadsheet();
  const sheet = ss.getSheetByName('Test');
  const rows = sheet.getLastRow() - row + 1;
  const range = sheet.getRange(row, 1, rows, 1);
  const values = range.getValues().flat();

 const dateRange = sheet.getRange(row, 2, rows, 1);
  const dateValues = dateRange.getValues().flat();

   const gameRange = sheet.getRange(row, 3, rows, 1);
  const gameValues = gameRange.getValues().flat();

   const typeRange = sheet.getRange(row, 4, rows, 1);
  const typeValues = typeRange.getValues().flat();

     const broadcastRange = sheet.getRange(row, 5, rows, 1);
  const broadcastValues = broadcastRange.getValues().flat();

  const matches = {};
  values.forEach((value, i) => {
    if (value !== '') {

 rundownSheet.getRange('E3').setValue(templatesNeeded.getRange(values).getValue());
   rundownSheet.getRange('B1').setValue(templatesNeeded.getRange(dateValues).getValue());
   rundownSheet.getRange('B2').setValue(templatesNeeded.getRange(gameValues).getValue());
   rundownSheet.getRange('B3').setValue(templatesNeeded.getRange(typeValues).getValue());
rundownSheet.getRange('H2').setValue(templatesNeeded.getRange(broadcastValues).getValue());

     var tss = SpreadsheetApp.openById('16nn9mfSOpVbPZBsB_nwhRNRv4nYQblrS1GzAD4jgmoQ');

 var sheet = tss.getSheetByName('Single Template');

 sheet.copyTo(tss).setName(tabname);

// Logger.log(value)

  sheet.getRange(1,1,pasteTemplate.length,pasteTemplate[0].length).setValues(pasteTemplate);

Utilities.sleep(1000);
    }
  });
}

I think it's clearly a problem with how I created my ranges (or something with the loop).  Any thoughts are greatly, greatly appreciated.
Here's a test link where the code would be hosted:
https://docs.google.com/spreadsheets/d/1WeBgyi8JVfC02rCIB0T1eEbbmtpaXYF16qM7MLIzqPs/edit#gid=0
Here's a test link where the code will be pushed to (templates will be created here):
https://docs.google.com/spreadsheets/d/16nn9mfSOpVbPZBsB_nwhRNRv4nYQblrS1GzAD4jgmoQ/edit#gid=804269175
Large improvement, but still hitting some errors.  Now, it's looping through and creating the tabs, but the setValues to actually move the data over doesn't seem to work. Thought it was a timing issue -  I added in utilities.sleep but still playing with it, with no luck yet.  Basically,  I want the variables to surface the data needed, that data to copy and paste to a template, then new variables, then new template:
   function createNewTemplates() {
  const ss = SpreadsheetApp.getActive();
  const sh1 = ss.getSheetByName('Test');
  const sh2 = ss.getSheetByName('Exclusive Template Creation');
  const sh1A2 = sh1.getRange('A2').getValue();
  const vs2 = sh2.getRange('e1:l150').getValues();
  const sr = 2;
  // const sh1 = ss.getSheetByName('Test');
  const vs1 = sh1.getRange(sr, 1, sh1.getLastRow() - sr + 1, 5).getValues();
  const tss = SpreadsheetApp.openById('16nn9mfSOpVbPZBsB_nwhRNRv4nYQblrS1GzAD4jgmoQ');
  vs1.forEach((r, i) => {
    if (r[0] !== '') {
       Utilities.sleep(2000);
      sh2.getRange('E3').setValue(r[0]);
      sh2.getRange('B1').setValue(r[1]);
      sh2.getRange('B2').setValue(r[2]);
      sh2.getRange('B3').setValue(r[3]);
      sh2.getRange('H2').setValue(r[4]);

      let sh = tss.getSheetByName('Single Template');
      sh.copyTo(tss).setName(r[0]);
      let shnew = tss.getSheetByName(r[0]);
      Utilities.sleep(200);
      shnew.getRange(1, 1, vs2.length, vs2[0].length).setValues(vs2);

    }
  });
}

A: Try this:
function createNewTemplates() {
  const ss = SpreadsheetApp.getActive();
  const sh1 = ss.getSheetByName('Test');
  const sh2 = ss.getSheetByName('Exclusive Template Creation');
  const vs2 = sh2.getRange('e1:l150').getValues();
  const sr = 2;
  const vs1 = sh1.getRange(sr, 1, sh1.getLastRow() - sr + 1, 5).getValues();
  const tss = SpreadsheetApp.openById('16nn9mfSOpVbPZBsB_nwhRNRv4nYQblrS1GzAD4jgmoQ');
  let sh = tss.getSheetByName('Single Template');
  vs1.forEach((r, i) => {
    if (r[0] !== '') {
      sh2.getRange('E3').setValue(r[0]);
      sh2.getRange('B1').setValue(r[1]);
      sh2.getRange('B2').setValue(r[2]);
      sh2.getRange('B3').setValue(r[3]);
      sh2.getRange('H2').setValue(r[4]);
      let shnew = sh.copyTo(tss).setName(r[0]);
      shnew.getRange(1, 1, vs2.length, vs2[0].length).setValues(vs2);
    }
  });
}


Q: "Before I know it" vs "before I knew it." Should I write "before I know it" or "before I knew it" when speaking in the present tense?
Example sentence:

"This boss is too tyrannical. Before I know it/before I knew
  it, I'll/I'd become his slave."

I chose the first version, but a native English speaker told me I should use the second.

A: The answer here is shown by the verb tenses you're using for the rest of the sentence. (and you did get the verb tenses correct, BTW, which many people don't, so good job on that!)

Before I know it, I will become his slave.

This is perfectly correct, but it is a future tense sentence.  It says that you will become his slave in the future, and that when that happens, you expect it will be true before you actually realize it.

Before I knew it, I had become his slave.

Here, you need to use the past tense "knew", because your main verb ("had become") is in a past tense.  This whole thing is, therefore, describing something that happened in the past.  You already have become his slave, and it happened before you knew it.
So the answer is:  You can use either one, but which one you use should depend on whether you want to talk about a past thing or a future thing.


Q: Conditional probability with bayes rule?? http://cseweb.ucsd.edu/~dasgupta/103/2b.pdf part 2.1.2 implies $P(X|Y \cap Z) = \frac{P(X|Y)}{P(Y|Z)}$
Seems to imply that this is true but if you take bayes, the left hand side is:
$P(X|Y \cap Z) = \frac{P(X \cap Y \cap Z)}{P ( Y \cap Z)}$
While the right hand side is:
$\frac{P(X|Y)}{P(Y|Z)} = \frac{\frac{P(X \cap Z)}{P(Z)}}{\frac{P(Y \cap Z)}{P(Z)}}  = \frac{P(X \cap Z)}{P(Y \cap Z)}$
This seems to imply that $P(X \cap Z) = P(X \cap Y \cap Z)$ but this isnt always true??

A: As you observed, it is not necessarily the case that $\Pr(X|(Y\cap Z))=\frac{\Pr(X|Y)}{\Pr(Y|Z)}$.
For example, toss a fair coin twice. Let $X$ and $Y$ each be the events "first is a head," and let $Z$ be the event "second is a head." Then $\frac{\Pr(X|Y)}{\Pr(Y|Z)}=2$, so it is not even a probability.


Q: MYSQL update, replace delete with PHP array I have a query I need to run on a $_POST array with php it's quite simple as it takes all the values in the array then runs a query for each of the values which updates the database, here is the tricky part: As the array is dependent of checkboxes selected by the user the query has to either Update, Replace or remove values in DB dependent on what is in the $_POST array. I've only been able to have the query successfully run the last value in the array.
I've tried both 'REPLACE INTO' and 'INSERT IGNORE INTO' but with no luck. I'm starting to think much more complex coding is going to be needed :( here's what I have so far:
foreach($params['text'] as $boilertext)
{
    $sql = 'UPDATE '._DB_PREFIX_.'boilertexts
            SET id_product="'.pSQL($boilertext).'" WHERE id_text="'.$params['id'].'"';
    if(!Db::getInstance()->Execute($sql))
    {
        echo mysql_error();
    }
}

EDIT:
This is the post params i'm getting:
Array (
       [text] => Array ( [0] => 8 [1] => 6 [2] => 10 ) // the Text ID i'm updating
       [textValue] => "Some text that I'm adding to another DB table"
       [id] => 28 // The ID that all the params from ['text'] are linked too
       [update] => update // Name of the submit button I'm using for form processing
     )

My issue is that although the foreach is running the SQL x amount of times for each query (tested it by printing out a count for each query) it will only insert the last value in ['text'] array. It also doesn't seem to update/remove the text id from the DB if it is not in the array

A: What you really do is 3 updates on same record . Thats why you get only last value in database.
You are  updating  record id_text=28 with values 8,6,10.

A: It will only end up set as the last value, as you are updating the same record the number of times that you have values in your array.
Only one field in one record is being processed, it can not magically become multiple records this way - you would need a separate table, or use INSERT.


Q: Doctrine Query count() and groupBy() date I need to find the total number of logins per day, but how would I select count() and group by day in DQL? I'm using Doctrine 2.3.
public function getLoginCount()
{
    return $this->createQueryBuilder('i')
            ->select('i') // and count(*)
            ->groupBy('i.timestamp') // group by day
            ->getQuery()
            ->execute()
        ;
}

I need something like this:
Date | count
2013-01-01 | 6
2013-01-02 | 7
2013-01-03 | 3

A: From help on the Doctrine IRC channel you need to create a custom DQL function.
Example:
https://github.com/beberlei/DoctrineExtensions/blob/master/lib/DoctrineExtensions/Query/Mysql/Day.php
Docs:
http://www.doctrine-project.org/blog/doctrine2-custom-dql-udfs.html

A: A bit late for OP, but maybe someone will find it handy. I was able to achieve that with the DQL query bellow:
    $dql = '
        SELECT
            SUBSTRING(i.timestamp, 1, 10) as date,
            COUNT(i) as count
        FROM Entity i
        GROUP BY date
    ';
    $query = $entityManager->createQuery($dql);
    return $query->getResult();

I think similar should be doable with Doctrine query builder.


Q: Installing TTF fonts in LaTeX One of the annoying aspects of LaTeX is the limited number of fonts that come by default, and the pain involved in making new fonts 'LaTeX' ready. I have a collection of truetype fonts that I'd like to prepare for use, and I definitely want to make sure I have vector versions of these fonts (i.e not type 3/bitmapped versions). Is there a relatively painless way to do this ?

A: The easiest way is with XeTeX or LuaTeX and the fontspec package. They can use any TTF font installed on the system. For Linux this means both the system wide fonts and any fonts you put into ~/.fonts/ (e.g. by installing them via Nautilus).
To use the fonts you simply have to load the fontspec package and set the font:
\documentclass{article}

\usepackage{fontspec}
\setmainfont{Arial}

\begin{document}
Lorem ipsum...
\end{document}

Then compile the the document with xelatex or lualatex. The fontspec documentation describes all the possibilities for changing fonts.
The only drawbacks (as far as I am aware) are that you can only generate .pdf files and that you need a sufficiently new TeX distribution (TeX Live 2009 should work for XeTeX and Tex Live 2010 for LuaTeX).

A: One solution is to use XeLaTeX, which lets you use system fonts (mostly) hassle-free.

A: The process for PdfTeX is something like this (depends a little bit on your distribution):

*

*Get autoinst.pl from Fontools from CPAN

*Get otf2tfm from lcdf-typetools

*Run autoinst.pl (using Perl) on all ttfs

*Add generated PdfTeX font mapping (in MikTeX for instance initexmf --edit-config-file updmap, add Map yourmap.map and run initexmf --mkmaps)

You can do the whole process manually as well (autoinst.pl is nothing but a smart wrapper):

*

*Create tfm metrics and a ttfonts.map using ttf2tfm

*Create virtual font tables using vptovf

*Create afm metrics using ttf2afm

*Create pdf font map using afm2tfm

*Put *.tfm, *.afm, *.ttf, *.vf into the fonts/tfm/ etc.

*Add the font maps

*Create a package/sty to pull the various fonts into a font family (this is where I am stuck)

My ruby script for running the commands looks like this:
require 'fileutils'

basename = "Nexus"

open("#{basename}.map", 'a') { |pdfFontMap|

    Dir["#{basename}*.ttf"].each{ |file|

        file.sub!(/\.ttf$/, "")

        ttf = "#{file}.ttf"

        file.gsub!(/_/,"") # Remove underscores

        puts `ttf2tfm #{ttf} -q -T T1-WGL4.enc -v ec#{file}.vpl rec#{file}.tfm >> ttfonts.map`

        puts `vptovf ec#{file}.vpl ec#{file}.vf rec#{file}.tfm`

        puts `ttf2afm -e T1-WGL4.enc -o rec#{file}.afm #{ttf}`

        pdfFontMap.puts `afm2tfm rec#{file}.afm -T T1-WGL4.enc rec#{file}.tfm`.gsub(/\r|\n/, "") + " <#{ttf}"
    }
}

You can find more details about the manual way in:
http://www.radamir.com/tex/ttf-tex.htm
P.S.:

*

*Run initexmf --update-fndb EVERY time new files are put somewhere

A: LuaTeX brings TTF-support, but I have no Idea how mature it is right now.


Q: What better design to support dynamic relationships? Instead of creating a seperated join table for one many-to-many relationship, I will design a centralized table, called 'Collection'. It will contain whole relationship data for all tables in database. This table like that:

*

*Towards row 1, since table A and table B has many-to-many relationship, so the value of 'Unique_key' column will be NULL

*Towards row 2 and 3, since table A and table C has one-to-many relationship, so there're multiple row value.

My question is: Compared to traditional design using a seperated join table for each of many-to-many relationships, by this way of using centralized table contains whole relationship data for all tables in database. Which way should should use?

A: You should definitely use the "traditional" way!

*

*You cannot enforce referential integrity with constraints like that, as such a constraint has to point to only one table and cannot have multiple target tables depending on a columns value. You had to simulate it with complex triggers, that are almost sure to be less efficient than a simple foreign key constraints.

*You won't be able to use "normal" indexes because of having everything in one table and with possibly the wrong type (I guess you intend Unique_key to be varchar?). Maybe there's some tricks around it with partial and function based indexes if (your version of) MySQL supports it (I don't know for sure at the moment). But even if such tricks were possible, again that's more effort than needed and likely to be less performant.

*And maybe more...
Don't try to reinvent the wheel, especially not a triangular one...


Q: How to resign first responder from text field when user tap elsewhere? I have filled my view with ScrollView (same size as the view) and I'm stuck at how to resign first responder when user tap elsewhere in the View (or the scrollview). Any idea on how to do that ? I'm using the following method but it's not working as expected:
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}

Thx for helping,
Stephane

A: I found the answer here:

If your ultimate aim is just to resign the first responder, this
should work: [self.view endEditing:YES]

The endEditing(_:) method is designed right for it

Causes the view (or one of its embedded text fields) to resign the first responder status.

A: UIViewController inherits from UIResponder so a naive way (I am pretty sure is not the smartest way to do it) would be by overwriting the following methods (at least 1 of them)
– touchesBegan:withEvent:
– touchesMoved:withEvent:
– touchesEnded:withEvent:
- touchesCancelled:withEvent:

Next you could get the touched view by doing
UITouch *touch = [touches anyObject];
UIView *touchedView = [touch view];

finally resign the first responder if that view is not your text field
if(touchedView != textField){
    [textField resignFirstResponder];
}

_
Demerits of this approach:
You will have to handle the "tap" by yourself. (Same problem as the old iOS 3.1 or earlier). You will have to come up with your own implementation to differentiate single taps from drags, swipes, double taps, long taps, etc. Is not hard to get it working well but it is not likely you get it exactly the same way Apple detects taps (timings, distances, thresholds count!)
However, that depends on your needs.
If your view structure is simple enough then you could add a gesture recognizer to the container view and resign the first responder every time the handler is called :)
Hope this helps

A: Nobody has yet presented the best answer here:
[[UIApplication sharedApplication] sendAction:@selector(resignFirstResponder) to:nil from:nil forEvent:nil];

From the documentation on this method:

Normally, this method is invoked by a UIControl object that the user
  has touched. The default implementation dispatches the action method
  to the given target object or, if no target is specified, to the first
  responder. Subclasses may override this method to perform special
  dispatching of action messages.

I bolded the relevant part of that paragraph. By specifying nil for the to: parameter, we automatically call the given selector on the first responder, wherever it is, and we don't need to have any knowledge of where in the view hierarchy it is. This can also be used to invoke other methods on the first responder as well, not just cause it to resign first responder status.

A:     -(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [self.TextField resignFirstResponder];

    return YES;
}

A: Give a unique Tag  to your UITextfield (i.e. 333), then to resign the first responder do this:
UITextField *textField = (UITextField *)[self.view viewWithTag:333];
[textField resignFirstResponder];

A: For a more robust and clean solution add a tap gesture recognizer to your primary view.
This will work better with nested views and will be cleaner than secret buttons in code and UI builder.
In your view did load:
UITapGestureRecognizer* tapBackground = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissKeyboard:)];
[tapBackground setNumberOfTapsRequired:1];
[self.view addGestureRecognizer:tapBackground];

..and define your target action to be triggered on tap:
-(void) dismissKeyboard:(id)sender
{
    [self.view endEditing:YES];
}

A: The best option is the shortest way ;)
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}

A: Using Swift you can do this:
func viewDidLoad() {
    super.viewDidLoad()

    let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.hideKeyboardByTappingOutside))

    self.view.addGestureRecognizer(tap)
}

@objc func hideKeyboardByTappingOutside() {
    self.view.endEditing(true)
}

A: Just create an IBOutlet or pointer to the text field  and call [textField resignFirstResponder]; from where ever you want.

A: UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(TapTodissmiss)];

[self.view addGestureRecognizer:tap];

and selector
-(void)TapTodissmiss{

    [self.txtffld resignFirstResponder];

}

A: I am posting this as a separate answer because a lot of the other answers recommend using [textField resignFirstResponder]. This is causing an invalid capability error in Xcode 11.5 with the incomprehensible addition "Unable to insert COPY_SEND"
On a iPad with iOS 9.3.6:
2020-05-23 20:35:01.576 _BSMachError: (os/kern) invalid capability (20)
2020-05-23 20:35:01.580 _BSMachError: (os/kern) invalid name (15)

On a iPad with iPadOS 13.5:
2020-05-23 20:38:49 [Common] _BSMachError: port 12f0f; (os/kern) invalid capability (0x14) "Unable to insert COPY_SEND"

On a iPhone with iOS 13.5:
2020-05-23 20:43:34 [Common] _BSMachError: port d503; (os/kern) invalid capability (0x14) "Unable to insert COPY_SEND"

[textField resignFirstResponder] cannot be used anymore.

A: When possible the best option is to make your UIView to inherit from UIButton instead.
You just need to change it in Interface Builder and immediately you will get the options to create an Action "Touch Up Inside" like any other button.
Your view will work as usual because UIButton is still a view but you will get notified when someone taps on the view. There you can call
[self.view endEditing:YES];

To resign any keyboard.
Please note that if your view is an UIScrollView this solution is not for you.

A: Create your IBOutlet in ViewController.h file like below:
//YOUR ViewController.h FILE

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController
{
    //WIRE THIS WITH YOUR UITextField OBJECT AT YOUR .xib FILE
    IBOutlet UITextField *yourIBOutletUITextField;
}

@end

Add this to your ViewController.m file:
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
     [yourIBOutletUITextField resignFirstResponder];
}

like below:
//YOUR ViewController.m FILE

#import "ViewController.h"

@implementation ViewController

//ADD THIS METHOD BELOW
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
     [yourIBOutletUITextField resignFirstResponder];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    }

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}

@end

A: For my implementation, [self.view endEditing:YES] did not work.
To finally make sure the keyboard was hidden, I had to make one of my views the first responder, and then immediately make it resign as per the function below:
-(void) hideKeyboardPlease{
   [uiTextTo becomeFirstResponder];
   [uiTextTo resignFirstResponder];
}

A: This is what I do...
UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideAllKeyboards)];
tapGesture.cancelsTouchesInView = NO;
[self.view addGestureRecognizer:tapGesture];

-(void) hideAllKeyboards {
    [textField_1 resignFirstResponder];
    [textField_2 resignFirstResponder];
    [textField_3 resignFirstResponder];
    .
    .
    .
    [textField_N resignFirstResponder];
}

A: This is the easiest way iv found that works consistently. Just add a tap gesture recognizer on the view and you're good to go.
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {

[self.view endEditing:YES];

}

A: Update
I found another simple way
simply declare a property :-
@property( strong , nonatomic) UITextfield *currentTextfield;

and a Tap Gesture Gecognizer:-
@property (strong , nonatomic) UITapGestureRecognizer *resignTextField;

In ViewDidLoad
_currentTextfield=[[UITextField alloc]init];
_resignTextField=[[UITapGestureRecognizer alloc]initWithTarget:@selector(tapMethod:)];

[self.view addGestureRecognizer:_resignTextField];

Implement the textfield delegate method didBeginEditing
 -(void)textFieldDidBeginEditing:(UITextField *)textField{

      _currentTextfield=textField;

    }

Implement Your Tap Gesture Method (_resignTextField)
 -(void)tapMethod:(UITapGestureRecognizer *)Gesture{

     [_currentTextfield resignFirstResponder];

 }

A: Create a big button behind it all, and the button's callback calls resignFirstResponder to every input you have. Just make sure to put everything that the user interacts with on top of the button.
Of course the button will be custom rect and transparent.
I would look into implementing an IBOutletCollection called resignables and set every input to that collection. And the button callback iterates over that collection calling resignFirstResponder to them all.
Edit: if it is a re-sizable scroll view, remember to correctly set the re-size markers in the button's view option, that way the button will always expand and contract to the scrollview's height and width


Q: coordinates for google maps from MySQL database, the right way for optimization? Is there a right way of getting coordinates from mysql for Google Maps?
The current way I'm doing is I have jQuery script to get coordinates from a populated element which I use MySQL to populate a list of coordinates.
// jQuery script to get the coordinates

var coordArray = [];

$(".marker").each(function(index,div)
{

 var coords = $(this).data("coords").split(",");
 coordArray.push([coords[0],coords[1]]);

});

//while loop in PHP and I have displayed the coordinates within a
 element:

while($row = $sql->fetch(PDO::FETCH_ASSOC))
{
 <div class="marker" data-coords="<?php echo $row['lat'].",".$row['lng'];?>">stuff

}

Is there a better way of doing so? Or would this be okay as well?

A: In your php you would create an array of the values from  DB in your while loop. Then output this array to a javascript variable using json_encode
$arr=array();
while($row = $sql->fetch(PDO::FETCH_ASSOC)){
   $arr[]=array( $row['lat'], $row['lng']);
}

echo `';

This will create a JavaScript array in page you would loop over to create markers:

You could also retirve the JSOn data using AJAX depending on your needs


Q: OR tag is not working with Cucumber Runner class For some reason when i apply OR tags in Runner class it not working my console just print
0 scenarios
0 steps
0.01ms

But when I provide individual tags then it works fine, can anyone provide timely help to fix this issue, please let me know what is missing here
Feature file
Feature: Validate foreign exchange rates for positive and negative scenarios

  Scenario Outline: Verify rates for latest and past dated foreign exchange rates

    Given rates for foreign exchange rates
    When user calls Get http request with <Uri>
    Then user gets success with status code 200
    And <base> in response body is <baseValue>

    @Regression
    Examples: Positive scenarios
    |Uri            |base  |baseValue|
    |/api/latest    |base  |EUR      |
    |/api/2020-05-08|base  |EUR      |
    |/api/2010-01-14|base  |EUR      |

 Scenario Outline: Verify the response from invalid url for

    Given rates for foreign exchange rates
    When user calls invalid Get http request with <Uri>
    Then user gets error message with status code 400

    @NegativeTest
    Examples: Negative scenarios
    |Uri            |
    |/api/          |
    |/api/2020-02-30|
    |/api/20100114  |

Runner Class
@RunWith(Cucumber.class)
@CucumberOptions(
        features="src/main/java/features",//the path of the feature files
        glue= {"stepDefinitions"},//the path of the step definition files
        tags= {"@Regression,@NegativeTest"},**// this one is not working**
        //tags = {"@Regression"},
        monochrome=true //display the console output in a proper readable format
        )

public class TestRunner {

}

A: Seems you are using the latest version of cucumber and it doesn't recognize the old way of mentioning multiple tags.
For the mentioned example ,we can run both scenarios by mentioning tags = {"@Regression or @NegativeTest"} in runner class
(ie tags = {"@Regression,@NegativeTest") should be given as tags = {"@Regression or @NegativeTest"})
Also in the above query , i could see that tags are used above example keyword. Normally the tags can be used at the feature file level or before the scenario/scenario outline keywords


Q: Looping through all the worksheets in a workbook This is my code to loop through all worksheets. I want to copy particular cell value from all the sheets and paste it to my master sheet. First i tried for one work sheet, its working fine. I modified the same code to loop through all the worksheets in the workbook. I displayed worksheets name and data which i want to copy. Its going to all the worksheets properly but i am not getting the data for worksheets except first sheet. Even its not displaying in msgbox except for first worksheet.
    For Each ws In ActiveWorkbook.Worksheets
    If Range("C3").Value = "" Then
    Coverge_ID = Range("C2")
    MsgBox Coverge_ID
    ThisWorkbook.Worksheets(2).Activate
    Range("A1").Offset(I, 0) = Coverge_ID
    I = I + 1
    Else
    Coverge_ID = Range("C3")
    MsgBox Coverge_ID
    ThisWorkbook.Worksheets(2).Activate
    Range("A1").Offset(I, 0) = Coverge_ID
    I = I + 1
    End If
    MsgBox ws.Name
    Next ws

A: Couple of things:

*

*You're not actually referring to the sheet in the loop by qualifying Range() with your ws variable

*You don't need to activate the worksheet to append a value to it

Try the below code instead:
Dim ws As Worksheet
Dim i As Long
Dim Coverage_ID As String

For Each ws In ActiveWorkbook.Worksheets
    If ws.Range("C3").Value = "" Then
        Coverage_ID = ws.Range("C2").Value
        MsgBox Coverage_ID
        ThisWorkbook.Worksheets(2).Range("A1").Offset(i, 0) = Coverage_ID
        i = i + 1
    Else
        Coverage_ID = ws.Range("C3").Value
        MsgBox Coverage_ID
        ThisWorkbook.Worksheets(2).Range("A1").Offset(i, 0) = Coverage_ID
        i = i + 1
    End If
    MsgBox ws.Name
Next ws


Q: Find the class of the clicked item using Jquery I have the following code:
    $(".perf-row").click(function(e) {
      if (e.target.tagName.toLowerCase() == "a") {
        pageTracker._trackPageview($(this).attr("rel"));
        return true; //link clicked
      } else {
        window.open($(this).attr("rel"));return false;
      }
    });

to the conditional statment of if (e.target.tagName.toLowerCase() == "a") i would like to also add "OR class is equal to price".
I'm not quite sure how to do that, i can't seem to find the class of the clicked element (which will be a td inside the table row).
i've tried $(this).class, $(this.class) but neither work....
Help would be greatly appreciated!

A: To see whether the element has class .price, use the $.hasClass() method.
$(this).hasClass("price");

A: You could combine both your tests into a single jQuery command:
if( $(e.target).is('.price, a') ) { .... }

That tests if the target is either has the class price, or is an a tag, or is both. If you wanted to test that it was an a tag and had the price class, you would use this:
if( $(e.target).is('a.price') ) { .... }

Update: I may have misread your question. If you were going to add this second test to the same if test, then use my code. If you wanted to add a else if then use the .hasClass method as explained by the other answers.

A: you can try:
$(this).attr("class");

but this will return you names of all the classes applied to the element.


Q: type parameters generics in interfaces and concrete classes I'm creating something like this and got struck about the usage of generics in java.
Idea: Producer produces something of type T and consumers contains command objects, command objects holds different mediators. Mediators holds objects of type Subject and updates values of type T
Note: I'm doing this to understand how generics works in terms of inheritance of the generic types and composition of the type parameter definitions in generic type intefaces and concrete classes, so please don't bother about rationale of the design.
Interfaces definitions:
Composition:

*

*IObserver

*ISubject which holds object of type T and IObserver.

*IMediator holds objects of type ISubject and type T

*ICommand holds objects of type IMediator and type T

*IProducerConsumer holds objects of type T and ICommand.
There are some concrete Objects for the corresponding interfaces.
I defined interfaces like this:
public interface IObserver<T>
public interface ISubject<T,O extends IObserver<T>>

Cool until now. But Now the problems started.
public interface IMediator<T,S extends ISubject<T,O>, O extends IObserver<T>>

compiler is forcing me to do this. I mean  O extends IObserver<T> as above. So, I infered that I can't define like below
public interface IMediator<T,S extends ISubject<T,O extends IObserver<T>> >

I concluded: that inner type parameter definition must not be expanded as above.
So, finally happy with
public interface IMediator<T,S extends ISubject<T,O>, O extends IObserver<T>>
Now mess started in ICommand
public interface ICommand <T,M extends IMediator<T, ?, ?>>,
I'm struck now compiler is not accepting many of my possibilities even what inference i made as above. I mean
public interface ICommand <T,M extends IMediator<T, S, o>, S extends ISubject<T, IObserver<T>>,O extends IObserver<T>>

is not working.
I don't want to user  wild card I want to tell to the compiler something more concrete.
My questions are:

*

*Is my inference correct as in ICommand definition.

*How to interpret the above case studies.

*What are the best defintions assuming that I want to insert T and must able to get and put.

*What is the rules and relations of the type parameter definitions in interface and implemented classes.
Please explain ?

A: Generics with Bound Parameters (no wildcards)

*

*Is my inference correct as in ICommand definition?
No. Two reasons

*

*You have written a small 'o' while passing it to Mediator. (I guess it's just a typing mistake.)

*You passed IObserver<T> in stead of O to ISubject which would definitely cause a parameter bound mismatch.

Correct Version:
interface ICommand<T, M extends IMediator<T, S, O>, S extends ISubject<T, O>, O extends IObserver<T>>

*

*How to interpret the above case studies?

*

*The first thing you'd need to understand that you have one unknown type T and five interfaces.

*Therefore you would have total six concrete types which have to be included progressively in the interface declarations. (You explicitly asked not to bother about rationale of the design.)

*If you write them in a correct order, it becomes much more manageable.

Interface declarations:
interface IObserver<T>

interface ISubject<T, O extends IObserver<T>>

interface IMediator<T, O extends IObserver<T>, S extends ISubject<T,O>>

interface ICommand<T, O extends IObserver<T>, S extends ISubject<T, O>,
                   M extends IMediator<T, O, S>>

interface IProducerConsumer<T, O extends IObserver<T>, S extends ISubject<T, O>,
                   M extends IMediator<T, O, S>, C extends ICommand<T, O, S, M>>

*

*What are the best defintions assuming that I want to insert T and must able to get and put?

*

*If you want to get and put object of type T, what you probably need is bunch of interfaces which take only one parameter T. Generics will enforce that all would be compatible as T will be replaced by same type everywhere.

*Your current system is too rigid. In real scenario, you would never have so many implementations of these interfaces (unless you are re-implementing facebook in java) so that you'd have many possible combinations of the implementations and you want to ensure compatibility.

*Generics enforces type-safety by applying restrictions which are good. But you should not put restrictions just because you can put them. You are losing flexibility, readability and maintainability of your code.

*You should add bounds only when you need them. They should not affect the design in any way before contracts between interfaces have been decided.

Possibly sufficient way:
interface IObserver<T>

interface ISubject<T>

interface IMediator<T>

interface ICommand<T>

interface IProducerConsumer<T>

*

*What is the rules and relations of the type parameter definitions in interface and implemented classes?

*

*The only relation between type parameters in interfaces and implementing class that I can think of is that implementing class has to provide a type to replace the generic type parameter.

*In some cases, that type can again be a generic type in which case the responsibility of providing concrete type is forwarded to the code using the class reference or another class which extends that class. It may even be recursive!

*The rules are not written in the language, in stead, you are applying all the rules on this mechanism when you make any type parameter bound. So as long as you are supplying a type which qualifies against all of your rules, you are good to go.

*More rules means more robust but less flexible/readable. So do the trade of wisely.

Two simple cases:
// General way
private class ProductObserver implements IObserver<Product> { }

private ProductObserver productObserver;

// Aspect oriented way
private class LoggerObserver<T> implements IObserver<T> { }

private LoggerObserver<Product> loggerObserver;

*

*Lastly, I'd suggest you to read (comprehensive) Java Generics FAQ by Angelika Langer if you have any further doubt.

*If you keep experimenting like this, you might as well end up inventing a design pattern. Don't forget to share it with us when you do :D

Hope this helps.
Good luck.


Q: MySQL: Mass Conversion Script for Table Engine I'm trying to figure out how to convert en mass from database table engine A to table engine B (in this case, from MyISAM to InnoDB).  I know I can do it for individual tables using the MySQL workbench, but i'd like a script or a program that can do the conversion en mass.  Anyone got any ideas?
* EDIT * I'd prefer an SQL query that I could use to do this, without using php, if possible.

A: In pseudo code using information_schema tables:
$rows = "SELECT TABLE_NAME
    FROM INFORMATION_SCHEMA.TABLES
    WHERE TABLE_SCHEMA = 'yourDBName'
        AND ENGINE LIKE 'engineA'";
foreach ($rows as $table) {
    $query = 'ALTER TABLE '.$table.' ENGINE = engineB';
}


Q: Position of the node of a graph relative to an underlying picture In the following code
reg = Import["https://i.stack.imgur.com/m9fyf.png"];
noeuds = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18};
arcs = {1 <->  2, 1 <->  3, 1 <-> 4, 2 <-> 3, 2 <-> 5, 2 <-> 6,
       2 <-> 7, 3 <-> 4, 3 <-> 8, 4 <-> 8, 4 <-> 9, 5 <-> 6, 6 <-> 7,
       6 <-> 9, 7 <-> 8, 7 <-> 9, 8 <-> 10, 9 <-> 10, 9 <-> 11, 10 <-> 12,
        11 <-> 12};
posom = {{6.5, 10}, {5, 7.9}, {7, 7.7}, {10, 7.7}, {2, 7}, {4,
        6.2}, {6, 6.2}, {9, 6.2}, {5.5, 4}, {8, 4}, {6.5, 2}, {8.5,
        2}, {10, 0}, {0.4, 9.35}, {0.3, 8}, {0.3, 7}, {0.3, 6}, {1, 2}};
Overlay[{reg,
      Graph[noeuds, arcs, VertexCoordinates -> posom,
       VertexSize -> {"Scaled", .02}, VertexLabels -> "Name",
       ImageSize -> 700]}]

I have some difficulties to chose the place of the vertex for two reasons
I have not starting point on the graph to adjust the nodes. Secondly when I change the position of a node the graph is changed. How can I do ?
Here is the picture ?
I wonder if there is a way to have a grid on the picture to position the nodes ?

A: Well, maybe you can do some image processing to find center points of each regions but sometimes manual processing could be better (unless you have many cases).
Using Manipulate manually move your node and then by clicking + symbol paste snapshot
Manipulate[
 Show[{reg,
   Graph[noeuds, arcs, VertexCoordinates -> vcoord,
    VertexSize -> {"Scaled", .02}, VertexLabels -> "Name"]},
  ImageSize -> 700], {{vcoord, 90 posom}, Locator}]

DynamicModule[{vcoord = {{571.5`, 809.`}, {412.`, 730.`}, {568.5`,
     707.`}, {755.`, 699.`}, {230.`, 653.`}, {352.5`, 600.`}, {503.`,
     578.`}, {688.`, 585.`}, {413.5`, 395.`}, {657.5`, 413.`}, {524.`,
      275.`}, {772.5`, 313.`}, {954.`, 129.`}, {56.5`, 835.`}, {33.5`,
      738.`}, {37.5`, 649.`}, {48.5`, 540.`}, {147.5`, 281.`}}},
 Show[{reg,
   Graph[noeuds, arcs, VertexCoordinates -> vcoord,
    VertexSize -> {"Scaled", 0.02`}, VertexLabels -> "Name"]},
  ImageSize -> 700]]

A: This answer is complementary to Halmir's answer.
After you adjusted the coordinates, you can copy the coordinates and use them as your final result.
In:
img = Import["https://i.stack.imgur.com/m9fyf.png"];
noeuds = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17,
   18};
arcs = {1 <-> 2, 1 <-> 3, 1 <-> 4, 2 <-> 3, 2 <-> 5, 2 <-> 6, 2 <-> 7,
    3 <-> 4, 3 <-> 8, 4 <-> 8, 4 <-> 9, 5 <-> 6, 6 <-> 7, 6 <-> 9,
   7 <-> 8, 7 <-> 9, 8 <-> 10, 9 <-> 10, 9 <-> 11, 10 <-> 12,
   11 <-> 12};
posom = {{6.5, 10}, {5, 7.9}, {7, 7.7}, {10, 7.7}, {2, 7}, {4,
    6.2}, {6, 6.2}, {9, 6.2}, {5.5, 4}, {8, 4}, {6.5, 2}, {8.5,
    2}, {10, 0}, {0.4, 9.35}, {0.3, 8}, {0.3, 7}, {0.3, 6}, {1, 2}};
graph[vcs_] :=
 Graph[noeuds, arcs, VertexCoordinates -> vcs,
  VertexSize -> {"Scaled", .02}, VertexLabels -> "Name"]
showMap[vcs_] := Show[{img, graph[vcs]}, ImageSize -> 700];
manipulateMap[] :=
 Manipulate[{cs = vcoord; showMap[vcoord]}, {{vcoord, 90 posom},
   Locator}]

Dynamic[cs]
manipulateMap[]

Out:

A: I know you try to specify the vertices coordinate to get a graph with a adjacent relationshiop.But I want to provide a method to generate such graph by your map image directly.
Firstly,I will remove those texts and small islands by CommonestFilter
img = Import["https://i.stack.imgur.com/m9fyf.png"];
imgPro = CommonestFilter[img, 8]

Let's build a image matrix.I mean I will replace every country with a difference integer in this matrix.I don't very content with this step resorted to DominantColors,and I hope to know this solution can be improved in furture by others.
imgMatrix = IntegerPart[ImageData[ImageAdd @@ MapIndexed[ImageMultiply[#, First[#2]] &,
        Flatten[Image /@ Values[ComponentMeasurements[#, "Mask"]] & /@
        Rest[DominantColors[imgPro,Automatic,"CoverageImage", MinColorDistance -> .1]]]]]];

Of course,we can show this matrix by MatrixPlot
MatrixPlot[imgMatrix, ColorFunction -> Hue,ColorRules -> {0 -> White}]

We can get the adjacent relation from this matrix by ComponentMeasurements
adj = ComponentMeasurements[imgMatrix, "Neighbors"]

Show the img and our graph in following
Row[{graph = SimpleGraph[
    Graph[Keys[adj], UndirectedEdge @@@ Flatten[Thread /@ adj]],
    VertexCoordinates -> ComponentMeasurements[imgMatrix, "Centroid"],
     EdgeStyle -> Directive[Red, Thick], VertexStyle -> Blue,
    VertexSize -> Medium], Show[img, graph]}]