text:
Q: Programmatically scrolling to the end of a ListView I have a scrollable ListView where the number of items can change dynamically. Whenever a new item is added to the end of the list, I would like to programmatically scroll the ListView to the end. (e.g., something like a chat message list where new messages can be added at the end)
My guess is that I would need to create a ScrollController in my State object and pass it manually to the ListView constructor, so I can later call animateTo() / jumpTo() method on the controller. However, since I cannot easily determine the maximum scroll offset, it seems impossible to simply perform a scrollToEnd() type of operation (whereas I can easily pass 0.0 to make it scroll to the initial position).
Is there an easy way to achieve this?
Using reverse: true is not a perfect solution for me, because I would like the items to be aligned at the top when there are only a small number of items that fit within the ListView viewport.

A: Do not put the widgetBinding in the initstate, instead, you need to put it in the method that fetches your data from database. for example, like this. If put in initstate, the scrollcontroller will not attach to any listview.
    Future<List<Message>> fetchMessage() async {

    var res = await Api().getData("message");
    var body = json.decode(res.body);
    if (res.statusCode == 200) {
      List<Message> messages = [];
      var count=0;
      for (var u in body) {
        count++;
        Message message = Message.fromJson(u);
        messages.add(message);
      }
      WidgetsBinding.instance
          .addPostFrameCallback((_){
        if (_scrollController.hasClients) {
          _scrollController.jumpTo(_scrollController.position.maxScrollExtent);
        }
      });
      return messages;
    } else {
      throw Exception('Failed to load album');
    }
   }

A: I came across this issue when I was using the StreamBuilder widget to get data from my database. I put WidgetsBinding.instance.addPostFrameCallback on top of the widget's build method, and it wouldn't scroll all the way to the end. I fixed it by doing this:
...
StreamBuilder(
  stream: ...,
  builder: (BuildContext context, AsyncSnapshot snapshot) {
    // Like this:
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (_controller.hasClients) {
        _controller.jumpTo(_controller.position.maxScrollExtent);
      } else {
        setState(() => null);
      }
     });

     return PutYourListViewHere
}),
...

I tried it with _controller.animateTo too but it didn't seem to work.

A: _controller.jumpTo(_controller.position.maxScrollExtent);
_controller.animateTo(_controller.position.maxScrollExtent);

These calls do not work well for a list of dynamically sized items. We don't know at the time that you call jumpTo() how long the list is, since all of the items are variable and are lazily built as we scroll down the list.
This may not be the smart way, but as a last resort you can do the following:
Future scrollToBottom(ScrollController scrollController) async {
  while (scrollController.position.pixels != scrollController.position.maxScrollExtent) {
    scrollController.jumpTo(scrollController.position.maxScrollExtent);
    await SchedulerBinding.instance!.endOfFrame;
  }
}

A: depending on  this answer    I have created this class, just send your scroll_controller, and if you want the opposite direction use the reversed parameter
import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';

class ScrollService {
  static scrollToEnd(
      {required ScrollController scrollController, reversed = false}) {
    SchedulerBinding.instance!.addPostFrameCallback((_) {
      scrollController.animateTo(
        reverced
            ? scrollController.position.minScrollExtent
            : scrollController.position.maxScrollExtent,
        duration: const Duration(milliseconds: 300),
        curve: Curves.easeOut,
      );
    });
  }
}

A: if you want to see the last item visible with a padding from bottom then add extra distance like this
 _controller.jumpTo(_controller.position.maxScrollExtent + 200);

here 200 will be extra distance

A: listViewScrollController.animateTo(listViewScrollController.position.maxScrollExtent) is the simplest way.

A: Screenshot:

*

*Scrolling with animation:
final ScrollController _controller = ScrollController();

// This is what you're looking for!
void _scrollDown() {
  _controller.animateTo(
    _controller.position.maxScrollExtent,
    duration: Duration(seconds: 2),
    curve: Curves.fastOutSlowIn,
  );
}

@override
Widget build(BuildContext context) {
  return Scaffold(
    floatingActionButton: FloatingActionButton.small(
      onPressed: _scrollDown,
      child: Icon(Icons.arrow_downward),
    ),
    body: ListView.builder(
      controller: _controller,
      itemCount: 21,
      itemBuilder: (_, i) => ListTile(title: Text('Item $i')),
    ),
  );
}

*Scrolling without animation:
Replace above _scrollDown method with this:
void _scrollDown() {
  _controller.jumpTo(_controller.position.maxScrollExtent);
}

A: I have so much problem trying to use the scroll controller to go to the bottom of the list that I use another approach.
Instead of creating an event to send the list to the bottom, I change my logic to use a reversed list.
So, each time I have a new item, I simply, made at insert at the top of the list.
// add new message at the begin of the list
list.insert(0, message);
// ...

// pull items from the database
list = await bean.getAllReversed(); // basically a method that applies a descendent order

// I remove the scroll controller
new Flexible(
  child: new ListView.builder(
    reverse: true,
    key: new Key(model.count().toString()),
    itemCount: model.count(),
    itemBuilder: (context, i) => ChatItem.displayMessage(model.getItem(i))
  ),
),

A: My solution :
Step : 1
Define global key like this :
final lastKey = GlobalKey();

Step : 2
Attach to last message
SingleChildScrollView(
    controller: scrollController,
    padding: const EdgeInsets.fromLTRB(10, 10, 10, 10),
    physics: const AlwaysScrollableScrollPhysics(),
    child: Column(
        children: List.generate(
            data.length,
            (index) {
            return BuildMessage(
                key:
                    data.length == index + 1 ? lastKey : null,
                message: data[index],
                focusNode: focusNode,
            );
            },
        ),
    ),
)

Step : 3
Create function call to scroll
void scrollToBottom() {
    Scrollable.ensureVisible(lastKey.currentContext!,alignment: 1, duration: const Duration(milliseconds: 500));
}

Call when you want to scroll to bottom with some delay 100 milliseconds
Timer(const Duration(milliseconds: 100),() => scrollToBottom());

A: to get the perfect results I combined Colin Jackson and CopsOnRoad's answers as follows:
_scrollController.animateTo(
    _scrollController.position.maxScrollExtent,
    curve: Curves.easeOut,
    duration: const Duration(milliseconds: 500),
 );

A: If you use a shrink-wrapped ListView with reverse: true, scrolling it to 0.0 will do what you want.
import 'dart:collection';

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Example',
      home: new MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => new _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  List<Widget> _messages = <Widget>[new Text('hello'), new Text('world')];
  ScrollController _scrollController = new ScrollController();

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      body: new Center(
        child: new Container(
          decoration: new BoxDecoration(backgroundColor: Colors.blueGrey.shade100),
          width: 100.0,
          height: 100.0,
          child: new Column(
            children: [
              new Flexible(
                child: new ListView(
                  controller: _scrollController,
                  reverse: true,
                  shrinkWrap: true,
                  children: new UnmodifiableListView(_messages),
                ),
              ),
            ],
          ),
        ),
      ),
      floatingActionButton: new FloatingActionButton(
        child: new Icon(Icons.add),
        onPressed: () {
          setState(() {
            _messages.insert(0, new Text("message ${_messages.length}"));
          });
          _scrollController.animateTo(
            0.0,
            curve: Curves.easeOut,
            duration: const Duration(milliseconds: 300),
          );
        }
      ),
    );
  }
}

A: While all the answers produces the desired effects we should do some improvements here.

*

*First of all in most cases (speaking about auto scrolling) is useless using postFrameCallbacks because some stuff could be rendered after the ScrollController attachment (produced by the attach method), the controller will scroll until the last position that he knows and that position could not be the latest in your view.

*Using reverse:true should be a good trick to 'tail' the content but the physic will be reversed so when you try to manually move the scrollbar you must move it to the opposite side -> BAD UX.

*Using timers is a very bad practice when designing graphic interfaces -> timer are a kind of virus when used to update/spawn graphics artifacts.
Anyway speaking about the question the right way to accomplish the task is using the jumpTo method with the hasClients method as a guard.

Whether any ScrollPosition objects have attached themselves to the ScrollController using the attach method.
If this is false, then members that interact with the ScrollPosition, such as position, offset, animateTo, and jumpTo, must not be called

Speaking in code simply do something like this:
if (_scrollController.hasClients) {
    _scrollController.jumpTo(_scrollController.position.maxScrollExtent);
}

Anyway this code is still not enough, the method will be triggered even when the scrollable isn't at the end of the screen so if you are manually moving the bar the method will triggered and autoscrolling will be performed.
We ca do better, with the help of a listener and a couple of bool will be fine.
I'm using this technique to visualize in a SelectableText the value of a CircularBuffer of size 100000 and the content keeps updating correctly, the autoscroll is very smooth and there are not performance issues even for very very very long contents. Maybe as someone said in other answers the animateTo method could be smoother and more customizable so feel free to give a try.

*

*First of all declare these variables:

ScrollController _scrollController = new ScrollController();
bool _firstAutoscrollExecuted = false;
bool _shouldAutoscroll = false;

*

*Then let's create a method for autoscrolling:

void _scrollToBottom() {
    _scrollController.jumpTo(_scrollController.position.maxScrollExtent);
}

*

*Then we need the listener:

void _scrollListener() {
    _firstAutoscrollExecuted = true;

    if (_scrollController.hasClients && _scrollController.position.pixels == _scrollController.position.maxScrollExtent) {
        _shouldAutoscroll = true;
    } else {
        _shouldAutoscroll = false;
    }
}

*

*Register it in initState:

@override
void initState() {
    super.initState();
    _scrollController.addListener(_scrollListener);
}

*

*Remove the listener in your dispose:

@override
void dispose() {
    _scrollController.removeListener(_scrollListener);
    super.dispose();
}

*

*Then trigger _scrollToBottom, basing on your logic and needs, in your setState:

setState(() {
    if (_scrollController.hasClients && _shouldAutoscroll) {
        _scrollToBottom();
    }

    if (!_firstAutoscrollExecuted && _scrollController.hasClients) {
         _scrollToBottom();
    }
});

EXPLANATION

*

*We made a simple method: _scrollToBottom() in order to avoid code repetitions;

*We made a _scrollListener() and we attached it to the _scrollController in the initState -> will be triggered after the first time that the scrollbar will move. In this listener we update the value of the bool value _shouldAutoscroll in order to understand if the scrollbar is at the bottom of the screen.

