text:
Q: Which is the fastest STL container for find? Alright as a preface I have a need to cache a relatively small subset of rarely modified data to avoid querying the database as frequently for performance reasons. This data is heavily used in a read-only sense as it is referenced often by a much larger set of data in other tables.
I've written a class which will have the ability to store basically the entirety of the two tables in question in memory while listening for commit changes in conjunction with a thread safe callback mechanism for updating the cached objects.
My current implementation has two std::vectors one for the elements of each table. The class provides both access to the entirety of each vector as well as convenience methods for searching for a specific element of table data via std::find, std::find_if, etc.
Does anyone know if using std::list, std::set, or std::map over std::vector for searching would be preferable? Most of the time that is what will be requested of these containers after populating once from the database when a new connection is made.
I'm also open to using C++0x features supported by VS2010 or Boost.

A: For searching a particular value, with std::set and std::map it takes O(log N) time, while with the other two it takes O(N) time; So, std::set or std::map are probably better. Since you have access to C++0x, you could also use std::unordered_set or std::unordered_map which take constant time on average.
For find_if, there's little difference between them, because it takes an arbitrary predicate and containers cannot optimize arbitrarily, of course.
However if you will be calling find_if frequently with a certain predicate, you can optimize yourself: use a std::map or std::set with a custom comparator or special keys and use find instead.

A: Since from your (extended) requirements you need to search on multiple fields, I would point you to Boost.MultiIndex.
This Boost library lets you build one container (with only one exemplary of each element it contains) and index it over an arbitrary number of indices. It also lets you precise which indices to use.
To determine the kind of index to use, you'll need extensive benchmarks. 500 is a relatively low number of entries, so constant factors won't play nicely. Furthermore, there can be a noticeable difference between single-thread and multi-thread usage (most hash-table implementations can collapse on MT usage because they do not use linear-rehashing, and thus a single thread ends up rehashing the table, blocking all others).
I would recommend a sorted index (skip-list like, if possible) to accomodate range requests (all names beginning by Abc ?) if the performance difference is either unnoticeable or simply does not matter.

A: A sorted vector using std::lower_bound can be just as fast as std::set if you're not updating very often; they're both O(log n). It's worth trying both to see which is better for your own situation.

A: If you only want to search for distinct values, one specific column in the table, then std::hash is fastest.
If you want to be able to search using several different predicates, you will need some kind of index structure. It can be implemented by extending your current vector based approach with several hash tables or maps, one for each field to search for, where the value is either an index into the vector, or a direct pointer to the element in the vector.
Going further, if you want to be able to search for ranges, such as all occasions having a date in July you need an ordered data structure, where you can extract a range.

A: Not an answer per se, but be sure to use a typedef to refer to the container type you do use, something like typedef std::vector< itemtype > data_table_cache; Then use your typedef type everywhere.


text:
Q: c++ vector title being a string I'm doing an university project on a library.
The class Book is used on data so I thought of creating a vector with pointers to the objects Book's. The problem is, I need to read an input file with the data and then create a Book to add to the vector<Book*> catalog.
Whenever I do so, the getline() with integers works fine, but as soon as I try to save a string data to the Book, such as Title, I get a total different string of characters instead of the desirable title, or worse, an error.
#ifndef LIBRARY_PROGRAM_BOOK_H
#define LIBRARY_PROGRAM_BOOK_H
#include <iostream>
#include <vector>
#include <string>
#include "Person.h"

class Book
{
public:
    //Book(std::string title, int id, );
    Book() {};
    ~Book(){};
    void setTitle(std::string title);
    std::string getTitle() const;
    void setBookId(int bookId);
    int getBookId() const;
    void setOwner(int owner);
    int getOwner() const;
    void setCategory(std::string category);
    std::string getCategory() const;
    void setValue(float value);
    float getValue() const;
    void setLoanFee(float loanFee);
    float getLoanFee() const;
    void setIsBorrowed(bool isBorrowed);
    bool getIsBorrowed() const;
    void setBeginOfLoan(int beginOfLoan);
    int getBeginOfLoan() const;
    void setMaximumLoanTime(int maximumLoanTime);
    int getMaximumLoanTime() const;
    void setEndOfLoan(int EndOfLoan);
    int getEndOfLoan() const;
    int getLoanTimeRemaining() const;
    void addRating(float rating);
    float getRating() const;
    void addComment(std::string comment);
    std::vector<std::string> getComments() const;
    //void addToWaitingList(Person* person);
    //bool removeFromWaitingList(Person* person);
    //void sortWaitingList();

private:
    std::string title; /**Book title*/
    int bookId; /**Book id*/
    int owner; /**Id from the book owner*/
    std::string category; /**Book category, i.e. Fiction, Drama, Police, ...*/
    float value; /**Book value*/
    float loanFee; /** Book loan fee*/
    bool isBorrowed; /** Boolean variable containing if the book is borrowed or not, true if yes, no otherwise*/
    int beginOfLoan; /**Will be set to 0 if book is not loaned in the moment */
    int maximumLoanTime; /**Max time that a book should be loaned, should be defined by the book owner*/
    int endOfLoan; /**Will be set to 0 if book is not loaned in the moment */
    std::vector<float> ratings; /**Vector containing all the ratings given by the readers*/
    std::vector<std::string> comments; /**Vector containing all the comments given by the readers*/
    //std::vector<Person*> waitingList; /**Vector containing who is waiting to read the book*/
    bool isLost; /** Boolean variable containing if the book is lost or not, true if yes, no otherwise*/
};

#endif //LIBRARY_PROGRAM_BOOK_H

This is the code where I read the file, create a Book, and add it to the catalog:
std::ifstream books_file ("../Books.txt");

// adding books to the catalog
while(!books_file.eof()) {
    Book book;
    std::getline(books_file, input);
    if(books_file.eof()) break;
    book.setTitle(input);
    std::getline(books_file, input);
    book.setBookId(std::stoi(input));
    std::getline(books_file, input);
    book.setOwner(std::stoi(input));
    catalog.push_back(&book);
}
books_file.close();

Does it have to do with the way I'm using pointers?
I tried doing vector<Book> instead of vector<Book*> and it works perfectly.
What am I not seeing right?
EDIT: error on Clion:

Process finished with exit code -1073741819 (0xC0000005)

A: while(!books_file.eof()) {
    Book book; <--------- stack allocated variable
    std::getline(books_file, input);
    if(books_file.eof()) break;
    book.setTitle(input);
    std::getline(books_file, input);
    book.setBookId(std::stoi(input));
    std::getline(books_file, input);
    book.setOwner(std::stoi(input));
    catalog.push_back(&book); <------- take address of stack allocation
} <----------- destroy stack allocation, making the address invalid

Solutions
make the vector contain books instead of pointers, if the vector is huge you will get hit by some copying/moving.
make a heap allocated copy of the book.
untested code
std::vector<std::unique_ptr<Book>> catalog.

auto book = std::make_unique<Book>(/* insert data for constructor of Book */);
catalog.emplace_back(std::move(book));

Using unique_ptr so the books gets destroyed when catalog does.

A: I think the root of your issue is that you create a Book right below the while line, take it's address when you put it in the vector, but then that Book immediately goes out of scope when you hit the } so it's destroyed and the pointer is pointing at essentially random memory. If you want to store a pointer to it you should allocate it on the heap via Book* book = new Book;. But as others have pointed out, you'd probably be better off storing the Book itself or a unique_ptr<Book> in your vector instead of raw pointers.

redpajama_set_name: RedPajamaStackExchange


text:
Q: парсинг json в интерфейс пишу парсер longpoll событий вк, столкнулся с проблемой
json: cannot unmarshal object into Go struct field LongPollEventUpdate.updates.object of type vkapi.LongPollUpdateObject

вот собственно код
package vkapi

type LongPollEvent struct {
    TS      string                `json:"ts"`
    Updates []LongPollEventUpdate `json:"updates"`
}

type LongPollEventUpdate struct {
    Type   string               `json:"type"`
    Object LongPollUpdateObject `json:"object"`
}

type LongPollUpdateObject interface {
    LongPollInterfaceDummy()
}

func (LongPollWallPostNew) LongPollInterfaceDummy() {}

type LongPollWallPostNew struct {
    ID          int    `json:"id"`
    FromID      int    `json:"from_id"`
    OwnerID     int    `json:"owner_id"`
    Date        int    `json:"date"`
    MarkedAsAds int    `json:"marked_as_ads"`
    PostType    string `json:"post_type"`
    Text        string `json:"text"`
    CanEdit     int    `json:"can_edit"`
    CreatedBy   int    `json:"created_by"`
    CanDelete   int    `json:"can_delete"`
    Comments    struct {
        Count int `json:"count"`
    } `json:"comments"`
}

почему вот json.Unmarshal не может распарсить кусок JSON в мой интерфейс?

A:
Не понятно, чего вы ожидаете?  Декодер доходит до вашего интерфейса
и что он по-вашему должен сделать?  Просканировать весь мир и найти «ту
самую» имплементацию интерфейса?  Такой магии в Go нет.  Либо
ставьте в этом месте конкретный тип, либо заворачивайте интерфейс
в обёрточный тип, который в свою очередь имплементирует интерфейс
enconding/json.Unmarshaler.


text:
Q: Should I mutate a type or create a new one If I have a Base type, which holds some Metadata and needs to be binded to a Data*. The Metadata is useless after binding happens. Should I:

*

*Mutate the type with some kind of method, and have it hold both the Metadata and bound Data*:

class Base
{
public:
    bool TryBind()
    {
        m_Data = TryBindMetadata(m_Metadata); // Function that returns a Data*

        if (!m_Data)
            return false;

        return true;
    }

private:
    Metadata m_Metadata;
    Data* m_Data{};
};

*Split it into two types, one holding the Metadata, and  the other holding the bound Data*
class Base
{
public:
    BoundBase* TryBind()
    {
        return TryBindMetadata(m_Metadata); // Function that returns a BoundBase*
    }

private:
    Metadata m_Metadata;
};

class BoundBase
{
public:
    BoundBase(Data* data) : m_Data{ data }
    {
    }

private:
    Data* m_Data;
};

Why should I choose one over the other? What are the benefits of one over the other?


text:
Q: $f$ is continuous if and only $f|x_1$ and $f|x_2 $ are continuous Exercise:
Let X and Y be topological spaces and $f: X → Y$ be  a map.
Assume that $X =X_1\bigcup X_2$, where $X_1$ and $X_2$ are two subsets of X.
Assume that $X_1$ and $X_2$ are closed/open subsets.
Show that $f$ is continuous $ \iff f|x_1$ and  $f|x_2 $ are continuous
Definition:
A map $f: X → Y$ between two topological spaces is continuous if $f^{-1}$ is open/closed in X for every open/closed set in Y.
Solution:
$ \Rightarrow$:
Assume that $f$ is continuous. Then from the definition we have that for every open V in Y is $f^{-1}(V)$ open i X.
But $f^{-1}(V) =(f^{-1}(V) \bigcap X_1)  \bigcup(f^{-1}(V) \bigcap X_2) $, so $f|x_1$ and  $f|x_2 $ are continuous because $f$ is continuous?
$\Leftarrow$:
Want to show that for every V open in Y then $f^{-1}(V)$ is open in X, which is equivalent to the continuity of $ f $.
Assume that $f|x_1$ and  $f|x_2 $ are continuous.
Let $V \subset Y$ be open.
Then $f^{-1}(V) =(f^{-1}(V) \bigcap X_1)  \bigcup(f^{-1}(V) \bigcap X_2) $ is open, since $f|x_1$ and  $f|x_2 $ are continuous. Hence $f$ is continuous.
I tried to prove the statement when $X_1$ and $X_2$ are both open, since a similar argument applies when X and Y are both closed. But I'm not completely sure that my method is right. Any help would be greatly appreciated.

