text:
Q: Filling a Triangle in Python I have a python program where the object is to have the user enter the length of the sides of a triangle, if they would like to fill it, and what color. I keep getting an attribute error pertaining to GeometricObject and fill.
After a few fixes I am stuck in the same area again (fill), this is the error I keep getting:
> Traceback (most recent call last):   File "Desktop/one.py", line 81,
> in <module>
>     main()   File "Desktop/one.py", line 78, in main
>     "Is filled? :  ", triangle.ColorFill())   File "Desktop/one.py", line 21, in ColorFill
>     return self.__filled AttributeError: 'Triangle' object has no attribute '_GeometricObject__filled'

I am not sure where to untangle this, any help would be welcomed. Below is my code:
12.1 The Triangle class
import math

#class for the GeometricObject, must be defined before Trianble. includes fill
class GeometricObject:
    #if true the color will be green
    def __init__(self, color =" ", filled = True):
        self.__color = color
        self__filled = filled
    #getting the fill color and setting it to green fill
    def getColor(self):
        return self.__color
    def setColor(self, color):
        self.__color = color
    def ColorFill(self):
        return self.__filled
    def setColorFill(self, filled):
        self__filled = filled
    #string that tells you if it is filled or not
    def __st__(self):
        return "Color is: " + (self.__color) \
               + "Fill: " + str(self.__filled)

#setting class for triangle and calling on geometric objects
class Triangle(GeometricObject):
    def __init__(self, side1 = 1.0, side2 = 1.0, side3 = 1.0):
        self.__side1 = side1
        self.__side2 = side2
        self.__side3 = side3
        #calling GeometricObject, this is what triangle is bound to
        GeometricObject.__init__(self)
     #getting length of sides
    def getLengthA(self):
        return side1
    def getLengthB(self):
        return side2
    def getLengthC(self):
        return side3
    #setting and getting perimeter
    def setPerimeter(self):
        self.perimeter = perimeter
    def getPerimeter(self):
        perimeter = self.__side1 + self.__side2 + self.__side3
        return perimeter
    #setting and getting area
    def setArea(self):
        self.area = area
    def getArea(self):
        s = (self.__side1 + self.__side2 + self.__side3) / 2
        area = math.sqrt(s * ((s - self.__side1) * (s - self.__side2) * (s - self.__side3)))
        return area
    #printing string, sides
    def toString(self):
        return "Triangle: Side 1: " + (self.__side1)\
               + "Side 2: " + (self.__side2)\
               + "Side 3: " + (self.__side3)

def main():
    #user enters sides of a triangle
    side1, side2, side3 = eval(input("Enter the length of the Tiangle's sides (A, B, C):  "))
    triangle = Triangle(side1, side2, side3)
    #user enters color
    color = input("Enter a color: ")
    triangle.setColor(color)
    #user enter if filled
    filled = eval(input("Enter 1 to fill with color \n Enter 0 for no fill: "))
    ColorFill = (filled == 1)
    triangle.setColorFill(ColorFill)

    print("The area of the triangle is: " ,  triangle.getArea(), \
          "The perimeter is: " , triangle.getPerimeter(), \
          "The color is: ", triangle.getColor(), \
          "Is filled? :  ", triangle.ColorFill())

main()


text:
Q: Add a subrow on a GWT CellTable I have a CellTable that needs a subrow of a different type; similar to http://showcase2.jlabanca-testing.appspot.com/#!CwCustomDataGrid
I do not want to use DataGrid as I understand it to have a fixed height, and my table looks better with a dynamic height.
I've tried to extend CellTable then write
    public void renderRowValues(SafeHtmlBuilder sb,
            java.util.List<ShipmentLeg> values,
            int start,
            SelectionModel<? super ShipmentLeg> selectionModel){
        super.renderRowValues(sb, values, start, selectionModel);

        GWT.log("HELLO");
    }

What is a good strategy to accomplish this?  Note: in this code GWT.log is never called as in the super a deprecation error is thrown
Cheers

A: The API between CellTable and DataGrid is the same. As of GWT 2.5 the renderRowValues() method is deprecated hence, in order to alter the default table structure of both tables (say, creating subrows), you need to provide a CellTableBuilder.
Both table implementations use a DefaultCellTableBuilder (an extension of AbstractCellTableBuilder that leverage most of the bits and expose only a buildRowImpl() method). This is what you are looking for, no matter if you are using CellTable or DataGrid.
Extend AbstractCellTableBuilder and give an implementation of buildRowImpl(), much like the sample you linked, does. Do note that you linked an old sample. You should always refer to the one in the current showcase, as the API is slightly different.
Side note: DataGrid does not have a 'fixed height' at all, but requires a ProvidesResize container, as it need to dynamically adjust its size when the layout change (e.g., on browser resize). Check this out, if you haven't already.

redpajama_set_name: RedPajamaStackExchange


text:
Q: What is the difference between procedural code and Domain Driven Design style code? I am going through Domain Driven Design(DDD) techniques and I am feeling like I didn't understand it well yet.
DDD suggests putting the business logic(not infrastructure stuff like persistence, security etc) in Domain Objects, Repositories for Persistence, Aggregators for assembling Domain Objects for Client(Presentation), Services which are thin layer on top of the Domain objects and Repositories, Aggregators and acts as Transactional boundary.
Let me put it in this way:
In DDD, ViewController --> SomeService --> {Domain Objects, Repositories, Aggregators}
In my current (Procedural style) approach:
ViewController --> SomeService --> DAO/Repository
Here ViewController talks to one or more Services to pull/push the data from/to the database using DAOs. If any business logic which only operates on properties of a Domain object will be in a method in that Domain Object itself. And finally the data got from service(s) are aggregated into DTOs to be presented in View Layer.
So to me both approaches almost looks similar.
Can someone explain me what I am missing?
P.S: I am adding some more info to better explain my question.
In theory everyone is saying DDD suggests "Logic should be in Domain Objects". OK.
Let us take a real scenario.
In ShoppingCart application, some user placed an Order. To process the Order I need to do all the following sub-tasks:

*

*Get Each Item details and calculate the total Order Price.

*Get the Delivery Address and Validate it using some Address Verification Service

*Validate/Authenticate CreditCard Details

*Save all the Order related info into DB
So by following DDD I will put the logic,

*

*Order Total calculation in Order object which loops through its List objects.

*In Address Object i would have validate() method which invokes some BING address validation.

*In CreditCard class I would have authorize() method which calls some CCAuthorizationService to authorize using some third party services.

*Save all order stuff into DB using some Repositories.
All these steps will be triggered by calling Order.process()
If this is correct DDD approach? If it is, our Domain Objects directly interacting with Repositories which seems to be violation of separation of concerns.
If this is not correct DDD approach, can some one please tell me how do you design for the above usecase?

A: It boils down to where the logic lives.  In DDD logic primarily goes into the model layer so it stays near the data.  In procedural code, logic goes into transactional layers so it is separated from the data.  Fowler has a good description you can read about here.

A: DDD is language independent, it's about understanding the domain through experts and building a common language with which you can talk about the domain.  So it cannot be compared directly to functional, procedural or object oriented programming languages, as they're not comparable.
View Controllers are specific to MVC frameworks and aren't specific to DDD.
In MVC a DTO for preparing data for the view would be a View Model.
Hope some of this helps.

A: They are similar.
Hopefully you're actually comparing "OOP" with "DDD". DDD is a subset of OOP (IMO), or at least should be in an OOPL. DDD is a specific way of thinking about breaking up responsibilities.

A: It's not about the technology or OOP or anything like that.
It's about focusing on the domain at hand, the language used by domain experts, understanding the domain and modelling that domain so that important concepts are present in the code.
It was originally done using OOP and many claimed that it could only be done using OOP.
However, lately people like Greg Young have shown how to do DDD in functional languages and still keep the focus on the domain.
Procedural code tend to ignore all that and just focus on how to read/write data from whatever datasource there is. e.g. integrating with a system like Movex there will be a billion tables and columns with completely retarded names like TAXEM.YAROOD FOOB.AAR which makes no sense to anyone reading that code...


text:
Q: Base class using data from derived class I have a class
Class A
{
    uint8_t* queue;
    uint32_t num_elems_queue;
    void DoSomethingWithQueue();
};

This class will be my library which will be used by different clients.
In the client code that used the above class I will have something like.
Class B
{
    const uint32_t num_elems = 8;
    uint8_t queue[num_elems];
};

Now in order to initialize the data in class A I have two options. One is that I pass data in to class A in constructor such as
Class A
{
    A(uint8_t* queue__, uint32_t num_elems_queue__): queue(queue__),num_elems_queue(num_elems_queue__)
    {
    }
    uint8_t* queue;
    uint32_t num_elems_queue;
    void DoSomethingWithQueue();
};

The other is that I inherit class B from class A and have pure virtual functions in class A that return pointer to needed data. such as
Class A
{

    uint8_t* queue;
    uint32_t num_elems_queue;
    void DoSomethingWithQueue();
    virtual uint32_t get_num_elems_queue() = 0;
    virtual uint8_t* get_queue() = 0;
};

Class B : public A
{
    const uint32_t num_elems = 8;
    uint8_t queue[num_elems];
    uint32_t get_num_elems_queue()
    {
        return num_elems;
    }
    uint8_t* get_queue()
    {
        return queue
    }
};

Now my question is which is the preferred way. I have been told that second method is better but my opinion is that in case of second method I am inheriting not to extend base class but to send data back to the base class. Does this not go against the basic reason why inheritance should be used "To extend the functionality of the class".
EDITED:
I think this situation can be solved by passing "num_elems" to class A. But in general when we have a single class that works on different data it is better to inherit and use the data from the derived class. Correct me if I am wrong. After a little searching I found a similar example from MSDN website:
The code is in VB I am not VB developer but from what I understood scenario is same.
From https://msdn.microsoft.com/en-us/library/27db6csx%28v=vs.90%29.aspx

Suppose, for example, that you have a large business application that manages several kinds of in-memory lists. One is an in-memory copy of your customer database, read in from a database at the beginning of the session for speed. The data structure might look something like the following:

Class CustomerInfo
    Protected PreviousCustomer As CustomerInfo
    Protected NextCustomer As CustomerInfo
    Public ID As Integer
    Public FullName As String

    Public Sub InsertCustomer(ByVal FullName As String)
        ' Insert code to add a CustomerInfo item to the list.
    End Sub

    Public Sub DeleteCustomer()
        ' Insert code to remove a CustomerInfo item from the list.
    End Sub

    Public Function GetNextCustomer() As CustomerInfo
        ' Insert code to get the next CustomerInfo item from the list.
        Return NextCustomer
    End Function

    Public Function GetPrevCustomer() As CustomerInfo
        'Insert code to get the previous CustomerInfo item from the list.
        Return PreviousCustomer
    End Function
End Class

Your application may also have a similar list of products the user has added to a shopping cart list, as shown in the following code fragment:

Class ShoppingCartItem
    Protected PreviousItem As ShoppingCartItem
    Protected NextItem As ShoppingCartItem
    Public ProductCode As Integer
    Public Function GetNextItem() As ShoppingCartItem
        ' Insert code to get the next ShoppingCartItem from the list.
        Return NextItem
    End Function
End Class

You can see a pattern here: two lists behave the same way (insertions, deletions, and retrievals) but operate on different data types. Maintaining two code bases to perform essentially the same functions is not efficient. The most efficient solution is to factor out the list management into its own class, and then inherit from that class for different data types:

Class ListItem
    Protected PreviousItem As ListItem
    Protected NextItem As ListItem
    Public Function GetNextItem() As ListItem
        ' Insert code to get the next item in the list.
        Return NextItem
    End Function
    Public Sub InsertNextItem()
        ' Insert code to add a item to the list.
    End Sub

    Public Sub DeleteNextItem()
        ' Insert code to remove a item from the list.
    End Sub

    Public Function GetPrevItem() As ListItem
        'Insert code to get the previous item from the list.
        Return PreviousItem
    End Function
End Class

The ListItem class needs only to be debugged once. Then you can build classes that use it without ever having to think about list management again. For example:

Class CustomerInfo
    Inherits ListItem
    Public ID As Integer
    Public FullName As String
End Class
Class ShoppingCartItem
    Inherits ListItem
    Public ProductCode As Integer
End Class

A: It is usualy the superior option to derive class B from A
For example:
class Vehicle
{
public:
    int WheelCount;
};

class Truck : public Vehicle
{
public:
    int LadderHeight;
};

A Truck is also a Vehicle. Therefore you use derivation. The property WheelCount will also be available in Truck.
Derivation in general means, something is another thing. In this example, a Truck is a Vehicle. You can also say that a MonsterTruck is a Truck (i.e. multiple derivance).
Despite the fact that you could use std::vector or std::list for that, but I don't think that is the question here. I just thought it was worth mentioning...

A:
Now my question is which is the preferred way.

Answers will be heavily influenced by opinion and by other factors such as the coding style of the rest of the program or details of the specific problem you're solving.
So just do something that works and which passes code review, and then pay attention to how well it works over the life of the project. Then next time you have to make a similar design decision you can make it based on experience and with full knowledge of the specific project.

The most efficient solution is to factor out the list management into its own class, and then inherit from that class for different data types:

That statement is far too broad, and C++ in particular has many more tools for design than VB. Consider that C++ has a generic list type as well, and using it doesn't involve inheritance at all.

There are some other implementation options.

*

*Your class A currently uses implementation inheritance for both data members and the DoSomethingWithQueue() member function. You can reduce the implementation inheritance by eliminating the data members.
class A
{
  // A has no data members
public:
  void DoSomethingWithQueue(); // implemented purely in terms of the virtual functions
protected:
  virtual uint32_t get_num_elems_queue() = 0;
  virtual uint8_t* get_queue() = 0;
};

*You can also completely avoid inheritance:
template<typename QueueContainer>
void DoSomethingWithQueue(QueueContainer const &qc);

class B {
public:
  uint32_t get_num_elems_queue();
  uint8_t* get_queue();
};

B b;
DoSomethingWithQueue(b);

The above assumes the same basic interface for B as you specified, though there could be better designs for that as well. E.g., you might want it to conform to the standard Container concept rather than having custom get_queue() and get_num_elements_queue() members. Then you might even be able to use a standard Container instead of defining your own class B.


text:
Q: /var House Keeping Does anyone have any general advice or links for doing some house keeping on the /var filesystem on Unix and Linux servers?
I have searched the issue quite a bit but can find no real concrete information on what I can/cannot do when I need to free up some space under /var (which happens a lot where I work).

A: The usual way to minimize space on logdata is to use logrotate.
There is a good tutorial on The GeekStuff

A: The reason why there isn't a universal guide for cleaning /var is that it highly depends on the system. In short, /var is probably the most distribution-specific part of the filesystem hierarchy. Apart from logs, typically managed by logrotate (see ddeimeke's answer), the following factors can significantly differ from installation to installation:

*

*the way your distribution handles package installation: how much management-related and build-time data does it store, and under what specific paths,

*the history of package installation, including installation attempts that failed for whatever reason,

*automatic clean-ups scheduled by default by your distro,

*the structure of /var: is it standardised by the distro (paths adjusted in the packaging process for each distributed package) or left the way each program has defined for itself,

*the specific software installed and used: each has its own settings that determine how much is stored, where, and quite often also for how long.

So, if you are looking for a generic way for doing clean-up, a there are generally two ways to go: search for distribution-specific information about managing /var or(and) manually determine, what part of the /var subtree is filled most often.
For the latter, you can use many tools, but probably the most generic is the du (DiskUsage) command-line program, together with xdiskusage for visualisation. If it's a headless server, you can store the output from du to a file, download it and run xdiskusage locally, supplying du's output file as a parameter. The next step to implement some regular clean-up routines is determining, which program is responsible for which file(s) - some of this you can easily deduce, but in some cases you will have to use your distribution's package management utilities - they can very often tell you, which package a specific path belongs to.


text:
Q: SWP 6.0 TeX compilation error I had a working version of Scientific Workplace 6 (SWP 6) on my old laptop.  I just got a new laptop and I installed SWP 6 on it.  The version was downloadable for free from a legit site. I then added my old license number to the newly installed software.
Everything seems to work fine, except the PDF compiler. When I click on "PDF preview", the compilation fails.  I get a "TeX Error" stating "Unable to Create a PDF file".
I am not sure what is going on, it did not happen on my old laptop.
Did this happen to anyone?
Thanks,
Zsolt


text:
Q: Set active window I'm trying to make an app that gives a quake style drop-down HUD console.  I can get it to show and hide the window, but I can't figure out how to set it as the active window after showing it.  Im using Win API calls to show and hide the window.  I've tried SetForegroundWindow(IntPtr hWnd) and SetFocus(IntPtr hWnd) to no avail.  Anyone have any ideas?
http://pastebin.com/DgtJJGiv
public void ShowApp()
{
    IntPtr h = FindWindow(null, "C:\\Windows\\system32\\cmd.exe");
    ShowWindow(h, SW_SHOW);
    //EnableWindow(h, true);
    isHidden = false;
        // set focus to console window

    SetForegroundWindow(h);
    System.Diagnostics.Debug.WriteLine(h);
}

A: I found an answer here:
How to show form in front in C#
The winAPI approaches were not working correctly for me but this did:
form.TopMost = true;
form.TopMost = false;

I originally was only setting TopMost to true but I ran into problems with dialog boxes displaying behind the form. It appears that setting TopMost to true pulls the form to the front and holds it there. Setting it to false doesn't push it back but does allow other forms to be shown in front. I was still having problems with focus so I ended up going with the following:
form.Activate();

A: Try this (works for me):
public static void ShowApp()
{
    IntPtr h = FindWindow(null, "C:\\Windows\\system32\\cmd.exe");
    ShowWindow(h, ShowWindowCommands.Show);
    SetForegroundWindow(h);
    SetFocus(h);
    System.Diagnostics.Debug.WriteLine(h);
}

A: You may use SetActiveWindow winAPI method. Hope this helps...

A: Is there any reason why you can't implement your own console window?  What I mean is a simple Form with a Textbox set to the correct style.  You would probably have more control over how it works than trying to use the 'cmd' process.
Just a thought.


text:
Q: Can I possibly always display the this TimePicker Widget? I am trying to create an app where the user is able to select the time and the date, I want to make it such that the TimePicker is always showing on the screen for the user. I have managed to do this but I am unable to get the Time that is set by the user as there is no OnChanged method available.
Furthermore, I cannot change the functionality of the cancel and the Ok button that is displayed.
Here is the code:
Scaffold(
      backgroundColor: Color(0xff2E2E42),
      appBar: PreferredSize(preferredSize: Size.fromHeight(50),
          child: CustomAppBar("Add Alarm")),
      body: Column(

        children: [
          TimePickerDialog(initialTime: TimeOfDay.now(), onEntryModeChanged: (TimePicker){
            print(TimePicker);

          },),
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 42.0),
            child: Column(
              // mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                MaterialButton(onPressed: (){pickDate(context);},
                  child: Column(
                    children: [
                      Center(
                        child: Text(getDate(), style: TextStyle(
                          color: Colors.white,
                          fontSize: 30,
                        ),),
                      ),
                    ],
                  ),)
              ],
            ),
          ),
        ],
      ),
    );

This is what the output looks like:

Thanks for helping :)

A: Unfortunately there is no easy way to convert TimePickerDialog into a non-dialog version, because much of it is hardcoded. This is unlike the date picker counterpart, where we can choose to either use DatePickerDialog or standalone DayPicker, MonthPicker, YearPicker widgets.
You basically have 3 choices, none of them is great.

*

*Copy the dialog code (time_picker.dart file) into your project and modify it to suit your needs.

*Use CupertinoTimerPicker (very different visual style).

*Create your own, build it however you like.


text:
Q: Laravel - controller handle multiple models I'm starting with Laravel. I have LinksController that handle my links table (CRUD). I want to use this table to store all the links from my app.
I have two tables:

*

*tutorials

*posts

LinksController.php
public function store(Request $request, Tutorial $tutorial) {

    $link = new Link;
    $link->user_id = auth()->user()->id;
    $link->source_id = $tutorial->id;
    $link->link = $request->link;
    $link->save();
}

This works fine. Now I was trying to save posts links and I noticed my route model binding can use only one Model.
Routes:
tutorials/{tutorial}/links
posts/{post}/links

If I change Tutorial $tutorial for Post $post it will work for posts but not for tutorials.
I read about Polymorphic Relationships but I'm not sure how to pass different models to my LinksController.
Should I use something like this in my LinksController.php:
private $model;

public function __construct(Request $request) {
    // if route a
    //     $this->model = Tutorial::class;
    // else
    //     $this->model = Post::class;
}

I know that I can use hidden input to pass model, but I don't really want to do that.
Edit:
Other solutions that come to my mind would be Explicit Binding:
RouteServiceProvider.php
Route::model('tutorial', \App\Tutorial::class);
Route::model('post', \App\Post::class);