*We removed the listener in the dispose just to be sure to not do useless stuff after the widget dispose.

*In our setState when we are sure that the _scrollController is attached and that's at the bottom (checking for the value of shouldAutoscroll) we can call _scrollToBottom().
At the same time, only for the 1st execution we force the _scrollToBottom() short-circuiting on the value of _firstAutoscrollExecuted.

A: _scrollController.animateTo(
_scrollController.position.maxScrollExtent,
duration: const Duration(milliseconds: 400),
curve: Curves.fastOutSlowIn);
});

A: I was using a dynamic list view, but scrollController.animateTo() won't work for dynamic lists as mentioned here https://stackoverflow.com/a/67561421/13814518, and I didn't even find any good solution in previous replies. So here's how I solved the issue.
void scrollToMaxExtent() {
  WidgetsBinding.instance.addPostFrameCallback((_) {
    scrollController.animateTo(
      scrollController.position.maxScrollExtent,
      duration: const Duration(milliseconds: 100),
      curve: Curves.easeIn,
    );
  });
}

A: For me the issue was that scrollController.position.maxScrollExtent always returned 0.0. The reason was that my ListView was inside a ScrollView.
Removing the ScrollView fixed the issue.

A: Pros:
Here is the solution that works 100% of the time. It always scrolls to the end, online some of the other solutions. Also, it doesn't require reversing.
Cons:
Locked to Curves.linear animation curve.
    Future.doWhile(() {
      if (scrollController.position.extentAfter == 0)
        return Future.value(false);
      return scrollController
          .animateTo(scrollController.position.maxScrollExtent,
              duration: Duration(milliseconds: 100), curve: Curves.linear)
          .then((value) => true);
    });

A: you could use this where 0.09*height is the height of a row in the list and _controller is defined like this _controller = ScrollController();
(BuildContext context, int pos) {
    if(pos != 0) {
        _controller.animateTo(0.09 * height * (pos - 1),
                              curve: Curves.easeInOut,
                              duration: Duration(milliseconds: 1400));
    }
}


text:
Q: Doctrine два раза insert'ит в базу У меня есть сущность. Я делаю persist, flush, а затем мне приходят новые данные и я тут же опять делаю persist и flush. Однако doctrin'а считает что это всё ещё новая запись и вместо сохранения я получаю ошибку валидации на уникальные поля. Как это побороть?
$obj1 = new Test();
$obj1->setName('test');
$em->persist($obj1);
$em->flush();
$obj2 = new Test2();
$obj2->setObj1Id($obj1->getId());
$em->persist($obj2);
$obj1->setObj($obj2);
$em->persist($obj1);
$em->flush();

Вот, когда второй раз делаешь flush, то в obj1 возникает ошибка неуникального name, т.к первый раз его в бд вставил, а второй раз доктрина опять считает что это insert и пытается опять вставить данные вместо того чтобы просто обновить поле через сеттер setObj

A: По идеи вот так должно работать . Но судя по коду у вас похоже отношение один ко многим и если я прав реализуется оно не так.
$obj1 = new Test();
$obj1->setName('test');
$em->persist($obj1);
$em->flush();
$em->clear();

$obj2 = new Test2();
$obj2->setObj1Id($obj1->getId());
$em->persist($obj2);
$obj1->setObj($obj2);
$em->persist($obj1);
$em->flush();

redpajama_set_name: RedPajamaStackExchange


text:
Q: unittest tests reuse for family of classes I have problem organizing my unittest based class test for family of tests. For example assume I implement a "dictionary" interface, and have 5 different implementations want to testing.
I do write one test class that tests a dictionary interface. But how can I nicely reuse it to test my all classes? So far I do ugly:
DictType = hashtable.HashDict

In top of file and then use DictType in test class. To test another class I manually change the DictType to something else.
How can do this otherwise? Can't pass arguments to unittest classes so is there a nicer way?

A: The way I tackle this with standard unittest is by subclassing -- overriding data is as easy as overriding methods, after all.
So, I have a base class for the tests:
class MappingTestBase(unittest.TestCase):
    dictype = None
    # write all the tests using self.dictype

and subclasses:
class HashtableTest(MappingTestBase):
    dictype = hashtable.HashDict

class OtherMappingTest(MappingTestBase):
    dictype = othermodule.mappingimpl

Here, the subclasses need override only dictype.  Sometimes it's handier to also expose MappingTestBase use "hook methods". When the types being tested don't have exactly identical interfaces in all cases, this can be worked around by having the subclasses override the hook methods as needed -- this is the "Template Method" design pattern, see e.g. this page which has a commented and timelined collection of a couple of video lectures of mine on design patterns -- part II is about Template Method and variants thereof for about the first 30 minutes.
You don't have to have all of this in a single module, of course (though I often find it clearest to lay things out this way, you could also make one separate test module per type you're testing, each importing the module with the abstract base class).

A: You could look at testscenarios which allows you to set a list called scenarios. The code then generates a version of the test class for each value/scenario in the list
See the example
So in your case the scenarios would be a list like [ {dicttype:hashtable.HashDict}, {dicttype:otherimpl.class}, ] and use self.dicttype in your test code.


text:
Q: How do I Increment surrounding cells of a cell in a 2-Dimensional array? I'm currently creating a simple Minesweeper game and I want to write a method with parameters of row and column coordinates that sets the tiles to be mined, and uses for loops to increment the neighbouring mines of the surrounding tiles.  The method should return true if the square was successfully mined, and false if the maximum number of mines was exceeded, or the square has already been mined.
But I have no idea as to how I can begin writing this method, I already created the 2-Dimensional array, and attempted to make the neighbouring mines increment, but my logic is not all there lol.
The methods that you might be interested in is Display() and mineCount()
Here is my code:
Minefield Class:
import java.util.Random;

public class Minefield {

boolean[][] minefield;
int[][] minedNeighbour;
Random r = new Random();//random number generator

int row;
int column;
int mines;
public int emptySpaces = column*row;
public void Minefield(int row, int column, int mines) {
    this.row = row;
    this.column = column;
    this.mines = mines;

    minedNeighbour = new int[row][column];
    for(int i = 0;i < 5;i++)
    {
        for(int j = 0;j < 5;j++)
        {
            minedNeighbour[i][j] = -1;
        }
    }

    for(int i = 0;i < 5;i++)
    {
        int x,y;
        do{
            x = r.nextInt(5);
            y = r.nextInt(5);
        }
        while(minedNeighbour[x][y] == 99);
        minedNeighbour[x][y] = 99;
    }
}

public void display()
{
    System.out.println(". 0 1 2 3 4");

    for(int i = 0;i < 5; i++)
    {
        System.out.print(i);
        for(int j = 0;j < 5;j++)
        {
            if(minedNeighbour[i][j] > -1 && minedNeighbour[i][j] < 9)
                System.out.println(" "+minedNeighbour[i][j]);

            else System.out.println(" +");
        }
        System.out.println();
    }

}

public void mineCount(int x, int y)
{
    int i,j; //loop variables
    if(minedNeighbour[x][y]!= -1)return; //already used
    minedNeighbour[x][y] = 0;//used
    emptySpaces--;
    for (i = x-1 ;i<=x+1 ; i++)
    {
        for(j = y-1 ;j<=y+1 ; j++)
        {
            if(minedNeighbour[i][j] == 99)
            {
                minedNeighbour[x][y]++;
            }
        }
    }

    if(i >= 0 && j >= 0 && i < 5 && j < 5)
    {
        if(minedNeighbour[i][j] == 99)
        {
            minedNeighbour[x][y]++;
        }
    }
}
}

Any help at all would be greatly appreciated :)


text:
Q: How can I check whether the location declared by a twitter's user exists? I'm doing a twitter crawler and I have built a search engine on top of it using Lucene. Since many users submit locations that don't exist (e.g. "in my kitchen", "wonderland", "from LA to Paris"...), I think I should check which users to index depending on their location, in orer to make them reachable further with a location-search. I retrieve users by sampling english tweets (using TwitterStream.sample("en")).
My first idea was to download from some web sites all cities in the world and check if there was a match. However, there's a problem with this approach: It's difficult to find a document which contains all cities in the world spelled in all possible languages. The user, indeed, could either submit the name of his city (or country) in english, or in his own language.

A: You need to use geocoding google maps, yandex maps.

I'm facing the fact that the first link tells google API look for
  cities in USA by default. So...if a user says he's in "Paris", google
  API will response me NO_REPONSE

Red Light District