A: Your proof is flawless.
You are using the fact that $$f^{-1}(V) =(f^{-1}(V) \bigcap X_1)  \bigcup(f^{-1}(U) \bigcap X_2)$$
This is OK if you have  already proved it, which I assume you did.
Also, in your last statement, you need to change $X$, $Y$ to $X_1 $, $X_2$ are both closed.

A: Rephrasing:
Assume: $X_1,X_2$ open, and $X_1 \cup X_2=X.$
$V \subset Y$, $V$ open .
$\Rightarrow:$
$f^{-1}(V)$ is open since f continuous.
Hence :
$f^{-1}(V) \cap X_i$ is open in $X_i,$ $i=1,2$,
i.e. $f_{x_i},$  $i=1,2$ is open.
$\Leftarrow:$
$f_{x_i},$ $i=1,2$ is continuous.
Then $f_{x_i}^{-1}(V) = f^{-1}(V) \cap X_i$  is open in $X_i$, $i=1,2$.
$\rightarrow:$
$f_{x_i}^{-1}(V) = X_i \cap O_i$, $i=1,2$, for some open subset  $O_i$ of $X$.
Since $X_i$, $i=1,2$ is open in $X$ :
$f^{-1}(V) \cap X_i$ is open in $X$, and
finally:
$f^{-1}(V)=$
$ (f^{-1}(V) \cap X_1) \cup (f^{-1}(V) \cap X_2)$ is open in $X$.


text:
Q: NSMenu canelTracking is not working on Mac OSx 10.5 I m using NSComboBox inside NSMenu to show a list of items. When I choose any option in NSComboBox menu should get dismissed.
To dismiss NSMenu I m using cancelTrackingWithoutAnimation for 10.6 and above and it works fine. In case of 10.5 i am using cancelTracking but it is not dismissing NSMenu.

A: I fixed the issue by using carbon API CancelMenuTracking(),
CancelMenuTracking(
  MenuRef   inRootMenu,
  Boolean   inImmediate,
  UInt32    inDismissalReason)

Used _NSGetCarbonMenu to get the menuref of NSMenu.
menuRef = _NSGetCarbonMenu(myMenu);
CancelMenuTracking(menuRef,YES,kHIMenuDismissedByCancelMenuTracking); for 10.5 and CancelMenuTracking(menuRef,YES,0); for 10.6 and above