And then in my LinksController store method:
public function store(Request $request, Model $model) {

Do you think this would be a good approach? In this case, the first parameter from the route should always be a variable that is present in my RouteServiceProvider.
Is there any better and more elegant approach to my problem?

A: You should add a source_type field to your link model for the polymorphic relationship.
$link->source_type = "tutorial" or "post"

The route may be something like:
Route::post('/{sourceType}/{sourceTypeId}/links', 'LinksController@store')->where(['sourceType' => 'posts|tutorials', 'sourceTypeId' => '[0-9]+']);

Then in your controller
public function store(Request $request, string $sourceType, int $sourceTypeId) {
    if ($sourceType == 'posts') {
        $source = Post::findOrFail($sourceTypeId);
    } elseif ($sourceType == 'tutorials') {
       $source = Tutorial:findOrFail($sourceTypeId);
    }

    $link = new Link;
    $link->user_id = auth()->user()->id;
    $link->source_id = $source->id;
    $link->source_type = substr($sourceType, 0, -1);
    $link->link = $request->link;
    $link->save();
}

I never used polymorphic relationships but this is something I may do.


text:
Q: Nuxtjs app stops immediately when start with pm2 I am trying to run a nuxtjs app using pm2 however, the app exits immediately, and I could not get useful info from pm2 log:
2|frontend_nuxt  | Error: ENOENT: no such file or directory, chdir '����' -> '/var/www/frontend_nuxt/releases/20210831071742'
2|frontend_nuxt  |     at wrappedChdir (node:internal/bootstrap/switches/does_own_process_state:112:14)
2|frontend_nuxt  |     at process.chdir (node:internal/worker:100:5)
2|frontend_nuxt  |     at /usr/local/share/.config/yarn/global/node_modules/pm2/lib/ProcessContainer.js:298:13
2|frontend_nuxt  |     at wrapper (/usr/local/share/.config/yarn/global/node_modules/pm2/node_modules/async/internal/once.js:12:16)
2|frontend_nuxt  |     at next (/usr/local/share/.config/yarn/global/node_modules/pm2/node_modules/async/waterfall.js:96:20)
2|frontend_nuxt  |     at /usr/local/share/.config/yarn/global/node_modules/pm2/node_modules/async/internal/onlyOnce.js:12:16
2|frontend_nuxt  |     at WriteStream.<anonymous> (/usr/local/share/.config/yarn/global/node_modules/pm2/lib/Utility.js:186:13)
2|frontend_nuxt  |     at WriteStream.emit (node:events:394:28)
2|frontend_nuxt  |     at node:internal/fs/streams:72:16
2|frontend_nuxt  |     at FSReqCallback.oncomplete (node:fs:185:23)

The nuxtjs app it self can start without issue.
I have no idea how to debug this error, or how to get more useful details, any idea?

A: using npm2 show id I found that the script path was not updated.
so, i just had to:
pm2 delete frontend_nuxt && pm2 start ecosystem.config.js

and all is well.


text:
Q: datetime objects in list #3. add times as field
self.scheduled_transmitions = self.scheduled_transmitions_copy[:]
self.scheduled_transmitions_copy = []
self.datetime_clock = start_datetime
counter = 0
for scheduled_transmition in self.scheduled_transmitions:
    print(self.datetime_clock)
    self.scheduled_transmitions[counter]["datetime"] = self.datetime_clock
    self.datetime_clock = self.datetime_clock+datetime.timedelta(seconds=int(scheduled_transmition["duration_in_seconds"]))

    self.scheduled_transmitions_copy.append(self.scheduled_transmitions[counter])
    counter = counter + 1

print("------------")
self.scheduled_transmitions = self.scheduled_transmitions_copy[:]
self.scheduled_transmitions_copy = []

for scheduled_transmition in self.scheduled_transmitions:
    print(scheduled_transmition["datetime"])

return 1

The up code has wrong output.
#3. add times as field
self.scheduled_transmitions = self.scheduled_transmitions_copy[:]
self.scheduled_transmitions_copy = []
self.datetime_clock = start_datetime
for scheduled_transmition in self.scheduled_transmitions:
    print(self.datetime_clock)
    entry = {"datetime":self.datetime_clock}
    self.datetime_clock = self.datetime_clock+datetime.timedelta(seconds=int(scheduled_transmition["duration_in_seconds"]))

    self.scheduled_transmitions_copy.append(entry)

print("------------")
self.scheduled_transmitions = self.scheduled_transmitions_copy[:]
self.scheduled_transmitions_copy = []

for scheduled_transmition in self.scheduled_transmitions:
    print(scheduled_transmition["datetime"])

return 1

But the last one does not.
Why?
Output of first code (wrong):
2020-11-08 18:05:20.054000
2020-11-08 18:06:48.054000
2020-11-08 18:08:16.054000
2020-11-08 18:09:44.054000
2020-11-08 18:11:12.054000
2020-11-08 18:12:40.054000
2020-11-08 18:14:08.054000
2020-11-08 18:15:36.054000
2020-11-08 18:17:04.054000
2020-11-08 18:18:32.054000
------------
2020-11-08 18:18:32.054000
2020-11-08 18:18:32.054000
2020-11-08 18:18:32.054000
2020-11-08 18:18:32.054000
2020-11-08 18:18:32.054000
2020-11-08 18:18:32.054000
2020-11-08 18:18:32.054000
2020-11-08 18:18:32.054000
2020-11-08 18:18:32.054000
2020-11-08 18:18:32.054000

Output of seconds code.
2020-11-08 18:03:13.265000
2020-11-08 18:04:41.265000
2020-11-08 18:06:09.265000
2020-11-08 18:07:37.265000
2020-11-08 18:09:05.265000
2020-11-08 18:10:33.265000
2020-11-08 18:12:01.265000
2020-11-08 18:13:29.265000
2020-11-08 18:14:57.265000
2020-11-08 18:16:25.265000
------------
2020-11-08 18:03:13.265000
2020-11-08 18:04:41.265000
2020-11-08 18:06:09.265000
2020-11-08 18:07:37.265000
2020-11-08 18:09:05.265000
2020-11-08 18:10:33.265000
2020-11-08 18:12:01.265000
2020-11-08 18:13:29.265000
2020-11-08 18:14:57.265000
2020-11-08 18:16:25.265000

A: I don't know why that happens but the following code works:
    #3. add times as field
    self.scheduled_transmitions = self.scheduled_transmitions_copy[:]
    self.scheduled_transmitions_copy = []
    self.datetime_clock = start_datetime
    for scheduled_transmition in self.scheduled_transmitions:
        print(self.datetime_clock)
        entry = scheduled_transmition.copy()
        entry["datetime"]=self.datetime_clock
        self.datetime_clock = self.datetime_clock+datetime.timedelta(seconds=int(scheduled_transmition["duration_in_seconds"]))

        self.scheduled_transmitions_copy.append(entry)

    print("------------")
    self.scheduled_transmitions = self.scheduled_transmitions_copy[:]
    self.scheduled_transmitions_copy = []

    for scheduled_transmition in self.scheduled_transmitions:
        print(scheduled_transmition["datetime"])

    return 1

I copy the list element (dictionary) using dictionary.copy() method.


text:
Q: replace square brackets java I want to replace text in square brackets with "" in java:
for example I have the sentence
"Hello, [1] this is an example [2], can you help [3] me?"
it should become:
"Hello, this is an example, can you help me?"

A: This should work:
.replaceAll("\\[.*?\\]", "").replaceAll(" +", " ");

A: Please use this,
String str = "[How are you]";
str = str.replaceAll("\\[", "").replaceAll("\\]","");

A: String newStr = str.replaceAll("\\[\\d+\\] ", "");

What this does is to replace all occurrences of a regular expression with the empty String.
The regular expression is this:
\\[  // an open square bracket
\\d+ // one or more digits
\\]  // a closing square bracket
     // + a space character

Here's a second version (not what the OP asked for, but a better handling of whitespace):
String newStr = str.replaceAll(" *\\[\\d+\\] *", " ");

What this does is to replace all occurrences of a regular expression with a single space character.
The regular expression is this:
 *   // zero or more spaces
\\[  // an open square bracket
\\d+ // one or more digits
\\]  // a closing square bracket
 *   // zero or more spaces


text:
Q: pika dropping basic_publish messages sporadically I'm trying to publish messages with pika, using Celery tasks.
from celery import shared_task
from django.conf import settings
import json

@shared_task
def publish_message():
    params = pika.URLParameters(settings.BROKER_URL + '?' + 'socket_timeout=10&' + 'connection_attempts=2')
    conn = pika.BlockingConnection(parameters=params)
    channel = conn.channel()
    channel.exchange_declare(
                exchange = 'foo',
                type='topic'
            )
    channel.tx_select()
    channel.basic_publish(
                exchange = 'foo',
                routing_key = 'bar',
                body = json.dumps({'foo':'bar'}),
                properties = pika.BasicProperties(content_type='application/json')
            )
    channel.tx_commit()
    conn.close()

This task is called from the views.
Due to some weird reason, sometimes randomly, the messages are not getting queued. In my case, every second message is getting dropped. What am I missing here?

A: I would recommend that you enable confirm_delivery in pika. This will ensure that messages get delivered properly, and if for some reason the message could not be delivered. Pika will fail with either an exception, or return False.
channel.confirm_delivery()
successful = channel.basic_publish(...)

If the process fails you can try to send the message again, or log the error message from the exception so that you can act accordingly.

A: Try this:
chanel = conn.channel()
try:
    chanel.queue_declare(queue='foo')
except:
    pass

chanel.basic_publish(
    exchange='',
    routing_key='foo',
    body=json.dumps({'foo':'bar'})
)


text:
Q: Use NuGetCommand@2 to push packages to nuget.org The documentation here says

To publish to an external NuGet feed, you must first create a service connection to point to that feed....

It then provides this YAML:
- task: NuGetAuthenticate@0
  inputs:
    nuGetServiceConnections: '<Name of the NuGet service connection>'
- task: NuGetCommand@2
  inputs:
    command: push
    nuGetFeedType: external
    versioningScheme: byEnvVar
    versionEnvVar: <VersionVariableName>

This fails with

"Error: The service connection for 'https://api.nuget.org/v3/index.json' is not valid. ApiKey service connections are not supported in this task. Instead, use -ApiKey (NuGet) or --api-key (dotnet) when invoking the tool itself. See the task documentation for more details."

I have created a service connection that points to nuget.org with my ApiKey.
I do not understand this portion of the error message: "Instead, use -ApiKey (NuGet) or --api-key (dotnet) when invoking the tool itself. See the task documentation for more details."
I have also seen this question which refers to a deficiency which has since been implemented.
Edit:  Turns out the deficiency mentioned above is a red herring.  The real problem is a limitation of nuget which still exists as of this writing.

A: According to the NuGet Authenticate task document:

Some package sources such as nuget.org use API keys for authentication
when pushing packages, rather than username/password credentials. Due
to limitations in NuGet, this task cannot be used to set up a NuGet
service connection that uses an API key.
Instead:

*

*Configure a secret variable containing the ApiKey

*Perform the package
push using nuget push -ApiKey $(myNuGetApiKey) or dotnet nuget push
--api-key $(myNuGetApiKey), assuming you named the variable myNuGetApiKey


text:
Q: app crashing, need help understanding what the problem is Error:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.murach.splash/com.wickham.android.splash.Splash}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.app.ActionBar.setDisplayShowTitleEnabled(boolean)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2817)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6541)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.app.ActionBar.setDisplayShowTitleEnabled(boolean)' on a null object reference
at com.wickham.android.splash.Splash.onCreate(Splash.java:47)
at android.app.Activity.performCreate(Activity.java:6975)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1213)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2770)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6541)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
Splash Activity
package com.wickham.android.splash;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

import android.view.WindowManager;
import android.widget.ProgressBar;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;

public class Splash extends Activity {
    int i;

