text:
Q: Why is VNC on Windows so slow? In a test, I could stream a full HD movie across our network from my friend's computer, no problem.
It's as fast as I could want.
But VNC is painfully slow. We've tried Real VNC and Tight VNC, I've played around with the Capture Method settings, but nothing seems to make a difference; it's just so slow.
Does anyone have any tips on using VNC, on how to improve the speed, or perhaps any alternatives?
Is it the nature of not being able to notice invalidated portions of the screen quickly enough, or is there a network thing slowing it down perhaps?
We are both using Windows 7.
We need to be able to view and control each other's PCs without locking out the host, so RDP will not work (unless someone knows otherwise).

A: The absolute fastest VNC variant I've ever used is UltraVNC with the Video Mirror Driver installed.  RDP is still noticeably faster, but it's not nearly as bad.
I've also heard really good things about ZeroRemote, but never tested it.  It appears that TrueRemote is its successor.

A: VNC is just plain inefficient. VNC works pretty much by taking a series of screenshots, compressing them, and slinging them across the network
On Windows, RDP will give you better performance, but you need professional or better on the server/source end for proper RDP I believe.
wierdly remote assistance may work better for your needs -its RDP with both the user at the terminal, and the user at the remote system seeing the same screen
EDIT: 4 years on, I'm using nomachine for similar tasks - would work across OSes, and does a few other useful things.

A: If you're trying to watch video across a LAN, the fastest solution in terms of sheer screen-drawing speed is probably Radmin.

A: VNC is not comparable to video streaming. In video streaming you typically transfer a pre-compressed video stream via the network. For HD streams it's often H.264 encoded.
If you use VNC then your host computer has to take screen snapshots and compress them before sending them on to the network. There are several constraints here:

*

*Strong compression needs a lot of CPU power. For example encoding a 90 minutes movie in H.264 in high quality often takes more than 4 hours compression time on my Athlon X2 4450e server. Usually such strong compression is unsuitable for real-time applications like remote control.

*Less strong compression in turn will require more network bandwidth which might become an issue on low-bandwidth connections like the internet.

Well, there are a couple of "tricks" which are applied by video codecs and remote control and screen-sharing utilities. First of all they try to detect the screen changes and transfer the (compressed) image of the changes only. This usually saves A LOT of bandwith and processing power. However for full-screen video transfer it does not help a lot since the whole screen has to be re-transferred too often.
As written above current machines will probably be unable to rel-time encode your screen content in Full-HD and stream it to a remote-control application since your host will have to decode the video content and then re-encode the raw images before sending them to the network. Some older Dual-Core machines are even at the limit when decoding Full-HD video content. Not even speaking about having to re-encode the Full-HD images on screen again before sending them to the VNC client.
To improve your VNC remote-control speed you can do the following:

*

*Most VNC servers/clients support multiple compression algorithms. Some of them are optimized for small bandwidth, some for good image quality and some for low latency. This touches another aspect of remote control. Since the service is interactive latency matters (you don't want to see the reaction to a mouse click just after 5 minutes of encoding).

*Try to reduce the amount of screen changes on your host machine. For example try disabling Windows desktop effects, animations etc. This saves bandwitdth as only changed parts of the screen are transferred over network.

*Try disabling further visual effects on the host like transparency. Transparent Windows as used by Vista/Win7 reduce the "compressability" of images. Uni-colored/"flat" areas are much more efficient to compress than vibrant colors and fancy details. So disabling Aero transparency and desktop effects really speed up remote control experience. Most remote control tools even allow to disable such effects automatically on connect (e.g. Microsoft RDP and some VNC implementations).

*Same applies to background pictures. Try using uni-colored background setting instead of HD pictures.

Another issue for VNC is that it has to detect the changes on your screen. Some VNC implementations do "dumb" screenshots and compare them to the previous screenshot to detect changes. This is taking a lot of power already.
Some more advanced implementations work with special display drivers (check UltraVNC) which are more efficient here but require special drivers to be installed.
Of course all this does not help if you're playing a video on your host machine. In this case VNC will have to re-encode ~30 full-screen images per second and send it via network. On most compressions which can be performed in real-time by todays CPUs such a stream would take > 8Mbps of bandwidth. So it's unsuitable for most internet connections (especially think about asymmetric DSL connections with typically less than 1Mbps upload speed, and yes, it's upload speed which matters on host side).
It might be suitable for LAN use, but here you should probably more think about setting up a media server or share your media using DLNA/UPnP media server (even Win7 media player can do this). Then use a DLNA client to play the shared media.

A: As @Journeyman Geek says, VNC is inefficient.  This is by design so that VNC doesn't have to "understand" what the remote client is trying to display.
RDP actually does, so it can take shortcuts and render images faster.  RDP tells the other end, for example, "client opened a window at this location" instead of sending the bitmap data representing the screen change.
There are "terminal server" hacks out there that will add RDP capability to the versions of Windows that don't feature them, but I don't officially recommend them and you use these at your own risk.  However, I think even the "Starter" versions of Windows 7 come with "Remote Assistance" (msra.exe) which you might try using.
Things you can do to improve VNC performance, however, include lowering the display depth to 8 bits, lowering the resolution of the client screen, and using client-side bitmap caching.  That means VNC has to ship less data on the wire and you'll experience better performance (but it won't look pretty).

A: For me, even over internet (with ping rates > 50ms and decent bandwithd > 1mbit/s) I get very good behavior on UltraVNC. The magic comes with changing the connection settings.
After starting the viewer, go to "Connection Options", disable "Auto select best settings", enable "Tight" and lower the "Jpeg" to lower quality, if needed (2-4 works well).
That is the only way I know of of gting Full Colors with decent performance.
You will get several fps afterwards, enough to get a fast slideshow on a full screen movie (enough for everything I am doing, including remote development, for real movie watching too slow and also there is no audio).
Also, in server "Properties", it helps to have (if not using mirror driver which greatly helps performance) to have "Poll Full Screen", "Poll Foreground Window", "Poll Window Under Cursor", "System HookDll", "Low Accuracy" turned on. Basically, just about everything on the left.

A: If you are looking for performance you need to not use VNC, Try something like LogMeIn. It's free and works well.

A: You may also try TeamViewer, it's free for non-commercial use and was fairly fast for me. I've not tested it on HD video though.


text:
Q: Libreboot: Can I make ROMs on a powerful computer and then flash using RspberryPi I will be trying to flash LibreBoot (a particular coreboot downstream) on to a thinkpad T440p. Even with libreboot - instructions are quite complex, but look entirely doable. There is one thing, however - I cannot be sure if I can make the boot roms using lbmk on a relatively powerful linux computer (running manjaro/arch) and then flash using RaspberryPi, or must I make the roms on the raspberrypi that I will be using for flashing (with a SOIC-8 clip).
Intuitively I think there should be no problem, but I just don't know this area.
Perhaps someone who understands this better, or who has done libreboot flashing could explain this?

A: OK, the answer is easy enough. Yes. Firstly - as there are several distributions of coreboot (e.g. skulls) that ship pre-built roms - yes you can do that. Secondly - I like the quote from someone who built coreboot on their Thinkpad X230 Eric Holzbah: "Coreboot highly recommends using their patched tool chain to build coreboot roms. Don't bother trying to build the roms on your Pi. It will take forever and oom-killer may get to it. I used make nconfig to select coreboot options. Here is my configuration..."
What can I say - fiddling with Pomona clips and raspberry is quite an experience and it surely is fun and well worth it when it works :-).

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I manually highlight an NSPopUpButtonCell when drawing it (draw it using white instead of black)? I've got a custom cell composed out of several cells, one of which is an NSPopUpButtonCell.
When drawing my custom cell highlighted, I want to cause all the sub-cells to highlight as well (typically by turning white).
With, for example an NSTextCell, if I call setHighlighted:YES before calling drawWithFrame:inView the cell will be drawn with white text, exactly as I want it.
This does not work with NSPopUpButtonCells. The text just continues to draw as black.
It seems like this should be possible, since dropping an NSPopUpButtonCell into an NSTableView highlights properly.
Can somebody point me in the right direction for fixing this?

A: Where are you hosting this custom+composite NSCell subclass?
-setHighlighted:YES isn't what you are looking for. From the documentation:

By default, this method does nothing.
  The NSButtonCell class overrides this
  method to draw the button with the
  appearance specified by
  NSCellLightsByBackground,
  NSCellLightsByContents, or
  NSCellLightsByGray.

Typically the host view for a cell will set the cell's background style, and the cell will use that at draw time to display itself appropriately. Propagate the background style from the master cell to the sub-cells.
- (void)drawInteriorWithFrame:(NSRect)cellFrame inView:(NSView *)controlView
{
    NSRect textRect, popUpRect;
    NSDivideRect(cellFrame, &textRect, &popUpRect, NSWidth(cellFrame) / 2, NSMinXEdge);

    /* Draw the text cell (self) */
    [super drawInteriorWithFrame: textRect inView: controlView];

    /* Draw our compound popup cell - create & release every time drawn only in example */
    NSPopUpButtonCell *popUpCell = [[NSPopUpButtonCell alloc] initTextCell: @"popup title"];
    [popUpCell setBordered: NO];
    [popUpCell setBackgroundStyle: [self backgroundStyle]];
    [popUpCell drawWithFrame: popUpRect inView: controlView];
    [popUpCell release];
}

If you are hosting this composite cell in an NSTableView, that should be sufficient to get the correct background for selected rows.
If you are hosting this in your own view, you may need to do additional work. (And need to provide additional details about the host environment before we can offer advice.)


text:
Q: Search-AzGraph -Query "Resources | summarize count()" equivalent on GCP? I need to find equivalent of Azure Search-AzGraph -Query "Resources | summarize count()" equivalent on GCP.
So far I only found gcloud asset search-all-resources https://cloud.google.com/asset-inventory/docs/searching-resources-samples#use_case_count_all_the_cloud_resources_by_asset_type_and_location but it returned only lists. I need only counter.  Is there some easy way that I missed?


text:
Q: Add or modify a nullptr Vector from a partially filled flatbuffer? This builds off of the monster schema example. If I partially fill a flatbuffer such as in the official test.cpp.
Relevant lines also copied below
// Create a mostly empty FlatBuffer.
flatbuffers::FlatBufferBuilder nested_builder;
auto nmloc = CreateMonster(nested_builder, nullptr, 0, 0,
                           nested_builder.CreateString("NestedMonster"));
FinishMonsterBuffer(nested_builder, nmloc);

How can I modify the inventory part of the schema from nested_builder after already calling FinishMonsterBuffer(nested_builder, nmloc);?
Things I've tried (related to test.cpp):
std::string bfbsfile;
bool found = flatbuffers::LoadFile( "./monster_schema.bfbs", true, &bfbsfile );
const reflection::Schema& schema = *reflection::GetSchema( bfbsfile.c_str() );
auto root_table = schema.root_table();

auto fields = root_table->fields();

// The above works fine I've tested the fields and verified the schema.
// I'm unsure of the code below.

// First we put the FlatBuffer inside an std::vector.
std::vector<uint8_t> resizingbuf(
    nested_builder.GetBufferPointer(),
    nested_builder.GetBufferPointer() + nested_builder.GetSize());
// Get the root.
// This time we wrap the result from GetAnyRoot in a smartpointer that
// will keep rroot valid as resizingbuf resizes.
auto rroot = flatbuffers::piv(flatbuffers::GetAnyRoot(resizingbuf.data()),
                              resizingbuf);