I have read the first link with much attention and the second link
  with less attention, because the latter seems to be useful just for
  javascript application (I'm doing all in java).

No. It is not correct. You can get information by a HTTP request, refer HTTP request parameters.
A small code snippet for yandex maps using apache http client
private void request(String geocode) throws IOException {
        HttpResponse response = Request.Post(SEARCH_URL).version(HttpVersion.HTTP_1_1)
                .bodyForm(createForm(geocode).build(), Charsets.UTF_8).useExpectContinue()
                .connectTimeout(CONNECTION_TIMEOUT_MILS)
                .socketTimeout(CONNECTION_TIMEOUT_MILS)
                .execute().returnResponse();

        assertStatus(response, geocode);
        getCoordinatesFromResponse(response, geocode);
    }

    private Form createForm(String geocode) {
        return Form.form().add("format", "json").add("results", "1").add("geocode", geocode);
    }

    private void assertStatus(HttpResponse response, String requestString) {
        StatusLine statusLine = response.getStatusLine();
        if (statusLine.getStatusCode() >= ERROR_STATUS_MIN) {
            throw new RuntimeException(String.format(
                    "Error sending request '%s' to the map service, server response: %s",
                    requestString, response));
        }
    }


text:
Q: Site Stats Zeroed in Public Betas Site Stats Zeroed in Public Betas http://img839.imageshack.us/img839/8340/statszeroed.png

It seems that this problem is affecting all public beta sites, except for:

*

*Game Development

*Electronic Gadgets

*Geographic Information Systems

*Mathematics

A: I reported this on one of the beta meta sites.  Per Jeff it is normal behavior immediately after a deployment.
Site stats broken?

A: Will go away in 10 minutes.
edit: since this question keeps coming up, I changed the stats so they will say
loading
...
...
...
...

instead of all zeros. Hopefully that's clearer that the solution is to sit tight and wait 10 minutes.
(although, this could persist longer than 10 minutes if API is down for some catastrophic reason)


text:
Q: React Issue With Conditional Then Map I have some react code that checks if an array has any elements. If it does, then it should map over the elements and display them. I am able to do the check but the map throws an error, and I do not know why.
Here is the function:
    function MetalOptions() {
      const metals_options = GetsOptions(product,"Metal");
      if (metals_options.length > 0) {
        return(
          <React.Fragment>

yes

            {metals_options.map((option,index) =>

{option}

              )}

          </React.Fragment>
          );
      }
    }

Here is the entire render function:
render() {
    const { isLoading, productID, product} = this.state;

    function GetsOptions(product,kind) {
      const variant_metals = [];
      product.variants.map((variant) =>
          variant.option_values.map((option) =>
              variant_metals.push({type: option.option_type_name,value: option.presentation})
          )
      );

      const filter_variant_metals = variant_metals.filter(item => item.type === kind);
      const output = [...new Set(filter_variant_metals.map(s => JSON.stringify(s)))].map(s => JSON.parse(s));
      return output;
    }

    function GetsVariantImages(product) {
      const variant_images = [];
      product.variants.map((variant) =>
          variant.images.map((image) =>
              variant_images.push({
                original: image.product_url,
                thumbnail: image.small_url,
                description: image.alt,
                originalAlt: image.alt,
                thumbnailAlt: image.alt
              })
            )
        );
      const output4 = [...new Set(variant_images.map(s => JSON.stringify(s)))].map(s => JSON.parse(s));
      return output4;
    }

    if (isLoading) {
      return

              <BounceLoader
                sizeUnit={"px"}
                size={30}
                color={"#494847"}
                loading={isLoading}
              />

    }

    function MetalOptions() {
      const metals_options = GetsOptions(product,"Metal");
      const metals_options_array = Object.values(metals_options);
      if (metals_options.length > 0) {
        return(
          <React.Fragment>

yes

            {metals_options_array.map((option,index) =>

{option}

              )}

          </React.Fragment>
          );
      }
    }

    const size_options = GetsOptions(product,"Center Diamond Size");
    const shape_options = GetsOptions(product,"Center Diamond Shape");

    return (

            {product.master.images.length >= 3?

                {product.master.images.slice(0,3).map(image =>

                )}

:

                {product.master.images.slice(0,1).map(image =>

                )}

            }

{product.name}

Your Price {product.display_price}

                Text For More Info!
                Call To Take A Look

Select Your Options

              <MetalOptions />

This comes in various options listed below:

                {GetsOptions(product,"Metal").length > 0 &&

yes

                }
                {GetsOptions(product,"Center Diamond Shape").length > 0 &&

                    You have Center Diamond Shape {GetsOptions(product,"Center Diamond Shape").length} Options.

                }
                {GetsOptions(product,"Center Diamond Size").length > 0 &&

                    You have Center Diamond Size {GetsOptions(product,"Center Diamond Size").length} Options.

                }

              Center Gemstones

              Description

              <a className={"nav-link " + (product.product_properties.length < 0 && 'disabled')} id="properties-tab" data-toggle="tab" href="#properties" role="tab" aria-controls="properties" aria-selected="false">Properties

The Center

Deciding on a center diamond or gemstone is the important decision. The center diamond holds the sentiment and value. If your piece of jewelry is a play, the mounting is a stage, and the center is the actors and script.

We have helped so many in Kansas City find beautiful diamonds or gemstones in all qualities and price ranges usually complete with a GIA grading report. We would be honored to help you to your perfect one.

            <DiamondLinks />
            <GemLinks />

{product.description}

            {product.product_properties.map((property,index) =>

{property.property_name}: {property.value}

              )}

More Pictures

        <ImageGallery items={GetsVariantImages(product)} lazyLoad={true} showThumbnails={true} thumbnailPosition={'left'}/>

    );
  }
}

Any ideas? Thank you for your help!


text:
Q: How would I go about creating a list of Textbox items to use in other methods? I have a series of 5 text boxes on a winforms form which are used to collect data as strings. I intend to use these boxes in multiple ways from a method to clear the contents of each, to a method which takes the data from each to check before exporting to a text file.
In order to do this I planned to create a List<Textbox> which would essentially be a list of all 5 boxes so I could later use code such as
foreach(Texbox box in *texboxList*)
{
    box.Clear()
}

etc.
My only idea so far is to create a seperate method which adds all of the boxes to a list and then somehow pass the result of the method as a parameter to the relevant methods such as those that clear the boxes. The code I currently have is displayed below.
public List<TextBox> Clear_entered_data()
{
    List<TextBox> textBoxes = new List<TextBox>();
    textBoxes.Add(tbox1);
    textBoxes.Add(tbox2);
    textBoxes.Add(tbox3);
    textBoxes.Add(tbox4);
    textBoxes.Add(tbox5);
    return textBoxes;
}

This is the code I'm using to generate the list of textboxes to use. I think the problem I'm having is understanding how this can be passed to other methods through parameters. The method I'd like to make use of the list is shown below here as I have it so far.
private void Clear_button_Click(object sender, EventArgs e, List<TextBox> textBoxes)
  {

    DialogResult Clear_validation = MessageBox.Show("Are you sure you would like to clear all data from the form?","Clear data?", MessageBoxButtons.YesNo);

    if(Clear_validation == DialogResult.Yes)
    {
        foreach (TextBox box in textBoxes)
        {
            box.Clear();
        }
    }
}

With the code above I get the error upon running :
'Error  1   No overload for 'Clear_button_Click' matches delegate 'System.EventHandler''
But I've had no luck, please try and explain whats going wrong and help me find  more appropriate solution!
Thanks