    String getURL = "http://www.your-server.com/english-proper-names.txt";
    String ip204 =  "http://www.your-server.com/return204.php";

    public static int ConnectTimeout = 10000;
    public static int ReadTimeout = 10000;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        getWindow().setFlags(
                WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);

        this.setContentView(R.layout.splash);
47
48      // Setup the ActionBar and the Spinner in the ActionBar
        getActionBar().setDisplayShowTitleEnabled(true);
        getActionBar().setSubtitle("Practical Android");
        getActionBar().setTitle("Splash");

        if (haveNetworkConnection()) {
            new HttpDownload().execute();
        }
        else {
            noConnection();
        }
    }

    private boolean haveNetworkConnection() {
        boolean HaveConnectedWifi = false;
        boolean HaveConnectedMobile = false;

        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo[] netInfo = cm.getAllNetworkInfo();
        for (NetworkInfo ni : netInfo)
        {
            if (ni.getTypeName().equalsIgnoreCase("WIFI"))
                if (ni.isConnected())
                    HaveConnectedWifi = true;
            if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
                if (ni.isConnected())
                    HaveConnectedMobile = true;
        }
        return HaveConnectedWifi || HaveConnectedMobile;
    }

    public class HttpDownload extends AsyncTask<Void, String, Void> {
        @Override
        protected Void doInBackground(Void... unused) {
            publishProgress("Connecting","0");
            String fromServer = "";
            int BUFFER_SIZE = 2000;
            float fsize = 890000;
            InputStream in = null;
            try {
                // Check for reachability
                URL url = new URL(ip204);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setConnectTimeout(ConnectTimeout);
                conn.setReadTimeout(ReadTimeout);
                conn.setRequestMethod("HEAD");
                in = conn.getInputStream();
                int status = conn.getResponseCode();
                in.close();
                conn.disconnect();
                if (status == HttpURLConnection.HTTP_NO_CONTENT) {
                    // Server is reachabile, so initiate the download
                    publishProgress("Connecting:", "0");
                    in = OpenHttpConnection(getURL);
                    InputStreamReader isr = new InputStreamReader(in);
                    int charRead;
                    char[] inputBuffer = new char[BUFFER_SIZE];
                    while ((charRead = isr.read(inputBuffer))>0) {
                        //---convert the chars to a String---
                        String readString = String.copyValueOf(inputBuffer, 0, charRead);
                        fromServer += readString;
                        inputBuffer = new char[BUFFER_SIZE];
                        //---update the progress
                        float ratio = (fromServer.length() / fsize) * 100;
                        int num = (int) ratio;
                        publishProgress("Connecting: " + String.valueOf(num) + "%", String.valueOf(num));
                    }
                    in.close();
                } else {
                    publishProgress("Not Reachable", "0");
                    failedReach();
                }
            } catch (IOException e) {
                failedDownload();
            }
            publishProgress("Completed","100");
            return null;
        }

        @Override
        protected void onPostExecute(Void unused) {
            startActivity(new Intent(Splash.this, Main.class));
            finish();
        }

        @Override
        protected void onPreExecute() {
        }

        @Override
        protected void onProgressUpdate(String... item) {
            TextView txt = (TextView) findViewById(R.id.text);
            txt.setText(item[0]);
            ProgressBar progressBar = (ProgressBar) findViewById(R.id.progBar);
            int num = Integer.parseInt(item[1]);
            progressBar.setProgress(num);
        }
    }

    public void noConnection() {
        AlertDialog alertDialog = new AlertDialog.Builder(Splash.this).create();
        alertDialog.setTitle("Connection");
        alertDialog.setIcon(android.R.drawable.stat_sys_warning);
        alertDialog.setMessage("Data connection not available. Please restart.");
        alertDialog.setCancelable(false);
        alertDialog.setButton("Exit", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                finish();
            } });
        alertDialog.show();
    }

    public void failedReach() {
        AlertDialog alertDialog = new AlertDialog.Builder(Splash.this).create();
        alertDialog.setTitle("Connection");
        alertDialog.setIcon(android.R.drawable.stat_sys_warning);
        alertDialog.setMessage("Connection available, but server could not be reached. Please restart.");
        alertDialog.setCancelable(false);
        alertDialog.setButton("Exit", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                finish();
            } });
        alertDialog.show();
    }

    public void failedDownload() {

        AlertDialog alertDialog = new AlertDialog.Builder(Splash.this).create();
        alertDialog.setTitle("Connection");
        alertDialog.setIcon(android.R.drawable.stat_sys_warning);
        alertDialog.setMessage("Connection available, but downloading failed. Please restart.");
        alertDialog.setCancelable(false);
        alertDialog.setButton("Exit", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                finish();
            } });
        alertDialog.show();

    }

    public static InputStream OpenHttpConnection(String urlString) throws IOException {
        InputStream in = null;
        int response = -1;

        URL url = new URL(urlString);
        URLConnection conn = url.openConnection();

        if (!(conn instanceof HttpURLConnection)) throw new IOException("Not an HTTP connection");

        try{
            HttpURLConnection httpConn = (HttpURLConnection) conn;
            httpConn.setAllowUserInteraction(false);
            httpConn.setInstanceFollowRedirects(true);
            httpConn.setRequestMethod("GET");
            httpConn.connect();

            response = httpConn.getResponseCode();
            if (response == HttpURLConnection.HTTP_OK) {
                in = httpConn.getInputStream();
            }
        }
        catch (Exception ex) {
            throw new IOException("Error connecting");
        }
        return in;
    }
}

Splash Line 47 as noted above does not have any code written in it, so i'm unsure as to why it is bringing an error.

A: You will need to use getSupportActionBar() method, if you didn't make changes regarding ActionBar(eg.Theme to change No Action Bar).
The reason why you should use getSupportActionBar() method is due to what MainActivity inherits from, which is AppCompatActivity.
if you dive deep into source code, getActionBar() method derives from Activity.class whereas getSupportActionBar() method derives from AppCompatActivity, which MainActivity inherits from.
if you take a look at AppCompatActivity class, it has delegate class: AppCompatDelegate(abstract) and this AppCompatDelegate.class is implemented by AppCompatDelegateImpl.class, and this is where you get action bar in your case.
Both Activity.class and AppCompatDelegateImpl.class have mActionBar as member variable, but since your MainActivity.class inherits AppCompatActivity.class, you need to call getSupportActionBar() method to retrieve the value you want.
p.s. if you open AppCompatDelagateImpl.class and find getSupportActionBar() ,
it has commented with

The Action Bar should be lazily created as hasActionBar
could change after onCreate

if you wonder how to explore, I marked a breakpoint to the line where it retrieves actionbar and kept pressing F5(on window) to know how it returns action bar.


text:
Q: Message Queue: Which one is the best scenario? I write a web crawler.
The crawler has 2 steps:

*

*get a html page

*then parse the page

I want to use message queue to improve performance and throughput.

I think 2 scenarios:
scenario 1:
    structure:
    urlProducer -> queue1 -> urlConsumer -> queue2 -> parserConsumer

urlProducer: get a target url and add it to queue1
urlConsumer: according to the job info, get the html page and add it to queue2
parserConsumer: according to the job info, parse the page
scenario 2:
    structure:
    urlProducer -> queue1 -> urlConsumer
    parserProducer-> queue2 -> parserConsumer

urlProducer : get a target url and add it to queue1
urlConsumer: according to the job info, get the html page and write it to db
parserProducer: get the html page from db and add it to queue2
parserConsumer: according to the job info, parse the page

There are multiple producers or consumers in each structure.
scenario1 likes a chaining call. It's difficult to find the point of problem, when occurring errors.
scenario2 decouples queue1 and queue2. It's easy to find the point of problem, when occurring errors.
I'm not sure the notion is correct.
Which one is the best scenario?  Or other scenarios?
Thanks~

A: I think Scenario 1 is your best option as you don't have to monitor a database, which could slow things down.  Not sure what you plan on using to implement this, but I could see it done couple different ways:

*

*Using Kafka and laying out the consumers as you specified.

*Using storm and not relying on a message queue.  Essentially, you are doing stream processing.