// Now lets try to extend a vector by 100 elements (0 -> 110).
auto &inventory_field = *fields->LookupByKey("inventory");
// I don't think this works either if it doesn't already exist.
auto rinventory = flatbuffers::piv(
     flatbuffers::GetFieldV<uint8_t>(**rroot, inventory_field), resizingbuf);

// This line silently fails probably because *rinventory is probably a nullptr
// but I don't know how to set it after having already
// called FinishMonsterBuffer(nested_builder, nmloc);.
flatbuffers::ResizeVector<uint8_t>(schema, 110, 50, *rinventory,
                                   &resizingbuf);
// Try to print it but prints nothing.
// printf("%hhu", rinventory->Get(10));

Apologies in advance for the title I'm not quite sure how to phrase the exact problem or question.
Let me know if more context is needed or part of the question doesn't make sense.

A: Disclaimer: Flatbuffers doesn't generally allow mutating a vector after the buffer has been finished. However, we do have some advanced APIs in the reflection API for doing such mutations, but are generally slow and not recommended.
We don't support the case of resizing a null vector. We store null within the vtable and there is no data/size information in the buffer related to a null vector. Therefore there is nothing to resize.
You may try inserting a empty vector instead, as that should place the necessary data/size information into the buffer that can be later resized.


text:
Q: Make bootstrap modal utilize seperate form/sql table I have a form that alters a sql table called "invoices".  I want to popup a bootstrap modal that will alter a sql table called "customers".   Right now, the only thing that is saved properly is the customer name... am I missing something? Here is the code I have so far...
main page :

            <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Add New Customer

            <form action="<?php echo $_SERVER['PHP_SELF']; ?>" id="add_customer_form" method="post" class="form-horizontal myaccount" role="form">

                    Customer Name (Last Name, First Name)
                    <input type="text" class="form-control" id="customer_Name_modal" name="customer_Name_modal" placeholder="Last Name, First Name">

                    Phone Number (555-555-5555)
                    <input type="text" class="form-control" id="customer_Phone_modal" name="customer_Phone_modal" placeholder="555-555-5555">

                    Email (johndoe@gmail.com)
                    <input type="text" class="form-control" id="customer_Email_modal" name="customer_Email_modal" placeholder="john@doe.com">

                    Address Line 1
                    <input type="text" class="form-control" id="customer_Address1_modal" name="customer_Address1_modal" placeholder="">

                    Address Line 2
                    <input type="text" class="form-control" id="customer_Address2_modal" name="customer_Address2_modal" placeholder="">

            <input type="hidden" id="current_element_id">
        </form>

            <button type="button" id="add_new_customer_btn" class="btn btn-primary" data-loading-text="Saving Customer...">Save changes</button>
            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

Form Save Code :
var save_new_customer = function(){

    $('#add_new_customer_btn').button('loading');

    data = {
            customerName : $('#customer_Name_modal').val(),
            customerPhone : $('#customer_Phone_modal').val(),
            customerEmail : $('#customer_Email_modal').val(),
            customerAddress1 : $('#customer_Address1_modal').val(),
            customerAddress2 : $('#customer_Address2_modal').val(),
    }

    $.ajax({
         url: "ajax.php",
         dataType: "json",
         method: 'post',
         data: {
            data : data,
            type: 'saveNewCustomer'
         },
         success: function(result){
            if( (typeof result.success !== "undefined") && result.success ){

                $("html, body").animate({ scrollTop: 0 }, "slow");
                $('#add_new_customer_btn').button('reset');

                $('#addNewCustomer').modal('show');
                element_id = $('#current_element_id').val();
                $('#customerName_'+element_id).val($('#customer_Name_modal').val());
                $('#phone_'+element_id).val( $('#customer_Email_modal').val() );
                $('#email_'+element_id).val($('#customer_Phone_modal').val());
                $('#addressLine1_'+element_id).val($('#customer_Address1_modal').val());
                $('#addressLine2_'+element_id).val($('#customer_Address2_modal').val());

                $('#add_customer_form')[0].reset();
                $('#add_customer_form').find("div.form-group").removeClass('has-success');
                $('#message_h1').show();
                message('success', CUSTOMER_ADD_SUCCESS);
            }else{
                message('fail', CUSTOMER_ADD_FAIL);
            }
        }
     });

}

Sql Code :
if(isset($_POST['type']) && $_POST['type'] == 'saveNewCustomer' ){
    $res = array();
    $res['success'] = false;

    if(!isset($_POST['data']) || empty($_POST['data'])){
        echo json_encode($res);exit;
    }
    $data = $_POST['data'];

    $customerName = mysqli_real_escape_string( $db->con, trim( $data['customerName'] ) );
    $customerPhone = mysqli_real_escape_string( $db->con, trim( $data['phone'] ) );
    $customerEmail = mysqli_real_escape_string( $db->con, trim( $data['email'] ) );
    $customerAddress1 = mysqli_real_escape_string( $db->con, trim( $data['addressLine1'] ) );
    $customerAddress2 = mysqli_real_escape_string( $db->con, trim( $data['addressLine2'] ) );

    $uuid = uniqid();
    $result['operation'] = 'insert';
    $query = "INSERT INTO customers (id, customerName, phone, email, addressLine1, addressLine2, uuid)
            VALUES (NULL, '$customerName', '$customerPhone', '$customerEmail', '$customerAddress1', '$customerAddress2', '$uuid');";

    if(mysqli_query($db->con, $query)){
        mysqli_close($db->con);
        $res['success'] = true;
    }
    echo json_encode($res);exit;

}

A: You're using the wrong key in PHP
You're calling these keys:
$customerName = mysqli_real_escape_string( $db->con, trim( $data['customerName'] ) );
$customerPhone = mysqli_real_escape_string( $db->con, trim( $data['phone'] ) );
$customerEmail = mysqli_real_escape_string( $db->con, trim( $data['email'] ) );
$customerAddress1 = mysqli_real_escape_string( $db->con, trim( $data['addressLine1'] ) );
$customerAddress2 = mysqli_real_escape_string( $db->con, trim( $data['addressLine2'] ) );

but you should be calling:
$customerName = mysqli_real_escape_string( $db->con, trim( $data['customerName'] ) );
$customerPhone = mysqli_real_escape_string( $db->con, trim( $data['customerPhone'] ) );
$customerEmail = mysqli_real_escape_string( $db->con, trim( $data['customerEmail'] ) );
$customerAddress1 = mysqli_real_escape_string( $db->con, trim( $data['customerAddress1'] ) );
$customerAddress2 = mysqli_real_escape_string( $db->con, trim( $data['customerAddress2'] ) );

To fix this just copy and paste (replace) the variable assignment in the SQL code.


text:
Q: How to make sure that launch screen is being displayed Even after adding Thread.sleep(forTimeInterval: 3.0) to appdelegate.swift which I found in another thread, the launch screen of my app is not being displayed on my physical iPhone. However, in the Xcode simulator, it shows up just fine. Is there anything that I can check in the code of my app that might keep the launch screen from being displayed?

A: I found the answer. The changes to my launchscreen.storyboard where being cached on my local iphone and I had to delete the app and re-install it via Xcode. From then on the correct launch screen showed up.


text:
Q: Android - JSON stored list contains objects that revert to superclass when app is exited, reopened I have an ArrayList <GeneralTemplate> items
Throughout my program, I am adding Routines which are subclasses of GeneralTemplate i.e items.add(new Routine("Test")); and all is well.
Most importantly, I can do the following.. Routine myRoutine = items.get(position);
I am saving this big list of items in a special data object in JSON using Google's GSON library. I believe this may be the problem.
This data object contains the ArrayList <GeneralTemplate> items. During my program, I can see that the routines stored in the items list are indeed Routine objects. I then save it using the code below. I have followed this process with the debugger and when I setRoutineList, the Routine objects are maintained without problem.
// Global save String method
public static void save()
{
    Editor editor = sharedPreferences.edit();

    RoutineData tempSaveObject = new RoutineData();
    tempSaveObject.setRoutineList(routineList);

    String routineListInJSON = gson.toJson(tempSaveObject);

    editor.putString(ROUTINE_LIST, routineListInJSON).commit();
}

The problem occurs when I restart the app and retreive the data. All of the items in the list revert to GeneralTemplate objects and cannot be cast back to Routine via Routine routine = (Routine) items.get(position) -> ClassCastException (Code for loading below)
    // Get a global sharedPreferences object that can be used amongst Activities
    sharedPreferences = this.getSharedPreferences(SHARED_PREFS, Context.MODE_PRIVATE);

    if (sharedPreferences.contains(ROUTINE_LIST))
    {
        String routineListJSON = sharedPreferences.getString(ROUTINE_LIST, null);
        routineDataObject = gson.fromJson(routineListJSON, RoutineData.class);

        routineList = routineDataObject.getRoutineList();
    }
    else
    {
        routineList = new ArrayList<GeneralTemplate>();
    }

Therefore, I can't access specific methods and variables because I cant regain the subclass context. There are several other instances of this problem, so if there is any good solution to this that you good folks knowledge, it would help a lot.
Thanks!
SORTED:
Genson JSON library.
https://code.google.com/p/genson/downloads/detail?name=genson-0.94.jar&can=2&q=
Made things so much easier, no need for custom serializers/deserializers. Took care of all the in depth polymorphism stuff by default.
Implemented as shown in Eugen's answer

A: This is due to the fact that you have a list of GeneralTemplate, while serializing Gson knows the concrete type of each element in the list but during deserialization Gson doesn't know into which type to deserialize (as it is a list of GeneralTemplate).
I am not sure but it looks like they have some contrib (not part of Gson) that allows to add type information in the serialized stream, this allows Gson to deserialize back into the right type.
You could also try out Genson library, handling polymorphic types is supported out of the box. It has the features provided by Gson and some others too. Here is how you can achieve it:
// first configure your Genson instance to enable polymorphic types support and
// serialization based on concrete types
Genson genson = new Genson.Builder()
                            .setWithClassMetadata(true)
                            .setUseRuntimeTypeForSerialization(true)
                            .create();

// and now just use it to serialize/deser
String json = genson.serialize(routineData);
RoutineData data = genson.deserialize(json, RoutineData.class);

EDIT
Problem solved. The Routine class had no default constructor. Putting @JsonProperty("name") on the ctr parameter and using gensons previous configuration solved the problem.


text:
Q: Attaching a file to an email that sent using django-rest-framework and sendgrid I'm using Django rest framework to create an api.
I have a POST request that requires a FileField, and I need that the file attached to this request will be sent to some email address.
The only problem I facing is that I can't attach files to this mail without a problem.
Here is the logic that i put inside the POST view:
email = EmailMessage('subject', 'some message', 'from@me.com', emails_list)
email.attach_file(MYMODEL.SOME_FILE) # << the problem is here, without it all working
email.send()

The error that I've got is: expected bytes-like object, not FileDescriptor
the file type is word document (application/octet-stream)
what am I doing wrong? Thanks!!

A: inside of POST view method:
from django.core.mail import EmailMultiAlternatives

first, I saved the instance inside DB, and then accessed to its path inside
instance = serializer.save()
        email = EmailMultiAlternatives(
            'Subject',
            'Message',
            'from_emails',
            ['to_emails'])
        email.attach_file(instance.FILE_TO_SEND.path)
        email.send()


