PHP: Ways to tidy up date time information?

Question: A PHP/Laravel program of mine collects time dates from an API endpoint, in a variable that I'll call $time. It's presented in the following format:
2018-12-10T22:14:04Z
I want to tidy it up into something more typical, like any of the following:
"10-12-2018"
"22:14, 10-12-2018"
"10-12-2018, 22:14:04"
I'm new to this facet of PHP, so I've been researching different ways to do this. While I've come across some questions similar to mine, and I've found the documentation for tools like createfromformat and strtotime, but from what I've read I don't think they solve for the precise format I'm working with.
Are there any built-in ways in PHP that I can do this? Or any lines of code people might suggest I try to reformat the date as I want to? Any help on this would be greatly appreciated
Comment: That looks like an ISO 8601 date format so you *should* be able to use the [format 'c'](https://www.php.net/manual/en/function.date.php) with `DateTime::createfromformat()`
Comment: You should be aware of the danger of 'tidying' date strings. '2018-12-10T22:14:04Z' has the very desirable property that *most* common software that deals with converting date strings into DateTime objects (whether in PHP, javascript, c#, whatever) will be able to understand that format. Whatever date string that you turn it into may not be as universally recognizable, and you may find yourself having to convert your new date format back into a more universal one later on.

However, if it's just for display purposes and you're not planning on storing the data like that, then bon voyage.
Comment: Why not parse the input string like explained by CD001 and then format it in the expected output format? What have you tried so far? Where are you stuck?
Comment: @TKoL I understand, but I'm not worried about that. I'm not changing the actual property of the value, I'm just presenting it in another way on the front-end for the sake of presentation.
Comment: @CD001 Could you give an example of what that might look like? e.g is it like "echo DateTime::createFromFormat('c', $time)" ?
Comment: `echo (DateTime::createFromFormat('c', '2018-12-10T22:14:04Z'))->format('Y-m-d H:i:s');` ... in theory. **However** that's actually throwing an error on my dev box - and weirdly, if I do the reverse, take a date and format it to `c` (which replaces `Z` with `+01:00`) and put that exact string back in, it still fails to create the `DateTime` object. So it looks like you can format a date to ISO 8601 using `c` but **not** create a `DateTime object with createFromFormat('c', ...)` - the answer you've accepted works fine though :D
Comment: I see! Thank you for the extra understanding! :D
Answer: You can pass your stored datetime string into DateTime() object and freely control format (and more) of it. For example:
$time = '2018-12-10T22:14:04Z';

$dateTimeObject = new \DateTime($time);
echo $dateTimeObject->format('Y-m-d H:i:s'); // will output: 2018-12-10 22:14:04

Answer: I would suggest that you use the Carbon package to convert dates and datetime it is really awesome.
Usually Laravel already contains Carbon but if you somehow do not have it install it using this:
composer require nesbot/carbon

Now you need to import for instance if you want to use it in your controller:
use Carbon\Carbon;

And you should be able to do something like this:
Carbon::createFromFormat('d/m/Y', $yourcurrentformat);

You should read the docs


Programmatically find a moved file by the old name

Question: In an answer to another question, Edward Thomson recommends using QueryItems to find a moved file by its old file name.
However, I can't seem to figure this out.  It looks like it's part of Microsoft.teamfoundation.versioncontrol.server.dll, but I can't seem to locate this anywhere.  I wonder if this is a DLL on the TFS server itself (which I don't have access to at the moment).  If so, it won't help me for what I need.
How can I programmatically find the moved file name by the old file name in TFS 2010?
Comment: Apologies, as jessehouwing correctly points out below, I meant the `GetItems` method call.  (The TFS Java SDK, once upon a time, called that method "query items" to disambiguate from the `Get...` methods that *download items*.  And I'm hopelessly stuck in the past.)  I've updated that original answer to reflect.
Answer: If the server you are talking to is at least TFS 2010 then you can do this using Microsoft.TeamFoundation.VersionControl.Client.VersionControlServer.GetChangesForChangeset().  Once you determine the changeset that the rename occurred in using QueryHistory, call GetChangesForChangeset and pass "true" for the "includeMergeSourceInfo" parameter.  This will populate the "MergeSources" property on each Change object.
With the switch to "slotmode" in 2010 a rename in TFS Version Control is very similar to a "Branch and Delete" operation under the covers.  Because of this, renames are actually tracked as part of "merge history".
So, if you iterate over the changes and find the change that has a MergeSource that is both a rename (see IsRename property) and has your source item then you will have found the target item of the rename operation.
Answer: I think he actually means the GetItem(s) or QueryHistory methods of the
Microsoft.TeamFoundation.VersionControl.Client.VersionControlServer
Namespace:  Microsoft.TeamFoundation.VersionControl.Client
Assembly:  Microsoft.TeamFoundation.VersionControl.Client (in Microsoft.TeamFoundation.VersionControl.Client.dll)

See this msdn page for more information on these items. You can specify a VersionSpec which can include a Deletion Identifier. If I remember correctly though, you'll need to be careful if you want to use this code against older versions of TFS. In TFS2010 slotmode was introduced, which is more efficient and can track filename changes across versions. Before that a rename basically came down to a Delete of the old version and an Add of the new version, no relationship stored.
Comment: Yes - I did indeed mean `GetItems`, thank you for clarifying.  One minor note (more trivia than anything else) around the differences in rename handling between TFS2010 and pre-2010:  in TFS2010, it's actually *more* like an add and a delete than before.  (You'll see this reflected in pending changes on a delete where the source has a "delete, source rename" pending change.)  This actually makes it easier to solve this problem of "where did my file go" because you can query with deletionid.  In TFS2008 (IIRC) you'd have to query the old filename at a version it was known to exist.
Comment: I'm not able to get the new file name by passing the old file name into either GetItems or QueryHistory.  I'm returned the changesets right up to the rename (including the rename), but I don't see any members that return the new file name.  Nor do I see any changesets post rename.  Am I doing something wrong?


Logging with aspects

Question: Have a RESTful web-serice with Facade layer, Service layer and Dao layer.
Trying to journalize all invokes of all methods of classes, marked with annotation @Log
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Log {
}

Here's the aspect code:
public class LoggingAspect {
  @Around("@target(Log)")
  public Object log(ProceedingJoinPoint pjp) throws Throwable {
    log.debug("Start " + pjp.getSignature().getName());
    Object result = pjp.proceed();
    log.debug("End " + pjp.getSignature().getName());
    return result;
  }
}

Facade, Service and Dao are marked with @Log.
Some example:
public Obj Facade.createObj(String name){ //1
  return service.createObj(name);
}

public Obj Service.createObj(String name){ //2
  return dao.createObj(name);
}

public Obj Dao.createObj(String name){ //3
  Long idOfCreatedObj = /*code that creates an object and returns it's ID*/;
  return loadObjById(idOfCreatedObj); /* load the created object by id */
}

public Obj Dao.loadObjById(Long id){ //4
  return /* code that loads the object by it's id */;
}

In this example methods 1, 2, 3 are logged successfully. But the nested dao method (loadObjById) is not logged.
WHY?
P.S. In spring-config.xml there's
    <aop:aspectj-autoproxy proxy-target-class="true"/>
Comment: Has the loadObjById method the @log annotation?
Comment: What AOP implementation are you using? AspectJ weaving, or Spring's dynamic proxies? The latter doesn't work with non-public methods because they can't be proxied. (See the note in this section of the docs: http://static.springsource.org/spring/docs/2.5.5/reference/aop.html#aop-pointcuts-designators)
Comment: **jddsantaella**, yes, it has.

**millimoose**, I use Spring's dynamic proxies. And all these methods are public.
Comment: If I call loadObjById from Facade (by chain, instead of createObj), everything's fine. But when Dao method call other Dao method, the other methods aren't logged.
Comment: The problem is when in Dao method other Dao method is invoked. Or in Service method other Service method is invoked.
Comment: @omickron It doesn't matter whether they're public or not (I phrased it badly), but whether you're calling the method "through" the proxy. Because this proxy is a wrapper that ultimately delegates to your classes, `this` in your code is never an instance of the proxy, and thus won't invoke the aspects. (You can easily verify all this with a debugger.)
Answer: The issue is self calls (this.methodcall()) bypass the dynamic/cglib proxy that is created by Spring to handle the cross cutting concern.
The fix is either to use full Aspectj (compile time or load time weaving) or make the call by getting hold of the proxy (instead of alling this.methodCall(), use proxy.methodCall()
You can get hold of the proxy this way:
<aop:aspectj-autoproxy expose-proxy="true"/>

And in your code:  AopContext.currentProxy() will give you a reference to the proxy. Here is one blog article on this if you are interested - http://www.java-allandsundry.com/2012/07/reference-to-dynamic-proxy-in-proxied.html
Comment: Can you tell me, how to use full Aspectj (compile time or load time weaving)? What do you mean?
Comment: @omickron I think how to set up load time weaving should be mentioned in the Spring docs. (There should also be many blog posts about it on the Web.) AspectJ weaving is a process wherein your class files are *modified in place* (while on disk, or during loading) to add the code of the aspects into the intercepted methods. (As opposed to creating entirely different proxy classes wrapping yours.)
Comment: Great answer Biju Kunjummmen! But I'm wondering.. it is possible to configure  using only annotations?

Logging with aspects


How to pass multiple data fetched from json to next screen in flutter?

Question: I have fetch data from json. Now I have to pass that multiple data to next screen.
I am showing summary in listview and able to send it to next screen. But I am having problem to send multiple data like description, location to next screen.
1) This is JSON data.
List data = {
 "kind": "calendar#events",
 "etag": "\"p32gchndvjbiug0g\"",
 "updated": "2020-04-13T10:36:30.548Z",
 "timeZone": "Asia/Kolkata",
 "items": [
  {
   "kind": "calendar#event",
   "summary": "test event",
   "description": "test description",
   "location": "Maharashtra, India",
   "creator": {
    "email": "firstname.lastname@example.com"
   },
   "start": {
    "dateTime": "2022-09-23T16:30:00+05:30"
   },
  },
{
   "kind": "calendar#event",
   "summary": "DEMO",
   "description": "Join Zoom Meeting\u003cbr\u003e",
   "location": "Nyati Eureka ( Commercial Complex), K",
   "creator": {
    "email": "firstname.lastname@example.com",
    "self": true
   },
   "start": {
    "dateTime": "2020-04-13T10:00:00+05:30"
   },
   }
 ]
}

class Event {
  String kind;
  String etag;
  String summary;
  DateTime updated;
  String timeZone;
 List<Item> items;

  Event({
    this.kind,
    this.etag,
    this.summary,
    this.updated,
    this.timeZone,
    this.accessRole,
    this.items,
  });

  factory Event.fromJson(Map<String, dynamic> json) => Event(
        kind: json["kind"],
        etag: json["etag"],
        summary: json["summary"],
        updated: DateTime.parse(json["updated"]),
        timeZone: json["timeZone"],
       items: List<Item>.from(json["items"].map((x) => Item.fromJson(x))),
      );

  Map<String, dynamic> toJson() => {
        "kind": kind,
        "etag": etag,
        "summary": summary,
        "updated": updated.toIso8601String(),
        "timeZone": timeZone,
       "items": List<dynamic>.from(items.map((x) => x.toJson())),
      };
}

class Item {
  String kind;
  String summary;
  String description;
  String location;

  Item({
    this.kind,
    this.summary,
    this.description,
    this.location,
    });

  factory Item.fromJson(Map<String, dynamic> json) => Item(
        kind: json["kind"],
        summary: json["summary"],
        description: json["description"] == null ? null : json["description"],
        location: json["location"] == null ? null : json["location"],
       );

  Map<String, dynamic> toJson() => {
        "kind": kind,
       "summary": summary,
        "description": description == null ? null : description,
        "location": location == null ? null : location,
       };
}

2) JSON response
  Future<Map<DateTime, List>> getTask() async {
    Map<DateTime, List> mapFetch = {};
    await Future.delayed(const Duration(seconds: 1), () {});
    String link =
        "LINK";
    var res = await http
        .get(Uri.encodeFull(link), headers: {"Accept": "application/json"});
      List data = jsonDecode(res.body)['items'];
       if (res.statusCode == 200) {
      Event event = eventFromJson(res.body);
       return mapFetch;
  }

 void _onDaySelected(DateTime day, List events) {
    setState(() {
      _selectedEvents = events;
    });
  }

3)ListView on first Screen
Widget _buildEventList() {
    return ListView(
     children: _selectedEvents
          .map(
            (event) => Card(
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(10.0),
              ),
              margin: EdgeInsets.symmetric(horizontal: 10.0, vertical: 4.0),
              color: Colors.white,
              child: ListTile(
                leading: Icon(
                  Icons.album,
                  color: Colors.blue,
                ),
                onTap: () =>
                   getItemAndNavigate(event, context),
                  title: Text(
                  event.toString(),
                ),
              ),
            ),
          )
          .toList(),
    );
  }