A: create a private class member that of list of textboxes List<TextBox> _textBoxes;
then after you call InitializeComponents(because before that your textboxex doesn't exists if you used the IDE to create them) place your code to add the textboxes into the list
 _textBoxes = new List<TextBox>();
 _textBoxes.Add(tbox1);
 _textBoxes.Add(tbox2);
 _textBoxes.Add(tbox3);
 _textBoxes.Add(tbox4);
 _textBoxes.Add(tbox5);

now you can use in your methods the _textBoxes that contains all your created TextBox
your public List Clear_entered_data() became
public List<TextBox> ClearTextBoxes() {
    foreach(var textBox in _textBoxes){
       textBox.Clear();
    }
}

A: If you used a naming convention, you could just iterate over the form's control collection like this - in my example, the names all start with "SpecialTextBox":
foreach(Control c in someFormReference.Controls)
{
    if (c.GetType() == typeof(TextBox) && c.Name.StartsWith("SpecialTextBox"))
    {
        // do your thing here
    }
}


text:
Q: sudden Oracle 8 KVM Container crashes on startup " internal error: End of file from qemu monitor" we have 2 Hardware-Servers with Ubuntu 20.04 LTS on both we run Oracle linux 8 via KVM.
They were working fine until today. Both do not boot correctly with the following error message on the host machine:
internal error: End of file from qemu monitor
We have no clue why and why now. Nothing changed on the VM's.
We run a backup-script on both and use Cockpit for monitoring the VM and setting them up, but had no problems so far.
This script ist the only thing running on both host-machines, so i thought there might be something with it but can´t find anything.
Have you experienced something simlar?
Backup Script:
#!/bin/bash
set +x
exec < /dev/null

[[ -f /tmp/backup-running ]] && exit 1
touch /tmp/backup-running

# Path, where backups should be stored
PDST=/vmbackup

# Path, where temporary snapshots should be created
SNAP=/var/backups/temp_snapshots

# Check and create working directories
[[ -d ${PDST} ]] || mkdir -p ${PDST}
[[ -d ${SNAP} ]] || mkdir -p ${SNAP}

date=$(date +"%Y%m%d")

#mount /dev/sda1 ${DST} >/dev/null 2>&1

if [[ "$?" -ne 0 ]]; then
    echo "Unable to mount backup drive!"
    exit 1
fi

echo coppy VM: $(virsh list --all --name)

for VM in $(virsh list --all  --name); do
    #Directory path
    DST=${PDST}/$VM
    #Check and create VM Backup Folder
    [[ -d ${DST} ]] || mkdir -p ${DST}
    #add file with date
    rm -f ${PDST}/LAST_TRY_*
    rm -f ${DST}/LATEST_*

    echo "Backup KVM guest ${VM}"

    # Make sure, snapshot merging was successfull
    image_path=$(virsh domblklist ${VM} --details | \
                 grep vda | \
                 awk '{ print $4; }' | \
                 cut -d "/" -f -5)

    if [[ "$image_path" != "/var/lib/libvirt/images" ]]; then
        continue # Existing snapshot. Skipping
    fi

    if [[ ! -f ${SNAP}/backup-snapshot-${VM}.qcow2 ]]; then
        echo "Create Snapshot..."
        virsh snapshot-create-as ${VM} "backup-${VM}" \
            --diskspec vda,file=${SNAP}/backup-snapshot-${VM}.qcow2 \
            --disk-only \
            --atomic \
            --no-metadata
    else
        continue # Orphaned snapshot. Skipping
    fi

    echo "Copy guest image to backup drive..."
    cp -f --sparse=always /var/lib/libvirt/images/${VM}.qcow2 ${DST}/

    echo "Merge snapshot with guest image..."
    virsh blockcommit ${VM} vda --wait --active
    virsh blockjob ${VM} ${SNAP}/backup-snapshot-${VM}.qcow2 --pivot

    echo "Copy XML to backup drive..."
    cp -f /etc/libvirt/qemu/${VM}.xml ${DST}/

    # file with Date
    touch ${DST}/LATEST_$date

    # Make sure, snapshot merging was successfull
    image_path=$(virsh domblklist ${VM} --details | \
                 grep vda | \
                 awk '{ print $4; }' | \
                 cut -d "/" -f -5)

    if [[ "$image_path" == "/var/lib/libvirt/images" ]]; then
        echo "Remove snapshot..."
        rm -f ${SNAP}/backup-snapshot-${VM}.qcow2
    fi

    echo "VM as compressed_${VM}.qcow2"
    qemu-img convert -c -f qcow2 ${DST}/${VM}.qcow2 -O qcow2 ${DST}/compressed_${VM}.qcow2
    echo "entferne unkomprimiertes img ..."
    rm ${DST}/${VM}.qcow2
    echo "renaming VM to ${VM}.qcow2"
    mv ${DST}/compressed_${VM}.qcow2 ${DST}/${VM}.qcow2
done

touch ${PDST}/LAST_TRY_$date

echo "Syncing disk..."
sync
#umount ${DST}

rm -f /tmp/backup-running

exit 0

# vim: expandtab ts=4 sw=4


text:
Q: Обновление данных графика на OxyPlot в Xamarin Используется для рисования графика на Xamarin Oxyplot.Forms. График рисуется верно и обновление контента происходит. Однако, не могу начисто обновить контент. Метод InvalidatePlot(true) отлично обновляет интерфейс, если добавлены новые точки, но как мне сбросить построенные Axies?
Удаляю все точки из модели, добавляют новые, вызываю InvalidatePlot(true), новые точки добавляются, но Axies остается предыдущий.

A: Для обновления начисто перебейте сорц самого графика. Т.е. не точки конкретные, а всю модель.


text:
Q: Django background tasks I have an industrial controls system that I would like integrate into a simple django project. I'd like django to fetch values and commit this data without user interaction. Is there a simple way to have fields populated in this fashion on timed intervals? . For now I have temperature data from one sensor that I would like to fetch every 30 seconds so FloatField and a timestamp for that field.

A: The answer to your questions is pretty much the same as the answer to that question. You could use APScheduler's add_job or Celery's periodic tasks to run tasks/jobs every 30 seconds.
Celery might be more reliable, but it's just my gut feeling.
Oh, and it supports Django out of the box (there's also the older django-celery package).


text:
Q: AngularJS modify $scope inside interceptor How can i modify a $scope variable inside an interceptor?
var portal = angular.module('portal', ['ngResource', 'ui.utils', 'ngRoute']).config(function($httpProvider) {
    $httpProvider.interceptors.push(function($q) {
        return {
            responseError: function(rejection) {
                if(rejection.status == -1) {
                    // i want to modify this variable to true / false
                    $scope.restApiServerOnline = false;
                    return;
                }
                return $q.reject(rejection);
            }
        };
    });
});

The purpose of the above code is to intercept all HTTP post / get made to the REST server, and if it fails, toggle this scope variable.

A: I would look at including $rootScope in your config injection, eg:
function($httpProvider, $rootScope) {

Then set something like $rootScope.restApiServerOnline = false; as by the context of the variable, it appears you would like to access that globally anyway.


text:
Q: Grouping and setting conditions for list query I have a list of Status objects carrying int value and datetime in format of

Tue Sep 30 21:22:02 +0000 2014

Code:
public class Status
{
    public string created_at { get; set; }

    public int value { get; set; }
}

Now, I would like to display this information on chart, but for the last 7 days only.
How can I group objects by date in C# and manage to get this information? I would know how to do it in SQL, but I am not familiar with LINQ.

A: I guess you need to group Status to sum or count some other field on your class, so you can get a total of something by day.
If so, given the following example
        List<Status> statusList = new List<Status>();
        statusList.Add(new Status() { Value = 12, CreatedAt = "Tue Sep 30 21:22:02 +0000 2014" });
        statusList.Add(new Status() { Value = 11, CreatedAt = "Tue Sep 30 21:22:02 +0000 2014" });
        statusList.Add(new Status() { Value = 10, CreatedAt = "Tue Sep 30 21:22:02 +0000 2014" });
        statusList.Add(new Status() { Value = 9, CreatedAt = "Sat Sep 27 21:22:02 +0000 2014" });
        statusList.Add(new Status() { Value = 8, CreatedAt = "Fri Sep 26 21:22:02 +0000 2014" });
        statusList.Add(new Status() { Value = 7, CreatedAt = "Thu Sep 25 21:22:02 +0000 2014" });
        statusList.Add(new Status() { Value = 6, CreatedAt = "Wed Sep 24 21:22:02 +0000 2014" });
        statusList.Add(new Status() { Value = 5, CreatedAt = "Tue Sep 23 21:22:02 +0000 2014" });
        statusList.Add(new Status() { Value = 4, CreatedAt = "Mon Sep 22 21:22:02 +0000 2014" });
        statusList.Add(new Status() { Value = 3, CreatedAt = "Sun Sep 21 21:22:02 +0000 2014" });
        statusList.Add(new Status() { Value = 2, CreatedAt = "Sat Sep 20 21:22:02 +0000 2014" });
        statusList.Add(new Status() { Value = 1, CreatedAt = "Fri Sep 19 21:22:02 +0000 2014" });

        var groups = from status in statusList
                  let date = DateTime.ParseExact(status.CreatedAt, "ddd MMM dd HH:mm:ss zzz yyyy", CultureInfo.InvariantCulture)
                  group status by date into g
                  where g.Key.Date >= DateTime.Now - new TimeSpan(7, 0, 0, 0)
                  select g;

        foreach (IGrouping<DateTime, Status> group in groups)
        {
            DateTime day = group.Key;
            int countOfValues = group.Select(g => g.Value).Count();
            Console.WriteLine("Day: {0}", day.ToString());
            Console.WriteLine("countOfValues: {0}", countOfValues.ToString());
        }

It prints:
Day: 9/30/2014 4:22:02 PM
countOfValues: 3 //Three entries on Sep 30...
Day: 9/27/2014 4:22:02 PM
countOfValues: 1
Day: 9/26/2014 4:22:02 PM
countOfValues: 1
Day: 9/25/2014 4:22:02 PM
countOfValues: 1
Day: 9/24/2014 4:22:02 PM
countOfValues: 1

A: Try add following to yours where condition then yours SP/SQL Query will return only records within 7 days.
datediff(day, created_at, getdate()) < 7

A: if you are using int (it's pretty bad, but ok..) then first of all you must convert int to datetime: search on google int to datetime.
The second step's to implement TimeSpan and use overriden operators for Datetime and TimeSpan.
public bool LaterThan7Days(int valueFromClass)
{
    DateTime myTime = //here convert valueFromClass to Datetime, search in google please
    TimeSpan t = new TimeSpan(7,0 , 0, 0); //days, hours ,mins, seconds
    DateTime timeToCompare = myTime + t;
    return timeToCompare > DateTime.Now;
}

and the query should looks like:
var query = from Status in yourContext
            where LaterThan7Days(Status.value)
            select Status;

query.ToList().Foreach(p=> Console.WriteLine(p.created_at));


text:
Q: How can I add my own Resharper templates / snipets? <?xml version="1.0" encoding="utf-8" ?>
<CodeSnippets
  xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
<CodeSnippet Format="1.0.0">
<Header>
  <Title>cr</Title>
  <Shortcut>cr</Shortcut>
  <Description>Code snippet for Console.ReadLine</Description>
  <Author>Microsoft Corporation</Author>
  <SnippetTypes>
    <SnippetType>Expansion</SnippetType>
  </SnippetTypes>
</Header>
<Snippet>
  <Declarations>
    <Literal Editable="false">
      <ID>SystemConsole</ID>
      <Function>SimpleTypeName(global::System.Console)</Function>
    </Literal>
  </Declarations>
  <Code Language="csharp"><![CDATA[$SystemConsole$.ReadLine($end$);]]>
  </Code>
</Snippet>
</CodeSnippet>
</CodeSnippets>

I have been created my own snippets in VS for C#. At this time I am using ReSharper, but my own snippets doesn's show to me like cw, prop or any other.
like this

A: In Visual Studio Menu go to Resharper - Tools - Template Explorer. Add your snippets there.

A: You can define your own templates under:

Resharper > Tools > Template Explorer

In case usage is not immediately clear, here's an example. The following is a template I use for generating unit-tests for NUnit:

Click the dashed square icon to create a new template file (in a yellow circle below). Write your template-code in the window that opens up in the background, using $ before and after words you want to be able to tab between.
Give your template a shortcut in the upper right corner, and save. You should now be able to use it.
The example above can be run using "tmTab" or "tmEnter".
At that point, DO_SOMETHING will be selected for editing. Use Tab or Enter to jump to and select Test_logic.


text:
Q: How Shadow Copy Service works? how it backups the data which we modified I am Using Shadow Copy to restore my files,and restoring my files. I wonder how does it works.

A: A hardware or software shadow copy provider uses one of the following methods for creating a shadow copy:
Complete copy   This method makes a complete copy (called a "full copy" or "clone") of the original volume at a given point in time. This copy is read-only.
Copy-on-write   This method does not copy the original volume. Instead, it makes a differential copy by copying all changes (completed write I/O requests) that are made to the volume after a given point in time.
Redirect-on-write   This method does not copy the original volume, and it does not make any changes to the original volume after a given point in time. Instead, it makes a differential copy by redirecting all changes to a different volume.
Source: http://technet.microsoft.com/en-us/library/ee923636%28v=ws.10%29.aspx

A: the way shadow copy works is by placing a marker on the hard drive at the point of a snapshot so that when yu open a file and work on it further, it is actually saved again to a different part of the physical drive.  When you do a restore, the older copy of the file is marked as active and the newer version discarded.


text:
Q: Openwrt write to USB serial /dev/ttyACMO I have an STM32 connected over USB to and OpenWRT Linux device and it appears under /dev/ttyACM0. I have a custom C application that communicates with it. In my C application the device basically is treated like a serial port.
Until now this always worked 100%, I could always read and write, I built a new image for my LIMA module and now suddenly I can no longer write to my STM32 from my C application.
However this works fine and the message is received by the STM: echo -n -e "\x02\x00\x01\x02" > /dev/ttyACM0
When I look in dmesg I do see something funny:
[ 389.334398] usb 1-1.3: new full-speed USB device number 11 using ehci-platform
[ 389.458391] cdc_acm 1-1.3:1.0: ttyACM0: USB ACM device
[ 424.476642] cdc_acm 1-1.3:1.0: failed to set dtr/rts

Do you guys know what might be after going wrong? Could some USB package that updated itself have screwed something up?


text:
Q: Spring mvc @PathVariable not working I am struggling for a hour to resolve the @pathvariable annotaton issue.
In my jsp,code looks like below

<spring:url value="/deleteEmployee.html" var="deleteEmployee">
</spring:url>
<img src="<c:url value="/images/delete.png" />" />

In my controller i have a method
@RequestMapping(value = "deleteEmployee/{userId}",method=RequestMethod.GET)
public String deleteUser(@PathVariable("userId") String userId){
        System.out.println("userID::"+userId);
     return null;
}

But the controller was never getting called,always it is navigate to the 404 page
My URL looks like below:
http://localhost:8080/TaskMgmt/deleteEmployee.html/h776655

Please don't tag this question as duplicate since i searched all the URL before posting this question but i am not able to find a solution.
Spring version : 3.2.6
Also in my web.xml i have a below entry
<servlet-mapping>
        <servlet-name>taskMgmtServlet</servlet-name>
        <url-pattern>*.html</url-pattern>
    </servlet-mapping>

Please someone help me to resolve the issuse.

A: Your Url http://localhost:8080/TaskMgmt/deleteEmployee.html/h776655 not matching Spring Mvc Dispatcher Pattern *.html, it must finished by .html to be handled by Spring Mvc Dispatcher like this :
http://localhost:8080/TaskMgmt/deleteEmployee/h776655.html


text:
Q: Issue with date value when sending the date in ISO format to Web API Controller I am using an Angular Resource to post data, in JSON format, to my Web API controller. The post contains a date field in which I pass a date value in ISO, UTC format like so:
2016-05-01T07:00:00.000Z

But when I inspect the object when it hits my Web API controller, the date value is converted to an incorrect DateTime value of:
5/1/2016 7:00:00 AM

When it should be:
5/1/2016 12:00:00 AM

Correct me if I'm wrong, but I think the value should be this because if I execute the statement DateTime.Parse("2016-05-01T07:00:00.000Z"); I get the following value: 5/1/2016 12:00:00 AM
I've read through various posts on the Internet, including SO, but haven't been able to come up with a solution to post dates in ISO format and have them successfully convert into proper DateTime Values.
What I've tried:
I've tried various things like adding the following settings in my WebApiConfig.cs file:
config.Formatters.JsonFormatter.SerializerSettings.Converters.Add(new IsoDateTimeConverter());
config.Formatters.JsonFormatter.SerializerSettings.DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc;

I also tried a fix outlined here by adding the following line to my WebApiConfig.cs file:
config.Formatters.JsonFormatter.SerializerSettings.Culture = System.Globalization.CultureInfo.CurrentCulture;

And this line to my Web.config:
<globalization enableClientBasedCulture="false" requestEncoding="utf-8" responseEncoding="utf-8" culture="en-US" uiCulture="en-US"/>

I know I can change the properties that hold the DateTime values to be strings and use the DateTime.Parse(dateTimeString) method of generating a DateTime Value from an ISO date value, but I want to avoid having to do that all across my application which has many datetime objects specified in my models.
Most of the posts on SO have to deal with DateTime objects not being in the correct format for the response, but I just haven't found an answer to my issue when sending the request over.


text:
Q: wxPython - Setting a help string for a button in toolbar I noticed I can have a help string appear in the status bar whenever I mouse over tools in my toolbar. I cannot find a way to accomplish this with text buttons.
My toolbar creation is similar to
# Make Tool Bar
toolbar = self.CreateToolBar()
# Make Tool Bar Items
# Play
self.addBasicTool(toolbar, "Play",
                  "This is my help string",
                  stuff.image_play,
                  self.OnPlay)
# My Button
btn = wx.Button(toolbar, wx.ID_OPEN, label="TEXT BUTTON ")
btn.Bind(wx.EVT_BUTTON, self.OnButtonPress)
toolbar.AddControl(btn)

addBasicTool just takes the image, scales it to a proper size, creates the tool with AddBasicTool, and binds the tool to the handler.
def addBasicTool(self, toolbar, label, desc, imgPath, handler):
    icon_width=stuff.toolbar_icon_w
    icon_height=stuff.toolbar_icon_h
    size = (icon_width, icon_height)
    img = wx.Image(imgPath, wx.BITMAP_TYPE_ANY).\
                   Scale(*size).ConvertToBitmap()
    tool = toolbar.AddSimpleTool(-1, img, label, desc)
    self.Bind(wx.EVT_MENU, handler, tool)

For the tool, the helper string is set pretty straight forward. I can't find anything to do the same with a button.
This button may just end up being a filler until I get an icon for it, but I'm still curious how helper strings can be done. I could have a handler that sets the statusBar when the mouse is over the button, but I feel like that is already done somewhere. Thanks the help

A: Basically you'll have to catch the mouse as it moves over your buttons and update the status bar accordingly. It's not very hard. You just need to bind to wx.EVT_MOTION. Here's a simple example:
import wx

########################################################################
class MyPanel(wx.Panel):
    """"""

    #----------------------------------------------------------------------
    def __init__(self, parent):
        """Constructor"""
        wx.Panel.__init__(self, parent)
        self.frame = parent

        test_btn = wx.Button(self, label='Test Button')
        test_btn.Bind(wx.EVT_MOTION, self.updateStatusBar)

        test_btn_2 = wx.Button(self, label='Test Button')
        test_btn_2.Bind(wx.EVT_MOTION, self.updateStatusBar)

        self.buttons = {test_btn: 'Test help string',
                        test_btn_2: 'Another string'}

        main_sizer = wx.BoxSizer(wx.VERTICAL)
        main_sizer.Add(test_btn, 0, wx.ALL, 5)
        main_sizer.Add(test_btn_2, 0, wx.ALL, 5)
        self.SetSizer(main_sizer)

    #----------------------------------------------------------------------
    def updateStatusBar(self, event):
        """"""
        btn = event.GetEventObject()
        if btn in self.buttons:
            status = self.buttons[btn]
            self.frame.sb.SetStatusText(status)

########################################################################
class MyFrame(wx.Frame):
    """"""

    #----------------------------------------------------------------------
    def __init__(self):
        """Constructor"""
        wx.Frame.__init__(self, None, title='Test Help Strings')
        panel = MyPanel(self)
        self.sb = self.CreateStatusBar()
        self.Show()

if __name__ == '__main__':
    app = wx.App(False)
    frame = MyFrame()
    app.MainLoop()


text:
Q: IE 11 Объект не поддерживает свойство или метод "getAttribute" В IE v.11 вылезает ошибка при триггере функции по клику на рейтинг (5 звезд), причем, иногда, клик по рейтингу не отдает никакой ошибки. Пыталась выявить закономерность и найти какую-то зацепку: ошибка всегда вылезает рандомно.

Объект не поддерживает свойство или метод "getAttribute"

filter: {
    "ID": assertGetIdNotName ?
        function(id) {
            id = id.replace(rbackslash, "");
            return function (elem ) {
                /**
                 * Начало проблемы
                 */
                return elem.getAttribute("id") === id;
                /**
                 * Конец проблемы
                 */
            };
        } :
        function(id) {
            id = id . replace(rbackslash, "");
            return function (elem ) {
                var node = typeofelem.getAttributeNode !== strundefined && elem.getAttributeNode("id");
                return node && node.value === id;
            };
        },
    }

Данный метод должен поддерживаться IE, но тем не менее вылезает ошибка.


text:
Q: Gan loss tiny, discriminator loss huge? I can't find the problem in my code - I'm training a GAN and the gan loss and discriminator loss are very low, 0.04 and it seems like it's converging well but a - the pictures don't look very good but the actual problem is that, b - somehow when I do gan.predict(noise) it's very close to 1, but when I do discriminator.predict(gan(noise)), it's very close to 0 although it's supposed to be identical. Here's my code:
Generator code:

def create_generator():
    generator=tf.keras.Sequential()
    #generator.add(layers.Dense(units=50176,input_dim=25))
    generator.add(layers.Dense(units=12544,input_dim=100))
    #generator.add(layers.Dropout(0.2))
    generator.add(layers.Reshape([112,112,1])) #112,112
    generator.add(layers.Conv2D(32, kernel_size=3,padding='same',activation='relu'))
    generator.add(layers.UpSampling2D()) #224,224
    generator.add(layers.Conv2D(1, kernel_size=4,padding='same',activation='tanh'))

    generator.compile(loss='binary_crossentropy', optimizer=adam_optimizer())
    return generator
g=create_generator()
g.summary()

Discriminator code:
#IMAGE DISCRIMINATOR
def create_discriminator():
  discriminator=tf.keras.Sequential()
  discriminator.add(layers.Conv2D(64, kernel_size=2,padding='same',activation='relu',input_shape=[224,224,1]))
  discriminator.add(layers.Dropout(0.5))
  discriminator.add(layers.Conv2D(32,kernel_size=2,padding='same',activation='relu'))
  discriminator.add(layers.Dropout(0.5))
  discriminator.add(layers.Conv2D(16,kernel_size=2,padding='same',activation='relu'))
  discriminator.add(layers.Dropout(0.5))
  discriminator.add(layers.Conv2D(8,kernel_size=2,padding='same',activation='relu'))
  discriminator.add(layers.Dropout(0.5))
  discriminator.add(layers.Conv2D(1,kernel_size=2,padding='same',activation='relu'))
  discriminator.add(layers.Dropout(0.5))
  discriminator.add(layers.Flatten())

  discriminator.add(layers.Dense(units=1, activation='sigmoid'))

  discriminator.compile(loss='binary_crossentropy', optimizer=tf.optimizers.Adam(lr=0.0002))
  return discriminator
d =create_discriminator()
d.summary()

Gan code:
def create_gan(discriminator, generator):
    discriminator.trainable=False
    gan_input = tf.keras.Input(shape=(100,))
    x = generator(gan_input)
    gan_output= discriminator(x)
    gan= tf.keras.Model(inputs=gan_input, outputs=gan_output)
    #gan.compile(loss='binary_crossentropy', optimizer='adam')
    gan.compile(loss='binary_crossentropy', optimizer=adam_optimizer())
    return gan
gan = create_gan(d,g)
gan.summary()

Training code (I purposely don't do train_on_batch with the gan cause I wanted to see if the gradients zero out.)
#@tf.function
def training(epochs=1, batch_size=128, rounds=50):
    batch_count = X_bad.shape[0] / batch_size

    # Creating GAN
    generator = create_generator()
    discriminator = create_discriminator()
    ###########if you want to continue training an already trained gan
    #discriminator.set_weights(weights)
    gan = create_gan(discriminator, generator)
    start = time.time()

    for e in range(1,epochs+1 ):
        #print("Epoch %d" %e)
        #for _ in tqdm(range(batch_size)):
        #generate  random noise as an input  to  initialize the  generator
        noise= np.random.normal(0,1, [batch_size, 100])

            # Generate fake MNIST images from noised input
        generated_images = generator.predict(noise)
            #print('gen im shape: ',np.shape(generated_images))

            # Get a random set of  real images
        image_batch = X_bad[np.random.randint(low=0,high=X_bad.shape[0],size=batch_size)]
            #print('im batch shape: ',image_batch.shape)

            #Construct different batches of  real and fake data
        X= np.concatenate([image_batch, generated_images])

            # Labels for generated and real data
        y_dis=np.zeros(2*batch_size)
        y_dis[:batch_size]=0.99

            #Pre train discriminator on  fake and real data  before starting the gan.
        discriminator.trainable=True
        discriminator.train_on_batch(X, y_dis)

            #Tricking the noised input of the Generator as real data
        noise= np.random.normal(0,1, [batch_size, 100])
        y_gen = np.ones(batch_size)

            # During the training of gan,
            # the weights of discriminator should be fixed.
            #We can enforce that by setting the trainable flag
        discriminator.trainable=False

            #training  the GAN by alternating the training of the Discriminator
            #and training the chained GAN model with Discriminator's weights freezed.

        #gan.train_on_batch(noise, y_gen)
        with tf.GradientTape() as tape:
          pred=gan(noise)
          loss_val=tf.keras.losses.mean_squared_error(y_gen,pred)
    #     loss_val=gan.test_on_batch(noise,y_gen)
    #     loss_val=tf.cast(loss_val,dtype=tf.float32)
        grads=tape.gradient(loss_val,gan.trainable_variables)
        optimizer.apply_gradients(zip(grads, gan.trainable_variables))

        if e == 1 or e % rounds == 0:
          end = time.time()

          loss_value=discriminator.test_on_batch(X, y_dis)
          print("Epoch {:03d}: Loss: {:.3f}".format(e,loss_value))
          gen_loss=gan.test_on_batch(noise,y_gen)
          print('gan loss: ',gen_loss)
          #print('Epoch: ',e,' Loss: ',)
          print('Time for ',rounds,' epochs: ',end-start,' seconds')
          local_time = time.ctime(end)
          print('Printing time: ',local_time)
          plot_generated_images(e, generator,examples=5)
          start = time.time()
    return discriminator,generator,grads

Now, the final losses after around 2000 epochs are 0.039 for the generator and 0.034 for the discriminator. The thing is that when I do the following, look what I get
print('disc for bad train: ',np.mean(discriminator(X_bad[:50])))

#output
disc for bad train:  0.9995248

noise= np.random.normal(0,1, [500, 100])
generated_images = generator.predict(noise)
print('disc for gen: ',np.mean(discriminator(generated_images[:50])))
print('gan for gen: ',np.mean(gan(noise[:50])))

#output
disc for gen:  0.0018724388
gan for gen:  0.96554756

Can anyone find the problem?
Thanks!

A: If anyone stumbles upon this, then I figured it out (although I haven't fixed it yet). What's happening here is that my Gan object is training only the generator weights. The discriminator is a different object that is training itself but when I train the gan, I don't update the discriminator weights in the gan, I only updated the generator weights and therefore when I had the noise as the input to the gan, the output was as I wanted, close to one, however when I took the generated images as the input to the discriminator, since the discriminator was being trained separately from the generator (the discriminator weights were not being changed at all inside the gan), the result was close to zero. A better approach is to create a GAN as a class and be able to approach the discriminator within the gan and the generator within the gan in order to update both of their weights inside the gan.


text:
Q: help with literal syntax - not a function I keep trying to call getMonthDay function. I am passing a pubDate parameter and keep getting error - Break on ErrorXCopyDisableContinue
this.getMonthDay is not a function
Any ideas?
$(document).ready(function(){
    alert = console.log;

    var ns = {

        init : function(){
            $.ajax({
                url: '/calendar/RSSSyndicator.aspx?type=N&number=15&category=8-0%2c4-0%2c6-0%2c10-0%2c7-0%2c17-0%2c16-0%2c9-0%2c5-0%2c3-0%2c2-0&department=3&numdays=31&ics=Y&rsstitle=Annandale+-+Event+Listing&rssid=11',
                success: this.loaded
            });
        },

        loaded: function(data){

            // Find item from the RSS document and iterate over reach one.
            $(data).find('item').each(function(i, value){

                // Set the title and get rid of all chars including and between ()
                var title = $(this).find('title').text().replace(/\w+\s+\(.*?\)/, "");

                var link = $(this).find('link').text();
                var pubDate = $(this).find('pubDate').text();
                alert(title);
                alert(link);
                alert(pubDate);

                test = this.getMonthDay(pubDate);

                $('#events').append("
" + title + "
" + link + "
");

            });

        //  var t = items[0].getElementsByTagName('title');
        //  alert(t[0].firstChild.nodeValue);

        },

        getMonthDay : function(pubDate){

            var d = new Date(pubDate);

            d.month = d.getMonth();
            var months = ["January", "February", "March", "Thursday", "Friday", "Saturday", "Sunday"];
            var month = months[d.month]
            var newMonthDay = month + " " + d.getDay();

            return newMonthDay;

        }

    }

    ns.init();

});

A: There are actually 2 issues here.  The most immediate/local is that this refers to that <item> element you're on in the .each() loop, we can fix that by holding a reference outside to this, like so:
var self = this;

Then inside the function, use self.getMonthDay(pubDate);.  Second, after that's fixed...even then this isn't what you want, it refers to the options object you passed to $.ajax().  To remedy this, you need the context option there to maintain this being ns as well, like this:
$(document).ready(function(){
    alert = console.log;
    var ns = {
        init : function(){
            $.ajax({
                url: '/calendar/RSSSyndicator.aspx?type=N&number=15&category=8-0%2c4-0%2c6-0%2c10-0%2c7-0%2c17-0%2c16-0%2c9-0%2c5-0%2c3-0%2c2-0&department=3&numdays=31&ics=Y&rsstitle=Annandale+-+Event+Listing&rssid=11',
                context: this,          //add this!
                success: this.loaded
            });
        },
        loaded: function(data){
            var self = this;           //maintain a reference to this
            $(data).find('item').each(function(i, value){
                var title = $(this).find('title').text().replace(/\w+\s+\(.*?\)/, "");
                var link = $(this).find('link').text();
                var pubDate = $(this).find('pubDate').text();
                var test = self.getMonthDay(pubDate);
                $('#events').append("
" + title + "
" + link + "
");
            });
        },
        getMonthDay : function(pubDate){
            var d = new Date(pubDate);
            d.month = d.getMonth();
            var months = ["January", "February", "March", "Thursday", "Friday", "Saturday", "Sunday"];
            var month = months[d.month]
            var newMonthDay = month + " " + d.getDay();
            return newMonthDay;
        }
    }
    ns.init();
});

A: You're calling this.getMonthDay from within the callback you're passing to .each(). At that point, this is a completely different context. Instead, consider something like:
loaded: function(data){

    var ns = this;

    // Find item from the RSS document and iterate over reach one.
    $(data).find('item').each(function(i, value){

        // Set the title and get rid of all chars including and between ()
        var title = $(this).find('title').text().replace(/\w+\s+\(.*?\)/, "");

        var link = $(this).find('link').text();
        var pubDate = $(this).find('pubDate').text();
        alert(title);
        alert(link);
        alert(pubDate);

        test = ns.getMonthDay(pubDate);

        $('#events').append("
" + title + "
" + link + "
");

    });

//  var t = items[0].getElementsByTagName('title');
//  alert(t[0].firstChild.nodeValue);

},

Note the creation of an alias (ns) for this, which can then continue to refer to that object regardless of what objects/contexts might later come into play.


text:
Q: checkpointing library for C# Am looking for checkpointing library for C#. Any ideas ?
see  http://en.wikipedia.org/wiki/Application_checkpointing

A: This should be possible to implement using transactions (commit/rollback) or undo. If you design your classes and operations correctly it will work, it will require some hard work and discipline using the classes of course. You'll also need to be careful about exceptions.
The System.Transactions namespace (as Rune suggested) seems to be a good candidate, or atleast a good starting point.

A: If I understand you correctly (and the question is pretty vague so I'm not sure of this at all) then Windows Workflow Foundation certainly has this capability.  However, it's almost certainly overkill for what you're asking.

Okay, you added a link that better explains what you mean by checkpointing.
With that in mind, .Net doesn't have anything built in to support this directly.  However, anything that uses a state machine where the state machine can be persisted, can be  inspected/validated, and is transactional has this sort of thing naturally built-in.  WWF is one example of that.

A: I dont think there is built in support for this but it should be relatively easy to build you own.
Assuming that you have a central application class that stores your applications state, or at least the part used in the checkpointing. Then you could use serialization to store the state of your application whenever required. Further, it would be easy to store the snapshots in a database of a file if you needed it later. But this would require you to write your own library to support it.
As I write this I start feeling that there must be some support for this in the framework. Look at the System.Transactions namespace for instance.

A: Given the link from wikipedia, I can tell you .NET/CLR does not support this. What makes this impossible is due to the fact that .NET does not allow you to inspect of modify the application stack which in turn is not possible due to builtin security in .NET.


text:
Q: Change PHP Generated File Link Into Downloadable Click I have been looking for a solution to a problem I'm having with my code. The nearest solution to my problem was found here however that solution didn't fit my problem.
I'm listing uploaded files in PHP on my page, with each file being an  to the file's location. That works fine, however I am new to PHP and am having difficulty in implementing others code.
Here's the code I'm using, if it helps:
<?php
    // Directory Location
    $directory = './';

    // Timezone (UK BST)
    date_default_timezone_set(WET);

    // Define Byte Sizes
    function file_size($size)
    {
        $filesizename = array(" Bytes", " KB", " MB", " GB", " TB", " PB", " EB", " ZB", " YB");
        return $size ? round($size/pow(1024, ($i = floor(log($size, 1024)))), 1) . $filesizename[$i] : '0 Bytes';
    }

    // fetches all executable files in that directory and loop over each
    foreach(glob($file.'*wav') as $file) {

        // List Link to Files & Date/Time
        echo '
              ' . date("m/d/Y H:i", filemtime($file));

        // List File Name & Size
        echo '   '.$file.'
        Size: '.file_size(filesize($file)).'';
    }
?>

If possible I would prefer the download links to be generated in PHP for each individual file. The files are listed like this: http://i.stack.imgur.com/N8Lxa.png

A: You should use the code of the mentioned SO answer in the following way:
change the link you display to the following which direct the user to download.php and hands over the information which file to download:
echo ' ...

Then add an download.php with the content of the SO answer but using
$filename = $_GET['file'];

to get the given filename out of the url.
Additionally you have to change header('Content-Type: application/pdf'); to whatever filetype you want to be downloaded.

A: for list of files list.php e.g.
<?php

// salt for md5 check
$saltmd5 = '76t7gjbertdfv56w45sdve54etyv';

// Directory Location
$directory = './';

// Timezone (UK BST)
date_default_timezone_set(WET);

// Define Byte Sizes
function file_size($size)
{
    $filesizename = array(" Bytes", " KB", " MB", " GB", " TB", " PB", " EB", " ZB", " YB");
    return $size ? round($size/pow(1024, ($i = floor(log($size, 1024)))), 1) . $filesizename[$i] : '0 Bytes';
}

// fetches all executable files in that directory and loop over each
foreach(glob($file.'*wav') as $file) {

    // List Link to Files & Date/Time
    $file_md5 = md5("$file$saltmd5"); // md5 file check
    $file_link = "dwn.php?f=$file&c=$file_md5"; // file link

    echo '
          ' . date("m/d/Y H:i", filemtime($file));

    // List File Name & Size
    echo '   '.$file.'
    Size: '.file_size(filesize($file)).'';
}

?>

for download of files dwn.php e.g.
    <?php

    // salt for md5 check
    $saltmd5 = '76t7gjbertdfv56w45sdve54etyv';

$file_md5 = $_GET['c']; // md5 file check
$filename = $_GET['f']; // the name of the file that is downloaded

if($file_md5==md5("$filename$saltmd5")){

     // Directory Location
    $directory = './';

$size = filesize($directory . $filename) ;
header("Content-Type: application/force-download; name=\"". $filename ."\"");
header("Content-Transfer-Encoding: binary");
header("Content-Length: ". $size ."");
header("Content-Disposition: attachment; filename=\"". $filename ."\"");
header("Expires: 0");
header("Cache-Control: no-cache, must-revalidate");
header("Pragma: no-cache");
echo (readfile($directory . $filename));

}
else
   {
    die('no existo'); //bad file
    }

?>


text:
Q: Unable to install Twilio Whenever I try to install Twilio using the command:
sudo pip install twilio

the following error shows up:
    kvs@Hunter:~$ sudo pip install twilio
The directory '/home/kvs/.cache/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
The directory '/home/kvs/.cache/pip' or its parent directory is not owned by the current user and caching wheels has been disabled. check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
Requirement already satisfied: twilio in /usr/local/lib/python2.7/dist-packages/twilio-6.4.1-py2.7.egg
Requirement already satisfied: requests>=2.0.0 in /usr/local/lib/python2.7/dist-packages (from twilio)
Requirement already satisfied: six in /usr/lib/python2.7/dist-packages (from twilio)
Requirement already satisfied: pytz in /usr/lib/python2.7/dist-packages (from twilio)
Requirement already satisfied: PyJWT>=1.4.2 in /usr/local/lib/python2.7/dist-packages (from twilio)
Collecting cryptography>=1.3.4 (from twilio)
  Downloading cryptography-1.9.tar.gz (409kB)
    100% |████████████████████████████████| 419kB 785kB/s
Requirement already satisfied: idna>=2.0.0 in /usr/local/lib/python2.7/dist-packages/idna-2.5-py2.7.egg (from twilio)
Requirement already satisfied: pyOpenSSL>=0.14 in /usr/local/lib/python2.7/dist-packages/pyOpenSSL-17.0.0-py2.7.egg (from twilio)
Requirement already satisfied: urllib3<1.22,>=1.21.1 in /usr/local/lib/python2.7/dist-packages (from requests>=2.0.0->twilio)
Requirement already satisfied: chardet<3.1.0,>=3.0.2 in /usr/local/lib/python2.7/dist-packages (from requests>=2.0.0->twilio)
Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python2.7/dist-packages (from requests>=2.0.0->twilio)
Requirement already satisfied: asn1crypto>=0.21.0 in /usr/local/lib/python2.7/dist-packages (from cryptography>=1.3.4->twilio)
Requirement already satisfied: enum34 in /usr/local/lib/python2.7/dist-packages (from cryptography>=1.3.4->twilio)
Requirement already satisfied: ipaddress in /usr/local/lib/python2.7/dist-packages (from cryptography>=1.3.4->twilio)
Requirement already satisfied: cffi>=1.7 in /usr/local/lib/python2.7/dist-packages (from cryptography>=1.3.4->twilio)
Requirement already satisfied: pycparser in /usr/local/lib/python2.7/dist-packages (from cffi>=1.7->cryptography>=1.3.4->twilio)
Installing collected packages: cryptography
  Running setup.py install for cryptography ... error
    Complete output from command /usr/bin/python -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-0H7sWu/cryptography/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /tmp/pip-FO95l8-record/install-record.txt --single-version-externally-managed --compile:
    running install
    running build
    running build_py
    creating build
    creating build/lib.linux-x86_64-2.7
    creating build/lib.linux-x86_64-2.7/cryptography
    copying src/cryptography/utils.py -> build/lib.linux-x86_64-2.7/cryptography
    copying src/cryptography/__init__.py -> build/lib.linux-x86_64-2.7/cryptography
    copying src/cryptography/exceptions.py -> build/lib.linux-x86_64-2.7/cryptography
    copying src/cryptography/fernet.py -> build/lib.linux-x86_64-2.7/cryptography
    copying src/cryptography/__about__.py -> build/lib.linux-x86_64-2.7/cryptography
    creating build/lib.linux-x86_64-2.7/cryptography/hazmat
    copying src/cryptography/hazmat/__init__.py -> build/lib.linux-x86_64-2.7/cryptography/hazmat
    creating build/lib.linux-x86_64-2.7/cryptography/x509
    copying src/cryptography/x509/name.py -> build/lib.linux-x86_64-2.7/cryptography/x509
    copying src/cryptography/x509/general_name.py -> build/lib.linux-x86_64-2.7/cryptography/x509
    copying src/cryptography/x509/certificate_transparency.py -> build/lib.linux-x86_64-2.7/cryptography/x509
    copying src/cryptography/x509/__init__.py -> build/lib.linux-x86_64-2.7/cryptography/x509
    copying src/cryptography/x509/base.py -> build/lib.linux-x86_64-2.7/cryptography/x509
    copying src/cryptography/x509/oid.py -> build/lib.linux-x86_64-2.7/cryptography/x509
    copying src/cryptography/x509/extensions.py -> build/lib.linux-x86_64-2.7/cryptography/x509
    creating build/lib.linux-x86_64-2.7/cryptography/hazmat/backends
    copying src/cryptography/hazmat/backends/__init__.py -> build/lib.linux-x86_64-2.7/cryptography/hazmat/backends
    copying src/cryptography/hazmat/backends/interfaces.py -> build/lib.linux-x86_64-2.7/cryptography/hazmat/backends
    creating build/lib.linux-x86_64-2.7/cryptography/hazmat/primitives
    copying src/cryptography/hazmat/primitives/hmac.py -> build/lib.linux-x86_64-2.7/cryptography/hazmat/primitives
    copying src/cryptography/hazmat/primitives/constant_time.py -> build/lib.linux-x86_64-2.7/cryptography/hazmat/primitives
    copying src/cryptography/hazmat/primitives/keywrap.py -> build/lib.linux-x86_64-2.7/cryptography/hazmat/primitives
    copying src/cryptography/hazmat/primitives/__init__.py -> build/lib.linux-x86_64-2.7/cryptography/hazmat/primitives
    copying src/cryptography/hazmat/primitives/mac.py -> build/lib.linux-x86_64-2.7/cryptography/hazmat/primitives
    copying src/cryptography/hazmat/primitives/padding.py -> build/lib.linux-x86_64-2.7/cryptography/hazmat/primitives
    copying src/cryptography/hazmat/primitives/serialization.py -> build/lib.linux-x86_64-2.7/cryptography/hazmat/primitives
    copying src/cryptography/hazmat/primitives/cmac.py -> build/lib.linux-x86_64-2.7/cryptography/hazmat/primitives
    copying src/cryptography/hazmat/primitives/interfaces.py -> build/lib.linux-x86_64-2.7/cryptography/hazmat/primitives
    copying src/cryptography/hazmat/primitives/hashes.py -> build/lib.linux-x86_64-2.7/cryptography/hazmat/primitives
    creating build/lib.linux-x86_64-2.7/cryptography/hazmat/bindings
    copying src/cryptography/hazmat/bindings/__init__.py -> build/lib.linux-x86_64-2.7/cryptography/hazmat/bindings
    creating build/lib.linux-x86_64-2.7/cryptography/hazmat/backends/openssl
    copying src/cryptography/hazmat/backends/openssl/hmac.py -> build/lib.linux-x86_64-2.7/cryptography/hazmat/backends/openssl
    copying src/cryptography/hazmat/backends/openssl/ec.py -> build/lib.linux-x86_64-2.7/cryptography/hazmat/backends/openssl
    copying src/cryptography/hazmat/backends/openssl/utils.py -> build/lib.linux-x86_64-2.7/cryptography/hazmat/backends/openssl
    copying src/cryptography/hazmat/backends/openssl/ciphers.py -> build/lib.linux-x86_64-2.7/cryptography/hazmat/backends/openssl
    copying src/cryptography/hazmat/backends/openssl/decode_asn1.py -> build/lib.linux-x86_64-2.7/cryptography/hazmat/backends/openssl
    copying src/cryptography/hazmat/backends/openssl/dh.py -> build/lib.linux-x86_64-2.7/cryptography/hazmat/backends/openssl
    copying src/cryptography/hazmat/backends/openssl/__init__.py -> build/lib.linux-x86_64-2.7/cryptography/hazmat/backends/openssl
    copying src/cryptography/hazmat/backends/openssl/dsa.py -> build/lib.linux-x86_64-2.7/cryptography/hazmat/backends/openssl
    copying src/cryptography/hazmat/backends/openssl/backend.py -> build/lib.linux-x86_64-2.7/cryptography/hazmat/backends/openssl
    copying src/cryptography/hazmat/backends/openssl/encode_asn1.py -> build/lib.linux-x86_64-2.7/cryptography/hazmat/backends/openssl
    copying src/cryptography/hazmat/backends/openssl/rsa.py -> build/lib.linux-x86_64-2.7/cryptography/hazmat/backends/openssl
    copying src/cryptography/hazmat/backends/openssl/x509.py -> build/lib.linux-x86_64-2.7/cryptography/hazmat/backends/openssl
    copying src/cryptography/hazmat/backends/openssl/cmac.py -> build/lib.linux-x86_64-2.7/cryptography/hazmat/backends/openssl
    copying src/cryptography/hazmat/backends/openssl/hashes.py -> build/lib.linux-x86_64-2.7/cryptography/hazmat/backends/openssl
    creating build/lib.linux-x86_64-2.7/cryptography/hazmat/primitives/kdf
    copying src/cryptography/hazmat/primitives/kdf/kbkdf.py -> build/lib.linux-x86_64-2.7/cryptography/hazmat/primitives/kdf
    copying src/cryptography/hazmat/primitives/kdf/__init__.py -> build/lib.linux-x86_64-2.7/cryptography/hazmat/primitives/kdf
    copying src/cryptography/hazmat/primitives/kdf/hkdf.py -> build/lib.linux-x86_64-2.7/cryptography/hazmat/primitives/kdf
    copying src/cryptography/hazmat/primitives/kdf/concatkdf.py -> build/lib.linux-x86_64-2.7/cryptography/hazmat/primitives/kdf
    copying src/cryptography/hazmat/primitives/kdf/x963kdf.py -> build/lib.linux-x86_64-2.7/cryptography/hazmat/primitives/kdf
    copying src/cryptography/hazmat/primitives/kdf/pbkdf2.py -> build/lib.linux-x86_64-2.7/cryptography/hazmat/primitives/kdf
    copying src/cryptography/hazmat/primitives/kdf/scrypt.py -> build/lib.linux-x86_64-2.7/cryptography/hazmat/primitives/kdf
    creating build/lib.linux-x86_64-2.7/cryptography/hazmat/primitives/ciphers
    copying src/cryptography/hazmat/primitives/ciphers/algorithms.py -> build/lib.linux-x86_64-2.7/cryptography/hazmat/primitives/ciphers
    copying src/cryptography/hazmat/primitives/ciphers/__init__.py -> build/lib.linux-x86_64-2.7/cryptography/hazmat/primitives/ciphers
    copying src/cryptography/hazmat/primitives/ciphers/base.py -> build/lib.linux-x86_64-2.7/cryptography/hazmat/primitives/ciphers
    copying src/cryptography/hazmat/primitives/ciphers/modes.py -> build/lib.linux-x86_64-2.7/cryptography/hazmat/primitives/ciphers
    creating build/lib.linux-x86_64-2.7/cryptography/hazmat/primitives/asymmetric
    copying src/cryptography/hazmat/primitives/asymmetric/ec.py -> build/lib.linux-x86_64-2.7/cryptography/hazmat/primitives/asymmetric
    copying src/cryptography/hazmat/primitives/asymmetric/utils.py -> build/lib.linux-x86_64-2.7/cryptography/hazmat/primitives/asymmetric
    copying src/cryptography/hazmat/primitives/asymmetric/dh.py -> build/lib.linux-x86_64-2.7/cryptography/hazmat/primitives/asymmetric
    copying src/cryptography/hazmat/primitives/asymmetric/__init__.py -> build/lib.linux-x86_64-2.7/cryptography/hazmat/primitives/asymmetric
    copying src/cryptography/hazmat/primitives/asymmetric/dsa.py -> build/lib.linux-x86_64-2.7/cryptography/hazmat/primitives/asymmetric
    copying src/cryptography/hazmat/primitives/asymmetric/rsa.py -> build/lib.linux-x86_64-2.7/cryptography/hazmat/primitives/asymmetric
    copying src/cryptography/hazmat/primitives/asymmetric/padding.py -> build/lib.linux-x86_64-2.7/cryptography/hazmat/primitives/asymmetric
    creating build/lib.linux-x86_64-2.7/cryptography/hazmat/primitives/twofactor
    copying src/cryptography/hazmat/primitives/twofactor/utils.py -> build/lib.linux-x86_64-2.7/cryptography/hazmat/primitives/twofactor
    copying src/cryptography/hazmat/primitives/twofactor/hotp.py -> build/lib.linux-x86_64-2.7/cryptography/hazmat/primitives/twofactor
    copying src/cryptography/hazmat/primitives/twofactor/__init__.py -> build/lib.linux-x86_64-2.7/cryptography/hazmat/primitives/twofactor
    copying src/cryptography/hazmat/primitives/twofactor/totp.py -> build/lib.linux-x86_64-2.7/cryptography/hazmat/primitives/twofactor
    creating build/lib.linux-x86_64-2.7/cryptography/hazmat/bindings/openssl
    copying src/cryptography/hazmat/bindings/openssl/__init__.py -> build/lib.linux-x86_64-2.7/cryptography/hazmat/bindings/openssl
    copying src/cryptography/hazmat/bindings/openssl/binding.py -> build/lib.linux-x86_64-2.7/cryptography/hazmat/bindings/openssl
    copying src/cryptography/hazmat/bindings/openssl/_conditional.py -> build/lib.linux-x86_64-2.7/cryptography/hazmat/bindings/openssl
    running egg_info
    writing requirements to src/cryptography.egg-info/requires.txt
    writing src/cryptography.egg-info/PKG-INFO
    writing top-level names to src/cryptography.egg-info/top_level.txt
    writing dependency_links to src/cryptography.egg-info/dependency_links.txt
    writing entry points to src/cryptography.egg-info/entry_points.txt
    warning: manifest_maker: standard file '-c' not found

    reading manifest file 'src/cryptography.egg-info/SOURCES.txt'
    reading manifest template 'MANIFEST.in'
    no previously-included directories found matching 'docs/_build'
    warning: no previously-included files matching '*' found under directory 'vectors'
    writing manifest file 'src/cryptography.egg-info/SOURCES.txt'
    running build_ext
    generating cffi module 'build/temp.linux-x86_64-2.7/_padding.c'
    creating build/temp.linux-x86_64-2.7
    generating cffi module 'build/temp.linux-x86_64-2.7/_constant_time.c'
    generating cffi module 'build/temp.linux-x86_64-2.7/_openssl.c'
    building '_openssl' extension
    creating build/temp.linux-x86_64-2.7/build
    creating build/temp.linux-x86_64-2.7/build/temp.linux-x86_64-2.7
    x86_64-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fno-strict-aliasing -Wdate-time -D_FORTIFY_SOURCE=2 -g -fstack-protector-strong -Wformat -Werror=format-security -fPIC -I/usr/include/python2.7 -c build/temp.linux-x86_64-2.7/_openssl.c -o build/temp.linux-x86_64-2.7/build/temp.linux-x86_64-2.7/_openssl.o
    build/temp.linux-x86_64-2.7/_openssl.c:434:30: fatal error: openssl/opensslv.h: No such file or directory
    compilation terminated.
    error: command 'x86_64-linux-gnu-gcc' failed with exit status 1

    ----------------------------------------
Command "/usr/bin/python -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-0H7sWu/cryptography/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /tmp/pip-FO95l8-record/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /tmp/pip-build-0H7sWu/cryptography/

How to resolve it?

A: Just posting as the answer, for making it more helpful:
sudo apt-get install libssl-dev


text:
Q: No module named Crypto import error for sage I'm running Sage's notebook on an Ubuntu machine and I'm using module crypto for using AES. My code is from Crypto.Cipher import AES. There are lots of posts with the error ImportError: No module named Crypto but none of them works for me apparently because I have a python anaconda installation and a python installation for Sage. How can I solve it?

A: Installing the pycrypto module with Sage's pip,
by running the following in a terminal:
$ sage --pip install pycrypto

Then start Sage and use the Crypto module:
$ sage -q
sage: from Crypto.Cipher import AES
sage:


text:
Q: Using regex/search to find a string and isolate the column Hi so what I am trying to achieve is to locate the column in my csv file (converted to a dataframe) that contains the word 'outbound' and isolate that column, and the two columns next to it. So far I have tried the following snippets of code to no avail.
    mask = np.column_stack([NB_2c17_newburden[col].str.contains(r"outbound", na=False) for col in NB_2c17_newburden])

as well as using search
    for line in NB_2c17_newburden:
       if re.search('outbound', line):
         print (line)

I was just using print line to see if it would work. Any help would be appreciated.
In R it has been achieved with the following code:
  i <- grep('outbound',NB_2c17_newburden)
  i <- i:(i+2)

But I am not sure how to convert that to python

A: df=pd.DataFrame({"col1":["one","two","three"],"col2":["four","five","six"],"col3":["seven","outbound","nine"],"col4":["ten","eleven","twelve"]})

for i in range(len(df.columns)):
    if pd.Series.any(df.iloc[:,i].str.contains(pat="outbound")):
        new_list=pd.DataFrame({df.columns[i-1]:df.iloc[:,i-1],df.columns[i]:df.iloc[:,i],df.columns[i+1]:df.iloc[:,i+1]})

print(new_list)

  col2      col3    col4
0  four     seven     ten
1  five  outbound  eleven
2   six      nine  twelve


text:
Q: Add link to SiteOrigin Image widget's title On one of the websites for our customer, there's a SiteOrigin WordPress plugin installed.
One of the widgets that come with this plugin is SiteOrigin Image widget. There you could add a destination URL to the main image but it is not applied on the title text so basically, only the image leads works as a link which is annoying for our client.
See here, the "How" is not a link:

I've tried to find a way to do this the SiteOrigin way but the only thing I found was this outdated thread.
Is there an easy and elegant way to achieve it without using custom javascript or editing plugin's widget code (or replicating the widget)?