text:
Q: How can I grep/sed taking find/replace pairs from a file? I want to run a find and replace using a series of value pairs taken from a file (or two files, if that makes the task any easier). The find and replace strings are literal ones, not regexes in the practical sense. At the moment the file is tab-delimited, findstring \t replacestring, one pair per line, but I can change that as required.
I know a little about regex but with Unix commands I really need clear "copy and paste" instructions. Earlier in this project I was pleased to discover grep -f to get find strings from a file, but it seems that grep can't do the same thing for the replace strings.
Can I do this with a mixture of grep, sed and so on? The thread above explains how to pipe grep to sed, but then I need to tell sed how to read replace strings from the file.
I'm on macOS (with homebrew) if that makes a difference.

A: You can make a file with a list of sed commands like this in a file called commands.sed:
s|cat|cats|g
s|dog|dogs|g
s|person|people|g

and run it on some input with:
echo "House mouse cat dog person dog person" | sed -f commands.sed

and it will replace cat with cats, dog with dogs and person with people producing:
House mouse cats dogs people dogs people

So we want to turn your file with substitutions into a command file like that - using sed! So, if your replacements file subs.txt contains lines like this with the two words on each line separated by a TAB:
cat cats
dog dogs
person  people

That would be:
sed -e 's/^/s|/' -e $'s/\t/|/' -e 's/$/|g/' subs.txt > commands.sed

and then you can apply it with:
sed -f commands.sed SomeFile

Rather than creating a file with the commands in, we can run a process substitution like this to dynamically generate them, and do it all in one go with:
echo "House mouse cat dog person dog person" | sed -f <(sed -e 's/^/s|/' -e $'s/\t/|/' -e 's/$/|g/' subs.txt)


text:
Q: holoviews - Overlap plots with different y scales I have two dataframes (dataP and dataI) and I am trying to do a plot of both dataframes overlapped, each of them with their own scale, like a twin axis.
I am trying the following code:
c_def = hv.Curve(dataP, name='Integrated P').options(color='red', width=1300, ylabel='Integrated P', xlabel='Time', yaxis='left')
c_sec = hv.Curve(dataI, name='Integrated I').options(color='blue', width=1300, ylabel='Integrated I', xlabel='bare', yaxis='right')
c_def * c_sec

But all I get is the plot with both ylabels in the right side, and both plots have the scale of the dataframe with the bigger values.
Could someone please give me a hand with that?
Thank you in advance,


text:
Q: TinyMCE 6.3 : translate to Arabic any selected text from drop list datetime before put it in editor? In TinyMCE 6, I want to translate any item selected from the dropdown to Arabic before put in the editor.
try to use the "BeforeSetContent" event but not working.


text:
Q: Exchange Online: Sort conversations by time of last message I am accessing Office 365 via a browser.  I would like my email conversations to be sorted by the time of the last message in each conversation.  This currently happens for most of the conversations, but not if the last message is sent by me.  Is there a way to ensure that it always happens?

A: When displaying Outlook mail list in the form of a conversation, Outlook seems to only use the time of the latest mail in this conversation within the current folder as the latest time of the conversation. However, for those conversations whose last message is sent by you, the latest email message is in your Sent items folder. So, the simplest workaround is that you could try to create an Outlook rule to move a copy of your sent emails to the same folder.


text:
Q: Kafka stops after a certain period of time, lost brokers I have 4 kafka  running with debezium. After some days running well, three kafka machines get out of the network for a period of time and, on connectDistributed.out log file I have a lot of messages with the following error:
[2020-05-04 13:27:02,526] WARN [Consumer clientId=connector-consumer-sink-warehouse-6,
groupId=connect-sink-warehouse] 133 partitions have leader brokers without a matching listener,
 including [SCT010-2, SC2010-2, SC1010-0, SC1010-1, SF4010-0, SUB010-0, SUB010-1, SWP010-0,
SWP010-1, ACO010-2] (org.apache.kafka.clients.NetworkClient:1044)

I have 4 Kafka machines, brokers from 0 to 3
192.168.240.70 - Broker 0
192.168.240.71 - Broker 1
192.168.240.72 - Broker 2
192.168.240.73 - Broker 3

Zookeeper:
192.168.240.70
Follow my server.properties - There are the same, except the listeners, advertised.listeners that points for the same IP of the machine that Kafka is installed and broker.id that must be unique (from 0 to 3):
broker.id=0
listeners=CONTROLLER://192.168.240.70:9091,INTERNAL://192.168.240.70:9092
advertised.listeners=CONTROLLER://192.168.240.70:9091,INTERNAL://192.168.240.70:9092
listener.security.protocol.map=CONTROLLER:PLAINTEXT,INTERNAL:PLAINTEXT
control.plane.listener.name=CONTROLLER
inter.broker.listener.name=INTERNAL
num.network.threads=3
num.io.threads=8
socket.send.buffer.bytes=102400
socket.receive.buffer.bytes=102400
socket.request.max.bytes=104857600
log.dirs=/home/william/kafka/data/kafka/
num.partitions=3
num.recovery.threads.per.data.dir=1
offsets.topic.replication.factor=3
transaction.state.log.replication.factor=3
transaction.state.log.min.isr=1
log.retention.hours=150
log.retention.bytes=200000000000
log.segment.bytes=1073741824
log.retention.check.interval.ms=300000

zookeeper.connect=192.168.240.70:2181
zookeeper.connection.timeout.ms=6000
group.initial.rebalance.delay.ms=3

The kafka topics (configs/offsets and status) shows problems in replication. There are some related with listeners config?

About the connectors health:

And, on kafka connect. only one broker are presented:

How can I fix this error? Seems to be something related to leader election or finding the leader after a long time without broker access.

A: After a research I found the problem. So, to help here, follow the concept about the problem:
When we create a distributed Kafka systems, we distribute the topics around the brokers and create leader electors. In my case, I have 4 brokers that Zookeeper chooses on the fly who will be the leader of certain topics.
As three of four Kafka servers was down for more than a hour, Zookeeper tried to reach and can't reach the leader. As my config points the need to replicate to three brokers the same topic, Zookeeper can't maintain the topic healthy.
We have the rebalance config: group.initial.rebalance.delay.ms=3 that try to rebalance at every 3 seconds. And we have a limited number of tries to reconnect before one Kafka broker was down. The tries was occurred and Zookeeper can't reached the brokers lost.
In other way, the brokers was not down, they're only cant't reach Zookeeper by network problems so, after a time, the tries from Zookeeper was stopped and, after a time, Kafka brokers are reachable again but, the tries to rebalance are stopped.
Just, simply restarting my brokers to tell to zookeeper to reconnect solved my problem because, on restart, Kafka brokers tell to zookeeper: -I'm here, waiting for your instructions. And Zookeeper, recognizing the leaders lost, reconnect everything on the right place.
So, trying to be helpful.


text:
Q: Can't get rid of div line break in CSS I can not get rid of the linebreak between the input field and the submit button in this code example:
http://jsfiddle.net/m4FNx/1/
(using Chrome)
I set all the relevant tags to
display:inline-block

but it doesn't seem to do what it normally does.
I've been looking too long at it so I can't see the error in there anymore, so any help is appreciated.

A: If you don't want to set a fixed width (which won't always work), add
white-space:nowrap;

to your .bubble div.  This will prevent the contents from wrapping.

A: Set a width to the .bubble div
.bubble {
    width: 320px;
}


text:
Q: How to nest methods to execute a SQLite transaction safely in Python? I'm working on class creation in Python together with some SQLite tests and I'm wondering if the way I'm handling the connections is right (and most importantly, safe).
Inside class Test, I have two methods: simple_operation, which inserts a new value in a nested set model table, and coupled_operation, which executes two simple_operation in a row to avoid redundancy.
Currently, all other methods involving any insertion or updates on the database open the connection and close it upon completing the operation, like simple_operation is planned originally:
class Test:
    def simple_operation(self, value):
        conn = sqlite3.connect(mydatabase)
        cur = conn.cursor()
        with conn:
            cur.execute('UPDATE nested SET rgt = rgt + 2 WHERE rgt >= ?;', (value,))
            cur.execute('UPDATE nested SET lft = lft + 2 WHERE lft >= ?;', (value,))
            cur.execute('INSERT INTO nested(lft, rgt) VALUES(?, ?);', (value, value+1))

        conn.close()

However, since coupled_operation will execute it twice and its purpose is to pair two simple operations that have something in common, it would have its own transaction leading back to the simple method:
class Test:
    def coupled_operation(self, value):
        connd = sqlite3.connect(mydatabase)
        with connd:
            self.simple_operation(value)
            self.simple_operation(value+2)
        conn.close()

However, since simple_operation implements its own transaction, handling it the same way would commit every simple_operation it makes, defeating the purpose of connd as a context manager. In a practical level, this implementation does 2x conn.commit with 3x cur.execute each, instead of 6x cur.execute and then connd.commit.
My solution is currently passing through leaving the cursor as an optional argument in simple_operation, changing behaviour whether it is provided or not:
class Test:
    def coupled_operation(self, value):
        connd = sqlite3.connect(mydatabase)
        curd = connd.cursor()
        with connd:
            self.simple_operation(value, curd)
            self.simple_operation(value+2, curd) # A

        conn.close()

    def simple_operation(self, value, outer_cursor=None):
        if outer_cursor is None:
            conn = sqlite3.connect(mydatabase)
            cur = conn.cursor()
            with conn:
                cur.execute('UPDATE nested SET rgt = rgt + 2 WHERE rgt >= ?;', (value,))
                cur.execute('UPDATE nested SET lft = lft + 2 WHERE lft >= ?;', (value,))
                cur.execute('INSERT INTO nested(lft, rgt) VALUES(?, ?);', (value, value+1))

            connd.close()
        else:
            # Executes, but doesn't commit, leaves for coupled_operation to integrate into transaction
            outer_cursor.execute('UPDATE nested SET rgt = rgt + 2 WHERE rgt >= ?;', (value,))
            outer_cursor.execute('UPDATE nested SET lft = lft + 2 WHERE lft >= ?;', (value,))
            outer_cursor.execute('INSERT INTO nested(lft, rgt) VALUES(?, ?);', (value, value+1)) # B

I'm not sure, however, if done this way it is successfully contained within the desired transaction, in such a way that should something go wrong with # B when coming from # A the entire operation would be rolled back.

Just for curiosity's sake, I'm opening and closing connections every time I handle the database. Previously I set a single connection as a class property and started messing with other methods, but I ended up locking my database when instantiating the class. Would you guys consider this way or the one shown in the examples more efficient?

A: Surely the simplest solution is to separate concerns of the simple_operation() function into the part that commits the transaction and the part that does the actual work:
class Test:
    def __init__(self, path):
        self.conn = sqlite3.connect(path)

    def coupled_operation(self, value):
        with self.conn:
            cursor = self.conn.cursor()
            self.do_simple_operation(cursor, value)
            self.do_simple_operation(cursor, value+2)

    def simple_operation(self, value):
        with self.conn:
            cursor = self.conn.cursor()
            self.do_simple_operation(cursor, value)

    def do_simple_operation(self, cursor, value):
        cursor.execute('UPDATE nested SET rgt = rgt + 2 WHERE rgt >= ?;', (value,))
        cursor.execute('UPDATE nested SET lft = lft + 2 WHERE lft >= ?;', (value,))
        cursor.execute('INSERT INTO nested(lft, rgt) VALUES(?, ?);', (value, value+1))