There are other ways you can do this (web services, embedded queue's like ZeroMQ, other brokers, etc.), but since you mentioned throughput, those are two of the scenarios that would give you good throughput.

A: The second scenario would be a better way to handle this problem if you want to use a simple messaging system, in my opinion. The three key tasks that you have implemented are fetching links, fetching pages from the links and parsing them to get required information. We need to keep in mind that the rates at which these operations are performed are  different depending upon the size of the page being fetched. You would be better off having an intermediate storage to avoid clogging of the queueing systems.
That being said, I agree with @blockcipher's answer on this thread to use Storm Clusters instead of the simple queueing mechanisms. Storm worker nodes can also define flow control methods for you to vary the rates of flow of the different streams on an average rate. In such a case, the first scenario would be more beneficial. So, your choice would depend upon what you are planning to use for implementing your solution.


text:
Q: Python Program that takes an integer and returns a list of n even integers Question: Write a program which first defines a function evens(n). The function should take an integer as the argument and return a list of n even integers starting with 2 using the range function which takes a third argument that is the "step". Rewrite the function using the third argument in the range.
What I have so far:
def evens(n):
    evensLst = []

    for i in range(1,n+1):
            evensLst.append(2*i)
    return evensLst

    for i in range(1,n+1):
            evensLst.append(3*i)
    return evensLst

n = raw_input("Enter an integer: ")
print "Evens: ", evens(n)

A: def evens(n):
    return [2*n for n in range(1, n+1)]

If you use the "third" argument of range, you get the list you are looking for directly.
def evens(n):
    return range(2, 2*n+1, 2)


text:
Q: How do I transform a vector and a list of lists into a data.frame in R? Essentially I'm after the product of a vector and a list of lists where the LoL has arbitrary lengths.
dose<-c(10,20,30,40,50)
resp<-list(c(.3),c(.4,.45,.48),c(.6,.59),c(.8,.76,.78),c(.9))

I can get something pretty close with
data.frame(dose,I(resp))

but it's not quite right.  I need to expand out the resp column of lists pairing the values against the dose column.
The desired format is:
10 .3
20 .4
20 .45
20 .48
30 .6
30 .59
40 .8
40 .76
40 .78
50 .9

A: Here is a solution using rep() and unlist().

*

*Use rep to repeat the elements of dose, with the length of each element of resp.

*Use unlist to turn resp into a vector

The code:
data.frame(
  dose = rep(dose, sapply(resp, length)),
  resp = unlist(resp)
)

   dose resp
1    10 0.30
2    20 0.40
3    20 0.45
4    20 0.48
5    30 0.60
6    30 0.59
7    40 0.80
8    40 0.76
9    40 0.78
10   50 0.90


text:
Q: What should I learn next? I am self-studying statistics (I am a undergrad mathematician).
I learned all of my statistics from a mathematical statistics book based on measure theory. I learned (by "learned", I mean "read a book which contained one detailed chapter on this topic"):

*

*Estimation theory (MLE + other methods + asymptotic results)

*Hypotheses

*Confidence intervals

*Linear model (regression + classification)

*Mixed models

Where should I go next? I prefer books, and as I am an advanced math student, I am fine with high mathematical requirements. I prefer them, probably. Or maybe I should now take a more applied approach?
I also know programming in R and python, so that's ok as well.

A: I think the best way forward at this point is to decide where you want to specialize, start reading academic articles from the top journals, and familiarizing yourself with the methods you encounter. If you want to go medical, read the biostatistics journals like biometrika. If you want to go finance/econ, read econometrika.
Other topics in statistics

*

*Generalized linear models

*Stochastic processes and time series

*Bayesian probability and estimation

*Semiparametric estimation theory (Cox models, sandwich estimators, quasilikelihood)

*Nonparametric estimation theory (minimax, smoothing)

*Survival analysis

*Survey design

*Power analysis, simulation, and so on

Other great books
McCullogh & Nelder: Generalized Linear Models. Boos and Stefanski: Essential Statistical Inference. Wakefield: Frequentist and Bayesian Regression Models. Agresti: Categorical Data Analysis. Hosmer Lemeshow: Logistic Regression Models, Hosmer Lemeshow & May Survival Analysis. Diggle Heagerty Liang & Zeger: Longitudinal Data Analysis. Sheldon Ross: Probability Models. Ferguson: A Course in Large Sample Theory.

A: Partially answered in comments:
With all respect--many of us have extensive mathematical backgrounds--you haven't even begun to learn statistics. Your education is akin to trying to learn quantum mechanics by studying C∗ algebras. The analogy isn't a bad one: the mathematical study might prepare you to appreciate mathematical descriptions of physical experiments, but the next step would be to perform a set of classical lab experiments. Likewise, you shouldn't feel ashamed to begin exploring and analyzing simple datasets--and perhaps to study introductory stats textbooks to learn how. – whuber
I agree with both the analogy whuber makes, and the suggestion of looking at actually making contact with data (which is where the fun is). Theorems are important, there's no doubt of that, but they don't always help you figure out how and when to do what, what else you might do instead and how much practical difference the choice might make. They don't usually tell you what parts of a real problem are fine to abstract away and what parts really matter. Ultimately choosing what to learn next depends on what you want to be able to do, but that's hard without exploring the territory a bit first. – Glen_b
(  Other more specific advice left in the comments  )


text:
Q: System.Text.Json.JsonException: 'F' is an invalid start of a value. (sockets in C#) im trying to make a program where you have client and server connected with a socket in C# .net 5.0.
In the beginning it works sending objects over a socket but after a while I get this error:
Unhandled exception. System.Text.Json.JsonException: 'F' is an invalid start of a value. Path: $ | LineNumber: 0 | BytePositionInLine: 0.
 ---> System.Text.Json.JsonReaderException: 'F' is an invalid start of a value. LineNumber: 0 | BytePositionInLine: 0.
   at System.Text.Json.ThrowHelper.ThrowJsonReaderException(Utf8JsonReader& json, ExceptionResource resource, Byte nextByte, ReadOnlySpan`1 bytes)
   at System.Text.Json.Utf8JsonReader.ConsumeValue(Byte marker)
   at System.Text.Json.Utf8JsonReader.ReadFirstToken(Byte first)
   at System.Text.Json.Utf8JsonReader.ReadSingleSegment()
   at System.Text.Json.Utf8JsonReader.Read()
   at System.Text.Json.Serialization.JsonConverter`1.ReadCore(Utf8JsonReader& reader, JsonSerializerOptions options, ReadStack& state)
   --- End of inner exception stack trace ---
   at System.Text.Json.ThrowHelper.ReThrowWithPath(ReadStack& state, JsonReaderException ex)
   at System.Text.Json.Serialization.JsonConverter`1.ReadCore(Utf8JsonReader& reader, JsonSerializerOptions options, ReadStack& state)
   at System.Text.Json.JsonSerializer.ReadCore[TValue](JsonConverter jsonConverter, Utf8JsonReader& reader, JsonSerializerOptions options, ReadStack& state)
   at System.Text.Json.JsonSerializer.ReadCore[TValue](Utf8JsonReader& reader, Type returnType, JsonSerializerOptions options)
   at System.Text.Json.JsonSerializer.Deserialize[TValue](String json, Type returnType, JsonSerializerOptions options)
   at System.Text.Json.JsonSerializer.Deserialize[TValue](String json, JsonSerializerOptions options)
   at LibClient.SimpleClient.start() in C:\Users\---\OneDrive\Documenten\GitHub\Courses\Networking\DistLibrary\LibClient\Client.cs:line 134
   at LibClientSimulator.ClientsSimulator.startSimulation() in C:\Users\---\OneDrive\Documenten\GitHub\Courses\Networking\DistLibrary\LibClient\Program.cs:line 62
   at LibClientSimulator.Program.Main(String[] args) in C:\Users\---\OneDrive\Documenten\GitHub\Courses\Networking\DistLibrary\LibClient\Program.cs:line 100

this is the client
while (true)
{
    int b = clientSocket.Receive(buffer);
    data = Encoding.ASCII.GetString(buffer, 0, b);
    Message message = JsonSerializer.Deserialize<Message>(data);   //Error happens here

    if(data != null)
    {
        if(message.Type == MessageType.Welcome)
        {
            Console.WriteLine("Hello");
            Console.WriteLine($"Message From Server: {message.Type}");
            message.Type = MessageType.BookInquiry;
            message.Content = bookName;

            jsonString = JsonSerializer.Serialize(message);
            msg = Encoding.ASCII.GetBytes(jsonString);

            clientSocket.Send(msg);
        }
    }
}

And this is the line in the server side which triggers the error:
Message message = JsonSerializer.Deserialize<Message>(data);
//Message messageFromBookhelper = JsonSerializer.Deserialize<Message>(databookhelper);

if (message.Type == MessageType.Hello)
{
    Console.WriteLine($"{message.Content}");
    Console.WriteLine($"Message from Client: {message.Type}\n");
                        message.Type = MessageType.Welcome;
                        message.Content = "";
    msg1 = Encoding.ASCII.GetBytes(JsonSerializer.Serialize(message));
    newSock.Send(msg1);
}
else if(message.Type == MessageType.BookInquiry)
{
    Console.WriteLine($"Book requested from client: {message.Content}");
    RequestedBook = message.Content;
    Booksock.Connect(BookHelperEndpoint);
    message.Type = MessageType.BookInquiry;
    message.Content = RequestedBook;
    msg1 = Encoding.ASCII.GetBytes(JsonSerializer.Serialize(message));
                        Booksock.Send(msg1);
                        int b1 = Booksock.Receive(buffer);
    databookhelper = Encoding.ASCII.GetString(buffer, 0, b1);

    Message messageFromBookhelper = JsonSerializer.Deserialize<Message>(databookhelper);
    Console.WriteLine(databookhelper);
    BookData bookdata = JsonSerializer.Deserialize<BookData>(messageFromBookhelper.Content);
    string bookdataJSON = JsonSerializer.Serialize<BookData>(bookdata);
    Console.WriteLine($"Book from Bookhelper: {bookdataJSON}");

//THIS LINE GIVES ERROR
    message.Type = MessageType.BookInquiryReply;
    message.Content = "Hey";
    msg1 = Encoding.ASCII.GetBytes(JsonSerializer.Serialize(message));
    newSock.Send(msg1);
}

data = null;
newSock.Send(msg);

Other messages are fine when it is being sent but when I am sending this last message it suddenly gives that error. I don't know why.
This is what is being received apparently on client through the variable 'data': {"Type":2,"Content":"Hey"}From server: Your message delivered


text:
Q: Knockout onpaste event I was wondering if there is a way to do this fiddle http://jsfiddle.net/ult_combo/HzkCw/1/ in knockout?
I am struggling to get the pasted value on the event.  I am abble to trigger it using
self.onScan = function (d, e) {
            var inputDate = e;
            setTimeout(function () {
                var theData = inputDate.target.value;
                console.log(theData );
            }, 100);

        };

and the element is binded by
data-bind="event:{ onpaste: onScan }

but just fail to get the value.  Even tried to bind the value to an observable but no luck.

A: You can get access to pasted text from clipboard that provided with event.

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

    self.pastedText = ko.observable("Start");

    self.onPaste = function (vm, event) {
        var text = event.clipboardData.getData("text/plain");
        self.pastedText(text);

        // Indicate that text could be added into textbox
        return true;
    }
}

ko.applyBindings(new ViewModel());

  <input type="text" placeholder="Paste text" data-bind="event:{ paste: onPaste }">

A: As a small addition to, Romaniuk's question, KnockoutJS makes its own event to pass in, which doesn't have the clipboardData variable in it. To reach the clipboardData, you need to access originalEvent.clipboardData:
self.onPaste = function (vm, event) {
    var text = event.originalEvent.clipboardData.getData("text/plain");
    self.pastedText(text);

    // Indicate that text could be added into textbox
    return true;
}


text:
Q: Loopback 4: Defining property in model as array I have a user model with a property addresses:
@property.array(Address)
addresses: Array<Address>;

But I get an error:
Cannot start the application. Error: "items" property must be present if "type" is an array

According to Loopback documentation, I do not need to do anything else.
Any idea what is missing?

A: We usually don't declare arrays with Array type. The below code works for us. Try it out.
@property.array(Address)
addresses?: Address[];

A: Loopback 4 (lb4)-
I had a requirement of creating a model property which would be an array of array. I tried to generate this property using lb4 CLI but I was not prompted for an array item type so I chose any.
The generated code was something like this-
@property({
  type: 'array',
  itemType: 'any'
})
extraInfo?: any[];


text:
Q: Missing dynamic Markers GMaps V3 I have written some code to fetch zipcodes from a mysql db via ajax call, geocode them, then make markers out of them on a GMap.  The markers are clickable to reveal some demographic data.  It works if i leave the alert in the each loop uncommented.  If not it only shows about 8 markers.  Any and all help is appreciated.  Relevant code:
function initialize() {
var geocoder = new google.maps.Geocoder();
var markers = [];
var latlng = new google.maps.LatLng("33.7463915", "-117.86044720000001");
var myOptions = {
    zoom: 11,
    center: latlng,
    mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

$.ajax({
    url: 'getzips.php',
    dataType: 'json',
    success: function (data) {
        $.each(data.rows, function(i, item) {
                //alert(item.zip);
                if (geocoder) {
                    geocoder.geocode({ 'address': item.zip }, function (results, status) {

                    if (status == google.maps.GeocoderStatus.OK) {
                        var latlng = new google.maps.LatLng(results[0].geometry.location.lat(), results[0].geometry.location.lng());
                        var marker = new google.maps.Marker({
                            position: latlng,
                            map: map,
                            title: item.zip
                            });
                        var infowindow = new google.maps.InfoWindow({
                            content: item.zip
                        });
                        google.maps.event.addListener(marker, "click", function() {
                            $.ajax({
                                url: 'getinfo.php?zipcode=' + marker.title,
                                success: function(data){
                                  infowindow.setContent(data);
                                  infowindow.open(map, marker);
                                }
                             });
                        });
                        markers.push(marker);
                    }
                    });
                }
                else
                    alert("geocode error");
            });
        }
    });
    //alert(markers.length);
}

A: Google Geocoding API has both query and rate limits. You need to slow down when querying.

Use of the Google Geocoding API is subject to a query limit of 2,500 geolocation requests per day.
Additionally, we enforce a request rate limit to prevent abuse of the service.


text:
Q: Include additional fields with Person Site Column When I create a column of type Lookup, there is a section at the bottom labeled "Add a column to show each of these additional fields:"  I want to do this same thing with a Person column.
It seems like this should be possible, per the MSDN SPFieldUser inherits from SPFieldLookup.  The Field Schema indicates that User is a specialized Lookup.
Is this possible?
I've thought about adding Text columns to my list, then creating a workflow to populate the values.  However, if the user profile is updated after the workflow runs, then my list will be out of date.
I really don't care if these values are on my list forms, but I need to be able to display them on a view.

A: Although SPFieldUser does inherit from SPFieldLookup and it really is a lookup field to the hidden "Users" list I don't think there is any way to display those additional fields via the UI.
The workflow idea will work as long as you make sure to trigger the workflow when an item is added and when an item is changed.
Another option would be to create a custom query for your view that will join to the Users list. This may not be trivial though as there is not much for documentation on the Users list.


text:
Q: SQL select output after inner join I have one problem.
I have 2 tables, and I performed an inner join on people id. Now I want that names of those people write. I tried this but it writes name of first on first and second.
SELECT g.id, g.idobject,
       p.name || ' ' || z.last as Per1,
       p.name || ' ' || z.last as Per2
    FROM
        grup g
           INNER JOIN people p on g.idper1=p.id
           INNER JOIN people p on g.iper2=p.id

A: When joining the same table twice, use different aliases.
For example:
SELECT g.id, g.idobject,
       concat(p1.name, ' ', p1.last) as Per1,
       concat(p2.name, ' ', p2.last) as Per2
    FROM
        grup g
           INNER JOIN people p1 on g.idper1=p1.id
           INNER JOIN people p2 on g.iper2=p2.id

A: Your code should fail.  You need different table aliases:
SELECT g.id, g.idobject,
       p1.name || ' ' || p1.last as Per1,
       p2.name || ' ' || p2.last as Per2
FROM grup g JOIN
     people p1
     ON g.idper1 = p1.id JOIn
     people p2
     ON g.iper2 = p2.id;

If you are indeed using MySQL, then the appropriate function is CONCAT() or better yet, CONCAT_WS():
SELECT g.id, g.idobject,
       CONCAT_WS(' ', p1.name, p1.last) as Per1,
       CONCAT_WS(' ', p2.name, p2.last) as Per2
FROM grup g JOIN
     people p1
     ON g.idper1 = p1.id JOIn
     people p2
     ON g.iper2 = p2.id;


text:
Q: C# How To Pass Linq Lambda Parameters to SwitchExpression And Receive Expression> in Lambda .Where(...) C# How To Pass Linq Lambda Parameters  to SwitchExpression And Return Expression To .Where(...) Lambda Linq Queryable
i write a linq Lambda query that Who i want use Func That Declare SwitchExpression in this And Use On where(p=>...)
in this code use predicat , It's like this :
model is :
public class FieldValue
    {
        public virtual int Id { get; set; }
        public virtual string Value { get; set; }
        public virtual int FieldId_fk { get; set; }
        public virtual int TAdvertiesId_fk { get; set; }
    }

var predicateItemTest = LinqKit.PredicateBuilder.True<FieldValue>().And(x => x.FieldId_fk == 2); //2 is digit for test
SwitchCase[] cases = new SwitchCase[] {
new SwitchCase[] { Expression.SwitchCase(Expression.Constant(predicateItemTest), Expression.Constant(2, typeof(int))) }
};

SwitchExpression _SwitchExpression = Expression.Switch(Value, Expression.Constant(LinqKit.PredicateBuilder.False<FieldValue>()), //Default Value
 cases);

SwitchCase_Predicate = Expression.Lambda<Func<int, Expression<Func<FieldValue, bool>>>>(_SwitchExpression, Value).Compile();

1) First Test :
var FilterResult = _FieldValue.Table.Where(p=>SwitchCase_Predicate(p.FieldId_fk).Compile()).ToList();

when call this method and who i want pass parameter to SwitchCase_Predicate(...) it has error because Return Type Is expression and should not pass Dynamic parameters.
if use like below worked but not allow pass parameter in .where(...) :
2) Second Test :
var FilterResult = _FieldValue.Table.Where(SwitchCase_Predicate(2).Compile()).ToList();

how to pass parameter in where(...) like "First Test" and return expression predicat for use in .where(...) correctly
Please help fix this problem.


text:
Q: What would cause getClass() != obj.getClass() not to be equal on identical objects I'm trying to compare two identical objects. When the page first loads, they are equal, however when I refresh the page a second time, the do not equal each other despite the data or object not changing.
What I'm doing.
I have a CurrentUser obj that I store in the user session at login. I use the currentUser to compare against the assignedUser of a form. If the currentUser.equals(pr.getAssignedUser()) then I enable access. AssignedUser is a hibernate variable reference to CurrentUser. If I remove getClass() != obj.getClass from my equals override and just use property comparisons, everything works fine.
The thing that concerns me most is it works on the first access, however it doesn't on a page refresh. Without knowing what is going on, I worry about a memory leak.
Does anybody know what might be going on here?
CurrentUserServiceImpl.class
@Scope(ScopeConstants.PERTHREAD)
public class CurrentUserServiceImpl implements CurrentUserServiceService {

    private final CrudDAO crudDAO;
    private CurrentUser currentUser;

    public CurrentUserServiceImpl(CrudDAO crudDAO) {
        this.crudDAO = crudDAO;
    }

    public Long getUserId() {
        return getUser().getId();
    }

    public CurrentUser getCurrentUser() {
        if (this.isUserExist() && applicationUser == null) {
            PersonProfile personProfile = (PersonProfile) SecurityUtils.getSubject().getPrincipal();
            currentUser = crudDAO.find(personProfile.getUid());
        }
        return currentUser;
    }

    public boolean isUserExist() {
        return SecurityUtils.getSubject().getPrincipal() != null;
    }
}

PurchaseRequisition.class
public PurchaseRequisition {

    @Inject
    private CurrentUserService currentUserService;

    @Inject
    private CrudDAO crudDAO;

    void setupRender() {
        CurrentUser currentUser = currentUserService.getCurrentUser();

        PurchaseReq pr = crudDAO.find(PurchaseReq.class, id);

        if(currentUser.equals(pr.getAssignedUser()) {
            System.out.println("equal");
        }
    }
}

A: Hibernate creates proxy classes using CGLib or javassist. Hence getClass() can't work. Use instanceof instead.
This answer has an alternative solution: https://stackoverflow.com/a/1139992/342852

A: It can only be when objects classes are loaded with different class loaders:
class TestClassLoader extends URLClassLoader {
...

class Test1 {

    public static void main(String[] args) throws Exception {
        Object obj1 = new TestClassLoader().loadClass("test.Test1").newInstance();
        Object obj2 = new TestClassLoader().loadClass("test.Test1").newInstance();
        System.out.println(obj1.getClass() == obj2.getClass());
    }
}

this will print false
But if obj1 == obj2 then obj1.getClass() == obj2.getClass() always.


text:
Q: java sample rest program i was trying sample rest server application.
i was getting 404 every time i try to access the server.
code detail:-
Application(war) name :- Rest
Service class:
package com.sandeepjn.rest.service;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.core.Response;
@Path("/services")
public class EmployeeService {
    @GET
    @Path("/{param}")
     public Response sayHello() {
        String str ="working";
        return Response.status(200).entity(str).build();
    }
}

Web-inf:-
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
    <display-name>Rest</display-name>
    <servlet>
        <servlet-name>jersey-servlet</servlet-name>
        <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
        <init-param>
            <param-name>jersey.config.server.provider.packages</param-name>
            <param-value>com.sandeepjn.rest.service</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>jersey-servlet</servlet-name>
        <url-pattern>/rest/*</url-pattern>
    </servlet-mapping>
</web-app>

URl used for testing:-
http://localhost:8080/Rest/rest/services/data

Using this i am always getting 404.


text:
Q: Creating new pandas column from weighted values in other columns I'm trying to create a new column by totalling the weighted values in earlier columns.
example
 v1    v2   v3
  1    2    3
  4    3    6
  3    2    1

weights = [0.801,0.796,0.637]

I would like to multiply v1 by weights[0], then v2 by weights[1] etc and create a new column that is the total of these operations
so that the output would be
 v1       v2      v3    v_tot
0.801   1.592   -1.911  0.482
3.204   2.388   -3.822  1.77
2.403   1.592   -0.637  3.358

I have tried reating a new df
data2 = data3.mul(weights_a)

and this works, but when I try to create a new column
data2['v_tot'] = data2.loc[:,:].sum()

the new column is created but it's full of nan values.
can anyone offer some advice?

A: (not sure why are there negative values in v3)try:
df_new=df.mul(weights,axis=1)
df_new['v_tot']=df_new.sum(axis=1)
print(df_new)

      v1     v2     v3  v_tot
0  0.801  1.592  1.911  4.304
1  3.204  2.388  3.822  9.414
2  2.403  1.592  0.637  4.632

A: s = """
 v1    v2   v3
  1    2    3
  4    3    6
  3    2    1
"""
df = pd.read_csv(pd.compat.StringIO(s), delim_whitespace=True)

weights = [0.801,0.796,0.637]

df['v_tot'] = (df * weights).sum(axis=1)
df

Output:
   v1  v2  v3  v_tot
0   1   2   3  4.304
1   4   3   6  9.414
2   3   2   1  4.632

P.S. And if you want to have a DataFrame with weighted values as well:
dfw = df * weights
dfw['v_tot'] = dfw.sum(axis=1)
dfw

Output:
      v1     v2     v3  v_tot
0  0.801  1.592  1.911  4.304
1  3.204  2.388  3.822  9.414
2  2.403  1.592  0.637  4.632

A: Try:
data2['v_tot'] = data2.sum(axis=1)


text:
Q: Given a vector normal to a plane, how to find two vectors parallel to the plane? I understand that I can find the normal vector by using cross product on the two vectors parallel to the plane, but I can't seem to find anywhere that tells me how to do it in reverse, and using the cross product formulas and methods are extremely messy, slow, and prone to error.
How would I find the two parallel vectors quickly and efficiently?

A: Let's assume we're working in $\mathbb R^3$ and the plane is $$ax+by+cz+d=0.$$ A normal vector to the plane is $[a,b,c].$ If $c \ne 0$ then $[0,-c,b]$ and $[-c,0,a]$ are two linearly independent vectors perpendicular to $[a,b,c]$ and thus parallel to the plane $ax+by+cz+d=0.$

A: Given the normal vector $n=(a,b,c)$, a vector $v=(p,q,r)$ parallel to the plane is perpendicular to the normal vector and thus satisfies $n\cdot v=0$. If you put arbitrary values for $p,q$ and $c\ne0$ then $r=-\frac{pa+qb}c$ ensures $v$ is parallel to the plane; it should not take long to repeat this process (arbitrarily assuming two of $p,q,r$, then finding the third) to find two linearly independent parallel vectors. Just don't divide by zero.

However, in a sense, any formula for deriving vectors perpendicular to the normal vector, and hence parallel to the plane, must be messy. The hairy ball theorem guarantees that any continuous function $f:\mathbb R^3\to\mathbb R^3$ such that the input $v$ and output $w$ satisfy $v\cdot w=0$ must have some $v\ne\mathbf0$ for which $f(v)=\mathbf 0$, so you don't get a nontrivial parallel vector.

A: Assuming you are in dimension 3 (though it would also work in higher dimensions by changing "plane" to "hyperplane").
Let's call your vector $v$, and your plane $P$.
You know that $v \perp P$.
Let's call $v^\perp$ the space of vectors that are orthogonal to $v$. That space is of dimension 2. and $$P \subseteq v^\perp$$
But P is also of dimension 2. Thus $P = v^\perp$.
Now we need to find any two vectors that are in $v^\perp$. Ie we need any two vectors that are orthogonal to $v$. Ie we need $a$ and $b$ that verify
$$v^T a = 0$$
$$v^T b = 0$$
Those are linear equations (linear systems in the coordinates of a and b). You know how to solve them. In this case they have an infinity of solutions, you just need to pick any 2 that are not colinear


text:
Q: can i declare a variable with name Model i am trying to declare a variable in MVC model with the name "Model" and  use it in aspx view
i have written a sample code for this.
model:
public int id { get; set; }
public bool Model { get; set; }

view:
      <%@Page Language="C#" Inherits="System.Web.Mvc.ViewPage<MvcApplication1.Models.account>"  %>
      <% using (Html.BeginForm("modelsubmit","Home"))
      {%>
       <%: Html.EditorFor(x =>x.id) %>
       <%: Html.EditorFor(x =>x.Model) %>
Action :-

       var model = new account();
              model.id = 1;
               model.Model = true;
             return View(model);

Post Method:
[HttpPost]
public ActionResult modelsubmit(account acc)
{
    if(acc.Model == true){}
    return Json(null);
}

but it is throwing me error saying "parameter cannot be null".
it is  not throwing error  for  any other variables.
i am even specifying the value of variable while initializing the model.


text:
Q: building Equal Columns with space im trying to build 3 equal columns without using table option in html 5
result should be this:

but so far the result is that one of them doesnt look like the other 2 even with
same css for all 3

any ideas? also im using bootstrap template for this website

#refGan {
  display: inline-block;
  width: 193px;
  background-color: #F2F2F2;
  height: 378px;
  margin-right: 90px;
}

#refGan img {
  margin-left: auto;
  margin-right: auto;
  display: block;
  margin-bottom: 20px;
}

#refGan h3 {
  font-family: Miso;
  text-align: center;
  color: #A53D3E;
  font-weight: bold;
}

#refGan hr {
  width: 30px;
  position: center;
  color: #f00;
  background-color: #A53D3E;
  height: 5px;
}

#refGan p {
  font-family: 'Varela Round', sans-serif;
  font-size: 15px;
  color: black;
}

#refGan label {
  float: left;
  background: url(../pictures/button.png);
  background-repeat: no-repeat;
  background-size: 129px 30px;
  font-size: 12px;
}

רומנטיקה

    זה בדיוק איך שזה נשמע. בסדרות מסוג זה העלילה היא סביב זוג שמתאהבים. הז'אנר הזה מאוד פופולארי בקרב נערות צעירות וביפנית יש לו שם מיוחד: "שוג'ו".

                        לסדרות מומלצות

    אקשן

    ז'אנר קלאסי שמשלב בדרך כלל אומנויות לחימה וגיבור מרכזי אחד. הז'אנר הזה מאוד פופולארי בקרב נערים צעירים וביפנית יש לו שם מיוחד: "שונן".

                        לסדרות מומלצות

הרפתקאות

    הז'אנר המוכר מכולם! הוא אפילו חדר למדינות מעבר ליפן. כולל בתוכו סדרות כמו: הלב (מרקו) ונילס הולגרסון. מה שמאפיין אותו, כמובן, זה ההרפתקאות של הגיבור הראשי.

                        לסדרות מומלצות

A: Wrapping your sectons in a div

should fix your problem. But i made more changes to it to make it responsive also. That way you dnt need to hard code widths and margin.

#refGan {
    display: inline-block;
    width: 30%;
    background-color: #F2F2F2;
    height: 378px;
}

    #refGan img {
        margin-left: auto;
        margin-right: auto;
        display: block;
        margin-bottom:20px;
    }

    #refGan h3 {
        font-family: Miso;
        text-align: center;
        color: #A53D3E;
        font-weight: bold;
    }
    #refGan hr {
        width: 30px;
        position: center;
        color: #f00;
        background-color: #A53D3E;
        height: 5px;
    }
    #refGan p {
        font-family: 'Varela Round', sans-serif;
        font-size: 15px;
        color: black;
    }

    #refGan label {
        float: left;
        background: url(../pictures/button.png);
        background-repeat: no-repeat;
        background-size: 129px 30px;
        font-size: 12px;
    }

רומנטיקה

                        זה בדיוק איך שזה נשמע. בסדרות מסוג זה העלילה היא סביב זוג שמתאהבים. הז'אנר הזה מאוד פופולארי בקרב נערות צעירות וביפנית יש לו שם מיוחד: "שוג'ו".

                        לסדרות מומלצות

                        אקשן

                        ז'אנר קלאסי שמשלב בדרך כלל אומנויות לחימה וגיבור מרכזי אחד. הז'אנר הזה מאוד פופולארי בקרב נערים צעירים וביפנית יש לו שם מיוחד: "שונן".

                        לסדרות מומלצות

הרפתקאות

                        הז'אנר המוכר מכולם! הוא אפילו חדר למדינות מעבר ליפן. כולל בתוכו סדרות כמו: הלב (מרקו) ונילס הולגרסון. מה שמאפיין אותו, כמובן, זה ההרפתקאות של הגיבור הראשי.

                        לסדרות מומלצות

A: if you are using bootstrap
replace your html code in

רומנטיקה

                    זה בדיוק איך שזה נשמע. בסדרות מסוג זה העלילה היא סביב זוג שמתאהבים. הז'אנר הזה מאוד פופולארי בקרב נערות צעירות וביפנית יש לו שם מיוחד: "שוג'ו".

                    לסדרות מומלצות

                    אקשן

                    ז'אנר קלאסי שמשלב בדרך כלל אומנויות לחימה וגיבור מרכזי אחד. הז'אנר הזה מאוד פופולארי בקרב נערים צעירים וביפנית יש לו שם מיוחד: "שונן".

                    לסדרות מומלצות

הרפתקאות

                    הז'אנר המוכר מכולם! הוא אפילו חדר למדינות מעבר ליפן. כולל בתוכו סדרות כמו: הלב (מרקו) ונילס הולגרסון. מה שמאפיין אותו, כמובן, זה ההרפתקאות של הגיבור הראשי.

                    לסדרות מומלצות

and delete this css code:
#refGan {
float: left;
width: 25%;
background-color: #F2F2F2;
height: 478px;
margin: 50px;

}


text:
Q: Implement Idisposable on mvc3 controller I have a controller that instantiates a database context for EF. (As I'm sure most that aren't implementing the repository pattern do.)
When I ran code analysis on my project it recommended implementing IDisposable so I wrote the following code.
    #region Implementation of IDisposable
    public void Dispose()
    {
        Console.WriteLine("Dispose");
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    // The bulk of the clean-up code is implemented in Dispose(bool)
    protected override void Dispose(bool disposing)
    {
        Console.WriteLine("Dispose(disposing)");
        if (disposing)
        {
            // free managed resources
            if (_dataService != null)
            {
                ((IDisposable)_dataService).Dispose();
                _dataService = null;
            }
            // free managed resources
            if (_db != null)
            {
                ((IDisposable)_db).Dispose();
                _db = null;
            }

        }
        base.Dispose(disposing);

    }
    #endregion

I've also tried doing.
protected new virtual void Dispose(bool disposing)

But my console.writeline statements never execute.  What am I doing wrong?  Why isn't Dispose() being called on my controller?

A: Personally I think the best thing to do in this situation is to split out the database context away from the controller and move it to a service layer. You can them make that class implement IDisposable and pass the reference to the service layer class to the controller to use it
In doing this you will create a controller that is not dependant on the database. The term skinny controllers, fat models applies here. the service layer will act as a model in this instance. You can also unit test the service layer and controller (if you want) in isolation from each other

A: you don't do anything wrong. You get the recommentation because you hold some fields in your class (cotnroller) that implements IDisposable. The framework will call the "overload"-version so just move all your code in there.
Details on MSDN
BTW you won't see the console-writeline - use System.Diagnostic.Debug.WriteLine instead


text:
Q: Projector of an eigenvector If I have an eigenvector $v$ and I want to find the associated projector of this eigenvector (orthogonal onto its subspace), am I right to say the projector is $P = vv^T$?
Does $P = vv^T$ only holds true for eigenvectors or does it holds true for any vectors?

A: You can build such a projector for an arbitrary vector (not necessarily an eigenvector of some matrix) but as Michael Burr points out you want to normalise $|v| = 1$. To see why it works consider the following:
Define $u' = P(v)u = vv^{T}u$ and consider its properties.

*

*$P(v)u' = v |v|^{2} v^{T}u = |v|^{2}vv^{T}u = |v|^{2}P(v)u$ which means that $P(v)^{2} = P(v)$ if the vector is normalised to unit length.

*$ v^{T}u' = v^{T}v\, v^{T}u = |v|^{2} \, v^{T}u$ so with the same normalisation we get $v^{T}u$ which is the projection of $u$ along $v$ as desired.

*if $w$ is orthogonal to $v$ then $w^{T}u' = w^{T}v  \,  v^{T}u = 0$ so $u'$ is orthogonal to vectors perpendicular to $v$.

Points 2 and 3 imply that $u'$ is parallel to $v$, and as such $u$ been projected oto $v$.


text:
Q: If $P(x)-2^n$ has a rational root for each $n\in\mathbb{N}$, is $P$ linear? Let $P(x)\in \mathbb{R}[x]$ satisfy the condition $P(x)=2^n$ has at least one rational root for each $n\in \mathbb{N}$.
Does it follow $P$ is linear?

A: I can prove this under the assumption that there exist infinitely many Mersenne primes!
If a polynomial of degree $n$ takes on $n+1$ different rational values for rational values of $x$, then by Lagrange interpolation it must in fact have rational coefficients. So we have $P(x) \in \mathbb{Q}[x]$.
By hypothesis there are rational numbers $r_n$ such that $P(r_n) = 2^n$. After replacing $P(x)$ with the polynomial $Q(x) = P(x + r_1) - 2$ and $sr_n$ with the sequence $s_n = r_n - r_1$, we have a rational polynomial $Q(x)$ and rational numbers $s_n$ with $s_1 = 0$ such that
$$Q(s_n) = 2^n - 2.$$
In particular, $Q(0) = 0$, so $Q(x)$ has constant term $0$. Let $m \in \mathbb{N}$ be the greatest common denominator among the coefficients of $Q(x)$, so that $R(x) = m Q(x)$ has integer coefficients with $\gcd = 1$. Then we have an integer polynomial $R(x) \in \mathbb{Z}[x]$ and rational numbers $s_n$ with $s_1 = 0$ such that
$$R(s_n) = (2^n - 2) m.$$
Write $R(x) = a_d x^d + \dots + a_1 x$. Then by the rational root theorem, $s_n$ must have numerator dividing $(2^n - 2) m$ and denominator dividing $a_d$.
Now assume that there are infinitely many Mersenne primes $M_p = 2^p - 1$. If we set $n = p + 1$ for $p$ the index of a Mersenne prime it follows that $s_{p+1}$ must have numerator dividing $2m M_p$. By picking $p$ large enough that $M_p > \sum |a_i| (2m)^i$ we can rule out the possibility that the numerator of $s_{p+1}$ divides $2m$, so it must be divisible by $M_p$. Since the denominator of $s_{p+1}$ divides $a_d$, it follows that $|s_{p+1}| \ge \frac{M_p}{|a_d|}$.
But this is incompatible with the growth rate of $R(x)$ unless $d = 1$. More precisely, if $r$ is sufficiently large then $R(r)$ grows at least as fast as $c_1 r^d$ for some constant $c_1$, meaning $R(s_{p+1}) \ge c_2 M_p^d$ for some constant $c_2 = \frac{c_1}{|a_d|^d}$, and taking $p$ sufficiently large this contradicts $R(s_{p+1}) = 2m M_p$ unless $d = 1$.
A slightly more careful version of this argument would be able to lower bound the complexity of a counterexample as a function of the size of the largest known Mersenne prime. According to Wikipedia, as of the time of writing the largest known Mersenne prime is
$$M_{82589933} = 2^{82589933} - 1$$
which is truly enormous.


text:
Q: How to reduce SSH2 "loading" time I'm using phpseclib to execute a command on my unix server via SSH2, the command is only doing ctrl + c (exiting the script, I don't really know how to say that, sorry) after like 15 seconds and so when I want to do a file_get_contents("api.php?param=test"); in PHP the page is loading during like 15 seconds (it's finishing loading after the script is finish/done).
So I would like to execute the command, and directly write something like "ok" after. I don't want this loading time.
PS: I'm doing it like that : https://hastebin.com/hoyulazeha.xml
Sorry, I'm not English.
Thanks in advance for help.

A: I added $ssh -> setTimeout(1); before $ssh -> exec($command); and it's stopping loading after 1 second, and the script is executing correctly.


text:
Q: Spring applicationContext.xml: Unable to locate Spring NamespaceHandler for XML schema namespace I use spring in my test to load mock 'categoryDAO' delcared in my testApplicationContext.xml file, but running test raises error:
java.lang.IllegalStateException: Failed to load ApplicationContext
...
Caused by: org.springframework.beans.factory.parsing.BeanDefinitionParsingException: Configuration problem: Unable to locate Spring NamespaceHandler for XML schema namespace [http://www.mockito.org/spring/mockito]
Offending resource: file [/Users/sebastien/dev/categorydao/target/test-classes/testApplicationContext.xml]

    at org.springframework.beans.factory.parsing.FailFastProblemReporter.error(FailFastProblemReporter.java:70)

Here is the test I run:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath*:**/testApplicationContext.xml"})
public class CategoryDAORetryTest {

    @Autowired
    CategoryDAO categoryDAO;

    @Test
    public void try_several_times() {
        when(categoryDAO.list(anyInt()))
        .thenThrow(new RuntimeException("Remote Exception 1"))
        .thenThrow(new RuntimeException("Remote Exception 2"))
        .thenReturn(Arrays.asList(new CategoryDTO()));

        assertThat(categoryDAO.list(SITE_EN_TGU_US, 10).size(), equalTo(1));
    }

    @Configuration
    @EnableRetry
    public static class SpringConfig {

    }
}

Here is some others informations related the dependencies I use:
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:mockito="http://www.mockito.org/spring/mockito"
    xsi:schemaLocation="
    http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.0.xsd
    http://www.mockito.org/spring/mockito classpath:META-INF/mockito.xsd
    http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <context:component-scan base-package="com" />

     <mockito:mock id="categoryDAO" class="com.purch.category.dao.CategoryDAO" />

    <mvc:annotation-driven />
</beans>

I have also file mockito.xsd to use mock anotation:
.
└── src
    ├── main
    │   ├── java
 ...
    │   └── resources
    │       └── hibernate.cfg.xml
    └── test
        ├── java
        │   └── com
        │       ├── purch
        │       │   └── category
        │       │       └── dao
        │       │           ├── CategoryDAORetryTest.java
        └── resources
            ├── META-INF
            │   ├── mockito.xsd
            │   ├── spring.handlers
            │   ├── spring.schemas
            │   └── spring.tooling
            └── testApplicationContext.xml

Here is the list of spring libraries I use in my pom.xml with "dep.version.spring" to "4.3.1.RELEASE":
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>${dep.version.spring}</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-core</artifactId>
    <version>${dep.version.spring}</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-web</artifactId>
    <version>${dep.version.spring}</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-test</artifactId>
    <version>${dep.version.spring}</version>
</dependency>

<dependency>
    <groupId>commons-beanutils</groupId>
    <artifactId>commons-beanutils-core</artifactId>
    <version>${dep.version.commons.beanutils}</version>
</dependency>
<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-core</artifactId>
    <version>${dep.version.hibernate-core}</version>
</dependency>
<dependency>
    <groupId>org.springframework.data</groupId>
    <artifactId>spring-data-jpa</artifactId>
    <version>1.9.4.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-c3p0</artifactId>
    <version>5.1.0.Final</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-aop</artifactId>
    <version>${dep.version.spring}</version>
</dependency>
<dependency>
  <groupId>org.springframework.retry</groupId>
  <artifactId>spring-retry</artifactId>
  <version>1.1.2.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjweaver</artifactId>
    <version>1.8.8</version>
</dependency>

The file mockito.xsd stored in my project is :
<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema xmlns="http://www.mockito.org/spring/mockito"
    xmlns:xsd="http://www.w3.org/2001/XMLSchema"
    xmlns:beans="http://www.springframework.org/schema/beans"
    targetNamespace="http://www.mockito.org/spring/mockito"
    elementFormDefault="qualified"
    attributeFormDefault="unqualified">

   <xsd:import namespace="http://www.springframework.org/schema/beans"
        schemaLocation="http://www.springframework.org/schema/beans/spring-beans.xsd"/>

   <xsd:element name="mock">
      <xsd:complexType>
         <xsd:complexContent>
            <xsd:extension base="beans:identifiedType">
               <xsd:attribute name="class" type="xsd:string" use="required"/>
               <xsd:attribute name="useStaticMap" type="xsd:boolean" default="false" />
            </xsd:extension>
         </xsd:complexContent>
      </xsd:complexType>
   </xsd:element>

   <xsd:element name="spy">
      <xsd:complexType>
         <xsd:attribute name="beanName" type="xsd:string" use="required"/>
      </xsd:complexType>
   </xsd:element>

</xsd:schema>

A: The import "springockito" was missing in my pom.xml!
<dependency>
   <groupId>org.kubek2k</groupId>
   <artifactId>springockito</artifactId>
   <version>1.0.4</version>
   <scope>test</scope>
 </dependency>


text:
Q: Long running ruby code How to prevent long running code in Rails application
Block of Rails code taking more time to process. How to daemonize block of code or run it in background.

A: I answered here - How to run ruby script asynchronous from rails controller?
Anyway, you can choose preferred for your tasks: https://www.ruby-toolbox.com/categories/Background_Jobs


text:
Q: The argument must be a React element, but you passed undefined I am trying to use ResponsiveContainer from recharts in a react and getting this error.

React.cloneElement(...): The argument must be a React element, but you passed undefined.

My Sample code:
import React from 'react';
import { ResponsiveContainer } from 'recharts';

function App() {
  return (
       <ResponsiveContainer>
       </ResponsiveContainer>
  );
}

A: You need to put a chart inside the container. ResponsiveContainer is not designed to work on its own, and will throw the error you're seeing if there is no child component.
Here's the example from the documentation:
<ResponsiveContainer width={700} height="80%">
  <AreaChart data={data}
    margin={{ top: 20, right: 30, left: 0, bottom: 0 }}>
    <XAxis dataKey="name" />
    <YAxis />
    <CartesianGrid strokeDasharray="3 3" />
    <Tooltip />
    <ReferenceLine x="Page C" stroke="green" label="Min PAGE" />
    <ReferenceLine y={4000} label="Max" stroke="red" strokeDasharray="3 3" />
    <Area type="monotone" dataKey="uv" stroke="#8884d8" fill="#8884d8" />
  </AreaChart>
</ResponsiveContainer>


text:
Q: Can two electrolytic capacitors be made into a bipolar? I know if you put an electrolytic capacitor backwards they explode and it's quite fun to observe them exploding. I am wondering if you can use two of them (and some diodes) to turn it into a bipolar capacitor so it may be used with AC signals?

A: Using two electrolytic capacitors of identical value back to back is routinely used to get a non-polarized capacitor.
From this document:

If two, same-value, aluminum electrolytic capacitors are
  connected in series, back-to-back with the positive terminals or the negative terminals connected, the resulting single capacitor is a non-polar capacitor with half the capacitance to either of the original pair. The two capacitors rectify the applied voltage and act as if they had been bypassed
  by diodes. When voltage is applied, the correct-polarity
  capacitor gets the full voltage.

You do not even need additional diodes. The equivalent model for an electrolytic capacitor is given below. Note the implicit diode in there.
.
When two such capacitors are connected back to back, the diodes will be in opposition to each other, blocking DC in both polarities.

On a contrary note, see also this answer to another related question on this site, where @Kortuk has a contrary opinion in the comments, against using normal electrolytic capacitors back to back.
While that viewpoint has been put forward in discussion, I have been unable to find any academic study substantiating the concern. That is not to say that such a study or reference does not exist.
I do find several references to applying normal back to back capacitors for non-polarized functioning, and have used this myself for many years in various designs, with never a single failure. The only caveat I adhere to, is to not approach within shouting distance of the rated voltage for each of the capacitors, if using them this way.

A: Yes. You can.
Connect in the following manner
--|(--)|--
Short both the -ve terminals. The other two +ve terminals can be used as leads of a non-polar capacitor.
I know that if you do like this the capcitance will reduce. I thinks it by 1/2.