text:
Q: Horizontal scrolling text? Can anyone provide any tips when it comes to implementing some text that scrolls horizontally?
Right now I have a ScrollView *scrollView with a UILabel *textLabel inside of it.
I have the position of the label changing within the view until it is outside the bounds of the screen. The label is then reset to its original position and it starts scrolling again.
The problem(s) I am having are when I say: [textLabel sizeToFit];
This takes away the labels ability to handle multiple lines of text because once I say [textLabel sizeToFit]; it changes it into one big string.
Is there a simpler way to achieve the desired effect?
ANY help is greatly appreciated
P.S. The text inside of the label will be parsed from a website... so the size/length of the string will not be consistant.

A: try this
    CGSize maximumLabelSize = CGSizeMake(widthOfLabel, 9999);
    CGSize expectedLabelSize = [@"Text" sizeWithFont:[UIFont fontWithName:@"Helvetica" size:14] constrainedToSize:maximumLabelSize lineBreakMode:UILineBreakModeWordWrap];

then you can use expectedLabelSize.height or expectedLabelSize.width and change the frame size of UILabel


text:
Q: how does mypy type checking work? -in vscode I'm hoping to get some clarification or a good starting point to learn about mypy, specifically around the idea of type checking within my code editor, vscode. I've installed mypy in the virtualenv I'm working in and successfully selected it as the linter under Python: Select Linter, Python: Run Linting. I do see some expected behaviors when testing snippets such as:
l: List[str] = [1, 'a', 'b']

where I have an error message prompting:
List item 0 has incompatible type "int"; expected "A" mypy(error)
I also tested something like:
class A: ...

l: List[A] = [42]

where I also get an expected error of List item 0 has incompatible type "int"; expected "A" mypy(error)
However when I'm working with objects defined outside the scope of my project, i.e external libs, I don't see the behavior I would expect:
from pandas import DataFrame

l: DataFrame = 42 # no error

I've seen similar issues, or lack of, with using other libs such as the Google Ads sdk and I'm not sure why or if I'm even getting the right picture here of how mypy works. Any clarification would be greatly appreciated. Thank you.
UPDATE:
Per clarification from the comments, type stubs are necessary to enforce type checking, however, in the specific case of the google-ads-python client library, there are types available here
that seem to fit this purpose. When testing an example:
from google.ads.googleads.v11.services.types.customizer_attribute_service import CustomizerAttributeOperation

l: List[CustomizerAttributeOperation] = [1, 2, 3] # no error

This will still not raise an error. Do type stubs require a particular format in order to be considered a type stub, e.g. the extension .pyi?

redpajama_set_name: RedPajamaStackExchange


text:
Q: autoPlay not working for stream I just setup flowplayer to play rtmp streams, but for some reason I need to click on the splash screen (Play stream text) to start the video even though I have autoPlay: true.
Is this a bug, or am I missing some configuration settings?
<!-- video -->
        <div id="stream" class="stream" style="width: 1000px; height: 650px; display: block;">
            Play stream text
        </div>

    <script type="text/javascript">
         flowplayer("stream", "/flowplayer/flowplayer-3.2.7.swf", {

            clip: {
                url: 'mystream',
                live: 'true',
                provider: 'rtmp',
                scaling: 'orig',
                autoPlay: true
            },

            plugins: {
                rtmp: {
                    url: '/flowplayer/flowplayer.rtmp-3.2.3.swf',
                    netConnectionUrl: 'rtmp://mms.mysite.com/live/'
                }
            },

            canvas: {
                backgroundGradient: 'none'
            }
        });
    </script>

A: I guess the reason is that the so called splash screen should not be used as the way you suggest. If you put anything between the div, or as the documents to use , it always becomes a click-able area and the autoPlay true will come into place only when the player being really loaded (after you clicked).
I think the better way to go for the splashscreen would to use the recommended way in the document: http://flowplayer.org/documentation/skinning/


text:
Q: Is possible set Expanded Notification as default in Big Text Notifications? I followed this Sample Code
In Big Text Notifications section, he said that need expand to see Big text notification form, as image im below :

I wonder that we can not set Expanded Notification as default in Big Text Notifications?
People who know it is can or not,
If can,
Please tell me how to do it,
Thanks,

A: The documentation states:

A notification's big view appears only when the notification is
  expanded, which happens when the notification is at the top of the
  notification drawer, or when the user expands the notification with a
  gesture.

So my answer is no, you can't expand it by default.
There is however a trick to push the notification to the top of the list where it would be expanded. Simply set the Priority to Notification.PRIORITY_MAX and chances are that your app's notification will make it to the top.

A: Notification noti = new Notification.Builder()
... // The same notification properties as the others
.setStyle(new Notification.BigPictureStyle().bigPicture(mBitmap))
.build();

You change
.setStyle(new NotificationCompat.BigTextStyle().bigText(th_alert))

along with the announcement
notification = new NotificationCompat.Builder(context)

Here is an example:
You can set Code
Intent intent = new Intent(context, ReserveStatusActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
NotificationManager notificationManager =
            (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
intent = new Intent(String.valueOf(PushActivity.class));
intent.putExtra("message", MESSAGE);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
stackBuilder.addParentStack(PushActivity.class);
stackBuilder.addNextIntent(intent);
// PendingIntent pendingIntent =
stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);

// android.support.v4.app.NotificationCompat.BigTextStyle bigStyle = new     NotificationCompat.BigTextStyle();
// bigStyle.bigText((CharSequence) context);

notification = new NotificationCompat.Builder(context)
    .setSmallIcon(R.mipmap.ic_launcher)
    .setContentTitle(th_title)
    .setContentText(th_alert)
    .setAutoCancel(true)
 // .setStyle(new Notification.BigTextStyle().bigText(th_alert)  ตัวเก่า
 // .setStyle(new NotificationCompat.BigTextStyle().bigText(th_title))
    .setStyle(new NotificationCompat.BigTextStyle().bigText(th_alert))
    .setContentIntent(pendingIntent)
    .setNumber(++numMessages)
    .build();

notification.sound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
notificationManager.notify(1000, notification);

A: notificationBuilder.setStyle(new NotificationCompat.BigTextStyle().bigText("Your Long Text here"))

simply setStyle of your notification builder.

A: No need of doing any kind of modification in the any file for showing of multiple lines of Notification while using Push Notification V5, remove the field "style", from the object you are sending. Automatically the Multiple lines of notification will be seen. For more information, upvote the answer, ask your query. I will help you out.
For reference, visit this question

A: From this notification code you have got images, and big text or more.
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context);
            if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                mBuilder.setSmallIcon(R.drawable.small_logo);
                mBuilder.setColor(Color.parseColor("#D74F4F"));
            } else {
                mBuilder.setSmallIcon(icon);
            }

            mBuilder.setTicker(title).setWhen(when);
            mBuilder.setAutoCancel(true);
            mBuilder.setContentTitle(title);
            mBuilder.setContentIntent(intent);
            mBuilder.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
            mBuilder.setLargeIcon(BitmapFactory.decodeResource(context.getResources(), icon));
            mBuilder.setContentText(msg);
            mBuilder.setPriority(Notification.PRIORITY_MAX);
            if (Utils.validateString(banner_path)) {
                mBuilder.setStyle(notiStyle);
            } else {
                mBuilder.setStyle(new NotificationCompat.BigTextStyle().bigText(msg));
            }

            Notification noti = mBuilder.build();
            notificationManager.notify(0, noti);


text:
Q: (PHP) Problem with filename after downloading it While writing a PHP-Script, im stuck at an issue i cant resolve.
The PHP-Script consist in letting a user download a .mp4 file. The download works without any issues but the file downloaded can not be played.
Heres the code:
<?php
  $filepath = "/www/servermedia/technounion.mp4";
  $filename = basename($filepath);

  header("Content-type: video/mp4");
  header("Content-Disposition: attachment; filename=.$filename");
  readfile($filename);
  exit;
 ?>

After the .mp4 file gets downloaded, it cannot be played.
It looks like this:
The error message means that Windows Media Player cannot play back the file because probably the player doesnt support the codec. I already tried with VLC but it does not work either.
EDIT:
Comparing both file sizes, the downloaded file is only a couple bytes large instead of the 3,73 MB of the file on the server

A: Is the downloaded file the exact same filesize?
Does the content type exist in your webserver?
header("Content-Type: video/mp4"); Note capital 'T' for type.
This maybe worth testing with to see you can serve the file content inline:
http://www.phpmind.com/blog/2016/10/how-to-use-php-to-output-an-mp4-video/

A: Your code is not well-formed, you miss to escape double-quotes by adding single-quotes as I done here, please test my answer.
<?php
  $filepath = "/www/servermedia/technounion.mp4";
  $filename = basename($filepath);
  header('Content-Type: video/mp4');
  header('Content-Disposition: attachment; filename="' . $filename . '"');
  readfile($filename);
  exit;
?>

But I suggest a more complex way:
<?php
  $filepath = $_SERVER['DOCUMENT_ROOT'] . "/www/servermedia/technounion.mp4";
  $filename = basename($filepath);
  header('Content-Type: video/mp4');
  header('Content-Disposition: attachment; filename="' . $filename . '"');
  header('Content-Transfer-Encoding: binary');
  header('Connection: Keep-Alive');
  header('Expires: 0');
  header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
  header('Pragma: public');
  header('Content-Length: ' . sprintf("%u", filesize($filepath)));
  set_time_limit(0);
  $fh = fopen($filepath, "rb");
  while (!feof($fh)) {
    echo fgets($fh);
    ob_flush();
    flush();
  }
  fclose($fh);
  exit;
?>

$_SERVER['DOCUMENT_ROOT'] is useful to get the full path from the server
set_time_limit(0) is useful to avoid any timeout during download
fgets() is useful for reading large files
ob_flush() and flush() assure that there is not other output in the buffer
I hope this helps.


text:
Q: Does react subrender function must return content in the only one external tag? I have some subrender function called from main react render:
renderDueDateCell(){
    if(this.props.DueDate != null){
        return(

                { this.props.DueDate }

        )
    }
    return null
}

It works fine until I remove external div, which I do not need. Then I go syntax errors which I can't deal with. Is this related to the fact that there must be one most external tag ( in my case this div ) ?

A: Fragments
You can use Fragment
renderDueDateCell(){
    if(this.props.DueDate != null){
        return(
            <>
                { this.props.DueDate }

            </>
        )
    }
    return null
}

Note:- <> is Fragment short syntax


text:
Q: How to pass i18n key from parent to child component before translation starts? I'am using an input-field component which I can embed in different parent components using forms.
In the input child component, I have an i18n translation key as variable using interpolation, which I would like to generate dynamically from parent component, based on customer choice.
input.component.ts:

{{labelText}}

    <input matInput [required]="required"
                    [name]="name"
                    [(ngModel)]="value"
                    [type]="type">

form.component.ts:
<app-input [labelText]="'Second name'"
           [labelTextKey]="'@@LabelSecondName'"
           [name]="'secondName'"
           [ngModel] = "secondName"
           [type] = "'text'"
</app-input>

The issue is that when running the app, the translation occurs before the key is being passed to the variable in the child component, and therefore there is no translation for the key/id: @@LabelSecondName.
So, the labelText keep the original language. Instead of translation, I get a kind of digits which are being generated randomly and as those digits as a key don't exist in the XLF (Version 2.0) file, the text/label is not translated.