That should do the trick. There's no need to keep closing and reopening the database, that will only lead to slowness. I'm not sure why you had locking problems; maybe you were sharing objects of this class between threads? That isn't allowed in SQLite.
You could potentially split out all methods in this way, to be really safe. All methods foo() just open a connection context manager and call do_foo(), while methods starting with do_ could freely call each other.
Here are a few extra notes that might be useful:

*

*Using the same cursor has no effect on whether statements are considered to be part of the same transaction and no effect on efficiency (there is an internal statement cache in the Python sqlite3 module but it's per connection not per cursor) so you can just make a new cursor each time you execute a statement. There's even an execute() method on the sqlite3.Statement object which is a shortcut for creating a Cursor and calling execute() on it (and the return value is the Cursor object in case you need it).

*Just in case you're not aware (I certainly think it's not obvious!), with conn doesn't start a transaction, it just commits (if no exception) or rolls back (if there is an exception) a transaction that is somehow otherwise started. If no transaction is in progress when you get to the end of a with conn block then it silently does nothing so you'll never know!

*By default, the Python sqlite3 module automatically starts a transaction when certain statements are executed. The rules are complicated, but do include the statements in your example (but do not include e.g. CREATE TABLE ... or SELECT ...). It's probably safest to disable this confusing logic by setting isolation_mode=None and start transactions manually.

*The only slight exception to what I said about cursors and locking above is that if you execute a SELECT statement but don't consume all the resulting rows and don't destroy or call close() on the Cursor object then this can extend the database lock past the end of the transaction (even past a COMMIT, although if the transaction lock is a write lock then it will downgrade it to a read lock). This is rarely a practical problem so long as you don't hang on to Cursor objects for a long time in variables.

With these tweaks, your code ends up looking like this:
class Test:
    def __init__(self, path):
        self.conn = sqlite3.connect(path, isolation_mode=None)

    def coupled_operation(self, value):
        with self.conn:
            self.conn.execute("BEGIN")
            self.do_simple_operation(value)
            self.do_simple_operation(value+2)

    def simple_operation(self, value):
        with self.conn:
            self.conn.execute("BEGIN")
            self.do_simple_operation(value)

    def do_simple_operation(self, value):
        self.conn.execute('UPDATE nested SET rgt = rgt + 2 WHERE rgt >= ?;', (value,))
        self.conn.execute('UPDATE nested SET lft = lft + 2 WHERE lft >= ?;', (value,))
        self.conn.execute('INSERT INTO nested(lft, rgt) VALUES(?, ?);', (value, value+1))


text:
Q: What does 'We didn't bring you up to watch yourself cancer.' mean? 'bring up' is a kind of collocations?
I would like to know the meaning of this sentence.

A: I think the original was probably...

We did not bring you up to watch / have you die of cancer

Bring up
is a "phrasal verb" which means "to raise and educate" a child.
No parent wants to accept the loss a child for any reason: it is not the natural order of things.


text:
Q: Kendo Grid - disable popup edit auto close (achieved), but unable to close the popup when click "Cancel" So basically I achieved what I want that is to disable Kendo Grid Popup Edit auto closing after submit based on this:
https://docs.telerik.com/kendo-ui/knowledge-base/grid-prevent-popup-close-on-edit
But, after submitting, when I click "Cancel" button, it won't allow me to close the popup edit. I'm not sure what cause it. Before submit anything, I can close the popup edit as usual when click "Cancel" button.
Here is little modification I made to the above code:
https://dojo.telerik.com/oYoxEdEj
I just change the text of the "Cancel" button to "Finished".

A: You can call window.close on 'Finished' button click.
$(".k-grid-cancel").on('click', function(e) {
    editWindow.close();
});

Edited example: Close event


text:
Q: What's wrong with this java for loop? I'm trying to see what are some cool things i can do with a for loop.
Here's a simple code to print all numbers divisible by 321 between 10_000 and 100_000.
but it doesn't work:
for(int i=10000;i<=100000 && i%321==0;i++){
  println(i);
}

wasn't it true that i can put conditional statement between the second and third semicolon?
this just outputs nothing, so i'm assuming there's no i values true.

A: The loop will stop as soon as i % 321 == 0 is false, which it will be right off the bat. Try:
for (int i = 10000; i <= 100000; i++) {
  if (i % 321 == 0) {
    println(i);
  }
}

Or:
for (int i = 10000 + (10000 % 321); i <= 100000; i += 321) {
  println(i);
}

A: The problem is with the condition of your loop.
when (i = 10000)

i % 321 = 10000 % 321 = 49
So the condition i % 321 == 0, is false

you need to try something like this, in order to work
for (int i = 10000; i <= 100000; i++) {
  if (i % 321 == 0) {
    println(i);
  }
}


text:
Q: How can a Wi-Fi client distinguish between ad-hoc and hotspot networks? Android does not support ad-hoc WiFi networks. My question is, how can it distinguish between ad-hoc and hotspot networks?
UPDATE
In other words, what are protocol differences between ad-hoc and hotspot networks? Or what is the key difference?

A: The BSSID of an ad-hoc network is a MAC address flagged as individual and local (i.e. the two least-significant bits of the first octet will be "10").


text:
Q: mysql server: What is the Difference between "Stop Server" and "Bring Offline"? I could see  Stop Server and Bring Offline in mysql workbench.

I hope both are used to stop the services but still confused in difference between both in terms of when to use Stop Server and Bring Offline?

A: Stop server just stops the mysql process
Offline mode is a new feature introduced in MySQL 5.7.5, that basically throws out all users except DBAs :

MySQL Server now supports an "offline mode" with these
  characteristics:

*

*Connected client users who do not have the SUPER privilege are disconnected on the next request, with an appropriate error.
  Disconnection includes terminating running statements and releasing
  locks. Such clients also cannot initiate new connections, and receive
  an appropriate error.

*Connected client users who have the SUPER privilege are not disconnected, and can initiate new connections to manage the server.

*Replication slave threads are permitted to keep applying data to the server.
Only users who have the SUPER privilege can control offline mode. To
  put a server in offline mode, change the value of the new offline_mode
  system variable from OFF to ON. To resume normal operations, change
  offline_mode from ON to OFF. In offline mode, clients that are refused
  access receive an ER_SERVER_OFFLINE_MODE error.

Source : Changes in MySQL 5.7.5 (2014-09-25, Milestone 15)


text:
Q: Как убрать анимацию вращения у Progress bar? Доброго времени суток, необходимо на круглом progress bar отображать рейтинг заведения. Т.е без анимации вращения.
Подскажите как это реализовать, а то я уже все перепробовал?

A: Такого параметра у круглого прогресс бара нет. Но вы можете притвориться горизонтальным прогрессом и установить круглый вид для progressDrawable, описанный в xml примерно так:
progress.xml
<?xml version="1.0" encoding="utf-8"?>
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
        android:fromDegrees="270"
        android:toDegrees="270">

    <shape
        android:shape="ring"
        android:thickness="4dp"
        android:useLevel="true">

        <solid
            android:color="@color/colorAccent" />

    </shape>

</rotate>

Сам ProgressBar в разметке:
<ProgressBar
    android:id="@+id/progressBar"
    android:layout_width="64dp"
    android:layout_height="64dp"
    style="?android:attr/progressBarStyleHorizontal"
    android:progressDrawable="@drawable/progress"
    android:indeterminate="false"
    android:max="100"
    android:progress="66"
    />

A: Вижу как минимум 2 способа решения:
1) Тупой: вписываем прогрессбар в RelativeLayout и сверху крутилки впихиваем картинку.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:clickable="false">

    <ProgressBar
        android:id="@+id/myProgressBar"
        style="@android:style/Widget.ProgressBar.Small.Inverse"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:indeterminate="true"
        android:layout_centerInParent="true"
        android:padding="0dp"
        android:clickable="false"/>

    <ImageView
        android:id="@+id/myImage"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:src="@drawable/my_image"
        android:clickable="false"/>
</RelativeLayout>

2) Применяем кастомный ProgressBar с картинкой посередине:


text:
Q: Writing multiple queries for single Jasper report based on condition check I am trying to generate one Jasper report in that I need to write query based on start and end date parameters. Here start and end dates might be null values, so based on start and end dates my query should change.
So far I have taken 4 parameters like id, from, to, condition1, condition2 for condition1
I defined an expression like
$P{from} != null ? "and date >= $P{from}:""
condition2 expression $P{to} != null ? "and date < $P{to}:""

And my query is like this
select name from app_info where id=$P{id} $P!{condition1} $P!{condition2}

This query is giving all records even if I give date limits. I checked with my database and this output is wrong.

A: "and date >= $P{from}:"" not correct (check quotes)
Result string for expression like "and date >="+ $P{from}:"" makes no sense.
This solution for Oracle database.
Expression for convert string to date for example : to_date('10.04.2008 10:00','DD.MM.YYYY HH:mi')
<parameter name="from" class="java.util.Date"/>
<parameter name="to" class="java.util.Date"/>
<parameter name="condition1" class="java.lang.String" isForPrompting="false">
    <defaultValueExpression><![CDATA[$P{from} != null ? "and myDateField >to_date('"+new java.text.SimpleDateFormat("dd.MM.yyyy HH:mm").format($P{from})+"','DD.MM.YYYY HH:mi')":""]]></defaultValueExpression>
</parameter>
<parameter name="condition2" class="java.lang.String" isForPrompting="false">
    <defaultValueExpression><![CDATA[$P{to} != null ? "and myDateField <=to_date('"+new  java.text.SimpleDateFormat("dd.MM.yyyy HH:mm").format($P{to})+"','DD.MM.YYYY HH:mi')":""]]></defaultValueExpression>
</parameter>

And parameter $P{condition1} must be declared after $P{from}. Order of parameters is important in this case (calculation second parameter by value first parameter)
HTH


text:
Q: Looking for C source code for snprintf() I need to port snprintf() to another platform that does not fully support GLibC.
I am looking for the underlying declaration in the Glibc 2.14 source code.  I follow many function calls, but get stuck on vfprintf().  It then seems to call _IO_vfprintf(), but I cannot find the definition.  Probably a macro is obfuscating things.
I need to see the real C code that scans the format string and calculates the number of bytes it would write if input buffer was large enough.
I also tried looking in newlib 1.19.0, but I got stuck on _svfprintf_r().  I cannot find the definition anywhere.
Can someone point me to either definition or another one for snprintf()?

