text:
Q: Javascript - parsing dynamically added forms How can I work with forms that have ben added dynamically ?
Hello. I am dynamically adding forms to my page using the following code snippet. Now everything works fine:
$(document).ready(function() {
$("#add").click(function() {
    var intId = $("#buildyourform div").length + 1;
    var fieldWrapper = $("

");
    // I am adding 2 new forms there:
    var topic = $( '<form action = "#" method = "POST" name="new_topic" id="new_topic">'+ document.getElementById('csrf_token').value +
                  '<textarea  name="name" maxlength="1000" cols="25" rows="6" id="new_form"></textarea></form>'+
                  '
<input type="submit" value="Submit" class="newMygt" />');

    var summary = $('<form action = "#" method = "POST" name="new_summary" id="new_summary">'+ document.getElementById('csrf_token').value +
                    '<textarea  name="content" maxlength="1000" cols="25" rows="6" id="new_form"></textarea></form>'+
                    '
<input type="submit" value="Submit" class="newMygt" />');

    (topic).appendTo(fieldWrapper).show('slow');
    (summary).appendTo(fieldWrapper).show('slow');
    $("#buildyourform").append(fieldWrapper);

});

After adding the forms I am parsing them with a great tool called jquery-serialize-object and creating some object literals (f.ex. {"name":"John","content":"blah blah"}).
And then I am turning those object literals into Json with JSON.stringify()
Everything woorks smoothly with simple forms, but when I try to parse form that I add dynamically. I am receiving  {"name":"","content":""} data, because the form that I am parsing does not exist yet.
The question: Could I get some reading material or tips how could I modify the jquery-serialize-object to parse forms that I ad dynamically ? The extension's code is a bit too complicated for me.
EDIT:
I found another Javascript snippet jquery.serializeJSON that serializes a form into a JavaScript Object (for json.stringify()'ing it into Json later) and it seems that it is more up-to-date and it is actively developed, but I am getting completely same results with it: {"name":"","content":""}
THE ANSWER:
I actually should serialize the forms on the submit event and not on the button click. This way I will be serializing data after the user fills it in. And I should have put the  closing tag AFTER the submit buttons, not before. The working code:
$(document).ready(function() {
$("#add").click(function() {
    var intId = $("#buildyourform div").length + 1;
    var fieldWrapper = $("

");
    // I am adding 2 new forms there:
    var topic = $( '<form action = "#" method = "POST" name="new_topic" class="new_topic">'+ document.getElementById('csrf_token').value +
                  '<textarea id ="1" name="name" maxlength="1000" cols="25" rows="6" id="new_form"></textarea>
<input type="submit" value="Submit" class="newMygt" /></form>'
                  );

    var summary = $('<form action = "#" method = "POST" name="new_summary" class="new_summary">'+ document.getElementById('csrf_token').value +
                    '<textarea id="2" name="content" maxlength="1000" cols="25" rows="6" id="new_form"></textarea>
<input type="submit" value="Submit" class="newMygt" /></form>'
                    );

    (topic).appendTo(fieldWrapper).show('slow');
    (summary).appendTo(fieldWrapper).show('slow');
    $("#buildyourform").append(fieldWrapper);

});

$('#buildyourform').on('submit', 'form', function() {
    var $submittedForm = $(this); // form where you clicked submit button
    var $forms = $submittedForm.parents('.fieldwrapper').find('form'); // both forms
    var serializedForm = $forms.serializeJSON(); // serialize both forms
    var json = JSON.stringify(serializedForm);
    alert(json)
    event.preventDefault(); // do not submit the form
});

Now I am getting exactly what I wanted:
{"name":"John","content":"blah blah blah"}

A: There's a couple problems I see right away, but I haven't had time to fully go over your answer yet

*

*Your </form> tag is before your submit button

*You generally want to to serialize the form on the submit event
$("form").submit(function(event) {

  var obj = $(this).serializeObject();
  console.log(obj);

  var json = $(this).serializeJSON();
  console.log(json);

  event.preventDefault();
});

This way you will be serializing the values after a user has filled it in.
However, we need to make a slight modification to this because you're dynamically creating the forms. We need to use a "live" listener with jQuery's .on function
$("document").on("submit", "form", function(event) {
  // ...
});

This will attach a single submit event listener to the document, but it will be triggered by any form that bubbles up a submit event. This means that it will work for forms that are dynamically created after page load, too.

A: There's nothing wrong with the plugins, both serializeJSON and serialize-object can read dynamically created forms.
I don't know how are you reading the forms later, but you need to make sure they exist at the time you are serializing them.
I created a fiddle to try out your code with jquery.serializeJSON: http://jsfiddle.net/vG39k/
I tried to serialize on "submit" event, and realized that you had the input type="submit" buttons outside the forms, so they didn't fire a submit event.
Note that in the fiddle, I put the </form> closing tag AFTER the submit buttons, not before.
That could be your problem.
HINT: use fiddle.net or other similar tool to test your code ;)


text:
Q: wordpress transfer error with bigdump Hello all I'm in the process of transferring my blog via big-dump due to its huge size of 30MB. However when transferring I get this error:
Error at the line 139: INSERT INTO `wp_commentmeta` VALUES (21620,13544,'akismet_as_submitted','a:67:{s:15:\"comment_post_ID\";s:4:\"6034\";s:14:\"comment_author\".....................continues..

I would like to know why this is occurring and how can I fix it.
Thanks in advance!

A: One can't be sure with the limited amount of information you have given, but I think the dump file was not uploaded or created properly. Probably, there is a file size limit for uploading on your new server.
Try to take a compressed database dump and importing.

redpajama_set_name: RedPajamaStackExchange


text:
Q: unordered_map for  in C++ I am trying to create an unordered_map for <xml_node*,string> pair, where xml_node is an element of xml from pugixml library, and i wish to store its pointer as the key. I have declared the map like this :
unordered_map<xml_node*,string> label_hash;

Now the insert function is working well and good. But whenever I try to find an element from the hash like this :
string lb = string(label_hash.find(node));

I get the following error :
no matching function for call to 'std::basic_string<char>::basic_string(std::_Hashtable<pugi::xml_node*, std::pair<pugi::xml_node* const, std::basic_string<char> >, std::allocator<std::pair<pugi::xml_node* const, std::basic_string<char> > >, std::_Select1st<std::pair<pugi::xml_node* const, std::basic_string<char> > >, std::equal_to<pugi::xml_node*>, std::hash<pugi::xml_node*>, std::__detail::_Mod_range_hashing, std::__detail::_Default_ranged_hash, std::__detail::_Prime_rehash_policy, false, false, true>::iterator)'|

Now do I need to implement a hash function and equal function for the map? I was trying to implement them like follows but it doesn't work :
struct hashing_func {
    unsigned long operator()(const xml_node* key) const {
        uintptr_t ad = (uintptr_t)key;
        return (size_t)((13 * ad) ^ (ad >> 15));
        //return hash<xml_node*>(key);
    }
};

struct key_equal_fn {
    bool operator()(const xml_node* t1, const xml_node* t2) const {
        return (t1 == t2);
    }
};

I am a bit new to C++ so a little help would be great!

A: Please read the documentation: unordered_map::find returns an iterator to pair<xml_node const*, string>. (You can't pass that to the string constructor.) Instead do this:
auto iterator = label_hash.find(node);

if (iterator != label_hash.end()) { // `.find()` returns `.end()` if the key is not in the map
    string& lb = iterator->second; // The `&` is optional here, use it if you don't want to deepcopy the whole string.
    // use lb
}
else {
    // key not in the map
}

A: I wrote a little test program:
#include <unordered_map>
#include <string>
namespace pugi
{
  struct xml_node {};
}

int main()
{
  std::unordered_map<pugi::xml_node*, std::string> mymap;

  pugi::xml_node n1;

  mymap.emplace(&n1, "foo");

  auto i = mymap.find(&n1);

  i->second;

  return 0;

}

This compiles perfectly, indicating that as, suspected, the problem is not with the use of a pointer as a map key, not a lack of custom comparitor and not the lack of a hash function.
unordered_map::find returns an iterator - which points to a key/value pair.


text:
Q: Learning good OOP design and unlearning some bad habits
Possible Duplicate:
What books or resources would you recommend to learn practical OO design and development concepts?

I have been mostly a C programmer so far in my career with knowledge of C++. I rely on C++ mostly for the convenience STL provides and I hardly ever focus on good design practices. As I have started to look for a new job position, this bad habit of mine has come back to haunt me. During the interviews, I have been asked to design a problem (like chess, or some other scenario) using OOP and I doing really badly at that (I came to know this through feedback from one interview).
I tried to google stuff and came up with so many opinions and related books that I don't know where to begin. I need a good through introduction to OOP design with which I can learn practical design, not just theory.
Can you point me to any book which meets my requirements? I prefer C++, but any other language is fine as long as I can pick-up good practices.
Also, I know that books can only go so far. I would also appreciate any good practice project ideas that helped you learn and improve your OOP concepts.

A: As for training, I suggest going to http://www.cleancoders.com/ and watching those. They cover  very important ideas.
Once you have watched the videos, take a look at Head First Design Patterns. That walks you through a number of problems and solutions.
I don't have specific project suggestions, but I would advise you to try whatever project in a strictly object oriented language such as Java. C++ let's you cheat too easily, and maybe without even knowing you are doing so.

A: (IMO) There are not great books about software design. Many of the patterns books (I prefer the original, but have heard good things about some others) are pretty good to get the terminology and firm up concepts, but they should be used only after some practice. Without the practice first, programmers tend to over-apply design patterns or misunderstand what problems the patterns prevent.
As for practice problems, I recommend something you've already done for a start. Then you understand the domain and what it's supposed to do and can focus on design alone. Mostly though you just need to iterate. Design a program, implement it, see how it works (and doesn't). Make a new design with lessons learned for a new problem, repeat.
Program design is one of those things that ends up being more craft than science. Keep at it and you'll get progressively better.

A: The 'Head First Design Patterns' book mentioned in the Ben's answer is excellent.  It really brings the ideas from the original 'Gang of Four' Design Patterns Book to life.
As Telastyn says in the answer, understanding to domain is critical and this will really help inform your object model.  For this I really recommend Eric Evans' Domain Driven Design.  It also has a great bibliography of books on OO.
Finally, your approach to testing will inform the way you design your software and what OO patterns you use.
I didn't really 'get' Factory Pattern until I had to write a unit test for some legacy code which in its constructor created one of its dependencies.
This made it very hard to test and drove me to refactor the code to have the dependency created by a Factory which when the tests were being run could be set up to return a mock object.

A: A great book on the subject is Object Oriented Design Heuristics. The book has over 60 heuristics in it which are language independent. In addition to the theory the book has a 122 page appendix of C++ examples. I can't recommend this book enough, it is an excellent introduction.
It's a bit more difficult of a read, but Applying UML And Patterns is also a great introduction. This book is huge and is not a quick read, but it uses two case studies to introduce the material (the monopoly game and a point of sale system).
These two books (and Refactoring) are 3 of the biggest influences in my programming career. You won't be disappointed.

A: I think Uncle Bob's Agile Principles, Patterns, and Practices would be a really good book for you.  The book uses C# for many examples but think of those examples as pseudo-code rather than production C#.  Everything that book teaches can easily be applied to just about any OO language and the level of material will probably be perfect for you.
While you are new and learning, I would strongly advise to stay away from "design patterns" books.  Too many people pick those up, learn few patterns and start slapping them all over the place.  As Uncle Bob points out in the above book, you should code into a pattern when you see one developing, rather than starting with the goal of building a specific pattern in the first place.  However, you need good OOP sense before you can make design decision that would lead you to a pattern.
As far as material outside of the books, I would say learn the SOLID, KISS and DRY principles.  And when I say "learn", I don't mean read about them and think you understand them.  I mean, when you code you live and breath those principles.  Every time you add another function or another variable keep asking yourself:

*

*am I duplicating existing code?

*Is my function/class doing too many things?

*Can what I just wrote be done simpler?

*....

As @worldofchris mentioned (+1 to that answer), I would also recommend learning TDD while you are learning OO.  The two go hand-in-hand and well-designed code, will lend itself to be easily testable.  Conversely, if your code is already testable, it's quality will tend to be higher in relation to code that has no unit test coverage.

A: *

*Clean Code

*Pragmatic Programmer

*Working with Legacy Code
The majority of books will make you feel happy. That won't get you a job.
Start by reading few chapters of Pragmatic Programmer and then move onto Clean Code. Review your old code as you read the books and start refactoring.
Reading books won't give you experience, but making your code "clean" will. It's up to you to decide when to draw the line regarding quality of your code.
Reason why I recommend these books is because guys who wrote them have been working in this industry for decades, and they have a very good idea of what works and what doesn't.


text:
Q: Android showing image Bitmap Error Hi I am trying to read images from all the folders in SD card. So its create folder list like download, camera etc. Now when I press any of the folder it open the Photos in the Grid view. My download folders has images of small size and the application works fine but when i open the camera folder which has bigger size images my application is crashing. My get view function of grid vies is as follows.
 public View getView(int position, View convertView, ViewGroup parent) {
        ImageView i = new ImageView(mContext);
        View v = convertView;
        if (v == null) {
            LayoutInflater vi = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            v = vi.inflate(R.layout.localimageview, null);
        }

        BitmapFactory.Options options=new Options();
        options.inSampleSize=2;
        options.inTempStorage = new byte[16*1024];

        Bitmap bb=BitmapFactory.decodeFile(FileList.get(position).toString(),options);
        i.setImageBitmap(bb);

        i.setLayoutParams(new GridView.LayoutParams(75,75));
        i.setScaleType(ImageView.ScaleType.CENTER_CROP);
        i.setPadding(8, 8, 8, 8);
        v = (View)i;
        return v;
    }
}

}
Its crashing at
           Bitmap bb=BitmapFactory.decodeFile(FileList.get(position).toString(),options);
    07-04 14:21:17.211: ERROR/AndroidRuntime(11509): FATAL EXCEPTION: main
    07-04 14:21:17.211: ERROR/AndroidRuntime(11509): java.lang.OutOfMemoryError: bitmap size exceeds VM budget
    07-04 14:21:17.211: ERROR/AndroidRuntime(11509):     at android.graphics.BitmapFactory.nativeDecodeStream(Native Method)
    07-04 14:21:17.211: ERROR/AndroidRuntime(11509):     at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:459)
    07-04 14:21:17.211: ERROR/AndroidRuntime(11509):     at android.graphics.BitmapFactory.decodeFile(BitmapFactory.java:271)
    07-04 14:21:17.211: ERROR/AndroidRuntime(11509):     at com.ibm.imagegallery.ImageActivity$ImageAdapter.getView(ImageActivity.java:107)
    07-04 14:21:17.211: ERROR/AndroidRuntime(11509):     at android.widget.AbsListView.obtainView(AbsListView.java:1294)
    07-04 14:21:17.211: ERROR/AndroidRuntime(11509):     at android.widget.GridView.makeAndAddView(GridView.java:1219)
    07-04 14:21:17.211: ERROR/AndroidRuntime(11509):     at android.widget.GridView.makeRow(GridView.java:265)
    07-04 14:21:17.211: ERROR/AndroidRuntime(11509):     at android.widget.GridView.fillDown(GridView.java:218)
    07-04 14:21:17.211: ERROR/AndroidRuntime(11509):     at android.widget.GridView.fillFromTop(GridView.java:337)
    07-04 14:21:17.211: ERROR/AndroidRuntime(11509):     at android.widget.GridView.layoutChildren(GridView.java:1111)
    07-04 14:21:17.211: ERROR/AndroidRuntime(11509):     at android.widget.AbsListView.onLayout(AbsListView.java:1147)
    07-04 14:21:17.211: ERROR/AndroidRuntime(11509):     at android.view.View.layout(View.java:7035)
    07-04 14:21:17.211: ERROR/AndroidRuntime(11509):     at android.widget.FrameLayout.onLayout(FrameLayout.java:333)
    07-04 14:21:17.211: ERROR/AndroidRuntime(11509):     at android.view.View.layout(View.java:7035)
    07-04 14:21:17.211: ERROR/AndroidRuntime(11509):     at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1249)
    07-04 14:21:17.211: ERROR/AndroidRuntime(11509):     at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1125)
    07-04 14:21:17.211: ERROR/AndroidRuntime(11509):     at android.widget.LinearLayout.onLayout(LinearLayout.java:1042)
    07-04 14:21:17.211: ERROR/AndroidRuntime(11509):     at android.view.View.layout(View.java:7035)
    07-04 14:21:17.211: ERROR/AndroidRuntime(11509):     at android.widget.FrameLayout.onLayout(FrameLayout.java:333)
    07-04 14:21:17.211: ERROR/AndroidRuntime(11509):     at android.view.View.layout(View.java:7035)
    07-04 14:21:17.211: ERROR/AndroidRuntime(11509):     at android.view.ViewRoot.performTraversals(ViewRoot.java:1045)
    07-04 14:21:17.211: ERROR/AndroidRuntime(11509):     at android.view.ViewRoot.handleMessage(ViewRoot.java:1727)
    07-04 14:21:17.211: ERROR/AndroidRuntime(11509):     at android.os.Handler.dispatchMessage(Handler.java:99)
    07-04 14:21:17.211: ERROR/AndroidRuntime(11509):     at android.os.Looper.loop(Looper.java:123)
    07-04 14:21:17.211: ERROR/AndroidRuntime(11509):     at android.app.ActivityThread.main(ActivityThread.java:4627)
    07-04 14:21:17.211: ERROR/AndroidRuntime(11509):     at java.lang.reflect.Method.invokeNative(Native Method)
    07-04 14:21:17.211: ERROR/AndroidRuntime(11509):     at java.lang.reflect.Method.invoke(Method.java:521)
    07-04 14:21:17.211: ERROR/AndroidRuntime(11509):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860)
    07-04 14:21:17.211: ERROR/AndroidRuntime(11509):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
    07-04 14:21:17.211: ERROR/AndroidRuntime(11509):     at dalvik.system.NativeStart.main(Native Method)
    07-04 14:21:17.221: WARN/ActivityManager(1378):   Force finishing activity com.ibm.imagegallery/.ImageActivity
    07-04 14:21:17.231: WARN/ActivityManager(1378):   Force finishing activity com.ibm.imagegallery/.ImageGallery

A: Check for example this question. Or do a search, this is a common problem answered before.

A: When You access the camera pictures the once which get loaded are too large to handle for the application what you need to do is that you need to degrade the images and get it on your activity
a solution to this problem can be taken from here
Strange out of memory issue while loading an image to a Bitmap object

A: Try following code.Hope this help
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View row = convertView;
            ViewWrapper wrapper = null;

            try {
                if (row == null) {
                    LayoutInflater inflater = getLayoutInflater();
                    row = inflater.inflate(R.layout.gallery_template, parent,
                            false);
                    wrapper = new ViewWrapper(row);
                    row.setTag(wrapper);
                } else {
                    wrapper = (ViewWrapper) row.getTag();
                }

                Bitmap bitmap = getImage(position);

                if (bitmap != null ) {

                    wrapper.getIcon().setImageBitmap(bitmap);
                } else {
                                  showErrorDialogue(getString(R.string.noGalleryData));
                }
            } catch (Exception e) {}
            return (row);
        }

private Bitmap getImage(int position) {
        Bitmap bitmap = null;
        if (Constants.IMAGES_PATH.size() > 0) {

            try {
  BitmapFactory.Options options = new BitmapFactory.Options();
  options.inSampleSize = 4;

                String path = Constants.IMAGES_PATH.get(position);
                // -------- Decode THE BITMAP AND RESIZE IT
                bitmap = BitmapFactory
                    .decodeFile(path,options));
            } catch (Exception e) {}
        }
        return bitmap;
    }


text:
Q: Why was Guinan on the Enterprise in "Yesterday's Enterprise?" Given that it was a military ship (no families) in that timeline, should Guinan have even been there?

A: A deleted line from the original script explains that she's been with him (as a trusted advisor, tactician and confidante) since the year that the war began, e.g. 2344.

She moves closer to him... and if there is a sense of quiet power from Guinan that seems almost evangelical, it is intended.
GUINAN: Picard, we have been together for twenty-two years. I have been your advisor, your confidant, your friend and in all those twenty-two years, I have never led you astray. This time line cannot be allowed to continue. I've told you what you must do. You have only your faith in me to help you decide.

As to what she's doing on the Warship Enterprise (aside from acting as Picard's sounding board), the answer is that she's running the canteen.


text:
Q: String sub not working correctly I've got yet another question about lua. I've created a method to calculate the total amount of some prices. The prices are in this format: £500. So to convert them to numbers I'm using string:sub() and tonumber(), but I'm getting some weird results. Here is my code:`
function functions.calculateTotalAmount()
print("calculating total amount")
saveData.totalAmount = 0
print("There are " .. #saveData.amounts .. " in the amount file")
for i=1, #saveData.names do
    print("SaveData.amounts[" .. i .. "] original = " .. saveData.amounts[i])
    print("SaveData.amounts[" .. i .. "]  after sub= " .. saveData.amounts[i]:sub(2))
    print("totalAmount: " .. saveData.totalAmount)
    if saveData.income[i] then
        saveData.totalAmount = saveData.totalAmount + tonumber(saveData.amounts[i]:sub(2))
    else
        saveData.totalAmount = saveData.totalAmount - tonumber(saveData.amounts[i]:sub(2))
    end
end
totalAmountStr.text = saveData.totalAmount .. " " .. currencyFull
loadsave.saveTable(saveData, "payMeBackTable.json")

end
I printed out some info in the for loop to determine the problem and this is what is being printed for the first 2 print statements in the for loop:
16:03:51.452  SaveData.amounts1 original = ¥201
16:03:51.452  SaveData.amounts1  after sub=  201
It looks fine here in stackoverflow but for the the ¥ is actually not gone in my log, instead it is replaced with a weird rectangle symbol. There will be a picture of the printed text attached to this post.
Does anyone see what is going on here?

A: Don't use sub in this case as the ¥ sign is likely a multi-byte sequence (depending on the encoding), so using sub(2) you are cutting it in the middle instead of removing it.
Use gsub("[^%d%.]+","") instead to remove all non-numeric parts.

A: string.sub() works on the bytes of a string, not on its chars. There is a difference when the string contains Unicode text.
If the number is at the end of the string, extract it with
amount = tonumber(saveData.amounts[i]:match("%d+$"))

A: Lua strings are strings of bytes, not strings of characters.  ASCII characters are 1 byte long, but most other characters consume multiple bytes, so using string.sub() isn't going to work.
There are several standards for converting between bytes and characters (or code points), but by far the most common on the web is UTF-8.  If you are using Lua 5.3 or greater, you can use new built-in functions for performing UTF-8 manipulation.  For example, to take a substring of a UTF-8 string, you can do:
-- Simple version without bounds-checking.
function utf8_sub1(s, start_char_idx, end_char_idx)
  start_byte_idx = utf8.offset(s, start_char_idx)
  end_byte_idx = utf8.offset(s, end_char_idx + 1) - 1
  return string.sub(s, start_byte_idx, end_byte_idx)
end

-- More robust version with bounds-checking.
function utf8_sub2(s, start_char_idx, end_char_idx)
  start_byte_idx = utf8.offset(s, start_char_idx)
  end_byte_idx = utf8.offset(s, end_char_idx + 1)
  if start_byte_idx == nil then
    start_byte_idx = 1
  end
  if end_byte_idx == nil then
    end_byte_idx = -1
  else
    end_byte_idx = end_byte_idx - 1
  end
  return string.sub(s, start_byte_idx, end_byte_idx)
end

s = "¥201"

print(string.sub(s, 2, 4)) -- an invalid byte sequence
print(utf8_sub1(s, 2, 4)) -- "201"
print(utf8_sub2(s, 2, 4)) -- "201"
print(utf8_sub1(s, 2, 5)) -- throws an error

If you don't have Lua 5.3, you can use a UTF-8 library like this one instead to achieve the same functionality.


text:
Q: How the subject Several Complex Variables motivates to study Complex Manifolds? How the subject Several Complex Variables motivates to study Complex Manifolds/ Complex Geometry?
How one can study Several Complex variables?
Please advise me a roadmap to learn this subject


text:
Q: python: covert a file into a list of list of string a file contains informaton like below
I'd like to covert this file into list of list of string
There is a blank line between group.
pear
banana

milk
tea
coffee

and the result returns:
build_list(f):
[[pear, banana], [milk, tea, coffee]]

A: This should do it:
with open("data.txt") as f:
    res = [line.split('\n') for line in f.read().split('\n\n')]

Split the input data into groups then split each group into lines.

A: Try this:
from itertools import groupby

def build_list(name):
    with open(name, "r") as f:
        return [[i.strip() for i in group] for key, group in
                groupby(f, key=lambda k: (k.strip() == "")) if not key]

This solution will even allow for degenerate files where you have more than one empty line between groups or multiple empty lines at the end.

A: Stack_13328928.txt is your list. Please note that the last line in your input file has to be a new line, otherwise the last item is lost, but I think the code can be modified that you don't need a blank new line.
import csv
in_file = open("stack_13328928.txt")
CSV = csv.reader(in_file)
outer_ls = []
inter_ls = []
for i in CSV:
    try:
        i[0]
        inter_ls += i
    except:
        outer_ls.append(inter_ls)
        inter_ls = []

print outer_ls


text:
Q: Knockout.js reset the value of a select back to its default value when if another select is used I am working on a Data Table that is populated 1 of 3 ways.
1. Live Search
2. Select box 1 (searchCategory)
3. Select box 2 (searchTCA)
I have everything working except for one issue that I am unable to figure out.
When the user selects one of the options in either select box, I would like the other one to reset to default.
I am still learning knockout, so any help would be greatly appreciated.
Thank You-
Here is my HTML:

     <form id="requestForm" class="request-form form-horizontal">

             Search

                 <input id="searchInput" type="text" name="searchInput" class="form-control" placeholder="What are you looking for?" onfocus="this.value=''" data-bind="textInput: query, valueUpdate: 'keyup'" autocomplete="off" />

            View by Category

                <select id="searchCategory" data-bind="options: availableCategories, value: selectedCategory, optionsCaption: 'Search by Category'"></select>

            View by TCA Method

                <select id="searchTCA" data-bind="options: availableTcaMethods, value: selectedTcaMethod, optionsCaption: 'Search by TCA Method'"></select>

   </form>

Here is the JS:
 define(function (require) {
"use strict";

var $ = require("jquery"),
    ko = require("knockout"),
    komapping = require("komapping"),
    bootstrap = require("bootstrap"),
    $embedElement = $("#Architectural-Guidebook");

if ($embedElement.length) {

    function ArchitecturalGuidebookViewModel(dduration) {
        var self = this;

        self.specifications = ko.observableArray([]);
        debugger;

        self.availableCategories = ko.observable();
        self.selectedCategory = ko.observable();

        self.availableTcaMethods = ko.observable();
        self.selectedTcaMethod = ko.observable();

        self.availableCategories = ko.dependentObservable(function () {
            var types = ko.utils.arrayMap(self.specifications(), function (item) { return item.Category; });
            return ko.utils.arrayGetDistinctValues(types).sort();
        });

        self.availableTcaMethods = ko.dependentObservable(function () {
            var types = ko.utils.arrayMap(self.specifications(), function (item) { return item.TcaMethod; });
            return ko.utils.arrayGetDistinctValues(types).sort();
        });

        self.specifications($.parseJSON(window.jsonModel));

        self.query = ko.observable('What are you looking for?');

        // Search
        self.pageNumber = ko.observable(0);
        self.filterSpecifications = ko.computed(function () {
            self.pageNumber(0);
            return ko.utils.arrayFilter(self.specifications(), function (i) {
                var filterLogic =
                    (i.TcaMethod.toLowerCase().indexOf(self.query().toLowerCase()) >= 0) ||
                    (i.Title.toLowerCase().indexOf(self.query().toLowerCase()) >= 0) ||
                    (i.Category.toLowerCase().indexOf(self.query().toLowerCase()) >= 0) ||
                    (i.Application.toLowerCase().indexOf(self.query().toLowerCase()) >= 0) ||
                    (i.Category === self.selectedCategory() && self.query('What are you looking for?')) ||
                    (i.TcaMethod === self.selectedTcaMethod() && self.query('What are you looking for?'));
                return filterLogic;
            });
        });

        // Pagination
        self.nbPerPage = 8;
        self.totalPages = ko.computed(function () {
            var div = Math.floor(self.filterSpecifications().length / self.nbPerPage);
            div += self.filterSpecifications().length % self.nbPerPage > 0 ? 1 : 0;
            return div - 1;
        });

        self.paginated = ko.computed(function () {
            var first = self.pageNumber() * self.nbPerPage;
            return self.filterSpecifications().slice(first, first +
                      self.nbPerPage);
        });

        self.hasPrevious = ko.computed(function () {
            return self.pageNumber() !== 0;
        });

        self.hasNext = ko.computed(function () {
            return self.pageNumber() !== self.totalPages();
        });

        self.next = function () {
            if (self.pageNumber() < self.totalPages()) {
                self.pageNumber(self.pageNumber() + 1);
            }
        };

        self.previous = function () {
            if (self.pageNumber() !== 0) {
                self.pageNumber(self.pageNumber() - 1);
            }
        };

    };

    ko.applyBindings(new ArchitecturalGuidebookViewModel());

  }

});

A: You can subscribe to the selectedCategory and selectedTcaMethod observables and set the other dropdown's value to undefined when one of them changes.
Also, you are clearing the input's value on focus. This will only clear the input and not query observable's value. So, filterSpecifications computed property doesn't get triggered onfocus even though the input is cleared. Instead, you could use the event binding to call a function onfocus.
Here's a minimal working snippet:

var viewModel = function() {
  var self = this;

  self.selectedCategory = ko.observable();
  self.selectedTcaMethod = ko.observable();

  self.availableCategories = ko.observableArray(["Category 1"]);
  self.availableTcaMethods = ko.observableArray(["TCA 1"]);

  self.selectedCategory.subscribe(function() {
    // if condition added to avoid cyclic subscribe triggers
    if (self.selectedCategory())
      self.selectedTcaMethod(undefined);
  })
  self.selectedTcaMethod.subscribe(function() {
    // if condition added to avoid cyclic subscribe triggers
    if (self.selectedTcaMethod())
      self.selectedCategory(undefined);
  });

  self.query = ko.observable('What are you looking for?');

  self.onFocus = function() {
    // clear the input on focus
    self.query('');
  };

  self.filterSpecifications = ko.computed(() => {
    self.query() + self.selectedCategory() + self.selectedTcaMethod();
    console.log("computed");
  });
}

ko.applyBindings(new viewModel());

<input data-bind="textInput: query, valueUpdate: 'keyup', event: { focus: onFocus }" type="text" placeholder="What are you looking for?" />

<select id="searchCategory" data-bind="options: availableCategories, value: selectedCategory, optionsCaption: 'Search by Category'"></select>

<select id="searchTCA" data-bind="options: availableTcaMethods, value: selectedTcaMethod, optionsCaption: 'Search by TCA Method'"></select>


text:
Q: Binary serial port reading messes up data sometimes I have a serial port. The other program writes to the serial port in every 0.2 second. Each time, the data written to the serial port is always 83 bytes in length. The serial port can be read correctly using minicom.
I have a program that can read the serial port. Each time, the byte stream written to the serial port is:
65 66 67 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90
Most of the times the data can be received correctly. However, sometimes the data is messed up. Once the data is messed up, almost all the incoming messages are messed up.
Sometimes, I get output from my code as:
65 0 66 67 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 65 66 67
This is weird. Since apparently, there is a 0 after the first 65. Also, the last three bytes is 65 66 67, which looks like is the begging of a new message.
The code for opening and configurating the serial port is:
int serial_fd = open(device, O_RDWR | O_NOCTTY | O_NDELAY|O_NONBLOCK);
if (serial_fd < 0) {
    return -1;
}

struct termios options;
tcgetattr(serial_fd, &options);
options.c_cflag |= (CLOCAL | CREAD);
//8N1 mode
options.c_cflag &= ~CSIZE;
options.c_cflag |= CS8;
options.c_cflag &= ~CSTOPB;
options.c_cflag &=~PARENB;
options.c_cflag &= ~CRTSCTS;

options.c_lflag &= ~(ICANON|ECHO|ECHONL|ISIG|IEXTEN);
options.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP|INLCR|IGNCR|ICRNL|IXON);
options.c_oflag &= ~OPOST;
cfsetospeed(&options, B115200);
cfsetispeed(&options, B115200);
tcsetattr(serial_fd, TCSANOW, &options);
tcflush(serial_fd, TCIFLUSH);

The code for reading from the serial port and printing out the received message is:
uint8_t *buff,buff_data[100];
buff = buff_data;
int len,fs_sel;
fd_set fs_read;

int expectedLength=83;
int len_acc = 0;

while(1){
    FD_ZERO(&fs_read);
    FD_SET(serial_fd, &fs_read);
    fs_sel = select(serial_fd+1,&fs_read,NULL,NULL,NULL);
    if(fs_sel)
    {
        len = read(serial_fd, buff, expectedLength-len_acc);
        if (len<=0) continue;
        len_acc += len;
        if (len_acc < expectedLength) {
            buff += len;
            continue;
        }
        len_acc = 0;
        buff = buff_data;
        for (int i=0; i<expectedLength; i++){
            std::cout <<(int)buff[i]<<" ";
        }
        std::cout<< std::endl;
    }
}

Thanks for your help.


text:
Q: Can't add TomCat sever in Eclipse using ubuntu So I installed tomcat using this tutorial (instructions from 0:00 to 3:30): https://www.youtube.com/watch?v=xyd9EoO-1nk
Later I restarted my computer and now when I go into "eclipse -> Window -> Preferences -> Server -> Runtime Environments -> Add" I have here only "Basic" and "GlassFish" directories. Somebody have maybe idea how to make visible tomcat here?
I also installed tomcat using "sudo apt-get install tomcat7" but it also didn't help. But when I go into "localhost:8080" I see "It works! If you're seeing this page via a web browser...".

A: First part, the tomcat installation
You installed tomcat in your linux as a service. I mean your tomcat 7 is installed, start when you start your OS, and stop when you stop your OS.
You can check this by looking in /etc/init.d/, you must have a tomcat script (and you can control it by doing /etc/init.d/tomcat start|stop|restart). If you want to use this tomcat, I recommend you to

*

*stop tomcat (as root, /etc/init.d/tomcat stop),

*remove the tomcat script (as root, rm /etc/init.d/tomcat) to avoid a
tomcat start when the ubuntu boots

*Locate the tomcat instance installation. find / -name tomcat
-print will print you all the directory where files named tomcat are located. Identify the tomcat root directory, which is the root
to give to eclipse.

Else you can just remove tomcat (apt-get remove tomcat7), download a tomcat release from tomcat.apache.org and untar it where you want. I prefer this method, because the tomcat installation won't have any "root" o weird user permission, more convenient when you're developing.
Second part, the eclipse configuration:
In the "Add Runtime Environment" windows, you'd have a link Download additional server adapters. If you click it (with a working network connection), eclipse will propose you to download the tomcat adapter. Install it and you'll be capable to add a new tomcat server.
If it doesn't work, I think you may reinstall your eclipse...
Hope this helps


text:
Q: Using Python and Pandas to generate trends from indicators I'm trying to determine what kinds of corrections a market makes in response to changes.
A simple version of this using Python, Pandas and matplotlib might look like:
from pandas import *
ts = read_csv("time_series.csv")

chng = ts / ts.shift(1)
chng.name="current"
f = chng.shift(-1)
f.name="future"
frame = concat([chng, f], axis=1)
frame.groupby(frame.current.round(2)).future.mean().plot()

For example if my data set had a strong habit of correcting changes back to the original value (within 1 tick) the output of the code above might show a negative correlation.

The problem with this method is that it can only show what the response is over a fixed time frame (i.e. I can change the amount that the future data set is shifted, but it can only be one value).
What I would like to do is divide the initial values into buckets and show a trendline for how each range of initial values was received over time (1 tick later, 3 ticks later, etc).
How could I go about doing that?


text:
Q: Why would I want less Kinesis when consuming using Lambda? I'm using AWS Lambda to consume from Kinesis. My Lambda function doesn't have any requirements on max concurrency. Is there any reason for me to not have the maximum possible number of shards for my stream? I can't see that number of shards would affect cost.

A: The Amazon Kinesis pricing page shows price per shard hour. Data retention (beyond 24 hours) is also charged per shard hour.
So, yes, it will affect your cost.


text:
Q: how to download photos from remote server to iphone app? My situation is that I am making a uitableviewcontroller with uitableviewcells having a thumb nail or picture on the left, text on the right. All data is stored in a remote server. I have made a php to communicate with backend batabase and generate JSON to pass the data to iphone through http. However, I don't know how to do the same thing to photos. Please suggest me someway to do it. Thanks!

A: As Mundi said it already.
And make sure that you load them asynchronously.
There is a nice tutorial on this page:
http://www.markj.net/iphone-asynchronous-table-image/

A: I assume you are using NSURLConnection to fetch your data from the server. Do this:
Collect the photo data into an NSData object.
In the didFinishLoading method use this to create the images:
UIImage *thumbnailImage = [[UIImage alloc] initWithData:downloadedData];
// don't forget to discard the downloaded Data and release the image

The actual setup of your cells might be more complicated. The way I do it is to check in each call to cellForRowAtIndexPath: if I have cached the image, if not I pass to URL of the image to a NSURLConnection. I keep the open connections in an array and eliminated them when each download finishes or the view disappears. Let me know if you need more hints...


text:
Q: Creating Function To Generate List of Contingency tables I am trying to write a function that would generate a list of contingency tables from an imported data.frame (tibble). I could use a for loop to do so; however, because of the number of rows within the file, I would rather use the apply family.
library(dplyr)
set.seed(01142022)
df <- tibble('MLST' = sample(1000:9999, 5, replace = F),
             '2018(n)' = sample(1:25, 5, replace = T),
             '2019(n)' = sample(1:25, 5, replace = T))

df <- rbind(df, c('Total', colSums(df[, 2:3])))
df %<>%
  mutate(across(.cols = MLST, as.factor)) %>%
  mutate(across(.cols = c(`2018(n)`, `2019(n)`), as.numeric))
# Contigency Table
C1 <- matrix(
data = c(df[1,2],
         df[nrow(df), 2] - df[1,2],
         df[1,3],
         df[nrow(df), 3] - df[1,3]),
nrow = 2,
ncol = 2,
dimnames = list(c("MLST", "Non-Typed"), c("2018", "2019")))

The above code provides the reprex df of what the imported file would look like, with counts for each MLST type and a row totaling those counts. C1 is an example of how I would like each contingency table to appear for each MLST type.
Any suggestions on how to write a function that would generate a list of contingency tables for each MLST type that I could then use within one of the apply functions?

A: library(dplyr)

set.seed(01142022)

df <- tibble('MLST' = sample(1000:9999, 5, replace = F),
             '2018(n)' = sample(1:25, 5, replace = T),
             '2019(n)' = sample(1:25, 5, replace = T))

ctab <- function(x){
  matrix(
    data = c(df[x,2],
             sum(df[-x,2]),
             df[x,3],
             sum(df[-x,3])),
    nrow = 2,
    ncol = 2,
    dimnames = list(c("MLST", "Non-Typed"), c(names(df)[2], names(df)[3])))
}

lapply(1:nrow(df), ctab)
#> [[1]]
#>           2018(n) 2019(n)
#> MLST      6       10
#> Non-Typed 33      43
#>
#> [[2]]
#>           2018(n) 2019(n)
#> MLST      14      14
#> Non-Typed 25      39
#>
#> [[3]]
#>           2018(n) 2019(n)
#> MLST      12      8
#> Non-Typed 27      45
#>
#> [[4]]
#>           2018(n) 2019(n)
#> MLST      1       13
#> Non-Typed 38      40
#>
#> [[5]]
#>           2018(n) 2019(n)
#> MLST      6       8
#> Non-Typed 33      45
Created on 2022-01-14 by the reprex package (v2.0.1)

A: Here is another option using tidyverse, where you could just skip using a function and return a list of matrices. Here, I first remove the total row, then split each row into its own dataframe. Then, use purrr::map to bind the total row to all the dataframes. Then, I change the names in the first column, then make those the rownames. Then, I mutate across all columns and subtract MLST from the Non-Typed (i.e., the total). Then, return as a matrix.
library(tidyverse)

df %>%
  filter(MLST != "Total") %>%
  split(., row(.)[, 1]) %>%
  map(
    function(x)
      bind_rows(x, df %>%
                  filter(MLST == "Total")) %>%
      mutate(MLST = c("MLST", "Non-Typed")) %>%
      tibble::column_to_rownames("MLST") %>%
      mutate(across(everything(),  ~ c(first(.), diff(.)))) %>%
      as.matrix()
  )

Output
$`1`
          2018(n) 2019(n)
MLST            6      10
Non-Typed      33      43

$`2`
          2018(n) 2019(n)
MLST           14      14
Non-Typed      25      39

$`3`
          2018(n) 2019(n)
MLST           12       8
Non-Typed      27      45

$`4`
          2018(n) 2019(n)
MLST            1      13
Non-Typed      38      40

$`5`
          2018(n) 2019(n)
MLST            6       8
Non-Typed      33      45


text:
Q: Mikrotik - Upload file and change it into a script New into Mikrotik scripting, and missing something really obvious. When create a new script with
/system script add name=mail
/system script edit mail source

save the script and run it, everything is just fine.
Now, if I want to push scripts via scp I hit a roadblock. I upload the rsc files but now don't know, how to make i.e. the uploaded script.rsc to be used as the source for a new script. And my google-fu fails me. Any help appreciated here!

A: To push a file and execute commands on RouterOS/Mikrotik:
Use a Linux server:

*

*Prepare variables:
ROUTEROS_USER=$1
ROUTEROS_HOST=$2
ROUTEROS_SSH_PORT=$3
FILE=somescript.rsc

*Push a file using:
scp -P $ROUTEROS_SSH_PORT "$FILE" "$ROUTEROS_USER"@"$ROUTEROS_HOST":"$FILE"

*Execute the commnad that will run a command on RouterOS

ssh $ROUTEROS_USER@$ROUTEROS_HOST -p $ROUTEROS_SSH_PORT "/import file-name=$FILE"

command /import file-name=$FILE.rsc" may be different depends on
  your RouterOS version


text:
Q: Spring Security - Enabled basic auth for just one nested resource I have an application with following resources ,

*

*POST /car

*Create API POST /car/{someId}

*Update API GET  /car/insurace

*POST /car/insurance-note - Required Basic AUTH

Only the last API needs basic auth , the rest above urls should allow everyone regardless if a "BASIC xxxx" . header is passed or not.
I have a configuration as follows,
http
                .antMatcher("/car/insurance-note")
                .httpBasic()
                .and().authorizeRequests().antMatchers("/car/**").permitAll();

This does allow access to other URLS regardless if I pass a BASIC header or not.
However , it also allows the car/insurance note in without a BASIC header.
Then I changed the configuration to ,
http.authorizeRequests()
            .antMatchers("/car/insurance-note")
            .hasAuthority("USER")
            .and()
            .httpBasic()
            .and()
            .authorizeRequests()
            .antMatchers("/car/**")
            .permitAll();

Now , as well it looks like anytime a request has a "BASIC xxx" header the permit all does not work.
I am failing to get the logic of how this chaining works.

A: In short, what you trying to do is to protect one endpoint, and allow the others, if I understood correctly. You can do something like this:
http.authorizeRequests((requests) -> requests
    .antMatchers("/car/insurance-note").authenticated()
    .anyRequest().permitAll() // or antMatchers("/car/**").permitAll()
)
.httpBasic(Customizer.withDefaults());

A: Adding an answer in case someone is looking for a case like this,
http.antMatcher("/car/insurance-note")
                .authorizeRequests()
                .antMatchers("/").permitAll()
                .anyRequest().authenticated()
                .and().httpBasic();


text:
Q: STM32F769 Header Power Input As a new STM32 user, I would like to know if it is possible to connect unregulated voltages (6.2V to 9V) to a Power input pin on the headers as same as on the Arduino?
The board I'm using is STM32F769 Discovery Kit with the touchscreen. I would like to power it with a nonregulated battery pack, just to make it portable.

A: According to page 15 of the specifications (Assuming that's the same kit) you can use a 7-12V DC which may fit your requirement if your supply is over 7V.


text:
Q: My ubuntu software center is not loading, how can I repair this defect How can i deal with an Ubuntu software center that is not loading when I click on it?

A: Please, try to run snap-store from terminal
snap-store

What is the kernel version?
uname -r


text:
Q: Can't append column headers to dataframe when using to_dict() in pandas I have a key/value paired dict of (datetime/object) variables and am having trouble appending a header and dtypes to the data types.
I can make a dataframe with no column headers and dtype of object which is what I don't want. I'm trying to use the dtype and column parameters but am only being met with errors.
My code to create my dict:
for files_local in glob.glob(share_dr + '/**/*.csv', recursive=True):
    match = re.search(get_matches_regex, files_local)
    if match and match.group(0):
        d = datetime.datetime.strptime  # short form
        dict_of_files_local[d(match.group('fileDate'), '%Y%m%d_%H%M%S')] = files_local

My dict when looping through:
2019-02-07 09:11:39 C:\csv\myfile_20190207_091139_092739.csv
2019-02-08 03:08:11 C:\csv\myfile_20190208_030811_031734.csv

This all works, great, but when I try to add it to a dataframe using:
df = pd.DataFrame.from_dict(dict_of_files_local, orient='index', dtype=['datetime', 'object'], columns=['Timestamp', 'Filename'])

I'm getting the error:
TypeError: data type not understood

Why is this? I thought pandas was had great datetime parsing availability?
How can I solve this problem? Am still rather new to python/pandas BTW.
Thanks a lot !

A: I have managed to find a workaround, which is just by passing the dict.items() to the pd.DataFrame parameter.
My code below:
df = pd.DataFrame(dict_of_files_local.items(), columns=['Timestamp', 'Filename'])

Now outputs the following:
            Timestamp                           Filename
0 2019-02-07 09:11:39  C:\csv\myfile_20190207_091139_...
1 2019-02-08 03:08:11  C:\csv\myfile_20190208_030811_...


text:
Q: Value does not update after state change with custom hook as middleware I am trying to create a multistep form with multiple views.
I dynamically generate input fields with a object that looks like this:
const InitialFormState: FormState = [
    {
        viewId: 0,
        title: "Step 1",
        fields: [
            {name: multiStepForm.firstName, placeholder:"Förnamn", type: "text", required: true, value:""},
            {name: multiStepForm.lastName, placeholder:"Efternamn", type: "text", required: true, value:""},
            {name: multiStepForm.email, placeholder:"Email", type: "email", required: true, value: ""},
        ]
    },
    {
        viewId: 1,
        title: "Step 2",
        fields: [
            {name: multiStepForm.lastName, placeholder:"Datum", type: "date", required: true , value:""},
        ]
    }
]

This object is stored in the "root" component with a useReducer and then generate the fields using
<ViewWrapper>
    {fields.map((field: Field) => <input
            key={field.name}
            name={field.name}
            type={field.type}
            required={field.required || false}
            placeholder={field.placeholder}
            value={field.value} // Not working
            onChange={(e) => dispatch({
                    viewId: viewId,
                    type: (field.name as multiStepForm),
                    value: e.target.value
                })
            }
        />
    )}
</ViewWrapper>

However I have a custom hook which handles which object index of the object to render. (What step on the form you are on)
export const useMultiStepForm = (steps: any[]) => {
    const [currentStepIdx, setCurrentStepIdx] = useState(0); // Initialize step to step 1
    const MAX_STEP = steps.length - 1; // Max step, change to generic depending on how many views

    /* Functions wrappers that interact with state */
    const nextStep = () => (currentStepIdx < MAX_STEP) ? setCurrentStepIdx(prev => prev + 1) : currentStepIdx; // Increment step
    const prevStep = () => (currentStepIdx > 0) ? setCurrentStepIdx(prev => prev - 1) : currentStepIdx;         // Decrement step
    const goToStep = (step: number) => setCurrentStepIdx(step); // Go to specific step, If needed

    const currentView  = steps[currentStepIdx]

    return {
        currentView,
        currentStepIdx,
        nextStep,
        prevStep,
        isFirstStep: currentStepIdx === 0,
        isLastStep: currentStepIdx === MAX_STEP,
        steps
    }
}

The problem comes when trying to input any values into the generated fields. The dispatch of the useReducer is called and the new state is set of the InitialFormState and some type of rerender happens. But the value in the input does not update on the page. Is there any problem with passing state to a custom hook for handling?
full code:
export const enum multiStepForm {
    firstName = "firstName",
    lastName = "lastName",
    dateBooked = "dateBooked",
    email = "dateBooked",
}

export interface IFormState {
    [multiStepForm.firstName]: string,
    [multiStepForm.lastName]: string,
    [multiStepForm.dateBooked]: string,
    [multiStepForm.email]: string,
}

interface Field {
    name: string, // field name in formSchema, input, data to be sent to backend see example below
    type: string, // type (text, date, etc)
    required: boolean, // required or not
    placeholder: string,
    value: string, // input value to be parsed with inputType
}

interface ViewData {
    viewId: number,
    title: string,
    fields: Field[]
}

function ViewWrapper({children}: {children: ReactNode}) {
    return (

            {children}

    )
}

const useMultiStepForm = (steps: any[]) => {
    const [currentStepIdx, setCurrentStepIdx] = useState(0); // Initialize step to step 1
    const MAX_STEP = steps.length - 1; // Max step, change to generic depending on how many views

    /* Functions wrappers that interact with state */
    const nextStep = () => (currentStepIdx < MAX_STEP) ? setCurrentStepIdx(prev => prev + 1) : currentStepIdx; // Increment step
    const prevStep = () => (currentStepIdx > 0) ? setCurrentStepIdx(prev => prev - 1) : currentStepIdx;         // Decrement step
    const goToStep = (step: number) => setCurrentStepIdx(step); // Go to specific step, If needed

    const currentView  = steps[currentStepIdx]

    return {
        currentView,
        currentStepIdx,
        nextStep,
        prevStep,
        isFirstStep: currentStepIdx === 0,
        isLastStep: currentStepIdx === MAX_STEP,
        steps
    }
}

const InitialFormState: FormState = [
    {
        viewId: 0,
        title: "Step 1",
        fields: [
            {name: multiStepForm.firstName, placeholder:"Förnamn", type: "text", required: true, value:""},
            {name: multiStepForm.lastName, placeholder:"Efternamn", type: "text", required: true, value:""},
            {name: multiStepForm.email, placeholder:"Email", type: "email", required: true, value: ""},
        ]
    },
    {
        viewId: 1,
        title: "Step 2",
        fields: [
            {name: multiStepForm.lastName, placeholder:"Datum", type: "date", required: true , value:""},
        ]
    }
]

const FormReducer = (state: FormState, {viewId, type, value}:
    {viewId: number, type: multiStepForm, value: any}
) => {
    console.log("Dispatch event")
    console.log("current State: ", state, "Dispatch vals:", {viewId, type, value})

    const field = state[viewId].fields.findIndex(x => x.name === type)
    state[viewId].fields[field].value = value

    console.log("new state", state)
    return state
}

export default function Form() {
    const [viewState, dispatch] = useReducer(FormReducer, InitialFormState)

    const {
        currentView,
        currentStepIdx,
        nextStep,
        prevStep,
        isFirstStep,
        isLastStep
    } = useMultiStepForm(viewState)

    const handleSubmit = (e: FormEvent) => {
        e.preventDefault();

        nextStep();
    }

    console.log("currentView from useMultiStepForm", currentView)
    const {viewId, title, fields} = currentView
    return (
        <Fragment>
            <form onSubmit={handleSubmit}>

{title}

                <ViewWrapper>
                    {fields.map((field: Field) => <input
                            key={field.name}
                            name={field.name}
                            type={field.type}
                            required={field.required || false}
                            placeholder={field.placeholder}
                            value={field.value} // Not working
                            onChange={(e) => dispatch({
                                    viewId: viewId,
                                    type: (field.name as multiStepForm),
                                    value: e.target.value
                                })
                            }
                        />
                    )}
                </ViewWrapper>
                <button type="button" onClick={prevStep}>prev</button>
                <button>next</button>

                    View id: {viewId}

                    Current step index: {currentStepIdx}

            </form>
        </Fragment>
    )
}


text:
Q: Creating a struct during while loop skips over input I'm trying to create a struct and collect its inputs from the user with a while loop, however on the second iteration it just seems to skip past the inputs.
#include <iostream>
#include <list>

struct Student {
    std::string name;
    std::string course;
    float mark;
};

int main() {

    std::list<Student> students;

    while (students.size() < 2) {
        Student student;

        std::cout << "Student Name:" << std::endl;
        std::getline (std::cin, student.name);
        std::cout << "Course and Mark:" << std::endl;
        std::cin >> student.course >> student.mark;

        students.push_back(student);
    }

    for(auto const& student: students) {
        std::cout << student.name << std::endl;
    }

    return 0;
}

The output looks like so:
Student Name:
Ari Stackoverflow
Course and Mark:
course543 56.2
Student Name:   <---- skipped :(
Course and Mark:
Steve Jobs

As you can see, one the second iteration it skips over getting the name, not sure why.

A: The problem here is that when you press "Enter" after your second line of input, that newline is fed to std::getline(std::cin, student.name); on the next iteration. And so students[1].name would be an empty string.
To get around this, add std::cin.ignore() or std::cin.get() after reading your second line. This tells cin to ignore the newline.


text:
Q: Can std::move cause slicing when moving into l-value reference? See the following code:
#include <iostream>
#include <chrono>

class Parent
{
public:
    Parent() = default;
    virtual ~Parent() = default;
    Parent(const Parent& pr) : i{pr.i} {std::cout << "Parent copy constructor\n";}
    Parent& operator=(const Parent& pr) {std::cout << "Parent copy assignment\n"; this->i = pr.i; return *this;}
    Parent(Parent&& pr) : i{std::move(pr.i)} {std::cout << "Parent move constructor\n";}
    Parent& operator=(Parent&& pr) {std::cout << "Parent move assignment\n"; this->i = std::move(pr.i); return *this;}

    virtual void print_i_j() = 0;

    int i = 10;
};

class Child : public Parent
{
public:
    Child() = default;
    Child(const Child& cr) : Parent{cr}, j{cr.j} {std::cout << "Child copy constructor\n";}
    Child& operator=(const Child& cr) {std::cout << "Child copy assignment\n"; this->j = cr.j; return *this;}
    Child(Child&& cr) : Parent{std::move(cr)}, j{std::move(cr.j)} {std::cout << "Child move constructor\n";}
    Child& operator=(Child&& cr) {std::cout << "Child move assignment\n"; Parent::operator=(std::move(cr)); this->j = std::move(cr.j); return *this;}

    void print_i_j() {std::cout << "i = "<< i << " j = " << j << std::endl;}

    int j = 100;
};

int main(int argc, const char * argv[])
{
    Child c;
    c.i = 30;
    c.j = 300;
    c.print_i_j();

    Child c2;               // leave c2 with defaults (i=10, j=100)
    Parent& p_ref = c2;
    p_ref.print_i_j();

    c2.j = 150;
    p_ref.print_i_j();

    p_ref = std::move(c);   // (1)
    p_ref.print_i_j();      // (2)

    return 0;
}

When I run this I get:
i = 30 j = 300
i = 10 j = 100
i = 10 j = 150
Parent move assignment
i = 30 j = 150

As far as I can tell, as indicated in this output, i changes as a result of moving an instance of the derived class into a reference to the parent class, but j does not.
Is the result printed in (2) an indication that the move in (1) caused slicing? Or is some other behavior (or even undefined behavior) kicking in?

A:
Can std::move cause slicing ...

No. std::move doesn't cause slicing.
However, assignment into a base object causes slicing i.e. only the base is assigned and rest of the object is unaffected. This happens both when copy assigning as well as move assigning. Move assignment does however have an extra consideration: Not only is only the base of the left hand operand assigned (like in the case of copy), but also only the base of the right hand operand has been moved from.
Whether the base is assigned through a reference or not does not affect slicing unless the assignment operator is virtual (don't use virtual assignment operators though; they are not an easy / good solution).

Either:

*

*Make sure that derived classes can deal with assigned / moved from base sub objects (i.e. there should be no class invariants that could be violated by such assignment).

*Or make base unassignable (maybe make assignment protected).

*Or make base inaccessible (protected or private)

In any case, make sure that the static type of the left hand operand is what you expect it to be when assigning.

A: Yes, slicing occurs because the move assignment operator is selected statically (at compile time), and the left-hand side's static type is Parent&, not Child:
Child c;
Child c2;
Parent& p_ref = c2;
p_ref = std::move(c);   // (1)

To clarify, you don't "move into lvalue-reference". You move into the object, but not using the function which moves the entire object (Child::operator=) but the one which moves only the Parent part (Parent::operator=).
In particular, there is nothing special about move semantics; the same behavior would apply to any member function. The right-hand side operator's type is not relevant in this case.
class Parent
{
public:
    virtual ~Parent() = default;
    void func(); // non-virtual, like move assignment
};

class Child : public Parent
{
public:
    void func();
};

// usage:
Child c;
Parent& p_ref = c;
p_ref.func(); // calls Parent::func(), not Child::func()


text:
Q: Uncaught PDOException: SQLSTATE[42000] Good Day Guys! I want to ask help about this error I already double check the code but the error still exist.
This is the error:

Fatal error: Uncaught PDOException: SQLSTATE[42000]: Syntax error or
access violation: 1064 You have an error in your SQL syntax; check the
manual that corresponds to your MariaDB server version for the right
syntax to use near ''firstname', 'lastname',
'birthdate','gender','email','phone','street','house...' at line 1 in
D:\xampp\htdocs\DentalClinic\Dashboard\pages\databases\userPDO.php:24
Stack trace: #0
D:\xampp\htdocs\DentalClinic\Dashboard\pages\databases\userPDO.php(24):
PDOStatement->execute(Array) #1 {main} thrown in
D:\xampp\htdocs\DentalClinic\Dashboard\pages\databases\userPDO.php on
line 24

See the code
dbconnection.php
<?php
    $serverName = 'localhost';
    $userName = 'root';
    $password = '';
    $dataBase = 'noceabdentalclinic';

    try {
        $conn = new PDO('mysql:host=' . $serverName . '; dbname=' . $dataBase, $userName, $password);
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    } catch (PDOException $e) {
        echo 'Error: ' . $e->getMessage();
    }

    $pageContext = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];

?>

userPDO.php
<?php
include 'dbconnection.php';
session_start();

      if(isset($_POST["create"]))
      {
        $firstname   = $_POST['firstname'];
        $lastname    = $_POST['lastname'];
        $birthdate   = $_POST['birthdate'];
        $gender      = $_POST['gender'];
        $email       = $_POST['email'];
        $phone       = $_POST['phone'];
        $username    = $_POST['username'];
        $password    = $_POST['password'];
        $street      = $_POST['street'];
        $housenumber = $_POST['housenumber'];
        $barangay    = $_POST['barangay'];
        $city        = $_POST['city'];
        $roles       = $_POST['roles'];

        $pdoQuery = "INSERT INTO usersprofile ('firstname', 'lastname', 'birthdate','gender','email','phone','street','housenumber','barangay','city','roles') VALUES (:firstname,:lastname,:birthdate,:gender,:email,:phone,:street,:housenumber,:barangay,:city,:roles)";
        $pdoResult = $conn ->prepare($pdoQuery);
        $pdoExec = $pdoResult->execute([":firstname"=>$firstname,":lastname"=>$lastname,":birthdate"=>$birthdate,":gender"=>$gender,":email"=>$email,":phone"=>$phone,":street"=>$street,":housenumber"=>$housenumber,":barangay"=>$barangay,":city"=>$city,":roles"=>$roles]);  // This is the line 24

        if($pdoExec)
        {
            echo 'Data Inserted';
        }else{
            echo 'Data Not Inserted';
        }

      }
?>

This the the tables in the PhpMyAdmin

Thank you for the help :)

A: INSERT INTO usersprofile (firstname, lastname, birthdate,gender,email,phone,street,housenumber,barangay,city,roles)

Remove the single quotes from your statement, they are just column names.


text:
Q: Making YouTube player go fullscreen via JavaScript I'm running into a bug when making the YouTube player to go into fullscreen mode via JavaScript.
I have a button that when it's clicked, it triggers the YT.Player.playVideo() method, while at the same time asking the containing iframe to go into fullscreen as follows:
thisVid = document.getElementById("ytIframe");

if (thisVid.requestFullscreen) {
    thisVid.requestFullscreen();
}
else if (thisVid.msRequestFullscreen) {
    thisVid.msRequestFullscreen();
}
else if (thisVid.mozRequestFullScreen) {
    thisVid.mozRequestFullScreen();
}
else if (thisVid.webkitRequestFullScreen) {
    thisVid.webkitRequestFullScreen();
}

(This is using Stack Overflow answers here and here)
The iframe successfully takes up the screen, however, the YouTube player doesn't know it's in fullscreen mode because the fullscreen button in the bottom-right is still available:
When I click it, it stays in fullscreen, and it tells me "youtube.com is now fullscreen":
This is a problem because the user needs to click the button twice to be able to exit fullscreen mode. Is there a way to tell the youtube player to go fullscreen, instead of just telling its containing iframe to do so?

A: Because the YouTube player actually exists inside an iFrame, when you use the javascript fullscreen API you're full screening the iframe, not the player. So as far as it's concerned it is not full screen. The only way to get the player to go to full screen mode is for the user to click the button manually (this is a legacy requirement, as the iframe could still contain the Flash player, and Flash has security measures to prevent programmatic fullscreening). For now your only solution is a custom control bar (and even then you won't be full screening the player, but just its container ... but at least you'd have control over what the buttons do).


text:
Q: tensor dot product in keras I am new to keras, and got some problems understanding the keras.layers.Dot() layer.
I am trying to calculate a dot product of two vectors.
from keras.layers import Input, Dot
from keras.models import Model
import numpy as np

x1 = Input(shape=(4,))
x2 = Input(shape=(4,))
y1 = Dot(axes=1)([x1,x2])
model = Model(inputs=[x1, x2], outputs=y1)

a1 = np.arange(4)
a2=np.arange(4)
model.predict([a1,a2])

I expect the output to be 14=0+1^2+2^2+3^2. However, I got error message like below:
ValueError: Error when checking input: expected input_46 to have shape (4,) but got array with shape (1,)

I tried to run model.get_config(), and below is the corresponding information about the graph of the model. As you can see input_46 is x1, and input_47 is x2.
{'name': 'model_19',
 'layers': [{'name': 'input_46',
   'class_name': 'InputLayer',
   'config': {'batch_input_shape': (None, 4),
    'dtype': 'float32',
    'sparse': False,
    'name': 'input_46'},
   'inbound_nodes': []},
  {'name': 'input_47',
   'class_name': 'InputLayer',
   'config': {'batch_input_shape': (None, 4),
    'dtype': 'float32',
    'sparse': False,
    'name': 'input_47'},
   'inbound_nodes': []},
  {'name': 'dot_20',
   'class_name': 'Dot',
   'config': {'name': 'dot_20',
    'trainable': True,
    'axes': 1,
    'normalize': False},
   'inbound_nodes': [[['input_46', 0, 0, {}], ['input_47', 0, 0, {}]]]}],
 'input_layers': [['input_46', 0, 0], ['input_47', 0, 0]],
 'output_layers': [['dot_20', 0, 0]]}

Is there anything I didn't do right? Thanks!
UPDATE
The following code worked:
x1 = Input(shape=(4,))
x2 = Input(shape=(4,))
y1 = Dot(axes=1)([x1,x2])
model = Model(inputs=[x1, x2], outputs=y1)
a1 = np.arange(4).reshape(1,4)
a2=np.arange(4).reshape(1,4)
model.predict([a1,a2])

or
from keras.layers import Input, Dot
from keras.models import Model
import numpy as np

x1 = Input(shape=(4,))
x2 = Input(shape=(4,))
y1 = Dot(axes=1)([x1,x2])
model = Model(inputs=[x1, x2], outputs=y1)

a1 = np.arange(4)
a2=np.arange(4)
model.predict([[a1],[a2]])

A: Keras waits for get a batch of your inputs. like a vector of size N*4 if you have N inputs of the dimension 4. So if you want to send a single vector, it shoul dbe in the dimension of 1*4 and not 4.
So you have two choices:

*

*Change the
a1 = np.arange(4)
a2=np.arange(4)
To
a1 = np.arange(1,4)
a2=np.arange(1,4)

*or Try model.predict([[a1],[a2]]) . Should solve your issue.


text:
Q: Running a process using boost process in async mode with timeout In the following code, I am trying to implement a program that runs a shell command and get the stdio, stderr and return code. I am doing it using boost process in the async mode as advised here.
namespace bp = boost::process;
class Process {

public:
    Process(std::string & cmd, const int timeout);
    void run();

private:
    void timeout_handler();

    const std::string command;
    const int timeout;

    bool killed;
    bool stopped;

    std::string stdOut;
    std::string stdErr;
    int returnStatus;

    boost::asio::io_service ios;
    boost::process::group group;
    boost::asio::deadline_timer deadline_timer;
};

Process::Process(std::string & cmd, const int timeout):
    command(cmd),
    timeout(timeout),
    deadline_timer(ios)
{}

void Process::timeout_handler()
{
    if (stopped)
    return;

    if (deadline_timer.expires_at() <= boost::asio::deadline_timer::traits_type::now())
    {
        std::cout << "Time Up!" << std::endl;
        group.terminate();
        std::cout << "Killed the process and all its decendents" << std::endl;
        killed = true;
        stopped = true;
        deadline_timer.expires_at(boost::posix_time::pos_infin);
    }
    deadline_timer.async_wait(std::bind(&Process::timeout_handler, this));
}

void Process::run()
{

    std::future<std::string> dataOut;
    std::future<std::string> dataErr;

    bp::child c(command, bp::std_in.close(), bp::std_out > dataOut, bp::std_err > dataErr, ios, group);
    deadline_timer.expires_from_now(boost::posix_time::seconds(timeout));
    deadline_timer.async_wait(std::bind(&Process::timeout_handler, this));

    ios.run();
    c.wait();

    stdOut = dataOut.get();
    stdErr = dataErr.get();
    returnStatus = c.exit_code();
}

int main(int argc, char** argv)
{
    if(argc < 2)
    {
    std::cout << "Usage: \na.out <command>" << std::endl;
    exit(1);
    }
    std::vector<std::string> arguments(argv + 1, argv + argc);

    std::string command;
    for( const auto & tok : arguments)
    {
        command += tok + " ";
    }

    std::cout << command << std::endl;
    Process p(command, 10);
    p.run();
    return 0;
}

Now, the above code returns only after deadline_timer expires. What I want is that the child process should exit if it finishes before the timer expires or it (along with all the child processes it forks), should be terminated. Please point out the mistake in my code.

A: The mistake is indeed very simple: you should cancel the deadline timer!
io_service::run() will not return unless

*

*an exception emanated from a handler

*no more work is queued.

While the dead line timer is in progress, that means the second condition isn't met. So io_service::run() waits for it because you asked it to.
Other notes:

*

*use the error code to detect timer cancellation instead of racy time comparisons

*no need to loop-chain the timer (in fact, that's asking for bugs where the io_service never completes)

*your code failed to initialize stopped and killed

Live On Coliru
#include <boost/process.hpp>
#include <boost/process/async.hpp>
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <iostream>

namespace bp = boost::process;
class Process {

  public:
    Process(std::string &cmd, const int timeout);
    void run();

  private:
    void timeout_handler(boost::system::error_code ec);

    const std::string command;
    const int timeout;

    bool killed = false;
    bool stopped = false;

    std::string stdOut;
    std::string stdErr;
    int returnStatus = 0;

    boost::asio::io_service ios;
    boost::process::group group;
    boost::asio::deadline_timer deadline_timer;
};

Process::Process(std::string &cmd, const int timeout) : command(cmd), timeout(timeout), deadline_timer(ios) {}

void Process::timeout_handler(boost::system::error_code ec) {
    if (stopped)
        return;

    if (ec == boost::asio::error::operation_aborted)
        return;

    if (deadline_timer.expires_at() <= boost::asio::deadline_timer::traits_type::now()) {
        std::cout << "Time Up!" << std::endl;
        group.terminate(); // NOTE: anticipate errors
        std::cout << "Killed the process and all its decendants" << std::endl;
        killed = true;
        stopped = true;
        deadline_timer.expires_at(boost::posix_time::pos_infin);
    }
    //NOTE: don't make it a loop
    //deadline_timer.async_wait(boost::bind(&Process::timeout_handler, this, boost::asio::placeholders::error));
}

void Process::run() {

    std::future<std::string> dataOut;
    std::future<std::string> dataErr;

    deadline_timer.expires_from_now(boost::posix_time::seconds(timeout));
    deadline_timer.async_wait(boost::bind(&Process::timeout_handler, this, boost::asio::placeholders::error));

    bp::child c(command, bp::std_in.close(), bp::std_out > dataOut, bp::std_err > dataErr, ios, group,
            bp::on_exit([=](int e, std::error_code ec) {
                // TODO handle errors
                std::cout << "on_exit: " << ec.message() << " -> " << e << std::endl;
                deadline_timer.cancel();
                returnStatus = e;
            }));

    ios.run();

    stdOut = dataOut.get();
    stdErr = dataErr.get();

    c.wait();

    returnStatus = c.exit_code();
}

int main(int argc, char **argv) {
    if (argc < 2) {
        std::cout << "Usage: \na.out <command>" << std::endl;
        exit(1);
    }
    std::vector<std::string> arguments(argv + 1, argv + argc);

    std::string command;
    for (const auto &tok : arguments) {
        command += tok + " ";
    }

    std::cout << command << std::endl;
    Process p(command, 2);
    p.run();
}

Prints e.g.
 $ ./sotest 'echo hello'

echo hello
on_exit: Success -> 0

 $ ./sotest 'sleep 1'

sleep 1
on_exit: Success -> 0

 $ ./sotest 'sleep 3'

sleep 3
Time Up!
Killed the process and all its decendants
on_exit: Success -> 9

A: A very simple logic for how to run a process with timeout is the following.
std::string cmd = "sleep 20";
int timeout = 5;

boost::process::child c(cmd);
std::error_code ec;
if (!c.wait_for(std::chrono::seconds(timeout), ec)) {
    std::cout << "nTimeout reached. Process terminated after "
              << timeout << " seconds.\n";
      c.terminate(ec);
}


text:
Q: Escrever em um arquivo .txt com laço 'for' no Python Preciso que um arquivo .txt guarde o último serial gerado, para das próximas vezes que for executado esse arquivo ser lido e continuar a sequencia. Ou seja, se o ultimo serial(serial2) gerado for o número 6 quero que seja guardado o número 6 no txt para que na proxima execução do código ele inicie no 6. Estou usando o txt como um "Banco de Dados".
def GerarSerial(start_at=int(open('ultimaos.txt', 'r').readlines(0)[0])+1):
    serial = f'{start_at:0>5}'
    serial2 = f'{start_at+1:0>5}'
    with open('ultimaos.txt', 'w') as ultimaosarquivo:
        ultimaosarquivo.write(serial2)
    with open('ultimaos.txt', 'r') as ultimaosarquivo:
        ultima_os = ultimaosarquivo.readlines(0)[0]
    return f'{ultima_os:0>5}'

if __name__ == '__main__':
    for x in range(3):
        GerarSerial()
        print(GerarSerial())

ultimaos.txt:
00006

Porém ao executar o código ele apenas repete o valor 3 vezes.

A: O problema é que você definiu um valor default para o parâmetro start_at. E segundo a documentação, esse valor só é avaliado uma vez, quando a função é criada, e depois não muda mais:

Default parameter values are evaluated from left to right when the function definition is executed. This means that the expression is evaluated once, when the function is defined, and that the same "pre-computed" value is used for each call.

Ou seja, quando você cria a função, o start_at terá o valor default com base no conteúdo atual do arquivo, somado com 1. E para todas as chamadas feitas sem nenhum argumento, será usado o valor inicial que ele tinha. Por isso que, não importa quantas vezes você chame a função, o mesmo valor está sendo usado.
Sendo assim, retire este parâmetro. Dentro da função você tem que sempre ler o valor atual e somar 1:
def GerarSerial(arquivo='ultimaos.txt'): # acho que faz mais sentido o nome do arquivo ser um parâmetro
    try:
        # tenta ler o arquivo
        with open(arquivo, 'r') as arq:
            atual = int(arq.read()) # como o arquivo só tem uma linha, lê tudo
    except OSError:
        # se o arquivo não existe, começa um novo serial
        # mas também poderia dar erro, você decide o que faz mais sentido para o seu caso
        atual = 0

    # calcula o novo serial (no caso, soma 1 com o atual)
    serial = f'{atual + 1:0>5}'
    with open(arquivo, 'w') as arq: # atualiza o arquivo
        arq.write(serial)
    return serial

for _ in range(3):
    print(GerarSerial())

Como o arquivo sempre tem apenas uma linha, não precisa de readlines para ler todas as linhas e depois pegar a primeira. Basta usar read para ler tudo (mas também poderia ser readline() - no singular - para ler a primeira linha).
Claro que faltou verificar se o conteúdo é um número mesmo, mas a ideia geral é essa: se o arquivo não existe, começa um novo serial (mas poderia dar erro, você decide o que faz mais sentido para o seu caso), e se existe, lê o conteúdo dele.
Depois basta somar 1 e gravar o novo serial no arquivo, e retornar este serial. E veja que não precisa abrir de novo o arquivo para ler o que você acabou de gravar, pois isso já está na variável serial.


text:
Q: Windows 10 dual boots straight to Ubuntu The only way I can get back into Windows 10 is to go into the boot manager where it shows these items and choosing the second option with the first being the newly-installed Ubuntu installation:

*

*Windows Boot Manager (Intel OEMRAID0)

*Windows Boot Manager (Intel OEMRAID0)

*Linux (OEMRAID0)

The third one appeared after I tried boot repair in Ubuntu.
If I select the first one, a blank Grub Loader screen appears and then boots straight into Ubuntu 18.04.
I have 2 x 128 gb for Windows and 1 x 1 TB that has about 260 gb for Ubuntu with the rest for data and storage for Windows.
Both OSes should be installed under UEFI, but if there's a sure way to check, I'm glad to do it, and os-prober returns nothing.
This is what fdisk shows: (excluding loop devices)
Disk /dev/sda: 119.2 GiB, 128035676160 bytes, 250069680 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disklabel type: dos
Disk identifier: 0xe0d5da1e

Device     Boot Start        End    Sectors Size Id Type
/dev/sda1           1 4294967295 4294967295   2T ee GPT

Disk /dev/sdb: 119.2 GiB, 128035676160 bytes, 250069680 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes

Disk /dev/sdc: 931.5 GiB, 1000204886016 bytes, 1953525168 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disklabel type: gpt
Disk identifier: 69F57C74-1B25-417A-94DA-8FA89C8F8BF8

Device          Start        End    Sectors   Size Type
/dev/sdc1          34      32767      32734    16M Microsoft reserved
/dev/sdc2       32768 1433632767 1433600000 683.6G Microsoft basic data
/dev/sdc3  1433632768 1953523711  519890944 247.9G Linux filesystem

Disk /dev/md126: 238.5 GiB, 256066453504 bytes, 500129792 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 131072 bytes / 262144 bytes
Disklabel type: gpt
Disk identifier: 6B279885-C27E-4714-8AF9-B8CC095E89B9

Device           Start       End   Sectors   Size Type
/dev/md126p1      2048    206847    204800   100M EFI System
/dev/md126p2    206848    239615     32768    16M Microsoft reserved
/dev/md126p3    239616 498014207 497774592 237.4G Microsoft basic data
/dev/md126p4 498014208 500111359   2097152     1G Windows recovery environment


text:
Q: Coloring lines in plane We assume that all the lines in the plane are each colored with one of two colors: red or blue. Given angle $\alpha.$

My question 1. Is there possible to get two lines with the same color and angle between them is angle $\alpha?$
My question 2. Is there possible to get a regular $n$-polygon with all side have the same color?
My question 3. If question 2 is not true for all $n$ then which are $n$ for it true?

A: (1)
We have problems only when parallel lines are colored in the same color.
(If in at least one direction we have two colors, then make a choice of a line making the angle $\alpha$ with it...)
So we assume this "bad case" already happens.
We separate the cases $\alpha \not\in \Bbb Q\cdot \pi$ and
$\alpha\in \Bbb Q\cdot \pi$. The first case first. The system $\{\alpha,\pi\}$ is $\Bbb Q$-linearly independent, so we can choose a basis of $\Bbb R$ over $\Bbb Q$ extending it. Each $x\in \Bbb R$ can then be written uniquely as
$$
x = x_\alpha\cdot \alpha +x_\pi\cdot \pi+\dots
$$
as a finite sum with coefficients $x_\alpha,x_\pi,\dots\in\Bbb Q$. (Only finitely many coefficients are non zero, we omit the other terms from the above linear combination to have a finite sum.)
Now we color the possible rational numbers $x_\alpha$ in two colors, so that $r\in \Bbb Q$ and $(r+1)\in \Bbb Q$ always have a different color. For instance we can do the following. Fix $q\in\Bbb N_{>0}$, a possible denominator. Fix some colors for $0/q,\dots,(q-1)/q\in[0,1)$. Then take the opposite colors for the fractions with denominator $q$ in $[1,2)$, then pass again to the opposite color in the next interval $[2,3)$, and so on, do "the same" alternatively for $[-1,0)$, $[-2,-1)$, ... Or just simply use the same color for $r$ in the intervals $[n,n+1)$, $n\in \Bbb Z$ even, and the other color for $r$ in the other intervals.
We now color the line making the angle $x\in\Bbb R$ with $Ox$ by the color associated as above to the rational number $x_\alpha$. This does not depend on adding a (rational) multiple of $\pi$ to $x$, so the coloring is well defined. However, $x$ and $x+\alpha$ always have a different coloring, since the rational numbers
$$
x_\alpha\text{ and }
(x+\alpha)_\alpha=x_\alpha+1
$$
have a different coloring.
The remained case, $\alpha=\frac pq\cdot \pi$, where the fraction $p/q$ is irreducible, $p,q\in\Bbb Z$, $q>0$.
If $q$ is even, (so $p$ is odd,) then we color the sectors delimited by the regular polygon with $q$ sides alternatively, i.e. the lines making an angle in $\left[\ k\cdot\frac {2\pi}q\ ,\ (k+1)\cdot\frac {2\pi}q\ \right)$ in the "color" $k$ modulo $2$. Then any two lines forming the angle $\alpha$ have a different color.
Consider now the case $q$ is odd. Yes, it is finally possible to realize the coloring. Consider the list of angles w.r.t. $Ox$:
$$
0\cdot\frac {2\pi}q\ ,\
p\cdot\frac {2\pi}q\ ,\
2p\cdot\frac {2\pi}q\ ,\dots\ ,\
(q-1)p\cdot\frac {2\pi}q\ ,\
qp\cdot\frac {2\pi}q\ .
$$
We have an odd number of values, the first and the last one correspond to the same color, so there are two different consecutive values in the list colored in the same way.
$\square$
(2 and 3) We have $n\ge 3$. I suppose the "color of a side" is the color of the line determined by it. We show the answer is negative, the counterexample will give the same color for parallel lines.
Fix a line / a direction $d$.
Consider the perpendicular, $d'$.
Then $d'$ and $Ox$ are forming an angle $x\in [0,\pi)$.
We use the color red for $d$ if $x\in [0,2\pi/n)$, corresponding to "the first sector" (of the unit circle) else blue.
Start now with a regular polygon with $n$ sides, $(P)=A_1A_2A_3\dots A_n$. Without loss of generality we move it in a  parallel manner to be centered in the origin $O$.
It is clear, that at least one side mid point $A_{j,j+1}$ (of side $A_jA_{j+1}$ of $(P)$ is in the first sector $d_0Od_1$, say $A_{12}$, then $A_{23}$ outside this first sector, so $A_1A_2$ is red and $A_2A_3$ is blue.
We have constructed a counterexample coloring. At a closer look, only for $n\ge 4$. For $n=3$ we use the same coloring strategy for the direction $d$ itself, if it is in the first sector use white, else black.
$\square$


text:
Q: What is the variance of $X^2$ (without assuming normality)? If $X \sim \text{N}(0, \sigma^2)$ then it is well-known that $X^2/\sigma^2 \sim \text{ChiSq}(1)$ which gives $\mathbb{V}(X^2) = 2 \sigma^4$.  However, this variance holds only for the normal distribution with zero mean.  What is the general formula for $\mathbb{V}(X^2)$ without assuming normality or zero mean?

A: The general form of this variance depends on the first four moments of the distribution.  To facilitate our analysis, we suppose that $X$ has mean $\mu$, variance $\sigma^2$, skewness $\gamma$ and kurtosis $\kappa$.  The variance of interest exists if $\kappa < \infty$ and does not exist otherwise.  Using the relationship between the raw moments and the cumulants, you have the general expression:
$$\begin{equation} \begin{aligned}
\mathbb{V}(X^2)
&= \mathbb{E}(X^4) - \mathbb{E}(X^2)^2 \\[6pt]
&= ( \mu^4 + 6 \mu^2 \sigma^2 + 4 \mu \gamma \sigma^3 + \kappa \sigma^4 ) - ( \mu^2 + \sigma^2 )^2 \\[6pt]
&= ( \mu^4 + 6 \mu^2 \sigma^2 + 4 \mu \gamma \sigma^3 + \kappa \sigma^4 ) - ( \mu^4 + 2 \mu^2 \sigma^2 + \sigma^4 ) \\[6pt]
&= 4 \mu^2 \sigma^2 + 4 \mu \gamma \sigma^3 + (\kappa-1) \sigma^4. \\[6pt]
\end{aligned} \end{equation}$$
The special case for an unskewed mesokurtic distribution (e.g., the normal distribution) occurs when $\gamma = 0$ and $\kappa = 3$, which gives the variance $\mathbb{V}(X^2) = 4 \mu^2 \sigma^2 + 2 \sigma^4$.


text:
Q: How to show regional characters in Android I get a sites source code by Java and assign it to a string. But when i see content of that string there ara ? instead of ç,ş,İ,ğ. Hope you can help me.

A: DataInputStream.readLine is capable of reading latin1-encoded text only. The characters you want are not in latin1 so the page must have some different encoding, such as UTF-8.
Assuming the page is encoded in UTF-8 you can read it if you substitute the part where you declare and initialize the variable in with the following:
 Reader in = null;
 try {
 in = new BufferedReader(new InputStreamReader(u.getInputStream(), "UTF-8"));

If you don't know the page encoding beforehand you may be able to use the URLConnection.getContentEncoding() method to find out. This method returns the encoding declared i the HTTP header Content-Type. If the content type does not have the encoding you just have to guess.


text:
Q: How to find currently streaming file in ffmpeg stream that uses a file list I am using ffmpeg to stream to an RTMP server. I am using the option to provide ffmpeg a text file with a list of files to stream. My file looks like this:
ffconcat version 1.0
file 'stream_file1.flv'
file 'stream_file2.flv'
file 'stream_file3.flv'

It loops through these files while streaming. Is there a way to programmatically find out when ffmpeg switches between each file? Either from ffmpeg dumping some logs that I can injest, or by using python to check the state of the stream every second?

A: Add -loglevel debug to your ffmpeg command and parse the console output for lines such as:
[NULL @ 0x559e278d8a40] Opening 'stream_file2.flv' for reading


text:
Q: iPhone Facebook request Error I request @"me", but requestDidLoadWithError method show this error.
An active access token must be used to query information about the current user.
I can't resolve this problem. Any solution?
- (IBAction)loginBtn:(id)sender
{
facebook = [[Facebook alloc] initWithAppId:@"231190276934148" andDelegate:self];

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
if ([defaults objectForKey:@"FBAccessTokenKey"] && [defaults objectForKey:@"FBExpirationDateKey"]) {
    facebook.accessToken = [defaults objectForKey:@"FBAccessTokenKey"];
    facebook.expirationDate = [defaults objectForKey:@"FBExpirationDateKey"];
}

if (![facebook isSessionValid]) {
    NSArray *permissions = [[NSArray alloc] initWithObjects:
                            @"user_likes",
                            @"user_about_me",
                            nil];
    [facebook authorize:permissions];
}

[self fbDidLogin];

[facebook requestWithGraphPath:@"me" andDelegate:self];

}

A: You have done every thing correct but not in correct flow.
Just follow like this formatted code.
- (void)viewDidLoad
{
[super viewDidLoad];

permissions = [[NSArray alloc] initWithObjects:@"read_stream", @"publish_stream",@"offline_access", nil];

facebook = [[Facebook alloc] initWithAppId:kAppId andDelegate:self];

}

-(IBAction)onClickLoginWithFb:(id)sender
{
if (![facebook isSessionValid]) {
    [ facebook authorize:permissions];
}
else {
    [facebook requestWithGraphPath:@"me" andDelegate:self];
}
}

- (void)fbDidLogin {
[appDelegate showLoadingView];
[facebook requestWithGraphPath:@"me" andDelegate:self];
// Save authorization information
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:[facebook accessToken] forKey:@"FBAccessTokenKey"];
[defaults setObject:[facebook expirationDate] forKey:@"FBExpirationDateKey"];
[defaults synchronize];

}
- (void)fbDidLogout {

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[facebook invalidateSession];
[defaults removeObjectForKey:@"FBAccessTokenKey"];
[defaults removeObjectForKey:@"FBExpirationDateKey"];
[defaults synchronize];

}
- (void)request:(FBRequest *)request didReceiveResponse:(NSURLResponse *)response {
NSLog(@"received response");

}
- (void)request:(FBRequest *)request didLoad:(id)result {

if ([result isKindOfClass:[NSArray class]]) {
    result = [result objectAtIndex:0];
}

}

A: You do not have to call [self fbDidLogin];
fbDidLogin is delegate method and will be called back when login will be successful.
Then move the code [facebook requestWithGraphPath:@"me" andDelegate:self]; only after successful login.