Error message: Missing translation for message "8901569964118207331"

The behavior is in a way expected, because the variable: labelTextKey doesn't get the value: @@LabelSecondName passed right in time.
Have been searching, but not able to find a correct solution for that. This question seems to be closer to mine, but not exact the same case, and there also no answer.

A: Issue fixed. Solution:
No need of i18n tag in the child component, just use it in the parent like this:
<app-input i18n-labelText="@@LabelSecondName" labelText="Second name"></app-input>

so, the whole code will look as .:
<app-input [labelText]="'Second name'"
       i18n-labelText="@@LabelSecondName"
       [name]="'secondName'"
       [ngModel] = "secondName"
       [type] = "'text'"
</app-input>


text:
Q: How to wrap jqueryUI tooltip with custom div? So by default, a tooltip is created with the parent div containing .ui-tooltip. Is there any way I can do something like this to wrap .ui-tooltip in a custom div, without using another library?
$(tooltipTrigger).tooltip({
  tooltipClass: "custom-tooltip-styling", // this works
  tooltipWrapper: "

" // this is what I want to work
});

I basically want the output to look like this:

I tried using .wrap() within .tooltip(), but that didn't seem to work. Any ideas?

A: You could use the open - event to wrap your div around the created tooltip:
$(document).tooltip({
    tooltipClass: "custom-tooltip-styling",
    open: function(event, ui) {
      $(ui.tooltip).wrap("

");
    },
    close: function(event, ui) {
        $('.custom-tooltip-wrapper').remove();
    }
});

However, you need to style your wrapper accordingly, it otherwise will just appear at the end of the page.
I use the close - event here to get rid of the wrapper afterwards.

Example


text:
Q: Java IntelliJ: Change existing class usages to a new class In Java Spring Boot using IntelliJ, how do I refactor existing class usages to a different class? I don't want to rename an existing class, but migrate to a new class. For example, change Fruit to Automobile class,
This reference does not help, https://www.jetbrains.com/help/idea/rename-refactorings.html#rename_class_example

A: You can try to use "Type migration" refactoring, see this

A: The problem, as you know, is that all usages of your class are linked to it in IntelliJ. You can solve this by relinking all the usages to the new class.
Say you have ClassA and ClassB. You want to move all usages of ClassA to use ClassB.
Step 1 - rename ClassA to ClassATemp. Make sure to not use Shift-F6 for this, i.e. don't use IntelliJ's refactoring rename. Just change the text. Do the same for the filename. Now you have successfully changed ClassA to ClassATemp, and your code is completely broken. Hurray!
Step 2 - rename ClassB to ClassA. During this step, links to ClassA will "re-establish", but with the new class. You may need to reimport everything to the new package, or alternatively change the package as well (might be more of a hassle).
Step 3 - re-rename the newly renamed ClassA back to ClassB. Make sure to do this using IntelliJ's refactor. All links will now follow.
Final step - re-rename ClassATemp to ClassA.

A: On the toolbar:
Edit -> Find -> Replace in Files...


text:
Q: Meaning of domain, application in URL what is the meaning of the "abc", "def" in the URL: http://abc.def.xyz.com . I understand xyz is called domain. I read somewhere abc is an application. How can i configure like this and where is it made? In a Java webapp, is it made in web.xml since i have not come across anything like that so far. Or is it made in servlet container/application server.
Any information on this is appreciated.

A: Calling 'abc' application it is only convention. There are no technical reason behind.
Technically speaking abc.def.xyz.com is domain name. As well as def.xyz.com, xyz.com and even com.
If you interest in this topic you can read further about domain names

A: "abc" and "def" are subdomains of "xyz", which in turn is a subdomain of the top-level domain "com". But domains directly under a top-level domain are rarely referred to as a subdomains.
Basically you can bind your domain names to whatever you want, it doesn't have to be a specific application.
Example:
Let's say you have your own personal domain mydomain.com, which is bound to the IP-address of your home router. You could have phone.mydomain.com point to the IP-address of your phone, www.mydomain.com to your remotely hosted web server and laptop.mydomain.com to your laptop. This is all set up by a DNS host (the name itself is managed by a registrar).
In other words, it has nothing to do with your application (aside from the convention of pointing certain domain names to the server hosting your application). Although I guess it's possible to have app1.mydomain.com and app2.mydomain.com point to the same application server, which then does some internal routing based on subdomains...


text:
Q: Create a runnable file from .java files and png images I have 2 individual .java files, and in those files, I have taken in some buffered images, which are 3 .png files. I want to turn this grouping, the 2 java files and the 3 png images into a single file that can be opened and executed without a compiler. How do I do this?

A: You have to build a jar file for this. So you will be able to run your application by double clicking on your .jar file. If you are using netbeans to develop you can simply do it by right click on your application and by selecting clean and build.
I hope this link will help you.


text:
Q: How to change or delete tags in boost serialization? I'm trying to serialize my classes to xml. My classes;
class HardwareDto{
    friend class boost::serialization::access;
    template<class Archive> void serialize(Archive & ar, const unsigned int version) {
        ar & BOOST_SERIALIZATION_NVP(HardwareID);
        ar & BOOST_SERIALIZATION_NVP(HardwareHostID);
        ar & BOOST_SERIALIZATION_NVP(HardwareFriendlyName);
    }
public:
    int HardwareID;
    int HardwareHostID;
    string HardwareFriendlyName;
    inline HardwareDto(int HardwareHostID, int HardwareID, string HardwareFriendlyName) {
        this->HardwareHostID = HardwareHostID;
        this->HardwareID = HardwareID;
        this->HardwareFriendlyName = HardwareFriendlyName;
    }
};

And a class which contains a HardwareDto list.
class HardwareHostDto {
private:
    friend class boost::serialization::access;
    template<class Archive> void serialize(Archive & ar, const unsigned int version) {
        ar & BOOST_SERIALIZATION_NVP(HardwareHostID);
        ar & BOOST_SERIALIZATION_NVP(BranchID);
        ar & BOOST_SERIALIZATION_NVP(HardwareHostFriendlyName);
        ar & BOOST_SERIALIZATION_NVP(HardwareList);
    }

public:
    int HardwareHostID;
    int BranchID;
    string HardwareHostFriendlyName ;
    HardwareDto* HardwareList[20];

    inline HardwareHostDto(int HardwareHostID, int BranchID, string HardwareHostFriendlyName, HardwareDto* HardwareList[20]) {
        this->HardwareHostID = HardwareHostID;
        this->BranchID = BranchID;
        this->HardwareHostFriendlyName = HardwareHostFriendlyName;
        this->HardwareList[0] = HardwareList[0];
    }
};

And
HardwareDto *HardwareList[20];

is my global hardwaredto list. In this example I only inserted one hardwarehostdto object into this list.
I'm trying to serialize this via boost function:
std::ofstream ofs("filename.xml");

unsigned int flags = boost::archive::no_header;
boost::archive::xml_iarchive ia(is, boost::archive::no_header);
boost::archive::xml_oarchive oa(ofs, flags);

HardwareHostDto* HardwareHost = new HardwareHostDto(1, 1, "kiosk", HardwareList);

oa << BOOST_SERIALIZATION_NVP(HardwareHost);

After this code executed, i got this filename.xml:
<HardwareHost class_id="0">
    <HardwareHostID>1</HardwareHostID>
    <BranchID>1</BranchID>
    <HardwareHostFriendlyName>kiosk</HardwareHostFriendlyName>
    <HardwareList>
        <count>20</count>
        <item class_id="1">
            <HardwareID>2</HardwareID>
            <HardwareHostID>2</HardwareHostID>
            <HardwareFriendlyName>Ankara</HardwareFriendlyName>
        </item>
    </HardwareList>
</HardwareHost>

<item> tag should be <Hardware> but i cant change it.
My question is: is there any way to change <item> tag, or actullay customize this xml structure, like no <count> tag or flags? I found a few ways to do it in boost website but couldnt handle it.
Thank you.

A: Yes, you can hack it. Maybe. To an extent. See:

*

*how to customise default Boost xml Serialisation default node naming to make it more readable

*How to use Boost XML Parser

*deserialization issue after changing namespace to customise tag names for boost xml
And no, you shouldn't. Use an XML library to write arbitrary XML.
Boost Serialization only does serialization. The archive format is implementation detail.

Bad Example
What not to do (it breaks non-default constructible types, it breaks versioning).
On the bright side, this code doesn't leak memory.
Live On Coliru
#include <boost/archive/xml_iarchive.hpp>
#include <boost/archive/xml_oarchive.hpp>
#include <boost/serialization/serialization.hpp>
#include <boost/serialization/vector.hpp>

class HardwareDto {
    friend class boost::serialization::access;
    template <class Archive> void serialize(Archive &ar, unsigned) {
        ar &BOOST_SERIALIZATION_NVP(HardwareID);
        ar &BOOST_SERIALIZATION_NVP(HardwareHostID);
        ar &BOOST_SERIALIZATION_NVP(HardwareFriendlyName);
    }

  public:
    int HardwareHostID;
    int HardwareID;
    std::string HardwareFriendlyName;

    HardwareDto(int HardwareHostID = -1, int HardwareID = -1, std::string HardwareFriendlyName = {})
       : HardwareHostID(HardwareHostID),
         HardwareID(HardwareID),
         HardwareFriendlyName(HardwareFriendlyName)
    { }
};

using HardwareDtoList = std::vector<HardwareDto>;

class HardwareHostDto {
  private:
    friend class boost::serialization::access;
    template <class Archive> void serialize(Archive &ar, unsigned) {
        ar &BOOST_SERIALIZATION_NVP(HardwareHostID);
        ar &BOOST_SERIALIZATION_NVP(BranchID);
        ar &BOOST_SERIALIZATION_NVP(HardwareHostFriendlyName);
        ar &BOOST_SERIALIZATION_NVP(HardwareList);
    }

  public:
    int HardwareHostID;
    int BranchID;
    std::string HardwareHostFriendlyName;
    HardwareDtoList HardwareList;

    HardwareHostDto(int HardwareHostID, int BranchID, std::string HardwareHostFriendlyName, HardwareDtoList HardwareList)
        : HardwareHostID(HardwareHostID),
          BranchID(BranchID),
          HardwareHostFriendlyName(HardwareHostFriendlyName),
          HardwareList(HardwareList)
    { }
};

namespace boost { namespace serialization {
    template <typename Ar>
        void serialize(Ar& ar, std::vector<HardwareDto>& v, unsigned) {
            size_t count = v.size();
            ar & BOOST_SERIALIZATION_NVP(count);
            v.resize(count);

            for (auto& el : v)
                ar & boost::serialization::make_nvp("Hardware", el);
        }
} }

#include <fstream>
#include <iostream>

int main() {
    unsigned int flags = boost::archive::no_header;

    {
        HardwareDtoList HardwareList;
        HardwareList.emplace_back(1, 2, "friendly");

        std::ofstream ofs("filename.xml");
        boost::archive::xml_oarchive oa(ofs, flags);

        HardwareHostDto host(1, 1, "kiosk", HardwareList);

        oa << boost::serialization::make_nvp("HardwareHost", host);
    }

    {
        HardwareHostDto roundtrip(-1, -1, "", {});
        std::ifstream ifs("filename.xml");
        boost::archive::xml_iarchive ia(ifs, flags);

        ia >> boost::serialization::make_nvp("HardwareHost", roundtrip);

        std::cout << "Read back: " << roundtrip.HardwareHostID << "\n";
        std::cout << "Read back: " << roundtrip.BranchID << "\n";
        std::cout << "Read back: " << roundtrip.HardwareHostFriendlyName << "\n";
        for (auto& h: roundtrip.HardwareList) {
            std::cout << "Item: " << h.HardwareID << ", " << h.HardwareHostID << ", " << h.HardwareFriendlyName << "\n";
        }
    }

}

Prints
Read back: 1
Read back: 1
Read back: kiosk
Item: 2, 1, friendly

And writes the XML as:
<HardwareHost class_id="0" tracking_level="0" version="0">
    <HardwareHostID>1</HardwareHostID>
    <BranchID>1</BranchID>
    <HardwareHostFriendlyName>kiosk</HardwareHostFriendlyName>
    <HardwareList class_id="1" tracking_level="0" version="0">
        <count>1</count>
        <Hardware class_id="2" tracking_level="0" version="0">
            <HardwareID>2</HardwareID>
            <HardwareHostID>1</HardwareHostID>
            <HardwareFriendlyName>friendly</HardwareFriendlyName>
        </Hardware>
    </HardwareList>
</HardwareHost>

What To Do
Using an XML library. This calls for (a lot) generalization, but here's a start using PugiXML:
Live On Coliru
#include <pugixml.hpp>
#include <iostream>
#include <vector>

struct HardwareDto {
    int HardwareHostID;
    int HardwareID;
    std::string HardwareFriendlyName;
};

struct HardwareHostDto {
    int HardwareHostID;
    int BranchID;
    std::string HardwareHostFriendlyName;
    std::vector<HardwareDto> HardwareList;
};

struct Xml {
    struct Saver {
        template <typename T>
        void operator()(pugi::xml_node parent, std::string const& name, T const& value) const {
            auto node = named_child(parent, name);
            node.text().set(to_xml(value));
        }

        void operator()(pugi::xml_node parent, std::string const& name, HardwareDto const& o) const {
            auto dto = named_child(parent, name);
            operator()(dto, "HardwareHostID", o.HardwareHostID);
            operator()(dto, "HardwareID", o.HardwareID);
            operator()(dto, "HardwareFriendlyName", o.HardwareFriendlyName);
        }

        template <typename C>
        void operator()(pugi::xml_node parent, std::string const& name, std::string const& item_name, C const& container) const {
            auto list = named_child(parent, name);

            for (auto& item : container)
                operator()(list, item_name, item);
        }

        void operator()(pugi::xml_node parent, std::string const& name, HardwareHostDto const& o) const {
            auto dto = named_child(parent, name);
            operator()(dto, "HardwareHostID", o.HardwareHostID);
            operator()(dto, "BranchID", o.BranchID);
            operator()(dto, "HardwareHostFriendlyName", o.HardwareHostFriendlyName);
            operator()(dto, "HardwareList", "Hardware", o.HardwareList);
        }
      private:
        // serialization
        template <typename T> static T const& to_xml(T const& v) { return v; }
        static char const* to_xml(std::string const& v) { return v.c_str(); }

        pugi::xml_node named_child(pugi::xml_node parent, std::string const& name) const {
            auto child = parent.append_child();
            child.set_name(name.c_str());
            return child;
        }
    };

    struct Loader {
        void operator()(pugi::xml_node parent, std::string const& name, std::string& value) const {
            auto node = parent.first_element_by_path(name.c_str());
            value = node.text().as_string();
        }
        void operator()(pugi::xml_node parent, std::string const& name, int& value) const {
            auto node = parent.first_element_by_path(name.c_str());
            value = node.text().as_int();
        }

        void operator()(pugi::xml_node dto, HardwareDto& o) const {
            operator()(dto, "HardwareHostID", o.HardwareHostID);
            operator()(dto, "HardwareID", o.HardwareID);
            operator()(dto, "HardwareFriendlyName", o.HardwareFriendlyName);
        }

        void operator()(pugi::xml_node parent, std::string const& name, HardwareDto& o) const {
            auto dto = parent.first_element_by_path(name.c_str());
            operator()(dto, "HardwareHostID", o.HardwareHostID);
            operator()(dto, "HardwareID", o.HardwareID);
            operator()(dto, "HardwareFriendlyName", o.HardwareFriendlyName);
        }

        template <typename C>
        void operator()(pugi::xml_node parent, std::string const& name, std::string const& item_name, C& container) const {
            auto list = parent.first_element_by_path(name.c_str());

            for (auto& node : list) {
                if (node.type() != pugi::xml_node_type::node_element) {
                    std::cerr << "Warning: unexpected child node type ignored\n";
                    continue;
                }
                if (node.name() != item_name) {
                    std::cerr << "Warning: unexpected child node ignored (" << node.name() << ")\n";
                    continue;
                }

                container.emplace_back();
                operator()(node, container.back());
            }
        }

        void operator()(pugi::xml_node dto, HardwareHostDto& o) const {
            operator()(dto, "HardwareHostID", o.HardwareHostID);
            operator()(dto, "BranchID", o.BranchID);
            operator()(dto, "HardwareHostFriendlyName", o.HardwareHostFriendlyName);
            operator()(dto, "HardwareList", "Hardware", o.HardwareList);
        }

        void operator()(pugi::xml_node parent, std::string const& name, HardwareHostDto& o) const {
            operator()(parent.first_element_by_path(name.c_str()), o);
        }
    };
};

int main() {
    {

        pugi::xml_document _doc;
        Xml::Saver saver;

        HardwareHostDto host = { 1, 1, "kiosk", { { 1, 2, "friendly" } } };
        saver(_doc.root(), "HardwareHost", host);

        _doc.save_file("test.xml");
    }

    {
        HardwareHostDto roundtrip;
        {
            pugi::xml_document _doc;
            _doc.load_file("test.xml");
            Xml::Loader loader;

            loader(_doc.root(), "HardwareHost", roundtrip);
        }

        std::cout << "Read back: " << roundtrip.HardwareHostID << "\n";
        std::cout << "Read back: " << roundtrip.BranchID << "\n";
        std::cout << "Read back: " << roundtrip.HardwareHostFriendlyName << "\n";
        for (auto& h: roundtrip.HardwareList) {
            std::cout << "Item: " << h.HardwareID << ", " << h.HardwareHostID << ", " << h.HardwareFriendlyName << "\n";
        }
    }

}

Which also prints
Read back: 1
Read back: 1
Read back: kiosk
Item: 2, 1, friendly

And writes a test.xml:
<?xml version="1.0"?>
<HardwareHost>
    <HardwareHostID>1</HardwareHostID>
    <BranchID>1</BranchID>
    <HardwareHostFriendlyName>kiosk</HardwareHostFriendlyName>
    <HardwareList>
        <Hardware>
            <HardwareHostID>1</HardwareHostID>
            <HardwareID>2</HardwareID>
            <HardwareFriendlyName>friendly</HardwareFriendlyName>
        </Hardware>
    </HardwareList>
</HardwareHost>

A: In order to fully customize XML output from boost serialization you can write your own XML archive. It's a three step process:

*

*Define a class that writes primitive types, let's say TextOPrimitiveOnXML.

*Define a class that writes composite types: BasicXMLOArchive. This is the class that will write XML tags.

*Glue everything together into XMLOArchive.

The advantage is that not only you can reuse your serialize code, but also you can use different backends. For example, you can have an archive that creates a DOM right away instead of merely text output.
Here are skeletons for the classes I mentioned.
TextOPrimitiveOnXML, its save methods define writing of primitive types.
class TextOPrimitiveOnXML
{
protected:
  TextOPrimitiveOnXML()
  {}
  template <class T>
  void save(const T & t) {
  }
  void save(const bool t) {
  }
  void save(const signed char t) {
  }
  void save(const unsigned char t) {
  }
  void save(const char t) {
  }
  void save(const wchar_t t) {
  }
  void save(const char *t) {
  }
  void save(const wchar_t *t) {
  }
  void save(const std::string &t) {
  }
  void save(const std::wstring &t) {
  }
  void save_binary(const void *address, std::size_t count);
};

BasicXMLOArchive, this is where you manipulate tags and attributes:
template <class Archive>
class BasicXMLOArchive :
  public boost::archive::detail::common_oarchive<Archive>
{
  friend class boost::archive::detail::interface_oarchive<Archive>;
  friend class boost::archive::save_access;

  typedef boost::archive::detail::common_oarchive<Archive> base;

protected:
  void init() {
  }

  BasicXMLOArchive(unsigned int flags)
    : base(flags)
  {}

  template <class T>
  void save_override(T & t, int)
  {
    // If your program fails to compile here, its most likely due to
    // not specifying an nvp wrapper around the variable to
    // be serialized.
    BOOST_MPL_ASSERT((boost::serialization::is_wrapper<T>));
    this->base::save_override(t, 0);
  }

  // special treatment for name-value pairs.
  template <class T>
  void save_override(const boost::serialization::nvp<T> &t, int)
  {
  }

  void save_override(const boost::archive::object_id_type & t);
  void save_override(const boost::archive::object_reference_type & t);
  void save_override(const boost::archive::version_type & t);
  void save_override(const boost::archive::class_id_type & t);
  void save_override(const boost::archive::class_id_optional_type & t);
  void save_override(const boost::archive::class_id_reference_type & t);
  void save_override(const boost::archive::class_name_type & t);
  void save_override(const boost::archive::tracking_type & t);

public:
  boost::archive::library_version_type get_library_version() const {
    return boost::archive::library_version_type(0);
  }
};

The final glue:
template <class Archive>
class XMLOArchiveImpl :
    public TextOPrimitiveOnXML
  , public BasicXMLOArchive<Archive>
{
  friend class boost::archive::save_access;
public:
  XMLOArchiveImpl(unsigned int flags)
    : TextOPrimitiveOnXML()
    , BasicXMLOArchive<Archive>(flags)
  {
    init();
  }

  void save_binary(const void *address, std::size_t count){
    this->TextOPrimitiveOnXML::save_binary(address, count);
  }
};

class XMLOArchive :
  public XMLOArchiveImpl<XMLOArchive>
{
  friend class BasicXMLOArchive<XMLOArchive>;
public:
  XMLOArchive(unsigned int flags)
    : XMLOArchiveImpl(flags)
  {}
};


text:
Q: Forwarding accelerated OpenGL GLX via SSH I'm currently porting an open-source OpenGL game to OpenGL ES.  The target device runs Linux and has a relatively weak CPU (ARM11 family, with FPU).  It has an OpenGL ES accelerator but not an OpenGL one.
Initially I want to get the existing OpenGL-GLX-X11 implementation to run, using an accelerated OpenGL instance on another Linux machine - for example, an Athlon X2 with a Radeon X1650 Pro.  This will help to verify that there are no serious CPU bottlenecks that need to be sorted out at a high level.
I have managed to set up SSH forwarding of the X11 connection.  The glxinfo and glxgears programs run, but the latter has very poor performance (8fps) compared to a locally running glxgears (60fps with vsync).  The glxinfo report stated that Direct Rendering is being used, which tells me that the local (to the ARM device) software renderer is being used.
What I want to happen is for OpenGL commands to be sent to the Athlon X2 machine and accelerated using the Radeon.  I believe I need to turn on Indirect Rendering for this.  However, setting LIBGL_ALWAYS_INDIRECT=1 does not change anything.  For example:
arm$ LIBGL_ALWAYS_INDIRECT=1 glxinfo | fgrep rendering
direct rendering: Yes
arm$

The ARM device is running Gentoo Linux.  What is the best way to force what I want to happen?

A:
The glxinfo and glxgears programs run, but the latter has very poor performance (8fps) compared to a locally running glxgears (60fps with vsync). The glxinfo report stated that Direct Rendering is being used, which tells me that the local (to the ARM device) software renderer is being used.

I'm a bit puzzled by this. If you see the OpenGL output on the remote display, then this would mean that instead of GLX commands pictures are transmitted. This however would mean, that the libGL.so on your host device is X11 aware for its output, but won't use GLX.
Could you please determine which package contributes the libGL.so on your ARM device. I suggest you install a separate libGL.so with only GLX command generation and LD_PRELOAD that.
Mesa3D can be configured to build GLX command stream generator library.


text:
Q: Как сделать корзину товаров на сессиях для битрикс 1с? Подскажите как сделать корзину на сессиях для битрикс 1с. Я хочу, чтобы при нажатие на кнопку у меня добавлялся товар в корзину без перегрузки страницы. Я сделал следующим образом:
C помощью ajax-передаю post запросом передаю id элемента инфоблока:
function Buy(element_id) {
            const id = document.getElementById(element_id).value;
            var formData = new FormData();
            formData.append('id', id);
            var HttpRequest = new XMLHttpRequest();
            HttpRequest.onload = function(e) {
                if (this.status == 200) {}
            };
            HttpRequest.open("POST", '/personal/cart/', true);
            HttpRequest.send(formData);

        }

/personal/cart/
<?php
require_once($_SERVER['DOCUMENT_ROOT'] . '/bitrix/modules/main/include/prolog_before.php'); //Обязательная строка инициирующая движок Битрикса, но не подключающая шаблон
header('Content-Type: application/json');
session_start();
$id = $_POST['id'];
if (!empty($_SESSION['BX_CART'])) {
    $arChart = $_SESSION['BX_CART'];
} else {
    $arChart = array();
}
$arChart[$id]= [
    "id" => $id,

];
$_SESSION["BX_CART"]=$arChart;
foreach($_SESSION['BX_CART'] as $session){

    $arr[]=$session["id"];

}
\Bitrix\Main\Loader::includeModule('iblock');
$arSelect = Array("ID", "NAME", "DATE_ACTIVE_FROM");
$arFilter = Array("IBLOCK_ID"=>IntVal(8),"ID"=> $arr, "ACTIVE_DATE"=>"Y", "ACTIVE"=>"Y");
$res = CIBlockElement::GetList(Array(), $arFilter, false, Array(), $arSelect);
while($ob = $res->GetNextElement())
{
 $arField = $ob->GetFields();
 $arFields[]=$arField;

}
echo json_encode($arFields);

В этой части получаю массив из выбранных элементов из инфоблока.
//ЗДЕСЬ ПОЛУЧАЮ JSON
     $.ajax({
        url: '/personal/cart/',
        method: 'get',
        //dataType: 'html',
        success: function (data) {

         const postData= data;

         function BlogPost(postData) {
  return `

${postData.NAME}

By ${postData.PRICE}

`;
}
function BlogPostList(posts) {

  return `

            ${posts.map(BlogPost).join('')}

          <button class="button">ssss</button>
          `
}
function update() {
  document.querySelector('.cont').innerHTML = BlogPostList(postData);
}
update();

        }
    });

Мне нужно,чтобы при нажатие на кнопку товар добавлялся сразу,но он добавляется только после перезагрузки. Буду рад любой помощи!


text:
Q: How to find a root when FindRoot refuses After empirically setting x = 960, I find that
Total@Table[
   If[(v/x)[[i]] > Sqrt[Floor[(v/x)[[i]]] Ceiling[(v/x)[[i]]]],
   Ceiling[(v/x)[[i]]], Floor[(v/x)[[i]]]], {i, Length[v]}] - s

equals 0 for s=26 and v = {9061, 7179, 5259, 3319, 1182}
So I was expecting that
FindRoot[Total@Table[
   If[(v/x)[[i]] > Sqrt[Floor[(v/x)[[i]]] Ceiling[(v/x)[[i]]]],
   Ceiling[(v/x)[[i]]], Floor[(v/x)[[i]]]], {i, Length[v]}] == s,{x, 1,   Total[v]}]

will return  960 but unfortunately, the return is a warning
Part::pkspec1: The expression i cannot be used as a part specification.

I ask certainly too much to FindRoot but is there simple  way to find the expected result algorithmicaly in MA


text:
Q: Does PM2 Automatically Detects Apps for the Modules System? In PM2 v1.0, it was mentioned that the new Modules System allows us to monitor application on a remote server. When I checked my Keymetrics dashboard, I discovered that there are already modules that are monitoring apps and data regarding CPU usage, Memory, etc.. Does PM2 automatically detects this when I monitored one of my apps?
I can recognized several apps (MySQL and RabbiMQ) that are being monitored, but I am confused because there are apps (elastic, redis, etc.) that I do not remember configured in my server (or I do not know they exists or perhaps pre-configured by a ZendServer installation).
Also note that I haven't upgraded pm2 to ver 1 in my server.
Specs.:

*

*pm2 v 0.15.10

A: PM2 does not automatically monitor apps in Keymetrics configured in a server unless the module server-monitor was installed in PM2 and you enabled monitoring for a specific app . Most of the apps listed in Keymetrics only contains static dummy data.


text:
Q: Plotly plots opening in non-default .html viewer when folder path contains '#' I am trying to plot some data in plotly and have noticed that occasionally the output plots do not open in my default .html viewer (Microsoft Edge) but open up in Internet Explorer instead. This only seems to happen when the folder I am putting the plot in contains a # character.
I am able to recreate the problem with this code:
import plotly.offline as py
import plotly.graph_objects as go
import numpy as np

x = np.linspace(0, 10, 10)
y = np.linspace(0, 10, 10)

trace = [go.Scatter(
    x=x,
    y=y,
    mode='lines'
)]

fig = go.Figure(trace)
py.plot(fig, filename=r'Test\test.html')
py.plot(fig, filename=r'#Test\test.html')

The first plot that this outputs opens in Microsoft Edge as expected but the second opens in Internet Explorer. However when I go to the files created and reopen them from the file explorer, they both open is Edge as expected.
How can I get both of these plots to open in Edge, either programmatically or by changing my computer settings?


text:
Q: How to represent object from array? I have the following array, which was retrieved from JSON results:
<NSCFArray 0x196e3e0>(
{
NameID = 3;
Name = test1;
},
{
NameID = 6;
Name = test2;
}
)

I'd like to go through each object via a tableview and assign its values to labels in a custom tableview cell.  How do I access NameID and Name on each iteration?  Do I need to create a class with those two properties and assign to it from the array?

A: Assuming the array is something like:
NSArray * array = [NSArray arrayWithObjects:
    [NSDictionary dictionaryWithObjectsAndKeys:
        [NSNumber numberWithInt:3], @"NameID", @"test1", @"Name", nil],
    [NSDictionary dictionaryWithObjectsAndKeys:
        [NSNumber numberWithInt:6], @"NameID", @"test2", @"Name", nil],
    nil];

You can iterate it like this:
NSEnumerator *enumerator = [array objectEnumerator];
id obj;
while ((obj = [enumerator nextObject]))
{
    NSLog(@"NameID:[%@]; Name:[%@]",
        [obj objectForKey:@"NameID"],
        [obj objectForKey:@"Name"]);
}

Output:
2010-02-04 11:41:53.266 x[8739] NameID:[3]; Name:[test1]
2010-02-04 11:41:53.267 x[8739] NameID:[6]; Name:[test2]

A: It's an array of NSDictionary so just iterate through the array and cast to NSDictionary then ask for the key to get the value.


text:
Q: How to use autocomplete inside a dialog box using jQuery? I have a form inside of a dialog box that is displayed when a user click on a button. When a user starts tying inside a field I want to display available options found inside a database.
The available options will need to be read using an AJAX request.
Here is my jQuery code where I try to initialize the autocomplete()
$("#icwsTransferTo")
// don't navigate away from the field on tab when selecting an item
.bind( "keydown", function( event ) {
    if ( event.keyCode === $.ui.keyCode.TAB &&
        $( this ).autocomplete( "instance" ).menu.active ) {
      event.preventDefault();
    }
  }).autocomplete({
    source: function(request, response) {

        $.ajax({
            type: 'GET',
            url: 'index.php',
            data: {method: 'userSearch', term: request.term},
            dataType: 'json',
            cache: false,
            timeout: 30000,
            success: function(data) {
            console.log(data);
                if(!data){
                    return;
                }

                var array = $.map(data, function(m) {
                return {
                        label: '
' + m.configurationId.displayName + ' (' + m.extension + ')
'
                    };
                });
                response(array);

            }
        });

    },
    search: function() {
        // custom minLength
        var term = extractLast( this.value );
        if ( term.length < 2 ) {
            return false;
        }
    },
    focus: function() {
        // prevent value inserted on focus
        return false;
    },
    select: function( event, ui ) {

        alert('Worked!');

    }
});

The field icwsTransferTo is located inside of a form which is displayed in the dialog box.
The problem is that when typing 2+ characters, I see the spinning icon in the field but no results is ever presented.
When I do a manual call to the index.php?method=userSearch&term=mike I get results like this
stdClass Object
(
    [items] => Array
        (
            [0] => stdClass Object
                (
                    [configurationId] => stdClass Object
                        (
                            [id] => msmith
                            [displayName] => Mike Smith
                            [uri] => /configuration/users/msmith
                        )

                    [extension] => 2062
                )

            [1] => stdClass Object
                (
                    [configurationId] => stdClass Object
                        (
                            [id] => mjohns
                            [displayName] => Mike Jones
                            [uri] => /configuration/users/mjohns
                        )

                    [extension] => 2083
                )
        )
)

what am I doing wrong here? Why the results are not showing?

A: I am assuming you are using the Jquery UI autocomplete? According to their documentation here: Documentation you should pass it a JSON array not html.


text:
Q: Resize array function does not change memory location I found a function to resize an array and am having trouble understanding how it works (or if it's working properly).  For testing I set the "temp" array to a new value and "startCounter" does get assigned to that value, however the memory location for startCounter doesn't change.  Here is my code:
int * startCounter;

void resizeArray(int *&arraySent,int origSize,int newSize) {
    output << "&arraySent " << &arraySent << endl;
    output << "arraySent[0] " << arraySent[0] << endl;
    int* temp = new int[newSize];
    output << "&temp " << &temp << endl;
    for (int i=0; i<origSize; i++) {
        temp[i] = arraySent[i];
    }
    temp[0]=744;
    delete [] arraySent;
    arraySent = temp;
    output << "&arraySent " << &arraySent << endl;
}

//....

startCounter = new int [3];
startCounter[0]=345;
output << &startCounter << endl;
resizeArray(startCounter,3,10);
output << "startCounter[0]" << startCounter[0] << endl;
output << "&startCounter" << &startCounter << endl;

Here is the output I get from this:
    &startCounter 0x60fab8
    &arraySent 0x60fab8
    arraySent[0] 345
    &temp 0x82cfe54
    &arraySent 0x60fab8
    startCounter[0] 744
    &startCounter 0x60fab8

My question is, why does the memory location of startCounter not change from 0x60fab8 after deleting it and assigning it to the new "temp" array?  Shouldn't it now become 0x82cfe54?
P.S.  I understand about vectors and such but am mainly concerned with understanding how this particular function works.

A: void resizeArray(int *&arraySent,int origSize,int newSize) {
    output << "&arraySent " << &arraySent << endl;

outputs the address of the pointer variable, not the address that it holds.
simply omit the address operator to get the (probably) intended effect

A: &startCounter is the address of the pointer, not the address it points to. it's value won't change. simply use startCounter.


text:
Q: To Apply Answers to MCQs I am now extending my own answers to MCQs, as made How to SED these paragraphs to MCQ format?.
Data in file.txt
1   c
2   a

Data in exam.tex
\item
Which of the following lorem ipsun are the best playstation games you have played?

A Pattman

B Pokemon

C Lorem

D Ipsun

E Heillui

\item
Which of the following lorem ipsun are the best playstation games you have played?

A Pattman

B Pokemon

C Lorem

D Ipsun

E Heillui

Wanted output where bold made by the answers in the file.txt
\item
Which of the following lorem ipsun are the best playstation games you have played?

A Pattman

B Pokemon

\textbf{C Lorem}

D Ipsun

E Heillui

\item
Which of the following lorem ipsun are the best playstation games you have played?

\textbf{A Pattman}

B Pokemon

C Lorem

D Ipsun

E Heillui

Pseudocode

*

*for loop \item's in Perl paragraph mode

*

*for loop empty lines in each paragaph by the count in the list (a=1, b=2, c=3, d=4, e=5)

*

*apply \textbf to the beginning of the line; and } to the end of the line

*step out of the current paragraph

*end

Pseudocode with Python-Perl
for item in items

   perl -00pe 's/\\item\n.*\n{$item}^/\textbf{/;' file
   perl -00pe 's/\\item\n.*\n{$item}$/}/;' file

end

where I do not like that I handle the beginning and the end in separate commands.

How can you apply answer to MCQs by Perl/SED/Python?

A: {   printf '[13*%d-n[bs]pc]s%c\n' 9 a 7 b 5 c 3 d 1 e
    tr  -s ' \n' lx <file.txt; }  |  dc |
sed -f- -eb -e:s -e's/.*/\\textbf{&}/' exam.txt

That uses the dc reverse-polish-notation calculator to generate a sed script that looks like:
8bs
17bs

...which is then concatenated with the sed scripts entered on the command-line and so results in every line number which is not included in the generated script to be branched away, and for the those that are included to have the string \textbf{ inserted before whatever exists on the line and } appended to its tail.
It will work for more than just the two sections, of course. Basically it multiplies the leading number on each line in file.txt by 13 and then subtracts from the product 1, 3, 5, 7, 9 for either of e, d, c, b, a respectively to arrive at the list of targeted line numbers.
In any case, all sed has to do at the end is the default print it does for every line which it doesn't edit before branching away, or else to do the one substitution for your string. tr and dc are both very fast utilities, and they handle nearly all of the pre-processing.

Possible advantages to this approach:

*

*No comparisons need be made between the two files.

*No regular expression matching is required at all.

*

*While true, sed's processing might benefit slightly from an initial additional filter to prevent it attempting to match every line number against those in the list, like:
... | sed -e'/^[ABCDE] /!b' -f- ...

*The answers in file.txt need not be in any particular order or even completely represent every question in exam.txt.
Possible disadvantages:

*

*Each answer letter in file.txt must be lowercase.

*

*use tr -s '[:upper:] \n' \[:lower:]lx to handle either/or.

*At least one intermediate space and intervening newline is required between the answer number and the answer letter and between each answer respectively in file.txt, though any larger number is permitted with the exception that no leading blank-lines can be found before the first answer, and no line can begin or end with spaces.

*Every question/answer block in exam.txt must be comprised of exactly 13 lines (excepting the last, which need not include a trailing blank-line).

This depends on one or two GNU dc extensions as written. Here is a more portable version:
{   printf '[13*%d-p[s]pc]s%c\n' 9 a 7 b 5 c 3 d 1 e
    tr  -s ' \n' lx <file.txt;}| dc | paste -db - -|
sed -f- -eb -e:s -e's/.*/\\textbf{&}/' exam.txt

...either way you write it, though:

\item
Which of the following lorem ipsun are the best playstation games you have played?

A Pattman

B Pokemon

\textbf{C Lorem}

D Ipsun

E Heillui

\item
Which of the following lorem ipsun are the best playstation games you have played?

\textbf{A Pattman}

B Pokemon

C Lorem

D Ipsun

E Heillui


text:
Q: Does SubtleCrypto API support in one algorithm encryption and signing together? I study the whole day the documentation of SubtleCrypto at Mozilla and was not able to find a way to do encryption and signing at the same time with one version of an RSA key.
I'am confused because I was able to write code in Java to do this job. Does Java here crazy stuff, does I not find the right way or is it just not implemented in the SubtleCrypto?

A: Some asymmetric algorithms will leak details about them, depending on how they are used. For this reason, the Webcrypto authors decided to "help keep users from hurting themselves" by preventing this.
Not all algorithms have this property, for example, ones based on EC-Schnorr do not (Curve25519 is such an example) that said this is not an algorithm supported by Web Crypto at this time.
It is possible to export a key and re-import it as another type, this does work around this restriction for exportable keys. That said you should use a unique key and cryptographically bind them to the same subject instead of using one key if you are using secp256r1 or its family members.


text:
Q: Convert string to unix timestamp and check if it is older than 8h I get a timestamp like below as a string:

1485661375

I need to parse it to unix timestamp and check if it is older than 8h.

A: [datetimeoffset]::FromUnixTimeSeconds('1485661375') -gt (get-date).AddHours(-8)

requires .NET 4.6, for converting without .NET 4.6 you can refer to this thread.


text:
Q: VS2010 debugger won't step into WCF Service locally hosted I have a simple "Hello World" WCF Service hosted on my local machine in the ASP.NET Development Server. A client C# console application (NET 4.0 / 4.03) calls the service to get a "Hello World". Can't be any simpler.
Everything was fine and beautiful: The service worked and I could step via F11 or via breakpoints from the client into the WCF service...
Then I had a problem with two Win7 updates that constantly wanted to reinstall. Following advice from the web, I used a DotNet Cleanup Tool (here) to remove the .NET framework. After reinstalling the .NET framework(s) and all updates everything seemed to be fine: No more update reinstalls, NET is working, debugger is working, everything OK... with one exception:
The VS debugger will not step anymore into my WCF service!
The following things are not working:

*

*I already reinstalled SP1 for VS2010

*compilation debug="true" is correctly set in web.config

*There is no problem with x86/x64 (it worked before)

*I can manually attach to the WebDev.WebServer40.exe and debug into the service, but this sucks if you have to do it often

Has anyone an idea?


text:
Q: Why did django 1.9 change my button styles? I am trying out updating from Django 1.8.4 to Django 1.9.1.
I have had an application working for years.  The original styling was done by somebody else years ago, and we used Compass.  I had to port from Google app engine to Heroku, and due to time constraints had to drop Compass, so I am working from old pre-computed CSS files.
When I change the Django version, my buttons completely change how they look.
Old:

New (I don't like it):

Why did this change, and how can I fix it?
P.S. No errors in server-side logs or Chrome debugging console.  I looked at the styling in the Chrome tools, but I can't spot a difference.  There are hundreds of lines of styling (inherited from, inherited from, ..) so I may have missed something.
Edit 1: I just pushed the Django 1.9.1 version to the production site, and the buttons still look fine. I don't know why they look weird in my dev environment, but now I am not going to worry about it.
Also, someone advised I post a truly reproducible example.  That is good advice, but I know little enough about the problem that it would take a long time to figure that out.  Given it seems to be okay in production I'm going to punt.
I am in the uncomfortable position of not being able to accept an answer because I didn't figure out what happened, but I bet it has to do with the flat styling mentioned below.
So, thanks to all for your help!

A: If you are using the Django admin, in Django 1.9, the admin has got a new flat look.

New styling for contrib.admin
  The admin sports a modern, flat design with new SVG icons which look perfect on HiDPI screens. It still provides a fully-functional experience to YUI's A-grade browsers. Older browser may experience varying levels of graceful degradation.

https://docs.djangoproject.com/en/1.9/releases/1.9/


text:
Q: Select specific index field in MongoDB I want to select only the "thetext" field on a specific index for example when the "comment_count"= 1
I have tried this query:
db.getCollection('mongotesi').find({},{'bug.long_desc.1.thetext':'1'})
I want show all the "thetext" fields too.
This is the json structure:
    {
    "_id" : ObjectId("5613c8acc8e53ab811000083"),
    "@attributes" : {
        "version" : "4.4.10",
        "urlbase" : "https://bugs.documentfoundation.org/",
        "maintainer" : "hostmaster@documentfoundation.org"
    },
    "bug" : {
        "bug_id" : "31585",
        "creation_ts" : "2010-11-12 08:55:00 +0000",
        "long_desc" : [
            {
                "@attributes" : {
                    "isprivate" : "0"
                },
                "commentid" : "194230",
                "comment_count" : "0",
                "attachid" : "40242",
                "who" : "eric.moret",
                "bug_when" : "2010-11-12 08:55:52 +0000",
                "thetext" : "Created attachment 40242ooo base fileI am running ooo 3.2.1 OOO320m18 (Build:9502). I am using an odb bas file to perform a mail merge on an odt file under writer. In the mail merge Wizard, on hitting Next in step 6. (Edit Document), the Status window - creating document opens up and generates my mailing. The crash happens reliably while performing this task. I have 118 items to generate.My error report id is: rpmrd6nAttached are the 2 files used for this merge."
            },
            {
                "@attributes" : {
                    "isprivate" : "0"
                },
                "commentid" : "194232",
                "comment_count" : "1",
                "attachid" : "40243",
                "who" : "eric.moret",
                "bug_when" : "2010-11-12 08:56:29 +0000",
                "thetext" : "Created attachment 40243ooo write file"
            },
        ],
    }
}

A:

Arrays take the form of [ skip , limit ], where the first value indicates the number of items in the array to skip and the second value indicates the number of items to return.

Using $slice query will be for finding first array object
db.collection.find({},{"bug.long_desc":{"$slice":[0,1]},"@attributes":0})

if you find out second object then skip first object like this
db.collection.find({},{"bug.long_desc":{"$slice":[1,2]},"@attributes":0})

EDIT
If print exact matching text then use forEach as :
db.collection.find({},{"bug.long_desc":{"$slice":[0,1]},"@attributes":0}).forEach(function(doc){print(doc.bug.long_desc[0].thetext);})

A: Mongo doesn't do this but this will do the trick:
var tm = require('tree-math');
var long_desc=db.getCollection('mongotesi').find({},{'bug.long_desc':'1'});
var bugtext = {};
tm.find(long_desc,function(path,val {if(path[3]==='thetext')tm.setPath(bugtext,path,val);});
console.log(JSON.stringify(bugtext,null,2));


text:
Q: Are all I(1) processes unit root and vice versa? This is more a question about definition.  On Wikipedia, it mentions taking a unit root process (that happens to be I(1)) and making it stationary via differencing.  However, it doesn't state if all unit root processes are I(1).  Can I(2) or higher order processes by unit root as well?
Are all I(1) processes unit root and are all unit root processes I(1)?

A: You can have more than one unit root. An I(2) process has 2 unit roots.


text:
Q: What is the currently accepted "correct" definition of a "transcendental function"? Caveat: this question has already been asked on this site more than once, but the question has not been addressed completely.
The question I want to ask is: there are two common definitions of a "transcendental function", both of which are readily found in the literature, and both of which are inconsistent with each other; which is "correct"?
This is the first:

*

*A transcendental function is an analytic function which cannot be expressed in terms of finite polynomials. That is, one which is not an algebraic function.

See for example Wikipedia, and also the Penguin Dictionary of Mathematics (2nd and 4th editions, 1998 and 2008, I have both immediately to hand).
Hence under this definition, the trigonometric, logarithmic and exponential functions are classed as transcendental, which is what you would expect.
This is the second definition:

*

*A transcendental function is "a function which cannot be defined in a finite number of steps from the elementary functions, and their inverses, such as $\sin x$."

See, for example, the Collins Dictionary of Mathematics (1989).
The elementary functions seem to be conventionally defined as: polynomial functions, rational functions, exponential, logarithmic and trig functions and their composites.
So on the one hand you have "not an algebraic function", hence including log, exp and trig functions.
On the other hand you have "not an elementary function", hence not including log, exp and trig.
The question now is: which of these definitions is considered canonical nowadays? Or is it generally understood that there are two definitions, and either one is valid, nobody really cares as long as you define which you mean when you use it? Or is it even that there are two warring camps which know that their definition is the correct one and anyone using the other definition is a heretic?
In the interest of creating a "definitive" definition of "transcendental function", it would be useful to know the current school of thought on the subject: do different branches of mathematics use different definitions? Is one more for advanced (PhD+) mathematics and the other a general convenient definition for less advanced (BSc-) mathematics? Or what?
I understand there is a lot of room here for personal opinions and/or professional bias as to which is correct, that's to be expected. But is there anyone out there with an objective view on this, so the definition can be nailed down (with whatever nuances necessary)?

A: I don't know that anyone really uses the term "transcendental function" one way or another, so I don't think this matters very much, but for what it's worth the first definition seems straightforwardly correct to me and the second definition seems like it means "non-elementary function" which is a different concept. I've never heard of the Collins Dictionary of Mathematics and I used to be a graduate student.


text:
Q: Assignee True to a variable if the environment variable is defined I would like to check if env variable is defined in Python. From previous threads I learn that I can use:
if os.environ.get('abc')=='True':
    # defined

But I would like to set a global variable and assigned True if the env exists, otherwise False. I tried:
X = os.environ.get('abc')

But if it is not defined than X is None and if it's defined it is the env's assigned value.
How can I achieve the wanted result?

A: You can assign it this Boolean expression:
X = os.environ.get('abc') is not None

which is True if os.environ.get('abc') is defined, and False if it is None (undefined).

A: Get allows for specifing a default value:
X = os.environ.get('abc', False)

A: Assignee True to a variable if the environment variable is defined:
abc = os.environ.get('abc')
X = abc is not None

A: get isn't the only thing you can do with os.environ. Like any good mapping, os.environ supports in for testing whether a key is present:
X = 'abc' in os.environ


text:
Q: Prime factors of $n^2+1$ I know it is unknown if there are infinitely many primes of the form $n^2+1$. Is it known if there is a positive integer $k$ such that $|\{n\in\mathbb{Z}:n^2+1 \text{ has at most k prime factors}\}|=\infty$?

A: Please see  Iwaniec, "Almost-primes represented by quadratic polynomials", Inventiones Math

A: Yes, Iwaniec, "Almost-primes represented by quadratic polynomials", Inventiones Math., 47:171–188, 1978, proves that there exist infinitely many
integers $n$ such that $n^2 + 1$ is either prime or the product of two
primes.


text:
Q: htaccess how use %{TIME_DAY} in header set retry-after %{TIME_DAY}+1 I need to use htaccess variables like %{TIME_DAY} in header set and even more if possible add 1 day to it, like:
header set retry-after: %{TIME_DAY}+1

second q I searched the web for %{TIME_MON} which would return like jan , sep.. is there a code for it ? If not how can I make variables in htaccess which translates 01 to Jan or 12 to Dec and so on ..
This is what finally I need , but not hard coded. It will say retry tomorrow, so if today is 19 Dec 2016 the header will be set like :
Header set Retry-After: Tue, 20 Dec 2016 02:59:59 GMT

A: After reading this SO answer and the Retry-After specification, the easiest solution in your case is to use the "delta-seconds" version, not the "HTTP-date" version:
header set Retry-After 86400

Where 86400 seconds is one day.


text:
Q: jQuery AJAX call not returning data I feel a little silly here. My ajax call is running the error: function every time. I know that the data is coming back as JSON, but i've done the datatype as jsonp to allow for cross origin stuff. I don't think I can do anything differently, unless I'm forgetting something obvious. Please- whats wrong with this:
function sartleApi(type,endpoint,object,callback){

 $.ajax({
    contentType: "application/json",
    dataType: 'jsonp',
    type:type,
    data:object,
    url:"http://dev.sartle.com/includes/ajax_reviewcomment.php?rid=1178",
    success:function(data){
        callback(data);
    },

    error: function (xhr, textStatus, errorThrown) {
        alert(xhr.statusText);
        alert(xhr.responseText);
        alert(xhr.status);
        alert(errorThrown);
    }
});

}

A: Your website doesn't support JSONP.
JSONP is just a fancy way of passing a JSON object to a global callback function via a <script> tag. It circumvents cross-origin restrictions by not sending an AJAX request in the first place, but instead creating a <script> tag.
A JSON response looks like this:
{"foo": "bar"}

But a JSONP response is:
some_callback({"foo": "bar"})

That PHP script doesn't wrap the JSON response in a callback function (whose name is usually specified via the callback GET parameter), so you simply can't make a JSONP request. The request will succeed, but the global callback function will not be called, so you will not be able to use the JSON.

A: *

*stlll, it seems a cross-domain issue: please try this library https://github.com/padolsey/jQuery-Plugins/blob/master/cross-domain-ajax/jquery.xdomainajax.js

*as a jsonp the result is already a callback function with a javascript object argument. Make sure that the returned function by the server is implemented:
The server could return my_callback({...}). You need to implement my_callback function client-side.

*place some alerts/console.log on both success and error functions. Always make a little debug of your own before posting the issue.

*as posted in the comment: state the return code of the ajax call.

A: So, to try to circumvent the cross domain issue, using jSONP turned out to be a bad idea. I'm running these calls from a localhost, so i've changed the url in the ajax call to
url:"http://localhost/includes/ajax_reviewcomment.php?rid=1178"
I will build this url to be dynamic so that the current URL always is domain-consistent with the server, and i should be in good shape!

A: in type you need put "GET" or "POST"
$.ajax({
    contentType: "application/json",
    dataType: 'jsonp',
    type:type, <<<<<<------ here
    data:object,
    url:"http://dev.sartle.com/includes/ajax_reviewcomment.php?rid=1178",
    success:function(data){
        callback(data);
    },

error: function (xhr, textStatus, errorThrown) {
    alert(xhr.statusText);
    alert(xhr.responseText);
    alert(xhr.status);
    alert(errorThrown);
}

});
}


text:
Q: GAWK Print string to STDOUT with -i inplace option I would like to run a GNU AWK script that is editing files in-place (e.g. with the -i inplace option) and have it print the filenames it is working on to STDOUT. Is there a way to do this? The following just adds the filename as the first line in the modified file, rather than printing the filename on the command line:
BEGINFILE {
  print FILENAME
}

A: Here is a workaround; drop -i inplace from the command line (not an obligatory though, see -e/-f) and place following at the very beginning of your script. Before starting to process a file's content, this will disable inplace temporarily and print FILENAME. Then inplace's BEGINFILE rule will enable itself again.
BEGINFILE {
    if (inplace::filename != "") {
        inplace::end(inplace::filename, inplace::suffix)
        inplace::filename = ""
    }
    print FILENAME
}

@include "inplace"

See how inplace is implemented for a better understanding.


text:
Q: "Unhandled Exception: System.FormatException: Input string was not in a correct format." being thrown with no obvious reason as to why I am pretty new to C# and I'm following the guide posted on tutorialspoint. I am following their code but not exactly because I don't just want to copy and paste what they have, I want to understand the code I'm writing. So their code runs fine, but mine throws the error shown in the title and I have no idea why. I don't see how my code isn't working but theirs is. Here is my code:
using System;

namespace Learning
{
    class Rectangle
    {
        double length;
        double width;

        public void setDimensions()
        {
            length = 4.5;
            width = 3.5;
        }

        public double getArea()
        {
            return length * width;
        }

        public void displayInfo()
        {
            Console.WriteLine("Length: {0)", length);
            Console.WriteLine("Width: {0}", width);
            Console.WriteLine("Area: {0}", getArea());
        }
    }

    class ExecRect
    {
        static void Main(string[] args)
        {
            Rectangle r = new Rectangle();
            r.setDimensions();
            r.displayInfo();
        }
    }
}

Here's their code:
using System;

namespace RectangleApplication {
   class Rectangle {

      // member variables
      double length;
      double width;

      public void Acceptdetails() {
         length = 4.5;
         width = 3.5;
      }
      public double GetArea() {
         return length * width;
      }
      public void Display() {
         Console.WriteLine("Length: {0}", length);
         Console.WriteLine("Width: {0}", width);
         Console.WriteLine("Area: {0}", GetArea());
      }
   }
   class ExecuteRectangle {
      static void Main(string[] args) {
         Rectangle r = new Rectangle();
         r.Acceptdetails();
         r.Display();
         Console.ReadLine();
      }
   }
}

Where is it that I'm going wrong?
EDIT: Lol, stupud mistake. Closed the curly braces with a ) instead of } on line 23. Thanks!

A: You are forgetting to close your braces at method displayInfo with "Length: {0)", length.
I suggest you use string interpolation with Console.WriteLine($"Length: {length}")


text:
Q: Unable to update useState to display on Webpage I am trying to display data retrieved from a sub-collection in firebase for my react app. I do know that there are other answers in stackoverflow. But the solutions does not help me in my scenario, like useState set method not reflecting change immediately.
As mentioned, I need to attain the data before the rendering of the page to prevent the page being loaded without the data. Shown in my getPortfolioData() this was not an issue and the data was set and displayed when the page load. But this was not the case for getImageData().
I tried the following below, and the outcome is that the data is only set after a repetition of 4-5 times on average, but it sets in the console but the display doesn't show it. But what I need is for it to be set and then render the display.
useEffect(() => {
        getPortfolioData();
        getImageData();
    }, [imageData])

Main Codes:
function getImageData() {
        setLoading(true);

        database.portfolioRef
            .doc(portfolioId)
            .collection("images")
            .get()
            .then((snapshot) => {
                const imageItems = [];
                snapshot.docs.map((doc) => {
                    console.log(doc.data());
                    imageItems.push(doc.data());
                });

                console.log(imageItems);
                setImageData(imageItems);
                console.log(imageData);
            }).catch((e) => console.log(e));

        setLoading(false);
    }

    function getPortfolioData() {
        database.portfolioRef
        .doc(portfolioId)
        .get()
        .then((snapshot) => {
            console.log(snapshot.data());
            setPortfolioData(snapshot.data())
            setLastModifiedBy(snapshot.data().lastModifiedBy)
            setlastModifiedDate(snapshot.data().lastModifiedDate)
        }).catch((e) => console.log(e));
    }

    useEffect(() => {
        getPortfolioData();
        getImageData();
    }, [])

SOLVED (Answer below)
async function getVideoData() {
        setLoading(true);
        setVideoMessage("")

        try {
            const snapshot = await database.portfolioRef.doc(portfolioId).collection("videos").get();
            if (snapshot !== null) {
                var videoItems = [];

                snapshot.docs.map((doc) => {
                    console.log(doc.data());
                    videoItems.push(doc.data());
                });

                setVideoData(videoItems);
            } else {
                setVideoMessage("There is not existing videos for this portfolio.")
                console.log("else" + videoMessage);
            }
        } catch {
            setVideoMessage("There is not existing videos for this portfolio.")
            console.log("catch" + videoMessage);
        }

        setLoading(false);
    }


text:
Q: Words that can be repeated and still make sense
Possible Duplicate:
Are there other repeated single word sentences like the Buffalo sentence?

Are there words in English like had that can be repeated while still making sense?
For example,

The faith that he had had, had had an affect on his life.

A: That that occurs sometimes.  It sometimes means that which, and sometimes just that that, as in I know that that will not work.

A: There's a whole bunch of words that function as more than one part of speech (albeit with different pronunciations). You can probably construct acceptable phrases from some of these. Here are 3 that come to mind:

*

*to record record profits

*to address address problems

*to refuse refuse charges

A: One way this arises very simply and commonly is the repetition of adjectives and adverbs for emphasis:

We were going really, really fast!

I had a strange, strange dream last night.

On a different tack, there's the interesting case of What it is, is…, discussed previously here and here.

A: Another example is the word "buffalo", which is repeated eight times in the following sentence.

Buffalo buffalo Buffalo buffalo buffalo buffalo Buffalo buffalo

Note that, according to the following Wikipedia link, it is a perfectly valid sentence.
Buffalo buffalo Buffalo...
As for "had had", take a look at the following Wikipedia link.
James while John had had had had had had had had had had had a better effect on
 the teacher
Other linguistic examples of this sort are given in the following link.
List of linguistic example sentences


text:
Q: AngularJS 1.2.1 - dynamically adding directives errors unless they do not replace source element I have upgraded my application to AngularJS 1.2.1 and am running into an issue with previously working code, which I am unable to solve.
I have a page where the user builds up the content from a pre-defined list of content, each of which is a separate AngularJS directive.  I have a service which stores the array of configured items and have this linked to an ng-repeat command.  All I am doing when the user chooses to add a new item is push it onto the array and leave it up to Angular to update the UI.  My HTML is similar to this.
<div data-ng-repeat="item in configuration">
    <directive-a data-ng-if="item.obj === 'directive-a'></directive-a>
    <directive-b data-ng-if="item.obj === 'directive-b'></directive-b>
    <directive-c data-ng-if="item.obj === 'directive-c'></directive-c>
    <directive-d data-ng-if="item.obj === 'directive-d'></directive-d>
</div>

All of the directives here inherit parent scope, and are about as simple as they come.
angular.module("App").directive("directiveA", function () {
    return {
        restrict: "E",
        replace: true,
        templateUrl: "partials/DriectiveA.html"
    };
});

When I have them set to replace 'true', I get the following error in the console upon adding them to the array and the item does not render:
TypeError: undefined is not a function
    at ngRepeatAction (file:///C:/TeamFoundation/PRE/js/libs/angular-1.2.1.js:18826:15)
    at Object.$watchCollectionAction [as fn] (file:///C:/TeamFoundation/PRE/js/libs/angular-1.2.1.js:11347:11)
    at Scope.$digest (file:///C:/TeamFoundation/PRE/js/libs/angular-1.2.1.js:11443:27)
    at Scope.$apply (file:///C:/TeamFoundation/PRE/js/libs/angular-1.2.1.js:11682:24)
    at HTMLDivElement.<anonymous> (file:///C:/TeamFoundation/PRE/js/libs/angular-1.2.1.js:17531:21)
    at HTMLDivElement.jQuery.event.dispatch (file:///C:/TeamFoundation/PRE/js/libs/jQuery-1.8.2.js:3063:34)
    at HTMLDivElement.elemData.handle.eventHandle (file:///C:/TeamFoundation/PRE/js/libs/jQuery-1.8.2.js:2681:47)

Line 9101, which is in a "consoleLog" function, so it appears to be failing to write something to the console, failing, but managing to write the error there anyway!  I've tried debugging it and can't actually manage to get it to.
When I have them set to replace 'false', it works fine.  I want them to replace the source element otherwise the formatting is a real pain because of the extra element, and was able to do so prior to the upgrade.
Can anyone offer any advice here?

A: I have found that if you wrap your html template in a div then it'll work fine.  Or if you have have the template in the directive instead of using templateUrl.

A: I couldn't solve this with the current code, but moving some of the HTML in the parent to the child directives solved the issue.  I don't understand why, but it is solved nonetheless.


text:
Q: MySQL won't enable InnoDB I am running MySQL 5.0.8
Recently (yesterday) my server host migrated my server and somehow in the process my MySQL got bonked.
After a bit of fishing, I believe the issue is that the InnoDB is now disabled for MySQL, and I cannot get it to re-enable.
Any help or direction is greatly appreciated.
Thanks
My my.cnf file is the following...
[mysqld]
datadir=/var/lib/mysql
socket=/var/lib/mysql/mysql.sock
user=mysql
innodb_buffer_pool_size=64M

# Default to using old password format for compatibility with mysql 3.x
# clients (those using the mysqlclient10 compatibility package).
old_passwords=1

# To allow mysqld to connect to a MySQL Cluster management daemon, uncomment
# these lines and adjust the connectstring as needed.
#ndbcluster
#ndb-connectstring="nodeid=4;host=localhost:1186"

[mysqld_safe]
log-error=/var/log/mysqld.log
log-bin=/var/lib/mysql/mysqld-bin
log-slow-queries=/var/log/mysqld-slow-queries.log
pid-file=/var/run/mysqld/mysqld.pid

[ndbd]
# If you are running a MySQL Cluster storage daemon (ndbd) on this machine,
# adjust its connection to the management daemon here.
# Note: ndbd init script requires this to include nodeid!
connect-string="nodeid=2;host=localhost:1186"

[ndb_mgm]
# connection string for MySQL Cluster management tool
connect-string="host=localhost:1186"

A: Issue the below command,
show engines and check you are able to find the INNODB in that list.  If so, do the below command, and then bounce the DB
SET default_storage_engine='INNODB'


text:
Q: django : How to write alias in queryset How can one write an alias for the column name in django query set.
Would be useful for union-style combinations of two linked field to the same foreign model (for instance).
for example in mysql :
select m as n, b as a from xyz

how can i do this in django query set ?
models.Table.objects.all().values('m', 'b')

Any help really appreciate it.

A: Although this could have been done before by using extra(select={'n':'m','a':'b'}), I agree that this really should have been a part of values() itself.
To that end, and inspired by Alex's ticket, I have just posted a patch that adds this feature.  I hope you'll find it useful!

A: Your reason in the comment makes no sense. Each field in the model has its own column in the database, and there's never any danger of mixing them up. You can of course tell a field to use a column name that's different from the field name:
myfield = models.CharField(max_length=10, db_column='differentname')

but I don't know if that will help you, because I still don't know what your problem is.

A: You can annotate the fields as you want, with the F expression:
from django.db.models import F

models.Table.objects.all().values('m', 'b').annotate(n=F('m'), a=F('b'))

A: I'm presuming this isn't possible, so I've raised a ticket for the feature to be added, I think there is some merit to being able to do this. Please see the ticket for more information.
https://code.djangoproject.com/ticket/16735

A: you can also use .alias() in your queryset.
.alias(alias=SomeExpression()).annotate(
    SomeOtherExpression('alias'))

.alias(alias=SomeExpression()).order_by('alias')

.alias(alias=SomeExpression()).update(field=F('alias'))

for your specific case, this would be the answer
models.Table.objects.all().alias(
    n=F('m'), a=F('b')).values('m', 'a')
)

A: I really can't understand what you are trying to do however it sounds like what you are looking for is the extra queryset method.  This for most purposes acts in the same manner as AS does in sql.


text:
Q: custom background image for every WordPress page? i am trying to have different header background images depending on which inner page is accessed. Right now i have the same picture for all inner pages and need the php code changed so its conditional. Like if im on contact page, 1.jpg to be set as header img. If on services page, 2.jpg to be set as header img etc, you get the idea.
Here is the php code ive found in this wp theme im trying to improve for a friend:

      <?php
        //display featured image if one exists
        $featimage = get_bloginfo('stylesheet_directory') . "/images/pageheader.png";

        if ((has_post_thumbnail( $post->ID ))&&(!is_single()&&(!is_category())) ){

          $image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'single-post-thumbnail' );
          $featimage = $image[0];
             }

      ?>

      <div class="pageheader" style="background: url(<?php echo $featimage; ?> ); background-position: center top;">

A: Well.. It's more of a structure thing. How are you determining which page they are on? Does the user click a link? Use the information available to the server to decide what content to serve. If you're using one script to serve all your pages, then you'll need to pass it a parameter when the user clicks a link. You can do this by making your links take parameters.
Markup like so:
 Navigate To Home
 Navigate To Blog

php like so:
if($_POST['page'] == "home")
    echo $homeheader;
elseif($_POST['page'] == "blog")
    echo $blogheader;

But, usually you just make multiple php pages that include some common elements (called templating). That helps keep things cleaner than making one php script that serves up your whole site.

A: If you're wanting the manage this in the back-end of WordPress: You can use the Advanced Custom Fields Plugin for WordPress (http://wordpress.org/plugins/advanced-custom-fields/). Through it, you can add a field on every page an even every post that allows you to enter in a background image.
Then, in your header.php template file, add the shortcode somewhere in your body tag:
<body background="(<?php the_field('background_image')" ?>)">
Depending on what page you're on, it will show that background image.

If You'd like the process automated: You can create a folder called "bg" and have an image with the same name as your page. For example, for about.php you can have about.jpg.
Then write a script that takes the page name, and then sets the background image to that name. You would place this in the header.php file in your template Something like:
 $page = end(explode("/",$_SERVER['REQUEST_URI']));
 $image = str_replace("php","jpg",$page);

Then use:
<body background="bg/<?php print $image ?>">
This is assuming that you are keeping your image files in http://www.yoursite.com/bg/ But you can also use shortcodes to keep these images within your theme with <?php echo get_template_directory_uri(); ?>


text:
Q: How can I kill only one item frame instead of all of them? I tried using /kill @e[type=item_frame]. However, it kills every item frame. So my question is, how can I kill only one item frame?

A: You can add a scoreboard tag to the item frame when you spawn it in, so your kill function looks like this:
kill @e[type=item_frame,tag=killable]
with killable being the tag. If a player is running the command/you aren't spawning it in you can kill one within a certain radius:
kill @e[type=item_frame,distance=..1]
which will kill any item frames within one block.
Edit: I saw your other question and here's the summon command you would use:
summon minecraft:item_frame -1242 58 219 {Facing:2,Tags["killable"]}
Edit 2:
I just remembered that a tag is not unique: if you have multiple entities tagged as 'killable' it will kill all of them. Instead, use a customName:
summon minecraft:item_frame -1242 58 219 {Facing:2,CustomName:"killableFrame"}
kill @e[name=killableFrame]

A: You can get right in front of the item frame, type /kill and press space then press tab.
You should see the item frame's uuid pop up. Then execute the command.
The item frame will disappear and a message will say "Killed Item Frame".


text:
Q: AWS: Find the endpoint of my DB Instance using the cli I want to find the endpoint of my DB Instance using the command-line interface, but I got this error:
MacBook-Pro-de-lopes:/ lopes$ aws rds describe-db-instances

A client error (InvalidClientTokenId) occurred when calling the DescribeDBInstances operation: The security token included in the request is invalid.

I tried to check my credentials, but I got also an error
MacBook-Pro-de-lopes:/ lopes$ cd ~/.aws/credentials
-bash: cd: /Users/lopes/.aws/credentials: Not a directory

A: It appears you have invalid credentials configured for you AWS Command-Line Interface (CLI).
You can view the configuration via:
cat ~/.aws/credentials

Or, you can view/configure them via:
aws configure

See: Configuring the AWS CLI


text:
Q: nested ng-repeat doesn't work I am using ng-table to put an array structure into a table the following way :

          {{val}}

Consider venues to be :
[{"id":"C001","name":"Bobo"},{"id":"C002","name":"Shobo"},{"id":"C003","name":"Soho"}]

The first ng-repeat works okay as I can see the 3 rows in the table. The second ng-repeat doesn't seem to work.
What am I doing wrong ?

A: A Table Row Element (
) can not accept a
 as a child. You must directly use the second ngRepeat on the Table Cell Element ():

        {{val}}

A:
 element can't be a direct child of
. You need to simply put your inner ngRepeat on tdelement:

        {{val}}


text:
Q: SQL Case Statement in set; Does it always fire? I was wondering if in the following statement:
  UPDATE u
  SET u.isactive =
        (
        CASE WHEN e.LVStatus<>'B' AND u.IsActive=1 AND u.AutoUpdate=1 THEN
              0
        WHEN e.LVStatus='B' AND u.IsActive=0 AND u.AutoUpdate=1 THEN
              1 END
         ),
      u.UpdatedB y= 0
  FROM tbl_e e
       INNER JOIN tbl_Users u ON e.id=u.id

If the conditions in the case statement are not met, for example u.IsActive=1 and e.LVStatus='B', will the query still set u.UpdatedBy=0? I was hoping if the conditions in the case statement are not met then do nothing, perhaps if I want that behavior I need to just have to separate update statements with different where clauses. Thanks!

A: Since your query sets u.UpdatedBy to zero unconditionally, the answer is yes, the value of u.UpdatedBy will be set regardless of the outcome of the CASE expression through which u.isactive is set.
To overcome this, you could add a separate CASE expression for the u.UpdatedBy field, and use the current value when the conditions of the other CASE statement are not met:
UPDATE u
SET u.isactive = CASE
        WHEN e.LVStatus<>'B' AND u.IsActive=1 AND u.AutoUpdate=1 THEN 0
        WHEN e.LVStatus='B' AND u.IsActive=0 AND u.AutoUpdate=1 THEN 1
        ELSE u.isactive
    END
,   u.UpdatedBy= CASE
        WHEN (e.LVStatus<>'B' AND u.IsActive=1 AND u.AutoUpdate=1) OR
             (e.LVStatus='B' AND u.IsActive=0 AND u.AutoUpdate=1)
        THEN 0
        ELSE u.UpdatedBy
    END
FROM tbl_e e
     INNER JOIN tbl_Users u ON e.id=u.id

Alternatively, you could move that condition into the WHERE clause, like this:
UPDATE u
SET u.isactive = CASE
        WHEN e.LVStatus<>'B' AND u.IsActive=1 AND u.AutoUpdate=1 THEN 0
        WHEN e.LVStatus='B' AND u.IsActive=0 AND u.AutoUpdate=1 THEN 1
        -- No ELSE is needed, because WHERE filters out all other cases
    END
,   u.UpdatedBy=0
FROM tbl_e e
INNER JOIN tbl_Users u ON e.id=u.id
WHERE (e.LVStatus<>'B' AND u.IsActive=1 AND u.AutoUpdate=1) OR
      (e.LVStatus='B' AND u.IsActive=0 AND u.AutoUpdate=1)

A: Both set conditions will always work.  A CASE expression without an ELSE clause has an implicit ELSE NULL.  See here.
If u.isactive has a NOT NULL constraint, you'll get a constraint violation and nothing will be updated by the statement.

A: Just do SET u.isactive = (CASE... ELSE u.isactive end).
That way, if your criteria in the case statment aren't met, just leave it as the existing value.  You could probably get away with no else statement, but I am never comfortable with that.

A: One way of doing this is to add an else clause and return the column's original value:
UPDATE u
  SET u.isactive=(CASE WHEN e.LVStatus<>'B' AND u.IsActive=1 AND u.AutoUpdate=1 THEN 0
                       WHEN e.LVStatus='B' AND u.IsActive=0 AND u.AutoUpdate=1 THEN 1
                       ELSE u.isactive END),
      u.UpdatedBy=0
  FROM tbl_e e
       INNER JOIN tbl_Users u ON e.id=u.id


text:
Q: Angular - Not Finding my Element by ID In my Angular app I have the code:
$rootScope.$on('$routeChangeSuccess', function() {
   var meta = document.querySelector('meta[name=description]');

   content = document.querySelector('#theTitle');

   if (content !== null) {
      meta.setAttribute('content', content.textContent.trim());
   }
});

In my HTML I have a h2 tag with id equal theTitle however the code document.querySelector('meta[name=description]') keeps returning null.
I can't see what I'm doing wrong? I did a console.log(document) and its returning everything so the page content appear to be available.
Any help would be appreciated.
Thanks.


text:
Q: Python Program to Display News Headlines? I am attempting to write a program that displays the current news headlines. I tried the python module newspaper, but had issues with the instillation. Does anyone know another way to go about this task? Thank you.

A: You can use feedparser module to fetch RSS info from your preferred newspapper.
RSS Source Examples:

*

*https://www.ft.com/news-feed

*http://www.reuters.com/tools/rss

*http://www.economist.com/rss

*https://www.rsssearchhub.com/feeds/
Code example:
import feedparser
d = feedparser.parse('http://www.reddit.com/r/python/.rss')
print d['feed']['title']
print d['feed']['link']
print d.feed.subtitle

Output:
>>> Python
>>> http://www.reddit.com/r/Python/
>>> news about the dynamic, interpreted, interactive, object-oriented, extensible programming language Python

If you have any doubt, you can take a deep look at the PythonForBeginners Feedparser Tutorial.


text:
Q: analyzing binary mortality data collected at different remeasurement intervals. Bonus for R implementation I am replicating an analysis that models tree mortality data. Data are structured such that forest sites are revisted at some random interval, which is recorded. It is then determined if a tree lived or died over that random interval, generating 0 1 mortality data (if a tree dies, it gets a 1 in the dependent variable). The interval between initial and final observation varies continuously, from 5-15 years. This is relevant, as the more time that passes, the more likely a tree will die.
Here are some pseudo data for R:
mort <- c(0,1,0,0,0,0,0,1,1,1,1,0,1,0,0,0,0,0,0,0,1,0)
interval <- runif(length(mort), 5, 15)
pollution <- rnorm(length(mort), 25,5)
data<- data.frame(mort, interval, pollution)

I am trying to replicate an analysis which uses a logistic regression model for binary mortality data using the the logit transformation. Authors then model how pollution affects tree mortality rates. In the manuscript the authors write, "because recensus is not annual, we relate annual mortality probability, pi, of tree i to the observed binomial data on whether that tree lived or died Mi via a Bernoulli likelihood,

where ti is the time interval between successive censuses."
My question: How would I implement this using the glm function, or something analagous, in R? Note: I understand modeling this as a hazard function would also be appropriate, but it is not what I am interested in.

A: Ok, if each tree $i$ has an age-independent hazard $\lambda_i$, then its lifetime $T_i$ follows an exponential distribution such that the probability that the tree is dead after a time interval of length $t_i$ becomes
\begin{equation}
p_i = P(T_i \le t_i) = 1-\exp(-\lambda_i t_i).
\end{equation}
If we in turn assume that pollution has an additive effect on the log of the hazard, that is, $\log\lambda_i=\beta_0 + \beta_1 x_i$, we get the overall model
\begin{equation}
p_i = 1-\exp(-\exp(\beta_0 + \beta_1 x_i + \log t_i)),
\end{equation}
or
\begin{equation}
\log(-\log(1-p_i) = \beta_0 + \beta_1 x_i + \log t_i
\end{equation}
which is a glm with cloglog link-function and $\log t_i$ as offset.
This is fitted in R by doing
glm(mort ~ pollution, offset=log(interval), binomial(link="cloglog"))

This model is similar to the one you're trying to reproduce in that survival probabilities $e^{-\lambda_i t_i}=(e^{-\lambda_i})^{t_i}$ decrease with powers of annual survival probabilities $e^{-\lambda_i}$ but the exact effect of pollution is slightly different from what what follows from the logit link assumption.


text:
Q: Django Queryset Filter where will be 3 month in 7 days I have queryset filtered user that created 3 month ago.
User.objects.filter(
    create_date__range=(
        datetime.now()-timedelta(90),datetime.now()
    )
)

that above return all the user within date range 3 month ago to now. but i don't need return it all since its to many.
I need return all the user that will be 3 month in 7 days from datetime.now().
example.
now = 2018-05-29
create_date = 2018-04-20 will now show since its more than 7 days till 3 month.
create_date = 2018-03-04 <-- this will show since in 6 days will be 3 month.

A: I'm assuming create_date is a models.DateField().
If I understand your question correctly, you could try something this:
import datetime as dt
from django.utils import timezone as tz

today_ = tz.now().date()
today_plus_7 = today_ + dt.timedelta(days=7)
today_plus_7_minus_90 = today_plus_7 - dt.timedelta(days=90)

# users that are 83 days or YOUNGER
#qs = User.objects.filter(create_date__range=[
#    today_plus_7_minus_90, today_plus_7])
qs = User.objects.filter(create_date__gte=today_plus_7_minus_90)

# users that are 83 days or OLDER
qs = User.objects.filter(create_date__lte=today_plus_7_minus_90)