A: I've spent quite a while digging the sources to find _svfprintf_r() (and friends) definitions in the Newlib. Since OP asked about it, I'll post my finding for the poor souls who need those as well. The following holds true for Newlib 1.20.0, but I guess it is more or less the same across different versions.
The actual sources are located in the vfprintf.c file. There is a macro _VFPRINTF_R set to one of _svfiprintf_r, _vfiprintf_r, _svfprintf_r, or _vfprintf_r (depending on the build options), and then the actual implementation function is defined accordingly:
int
_DEFUN(_VFPRINTF_R, (data, fp, fmt0, ap),
       struct _reent *data _AND
       FILE * fp           _AND
       _CONST char *fmt0   _AND
       va_list ap)
{
    ...

A: http://www.ijs.si/software/snprintf/ has what they claim is a portable implementation of snprintf, including vsnprintf.c, asnprintf, vasnprintf, asprintf, vasprintf. Perhaps it can help.

A: The source code of the GNU C library (glibc) is hosted on sourceware.org.
Here is a link to the implementation of vfprintf(), which is called by snprintf():
https://sourceware.org/git/?p=glibc.git;a=blob;f=stdio-common/vfprintf.c


text:
Q: Restrict one user to see other users courses I am kind of new to Moodle, but I am looking for the following:
I created two user(User1 and user2) from admin and both users have their own courses.
Structure is like:-
Admin have two Users:- User1 and User2
user1 have three course C1,C2,C3
user2 have two course C4,C5
And user1 and user2 should not see each others courses. Also, when the user clicks "All courses" he/she should still only see the assigned courses.

A: I found a plugin for this.it helped me to resolve all my issue. Hope it will help others too.
for demo you can visit
    http://demo.iomad.org/
Iomad is completely free. Like Moodle, anyone is free to download and use the software
    https://github.com/iomad

A: You may have to define a role for each user in Settings > Site administration > Users > Permissions > Define roles Assign system
There are more than a lot settings if you scroll down on create new role page.
And then assign that role to the each user from Settings > Site administration > Users > Permissions > Assign system roles
Though I am not entirely sure that this method will work as expected.
But this could be one of the options.


text:
Q: How to display folder and item in a treeview (inside a listview) First of all, thank you for reading this!
I have a custom list with folders and items in them. What I'm looking for is a webpart or view that shows the list in a treeview. An example for that is the navigation on the right side. I dont want to have it on the right side, it should be in the center instead of the listview.
Do you have any hints for me?

A: http://treeviewwebpart.codeplex.com/
http://www.codeproject.com/KB/sharepoint/librarytreewebpart.aspx
http://www.codeproject.com/KB/sharepoint/Tree_View_for_List.aspx


text:
Q: XSLT: Copy nested element multiple times I am trying to copy one of the nested element multiple times. I search and came across XSLT: copy object xml multiple times while incrementing attribute and value. This is close but not the answer that I'm looking for. This is what I'm trying to do
XML Input:
<Company xmlns="http://test.com" >
    <Group document="dump" >
        <dump>asdfasd</dump>
        <dump2>asdfasdf</dump2>
        <Person>
            <record>1</record>
            <dump2>asdfasdf</dump2>
            <properties>
                <name>John</name>
                <number>1</number>
            </properties>
        </Person>
    </Group>
</Company>

And output to something like:
<Company xmlns="http://test.com">
   <Group document="dump">
      <dump>asdfasd</dump>
      <dump2>asdfasdf</dump2>
      <Person>
         <record>1</record>
         <dump2>asdfasdf</dump2>
         <properties>
            <name>John</name>
            <number>1</number>
         </properties>
      </Person>
      ...
      <Person>
         <record>n</record>
         <dump2>asdfasdf</dump2>
         <properties>
            <name>John</name>
            <number>n</number>
         </properties>
      </Person>
   </Group>
</Company>

With my xslt:
<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
 xmlns:t="http://test.com"
>
     <xsl:output omit-xml-declaration="yes" indent="yes"/>
     <xsl:strip-space elements="*"/>

     <xsl:param name="pTimes" select="2"/>

     <xsl:template match="node()|@*">
      <xsl:param name="pPosition" select="1"/>
      <xsl:copy>
       <xsl:apply-templates select="node()|@*">
         <xsl:with-param name="pPosition" select="$pPosition"/>
       </xsl:apply-templates>
      </xsl:copy>
     </xsl:template>

     <xsl:template match="t:Person">
         <xsl:copy>
             <xsl:copy-of select="@*"/>
             <xsl:call-template name="applyNTimes">
                 <xsl:with-param name="pTimes" select="$pTimes"/>
                 <xsl:with-param name="pPosition" select="1"/>
             </xsl:call-template>
          </xsl:copy>
     </xsl:template>

     <xsl:template name="applyNTimes">
         <xsl:param name="pTimes" select="0"/>
         <xsl:param name="pPosition" select="1"/>

         <xsl:if test="$pTimes > 0">
             <xsl:choose>
             <xsl:when test="$pTimes = 1">
                 <xsl:apply-templates select="*">
                 <xsl:with-param name="pPosition" select="$pPosition"/>
                 </xsl:apply-templates>
             </xsl:when>
             <xsl:otherwise>
                 <xsl:variable name="vHalf" select="floor($pTimes div 2)"/>

                 <xsl:call-template name="applyNTimes">
                 <xsl:with-param name="pTimes" select="$vHalf"/>
                 <xsl:with-param name="pPosition" select="$pPosition"/>
                 </xsl:call-template>

                 <xsl:call-template name="applyNTimes">
                 <xsl:with-param name="pTimes" select="$pTimes - $vHalf"/>
                 <xsl:with-param name="pPosition" select="$pPosition + $vHalf"/>
                 </xsl:call-template>
             </xsl:otherwise>
             </xsl:choose>
         </xsl:if>
     </xsl:template>

     <xsl:template match="t:record">
         <xsl:param name="pPosition" select="1"/>

         <xsl:copy>
              <xsl:value-of select="$pPosition"/>
          </xsl:copy>
     </xsl:template>

     <xsl:template match="t:number">
          <xsl:param name="pPosition" select="1"/>
            <xsl:copy>
              <xsl:value-of select="$pPosition"/>
            </xsl:copy>
     </xsl:template>
</xsl:stylesheet>

This is what I have
<Company xmlns="http://test.com">
   <Group document="dump">
      <dump>asdfasd</dump>
      <dump2>asdfasdf</dump2>
      <Person position="1">
         <record>1</record>
         <dump2>asdfasdf</dump2>
         <properties>
            <name>John</name>
            <number>1</number>
         </properties>
         <record>2</record>
         <dump2>asdfasdf</dump2>
         <properties>
            <name>John</name>
            <number>2</number>
         </properties>
      </Person>
   </Group>
</Company>

How do I prevent Person element from disappearing when it gets copied?

A: The solution in this case is to move the xsl:copy for the Person from the template matching t:Person and into the applyNTimes template (in the case when pTimes is 1).
Try this XSLT
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:t="http://test.com" version="1.0">
   <xsl:output omit-xml-declaration="yes" indent="yes"></xsl:output>
   <xsl:strip-space elements="*"></xsl:strip-space>
   <xsl:param name="pTimes" select="2"></xsl:param>

   <xsl:template match="node()|@*">
      <xsl:param name="pPosition" select="1"></xsl:param>
      <xsl:copy>
         <xsl:apply-templates select="node()|@*">
            <xsl:with-param name="pPosition" select="$pPosition"></xsl:with-param>
         </xsl:apply-templates>
      </xsl:copy>
   </xsl:template>

   <xsl:template match="t:Person">
      <xsl:call-template name="applyNTimes">
         <xsl:with-param name="pTimes" select="$pTimes"></xsl:with-param>
         <xsl:with-param name="pPosition" select="1"></xsl:with-param>
      </xsl:call-template>
   </xsl:template>

   <xsl:template name="applyNTimes">
      <xsl:param name="pTimes" select="0"></xsl:param>
      <xsl:param name="pPosition" select="1"></xsl:param>
      <xsl:if test="$pTimes > 0">
         <xsl:choose>
            <xsl:when test="$pTimes = 1">
               <xsl:copy>
                  <xsl:apply-templates select="*">
                     <xsl:with-param name="pPosition" select="$pPosition"></xsl:with-param>
                  </xsl:apply-templates>
               </xsl:copy>
            </xsl:when>
            <xsl:otherwise>
               <xsl:variable name="vHalf" select="floor($pTimes div 2)"></xsl:variable>
               <xsl:call-template name="applyNTimes">
                  <xsl:with-param name="pTimes" select="$vHalf"></xsl:with-param>
                  <xsl:with-param name="pPosition" select="$pPosition"></xsl:with-param>
               </xsl:call-template>
               <xsl:call-template name="applyNTimes">
                  <xsl:with-param name="pTimes" select="$pTimes - $vHalf"></xsl:with-param>
                  <xsl:with-param name="pPosition" select="$pPosition + $vHalf"></xsl:with-param>
               </xsl:call-template>
            </xsl:otherwise>
         </xsl:choose>
      </xsl:if>
   </xsl:template>

   <xsl:template match="t:record|t:number">
      <xsl:param name="pPosition" select="1"></xsl:param>
      <xsl:copy>
         <xsl:value-of select="$pPosition"></xsl:value-of>
      </xsl:copy>
   </xsl:template>
</xsl:stylesheet>

Note that, if you could use XSLT 2.0, then things become much easier due the support of a "for 1 to n" construct (and the existences of "tunneling" to avoid having to explicitly pass around parameters in every single template).
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                xmlns:t="http://test.com"
                version="2.0">

   <xsl:output omit-xml-declaration="yes" indent="yes"></xsl:output>
   <xsl:strip-space elements="*"></xsl:strip-space>

   <xsl:param name="pTimes" select="2"></xsl:param>

   <xsl:template match="node()|@*">
      <xsl:copy>
         <xsl:apply-templates select="node()|@*" />
      </xsl:copy>
   </xsl:template>

   <xsl:template match="t:Person">
      <xsl:variable name="person" select="." />
      <xsl:for-each select="1 to $pTimes">
        <xsl:apply-templates select="$person" mode="repeat">
           <xsl:with-param name="pPosition" select="position()" tunnel="yes" />
        </xsl:apply-templates>
      </xsl:for-each>
   </xsl:template>

   <xsl:template match="t:Person" mode="repeat">
     <xsl:copy>
       <xsl:apply-templates />
     </xsl:copy>
   </xsl:template>

   <xsl:template match="t:record|t:number">
      <xsl:param name="pPosition" select="1" tunnel="yes"></xsl:param>
      <xsl:copy>
         <xsl:value-of select="$pPosition"></xsl:value-of>
      </xsl:copy>
   </xsl:template>
</xsl:stylesheet>


text:
Q: Map mvc3 Model object to select2 plugin data I am trying to map Model.property to the data of Select2 plugin with no luck, keep getting "TypeError: invalid 'in' operand result" in the console.
public class Items{
    public int id;
    public string text;
};
public class Model{
    ...
    public Items[] arr { get; set; }
    ...
}

The Model is passed to the Razor partialview where my jsScript does some magic
<script>
    $(document).ready(function(){
        $('#sel').select2({
            data: '@Model.arr',
            ...
    });
</script>

Everything looks ok until I click inside the select box to see the items in it. Then I get the console error I referred to earlier.
Solution to my proplem:
// Changed the property of Model class to string.
public class Model{
    ...
    public string arr { get; set; }
    ...
}

*

*In the controller-> Create IList object and fill it with items.

*In the controller-> Serialize the list object and put it into 'arr' property in Model class.

*In the view
select2({
    ...
    data: { results: eval('(@Html.Raw(Model.arr))') }
    ...
})

A: Try to declare your list as IList, I had a similar problem and it worked:
public IList<Items> arr { get; set; }

And you have an obvious error because you don't specify the id and text to display in the box, like:
.select2({
data:[
{id:0,text:'item1'},
{id:1,text:'item2'},
{id:2,text:'item3'},
{id:3,text:'item4'},
{id:4,text:'item5'}
]});

So, you should be able to work around with:
<script>
    $(document).ready(function(){
        $('#sel').select2({
             data:{ results: '@Model.arr', text: 'text' }, // 'text' is the name of you model property with your text
             formatSelection: format,
             formatResult: format
    });
function format(item) { return item.text; };
</script>

If it dows not work, I suggest you start debugging by declairing a test array like the official doc
var data=[{id:0,tag:'enhancement'},{id:1,tag:'bug'},{id:2,tag:'duplicate'},{id:3,tag:'invalid'},{id:4,tag:'wontfix'}];
function format(item) { return item.tag; };

$("#e10_2").select2({
data:{ results: data, text: 'tag' },
formatSelection: format,
formatResult: format
});

If this code is not working, you will know that the error is coming from the Jquery and not your code


text:
Q: Why is DefaultItemAnimator forcing changed ViewHolders to recreate? Hey so basically I run into a issue with RecyclerView lately (The issue I had is described here: RecyclerView recreating ViewHolder instead of rebinding). What I discovered was that the ItemAnimator inside RecyclerView decides if a changed ViewHolder just has to be rebound or a new ViewHolder should be created and crossfaded.
This article explains some of the things:
https://medium.com/android-news/anatomy-of-recyclerview-part-1-a-search-for-a-viewholder-continued-d81c631a2b91
I assume this is the part of the DefaultItemAnimator that decides what should happen:
     /**
     * {@inheritDoc}
     *

     * If the payload list is not empty, DefaultItemAnimator returns true.
     * When this is the case:
     *

     *
If you override {@link #animateChange(RecyclerView.ViewHolder, RecyclerView.ViewHolder, int, int, int, int)}, both
     * ViewHolder arguments will be the same instance.
     *

     *

     * If you are not overriding {@link #animateChange(RecyclerView.ViewHolder, RecyclerView.ViewHolder, int, int, int, int)},
     * then DefaultItemAnimator will call {@link #animateMove(RecyclerView.ViewHolder, int, int, int, int)} and
     * run a move animation instead.
     *

     *

     */
    @Override
    public boolean canReuseUpdatedViewHolder(@NonNull RecyclerView.ViewHolder viewHolder,
            @NonNull List<Object> payloads) {
        return !payloads.isEmpty() || super.canReuseUpdatedViewHolder(viewHolder, payloads);
    }

Now the solution to my problem was to just call onItemRangeChanged() with some arbitrary payload and it would always reuse the ViewHolder.
My question:
Now I was wondering why and when it would be better to recreate the whole ViewHolder and crossfade it than just updating a specific part of it? In the crossreferenced problem mentioned above I was just changing the visibility of a small part of the ViewHolder but the whole things was recreated, which - I assume - is way worse performance wise?

A: Remember RecyclerView can have multiple item view types. When notifyItemChanged causes view type to change then viewholders are ineligible for reuse regardless of payload.
By replacing viewholders animator maintains unified behavior in this case.
Also by updating the ViewHolder they will not undergo adapters onViewAttachedToWindow(holder) which people might expect while new items are being laid out and onViewRecycled(holder) & onViewDetachedFromWindow(holder) which are called for items that are being removed.
As a side note if you're experiencing onCreateViewHolder calls during your subsequent range updates (without payload) you should probably increase size of your RecyclerView.RecycledViewPool.


text:
Q: A quasimetric for a space formed by nouns Recently I came with the problem: define a metric for a space formed by nouns.
Here is my formulation:
Let $W$ be the set of all words and let $S \subset W$ be the set of all nouns. Let $A$ be the set of sequences from $W$ such that, for each element $a \in A$, the range of $a$ contains at least one element from $S$.
Define the function $N: S \times S \rightarrow \mathbb{Z}$ given by $N(x, y)$ = the number of sequences on A that has both $x \in S$ and $y \in S$ in its range, where $\mathbb{Z}$ is the set of all integers. Define the map $dep: S \times S \rightarrow \mathbb{R}_+$ such that $dep(x,y) = N(x,x) - N(x,y)$, where $\mathbb{R}_+$ is the set of all non-negative real numbers.
Question: is $dep$ a metric? if not, is it a quasimetric?

A: I hope I'm not misunderstanding your definitions.
Suppose $x$, $y$ and $z$ are nouns.
If $A=\{xyz,xy,x\}$ then $dep(x,y)=3-2=1$ and $dep(y,x)=2-2=0$. Non-symmetric!
As I pointed out in the comments, if $A=\{xy,xyz\}$ then $dep(x,y)=0$ with $x\neq y$.
As for the triangle inequality, we can reduce it...
$$\begin{align}
dep(x,y)+dep(y,z)&\geq dep(x,z)\\
N(x,x) - N(x,y) + N(y,y) - N(y,z) &\geq N(x,x) - N(x,z)\\
N(y,y) - (N(x,y) + N(y,z)) &\geq - N(x,z)
\end{align}$$
I don't have a proof but I believe it holds.
It looks like you have a pseudoquasimetric.

A: I suggest the following approach: to each noun $x$ there corresponds the set $A_x=\{a\in A: x\in a\}$. In plain English, $A_x$ is the set of articles that mention $x$. There is a natural metric on the space of subsets: namely, $d(A,B)=|A\Delta B|$, the cardinality of symmetric difference. This metric induces a pseudo-metric on the set of nouns, $d(x,y)=d(A_x,A_y)$ (a pseudo-metric because it turns to zero when $A_x=A_y$, even if $x\ne y$.) This sort of makes sense: if $x$ and $y$ always appear together, they can be treated as the same entity. Chances are that they form a popular compound noun.
Another way to look at the above is that to each $x$ we associated a function $F_x$ such that $F_x(a)=1$ if $x\in a$ and $F_x(a)=0$ otherwise. The symmetric difference distance is just the $L^1$ distance with the counting measure: $d(x,y)=\sum_a |F_x(a)-F_y(a)|$. But it may be that not all articles are equally important. They could be weighed by the number of citations, or length, or the journal's prestige, etc. The weighted $L^1$ space fits well into the problem: $d_w(x,y)=\sum_a |F_x(a)-F_y(a)|\,w(a)$.
Finally, we may want to take into account the number of appearances of $x$ in $a$, denoted $n(x,a)$ below. The straightforward approach $F_x(a)=n(x,a)$ does not look appropriate. But I would at least experiment with exponential model $F_x(a)=1-2^{-n(x,a)}$. In yet another direction, it is worth considering the einmal ist keinmal principle: $F_x(a)=1$ if $n(x,a)\ge 2$ and $F_x(a)=0$ otherwise.


text:
Q: Differences in dis-assembled C code of GCC and Borland? Recently I have gotten interested into dis-assembling C code (very simple C code) and followed a tutorial that used Borland C++ Compiler v 5.5 (compiles C code just fine) and everything worked. Then I decided to try my own c code and compiled them in Dev C++ (which uses gcc). Upon opening it in IDA Pro I got a surprise, the asm of gcc was really different compared to Borland's. I expected some difference but the C code was EXTREMELY simple, so is it just that gcc doesn't optimize as much or is it that they use different default compiler settings?
The C Code
int main(int argc, char **argv)
{
   int a;
   a = 1;
}

Borland ASM
.text:00401150 ; int __cdecl main(int argc,const char **argv,const char *envp)
.text:00401150 _main           proc near               ; DATA XREF: .data:004090D0
.text:00401150
.text:00401150 argc            = dword ptr  8
.text:00401150 argv            = dword ptr  0Ch
.text:00401150 envp            = dword ptr  10h
.text:00401150
.text:00401150                 push    ebp
.text:00401151                 mov     ebp, esp
.text:00401153                 pop     ebp
.text:00401154                 retn
.text:00401154 _main           endp

GCC ASM (UPDATED BELLOW)
.text:00401220 ; ¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦ S U B R O U T I N E ¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦
.text:00401220
.text:00401220 ; Attributes: bp-based frame
.text:00401220
.text:00401220                 public start
.text:00401220 start           proc near
.text:00401220
.text:00401220 var_14          = dword ptr -14h
.text:00401220 var_8           = dword ptr -8
.text:00401220
.text:00401220                 push    ebp
.text:00401221                 mov     ebp, esp
.text:00401223                 sub     esp, 8
.text:00401226                 mov     [esp+8+var_8], 1
.text:0040122D                 call    ds:__set_app_type
.text:00401233                 call    sub_401100
.text:00401238                 nop
.text:00401239                 lea     esi, [esi+0]
.text:00401240                 push    ebp
.text:00401241                 mov     ebp, esp
.text:00401243                 sub     esp, 8
.text:00401246                 mov     [esp+14h+var_14], 2
.text:0040124D                 call    ds:__set_app_type
.text:00401253                 call    sub_401100
.text:00401258                 nop
.text:00401259                 lea     esi, [esi+0]
.text:00401259 start           endp

GCC Update
Upon following the suggestion of JimR I went to see what sub_401100 is and then I followed that code to another and this seems to be the code (Am I correct in that assumption and if sowhy does GCC have all of its code in the main function?):
.text:00401100 sub_401100      proc near               ; CODE XREF: .text:004010F1j
.text:00401100                                         ; start+13p ...
.text:00401100
.text:00401100 var_28          = dword ptr -28h
.text:00401100 var_24          = dword ptr -24h
.text:00401100 var_20          = dword ptr -20h
.text:00401100 var_1C          = dword ptr -1Ch
.text:00401100 var_18          = dword ptr -18h
.text:00401100 var_C           = dword ptr -0Ch
.text:00401100 var_8           = dword ptr -8
.text:00401100
.text:00401100                 push    ebp
.text:00401101                 mov     ebp, esp
.text:00401103                 push    ebx
.text:00401104                 sub     esp, 24h        ; lpTopLevelExceptionFilter
.text:00401107                 lea     ebx, [ebp+var_8]
.text:0040110A                 mov     [esp+28h+var_28], offset sub_401000
.text:00401111                 call    SetUnhandledExceptionFilter
.text:00401116                 sub     esp, 4          ; uExitCode
.text:00401119                 call    sub_4012E0
.text:0040111E                 mov     [ebp+var_8], 0
.text:00401125                 mov     eax, offset dword_404000
.text:0040112A                 lea     edx, [ebp+var_C]
.text:0040112D                 mov     [esp+28h+var_18], ebx
.text:00401131                 mov     ecx, dword_402000
.text:00401137                 mov     [esp+28h+var_24], eax
.text:0040113B                 mov     [esp+28h+var_20], edx
.text:0040113F                 mov     [esp+28h+var_1C], ecx
.text:00401143                 mov     [esp+28h+var_28], offset dword_404004
.text:0040114A                 call    __getmainargs
.text:0040114F                 mov     eax, ds:dword_404010
.text:00401154                 test    eax, eax
.text:00401156                 jz      short loc_4011B0
.text:00401158                 mov     dword_402010, eax
.text:0040115D                 mov     edx, ds:_iob
.text:00401163                 test    edx, edx
.text:00401165                 jnz     loc_4011F6

.text:004012E0 sub_4012E0      proc near               ; CODE XREF: sub_401000+C6p
.text:004012E0                                         ; sub_401100+19p
.text:004012E0                 push    ebp
.text:004012E1                 mov     ebp, esp
.text:004012E3                 fninit
.text:004012E5                 pop     ebp
.text:004012E6                 retn
.text:004012E6 sub_4012E0      endp

A: Compiler output is expected to be different, sometimes dramatically different for the same source.  In the same way that a toyota and a honda are different.  Four wheels and some seats sure, but more different than the same when you look at the details.
Likewise the same compiler with different compiler options can and often will produce dramatically different output for the same source code.  Even for what appears to be simple programs.
In the case of your simple program, which actually does not do anything (code does not affect the input, nor output, nor anything outside the function), a good optimized compiler will result in nothing but main: with a return of some random number since you didnt specify the return value.  Actually it should give a warning or error.  This is the biggest problem I have when I compare compiler output is making something simple enough to see what they are doing but something complicated enough that the compiler does more than just pre-compute the answer and return it.
In the case of x86, which I assume is what you are talking about here, being microcoded these days there is really no answer for good code vs bad code, each family of processor they change the guts around and what used to be fast is slow and what is now fast is slow on the old processor.  So for compilers like gcc that have continued to evolve with the new cores, the optimization can be both generic to all x86es or specific to a particular family (resulting in different code despite max optimization).
With your new interest in disassembling, you will continue to see the similarities and differences and find out just how many different ways the same code can be compiled.  the differences are expected, even for trivial programs.  And I encourage you to try as many compilers as you can.  Even in the gcc family 2.x, 3.x, 4.x and the different ways to build it will result in different code for what might be though thought of as the same compiler.
Good vs bad output is in the eyes of the beholder.  Folks that use debuggers will want their code steppable and their variables watchable (in written code order).  This makes for very big, bulky, and slow code (particularly for x86).  And when you compile for release you end up with a completely different program which you have so far spent zero time debugging.  Also optimizing for performance you take a risk of the compiler optimizing out something you wanted it to do (your example above, no variable will be allocated, no code to step through, even with minor optimization).  Or worse, you expose the bugs in the compiler and your program simply doesnt work (this is why -O3 is discouraged for gcc).  That and/or you find out the large number of places in the C standard whose interpretation is implementation defined.
Unoptimized code is easier to compile, as it is a bit more obvious.  In the case of your example the expectation is a variable is allocated on the stack, some sort of stack pointer arrangement set up, the immediate 1 is eventually written to that location, stack cleaned up and function returns.  Harder for compilers to get wrong and more likely that your program works as you intended.  Detecting and removing dead code is the business of optimization and
that is where it gets risky.  Often the risk is worth the reward.  But that depends on the user, beauty is in the eye of the beholder.
Bottom line, short answer.  Differences are expected (even dramatic differences).  Default compile options vary from compiler to compiler.  Experiment with the compile/optimization options and different compilers and continue to disassemble your programs in order to gain a better education about the language and the compilers you use.  You are on the right track so far.  In the case of the borland output, it detected that your program does nothing, no input variables are used, no return variables are used, nor related to the local variables, and no global variables or other external to the function resources are used.  The integer a and the assignment of an immediate are dead code, a good optimizer will essentially remove/ignore both lines of code.  So it bothered to setup a stack frame then clean it up which it didnt need to do, then returned.  gcc looks to be setting up an exception handler which is perfectly fine even though it doesnt need to, start optimizing or use a function name other than main() and you should see different results.

A: What is most likely happening here is that Borland calls main from its start up code after initializing everything with code present in their run time lib.
The gcc code does not look like main to me, but like generated code that calls main.  Disassemble the code at sub_401100 and see if it looks like your main proc.

A: First of all, make sure you have at least enabled the -O2 optimization flag to gcc, otherwise you get no optimization at all.
With this little example, you arn't really testing optimization, you're seeing how program initialization works, e.g. gcc calls __set_app_type to inform windows of the application type, as well as other initialization. e.g. sub_401100 registers atexit handlers for the runtime. Borland might call the runtime initialization beforehand, while gcc does it within main().

A: Here's the disassembly of main() that I get from MinGW's gcc 4.5.1 in gdb (I added a return 0 at the end so GCC wouldn't complain):
First, when the program is compiled with -O3 optimization:
(gdb) set disassembly-flavor intel
(gdb) disassemble
Dump of assembler code for function main:
   0x00401350 <+0>:     push   ebp
   0x00401351 <+1>:     mov    ebp,esp
   0x00401353 <+3>:     and    esp,0xfffffff0
   0x00401356 <+6>:     call   0x4018aa <__main>
=> 0x0040135b <+11>:    xor    eax,eax
   0x0040135d <+13>:    mov    esp,ebp
   0x0040135f <+15>:    pop    ebp
   0x00401360 <+16>:    ret
End of assembler dump.

And with no optimizations:
(gdb) set disassembly-flavor intel
(gdb) disassemble
Dump of assembler code for function main:
   0x00401350 <+0>:     push   ebp
   0x00401351 <+1>:     mov    ebp,esp
   0x00401353 <+3>:     and    esp,0xfffffff0
   0x00401356 <+6>:     sub    esp,0x10
   0x00401359 <+9>:     call   0x4018aa <__main>
=> 0x0040135e <+14>:    mov    DWORD PTR [esp+0xc],0x1
   0x00401366 <+22>:    mov    eax,0x0
   0x0040136b <+27>:    leave
   0x0040136c <+28>:    ret
End of assembler dump.

These are a little more complex than Borland's example, but not excessively.
Note, the calls to 0x4018aa are calls to a library/compiler supplied function to construct C++ objects.  Here's a snippet from some GCC toolchain docs:

The actual calls to the constructors are carried out by a subroutine called __main, which is called (automatically) at the beginning of the body of main (provided main was compiled with GNU CC). Calling __main is necessary, even when compiling C code, to allow linking C and C++ object code together. (If you use '-nostdlib', you get an unresolved reference to __main, since it's defined in the standard GCC library. Include '-lgcc' at the end of your compiler command line to resolve this reference.)

I'm not sure what exactly IDA Pro is showing in your examples. IDA Pro labels what it's showing as start not main so I'd guess that JimR's answer is right - it's probably the runtime's initialization (perhaps the entry point as described in the .exe header - which is not main(), but the runtime initialization entry point).
Does IDA Pro understand gcc's debug symbols? Did you compile with the -g option so the debug symbols are generated?

A: It looks like the Borland compiler is recognizing that you never actually do anything with a and is just giving you the equivalent assembly for an empty main function.

A: Difference here is mosly not in compiled code, but in what disassembler shows to you.
You may think that main is the only function in your program but it is not. In fact your program is something like this:
void start()
{
    ... some initialization code here
    int result = main();
    ... some deinitialization code here
    ExitProcess(result);
}

IDA Pro knows how Borland works, so it can navigate directly to your main, but it doesn't know how gcc works so it shows you the true entry point of your program. You can see in Borland ASM that main is called from some other function. In GCC ASM you can go thru all of these sub_40xxx to find your main


text:
Q: The logic of clicking like in SwiftUI world! I want to make sure that the like is placed only on one card, and not on all at once. I wrote the logic of painting the like and clicking it. But this applies to all cards, not just the one where I clicked like.
How can I change the logic so that the like is placed only on the card I clicked on?
Below the code CellView() is a cell with a card, which I then use in another view
struct CellView: View{
    //MARK: - PROPERTIES

    @AppStorage("isLiked") var isLiked: Bool = false

    var data: Model

    //MARK: - BODY
    var body: some View{
        VStack{
            VStack{
                AnimatedImage(url: URL(string: data.photo)!)
                    .resizable()
                    .aspectRatio(contentMode: .fit)

                    .overlay(RoundedRectangle(cornerRadius: 10).stroke(Color("GrayWhite"), lineWidth: 0.5)
                    )
            }.background(Color.white)
                .cornerRadius(10)

            VStack{
                HStack{

                    Text("\(data.price) ₽")
                        .font(.system(size: 16, weight: .bold))
                        .foregroundColor(Color("BlackWhite"))

                    Spacer()

                    Button(action: {
                            self.isLiked.toggle()
                    }, label: {
                        Image(systemName: isLiked ? "heart.fill" : "heart")
                            .frame(width: 22, height: 22)
                            .foregroundColor(isLiked ? .red : .black)
                    })
                }.padding(.bottom, 1)

                HStack{
                    Text(data.company)
                        .font(.system(size: 14, weight: .bold))
                        .lineLimit(1)
                        .foregroundColor(Color("BlackWhite"))
                    Spacer()
                }

                HStack{
                    Text(data.name)
                        .font(.system(size: 14, weight: .bold))
                        .lineLimit(1)
                        .foregroundColor(.gray)
                    Spacer()
                }
            }
            .padding(.horizontal, 2)
        }
        .padding(5)
    }
}

Thank you in advance for your help

A: Each cell has to be identified for Swift to know what is liked.
import SwiftUI

struct CardData: Identifiable {
    var id: String = UUID().uuidString

    // add the rest of the data associated with the cards, company, etc.

}

And if we want to follow the MVVM-structure you create a separate file for the functions (when we check like and unlike each card).
class CellViewModel: ObservableObject {

    @Published var card: CardData!
    @Published var isLiked = false

    func like() {
        isLiked.toggle()
    }

}

Now all our CellViews can be liked seperately (I removed some your inputs, for test)
struct CellView: View{
    //MARK: - PROPERTIES

    @ObservedObject var cellViewModel: CellViewModel = CellViewModel()

    init(cardData: CardData) {
        self.cellViewModel.card = cardData

    }

    //MARK: - BODY
    var body: some View{
        VStack{
            VStack{
                Image(systemName: "circle")
                    .resizable()
                    .aspectRatio(contentMode: .fit)

                    .overlay(RoundedRectangle(cornerRadius: 10).stroke(Color("GrayWhite"), lineWidth: 0.5)
                    )
            }.background(Color.white)
                .cornerRadius(10)

            VStack{
                HStack{

                    Text(" ₽")
                        .font(.system(size: 16, weight: .bold))
                        .foregroundColor(Color("BlackWhite"))

                    Spacer()

                    Button(action: {
                        cellViewModel.like()
                    }, label: {
                        Image(systemName: cellViewModel.isLiked ? "heart.fill" : "heart")
                            .frame(width: 22, height: 22)
                            .foregroundColor(cellViewModel.isLiked ? .red : .black)
                    })
                }.padding(.bottom, 1)

                HStack{
                    Text("company")
                        .font(.system(size: 14, weight: .bold))
                        .lineLimit(1)
                        .foregroundColor(Color("BlackWhite"))
                    Spacer()
                }

                HStack{
                    Text("name")
                        .font(.system(size: 14, weight: .bold))
                        .lineLimit(1)
                        .foregroundColor(.gray)
                    Spacer()
                }
            }
            .padding(.horizontal, 2)
        }
        .padding(5)
    }
}

Testing liking seperately:
struct ContentView: View {

    var body: some View {

        VStack {
            CellView(cardData: CardData())
            CellView(cardData: CardData())
            CellView(cardData: CardData())
            CellView(cardData: CardData())

        }

    }
}


text:
Q: Prove that $P_nTP_nh \longrightarrow Th$ as $n \to \infty.$
Let $\{e_n \}_{n \in \Bbb N}$ be an orthonormal basis of a Hilbert space $\mathcal H$ and $P_n$ be the orthogonal projection onto $\text {span}\ \{e_1,e_2, \cdots , e_n \},\ n \geq 1.$ Prove that for all bounded linear operator $T : \mathcal H \longrightarrow \mathcal H$ and $h \in H,$ $P_nTP_nh \longrightarrow Th$ as $n \to \infty.$

We can write $h = \displaystyle\sum\limits_{n=1}^{\infty} \left \langle h, e_n \right \rangle e_n.$ Then $P_nTP_n h = \displaystyle\sum\limits_{k=1}^{n} \left \langle h, e_k \right \rangle P_n T e_k.$ Since $M = \text {span} \{e_1,e_2, \cdots , e_n \}$ is a finite dimensional subspace of $\mathcal H$ of dimension $\geq 1$ it follows that $M$ is a non-zero closed subspace of the Hilbert space $\mathcal H$ and hence $\|P_n\|_{\text {op}} = 1$ (because $P_n$ is a projection onto $M$). Now my idea is to to show $\|P_nTP_nh - Th\|  \longrightarrow 0$ as $n \to \infty.$
But how do I do that? Any help in this regard will be highly appreciated.
Thanks in advance.

A: $\newcommand{nrm}[1]{\left\lVert{#1}\right\rVert}$\begin{align}\nrm{P_nTP_nh-Th}&=\nrm{P_nTP_nh-P_nTh+P_nTh-Th}\le\\&\le \nrm{P_nT(P_nh-h)}+\nrm{P_nTh-Th}\le\\&\le \nrm{P_n}\nrm T\nrm{P_nh-h}+\nrm{P_nTh-Th}\le\\&\le \nrm T\nrm{P_nh-h}+\nrm{P_nTh-Th}\to0\end{align}


text:
Q: a small doubt with partial derivative This is is pretty straightforward. I have a function, say $X = X(q)$. And $q=q_1+q_2(q_1)$. So X is a function of q, and q is a function of $q_1,q_2$. But $q_2$ is also a function of $q_1$. Now calculate
$\frac{\partial X}{\partial q_1}$
I proceed like:
$\frac{\partial X}{\partial q_1} = \frac{\partial X}{\partial q} \cdot \frac{\partial q}{\partial q_1}= \frac{\partial X}{\partial q} \cdot (1+\frac{\partial q_2}{\partial q_1}) $
Is this correct? Any insight or any more detailed expression that i am missing will be useful.

A: This is a problem you encounter early and often in calculus of variations and Lagrangian mechanics. Here is how it is resolved there:

*

*You can consider $X$ as a function of the single variable $q$. In that case, you can ask about $\frac{dX}{dq}=X'(q)$

*You can consider $X$ as a function of the two (independent) variables $q_1,q_2$, and in that case, you can ask about $\frac{\partial X}{\partial q_1}$ and $\frac{\partial X}{\partial q_2}$, both of which happen to be equal to $X'(q_1+q_2)$.

*You can consider $X$ as a function of the single variable $q_1$, and in that case you can ask about $$\frac{dX}{dq_1}=\frac{\partial X}{\partial q_1}\cdot\frac{dq_1}{dq_1}+\frac{\partial X}{\partial q_2}\cdot \frac{dq_2}{dq_1}\\=X'(q_1+q_2(q_1))\cdot \left(1+q_2'(q_1)\right)$$
It is easy to mix cases 2 and 3, but that makes no sense. It's one or the other.

A: $X(q)$, $X(q_1)$ and $X(q_1,q_2)$ are three different functions which happen to have the same name. Let me expand on that (I am going to assume that $q_1$, $q_2$ and the $X$s all take real values) ...
$X(q_1,q_2)$ is a function from $\mathbb{R}^2$ to $\mathbb{R}$. It is defined for any pair of values $(q_1, q_2)$ in $\mathbb{R}^2$ (or, possibly, in some region $U \subset \mathbb{R}^2$). As such, its has partial derivatives $\frac{\partial X}{\partial q_1}$ and $\frac{\partial X}{\partial q_2}$ at each point $P \in \mathbb{R}^2$ (provided $X$ is continuous and is defined in some open region around $P$).
If we now introduce $q$ then $X(q)$ is a function from $\mathbb{R}$ to $\mathbb{R}$. As such it has a derivative $\frac{dX}{dq}$ (subject to the usual assumptions about continuity etc.) at each point $p \in \mathbb{R}$. If we further say that $q=q_1+q_2$ then we have defined a function $q(q_1,q_2)=q_1+q_2$ from $\mathbb{R}^2$ to $\mathbb{R}$, and we can define an implicit function $Y(q_1,q_2) = (X \circ q)(q_1,q_2) = X(q_1+q_2)$. The connection between the derivative of $X$ and the partial derivatives of $Y$ is
$\frac{\partial Y}{\partial q_1} = \frac{dX}{dq}\frac{\partial q}{\partial q_1}\\
\frac{\partial Y}{\partial q_2} = \frac{dX}{dq}\frac{\partial q}{\partial q_2}\\$
If we then say that $q_2$ is a function $Q_2: \mathbb{R} \to \mathbb{R}$ of $q_1$ then we are restricting our attention to the curve $q_2=Q_2(q_1)$ in $\mathbb{R}^2$ which we are paramterising by the value $q_1$ (which now serves double duty both as a co-ordinate in $\mathbb{R}^2$ and as a parameter of the curve). We now have yet another implicit function $Z:\mathbb{R} \to \mathbb{R}$ defined by $Z(q_1) = Y(q_1, Q_2(q_1)) = X(q_1+Q_2(q_1))$ and
$\frac{dZ}{dq_1} = \frac{\partial Y}{\partial q_1} + \frac{\partial Y}{\partial Q_2}\frac{dQ_2}{dq_1} = \frac{dX}{dq}\left(\frac{\partial q}{\partial q_1}+ \frac{\partial q}{\partial Q_2}\frac{dQ_2}{dq_1} \right)$
which tells us how $X(q)$ varies along the curve $q_2=Q_2(q_1)$.
By convention we often rename $Y(q_1,q_2)$ as $X(q_1,q_2)$ and $Z(q_1)$ as $X(q_1)$ and we depend on context to tell us which $X$ is meant on each occassion that we use the name, but this can be confusing (as you have found).

A: It seems correct to me but you can remove the partial sign of $\frac{\partial q_2}{\partial q_1}$ becasuse $q_2$ depends on the single variable $q_1$,
$$\frac{\partial X}{\partial q_1}=\frac{\partial X}{\partial q}(1+\frac{d q_2}{d q_1})$$

A: Partial differentiation depends on the explicit form of the expression. Consider applying chain rule to compute a full derivative of an example function
$\frac{df(x, y)}{dt} = \frac{\partial f}{\partial x} \frac{dx}{dt} +
 \frac{\partial f}{\partial y} \frac{dy}{dt} +
 \frac{\partial f}{\partial t}
$
If we were forced to explicitly rewrite $x$ and $y$ in terms of $t$, there would be no difference between a full and a partial derivative.
I would argue that, in your example, the calculation might not be correct, in case $q_2$ is an implicit function of $q_1$. Please have a look at the example from fluid dynamics  to get the feeling for the difference between these two types of derivatives

A: There are only functions of a single variable here, so partial derivatives are irrelevant. By the ordinary chain rule,
$$\frac{dX}{dq_1}=\frac{dX}{dq}\frac{dq}{dq_1}=X'\left(1+\frac{dq_2}{dq_1}\right)=X'(1+q_2').$$
The $'$ denotes differentiation with respect to the argument.

Technically, you can consider that $q=q_1+q_2$ is a function of two variables and write
$$dq=\frac{\partial q}{\partial q_1}dq_1+\frac{\partial q}{\partial q_2}dq_2=dq_1+dq_2,$$ which justifies
$$\frac{dq}{dq_1}=1+\frac{dq_2}{dq_1},$$
but this is the only place where partials can be used, and in a contrived way.


text:
Q: mysql join query with sum retuns null If makale_payments table is null the query returns null. How shoul i set the query yo get recors if doesnt exist in SUM(payment_total) like 0.00 ?
SELECT article_name,user_real_name,user_name,SUM(`article_payment`) as holding,paid
FROM makale_articles AS t1
JOIN makale_users ON (t1.article_name=makale_users.user_id)
JOIN (SELECT user_id,SUM(`payment_total`) as paid FROM makale_payments GROUP BY user_id) AS t2 ON (t1.article_name=t2.user_id)
GROUP BY t2.user_id

A: This is what IFNULL is for:
IFNULL(SUM(...), 0.0)

A: article_payment is probably NULL for some row. Try this:
SELECT
    article_name,
    user_real_name,
    user_name,
    SUM(COALESCE(`article_payment`, 0)) as holding,
    paid
FROM article_articles AS t1
JOIN article_users ON (t1.article_name=article_users.user_id)
JOIN (
    SELECT user_id, SUM(COALESCE(`payment_total`, 0)) as paid
    FROM article_payments
    GROUP BY user_id
) AS t2 ON (t1.article_name=t2.user_id)
GROUP BY t2.user_id

A: A simple WHERE wouldn't have hurt I guess
WHERE SUM(`article_payment`) > 0

A: MySQL does not return aggregate values for rows that return nulls, even if specifically testing for ISNULL.  ISNULL is only to check if a column is null, not if the relation returns null.  I did however find a (albeit very obscure) way to get around this limitation.  The basic premise is to union all two sql statements and use the two unioned query as a subquery to select from.
The unioned queryies would be of the form:
   select column1, column2, SUM(column3) as payment from tablea, tableb where....
   union all
   select column1, column2, 0.00 as payment from tablea --notice no join, and a specified value and alias for aggregate column

With the above query, you will get two rows for every row that the relation is not null, and one row when it is.  If you sum that rows and group by, then you should end up with the values you want.  So you then create a query that uses the above as the table to select from and sums the aggregate column:
   select column1, column2, SUM(payment) from

   (select column1, column2, SUM(column3) as payment from tablea, tableb where....
   union all
   select column1, column2, 0.00 as payment from tablea) as b
   group by column1, column2

I am probably off on the syntax of the query, sorry, I don't have MySQL here to test.


text:
Q: Parse malformed HTML content I know, malformed XML content is invalid and you should not work with it - but I have no other opportunity. I want to parse the website of a service and there is a missing closing tag.
I am using the XMLPullParser from Android and I get this exception:
XmlPullParserException: expected: /div read: a (position:END_TAG @40:104)

The problem is this part:

I don't want to use a third party library if its not really necessary.
Regards and happy new year!

A: Try setting the "RELAXED FEATURE" on the parser. It will be more lenient. See docs:
http://developer.android.com/reference/android/util/Xml.html#FEATURE_RELAXED

BUT... I also note your trying to parse HTML with that XML Parser. Your going to run into issues because HTML is NOT XML and many sites do not use xhtml. You will create a lot less headaches for yourself if you use an HTML Parser instead. I've not used this one but I hear it works pretty well on Android. I am sure there are others which you can find with a little googlology. But I would strongly recommend you use an HTML parser to parse HTML :)
http://jsoup.org/


text:
Q: "Uncaught TypeError: Object(...) is not a function" error on Vue 2.6.12 My situation: IE11 support required.
Current version in my project

*

*Vue : 2.6.12 (Requirement version from my client cuz Vue3.x doesn't
support ie11 perfectly)

*v-calendar : 3.0.0-alpha.4

*babel-polyfill :6.26.0

It occurs this error

Module parse failed: Unexpected token (5222:58)

on console, so I tried to change the webpack.base.conf as below:
{
  test: /\.js$/,
  loader: 'babel-loader',
  include: [resolve('src'), resolve('test'), resolve('node_modules/webpack-dev-server/client'), resolve('node_modules/v-calendar')]
},

and then I got this error

Uncaught TypeError: Object(...) is not a function

on Chrome dev tool and

export 'h' was not found in 'vue'

on console ....(eslint message)
What should I do about it?