getItemAndNavigate(String _selectedEvents, BuildContext context) {
    Navigator.push(
        context,
        MaterialPageRoute(
            builder: (context) => EventDetail(itemHolder: _selectedEvents)));
  }

4) I need to get the data in to my next screen how do i get it ?
Comment: @chunhunghan Can you help me to resolve this issue ?
Answer: You can copy paste run full code below
Step 1: In getTask() You can use Future<Map<DateTime, List<Item>>> getTask()
Step 2: For mapFetch[event.items[i].start.dateTime] = [event.items[i]];
Step 3: Event Detail
class EventDetail extends StatefulWidget {
  List<Item> itemHolder;

  EventDetail({this.itemHolder});
  @override
  _EventDetailState createState() => _EventDetailState();
}

class _EventDetailState extends State<EventDetail> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text("Detail"),
        ),
        body: Text(
            ' ${widget.itemHolder[0].creator.email} ${widget.itemHolder[0].description}'));
  }
}

working demo

full code
import 'package:flutter/material.dart';
import 'package:table_calendar/table_calendar.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';

Event eventFromJson(String str) => Event.fromJson(json.decode(str));

String eventToJson(Event data) => json.encode(data.toJson());

class Event {
  String kind;
  String etag;
  DateTime updated;
  String timeZone;
  List<Item> items;

  Event({
    this.kind,
    this.etag,
    this.updated,
    this.timeZone,
    this.items,
  });

  factory Event.fromJson(Map<String, dynamic> json) => Event(
        kind: json["kind"],
        etag: json["etag"],
        updated: DateTime.parse(json["updated"]),
        timeZone: json["timeZone"],
        items: List<Item>.from(json["items"].map((x) => Item.fromJson(x))),
      );

  Map<String, dynamic> toJson() => {
        "kind": kind,
        "etag": etag,
        "updated": updated.toIso8601String(),
        "timeZone": timeZone,
        "items": List<dynamic>.from(items.map((x) => x.toJson())),
      };
}

class Item {
  String kind;
  String summary;
  String description;
  String location;
  Creator creator;
  Start start;

  Item({
    this.kind,
    this.summary,
    this.description,
    this.location,
    this.creator,
    this.start,
  });

  factory Item.fromJson(Map<String, dynamic> json) => Item(
        kind: json["kind"],
        summary: json["summary"],
        description: json["description"],
        location: json["location"],
        creator: Creator.fromJson(json["creator"]),
        start: Start.fromJson(json["start"]),
      );

  Map<String, dynamic> toJson() => {
        "kind": kind,
        "summary": summary,
        "description": description,
        "location": location,
        "creator": creator.toJson(),
        "start": start.toJson(),
      };
}

class Creator {
  String email;

  Creator({
    this.email,
  });

  factory Creator.fromJson(Map<String, dynamic> json) => Creator(
        email: json["email"],
      );

  Map<String, dynamic> toJson() => {
        "email": email,
      };
}

class Start {
  DateTime dateTime;

  Start({
    this.dateTime,
  });

  factory Start.fromJson(Map<String, dynamic> json) => Start(
        dateTime: DateTime.parse(json["dateTime"]),
      );

  Map<String, dynamic> toJson() => {
        "dateTime": dateTime.toIso8601String(),
      };
}

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

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

  final String title;

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

class _MyHomePageState extends State<MyHomePage> with TickerProviderStateMixin {
  List<Item> _selectedEvents;
  int _counter = 0;
  Map<DateTime, List<Item>> _events;
  CalendarController _calendarController;
  AnimationController _animationController;

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

  Future<Map<DateTime, List<Item>>> getTask() async {
    Map<DateTime, List<Item>> mapFetch = {};

    await Future.delayed(const Duration(seconds: 3), () {});

    /*String link = baseURL + fetchTodoByDate;
    var res = await http.post(Uri.encodeFull(link), headers: {"Accept": "application/json"});
    if (res.statusCode == 200) {
      // need help in creating fetch logic here
    }*/

    String responseString = '''
   {
 "kind": "calendar#events",
 "etag": "p32gchndvjbiug0g",
 "updated": "2020-04-13T10:36:30.548Z",
 "timeZone": "Asia/Kolkata",
 "items": [
  {
   "kind": "calendar#event",
   "summary": "test event",
   "description": "test description",
   "location": "Maharashtra, India",
   "creator": {
    "email": "firstname.lastname@example.com"
   },
   "start": {
    "dateTime": "2022-09-23T16:30:00+05:30"
   }
  },
{
   "kind": "calendar#event",
   "summary": "DEMO",
   "description": "Join Zoom Meeting\u003cbr\u003e",
   "location": "Nyati Eureka ( Commercial Complex), K",
   "creator": {
    "email": "firstname.lastname@example.com",
    "self": true
   },
   "start": {
    "dateTime": "2020-04-13T10:00:00+05:30"
   }
   }
 ]
}
    ''';

    Event event = eventFromJson(responseString);

    for (int i = 0; i < event.items.length; i++) {
      mapFetch[event.items[i].start.dateTime] = [event.items[i]];
    }

    return mapFetch;
  }

  void _onDaySelected(DateTime day, List events) {
    print('CALLBACK: _onDaySelected');
    setState(() {
      _selectedEvents = events;
    });
  }

  @override
  void initState() {
    final _selectedDay = DateTime.now();
    _selectedEvents = [];
    _calendarController = CalendarController();
    _animationController = AnimationController(
      vsync: this,
      duration: const Duration(milliseconds: 400),
    );

    _animationController.forward();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      getTask().then((val) => setState(() {
            _events = val;
          }));
      //print( ' ${_events.toString()} ');
    });
    super.initState();
  }

  @override
  void dispose() {
    _calendarController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            _buildTableCalendarWithBuilders(),
            const SizedBox(height: 8.0),
            const SizedBox(height: 8.0),
            Expanded(child: _buildEventList()),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }

  Widget _buildTableCalendarWithBuilders() {
    return TableCalendar(
      //locale: 'pl_PL',
      calendarController: _calendarController,
      events: _events,
      //holidays: _holidays,
      initialCalendarFormat: CalendarFormat.month,
      formatAnimation: FormatAnimation.slide,
      startingDayOfWeek: StartingDayOfWeek.sunday,
      availableGestures: AvailableGestures.all,
      availableCalendarFormats: const {
        CalendarFormat.month: '',
        CalendarFormat.week: '',
      },
      calendarStyle: CalendarStyle(
        outsideDaysVisible: false,
        weekendStyle: TextStyle().copyWith(color: Colors.blue[800]),
        holidayStyle: TextStyle().copyWith(color: Colors.blue[800]),
      ),
      daysOfWeekStyle: DaysOfWeekStyle(
        weekendStyle: TextStyle().copyWith(color: Colors.blue[600]),
      ),
      headerStyle: HeaderStyle(
        centerHeaderTitle: true,
        formatButtonVisible: false,
      ),
      builders: CalendarBuilders(
        selectedDayBuilder: (context, date, _) {
          return FadeTransition(
            opacity: Tween(begin: 0.0, end: 1.0).animate(_animationController),
            child: Container(
              margin: const EdgeInsets.all(4.0),
              padding: const EdgeInsets.only(top: 5.0, left: 6.0),
              color: Colors.deepOrange[300],
              width: 100,
              height: 100,
              child: Text(
                '${date.day}',
                style: TextStyle().copyWith(fontSize: 16.0),
              ),
            ),
          );
        },
        todayDayBuilder: (context, date, _) {
          return Container(
            margin: const EdgeInsets.all(4.0),
            padding: const EdgeInsets.only(top: 5.0, left: 6.0),
            color: Colors.amber[400],
            width: 100,
            height: 100,
            child: Text(
              '${date.day}',
              style: TextStyle().copyWith(fontSize: 16.0),
            ),
          );
        },
        markersBuilder: (context, date, events, holidays) {
          final children = <Widget>[];

          if (events.isNotEmpty) {
            children.add(
              Positioned(
                right: 1,
                bottom: 1,
                child: _buildEventsMarker(date, events),
              ),
            );
          }

          if (holidays.isNotEmpty) {
            children.add(
              Positioned(
                right: -2,
                top: -2,
                child: _buildHolidaysMarker(),
              ),
            );
          }

          return children;
        },
      ),
      onDaySelected: (date, events) {
        _onDaySelected(date, events);
        _animationController.forward(from: 0.0);
      },
      onVisibleDaysChanged: _onVisibleDaysChanged,
    );
  }

  void _onVisibleDaysChanged(
      DateTime first, DateTime last, CalendarFormat format) {
    print('CALLBACK: _onVisibleDaysChanged');
  }

  Widget _buildEventsMarker(DateTime date, List events) {
    return AnimatedContainer(
      duration: const Duration(milliseconds: 300),
      decoration: BoxDecoration(
        shape: BoxShape.rectangle,
        color: _calendarController.isSelected(date)
            ? Colors.brown[500]
            : _calendarController.isToday(date)
                ? Colors.brown[300]
                : Colors.blue[400],
      ),
      width: 16.0,
      height: 16.0,
      child: Center(
        child: Text(
          '${events.length}',
          style: TextStyle().copyWith(
            color: Colors.white,
            fontSize: 12.0,
          ),
        ),
      ),
    );
  }

  Widget _buildHolidaysMarker() {
    return Icon(
      Icons.add_box,
      size: 20.0,
      color: Colors.blueGrey[800],
    );
  }

  Widget _buildEventList() {
    return ListView(
      children: _selectedEvents
          .map((event) => Container(
                decoration: BoxDecoration(
                  border: Border.all(width: 0.8),
                  borderRadius: BorderRadius.circular(12.0),
                ),
                margin:
                    const EdgeInsets.symmetric(horizontal: 8.0, vertical: 4.0),
                child: ListTile(
                  title: Text(event.description),
                  onTap: () {
                    Navigator.push(
                        context,
                        MaterialPageRoute(
                            builder: (context) =>
                                EventDetail(itemHolder: _selectedEvents)));
                  },
                ),
              ))
          .toList(),
    );
  }
}