text:
Q: Wrote alternative to jQuery Accordion, it spazzed. Why? I wrote an alternative to the jQuery Accordion, as that didn't offer multiple open section support (any idea why they opted to not include support for that? What's the history there?). I did some research on StackOverflow, as well on Google to see what other options others came up. I needed something that could be used on the fly on multiple elements.
After seeing several solutions and experimenting with them, in the end, I wrote my own version (based on Kevin's solution from http://forum.jquery.com/topic/accordion-multiple-sections-open-at-once , but heavily modified).
jsFiddle can be found here: http://jsfiddle.net/3jacu/1/
Inline Code:
$(document).ready(function(){

$.fn.togglepanels = function(){
    return this.each(function(){
        h4handler = $(this).find("h4");
        $(h4handler).prepend('
▼
');
        $(h4handler).click(function() {
            $(h4handler).toggle(
                function() {
                    barclicked = $(this);
                    $(barclicked).find(".accordionarrow").html('►');
                    $(barclicked).next().slideUp('slow');
                    window.console && console.log('Closed.');
                    return false;
                },
                function() {
                    barclicked = $(this);
                    $(barclicked).find(".accordionarrow").html('▼');
                    $(barclicked).next().slideDown('slow');
                    window.console && console.log('Open.');
                    return false;
                }
            );
        });
    });
};

$("#grouplist").togglepanels(); }

Oddly, the accordion arrow at the right side stopped working once I pasted it in jsFiddle, while it works in my local copy.
In any case, the issue is that toggling isn't working as expected, and when it does, it fires duplicate toggle events which result in it closing, opening, then ultimately closing the section and it won't open from that point on (it toggles open then closes back). That's assuming it works! At first, it won't work as it doesn't respond. I think there's a logic error somewhere I'm missing.
From what I wrote/see in the code, it searches the given handle for the corresponding tag (in this case, h4), pops the handle into a variable. It then adds the arrow to the h4 tag while applying the accordionarrow class (which floats it to the right). It then adds a click event to it, which will toggle (using jQuery's toggle function) between two functions when h4 is clicked.
I suspect the problem here is that I may be mistakenly assuming jQuery's toggle function will work fine for toggling between two functions, that I'll have to implement my own toggle code. Correct me if I'm wrong though!
I'm trying to write the code so it'll be as efficient as possible, so feedback on that also would be appreciated.
Thanks in advance for your time, assistance, and consideration!

A: You have the toggle binding (which is deprecated by the way) inside of the click binding, so a new event handler is getting attached every time you click the header.
As a random aside you should also fire events within the plugin (where you have the console lines would make sense) so that external code can react to state changes.

A: You forgot to paste the trailing characters ); to close the function call to jQuery function ready. Fixed: http://jsfiddle.net/LeZuse/3jacu/2/
UPDATE: I've just realised I did not really answer your question.
You are duplicating the .toggle functionality with binding another .click handler.
The doc about .toggle says:

Description: Bind two or more handlers to the matched elements, to be executed on alternate clicks.

Which means the click event is already built in.
NOTE: You should use local variables instead of global, so your plugin won't pollute the window object. Use the var keyword for this:
var h4handler = $(this).find("h4");

A: I believe your issue is the $(h4handler).click(function() { you have wrapped around the toggle listener. Essentially what this was doing was making so every click of the tab was adding the toggle listener, which was then also firing an event. Removing the click listener will have the behaviour you expect.


text:
Q: How to set LibreOffice to use Persian / Arabic-Indic / Hindi page numbers? I want to have my page numbers in LibreOffice Impress to be in Persian.
Which means ۰۱۲۳۴۵۶۷۸۹ instead of 0123456789.

A: tools-> options -> languages settings -> complex text layout
general options set it to hindi
and here's a screen shot of it

A: These settings work across all LibreOffice applications and documents, so you can make changes from any of the set of applications.
Changing the locale
You can set Persian as the default for all of your documents or for the current document only.
From the menu bar, Tools >> Options, then expand the Language Settings and click Languages

Change Locale to Farsi. (Note that this is independent of the setting for the user interface above.)
Change CTL to Default - Farsi. This will also automatically check Enabled for complex text layout (CTL) below. CTL handles right-to-left languages.
Check For the current document only according to your prefrence.
Changing the global numeral style
Click on Complex Text Layout on the left side of the dialog and change numerals to Hindi. (not shown in this screenshot)
Use Insert >> Page Number to show the Header/Footer dialog in order to add page numbers to your slides.
Setting numerals to Hindi in the Language Settings lets you use "Arabic" numbers without using an input method editor such as Ibus. In this context, of course, Arabic numerals are 1,2,3...
Is it possible to use Hindi numbers in the slide footer page number function without changing every number to Hindi?
Short answer: not through the GUI settings. Apart from the global number style setting, there does not appear to be any way to modify the function that inserts page numbers.
Interestingly enough, the footer lets you easily change the date to Persian. I believe the page numbers cannot be changed in a similar way because the page numbers appears to be drawn from functions to work with the printer.
The solution is to not use the built-in footer page numbering at all and instead insert your own text shape in the same area with the text set the way you want. For a small number of slides, this would not be too bad; but would not be feasible with more than a handful.
The solution to this problem is to use a LibreOffice Basic macro to insert the page numbers for you. For a short overview of LibreOffice macros and how to use them in your document, please see this answer.
Here is the macro code:
Sub AddPersianPageNumbers

    Dim Doc as Object
    Set Doc = ThisComponent

    'Get the collection of DrawingPages
    Dim DrwPages as Object
    Set DrwPages = Doc.getDrawPages()

    Dim DrwPg as Object
    Dim TxtShp as Object
    Dim TxtPoint as New com.sun.star.awt.Point

    Dim i as Long
    Dim k as Long

    Dim strNum as string
    Dim strI as string
    Dim idx as long
    Dim uni as string

    'Each slide has it's own Drawpage, so go through the collection
    For i = 0 to DrwPages.getCount() - 1

        'Get the Drawing Page and create a TextShape
        Set DrwPg = DrwPages.getByIndex(i)
        Set TxtShp = Doc.createInstance("com.sun.star.drawing.TextShape")

        'Add it to the Drawing Page (must do first)
        DrwPg.Add(TxtShp)

        TxtPoint.X = DrwPg.Width * 0.9
        TxtPoint.Y = DrwPg.Height * 0.9

        TxtShp.Position = TxtPoint
        TxtShp.TextAutoGrowWidth = true
        TxtShp.TextAutoGrowHeight = true

        'Just changing the font is not enough since it will still show as Arabic
        'You can change the locale and ComplexText props for just this para
        'but I couldn't find a way to set the para to be seen as ComplexText
        'That would have been elegant, but instead just convert
        'the page number to a string converted from the Unicode code points

        strI = Cstr(i + 1)

        for k = 1 to Len(strI)
            uni =  "&H66" & mid(strI, k, 1) 'Hindi numeral code points are ascii+660
            strNum = strNum & Chr(uni)
        next k

        TxtShp.SetString(strNum)
        strNum = ""

        TxtShp.CharFontName = "Lohit Hindi"

    Next i

End Sub

A: This can be easily done in two steps.
STEP 1: Change the Locale
Got to the menu and click: Tools > Options, then select Languages under Language Settings.
Image Showing Step One
Here change the following:

*

*Locale Setting - change this to Arabic (or whatever language you want).

*CTL - set this to Arabic as well (only if you are using a language that uses Complex Text Layout)

*Tick the 'For the current document only' check-box if you want this change just for this document that's being edited

*Click 'OK' and save the setting. At this point make sure that the font used in the page number field support the language. In my case Time New Roman font has Arabic number Characters (۰۱۲۳)

STEP 2: Select the Field Type
Now select the text in the page number field (ensure the font is right) and then from the menu select: Edit > Fields
Image Showing Step Two
In the 'Edit Fields' window that opens up, change the Format to Native Numbering (as shown above). Click 'OK' to save and close.
You're done!

A: You can do it just in simple steps.
in the menu bar find Tools, at the end of Tools pane we can find options . In the options page we have two side, at the left side we see Language Settings, by pressing its triangle we have three options and we choose fist one, Languages . Now at the right side of the page we have three different part, in second one (Default Languages for Document) we have to choose Complex text layout in its options we pick our desired language (Persian).

A: I found the solution in this Super User post, in one of the answers which start with

In libreOffice, there are a number of page number format style to
choose from, like Roman, Arabic etc., which can be accessed from
Insert>Fields>Other in the Document tab of the Fields dialogue. There
is a page in the list and there is Format section from where you can
choose the required ....

See the attached screenshot


text:
Q: Why we declare metaclass=abc.ABCMeta when use abstract class in python? When I was reading the code online, I have encountered the following cases of using abstract classes:
from abc import abstractmethod,ABCMeta
class Generator(object,metaclass=ABCMeta):
    @abstractmethod
    def generate(self):
        raise NotImplementedError("method not implemented")
generator=Generator()
generator.generate()

The following error is returned, as expected:
TypeError: Can't instantiate abstract class Generator with abstract methods generate
But if I write it like this (the only difference is in the second line)
from abc import abstractmethod,ABCMeta
class Generator(object):
    @abstractmethod
    def generate(self):
        raise NotImplementedError("method not implemented")
generator=Generator()
generator.generate()

Although there are changes in the error message,
NotImplementedError: method not implemented
When I implemented the generate method, both of the above ways of Generator were executed correctly,
class GeneticAlgorithm(Generator):
    def generate(self):
        print("ABC")
ga=GeneticAlgorithm()
ga.generate()

>>> ABC

So why do we need the statement metaclass=ABCMeta?
I know something from GeeksforGeeks that

ABCMeta metaclass provides a method called register method that can be invoked by its instance. By using this register method, any abstract base class can become an ancestor of any arbitrary concrete class.

But this still doesn't make me understand the necessity of declaring metaclass=ABCMeta, it feels like @abstractmethod modifying the method is enough.

A: You "need" the metaclass=ABCMeta to enforce the rules at instantiation time.
generator=Generator()  # Errors immediately when using ABCMeta
generator.generate()   # Only errors if and when you call generate otherwise

Imagine if the class had several abstract methods, only some of which were implemented in a child. It might work for quite a while, and only error when you got around to calling an unimplemented method. Failing eagerly before you rely on the ABC is generally a good thing, in the same way it's usually better for a function to raise an exception rather than just returning None to indicate failure; you want to know as soon as things are wrong, not get a weird error later without knowing the ultimate cause of the error.
Side-note: There's a much more succinct way to be an ABC than explicitly using the metaclass=ABCMeta syntax:
from abc import abstractmethod, ABC

class Generator(ABC):

Python almost always makes empty base classes that use the metaclass to simplify use (especially during the 2 to 3 transition period, where there was no compatible metaclass syntax that worked in both, and direct inheritance was the only thing that worked).

A: The second example,
from abc import abstractmethod,ABCMeta
class Generator(object):
    @abstractmethod
    def generate(self):
        raise NotImplementedError("method not implemented")
generator=Generator()
generator.generate()  # HERE it raises

does not use the @abstractclass decorator in any way. It only raises the NotImplemetedError exception when the generate() function is called, whereas in the first example an error is raised on the instantiation (generator=Generator()).
In order to use @abstractmethod, the class has to have metaclass ABCMeta  (or it has to inherit from such class, e.g. ABC).
By the way, there are ways to check whether a method is implemented even sooner (on class definition) using, for example __init_subclass__ or by defining a custom metaclass and modifying its __new__ method.


text:
Q: AttributeError: 'ResourceVariable' object has no attribute '_distribute_strategy' I try to implement ELMo word embedding in a Bi-LSTM model. But when I finish my code in Google Colab with tensorflow, I meet some problems.
There is an "AttributeError". I think the architecture of my model is correct, but I don't know where the problem is.
INFO:tensorflow:Saver not created because there are no variables in the graph to restore
INFO:tensorflow:Saver not created because there are no variables in the graph to restore
Model: "model_5"
__________________________________________________________________________________________________
Layer (type)                    Output Shape         Param #     Connected to
==================================================================================================
input_6 (InputLayer)            [(200, 200)]         0
__________________________________________________________________________________________________
elmo_embedding_5 (ElmoEmbedding (200, 200, 1024)     4           input_6[0][0]
__________________________________________________________________________________________________
dense_11 (Dense)                (200, 200, 1024)     1049600     elmo_embedding_5[0][0]
__________________________________________________________________________________________________
bidirectional_3 (Bidirectional) (200, 200, 256)      2623488     dense_11[0][0]
__________________________________________________________________________________________________
tf_op_layer_Tanh_6 (TensorFlowO [(200, 200, 256)]    0           bidirectional_3[0][0]
__________________________________________________________________________________________________
dense_12 (Dense)                (200, 200, 1)        257         tf_op_layer_Tanh_6[0][0]
__________________________________________________________________________________________________
tf_op_layer_MatMul_3 (TensorFlo [(200, 1, 256)]      0           dense_12[0][0]
                                                                 bidirectional_3[0][0]
__________________________________________________________________________________________________
tf_op_layer_Tanh_7 (TensorFlowO [(200, 1, 256)]      0           tf_op_layer_MatMul_3[0][0]
__________________________________________________________________________________________________
flatten_5 (Flatten)             (200, 256)           0           tf_op_layer_Tanh_7[0][0]
__________________________________________________________________________________________________
dense_13 (Dense)                (200, 1)             257         flatten_5[0][0]
==================================================================================================
Total params: 3,673,606
Trainable params: 3,673,606
Non-trainable params: 0
__________________________________________________________________________________________________
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-13-ec34ae4d734a> in <module>()
     56
     57 model = ElmoClassification()
---> 58 model.run(data.train_reviews, data.train_labels, batch_size=200, epochs=100)

12 frames
/usr/local/lib/python3.7/dist-packages/tensorflow/python/distribute/distribute_lib.py in variable_created_in_scope(self, v)
   3566
   3567   def variable_created_in_scope(self, v):
-> 3568     return v._distribute_strategy is None  # pylint: disable=protected-access
   3569
   3570   def _experimental_distribute_dataset(self, dataset, options):

AttributeError: 'ResourceVariable' object has no attribute '_distribute_strategy'


text:
Q: Connect to socket in infinate loop with python I have a ssh deamon running on my local machine. I want infinitely connect to ssh deamon and echo received data.
Here is my script.
[azatuni@noc python-tests]$ cat test.py
#!/usr/bin/python

import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
PORT = 22
DESTIP = '127.0.0.1'

while 1 == 1:
 s.connect((DESTIP, PORT))
 data = s.recv(1024)
 s.close()
 print data

But when I run script, recieves the following error. But wihout loop, everything works fine.
[azatuni@noc python-tests]$ ./test.py
SSH-2.0-OpenSSH_5.3

Traceback (most recent call last):
  File "./test.py", line 9, in <module>
    s.connect((DESTIP, PORT))
  File "<string>", line 1, in connect
  File "/usr/lib64/python2.6/socket.py", line 167, in _dummy
    raise error(EBADF, 'Bad file descriptor')
socket.error: [Errno 9] Bad file descriptor

Thanks beforehand.

A: You need to create a new socket before connecting again. This will work for your:
#!/usr/bin/python
import socket
PORT = 22
DESTIP = '127.0.0.1'
while 1 == 1:
 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
 s.connect((DESTIP, PORT))
 data = s.recv(1024)
 s.close()

 print data

Be aware that code you've posted has errors in it:
data = s.recv(102SSH-2.0-OpenSSH_5.3


text:
Q: Creating JSON Array in Azure Data Factory with multiple Copy Activities output objects Is it possible to embed the output of a copy activity in Azure Data Factory within an array that is meant to be iterated over in a subsequent ForEach?
My goal is to create an array with the output of several copy activities and then in a ForEach, access the properties of those copy activities with dot notation (Ex: item().rowsRead). Image shows code details.
Image
Specifically, I have 7 copy activities whose output JSON object (described here) would be stored in an array that I then iterate over. In the ForEach I would be checking the properties on each of the copy activities (rowsRead, rowsCopied, etc.) for validation purposes.
https://learn.microsoft.com/en-us/azure/data-factory/copy-activity-monitoring

A: I think we can embed the output of a copy activity in Azure Data Factory within an array. I've created a test to save the output of 2 Copy activities into an array. We need to concat a string type and then convert it to json type. Please see my step2.

*

*We can declare an array type variable named CopyInfo to store the output. The another array type variable named JsonArray is used to see the test result at debug mode.

*In Append variable1 activity, I use @json(concat('{"activityName":"Copy1","activityObject":',activity('Copy data1').output,'}')) to save the output of Copy data1 activity and convert it from String type to Json type.

*In Append variable2 activity, I use @json(concat('{"activityName":"Copy2","activityObject":',activity('Copy data2').output,'}')) to save the output of Copy data2 activity and convert it from String type to Json type.

*Then I assign the value of variable CopyInfo to variable JsonArray

*In the end, we can see the json array like :
"name": "JsonArray",
"value": [
    {
        "activityName": "Copy1",
        "activityObject": {
            "dataRead": 643,
            "dataWritten": 643,
            "filesRead": 1,
            "filesWritten": 1,
            ...
    },
    {
        "activityName": "Copy2",
        "activityObject": {
            "dataRead": 643,
            "dataWritten": 643,
            "filesRead": 1,
            "filesWritten": 1,
            ...
            }
    }
]


text:
Q: How can I create an application-wide 404 error page? In my ASP.Net MVC2, how do I create a wide 404 page?
Meaning every single time someone tries to enter a non-existent view/page, he's redirected to this error page of my choosing?

A: Use the standard ASP.NET error pages (activate in web.config):
<customErrors mode="On|RemoteOnly" defaultRedirect="/error/problem">
    <error statusCode="404" redirect="/error/notfound"/>
    <error statusCode="500" redirect="/error/problem"/>
</customErrors>

And/or create an error handling controller and use it with a catchall route:
ErrorController.cs:
public class ErrorController : Controller
{
    public ActionResult NotFound(string aspxerrorpath)
    {
        // probably you'd like to log the missing url. "aspxerrorpath" is automatically added to the query string when using standard ASP.NET custom errors
        // _logger.Log(aspxerrorpath);
        return View();
    }
}

global.asax:
// This route catches all urls that do not match any of the previous routes.
// So if you registered the standard routes, somthing like "/foo/bar/baz" will
// match the "{controller}/{action}/{id}" route, even if no FooController exists
routes.MapRoute(
     "Catchall",
     "{*catchall}",
     new { controller = "Error", action = "NotFound" }
);


text:
Q: ASP.NET: Core_WebApp vs. Core_WebApp (MVC) - .NET 6 I wanted to experiment a little with the new project templates in Visual Studio 2022 and noticed that there are 2 project types:

*

*ASP.NET Core Web App

*ASP.NET Core Web App (Model-View-Controller)

When I visit the official ASP.NET website from Microsoft, I saw that they are promoting the non-mvc version, which resembles a little the WebForms at least with its code-behind logic.
So what's going on here? Is Microsoft silently deprecating the usage of MVC pattern?
If we start a brand new non-blazor web project, which way should we go? Which one is more future-proof? My question is merely based on the future plans of Microsoft and not on a debate, what architectural pattern we should use.

A: I noticed that my question is already answered here:
Why is Razor Pages the recommended approach to create a Web UI in Asp.net Core?
and here:
https://learn.microsoft.com/en-us/dotnet/architecture/porting-existing-aspnet-apps/comparing-razor-pages-aspnet-mvc


text:
Q: Sending http request on node process exit I have written sample node application to handle error data such as database connection error, port conflict error, process uncaught exception. When error occurrs an http request is made to process the error. In such case when node process exist abnormally, I am able to handle exist in process.on('exit') function but I am not able to send http request, the process is exiting quickly.
Can any one suggest how to send http request and get the response on Node.js before process exit. Below is the sample code for sending http request on process exists
var http = require('http');
var errorData=null;
var sendErrorReport = function(data,callback){
    var options = {
        host : connection.host,
        path : "/api/errorReport",
        port : connection.port,
        method : 'POST',
        timeout: connection.timeInterval,
        headers:{
            'Content-Type':'application/json',
            'Content-Length': Buffer.byteLength(data)}
    }
    var request =  http.request(options,function(response){
        callback(response);
    });
    request.on('error',function(err){
        console.log("On Error");
        callback(err);
    });
    request.on('timeout', function(err){console.log("On Timeout");
        callback(err);});
    request.write(data);
    request.end();
}
process.on('uncaughtException', function ( err ) {
    errorData = err;
});
process.on('exit',function(code){
    sendErrorReport(errorData,function(err,res){
        console.log(res);
    });

})

A: In process.on('exit', [fn]) you cannot do any asynchronous action as stated in the docs. However, this is an anti-pattern also discovered in many libraries.
You need to rely on process.on('uncaughtException', [fn]) or any signal handlers like SIGTERM.

A: Hit on same problem,
according to the doc https://nodejs.org/api/process.html#process_event_exit
"Event: 'exit' Listener functions must only perform synchronous operations." make it hard to send request to other system.
A possible workaround method is to to execute another script/cmd, eg.
import exec from 'child_process'

mocha.run(failures => {
  process.on('exit', () => {
    exec.execSync(some cmd, function (error, stderr) {
      if (error) {
        throw (error);
      }
 }
}


text:
Q: Как я могу проверить не попал ли случайно текст в editText (numberDecimal)? У меня есть editText (numberDecimal) который считает числа (также в этот editText копируются значение  и если в него попадет не цифра   ) сбой гарантирован!
Как я могу  проверить не попал  ли случайно текст  в editText (numberDecimal)?
вот `что приблизительно получается `(0.1669 Max Su)

вот что я нашел if(el4.getText().toString().contains(" "))

как это работает?


text:
Q: Set layout template paths with PyQGIS Under Settings>Options>Layout>Layout Paths we can define Path(s) to search for extra print templates like shown here:

I intend to deploy an organization-wide standard path for print templates using PyQGIS in a startup-script but struggle in finding a method that does what I desire.
I cannot find something related in the QgsSettings(), but I found a method
QgsApplication.instance().layoutTemplatePaths()

returning a list of the currently defined print template paths, but no equivalent method setLayoutTemplatePaths().
How may I set these print template paths using PyQGIS?

A: The values are in the QGIS3.ini and under QGIS, in the properties > Advanced tab > core > Layout > searchPathsForTemplates.
I modify the values with the following code :
new_template_dir = "/home/me/my_custom_template_dir"
app = QgsApplication.instance()
params = QgsSettings(
    app.qgisSettingsDirPath() + "QGIS/QGIS3.ini", QSettings.IniFormat
)
params.beginGroup("/core/Layout")
# retrieve the current directories
existing_dir = params.value("searchPathsForTemplates")
# append the new one in the list
if existing_dir is None:
    existing_dir = [new_template_dir]
elif isinstance(existing_dir, str):
    if new_template_dir != existing_dir:
        existing_dir = [existing_dir, new_template_dir]
    else:
        existing_dir = [existing_dir]
elif isintance(existing_dir, list):
    if new_template_dir not in existing_dir:
        existing_dir.append(new_template_dir)

# setting the new list
params.setValue("searchPathsForTemplates", existing_dir)

The code can be improved by verifying the new_template_dir exists for example but for me, it works.


text:
Q: Creating and writing to directories in Python with leading slash stopped working after creating tar archive I have a Python 2.7 program running on Ubuntu that - among other things - creates a directory structure if the directories are not there, then writes files to these new directories.
It worked fine until yesterday after I created a tar archive with the program and its output files.
Then it suddenly stopped working. I did not edit the code itself.
It turns out Python - in this program as well as elsewhere and in this directory as well as elsewhere - will no longer create or write to directories with a path with a leading slash. This worked just fine before.
Trying to recreate it using os.makedirs('/tmp/2015-03-21') results in an OSError: File Exists - even though I have deleted the directories. The same thing happens if I execute this command from anywhere else in my directory structure trying to create directories that have never existed. Calling os.makedirs with any other path with a leading slash results in an OSError: Permission Denied.
If I remove the leading slash it all works fine.
I write files to these directories using a number of different methods. For all of them trying to write a file to one of these directories using a path with a leading slash produces no output. Again, omitting the leading slash everything works just fine.
What is going on?


text:
Q: For i.i.d. $\{X_n\}$ proving $\frac1n\max\limits_{1\leqslant k\leqslant n}|X_k|\xrightarrow{\mathrm{a.s.}}0\Leftrightarrow E(|X_1|)<+∞$
$\def\d{\mathrm{d}}$Given that $X_1, X_2, \cdots$ are i.i.d., prove that$$
\frac{1}{n} \max_{1 \leqslant k \leqslant n} |X_k| \xrightarrow{\mathrm{a.s.}} 0 \Longleftrightarrow E(|X_1|) < +\infty.
$$

My try:
Because $\varliminf\limits_{n \to \infty} \dfrac{1}{n} \max\limits_{1 \leqslant k \leqslant n} |X_k|$ and $\varlimsup\limits_{n \to \infty} \dfrac{1}{n} \max\limits_{1 \leqslant k \leqslant n} |X_k|$ are both measurable with respect to the exchangeable σ-algebra of $X_1, X_2, \cdots$, they are both almost surely constants by the Hewitt-Savage 0-1 law, i.e.$$
\varliminf_{n \to \infty} \frac{1}{n} \max_{1 \leqslant k \leqslant n} |X_k| = c_1, \quad \text{a.s.} \tag{1}\\
\varlimsup_{n \to \infty} \frac{1}{n} \max_{1 \leqslant k \leqslant n} |X_k| = c_2, \quad \text{a.s.}
$$
where $c_1, c_2 \in [0, +\infty]$. Also, if the distribution function of $|X_1|$ is $F(x)$, then the distribution function of $\dfrac{1}{n} \max\limits_{1 \leqslant k \leqslant n} |X_k|$ is$$
F_n(x) = P\left( \frac{1}{n} \max_{1 \leqslant k \leqslant n} |X_k| \leqslant x \right) = \prod_{k = 1}^n P(|x_k| \leqslant nx) = (F(nx))^n,
$$
which implies\begin{align*}
E\left( \frac{1}{n} \max_{1 \leqslant k \leqslant n} |X_k| \right) &= \int_0^{+\infty} x \,\d((F(nx))^n) = \frac{1}{n} \int_0^{+\infty} y \,\d((F(y))^n)\\
&= \frac{1}{n} \int_0^{+\infty} y·n (F(y))^{n - 1} \,\d F(y) = \int_0^{+\infty} y (F(y))^{n - 1} \,\d F(y)\\
&\leqslant \int_0^{+\infty} y \,\d F(y) = E(|X_1|).
\end{align*}
Also for any $c > 0$,$$
\sum_{k = 1}^\infty P(|X_1| \geqslant ck) < \infty \Longleftrightarrow E(|X_1|) < +\infty. \tag{2}
$$
However, I failed to connect (1) and (2) to prove the proposition.
Any ideas are appreciated. Thanks in advance.

A: Hints:

*

*Show that $$\frac{1}{n} \max_{1 \leq k \leq n} |X_k(\omega)| \to 0 \tag{3}$$ if, and only if, $$\forall \epsilon>0 \, \, \exists N \in \mathbb{N} \, \, \forall n \geq N: \quad |X_n(\omega)| \leq n \epsilon. \tag{4}$$

*Use the Borel cantelli lemma to show that $(4)$ (and hence $(3)$) holds almost surely if, and only if, $$\forall \epsilon>0: \quad \sum_{n \geq 1} \underbrace{\mathbb{P}(|X_n| \geq n \epsilon)}_{\mathbb{P}(|X_1| \geq n \epsilon)} < \infty.$$

*Combine Step 2 with $(2)$ to prove the assertion.

Remark: Step 1 is actually a purely deterministic result. For any sequence $(a_n)_{n \in \mathbb{N}} \subseteq \mathbb{R}$ of real numbers the following equivalence holds: $$\frac{a_n}n \xrightarrow[]{n \to \infty} 0 \iff \frac1n\max_{k \leq n} |a_k|  \xrightarrow[]{n \to \infty} 0.$$


text:
Q: Exclude  from ViewModel I have the following file input tag in the "Create" View:
<input type="file" id="RequestFile" name="RequestFile"/>
@Html.ValidationMessage("RequestFile")

The  ViewModel contains this corresponding property:
[Required(ErrorMessage="Please select a file")]
public HttpPostedFileBase RequestFile { get; set; }

This works fine in the "Create" View, but in the "Edit" View, I get ModelState.Isvalid as false. Using the same ViewModel I would like to exclude this field from validations because I would not want to upload the file again.
I tried simply disabling the input tag like this:
<input type="file" id="RequestFile" name="RequestFile" disabled/>

This has a disabled input control but the Validation still fired.
Also applying the BindAttribute in the Controller did not work (see this Question)
Ideally (I know it sounds unlikely), if there is a server-side solution to this, please post  your thoughts. If there is a small client-side trick, please let me know!

A: The best ways are remove the property altogether, and always access it directly from the form collection (and manually validate it) or manually remove the model state error using the property name (as @cheesemacfly has in his comment, ModelState.Remove("RequestFile")).  The latter makes it very easy to fix then.

A: You could use form.onsubmit to check to see it document.getElementById("RequestFile").value is not null/empty and cancel the submit if it is.
something like
<form onsubmit="if(!document.getElementById('RequestFile').value){alert('Please select a file.');return false;}" >
<input type="file" id="RequestFile" name="RequestFile" />
<input type="submit"/>
</form>

return false cancels the submission.
http://jsfiddle.net/Cg7HY/1/
or put it in the click event of the submit button itself
http://jsfiddle.net/Cg7HY/3/


text:
Q: Bmcweb sensors cannot be shown successfully I want to ask how to show the sensors reading in bmcweb with webui-vue.
After tracing the code and from openbmc doc, I thought webui-vue is getting the sensor reading information from redfish and seems like I have to completed file "association.json".
But I have no idea how to refer from meta-ibm's association.json file due to I don't have its machine structure.
I am wondering if someone can help me, thanks!
I have completed hwmon system, so I can see all my sensors data in /sys/class/hwmon/hwmonXXX.
And I can request the data from dbus like busctl introspect xyz.openbmc_project.Hwmon-607868621.Hwmon1 /xyz/openbmc_project/sensors/temperature/PDB_Temp.
I also registered the sensor reading data to ipmi like below.
ipmitool sensor
So, I think the reading data is on d-bus correctly.
Thanks for your help.

A: There are two solutions to put your sensor data to Redfish:

*

*phosphor-hwmon + phosphor-inventory-manager
From your service name it looks like you already use phosphor-hwmon, so to push the sensor data to Redfish you will need something like this:
https://gerrit.openbmc.org/c/openbmc/meta-amd/+/38320

*dbus-sensors + entity-manager
This is a more modern solution. For the example please look at the:
https://gerrit.openbmc.org/c/openbmc/openbmc/+/42415


text:
Q: Display Date as Local Timzone, in AWS Quicksight (i have multiple timezones in 1 dataset) I have referenced this thread in Stackoverflow
I have a dataset in Quicksight and it contains multiple timezones (Australia, India, Japan Korea).
i tested out one of the answers/solution (see below) and this works well. But this converts everything to Japan timezone.
parseDate(toString(formatDate({start_date},'MM-dd-yyyy HH:mm:ss','Asia/Tokyo')),'MM-dd-yyyy HH:mm:ss')

So I tried to incorporate ifelse into the Calculated Field option like below. But it showed error. I am also not sure where to click to understand where is the error. any one has experience with this, please advice, thanks!
ifelse(
    {country}='Japan',
        parseDate(toString(formatDate({start_date},'MM-dd-yyyy HH:mm:ss','Asia/Tokyo')),'MM-dd-yyyy HH:mm:ss'),
    {country}='Korea',
        parseDate(toString(formatDate({start_date},'MM-dd-yyyy HH:mm:ss','Asia/Seoul')),'MM-dd-yyyy HH:mm:ss'),
    {country}='Australia',
        parseDate(toString(formatDate({start_date},'MM-dd-yyyy HH:mm:ss','Australia/Melbourne')),'MM-dd-yyyy HH:mm:ss'),

    {Start_date})


text:
Q: Put Text on Image from database while editing image in Canvas I have a question and i am confused what strategy i should choose to solve this.
Here is the description.

*

*I have a gallery which is managed on user authentication.

*Next I have basically a simple form which saves quotes into database.

*Selecting an image from gallery it is opened in a canvas. I am using Adobe Creative SDK.
Here is the demonstration image.

*Next i have to select(copy) text from database to add(paste) in text field but i have no idea how to do it.

This is the task i have to do for a client. I have never seen a similar example. This is seems unique. Please provide some suggestion on doing it.

A: Adobe Creative SDK's editor will not allow you to pre-populate text on an image so it's out of the question for this task. You could probably find a way to overlay text on top of the Adobe editor, but then the issue with saving the image rears its head.
If you don't need any of the other editing tools, you could simply create a canvas with the image, overlay the text and allow the user to choose the font, position the text, apply stamps, etc...
Once they're done, wire up a save button to post the field with the contents of canvas.toDataURL('image/png') and have something server-side to save it.
It will be more work than using someone else's widget, but the client will be in control of their own destiny (and have a working product which they wouldn't have before).
Keep it simple and build from there.


text:
Q: Preventing Hidden Contents of each column When Exports from Datatables I am using JQuery Data table and having some hidden values in each column . When exporting to excel, its showing that hidden values too  each column .
is there any way to prevent this ?

A: Not sure if you mean that you have hidden columns or if you have hidden data in some of your columns? Assuming you have hidden columns:
DataTables has a built-in Excel exportOptions function to specify what data to be exported. Wherever you declare your button, just add the following to only export the visible data:
  buttons: [
    {
      extend: 'excel',
      exportOptions: {
        columns: ':visible'
      }
    }
   ]

This is an example of the same behaviour, only with the print button:
https://datatables.net/extensions/buttons/examples/print/columns.html


text:
Q: How to get Shared preferences in doInBackground method of AsyncTask I am building a data transfer app using direct Wifi. I am getting the string value of extension from Uri in the onActivityResult method and storing it in Shared preferences.
@Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

 String extension;
        Uri uri = data.getData();
 Context context =  getActivity().getApplicationContext();
        extension = "."+getMimeType(context, uri);
       SharedPreferences sharedPreferences = myContext.getSharedPreferences(myName, MODE_PRIVATE);
        SharedPreferences.Editor myEdit = sharedPreferences.edit();
        myEdit.putString("hello", extension);
        myEdit.apply();

    }

It is working fine till now as the value of extension is storing in shared preferences successfully.  Now, in the onConnectionInfoAvailable method (related to the broadcast receiver), I am calling an AsyncTask.
  @Override
    public void onConnectionInfoAvailable(final WifiP2pInfo info) {
          new FileServerAsyncTask().execute();
}

Now, I  want to get the shared preference value in doInBackground method of AsyncTask. But I am not getting the value of extension from shared preferences, although my code is working fine. Please help.
public static class FileServerAsyncTask extends AsyncTask<Void, Void, String> {

    @Override
        protected String doInBackground(Void... params) {

            try {
                 SharedPreferences sh = myContext.getSharedPreferences(myName, MODE_PRIVATE);
                    String extension = sh.getString("hello", "no");
}....

Note: myContext and myName are defined as public static variables.


text:
Q: Why narrow casting in java allowed from long to byte We can cast a larger number type, such as a long, into a smaller number type,
such as a byte. for exp:
long l = 130L;
byte b = (byte)l;

When compile, we don't get a runtime error, even when the value being narrowed is too large
for the type (in this case byte).
Ideally compiler should complain, but it works why?

A: This works because you explicitly tell the compiler to allow it. You do this by adding (byte) before your long variable.
The Java Language Specification (java 7) explains what happens when you do a so-called narrowing cast. It will just discard the most significant bits.

A:
Why narrow casting in java allowed from long to byte

Because:

*

*it can be done easily

*it can be done in an unambiguous, straightforward way

*and it is useful.

When compile, we don't get a runtime error

When you compile, the most you can get is a "compile time error". You can get "runtime error" when you run the application.
You don't get a compile time error in this case becase you explicitly stated you want it to be converted to byte. Casting to byte has a type of byte which can be assigned to a variable having a type of byte.


text:
Q: Issue involving sending mail with a WordPress theme I bought a theme on ThemeForest, it installed normally, but the contact form is having problems with the variables used.
Let me explain: the form has 3 fields (Name, Email and Message), the visitor fills out and submits, however, I get only the name and email address of the visitor, but I don't get the message that the visitor wrote.
I am in contact with the support of the theme for almost 10 days and they are not solving my problem.
I'm not a programmer, but I decided the little I know, I see clearly wrong in the formmail code (refer to fields / variables used).
See if you can help me solve:

*

*Send_mail.php : http://pastebin.com/MMjEnAy0

*Contact.php : http://pastebin.com/dd1Km2Hg
If you need any more information or file, I can post too.
Well, the file send_mail.php I'm finding a strange line 6 ( $ msg = " ). Such is not the variable that should be written with any value or different?
I'm getting emails like this below:
    Name: Test João
    Email: teste-joao@email.com
    Subject:

    Message sent from website on date  Friday, March 14th, 2014, hour: 07:42 PM.

    Message:

I'm not a programmer. If you can help me.


text:
Q: How to iframe YouTube Video with custom suggested videos at the end of the video (by the YouTuber, not automatic) How to iframe YouTube Video with custom suggested videos at the end of the video (by the YouTuber, not automatic)
just like below imageenter image description here


text:
Q: Mocking RestTemplateBuilder and RestTemplate in Spring integration test I have a REST resource that gets a RestTemplateBuilder injected to build a RestTemplate:
public MyClass(final RestTemplateBuilder restTemplateBuilder) {
    this.restTemplate = restTemplateBuilder.build();
}

I would like to test that class. I need to mock the calls the RestTemplate makes to another service:
request = restTemplate.getForEntity(uri, String.class);

I tried this in my IT:
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class MyIT {

@Autowired
private TestRestTemplate testRestTemplate;
@MockBean
private RestTemplateBuilder restTemplateBuilder;
@Mock
private RestTemplate restTemplate;

@Test
public void shouldntFail() throws IOException {

    ResponseEntity<String> responseEntity = new ResponseEntity<>(HttpStatus.NOT_FOUND);
    when(restTemplateBuilder.build()).thenReturn(restTemplate);
    when(restTemplate.getForEntity(any(URI.class), any(Class.class))).thenReturn(responseEntity);
...
ResponseEntity<String> response = testRestTemplate.postForEntity("/endpoint", request, String.class);
  ...
}
}

When I run the test, I get the following exception:
java.lang.IllegalStateException: Failed to load ApplicationContext
...
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.boot.test.web.client.TestRestTemplate': Initialization of bean failed; nested exception is java.lang.IllegalArgumentException: RestTemplate must not be null

How do I do this correctly?

A: Your problem is the order of execution. The context is created containing your MockBean before you have a chance to set it up in your @Test. The solution is to provide a RestTemplateBuilder that's already fully setup when it's inserted into the context. You can do that like this.
Add the following to your @SpringBootTest annotation. Where TestApplication is your Spring Boot application class.
classes = {TestApplication.class, MyIT.ContextConfiguration.class},

Modify your class members thus, deleting your restTemplate and restTemplateBuilder.
@Autowired
private TestRestTemplate testRestTemplate;

Add a static inner class to your MyIT class:
@Configuration
static class ContextConfiguration {
  @Bean
  public RestTemplateBuilder restTemplateBuilder() {

    RestTemplateBuilder rtb = mock(RestTemplateBuilder.class);
    RestTemplate restTemplate = mock(RestTemplate.class);

    when(rtb.build()).thenReturn(restTemplate);
    return rtb;
  }
}

In your tests, modify the RestTemplate mock to do whatever you want:
@Test
public void someTest() {

  when(testRestTemplate.getRestTemplate().getForEntity(...
}

A: I had a similar issue. My Service class had RestTemplateBuilder in constructor and RestTemplate as private field and I wanted to mock RestTemplate.
I solved using ReflectionTestUtils Spring class to change my private field RestTemplate after my Service class Bean was created.
@Mock
private RestTemplate restTemplate;

@Autowired
private MyServiceClass myServiceClass;

@BeforeEach
void setUp() {
    ReflectionTestUtils.setField(myServiceClass, "restTemplate", restTemplate);
}

A: Just use the Reflection to substitute restTemplate created by builder for mocked restTemplate.
For example:
@Mock
private RestTemplate mockRestTemplate;

@Test
public void shouldntFail() throws IOException {
    this.initRestTemplate()

    ResponseEntity<String> responseEntity = new ResponseEntity<>(HttpStatus.NOT_FOUND);
    when(mockRestTemplate.getForEntity(any(URI.class), any(Class.class))).thenReturn(responseEntity);
}

private void initRestTemplate() {
    Field field = ReflectionUtils.findField(MyClass.class, "restTemplate");
    if (ObjectUtils.isNotEmpty(field)) {
      field.setAccessible(Boolean.TRUE);
      ReflectionUtils.setField(field, *yourObjectWithRestRemplate*, mockRestTemplate);
    }
}

P.S. I used ReflectionUtils provided by Spring, you can use any you prefer.


text:
Q: Postgresql: Calculate rank by number of true OR clauses I need to order/rank the results of a PostgreSQL query by the number of OR-clauses that are true. For example, given a query like
SELECT * FROM mytable WHERE cond1 OR cond2 OR cond3 ORDER BY rank DESC

should rank results based on the number of fulfilled conditions. Also approaches that solve this issue with views/stored procedures are very welcome!

A: Repeat the conditions and add them:
SELECT * FROM mytable
WHERE fld = 'A' OR fldB = CURRENT_DATE OR fldC = 7
ORDER BY
   (fld = 'A')::int + (fldB = CURRENT_DATE)::int + (fldC = 7)::int
DESC

A: Something like this maybe:
select *
from (
    SELECT * , case when cond1 then 1 else 0 end
             + case when cond2 then 1 else 0 end
             + case when cond3 then 1 else 0 end as cond_count
    FROM mytable
    WHERE cond1
       OR cond2
       OR cond3
) t
order by cond_count desc

The ugly thing about this solution is that you have every condition twice in the statement, but I can't think of another solution right now.

A: The above query will check those conditions from the left side one by one i.e

if the cond1 is true then
      return the results order by rank.
if cond1 is false and cond2 is true then
      return the results order by rank.
if cond1 and cond2 both are false but cond3 is true
      returns the results order by rank.
if all conditions are false then no result is returned.

So in brief it doesn't check all the conditions simultaneously for OR conditions.

Thanks.


text:
Q: Why can't I configure an external difftool or mergetool for Git? I'm trying to configure an external difftool and mergetool for Git under Windows 10.
Everything keeps telling me to type out two Git commands like the ones below.
Some say to use a wrapper.sh while others say it's not necessary.
git config --global diff.tool diffmerge

(The second line looks something like this:)
git config --global difftool.diffmerge.cmd "path to sgdm.exe or some_wrapper.sh" $LOCAL $REMOTE**

This doesn't work for me. I've also tried:
git config --global difftool.diffmerge.cmd C:/Program\ Files/SourceGear/Common/DiffMerge/sgdm.exe \"$LOCAL\" \"$REMOTE\"

git config --global difftool.diffmerge.cmd C:/Program\ Files/SourceGear/Common/DiffMerge/sgdm.exe "$LOCAL" "$REMOTE"

git config --global difftool.diffmerge.cmd "C:/Program\ Files/SourceGear/Common/DiffMerge/sgdm.exe $LOCAL $REMOTE"

My config file looks like this:
[filter "lfs"]

        clean = git-lfs clean %f
        smudge = git-lfs smudge %f
        required = true
[user]

        name= John Doe
[diff]

        tool = dm
[difftool]

        prompt = true
[difftool "dm"]

        cmd = \"C:\\Program Files\\SourceGear\\Common\\DiffMerge\\sgdm.exe\" \"$LOCAL\" \"$REMOTE\" //t

What am I doing wrong?

A: Check your global .gitconfig file to make sure that the paths ended up in the correct format (with quotes around paths with spaces etc).
Here is my relevant section from my config file:
[diff]
    tool = vsdiffmerge
[difftool]
    prompt = true
[difftool "vsdiffmerge"]
    cmd = \"C:\\Program Files (x86)\\Microsoft Visual Studio 11.0\\Common7\\IDE\\vsdiffmerge.exe\" \"$LOCAL\" \"$REMOTE\" //t
    keepbackup = false
    trustexistcode = true
[merge]
    tool = vsdiffmerge
[mergetool]
    prompt = true
[mergetool "vsdiffmerge"]
    cmd = \"C:\\Program Files (x86)\\Microsoft Visual Studio 11.0\\Common7\\IDE\\vsdiffmerge.exe\" \"$REMOTE\" \"$LOCAL\" \"$BASE\" \"$MERGED\" //m
    keepbackup = false
    trustexistcode = true

A: It sounds like you might be happy with a full GUI client. I have used Sourcetree to integrate with external merge tools (on OSX). And infact, Sourcetree's in-built merge tool is great too.


text:
Q: Ops Hub Utility does not continue after one failure. It keeps stopping and refuses to continue the migration. I am currently migrating my project form On Prem to VSO. Using Ops Hub tool I was able to migrate upto a few thousand change sets. After one failure occurred, the tool just stopped and did not continue the migration further. Is there any way I can skip the failed item and ask the tool to move on?

A: Can you please describe to us the error message of the failure. Source Control data is usually linearly dependent on it's previous changesets. Owing to that behavior, if any particular changeset fails, the subsequent changeset migration is halted.
Hence, unless that failure is fixed you wont be able to move on.

A: If you switch to the TFS Integration Platform for moving source and Work Items you can do some amount of edit and continue.
If there is a failure you can:
1) perform a manual checkin and then tell the platform the checkin id that solves the issue
2) start a fresh migration from where the old one left off after you have taken some action to resolve the issue.
It really depends on the error, however I have found the TFS IP to have more flexible error/exception resolution than OpsHub.
It is however not user friendly or intuitive. That is the advantage of OpsHub for simple migrations. It's Easter...


text:
Q: spring boot custom Validator annotation not working on parameter I have created a new annotation to validate my parameters on a controller:
@Constraint(validatedBy = ValueValidator.class)
@Target( { ElementType.PARAMETER })
@Retention(RetentionPolicy.RUNTIME)
public @interface ValidValue {
    String message() default "Invalid value";
    Class<?>[] groups() default {};
    Class<? extends Payload>[] payload() default {};
}

This is my validator:
public class ValueValidator implements ConstraintValidator<ValidValue, String> {
    @Override
    public void initialize(ValidValue constraintAnnotation) {
        ConstraintValidator.super.initialize(constraintAnnotation);
    }

    @Override
    public boolean isValid(String s, ConstraintValidatorContext constraintValidatorContext) {
        if (s.contains("hello")) {
            throw new IllegalArgumentException("hello is not valid");
        }
        return true;
    }
}

And this is my controller:
@GetMapping(value = "/extraction-date", produces = MediaType.APPLICATION_JSON_VALUE)
@Operation(summary = "Find  customers by extraction date")
public ResponseEntity<List<Customer>> findAllCustomersByExtractionDate(@RequestParam @ValidValue String value)
{
    System.out.println(value);
    return null;
}

my controller is annotated with:
@RestController
@RequestMapping("api/v1/customers")
@AllArgsConstructor
@Controller
@Validated
@CrossOrigin
@Tag(name = "customer-controller", description = "Controller managing operations related to customers ")

I also have an Advice controller, which I'm intending to use to catch the thrown exception:
@ControllerAdvice()
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {
    private static final Logger LOG = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * @param ex a Throwable
     * @return a responseEntity with a descriptive message and some other information
     */
    @ExceptionHandler(Throwable.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ResponseBody
    public ErrorMessage globalExceptionHandler(Throwable ex) {
        LOG.error(ex.getMessage());
        return getErrorMessage();
    }

    /**
     * @param ex a Exception
     * @return a responseEntity with a descriptive message and some other information
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ResponseBody
    public ErrorMessage globalExceptionHandler(Exception ex) {
        LOG.error(ex.getMessage());
        return getErrorMessage();
    }

    /**
     * @param ex      an InvalidInputException
     * @return a responseEntity with a descriptive message and some other information
     */
    @ExceptionHandler({InvalidInputException.class})
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ResponseBody
    public ErrorMessage invalidInputExceptionHandler(Exception ex) {
        LOG.error(ex.getMessage());
        return getErrorMessage(ex, ErrorCode.INVALID_INPUT_ERROR);
    }

    /**
     * @param ex      an ResourceNotFoundException
     * @param request the request from the client
     * @return a responseEntity with a descriptive message and some other information
     */
    @ExceptionHandler({ResourceNotFoundException.class})
    @ResponseStatus(HttpStatus.NOT_FOUND)
    @ResponseBody
    public ErrorMessage resourceNotFoundException(Exception ex, WebRequest request) {
        LOG.error(ex.getMessage());
        return getErrorMessage(ex, ErrorCode.RESOURCE_NOT_FOUND);
    }

    /**
     * @param ex thrown exception
     * @param errorCode to be returned to the client in message
     * @return the error message with all attributes
     */
    private ErrorMessage getErrorMessage(Exception ex, ErrorCode errorCode) {
        return new ErrorMessage(
                errorCode.code,
                new Date(),
                ex.getMessage(),
                errorCode.description);
    }

    /**
     * @return the error message with all attributes
     */
    private ErrorMessage getErrorMessage() {
        return new ErrorMessage(
                ErrorCode.INTERNAL_ERROR.code,
                new Date(),
                "Error while proceeding a joinPoint, unhandled exception: see log messages for more details.",
                ErrorCode.INTERNAL_ERROR.description);
    }
}

This is what I get after calling the method from postman:

What I got on the console:
INFO |2021-11-17T08:51:48,898|88D0657C2A8042FDBD32C05E96280791| [http-nio-8080-exec-1] com.obs.dqsc.api.controller.CustomerController - Entered in CustomerController.findAllCustomersByExtractionDate(hello)
hello
INFO |2021-11-17T08:51:48,903|88D0657C2A8042FDBD32C05E96280791| [http-nio-8080-exec-1] com.obs.dqsc.api.controller.CustomerController - Exit from CustomerController.findAllCustomersByExtractionDate(..); Execution time: 2 ms;

The dependencies I have in my pom.xml:
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-configuration-processor</artifactId>
        <optional>true</optional>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-mongodb</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
        <exclusions>
            <exclusion>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-logging</artifactId>
            </exclusion>
        </exclusions>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-log4j2</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-aop</artifactId>
    </dependency>
    <dependency>
        <groupId>org.aspectj</groupId>
        <artifactId>aspectjweaver</artifactId>
    </dependency>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <optional>true</optional>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi</artifactId>
        <version>5.0.0</version>
    </dependency>
    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi-ooxml</artifactId>
        <version>5.0.0</version>
    </dependency>
    <dependency>
        <groupId>org.springdoc</groupId>
        <artifactId>springdoc-openapi-ui</artifactId>
        <version>1.5.12</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
</dependencies>

Please could anyone tell me what I am missing?

A: I was missing the start-validator to make it work, so all what I had to do is to add this dependency:
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-validation</artifactId>
</dependency>


text:
Q: CakePHP create route used only if all other routes fail I am using a PagesController (not the same that Cake has built in) and I would like to connect a new route:
Router::connect('/*', array('controller' => 'pages', 'action' => 'view'));

I really want Cake to ONLY use this route if all other (default) routes fail. However, I can't seem to get it to work with just routes. I have a hunch that I will need to use a custom CakeRoute class, but I have absolutely no idea how to get it to do what I want it to do.
Could somebody please help me with this?
[edit] Oh and it might be useful to know that I'm using CakePHP 2.2.0
[2nd edit] On request, a little more info.
My router currently looks like this:
Router::connect('/', array('controller' => 'pages', 'action' => 'index'));
CakePlugin::routes();
require CAKE . 'Config' . DS . 'routes.php';
Router::connect('/*', array('controller' => 'pages', 'action' => 'view'));

And when I go to /home/about I get "Error: HomeController could not be found."
I also tried this:
Router::connect('/', array('controller' => 'pages', 'action' => 'index'));
CakePlugin::routes();
Router::connect('/*', array('controller' => 'pages', 'action' => 'view'));
require CAKE . 'Config' . DS . 'routes.php';

But then EVERYTHING is routed to my pages controller and I don't want that. I only want that route to be used if all other routes fail.
Again, I have a hunch that this can only be done with a custom CakeRoute class, but I have no idea how exactly.

A: try to put your general route at the end but before the CakePlugin::routes(); line. Something like this:
Router::connect('/', array('controller' => 'pages', 'action' => 'index'));
//all your routes
Router::connect('/*', array('controller' => 'pages', 'action' => 'view'));

CakePlugin::routes();
require CAKE . 'Config' . DS . 'routes.php';

hope this helps
EDITED:
I have a website with the same principle.. and I used this route
Router::connect('/:slug', array('controller' => 'users', 'action' => 'view'),array('pass'=>array('slug'),'slug'=>"[a-z0-9\-]+"));

at the end (before CakePlugin::routes()) and its working fine for me.

A: I know this is an old post, but for anyone struggling with catch-all routing in Cake, here's the skinny:
When you create a catch-all route such as /* then you're allowing that definition to grab anything and everything in the URL. It's very greedy, in other words. As far as I can tell, there's no way to enable this kind of definition conditionally. This means if the URL does not match any route definition before the /* is defined, then the /* definition will pick it up. So always define catch-all routes last, which we already know, of course :-)
Now, in order to ensure that Cake continues to operate "normally" - meaning that a URL such as /posts/view/4 will route to PostsController::view($id = 4) - you actually need to explicitly define it in the routes file, before the /* definition. Yes, if you're using catch-all routes in Cake, you'll need to explicitly define every Controller::method() route ahead of it to utilize the standard Cake routing conventions.
While this may sound daunting, it's not that bad if you alphabetize all your route definitions in routes.php. Simply look at your project's /Controller directory and list them off in the same order. I also implement a comment above each controller grouping as some require more than one route definition. Here's an example extracted from one of my routes.php files:
/**
 * CaseStudiesController
 */
Router::connect('/case-studies', array('controller' => 'case_studies', 'action' => 'index'));
Router::connect('/case-studies/:action', array('controller' => 'case_studies'));
Router::connect('/case-studies/:action/*', array('controller' => 'case_studies'));
Router::connect('/case-studies/*', array('controller' => 'case_studies', 'action' => 'index'));

/**
 * PostsController
 */
Router::connect('/posts', array('controller' => 'posts', 'action' => 'index'));
Router::connect('/posts/:action', array('controller' => 'posts'));
Router::connect('/posts/:action/*', array('controller' => 'posts'));
Router::connect('/posts/*', array('controller' => 'posts', 'action' => 'index'));

Generally speaking, you'll only need 4 route definitions per Controller. Lastly, here's the bottom end of routes.php in my case:
/**
 * UrlAliasesController
 *
 * This catch-all route is very greedy and even grabs the default CakePHP /:controller/:action URL format
 * Above this line, all public controller methods must be accounted for in specific routes
 */
Router::connect('/*', array('controller' => 'url_aliases', 'action' => 'check', 'admin' => false));

/**
 * Load all plugin routes. See the CakePlugin documentation on
 * how to customize the loading of plugin routes.
 */
CakePlugin::routes();

/**
 * Load the CakePHP default routes. Only remove this if you do not want to use
 * the built-in default routes.
 */
require CAKE . 'Config' . DS . 'routes.php';


text:
Q: fasterxml serialization of an attribute I'm using fasterxml 2.9.4 per the below and trying to serialise the CurrencyAndAmount class inside a parent class as:
<ParentClass Currency="USD">100000</ParentClass>

But instead I am getting below. The documentation suggests that isAttribute is what I need by is not working for me. What am I missing? Thank you in advance for any pointers in the correct direction.
<ParentClass>100000</ParentClass>

Dependencies:
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.9.4</version>
 </dependency>
 <dependency>
    <groupId>com.fasterxml.jackson.dataformat</groupId>
    <artifactId>jackson-dataformat-xml</artifactId>
    <version>2.9.9</version>
 </dependency>

XmlMapper configuration:
mapper.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true);
mapper.enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY);
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
AnnotationIntrospector primary = new JacksonAnnotationIntrospector();
AnnotationIntrospector secondary = new JaxbAnnotationIntrospector(TypeFactory.defaultInstance());
mapper.setAnnotationIntrospector(AnnotationIntrospector.pair(primary, secondary));

POJO:
public class CurrencyAndAmount {
    @JacksonXmlText
    protected BigDecimal value;
    @JacksonXmlProperty(localName = "Currency", isAttribute = true)
    protected String currency;

    @JsonValue
    public BigDecimal getValue() {
        return value;
    }

    public void setValue(BigDecimal value) {
        this.value = value;
    }

    public String getCurrency() {
        return currency;
    }

    public void setCurrency(String value) {
        this.currency = value;
    }
}

A: You should remove JsonValue annotation and simplify your POJO to:
class CurrencyAndAmount {

    @JacksonXmlText
    protected BigDecimal value;

    @JacksonXmlProperty(localName = "Currency", isAttribute = true)
    protected String currency;

    ...
}


text:
Q: Unity Crashes On LoadAll When I try to execute the following line of code, my unity3d Crashes without further nothice.
allmeshes = Resources.LoadAll("Meshes",typeof(Mesh)) as Mesh[];

Could it be because it wants to Load too much data at once or is it something different?


text:
Q: How to set the default value to the dropdown? How to set the default value to dropdown menu?

NAME*

        <select name="i" class="dropdown multiple" ng-model="i" ng-options="obj.name as obj.name for obj in uniqueMultiSlectStrataList" style="width: 100%;">
        <option value="Retail" selected>Retail</option>
        </select>

A: assign a value ng-model="i" in controller
$scope.i = 'Retail';

it will make it selected


text:
Q: convert python sqlite db to hdf5 A Pandas DataFrame can be converted to a hdf5 file like this;
df.to_hdf('test_store.hdf','test',mode='w')
I have an sqlite db file which has to be converted to a hdf5 file and then I would read the hdf5 file through pandas using pd.read_hdf.
But first how do I convert a python sqlite db to a hdf5 file ?
EDIT:
I am aware of using the .read_sql method in pandas. But I would like to convert the db to hdf5 first.

A: This is surprisingly simple: Use pandas!
pandas supports reading data directly from a SQL database into a DataFrame. Once you've got the DataFrame, you can do with it as you wish.
Short example, taken from the docs:
import sqlite3
from pandas.io import sql
# Create your connection.
cnx = sqlite3.connect('mydbfile.sqlite')

# read the result of the SQL query into a DataFrame
data = sql.read_sql("SELECT * FROM data;", cnx)

# now you can write it into a HDF5 file
data.to_hdf('test_store.hdf','test',mode='w')

A: Have a look at this ---
http://www.tutorialspoint.com/sqlite/sqlite_limit_clause.htm
The idea would be to iterate a select * from table query and limit the results with an increasing offset. Write the results to the hdf5 data store as shown above. First count the number of entries with a select count(*) from table and then split the iteration with into a managble chunks of this. e.g if there are 4million records read 200,000 at a time and increase the offet from 0, 200000, 400000 etc...
I need to do this to a very large sqlite file. will report if it works.


text:
Q: Javascript Class Properties Can anyone tell me if the following example classes are equivalent, with respect to the class properties. One is defined within the constuctor and one outside.
Example 1
function Test(input)
{
    this.output = input ;
    Test.WELCOME = "Hello ;
}

Example 2
function Test(input)
{
    this.output = input ;
}

Test.WELCOME = "Hello ;

I have been using the second type but both seems to work.
Cheers

A: I'm pretty sure neither of those does what you really want it to do. The usual way this inside of Test is something useful will be when instantiating it using new. Setting a property on Test itself doesn't have any effect on objects created from it using x = new Test('someinput'). What you would want to do is Test.prototype.WELCOME = 'Hello' and instances of Test would have that property in their [[proto]] tree and then be able to make use of it.
function Test(input){
  this.output = input;
}
Test.prototype.WELCOME = 'Hello';

var instanceOfTest = new Test('whatever');

// produces this structure:
instanceOfTest => {
  output: 'whatever',
  __proto__: {
    WELCOME: 'Hello'
  }
}

console.log(instanceOfTest.WELCOME); // 'Hello'

A: Assuming you mean:
function Test(input)
{
  this.output = input;
  Test.WELCOME = "Hello";
}

Example 2
function Test(input)
{
  this.output = input ;
}
Test.WELCOME = "Hello";

Then there will be no difference in terms of the properties of any new Test objects, however in Example 1 you will be assigning a WELCOME property to the Test function on each call to the method, whereas in Example 2 you will only assign this property once.


text:
Q: Django redirect user to app based on permission and group Say i have a django project which have 4 apps 1 app is for logging in
project urls:
from django.conf.urls import url, include
from django.contrib import admin
from django.conf import settings

urlpatterns = [
    url(r'^', include('Login.urls')),
    url(r'^admin/', admin.site.urls),
]

settings:
LOGIN_REDIRECT_URL = '/'

login app urls:
from django.conf.urls import url
from django.contrib.auth import views as auth_views

urlpatterns = [
    url(r'^login/$', auth_views.login, name='login'),
    url(r'^logout/$', auth_views.logout, {'next_page': '/'}, name='logout'),
]

now say i have 3 apps based on user type i.e. Admin, Team Lead, Worker
so i want to redirect user based on their type of employment.
how can i achieve this ?
any help is appreciated

A: I guess that you will manually add/edit the user groups.
That can be done from django admin panel.
Here is the group/permission django docs: Permissions and Authorization
This is what I did:
I've created an index view in order to get the user group and redirect to the respective view that you want.
So, index view in views.py:
from django.contrib.auth.decorators import login_required

@login_required
def index(request):
    group = request.user.groups.filter(user=request.user)[0]
    if group.name=="employees":
        return HttpResponseRedirect(reverse('worker'))
    elif group.name=="teamLeader":
        return HttpResponseRedirect(reverse('teamLeader'))
    elif group.name=="admin":
        return HttpResponseRedirect(reverse('adm'))

    context = {}
    template = "index.html"
    return render(request, template, context)

And urls in urls.py:
from django.conf.urls import url
from django.contrib import admin
from django.contrib.auth import views as auth_views
from app import views as app_views
urlpatterns = [
    url(r'^login/$', auth_views.login, name='login'),
    url(r'^$', app_views.index, name='index'),
    url(r'^employees/$', app_views.employees, name='employees'),
    url(r'^teamLeader/$', app_views.teamLeader, name='teamLeader'),
    url(r'^adm/$', app_views.adm, name='adm'),
]

In settings.py
LOGIN_URL = '/login'
LOGIN_REDIRECT_URL = '/'

Is this what you want to do?


text:
Q: Exist-db: extracting name from _eXist_xmldb_user string This question was asked a long time ago by @lovemeansnothing. It was answered with the function: xmldb:get-current-user(). However, that function is no longer defined in the namespace and has been removed from exist-db documentation. The statements in the original question remain, so I have quoted it verbatim:
"I need to get the username of the current session as a string
this:
session:get-attribute('_eXist_xmldb_user')
returns this:
< account name="foobar" id="11" >< group name="dba" id="1048575" >< manager name="admin"/ >< /group>< /account >
But I only want the username that, in this example, is:
foobar
Is there any way to do that?"
Any help gratefully received
Ralph

A: Try
xquery version "3.1";

import module namespace sm = "http://exist-db.org/xquery/securitymanager";

sm:id()//sm:real/sm:username/text()


text:
Q: Powershell: Azure Web App - Set httpsOnly on I'm automating the deployment of an Azure Web App via powershell.  I can't figure out how you force "HTTPS Only" to on.  The code below is my best guess, but it isn't working.  Any ideas?
$properties = @{"httpsOnly" = $true}
Set-AzureRmResource -PropertyObject $properties -ResourceGroupName
$resourcegroupname  -ResourceType Microsoft.Web/sites/config -ResourceName
$webappname/web -ApiVersion 2015-08-01 -Force

A: You could use the following script.
$app=Get-AzureRmResource -ResourceId "/subscriptions/<subscription id>/resourceGroups/shuiapp/providers/Microsoft.Web/sites/shuicli"
$app.Properties.httpsOnly=$true
$app|Set-AzureRmResource -Force

Note: If you want to set httpsOnly on, the web app's App Service plan must be a paid tier (Shared, Basic, Standard, or Premium). More information about this please check this link.
I also test in Visual Studio, it also works for me.

I suggest you could upgrade your Azure Power Shell version.


text:
Q: i'm new to scala. can somebody tell me why i'm getting a error illicit start of simple function when writing the def recur function def fact(n: Int) = products(x => x)(1,n)

fact(5)

def mapReduce(f: Int => Int, combine: (Int, Int) => Int, zero: Int)(a:Int,b:Int): Int =
    def recur(a: Int): Int =
        if(a>b) zero
        else combine(f(a),recur(a+1))
    recur(a)

def sum(f: Int => Int) = mapReduce(f, (x, y) => x+y, 0)
def products(f: Int => Int) = mapReduce(f, (x, y) => x*y, 1)
sum(fact)(1,5)
products(fact)(1,5)

A: def mapReduce(f: Int => Int, combine: (Int, Int) => Int, zero: Int)(a:Int,b:Int): Int = {
  def recur(a: Int): Int =
    if (a > b) zero
    else combine(f(a), recur(a + 1))

  recur(a)
}

def sum(f: Int => Int): (Int, Int) => Int = mapReduce(f, (x, y) => x+y, 0)
def products(f: Int => Int): (Int, Int) => Int = mapReduce(f, (x, y) => x*y, 1)
def fact(n: Int) = products(x => x)(1,n)

fact(5)
sum(fact)(1,5)
products(fact)(1,5)

I tried it using scala 2.13 on a scala worksheet, here curly brackets are needed for mapReduce as it contains two expressions one is a function definition and another a function invocation. Secondly when methods that returns functions such as sum and products the return type need to be specified. But I wasn't able to reproduce the error that you mentioned.


text:
Q: Cannot find the AddObject method in EF6 for inserting records I have not used the entity framework for a while and now I have to do it again with EF6. For queries, everything seems to be working just like in the past. I define a context as
var ctx = new DBContext();

and, from then on ctx. and IntelliSense will show me the available methods, tables and such. However, for insertion, I used to type
ctx.AddToMyTable();

but it seems to be deprecated. I read that you're supposed to use ctx.MyTable.AddObject(), but I don't have it either. I can only find Add and AddRange. Did I do something wrong with the mapping? Is there anything I'm missing? Just for your info, I am using EF6 and my database is MySql and I already had plenty of trouble for mapping the database model (buy I made it). Another piece of information that may be important for your analysis: I'm developing with Visual Studio Community 2013.
Can someone please tell me how I can insert the records?
Thanks very much in advance.

A: Using Add or AddRange will work.
Add will attach one object, AddRange will attach multiple objects in one go.
More info here


text:
Q: Stax parser ignore encoding I am parsing a XML file with Stax parser which has encoding mentioned as encoding="UTF-16",
But the actual content of this XML file is not UTF-16. How can i tell the Stax parser to ignore the encoding mentioned in the file and do auto detect based on the content

A: Depending on what method of StAX-Parsing you use (XMLStreamReader vs. XMLEventReader), you can pass the encoding to the create-Method of the XMLInputFactory.

*

*createXMLStreamReader(InputStream stream, String encoding)

*createXMLEventReader(InputStream stream, String encoding)

If none specified, some StAX implementations try to "guess" the actual encoding (Weblogic's StAX-Implementation, for instance, tries to do that), whereas others would use the JVM's Default-Encoding (System-Property file.encoding; careful: has to be set at startup already, no change at runtime).
If you want/have to figure out the encoding on your own, you would have to implement this on your own. I had to do this once and - based on the requirements, specifications and environment I had back then - ended up with a little and not really very nice trial-and-error approach where I had to try all the encodings I supported in my system. One after the other until I had a "good enough match". I also had to be very careful about BOMs (Byte Order Marks).
In general I believe that the XML-Prologue should hold the correct encoding, because whatever's done in the code can only be a best-guess (however, this guess can also be right).
And as a personal note, that might be terribly wrong but works well for me: Since XML mainly is Input Data, I strongly believe in GIGO.

A: You can try something like this :
byte[] byteArray = null;
        try {
            if (something)) {
                byteArray = sourceXMLString.getBytes(Constants.ENCODING_UTF_16);
            } else {
                byteArray = sourceXMLString.getBytes(Constants.ENCODING_ISO_8859_1);
            }
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        }
        ByteArrayInputStream inputStream = new ByteArrayInputStream(byteArray);
        XMLInputFactory inputFactory = XMLInputFactory.newInstance();

        try {
            xmlEventReaderSource = inputFactory.createXMLEventReader(inputStream);

        } catch (XMLStreamException e) {
            logger.error("ERROR is StAX reader initialization" + e.getLocalizedMessage());

        }


text:
Q: Turning on and off background tasks in Angular I'm currently developing an Ionic / Cordova app, and I've a little question about Angular. I've got some states, and I go from a state to an other using $state.go. Each state got his controller, and it's working great.
Now I'm trying to add a GPS tracker (the app is for an orientation game, it allows the game master to follow players) but I don't know how to do it. I need to create a module / service / function / whatever which can be launch from anywhere in any controller, and can be stop using the same way.
I'd like to start this "thread", containing a setInterval function that's refreshing the position, and continue to navigate between states and controllers. But I need to stop it at the end of the game, so I need a way to shut it down.
Can you please help me to do that ?
Thanks a lot !

A: You can use web workers to achieve it if you want the process to run on its own thread. Kindly check the project below :
https://github.com/mattslocum/ng-webworker
https://github.com/FredrikSandell/angular-workers


text:
Q: Reading all numbers that follow a specific string on a line of a text file I'm asking this question because the solutions I found to similar questions, here on stackoverflow, didn't allow me to solve my problem. I have a .txt file which is as follow:
VarA 10.0 20.0 30.0
VarBB 10
VarCz 1 2 3 4
VarDab 10 20 30 40 50
...

I'm trying to output (e.g. store them in a variable) the numbers associated to a specific variable using the sscanf function. For example, when looking for the string VarDab in the file, I want to store the numbers 10, 20, 30, 40, 50 in a variable. Because the number of numbers found for a specific string variable is not constant, I was trying to use the sscanf function in a loop. However, I'm not getting the result that I want. The code I have done so far:
FILE *fid;
char nameOfVariable[] = "VarDab";
int i;
while(!feof(fid))
{
    fgets(Line, maxLengthOfLine, fid);
    sscanf(Line, "%s", varString);
    if (strcmp(nameOfVariable, varString) == 0)
    {
        for (i = 0; i < maxLengthOfLine; i++)
        {
            sscanf(Line, "%lf%n", &varNumbers[i]);
        }
    }
}
flcose(fid);

EDIT
From the comments, I was able to modify my current implementation by adding an offset to the Line at each increment in the loop. It seems to work:
FILE *fid;
char nameOfVariable[] = "VarDab";
int i;
int variableIsFound = 1;
int offset = 0;
int numberOfNumbers = 5;

while(fgets(Line, maxLengthOfLine, fid) != NULL && variableIsFound)
{
    sscanf(Line, "%s %n", varString, &offset);
    if (strcmp(nameOfVariable, varString) == 0)
    {
        Line += offset;
        for (i = 0; i < numberOfNumbers; i++) {
            sscanf(Line, "%lf %n", &y[i], &offset);
            Line += offset;
        }
        variableIsFound = 0;
    }
}
fclose(fid);

A: You should use strtok to split line into tokens, example:
char *tok;
tok = strtok(Line, " "); // this is your String (first token in line)

tok = strtok(NULL, " "); // skip to next token (first number)
while (tok != NULL)
{
    printf("%s\n", tok); // use sscanf on tok to handle the numbers
    tok = strtok(NULL, " "); // skip to next token
}


text:
Q: In databinding, how do I programmatically set the root view of my layout to become another complex layout? I'm trying to make an error page for each of my activities where if there is a network error, it will show this error page. Some activities have two fragments, some have a Recycler view,some have a Toolbar, so on.
I'm trying to implement this showErrorPage() method in the BaseActivity class as a generic method for all activity that extend it.
I'm thinking I would get the root view using binding.getRoot() then I need some way to hide whatever that view is, and replace it with error_page.xml which the root view is layout as for all data binding and it contains a LinearLayout which includes TextView AND ImageView

A: I would definitely not try to do it the way you mentioned, since it would be unnecessarily complicated. In fact, you should never have to do this, since this isn't the way such a simple interface should be designed. Instead, I would probably create a Fragment which inflates error_page.xml as its root View.
Another approach you could try is surrounding your error_page.xml with <merge> tags and using <include> tags in each of the layouts of the activities/fragments you want to show your error layout (see https://developer.android.com/training/improving-layouts/reusing-layouts.html#Merge). Make sure that your <include> is at the bottom of each layout.
Then in every layout containing your <include> tag, I would set android:visibility="gone", android:layout_width="match_parent", android:layout_height="match_parent" within the body of the include and give it an id. In your method showErrorPage(), you could then set the visibility of the included layout, using its id, to View.VISIBLE.