class EventDetail extends StatefulWidget {
  List<Item> itemHolder;

  EventDetail({this.itemHolder});
  @override
  _EventDetailState createState() => _EventDetailState();
}

class _EventDetailState extends State<EventDetail> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text("Detail"),
        ),
        body: Text(
            ' ${widget.itemHolder[0].creator.email} ${widget.itemHolder[0].description}'));
  }
}

Comment: Thank you very much for helping me to resolving issue. You are true legend.
Answer: Please write your next Screen code similar like this...
 import 'package:flutter/material.dart';

class NextWidget extends StatefulWidget {
  final String event;
  NextWidget({Key key, @required this.event}) : super(key: key);
  @override
  _NextWidgetState createState() => _NextWidgetState(event: event);
}

class _NextWidgetState extends State<NextWidget> {
  final String event;
  _NextWidgetState({Key key, @required this.event});
  @override
  Widget build(BuildContext context) {
    return Container();
  }
}


did not find expected key while parsing a block mapping at line 431 column 15

Question:
I was trying to create a proxy_protocol policy for elb in Cloud formation template in YAML format. I was getting an error "did not find expected key while parsing a block mapping at line 431 column 15". I was trying to run the AWS cli commands while the CFN templates are created and passing required parameters. How to resolve the issue and run the AWS cli commands through CFN templates?
Proxy_policy:
          commands:
            01_Enable_proxy:
              command: "$(aws --region", !Ref "AWS::Region", " elb create-load-balancer-policy ",
                                "         --load-balancer-name ", !Ref "AppELB",
                                "         --policy-name ", !Join [ "", [!FindInMap [EnvironmentToPrettyEnvironmentMap, !Ref "Environment", label], ProxyProtocol]] ,
                                "         --policy-type-name ProxyProtocolPolicyType",
                                "         --policy-attributes AttributeName=ProxyProtocol,AttributeValue=True)"
        set_listener:
          commands:
            01_set_listener:
              command: "$(aws --region", !Ref "AWS::Region", "elb set-load-balancer-policies-for-backend-server",
                                "   --load-balancer-name ",!Ref "AppELB",
                                "   --policy-names ",!Join [ "", [!FindInMap [EnvironmentToPrettyEnvironmentMap, !Ref "Environment", label], ProxyProtocol]],
                                "   --instance-port 80")

Comment: Your YAML doesn't seem to be a valid YAML file because of the indentation for the first `commands` not being equal to that for `set_listener`.
Comment: That error is coming from their Yaml parser. You don't have valid Yaml.
Comment: i tired it but it's not working
Answer: Proxy_policy:
          commands:
            01_Proxy_policy:
              command: !Join ["", [
                               "  $(aws --region ", !Ref "AWS::Region" , " elb create-load-balancer-policy ",
                               "              --load-balancer-name ", !Ref "AppELB",
                               "              --policy-name ", !Join [ "", [!FindInMap [EnvironmentToPrettyEnvironmentMap, !Ref "Environment", label], ProxyProtocol]] ,
                               "              --policy-type-name ProxyProtocolPolicyType ",
                               "              --policy-attributes AttributeName=ProxyProtocol,AttributeValue=True); " ]]
        set_listener:
          commands:
            01_set_listener:
              command: !Join ["", [
                               "  $(aws --region ", !Ref "AWS::Region", " elb set-load-balancer-policies-for-backend-server ",
                               "              --load-balancer-name ", !Ref "AppELB",
                               "              --policy-names ", !Join [ "", [!FindInMap [EnvironmentToPrettyEnvironmentMap, !Ref "Environment", label], ProxyProtocol]] ,
                               "              --instance-port 80); " ]][enter image description here][1]


How to calc properly the size of an image to add fade effect to it

Question: I'm trying to add a fade effect to a banner but I can't properly calc the size of image to adjust the fade properly.
For example. if I have an image 1000x400 I need to adjust the calc to be calc(100% - 1010px); but if the image is 1200x400 I can't change dynamically the size to calc(100% - 1210px);

.container {
  width: 100%;
  min-height: 25rem;
  background-color: coral;
  display: block;
  overflow: hidden;
  position: relative;
}

.background-image {
  width: 100%;
  height: 100%;
  left: 0;
  top: 0;
  position: absolute;
  background-image: url("https://placeimg.com/1000/400/any");
  background-repeat: no-repeat;
  background-position: right;
  background-size: auto 100%;
}

.background-image:after {
  content: "";
  width: calc(100% - 1000px);
  height: 120%;
  position: absolute;
  top: -30px;
  left: 0;
  overflow: hidden;
  box-shadow: 50px 0 100px 100px coral;
}

You can try it on codepen: https://codepen.io/Gabrielr472/pen/jONKNdO
Answer: If you can use css variables you can try this solution:

and in css
width: calc(100% - var(--width));

and if you need to modify it in js:
elem.style.setProperty('--width', '1220px');

https://codepen.io/Xesenix/pen/qBWKoPY


profile.getinstalled() returns null every time in debug mode

Question: I am using this library for integrating facebook with my app  https://github.com/sromku/android-simple-facebook.Its running in debug mode,i have a requirement to use the invite friends functionality and get the friends of users who have installed my app but both or not working.Profile.getinstalled returns null and invite friends is not showing the web view to select friends.Is this because my app is in debug mode(because its working fine with http get requests)?
Getting profile information,friends information etc are working fine.I am even able to get the user's friends who have installed my app using http get method(https://graph.facebook.com/fbid?access_token=appid|appsecret&fields=installed) but using this to check for every friend slows down the whole process.Please help me with this issue.
<code>{
   mSimpleFacebook = SimpleFacebook.getInstance(this);
   mSimpleFacebook.getFriends(onFriendsListener);

OnFriendsListener onFriendsListener = new OnFriendsListener() {
         @Override
            public void onComplete(List<Profile> friends) {
                Boolean appInstallationStatus;
                for (int i = 0; i < friends.size(); i++) {
                  Profile E= friends.get(i);
                  if(E.getInstalled()!=null)
                  {
               System.out.println("----->"+E.getInstalled());
                       //Set a list adapter here
                  }
                }
            }

}
</code>
Here E.getinstalled() is always null but when i use the get method it gives me true or false.
Thanks in advance for any help
Comment: Show us your code. What have you tried so far and what specific problems did you encounter?
Comment: I have added the code in my new edit and my problem is E.getInstalled() always returns null but http get method returns true or false..
Answer: I have a workaround.
<code>@Override
    public void onComplete(List<Profile> friends) {

        facebookFriendArrayList = new ArrayList<FacebookFriendListDTO>();

        for (Profile profile : friends) {
            friendListDto = new FacebookFriendListDTO();
            try {
                if (profile.getInstalled()) {
                    friendListDto.setUserName(profile.getName());
                    friendListDto.setUserBirthday(profile.getBirthday());
                    friendListDto.setUserId(profile.getId());
                    friendListDto.setUserProfilePic(profile.getPicture());

                    facebookFriendArrayList.add(friendListDto);
                }
            } catch (NullPointerException ex) {
                continue;
            }
        }

        facebookFriendListAdapter = new friendListAdapter(getActivity(),
                facebookFriendArrayList);
        facebookFriendListView.setAdapter(facebookFriendListAdapter);
    }
</code>
hope that helped.
Regards,


swig: how to access C array in Python

Question: I have following variable in C code, where I am storing some variables in 2D array. I am trying to access this array in python. I am getting following info..How can I retrieve data from that array
module.c
uin32_t  array_vaiable[10][100]

module.h
extern uint32_t array_variable[10][100]

module.i
%module mod
%{
    #include "module.h"
%}
%include "typemaps.i"
%include "module.h"

swig -python module.i

<Swig Object of type 'int (*)[100]'>

Comment: Exposing global variables in an interface is bad practice. You will always prefer to expose a function returning a variable on an interface. What you can do is cast to simple pointer and use `cpointer.i`
Answer: It is in general a bad idea to expose global variables and you should use a function for exposing static information.
A very crude solution:
module.h
extern uint32_t array_variable[10][100]
uint32_t* cast(uint32_t (*a)[100]);

module.cpp
uint32_t array_variable[10][100] = {{}};
uint32_t* cast(uint32_t (*a)[100]) {
  return &(a[9][99]);
}

module.i
%module example
%{
     #include "test.h"
%}

%include "stdint.i"
%include "cpointer.i"
%pointer_functions(uint32_t, uint32p);

%include "test.h"

and do the following in Python to access e.g. the first element
import example
example.uint32p_assign(example.cast(example.cvar.array_variable),2)
example.uint32p_value(example.cast(example.cvar.array_variable))

If you want to access other elements, you can use carrays.i after that you cast'ed the 2D-array to a 1D-array.

swig: how to access C array in Python


How to delete rows based on field value but not if certain other field values Dont exist

Question: I am working on a financial reporting table for my business and trying to "massage" the data into something the parent company wants to read. I am VERY close.
Essentially, I have this:
Account FPeriod    Balance
   1          0      42
   1          1      53
   1          2      11
   2          0      62
   3          0     567
   3          1     564
   3          2      34

where each account has multiple rows, one for each fiscal period it has transactions in.
Fiscal period 0 represents the opening balance of the account for the fiscal year.
What I need to do is delete rows with fiscal period 0 but not if it is the only entry for that account.
I have done:
Delete from TABLE
WHERE Fperiod = 0

but this removes all the rows with FPeriod 0 where for instance i need to keep account 2 FPeriod 0 as it's the only entry for that account. I do need to delete account 1 and 3 FPeriod 0 rows.
I am not even sure where to begin, thinking maybe a while loop? I hear those are bad if you can avoid them.
I need the output to look like this:
Account FPeriod    Balance
       1          1      53
       1          2      11
       2          0      62
       3          1     564
       3          2      34

Any ideas?
Answer: DELETE FROM TABLE
WHERE Fperiod = 0
AND EXISTS (SELECT 1
            FROM TABLE t1
            WHERE t1.Account = TABLE.Account
             AND  t1.FPeriod > 0)

Answer: ;with cteBase as (
Select *
      ,RowNr=Row_Number() over (Partition By Account Order By FPeriod Desc)
 From YourTable
)
Select * From cteBase where RowNr>1 and FPeriod=0
-- Delete From cteBase where RowNr>1 and FPeriod=0

If you are happy with the results switch the final select with the Delete
From your sample, these two records would be deleted
Account FPeriod Balance
1       0       42
3       0       567

Comment: @GrahamTylerPurchase Happy to help.  Cheers.


Example of dependent random variables $X,Y$ such that there is no measurable $f$ with $Y=f(X)$

Question: Let $(\Omega,\mathcal A,\operatorname P)$ be a probability space and $X,Y$ be real-valued random variables on $(\Omega,\mathcal A,\operatorname P)$.
If $X$ and $Y$ are dependent, can we always find a Borel measurable $f:\mathbb R\to\mathbb R$ with $Y=f(X)$?
This is actually equivalent to the claim that $Y$ is $\sigma(X)$-measurable.
I guess the answer in general is "no", if we understand "dependent" as "not independent" and I guess $Y=f(X)$ for some Borel measurable $f:\mathbb R\to\mathbb R$ is a particular kind of dependence ... But what could dependence mean otherwise?
Answer: Let $A,B,C$ be a partition of the sample space where each of the three sets has positive probability. Let $X=1$ on $A \cup B$ and $0$ on $C$. Let $Y=2$ on $A$, $3$ on $B$ and $1$ on $C$. Note that $P(X=1,Y=1) =0$ but $P(X=1) P(Y=1) >0$. Hence $X$ and $Y$ are not independent. However there is no $f$ such that $Y=f(X)$; this is because if such a function exists then $X=1$ implies $Y=f(1)$. But $Y$ take two distinct values on the set $X=1$.
Comment: @0xbadf00d In Probability Theory one talks about various 'types of dependence': uncorrelated random variables, Markov property, martingale property etc.
Comment: Are there any common ways to express how random variables are dependent then?
Comment: Hm, yes. I ask because I try to make a more rigorous sense of the claim that the covariance is measure the "linear dependence" of random variables. I'm not really sure what's exactly meant. Clearly, assuming $X,Y\in L^2$ and $\operatorname E[X]=\operatorname E[Y]=0$, the covariance of $X,Y$ is just the $L^2$-inner product. On the other hand, they are linearly dependent in the vector space $L^2$, if $Y=aX$ for some $a$ in which case $\operatorname{Cov}[X,Y]=a\operatorname{Var}[X]$.


How to prove that as one zooms in on a point of the graph of a differentiable function, it looks more and more like the tangent at the point?

Question: How can one prove that as one zooms in on a point of the graph of a differentiable function of one variable, the graph looks more and more like the tangent line at the point?
One can see this phenomenon with the aid of computer graph plotters and their zooming capabilities, but how can one really prove this?
Also, it is intuitively clear, but what does it mean mathematically "to look more and more like the tangent line"? I guess we first need a proper mathematical definition of this intuitive notion before we proceed to a proof of the original question, but I have no idea how to obtain one (maybe it considers the "error" made by this tangent approximation in comparison to that of other straight lines at the same point? I really don't know).
Comment: If you look very closely at the definition of the derivative (coupled with the "epsilon-delta" definition of a limit), then you'll see that it precisely captures the intuition you're after: You can always find some neighborhood of the point of tangency such that the vertical distance between the graph and the tangent line are as small as you like.
Comment: Keyword here: Linearity.
Answer: Why not mimic the computer graph plotter idea, namely that after rounding off coordinates to the pixels on a screen, they form a straight line, and otherwise we could compute the standard deviation (via the sum of squares) from the tangent pixels to the graph pixels:

Let us make it simple and define the following screen: $[-b,b]\times(-\infty,\infty)$ pixels and the graph of $f$ translated such that the point of interest $(a,f(a))$ becomes centered at $(0,0)$ on the screen. Then we define a $k$-zoom as meaning that one pixel represents $1/10^k$ units on the graph. For each value of $x:=a+n/10^k$ and corresponding $y=f(x)$ we plot the point $$\newcommand{\round}{\operatorname{round}}P:=\left(\round(10^k(x-a)),\round(10^k(y-f(a))\right)$$ on the screen and compare point by point to the same type of plot of the tangent $$t(x)=f'(a)(x-a)+f(a)$$

Then what we have to prove is that the sum of squares of $y$-differences between the pixel plot of $f$ and $t$ converge to zero (as $k$ tends to $\infty$). Note that those differences can be upper bounded by differences of the form $|y_f-y_t|+1$ so this suggests that solving the problem without rounding off to integer pixel values will essentially give us the same metric of how well they match.


Who is the guy Kratos passes in the Hecatonchires prison that mysteriously disappears?

Question: In the opening act of the game, while chasing Megaera through the prison on Hecatonchires, there is a man that Kratos comes across who seems to be different from most cannon fodder in that he is incredibly buff (arguably more than Kratos), and just as he's about to die, he cries to the gods for help and disappears.  Who is this mystery man?
Answer: Slight spoilers:

This man ends up being your character if you choose to play the multiplayer aspect of Ascension.  As he cries to the gods for help, he teleports to them, then chooses an allegiance to Ares, Hades, Zeus, or Poseidon.  As always, Kratos seems to not care at all about this strange occurrence of a man and potential ally disappearing in front of him.


3-way Fixture Wiring Question

Question: A handyman replaced a light fixture for my sister, but badly screwed up the wiring such that it no longer turns off by either switch (everything worked fine with the old fixture).  I just got here and opened it up, and saw he had the fixtures ground connected to the Red wire, so I can't trust anything in the fixture's current wiring.
I have

2x switches

One of the switches that I peeked at has 2 relevant wires going into the box, of which the switch is connected with 1-black and 2-reds -- I didn't dig deeply into how it's wired, but this seems to imply this circuit isn't connected in any way I'd expect.

In the fixture box (the only part that's been messed with) there are 3 wires into the box:

1x 3-wire+ground cable into fixture (with red/white/black)
2x 2-wire+ground cable into fixture (with black/white)
All ground wires into the box are connected.

The fixture box was incorrectly connected such that all whites were tied together (including the fixture), all blacks tied together (including the fixture), and the red wire connected to the fixture's ground wire. I have no idea what the wiring looked at before the handyman "fixed" it.
The fixture originally worked as expected with either of the two switches.  After the handyman left the light is always on and both switches are non-functional.
What would the correct wiring for the fixture be here to restore normal function to the switches?
Thanks.
Comment: Please post a picture
Comment: Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking.
Comment: I just edited the question to hopefully be a bit clearer.  A photo isn't going to be very helpful here.  As noted, the handyman screwed up the wiring to "fix" things, instead of simply connecting the new fixture with the same wiring scheme as the old as I'd have expected (I didn't find out until weeks later).
Comment: If you haven't already, take that red wire off the ground. As noted, a multimeter or (sometimes, not always) a pen tester can identify the hot wires at the fixture. My gut is that the two wire is permanently hot and that the three wire acts as a switch loop, but you'll never know without diagnostics.
Comment: Yes, fixing the ground was the very first thing I did, thxs. I think I'll have to bite the bullet and hire an electrician (and try to send that handyman the bill after) - no time to buy the appropriate tools and fix it be4 I head home
Answer: You need to identify the wires on those switches, especially the ones that connect to each other (the travelers). I use a multimeter with looooong cables and do continuity testing. Also, a pen tester is pretty handy to test hot wires.

3-way Fixture Wiring Question


HTML to React Conversion blockholes

Question: I have been asked to convert a HTML file to react components.I have used html to jsx compiler. It's a huge file of about 1005 lines of code hence I'm unable to upload the file.
I'm unable to render css and local images even on following the proper syntax.
Synatx followed is something like this
<code>img src={require('./resources/cut.svg')} width={30} height={20}
</code>
Answer: Have you tried importing the items eg image folder at the top and then referencing that in react ?
Also this seems to be what you are doing: How to convert a html template to react
Comment: Yes I have tried importing the images. And you are correct i tried out https://stackoverflow.com/questions/47370369/how-to-convert-a-html-template-to-react

HTML to React Conversion blockholes


Equalizing upstairs and downstairs temperatures when A/C is on

Question: Our A/C unit is in the attic in an unfinished area on the second floor. The A/C thermostat is in the finished area on the other side of the wall from the unit. As expected, the the second floor is generally several degrees warmer than the downstairs and we have the A/C thermostat set at what is for us a comfortable 76 degrees. It appears to be working as expected, but while the upstairs is kept at 76 degrees, the downstairs is generally about 5 degrees colder.
Would a simple solution be to partially close some (all?) of the downstairs A/C vents help to raise the temperature there - I would experiment by gradually making small changes? Or would partially closing the vents in any way hamper the efficient running of the A/C?
Thanks.
Comment: Tell us about the location of the air return(s).
Comment: There is one return. It's on the second floor right above the A/C thermostat (on other side of wall from A/C unit in attic).
Answer: Cold air always sinks (gosh !   :-)  ), so the  stable condition will pretty much always have the lower floor ending up cooler than the upper floor.   Yes,  closing downstairs vents will help balance things out, and at least avoid overshoot in the downstairs temperature.   There should be dampers in the ductwork close to the heat exchanger (in the attic) and those are designed to adjust flow rates for each path.  If those weren't installed, go ahead and partially close whatever dampers are at the exit points of the downstairs vents.
Comment: And don't forget to reset the valves when heating season starts, so that the majority of hot air flows to the lower level.
Comment: The term you're after for those "valves" is *damper*, by the way
Comment: There's no heat exchanger - we have baseboard heating.
Comment: @ThreePhaseEel thanks -- edited.    Next you'll tell me  my electrical valves are diodes :-)
Comment: @Not_Einstein -- the heat exchanger in this case is the indoor (air handler) coil
Answer: Seems like your system is probably arranged pretty well. You can try closing some of the downstairs vents, but keep in mind this increases your risk of having ice form in the evaporator. The reason is this: with some vents closed the unit will have less air flowing through. Less air flowing through means the discharge air at the vents that remain open will get colder. That discharge air being colder means the evaporator is running colder -- and when its temperature drops below freezing ice starts forming. Ice in the evaporator blocks airflow, it gets even colder, and it can quickly cascade into a situation where the whole thing is blocked with ice and won't thaw until you shut the thing off for several hours.
Nevertheless: give it a try. Your system may be operating far enough from the freezing point that you won't have any problem. If it does start freezing, you'll now know why and what to do about it (re-open the downstairs vents).
Comment: That's the kind of consequence I was asking about. But I wasn't considering completely closing any downstairs vents, just reducing their openings a bit.
Answer: This is a common problem in warehouses and homes with high ceilings. You could use a ceiling fan. A device similar to this was designed for such a purpose. You can reverse the air flow based upon the season.
Thermal Equalizing   Note: I have not used this particular product -- not an endorsement.
IT is designed to circulate the air between the ceiling and the floor. Back in the day, there was a long tube with a fan in it that was mounted against a wall or post, etc. This looks like a newer version.
Of course, adding insulation to the unfinished area helps (if there isn't any now).
I would be reluctant to close vents as it changes the airflow and load on the blower. I is even possible to REDUCE the total airflow in the entire system -- exactly the opposite of what you want.
Comment: Sometimes it's hard to get a definitive answer. :-) One person says go ahead and close downstairs vents and another advises against it. I do appreciate the input, even if it is contradictory.
Comment: Agreed. It is contradictory. You can certainly try closing them. It may not have the affect that you want. An HVAC Engineer ($$$) would be able to tell you for sure. I'm always down for an experiment -- it's not like your going to blow up the house. :)


Use baseboard to conceal wires?

Question: I am not a carpenter (programmer actually), therefore I need to know if it is possible to conceal wires in a baseboard. Basically I want a combination of this

And this

But I don't want my entire house to look hideous.
If it is possible, are there any off the shelf baseboards, or do I have to get a carpenter to custom make them?
Comment: What type of wires are you trying to conceal? Line voltage? Low voltage? Audio? Network/Teleco?
Comment: Your corner-track could be hidden by larger crown moldings.  If you need to move up the wall a bit (or punch larger holes in sheetrock) you could apply wainscoting to the walls.  But then, sometimes the 'old english manor' look is more jarring than the cables.  ^_^
Comment: @mac cat5 cables or thin power cables
Comment: @scivitri I had to google a lot of those terms but I think I follow what you are saying
Comment: related : http://diy.stackexchange.com/q/420/86
Answer: Yes it's definitely possible. If you have carpeting you often can just push the wire under the baseboard in the gap left for the flooring.
Otherwise the most common option is to remove the baseboards, and then cut out a strip of drywall at the bottom of the wall. You hide your wires in this channel, and then replace the baseboards.  Make sure that when nailing your baseboards back down that you don't hit any of the wires.
The above advice does not apply to line-voltage wiring but can be used for Telco wiring.
Comment: There are often Electrical Code requirements that in-wall wiring be buried deeply, or be armored, to prevent accidental damage from nails or screws in the future.
Comment: You're right, I was thinking more along the lines of coax/Telco wires.
Answer: Yes, you can take the baseboard off, cut a groove in it on a table saw, and install low voltage cabling.  This would be suitable for a single Ethernet or coax.  Similarly you can groove the drywall behind, but it's messier.  You'll want prime paint after grooving to keep everything from falling apart.
Note that the baseboard area can be a source of air leakage into walls, and you can take the time when the baseboards are off to caulk the remaining junction.
As pictured you have hardwood floors, you must maintain a gap at the edges of hardwood to allow for thermal expansion.
High voltage power wires need to be armored, and this technique is only suitable for hiding conduit.  But in some cases you can relocate a transformer (for certain types of lighting) and bury the low voltage runs.
Answer: There is channel that you can run along the baseboard in place of the quarter round molding.  You paint to to match the baseboard or the quarter round (even cover it with wood-look contact paper) and it isn't noticeable.  Here's an example: Qtr Round Baseboard Channel

Lots of variations on the idea: http://www.homedepot.com/s/channel+raceway?NCNI-5

Use baseboard to conceal wires?


How to Programatically change UItextfield Placeholder and text to right alignment

Question: I am doing localization of Arabic in which i have to do text from right to left.
No i dont wont to use POD or Bundle.I am doing at runtime using CountryPicker for selecting Country.
for label i did using below code which is working
self.userNameLbl.textAlignment = .right

and i have used
UITextField.appearance().semanticContentAttribute = .forceRightToLeft

still no use
Comment: No use for what? You have not explained what the problem is.
Comment: "No i dont wont to use POD or Bundle.I am doing at runtime using CountryPicker for selecting Country." This is a really bad idea. Localization is built into iOS. You are going to be fighting a difficult battle to not do localization the way Apple intended it. Note that you can always do a mix: use built-in localization mechanisms as much as possible, and write custom code (with locale-detection) to fix the parts of your app that still need work.
Comment: My requirement from Client is to use API for 13 languages which i have to do localization of,  almost all languages are done except Right to Left  for Arabic. if i use UITextField.appearance().semanticContentAttribute = .forceRightToLeft  it wont reflect on that screen but it will reflect on next screen.
Answer: i am a little confused with your question you want to change the Alignment of textfield or label but for text field i used this and its working you have to create an outlet for your textfild first or define it in a variable
NameTextField.textAlignment = .right

Answer: go to storyboard -> select your textfield -> attributes inspector -> view -> semantic set to forceRightToLeft.

Comment: setting the attribute in IB is the same as the code the OP posted that supposedly doesn't work. Also IB won't work dynamically since they want the language to dynamically change from left-to-right to right-to-left
Answer: You can do:
label.textAlignment = NSTextAlignment.center;

Or, for shorthand:
label.textAlignment = .center;

Swift 3
label.textAlignment = .center

or
You can set the placeholder text using an attributed string. Pass the color you want with the attributes:
var myTextField = UITextField(frame: CGRect(x: 0, y: 0, width: 200, height: 30))
myTextField.backgroundColor = .blue
myTextField.attributedPlaceholder = NSAttributedString(string: "placeholder text",
                         attributes: [NSForegroundColorAttributeName: UIColor.yellow])

For Swift 3+ use following:
myTextField.attributedPlaceholder = NSAttributedString(string: "placeholder text",
                         attributes: [NSAttributedStringKey.foregroundColor: UIColor.white])

For Swift 4.2 use following:
myTextField.attributedPlaceholder = NSAttributedString(string: "placeholder text",
                         attributes: [NSAttributedString.Key.foregroundColor: UIColor.white])


Complexity of Graph Traversal

Question: What is the computational complexity of breadth-first and depth-first traversal in terms of the number of vertices v and the number of edges e when the graph is represented as an adjacency matrix?
Answer: The complexity is O(v^2), as the adjacency matrix must be searched to obtain all neighbors of a single vertex.

Complexity of Graph Traversal


Reversing and complementing a dna sequence in python

Question: I am having a certain problem when running my code, the console tells me that I have an AttributeError.

AttributeError: 'list' object has no attribute 'replace'

What could I do to fix my problem?

reverse_complement( )

The next step is to write a function named reverse_complement that
takes one argument seq. The argument seq is to be a string that
contains information for the bases of a DNA sequence and return the
reverse complement of that DNA sequence.
To determine the reverse complement, the DNA sequence need be (1)
reversed and (2) complemented.
One way to reverse a string is to use the slicing value of [::-1]
>>> reversed_seq = seq[::-1]

To complement a DNA sequence is to replace all:
all A's with T's
all T's with A's
all C's with G's
all G's with C's
One way to complement a DNA sequence is using the built-in Python
function of replace( ). However, this approach requires you to be
clever in order to get it to work correctly.
Another way to complement a DNA sequence is to loop through all of the
characters in the DNA sequence and use if statements to check for the
different bases and then to use concatenation to build a new string
using the complements of each each base.

def reverse_complement(seq):
    '''This function will reverse and then complement the given dna sequence.'''
    revSeq = seq[::-1]
    revSeq = revSeq.replace("A", "x")
    revSeq = revSeq.replace("T", "y")
    revSeq = revSeq.replace("G", "z")
    revSeq = revSeq.replace("C", "w")

    revSeq = revSeq.replace("x", "T")
    revSeq = revSeq.replace("y", "A")
    revSeq = revSeq.replace("z", "C")
    revSeq = revSeq.replace("w", "G")

    print(revSeq)
    return revSeq

# Tests for reverse_complement function. Should print True.
print ("\nreverse_complement")
print (reverse_complement('ATGCTTG') == 'CAAGCAT')
print (reverse_complement('AAAGGG') == 'CCCTTT')
print (reverse_complement('TTTCCC') == 'GGGAAA')
print (reverse_complement('ATCGATCAGTCCTAGCATCG') == 'CGATGCTAGGACTGATCGAT')

My test cases say they are true, but I am still getting the AttributeError.
Comment: @mkrieger1 no the order does not matter, the output just needs to be a reversely complemented string. I also tried doing an If Else statement but that also did not work out well.
Answer: You can make use of the (very handful) python sequence built-ins, like map and reversed. At the end, re-build the string with str.join
s = 'ATCGATCAGTCCTAGCATCG'

def complement(c):
  if c == 'A': return 'T'
  if c == 'T': return 'A'
  if c == 'C': return 'G'
  if c == 'G': return 'C'
  return c

''.join(map(complement, reversed(s)))            #'CGATGCTAGGACTGATCGAT'

Actually, python has an (almost forgotten) built-in str.translate that does exactly that!
s = 'ATCGATCAGTCCTAGCATCG'
s[::-1].translate(str.maketrans('ATCG','TAGC'))  #'CGATGCTAGGACTGATCGAT'

You gotta love python.
Answer: there is a built-in function in BioPython you can use
from Bio import Seq
seq = 'TTAACCGG'
print(Seq.reverse_complement(seq))

result:
CCGGTTAA


Make/install Python 2.7.6 over 2.7.3 on Ubuntu 12.04 VM, can't find pip installed packages

Question: My Ubuntu 12.04.5 LTS VM already had Python 2.7.3 in /usr/bin:
$ ls -ld /usr/bin/py*
-rwxr-xr-x 1 root root    4124 Jun 18  2013 /usr/bin/pyclean
-rwxr-xr-x 1 root root   11933 Jun 18  2013 /usr/bin/pycompile
lrwxrwxrwx 1 root root       8 Jun 18  2013 /usr/bin/pydoc -> pydoc2.7
-rwxr-xr-x 1 root root      79 Oct 26 14:35 /usr/bin/pydoc2.7
lrwxrwxrwx 1 root root      12 Jun 18  2013 /usr/bin/pygettext -> pygettext2.7
-rwxr-xr-x 1 root root   22103 Oct 26 14:35 /usr/bin/pygettext2.7
-rwxr-xr-x 1 root root     217 Mar  9  2012 /usr/bin/pyhtmlizer
lrwxrwxrwx 1 root root       9 Jun 18  2013 /usr/bin/python -> python2.7
lrwxrwxrwx 1 root root       9 Jun 18  2013 /usr/bin/python2 -> python2.7
-rwxr-xr-x 1 root root 2997528 Oct 26 14:36 /usr/bin/python2.7
-rwxr-xr-x 1 root root    1652 Oct 26 14:35 /usr/bin/python2.7-config
lrwxrwxrwx 1 root root      29 Jun 18  2013 /usr/bin/pyversions -> ../share/python/pyversions.py

I did a wget/configure/make/install of Python 2.7.6 yesterday, and also pip installed a few modules like braceexpand and pytz (/usr/bin/pip was used).
wget  https://www.python.org/ftp/python/2.7.6/Python-2.7.6.tgz
tar xvfz Python-2.7.6.tgz
cd Python-2.7.6
./configure
make
sudo make install

# add more
sudo apt-get install python2.7-dev
wget https://pypi.python.org/packages/c7/14/c4ea891fd8943623dcb325ab1194a1473351b02b82c3c58c8a4179027fdb/python-cdb-0.35.tar.gz
sudo pip install python-cdb-0.35.tar.gz
sudo pip install pytz
sudo pip install braceexpand
sudo pip install html

The modules all installed to /usr/local/lib/python2.7/dist-packages (and are the only things there)
$ ls -l /usr/local/lib/python2.7/dist-packages/
total 200
drwxr-sr-x 2 root staff  4096 Dec 14 22:12 braceexpand-0.1.2.egg-info
-rwxr-xr-x 1 root staff  6218 Dec 14 22:12 braceexpand.py
-rwxr-xr-x 1 root staff  6842 Dec 14 22:43 braceexpand.pyc
-rwxr-xr-x 1 root staff  6842 Dec 14 22:43 braceexpand.pyo
-rwxr-xr-x 1 root staff 87794 Dec 14 22:14 cdbmodule.so
drwxr-sr-x 2 root staff  4096 Dec 14 22:13 html-1.16.egg-info
-rwxr-xr-x 1 root staff 19209 Dec 14 22:13 html.py
-rwxr-xr-x 1 root staff 22326 Dec 14 22:43 html.pyc
-rwxr-xr-x 1 root staff 22326 Dec 14 22:43 html.pyo
drwxr-sr-x 2 root staff  4096 Dec 14 22:14 python_cdb-0.35.egg-info
drwxr-sr-x 3 root staff  4096 Dec 14 22:34 pytz
drwxr-sr-x 2 root staff  4096 Dec 14 22:16 pytz-2016.10.egg-info

not to /usr/lib/python2.7/dist-packages (where a lot of other modules already were)
$ ls -l /usr/lib/python2.7/dist-packages/
total 1968
drwxr-xr-x  3 root root   4096 Nov  6  2014 apt
-rw-r--r--  1 root root  60240 Jan 24  2014 apt_inst.so
-rw-r--r--  1 root root 346320 Jan 24  2014 apt_pkg.so
drwxr-xr-x  2 root root   4096 Nov  6  2014 aptsources
drwxr-xr-x 29 root root   4096 Nov  6  2014 boto
lrwxrwxrwx  1 root root     43 Jun 27  2013 boto-2.2.2.egg-info -> ../../../share/pyshared/boto-2.2.2.egg-info
drwxr-xr-x  2 root root   4096 Nov  6  2014 chardet
lrwxrwxrwx  1 root root     46 Dec 30  2011 chardet-2.0.1.egg-info -> ../../../share/pyshared/chardet-2.0.1.egg-info
drwxr-xr-x  7 root root   4096 Nov  6  2014 Cheetah
drwxr-xr-x  2 root root   4096 Nov  6  2014 Cheetah-2.4.4.egg-info
drwxr-xr-x  3 root root   4096 Jul 20 15:27 cloudinit
lrwxrwxrwx  1 root root     49 Oct 21  2014 cloud_init-0.6.3.egg-info -> ../../../share/pyshared/cloud_init-0.6.3.egg-info
drwxr-xr-x  2 root root   4096 Nov  6  2014 CommandNotFound
lrwxrwxrwx  1 root root     57 Apr 17  2012 command_not_found-0.2.44.egg-info -> ../../../share/pyshared/command_not_found-0.2.44.egg-info
drwxr-xr-x  2 root root   4096 Nov  6  2014 computerjanitor
drwxr-xr-x  2 root root   4096 Nov  6  2014 configobj-4.7.2.egg-info
lrwxrwxrwx  1 root root     36 Dec 30  2011 configobj.py -> ../../../share/pyshared/configobj.py
-rw-r--r--  1 root root  65941 Nov  6  2014 configobj.pyc
drwxr-xr-x  9 root root   4096 Nov  6  2014 Crypto
drwxr-xr-x  2 root root   4096 Nov  6  2014 curl
drwxr-xr-x  3 root root   4096 Nov  6  2014 dbus
-rw-r--r--  1 root root 163024 Jan 27  2012 _dbus_bindings.so
-rw-r--r--  1 root root  10952 Jan 27  2012 _dbus_glib_bindings.so
lrwxrwxrwx  1 root root     33 Jan 25  2012 deb822.py -> ../../../share/pyshared/deb822.py
-rw-r--r--  1 root root    317 Nov  6  2014 deb822.pyc
lrwxrwxrwx  1 root root     34 Mar 15  2012 debconf.py -> ../../../share/pyshared/debconf.py
-rw-r--r--  1 root root   5888 Nov  6  2014 debconf.pyc
drwxr-xr-x  2 root root   4096 Nov  6  2014 debian
drwxr-xr-x  2 root root   4096 Nov  6  2014 debian_bundle
drwxr-xr-x  2 root root   4096 Dec 14 20:58 distribute-0.6.24dev_r0.egg-info
drwxr-xr-x  2 root root   4096 Nov  6  2014 DistUpgrade
lrwxrwxrwx  1 root root     39 Oct 22  2011 easy_install.py -> ../../../share/pyshared/easy_install.py
-rw-r--r--  1 root root    315 Dec 14 20:59 easy_install.pyc
drwxr-xr-x  4 root root   4096 Nov  6  2014 euca2ools
lrwxrwxrwx  1 root root     48 Jun  4  2012 euca2ools-2.0.0.egg-info -> ../../../share/pyshared/euca2ools-2.0.0.egg-info
drwxr-xr-x  6 root root   4096 Nov  6  2014 gi
lrwxrwxrwx  1 root root     53 Dec 30  2011 GnuPGInterface-0.3.2.egg-info -> ../../../share/pyshared/GnuPGInterface-0.3.2.egg-info
lrwxrwxrwx  1 root root     41 Dec 30  2011 GnuPGInterface.py -> ../../../share/pyshared/GnuPGInterface.py
-rw-r--r--  1 root root  22520 Nov  6  2014 GnuPGInterface.pyc
drwxr-xr-x  2 root root   4096 Nov  6  2014 httplib2
lrwxrwxrwx  1 root root     47 Sep  6  2013 httplib2-0.7.2.egg-info -> ../../../share/pyshared/httplib2-0.7.2.egg-info
drwxr-xr-x  2 root root   4096 Nov  6  2014 HweSupportStatus
lrwxrwxrwx  1 root root     40 Sep 13  2013 ipachangeconf.py -> ../../../share/pyshared/ipachangeconf.py
-rw-r--r--  1 root root  16716 Nov  7  2014 ipachangeconf.pyc
drwxr-xr-x  5 root root   4096 Nov  6  2014 keyring
drwxr-xr-x  2 root root   4096 Nov  6  2014 keyring-0.9.2.egg-info
drwxr-xr-x  2 root root   4096 Nov  6  2014 LanguageSelector
drwxr-xr-x  2 root root   4096 Nov  6  2014 language_selector-0.1.egg-info
lrwxrwxrwx  1 root root     48 Sep 13  2013 language_support_pkgs.py -> ../../../share/pyshared/language_support_pkgs.py
-rw-r--r--  1 root root   9733 Nov  6  2014 language_support_pkgs.pyc
drwxr-xr-x  4 root root   4096 Nov  6  2014 launchpadlib
drwxr-xr-x  2 root root   4096 Nov  6  2014 launchpadlib-1.9.12.egg-info
drwxr-xr-x  4 root root   4096 Nov  6  2014 lazr
drwxr-xr-x  2 root root   4096 Nov  6  2014 lazr.restfulclient-0.12.0.egg-info
lrwxrwxrwx  1 root root     59 Jun 14  2013 lazr.restfulclient-0.12.0-nspkg.pth -> ../../../share/pyshared/lazr.restfulclient-0.12.0-nspkg.pth
drwxr-xr-x  2 root root   4096 Nov  6  2014 lazr.uri-1.0.3.egg-info
lrwxrwxrwx  1 root root     48 Jan 25  2012 lazr.uri-1.0.3-nspkg.pth -> ../../../share/pyshared/lazr.uri-1.0.3-nspkg.pth
lrwxrwxrwx  1 root root     38 Jun 13  2013 lsb_release.py -> ../../../share/pyshared/lsb_release.py
-rw-r--r--  1 root root   7587 Nov  6  2014 lsb_release.pyc
drwxr-xr-x  4 root root   4096 Nov  6  2014 M2Crypto
drwxr-xr-x  2 root root   4096 Nov  6  2014 M2Crypto-0.21.1.egg-info
drwxr-xr-x  2 root root   4096 Nov  6  2014 oauth
drwxr-xr-x  2 root root   4096 Nov  6  2014 oauth-1.0.1.egg-info
drwxr-xr-x  3 root root   4096 Nov  6  2014 OpenSSL
lrwxrwxrwx  1 root root     42 Mar  8  2012 PAM-0.4.2.egg-info -> ../../../share/pyshared/PAM-0.4.2.egg-info
-rw-r--r--  1 root root  19640 Mar  8  2012 PAMmodule.so
drwxr-xr-x  2 root root   4096 Nov  6  2014 paramiko
lrwxrwxrwx  1 root root     49 Mar 28  2013 paramiko-184.108.40.206.egg-info -> ../../../share/pyshared/paramiko-22.214.171.124.egg-info
drwxr-xr-x  4 root root   4096 Dec 14 20:59 pip
drwxr-xr-x  2 root root   4096 Dec 14 20:58 pip-1.0.egg-info
lrwxrwxrwx  1 root root     40 Oct 22  2011 pkg_resources.py -> ../../../share/pyshared/pkg_resources.py
-rw-r--r--  1 root root  94800 Nov  6  2014 pkg_resources.pyc
lrwxrwxrwx  1 root root     41 Oct 30  2014 problem_report.py -> ../../../share/pyshared/problem_report.py
-rw-r--r--  1 root root  15479 Nov  6  2014 problem_report.pyc
lrwxrwxrwx  1 root root     47 Jun 27  2012 pycrypto-2.4.1.egg-info -> ../../../share/pyshared/pycrypto-2.4.1.egg-info
lrwxrwxrwx  1 root root     46 Dec 30  2011 pycurl-7.19.0.egg-info -> ../../../share/pyshared/pycurl-7.19.0.egg-info
-rw-r--r--  1 root root  68880 Dec 30  2011 pycurl.so
lrwxrwxrwx  1 root root     47 Sep 23  2013 pyOpenSSL-0.12.egg-info -> ../../../share/pyshared/pyOpenSSL-0.12.egg-info
lrwxrwxrwx  1 root root     45 Dec 30  2011 pyserial-2.5.egg-info -> ../../../share/pyshared/pyserial-2.5.egg-info
-rw-r--r--  1 root root 447336 Sep 13  2013 pysss.so
lrwxrwxrwx  1 root root     58 Jan 24  2014 python_apt-0.8.3ubuntu7.2.egg-info -> ../../../share/pyshared/python_apt-0.8.3ubuntu7.2.egg-info
drwxr-xr-x  2 root root   4096 Nov  6  2014 python_debian-0.1.21ubuntu1.egg-info
lrwxrwxrwx  1 root root     44 Dec 16  2011 PyYAML-3.10.egg-info -> ../../../share/pyshared/PyYAML-3.10.egg-info
-rw-r--r--  1 root root    119 Oct 26 14:35 README
drwxr-xr-x  2 root root   4096 Nov  6  2014 serial
drwxr-xr-x  4 root root   4096 Dec 14 20:59 setuptools
lrwxrwxrwx  1 root root     43 Oct 22  2011 setuptools.egg-info -> ../../../share/pyshared/setuptools.egg-info
lrwxrwxrwx  1 root root     38 Oct 22  2011 setuptools.pth -> ../../../share/pyshared/setuptools.pth
drwxr-xr-x  3 root root   4096 Nov  6  2014 simplejson
lrwxrwxrwx  1 root root     49 Jan 30  2012 simplejson-2.3.2.egg-info -> ../../../share/pyshared/simplejson-2.3.2.egg-info
lrwxrwxrwx  1 root root     31 Oct 22  2011 site.py -> ../../../share/pyshared/site.py
-rw-r--r--  1 root root   1725 Dec 14 20:59 site.pyc
-rw-r--r--  1 root root  34912 Feb  9  2012 _snackmodule.so
lrwxrwxrwx  1 root root     32 Feb  9  2012 snack.py -> ../../../share/pyshared/snack.py
-rw-r--r--  1 root root  39925 Nov  6  2014 snack.pyc
drwxr-xr-x  2 root root   4096 Nov  6  2014 softwareproperties
lrwxrwxrwx  1 root root     37 Sep 13  2013 SSSDConfig.py -> ../../../share/pyshared/SSSDConfig.py
-rw-r--r--  1 root root  64074 Nov  7  2014 SSSDConfig.pyc
lrwxrwxrwx  1 root root     46 Sep 13  2013 sssd_upgrade_config.py -> ../../../share/pyshared/sssd_upgrade_config.py
-rw-r--r--  1 root root  14614 Nov  7  2014 sssd_upgrade_config.pyc
drwxr-xr-x 13 root root   4096 Nov  6  2014 tests
drwxr-xr-x 16 root root   4096 Nov  7  2014 twisted
lrwxrwxrwx  1 root root     52 Mar  9  2012 Twisted_Core-11.1.0.egg-info -> ../../../share/pyshared/Twisted_Core-11.1.0.egg-info
drwxr-xr-x  2 root root   4096 Nov  6  2014 ufw
lrwxrwxrwx  1 root root     45 Apr  5  2012 ufw-0.31.1_1.egg-info -> ../../../share/pyshared/ufw-0.31.1_1.egg-info
lrwxrwxrwx  1 root root     56 Nov 14  2012 unattended_upgrades-0.1.egg-info -> ../../../share/pyshared/unattended_upgrades-0.1.egg-info
drwxr-xr-x  3 root root   4096 Nov  6  2014 UpdateManager
lrwxrwxrwx  1 root root     35 Dec 30  2011 validate.py -> ../../../share/pyshared/validate.py
-rw-r--r--  1 root root  46734 Nov  6  2014 validate.pyc
drwxr-xr-x  3 root root   4096 Nov  6  2014 wadllib
drwxr-xr-x  2 root root   4096 Nov  6  2014 wadllib-1.3.0.egg-info
drwxr-xr-x  2 root root   4096 Nov  6  2014 xapian
drwxr-xr-x  2 root root   4096 Nov  6  2014 yaml
-rw-r--r--  1 root root 185456 Dec 16  2011 _yaml.so
drwxr-xr-x  3 root root   4096 Nov  6  2014 zope
drwxr-xr-x  2 root root   4096 Nov  6  2014 zope.interface-3.6.1.egg-info
lrwxrwxrwx  1 root root     54 Dec 31  2011 zope.interface-3.6.1-nspkg.pth -> ../../../share/pyshared/zope.interface-3.6.1-nspkg.pth

but those new modules in /usr/local/lib/python2.7/dist-packages only import using /usr/bin/python (still 2.7.3).
Using the default python (/usr/local/bin/python, 2.7.6) is the version I want to run, but doesn't see any modules to import.
What did I do wrong (should I have done an upgrade instead of a wget/make/install?)
How can I fix it now?
Answer: Good question, it's nice to have the logs, and information :)
If I understand correctly, then the modules are not installing to the Python version you want?
If so try this:

Navigate to the Python directory that you want to install the modules to.
Then navigate from the Python directory to the Scripts/ folder. (So your directory should be something like/usr/lib/python<Python Version>/Scripts/)
Now run sudo python pip.py install <Module Name>.

Now the module should install directly to that Python version.
If this wasn't the answer you were looking for, please leave a comment.
Hope this helps!
Comment: Thanks, I already did the directed workaround sort of thing with an alias like python=/usr/bin/python, putting /usr/bin in front of /usr/local/bin in my PATH, etc. What I want to know is why pip install went into the /usr/local/bin dist-packages after installing 2.7.6 on its own, but running the /usr/local/bin/python does not pick them up (only the *other* one in /usr/bin does). And how to fix it so the same version that runs by default is also where packages get installed by default like you'd expect.


jQuery confusion: why does $("input").eq(0)(":checked") give "jQuery(...) is not a function"?

Question: I am puzzled by this behavior. As I understand the docs, $("input") returns a jQuery object for all of the input elements in the DOM, and so $("input").eq(0) would return a jQuery object for the first input element in the DOM. And the ":checked" selector selects from the jQuery object all elements that are checked.
So I expected that $("input").eq(0)(":checked") would return a jQuery object of length 0 if the first input element was not checked, or a jQuery object of length 1 for the element itself if it was checked. What's wrong with my thinking? I realize this is really fundamental, but I can't figure it out. jQuery is an object, but I can normally call it like a function and pass it a string for a selector. But here I call a function that returns a jQuery object, but I can't call it with a string selector. Please enlighten me!
Answer: $("input").eq(0) returns a jQuery object, but you are trying to call it as a function with (":checked"). This is invalid, just like ({a: 1})() (attempting to call an object like a function). jQuery itself is a function that you can call, but its return value is not.
Use $('input').eq(0).is(':checked') to check if the element matches the selector.
Or use .filter(':checked') to get all the elements that match the selector.
Comment: @sootsnoot A jQuery object is just an instance of `jQuery.fn.init` and is quite similar to an array. You cannot call an object as it is not a function. jQuery itself is a function, but that is distinct from what jQuery returns when called.
Comment: I guess its just the terminology. Everything returns a jQuery object, and if you look [here](https://api.jquery.com/Types/#jQuery), it says "A jQuery object contains a collection of Document Object Model (DOM) elements" and "The jQuery object itself behaves much like an array". Yet you say "jQuery itself is a function", and the quoted section also says "Most frequently, you will use the jQuery() function to create a jQuery object". So I'm still a liitle puzzled. But your solution of using .is(selector) is exactly what I was looking for, I've never used that function before! Thanks!
Comment: Thanks, that maybe helps a little. My use of javascript is quite shallow. Guess I need to learn about ".fn.init", That one always puzzles me when it shows up in devtools. If I got  comfortable with it, maybe my jQuery confusion would go away.


Minecraft (1.13+) - Get Player By UUID using commands

Question: I'm trying to make a commands that give an arrow to the player that fired the arrow.
The arrow object has Owner key that contains UUID of the player.
Is there a way to select a player with an UUID from an arrow object?
Give command:
/give @a[nbt={UUID:???}] arrow 1

Where ??? should be the value of
@e[type=arrow].Owner

Answer: This is a tricky thing. Simply due to the fact we cannot compare NBT tag values directly. However, if we store the first chunk UUID of a player in a scoreboard...
execute as @a[scores={uuid=0}] store result score @s uuid run data get entity @s UUID[0]

Then store the Owner UUID of the arrow...
execute as @e[type=arrow, tag=!returned, scores={uuid=0}] store result score @s uuid run data get entity @s Owner[0]

Then all you need to do is compare the scoreboard values to determine who shot the arrow and give the player the item
execute as @a if score @s uuid = @e[type=arrow, tag=!returned] uuid run give @s arrow

Finally, tag the arrow with returned so we don't have an infinite arrow glitch
execute as @e[type=arrow, tag=!returned] if score @s uuid = @a uuid run tag @s add returned

This works in 1.20.1 Java Edition. I didn't do any testing outside of that version because I use a modded client (for shaders, optimization, etc). The process should be functional in all versions of Minecraft with /data, /execute if, /execute store, and /scoreboard.
I should note that you cannot store the entire UUID of the player inside a scoreboard. This is because the entire UUID of the player uses 4 integers (128 bits) and scoreboard uses 1 integer (32 bits). In a nutshell, this means there is a chance a player shares this first UUID int and would randomly receive an arrow and the player who actually shot it will not. You can fix this by using more scoreboards and a larger execute if statement, tracking if a player shot an arrow, or just roll with it. The chance of this happening is astronomically low, but it is still possible and thankfully easy to fix.


React native navigate like click post in Instagram

Question: I am making an album app with react native and want to make FlatList with images like Instagram. When clicks item of FlatList, it will navigate to the same item in another screen with different FlatList. How to do this?

when click image JS

navigate to it in another screen

My code:
const RenderItemList = ({item, index}) => {
   return (
     <Pressable onPress={() => navigation.navigate('detail')}>
     <View key={index} style={[index%3!==0 ? {paddingLeft:2} : {paddingLeft:0}, {marginBottom: 2}]}>

      <Image style={{width: sizeOfImage, height: sizeOfImage}}
      source={{uri : item.uri}}
      />
     </View>
     </Pressable>
)}

Comment: Could you specify your question? What is blocking you?
Comment: I got the answer! thank for your help!!
Answer: You can use initialScrollIndex prop from the Flatlist API. Pass the index as route params to other screen and set initialScrollIndex to that index.
Example below
<FlatList
  data={sampleImages}
  keyExtractor={(item) => item.id.toString()}
  numColumns={3}
  renderItem={({ item, index }) => (
    <Pressable
      style={{ width: EachWidth, height: EachWidth }}
      onPress={() => navigation.navigate('Details', { initialScroll: index })}>
      <Image
        source={{ uri: item.download_url }}
        style={{ width: EachWidth, height: EachWidth }}
      />
    </Pressable>
  )}
/>

On other screen,
<FlatList
  data={sampleImages}
  keyExtractor={(item) => item.id.toString()}
  initialScrollIndex={route.params.initialScroll || 0} // Use here
  renderItem={({ item }) => (
    <View style={{ width: ScreenWidth, height: ScreenWidth }}>
      <Image
        source={{ uri: item.download_url }}
        style={{ width: ScreenWidth, height: ScreenWidth }}
      />
    </View>
  )}
/>

Working Example
Comment: brilliant answer, thanks


Thane Krios is in the dead list on Normandy

Question: I can't find Thane, he isn't in Huerta Memorial Hospital and he is on the dead people list that is on the Normandy.  (The ones wich is in front of the elevator of the crew deck)
Is he really dead?
Answer: If Thane is listed on the memorial in the Normandy, then he is dead.
If he survived the events of Mass Effect 2, in most cases,

 He is injured in the assault on the Citadel by Cerberus forces, and he dies shortly afterwards.

You may also be interested in this question:
Can I change what happens to Thane?
Answer: Yes, he died, most likely shortly after the Cerberus attack on the Citadel, if he survived ME2. If he survived ME2 and you spoke to him in the hospital, he will help you repel the attack and get mortally wounded . You will have a short window of opportunity to visit him during his last moments, after which he will die.
Answer: Yes, he is dead. If you take too long to visit him in the hospital than you will miss some dialog.


Attempting to set up Dual boot Win8.1/Ubuntu 16.04 and struggling

Question: Using an Asus X551CA laptop running Windows 8.1.
I created a USB flash installer for Ubuntu 16.04 and attempted to install Ubuntu alongside Windows. During the install an alert came up suggesting that UEFI may not be the best option and inviting me to go back. Assuming that Windows may have been installed using BIOS (Legacy CSM in Asus-speak) I followed the guidance and the install completed fine. However there was no option to boot into Windows when I restarted.
I ran the installer again and opted for the UEFI route on the assumption that Windows was using UEFI, and that if I installed Ubuntu on the same basis this would resolve my problem. Same result - I was able to boot into Ubuntu but no sign of any option to boot into Windows.
Went back to the first install option and when complete ran boot-repair. Output is at http://paste2.org/fnFnN2mP
Now deeply confused and seeking guidance. Thanks in advance.
Comment: In Ubuntu did you run "sudo-update grub"? Also, did you check GParted to be sure that you didn't wipe your Windows partitions?
Comment: Let me put that in an answer for others who may have this issue.
Comment: Both Ubuntu & Windows are installed in BIOS boot mode. But you ran Boot-Repair in UEFI boot mode. Best to always boot in BIOS mode to avoid issues. A normal grub update from Boot-Repair should also have run the `sudo update-grub`, but in UEFI mode it may not have. Also what version of Windows? If Windows 8 or later, grub will not find it until you turn off fast start up. And that would require you to directly boot Windows. And then from your Windows you need your Windows repair disk to allow you to fix Windows.
Comment: Certainly checked in GParted that the Windows partitions are all there, but didn't run sudo update-grub. Just did that, and on rebooting, I now have two Windows boot options (sda1 and sda2). Two options is certainly way better than none. Thank you!
Comment: How do I control in which mode (BIOS or UEFI) to run Boot-Repair?
Answer: Run sudo-update grub from terminal.
Grub will automatically detect Windows boot partitions; however, Fast startup must be disabled, and Windows must not be in a hibernated state.


creating a file on android

Question: I am trying to create a file with my android application. I need to write to the file in a specific class. The code I currently have for it is listed below. I keep getting a nullpointerexception when it is trying to write to the file. The exact error is listed below. I am new to android, so please be detailed.
Can someone please tell me what I am doing wrong and how i can fix this issue?

//the class where i need to create and write to the file
public class DataRobot {
    Context tThis;
    FileOutputStream fOut;
    OutputStreamWriter writer;

    public DataRobot(SmartApp smartApp) extends Activity {
        tThis = (Context) smartApp;
    }
    public void onCreate(Bundle savedInstanceState) {
        try {
            //file = new File("/sdcard", "test.csv");
            fOut = openFileOutput("test.csv", MODE_WORLD_READABLE);
            writer = new OutputStreamWriter(fOut);
        } catch (NullPointerException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public void analyzeData(SmartDataObject temp) {
        data = temp;
        try {
                //the following line is where the error is occurring.
            writer.write(Double.toString(data.getHeartRate()));
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
     }
}

//the error
03-26 03:47:53.924: WARN/System.err(273): java.lang.NullPointerException
03-26 03:47:53.934: WARN/System.err(273):     at cpe495.smartapp.DataRobot.analyzeData(DataRobot.java:80)
03-26 03:47:53.946: WARN/System.err(273):     at cpe495.smartapp.SmartApp$1.dataReceivedReceived(SmartApp.java:49)
03-26 03:47:53.956: WARN/System.err(273):     at cpe495.smartapp.ConnectDevice.fireDataReceivedEvent(ConnectDevice.java:79)
03-26 03:47:53.956: WARN/System.err(273):     at cpe495.smartapp.ConnectDevice.run(ConnectDevice.java:46)
03-26 03:47:53.965: WARN/System.err(273):     at java.lang.Thread.run(Thread.java:1096)

Answer: It looks like you are doing this in your constructor.  You can't do that.  You need to wait until onCreate(), which is when you know the object has been initialized.
Comment: I thought the class had to be an activity to have an onCreate() method? My class is not an activity.
Comment: I made some changes, here is the new error that is occurring, do you have any ideas how to get rid of this new nullpointerexception? I have commented in the code where the error is occurring.
Answer: You should acces files via content providers, I think the path is wrong... look at this file tutorial
Comment: I am already using that as a reference. This is what i got from the reference. I had to change a little because it was not working for my implementation.
Comment: I made some changes, here is the new error that is occurring, do you have any ideas how to get rid of this new nullpointerexception? I have commented in the code where the error is occurring.
Comment: I dont see any wrong in code, maybe try to declare data variable as SmartDataObject
Comment: It already is, it is just left out of the code snippet to save room.
Answer: The following code is what i figured out and is working. Sorry it took so long to post.

public class DataRobot {
    Context tThis; //was enabled for preferences
    private FileOutputStream fOut;
    private OutputStreamWriter writer;

    public DataRobot(SmartApp smartApp) {
        tThis = (Context) smartApp;

    }

    public void analyzeData(SmartDataObject temp) {
        try {
            fOut = tThis.openFileOutput("test.csv", tThis.MODE_APPEND);
            writer = new OutputStreamWriter(fOut);
        } catch (NullPointerException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            writer.write("Test");//0
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

creating a file on android


Installing error for SCIP in Python

Question: I am using python 3 on windows 7 and trying to get SCIP on it. Please see the image. I want to run a mixed integer program.
SCIP
Any further instructions will be helpful.
I downloaded SCIP 3.2.1 as seen in the image, but then I don't understand how to implement that command and where?
Comment: Please put your problem in words and mention exactly where you need help.
Comment: I did it. Please see.
Comment: So no help at all?
Comment: I am not fully familiar with SCIP, but it looks like looking through tutorial docs might solve your problem. See http://scip.zib.de/doc/html/SHELL.php
Answer: PySCIPOpt does not officially support Windows. There are step-by-step instructions though, in the GitHub issues.
In general, PySCIPOpt is an interface from Python to C that is built using Cython. You need to compile the interface linking to a C library of SCIP. You don't necessarily need to build this library yourself, you might want to use a precompiled one from http://scip.zib.de/#download instead.
You do need a C/C++ compiler in any case. BTW, "that command" is make which is a build tool for Unix that is used to compile code. It doesn'twork out of the box on Windows 7. You either need the Ubuntu Bash from Windows 10 or a Linux "emulator" like Cygwin.

Installing error for SCIP in Python


What are the minimal guidelines for a dual command-line / gui interface?

Question: I'm designing a website that has a constant CLI and optional GUI's for every functionality. What i'm basically doing is an automated form generated for each parameter and a description.
I'm also indicating with a red asterisk the required parameters.
It works pretty much like this:
cmd is a generic command. visual is a command that makes the form for the command:

visual cmd

Then it makes something like this:

That's all i have, can you point me to improvements on this subject?
My goal: The system is mainly for the cli, so i want to drive users to it. This autoform thing should be a transition/helper, what else should i add?
Comment: "What else should I add?" and "Can you point me to improvements on this subject?" are very vague questions. It's unclear what the workflow is and whether users stumble in it somehow.
Comment: What is the problem you're trying to solve? Right now your question doesn't sound constructive.
Comment: What am i missing? The visual mode is for beginners.
Answer: It seems to me that CLI systems have been doing similar things for years:
1) help (cmd)
and 2) (cmd) /?
have both been used in OS like DOS and VMS.  Asking (presumably novice) users to learn a new command to get help seems counter-intuitive.  While not as pretty as your solution, those systems have been effective in providing help.
Unless your command line interface is significantly more complex than what you have presented, perhaps you have a solution in search of a problem.


Why Dash cant see new installed program?

Question:
Possible Duplicate:
How to pin Eclipse to the Unity launcher?

I installed Eclipse IDE on my Ubuntu 11.10:
1) To install Eclipse need to download eclipse-jee-indigo-SR1-linux-gtk.tar.gz from Download page
2) Untar downloaded archive tar zxvf eclipse-jee-indigo-SR1-linux-gtk.tar.gz
3) Move to ~/ mv eclipse ~/eclipse.
After this I opened Dash Window and in input field writed Eclipse, but - Dash found nothing...
Why?
Maybe, I must add eclipse in some Dash programs list or something like this?
Answer: The tar package from Eclipse does not include creating a launcher, you have just extracted the package, there was no installation.
You need to create a launcher and add it to dash for it to be available.
This question already has a explanation on how to do it, you just need to modify the path to the files (executable and icon) but the steps are the same.


Can Liquid Nails cover a small hole

Question: I'm installing some vinyl plank flooring. In one spot where a transition piece is going to go, there is a small hole that will expand under the vinyl. The transition piece is going to be installed with Liquid Nails or J.B. Weld.

Can I just fill in the hole with Liquid Nails/JB Weld or do I need to apply some type of patch first?
Answer: There are cementitious floor patches made for this purpose that will give you better results. Liquid Nails, indispensable though it may be, doesn't really harden enough to do a patch job like this. Here's a video of a guy patching a floor that's pretty thorough.Floor patch.
Answer: For such a small hole, how about spackle?

Can Liquid Nails cover a small hole


How do I join 2x4s without mitering?

Question: I asked this question on the Bicycles site:
DIY wooden bike rack — looking for plans
I'm planning to build this rack out of 2x4 pieces of wood. It'll live in my garage. I'm looking to make a rack similar to one of these, but simpler and, obviously, not made of metal:

(photo credit)
My question is, how can I join 2x4s so they'll be strong, particularly the ones that are horizontal? The stand won't support the weight of the bikes, but it will keep them upright. (Several of my bikes don't have kickstands.) I'd like to avoid mitering the joins, to make construction simpler, since I don't have a miter box. (We have a circ saw and a regular wood saw.)
Comment: If it's just the lack of a miter box that's keeping you from using miter joints, then you can pick one up for under $10 here: http://www.acehardwareoutlet.com/productdetails.aspx?sku=998006596&source=GoogleBase
Answer: I know you mentioned that you want to build the bike rack out of wood (and 2x4s) but...
You could probably build nearly that exact bike rack out of PVC pipe or even a slightly simpler design:

http://www.utahmountainbiking.com/goodies/TruckbedBikeRack.htm
Comment: You might be able to fill it with sand for extra weight.
Comment: This seems to be a great solution for holding bikes upright but if security is an issue, not so much. It would be trivial to cut PVC and steal a bike from this device.
Comment: That's really slick, and a great idea for a truck bed too!  (As indicated by the link.)
Comment: And if you go the PVC route, and you're shopping at Lowes or Home Depot, make sure to look for the boxes of connectors.  They sell 'em loose, but they're like 2 to 3 times the cost per item of buying a box.  And if you want to make it transportable, consider drilling & screwing a few of the connections (but you can always cut 'em and use couplers, if you don't do it, and need to break it down)
Answer: Go to your local big box store (Home Depot / Lowes / etc) and look into joist hanging / decking hardware, such as these.
Comment: +1.  Here's a [catalog](http://www.strongtie.com/ftp/catalogs/c-diy05/C-DIY05.pdf) with some sample projects.
Answer: I wouldn't use miter joints for a project like this anyway -- they're mainly for appearance, not strength.  Unless you want it to look pretty I'd stick with lap-type joints, where the pieces overlap each other.  Then you can just screw them together with deck screws, or for even more strength you can glue them too.  If you want to enhance the appearance you can create an official lap joint like this:

The advantage being that your boards end up in the same plane and look a bit less klugey. You could make these either with your hand saw (tedious), or by making several half-depth cuts with your circular saw and removing the remaining material with a chisel.
Where you need to butt a 2x4 up against the flat of another, this won't work.  The best joint to use in this case would be a dado:

You can make these with your circular saw and chisel too.  With some glue and a couple of screws through the long piece into the end of the butted piece, this makes for a very strong, nice-looking joint.
Comment: I assumed the OP's comment of a circular saw meant a hand operated one, and that's awfully tricky for a novice to hand cut dados.  It's tricky for a non-novice as well.
Comment: @Adam Musch: The term "circular saw" always refers to a power saw with a circular blade that's pushed by hand.  Is that what you're referring to?  If so, it's not that tricky to cut a dado.  Set the blade depth to the depth of your dado, make two cuts to define the width of the slot, then a few more in between. Depending on how many cuts you make, you can remove all the material in the slot or leave several "fins" of debris to remove with a chisel.
Answer: You don't have to worry about joining 2x4s so they will be strong.  I made the simplest possible bike rack by butting them together and nailing them.  It's not at all sophisticated but it is easy to build and strong enough to do the job.

I happened to have some scrap lumber, consisting of two 6-foot boards and many 30-inch pieces.  The two 6-foot boards are the top and bottom of the bike rack.  The bottom of the bike rack sits on the ground.  The 30-inch pieces are nailed vertically between the top and the bottom boards, forming slots into which your bike tires sit.  I spaced the vertical pieces according to the varying widths of various bikes' tires.
The bike rack can stand alone, but it becomes much more stable when at least one bike is inserted into each side of the rack.  The vertical boards keep the bikes from falling over.  There's enough friction that, on the floor of my garage, the bikes don't roll away on their own.
Here is a picture of the rack when it is fully-populated:
Comment: Welcome to the site. I added the photos to your post, +1 for including an example design that's quite simple. You should now have enough rep to remove the new user restrictions.
Answer: Miter joints are simply not strong enough here to support the loads they will see. And glue won't be strong enough either to keep the miters together. End-grain to end-grain does not make for a strong glue joint.
I've used hand cut mortice and tenon joinery on 2x4 construction before. Yes, it was overkill, but it was fun to do. :) It does yield a strong joint, one that you will trust. It is not even that difficult to do, since the 2x4s are soft wood to cut even with a handsaw and chisel. For even more assurance, after the joints are assembled, drill a hole through the joint, and insert a dowel through it to prevent the tenon from pulling out.
Answer: Based on your sketch in the link, I would just nail or screw them together. It would more than suffice.
Answer: I would suggest using a top and bottom rail of 4 * 2 and make the uprights from large diameter dowel (think broom handle). This should be more than strong enough for your needs and much lighter.

How do I join 2x4s without mitering?