text:
Q: Check a string in another string in C++ #include <iostream>
#include <string>
using namespace std;

int main() {
    string str_1 = "Gandalf";
    string str_2 = "dal";
    for (int i = 0; i <= str_1.length() - 2; i++)
        for (int j = 0; j <= str_2.length(); j++) {
            if (str_2[j] == str_1[i]) {
                if (str_2[j + 1] == str_1[i + 1]) {
                    if (str_2[j + 2] == str_1[i + 2])
                        cout << "true";
                }
            }
        }
    return 0;
}

I can do it but if length of str_2 is 4 characters, program doesn't work.
I want that program can work for every length of string
but how?

A: The function find below basically reproduces the behaviour of std::string::find (without the starting position parameter). You need to:

*

*loop through the outer string, and at each step:

*loop through the second string checking each character.

*If any of these fail, drop back to the outer loop.

*If we make it all the way through the inner loop, then the second string is there, and return the current position in the outer loop.

*If we run out of space in the first string, just skip the rest.

Hopefully the comments make this clear. I also include a little utility function to turn the found position into true/false, and some tests.
#include <iomanip>
#include <iostream>
#include <string>

std::string::size_type find(const std::string& s1,
                            const std::string& s2)
    // return the position of s2 within s1,
    // else npos if it is not present.
{
    using size_type = std::string::size_type;
    size_type curPos = 0;
    size_type lim    = s1.size();
    size_type innerLim = s2.size();

    for (; curPos<lim; ++curPos) { // loop through s1
        if (lim < curPos+innerLim) {
            break; // not enough space left
        }
        size_type innerPos = 0;
        for(; innerPos < innerLim // loop through s2, while matching
                && curPos + innerPos < lim
                && s1[innerPos+curPos] == s2[innerPos];
                ++innerPos) ; // do nothing in the loop
        if (innerPos == innerLim) { // matched the whole loop
            return curPos;
        }
    }
    return std::string::npos; // never matched
}

bool contains(const std::string& s1,
              const std::string& s2)
{
    return find(s1, s2)!=std::string::npos;
}

int main()
{
    std::cout
        << std::boolalpha
        << contains("abc", "")      << '\n' // true
        << contains("abc", "abc")   << '\n' // true
        << contains("abc", "bc")    << '\n' // true
        << contains("abc", "abcd")  << '\n' // false
        << contains("abc", "abd")   << '\n' // false
        << contains("abc", "xyz")   << '\n';// false
}

This does more than what you really need, but it most closely models the "real" answer (use the facilities the language provides). Plus it makes it not a great homework answer, but contains all the clues to write your homework answer.

A: You could try something like this:
for (int i = 0; i < str_1.length() - str_2.length(); i++) {
    bool is_same = true;
    for (int j = 0; j < str_2.length(); j++) {
        if (str[i + j] != str_2[j]) {
            is_same = false;
            break;
        }
    }
    if (is_same) {
        std::cout << "true" << std:endl;
    }
}

It iterates over every character in str_1 and checks whether the character sequence starting at that point is the same as str_2.


text:
Q: What does caret(^) in Oracle translate function mean? I encountered this statement from other developer's code which returns ABCDEF:
SELECT TRANSLATE('ABC123DEF456', '^0123456789', '^') FROM DUAL;

Then I tested with the following which have the same result:
SELECT TRANSLATE('ABC123DEF456', '^0123456789', ' ') FROM DUAL;
SELECT TRANSLATE('ABC123DEF456', '0123456789', ' ') FROM DUAL;

But this one returns null:
SELECT TRANSLATE('ABC123DEF456', '0123456789', '') FROM DUAL;

What does caret(^) mean? Why is it necessary?

A: TRANSLATE(expr, from_string, to_string):

You cannot use an empty string for to_string to remove all characters
  in from_string from the return value. Oracle Database interprets the
  empty string as null, and if this function has a null argument, then
  it returns null.

Thus you cannot specify '' as the value for the to_string parameter, because it would be interpreted as null.
I suspect ^ is used here because it will never appear in the expr, and thus you will never see it in the resulting string as in TRANSLATE('ABC12^3DE0F456', '^0123456789', '^') which returns ABC^DEF.
Your original function SELECT TRANSLATE('ABC123DEF456', '^0123456789', '^') FROM DUAL; effectively strips all digits from the source string because for every matching digit in from_string there's no corresponding character in to_string, the other characters are just ignored.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I easily setup scheduled recurring tasks on Google Cloud Platform? How can I easily set up scheduled recurring tasks on Google Cloud Platform to trigger Google Cloud Functions?

A: Previously you could setup up Cron jobs using Google App Engine which tigger a PubSub triggered Google Cloud Function, however, this defeated the 'serverless' approach as you are introducing infrastructure to manage and it can take a moderate amount of work to setup the Cron jobs.
You can now use the newly released Google Cloud Scheduler which is completely managed, cheap and which makes it very easy to create scheduled jobs via Google PubSub and via HTTP requests. These in turn can trigger the Google Cloud Functions at regular intervals per unit of time or at a specific time of the day/week/month down to a one-minute interval. Note that you are still required to have an App Engine instance in one of the supported regions.


text:
Q: CXF with OData v4 (Olingo) Could anybody tells me whether CXF has support for OData v4?
I know it's being using Olingo in order to provide partial support for OData v2.
I've took a look, however, it's not clear to me whether CXF is working for providing a full OData v4 support...
Thanks.

A: The OData V4 library is not depending on CXF or any other framework to work. It only needs a HttpServletRequest to evaluate and a HttpServletResponse to write into.
Here is the technical servlet they use for integration testing: https://github.com/apache/olingo-odata4/blob/bfeab37b1b51d6587e2e6f280f549944d146cb1c/lib/server-tecsvc/src/main/java/org/apache/olingo/server/tecsvc/TechnicalServlet.java
As you can see the library is contained in the OData object and the handling is done in the ODataHttpHandler.


text:
Q: How operations are performed for dynamic array? I have studied everywhere in books about Dymanic arrays. I have used them in STL of C++.
But I am still unclear about what are Dynamic arrays. How the operations over Dynamic arrays are implemented.

A: In C++ there are (well, pretty soon will be!) 4 kinds of arrays: C-style static arrays, C++11 static arrays, C++ dynamic vectors and C++14 dynamic arrays.
The C-style and C++11 static arrays take a compile-time constant size parameter and cannot be enlarged / shrunk after their initialization. C++ dynamic vectors can take any runtime number of elements at initialization, and can be enlarged / shrunk afterwards. With the upcoming C++14 Standard, there will also be std::dynarray that fills a smal gap between the existing containers: it will take a runtime number of elements during initialization, but cannot be enlarged / shrunk afterwards.
Here are some basic use cases:
static const int N = 4;                // compile-time constant int
int M = 4;                             // run-time int

int c[N] = { 0, 1, 2, 3 };             // C-style static array: compile-time constant size
std::array<int, N> a = { 0, 1, 2, 3 }; // C++11 static array: compile-time constant size

int rc[M] = { 0, 1, 2, 3 };             // ERROR: M is not a compile-time constant expression
std::array<int, M> ra = { 0, 1, 2, 3 }; // ERROR: M is not a compile-time constant expression

std::vector<int> v { std::begin(a), std::end(a) };   // C++ dynamic vector: runtime size, but can be enlarged afterwards
v.push_back(4);                                      // v enlarged to { 0, 1, 2, 3, 4 } now
v.pop_back();                                        // v shrunk back to { 0, 1, 2, 3 }

std::dynarray<int> d { std::begin(v), std::end(v) }; // C++14 dynamic array: runtime size, but cannot be enlarged afterwards

Static arrays (C-style arrays, std::array) do static memory allocation on the stack. Dynamic arrays (std::vector<T> and std::dynarray<T>) can take an Allocator template parameter. For std::vector this Allocator defaults to std::allocator<T>, which does dynamic low-level memory management behind the scenes using new. For std::dynarray the memory is allocated from an unspecified source, which may, or may not, invoke the global operator new.
By supplying a user-defined allocator, both std::vector and std::dynarray can be made to work with stack-based memory allocation, e.g. using @HowardHinnant 's stack allocator.


text:
Q: Abstracting CSS Is there any way of making an abstract rule of css where this kind of code (sass):
#cottage-image-gallery input:nth-of-type(1):checked ~ label:nth-of-type(1) img,
#cottage-image-gallery input:nth-of-type(2):checked ~ label:nth-of-type(2) img,
#cottage-image-gallery input:nth-of-type(3):checked ~ label:nth-of-type(3) img,
#cottage-image-gallery input:nth-of-type(4):checked ~ label:nth-of-type(4) img,
#cottage-image-gallery input:nth-of-type(5):checked ~ label:nth-of-type(5) img,
#cottage-image-gallery input:nth-of-type(6):checked ~ label:nth-of-type(6) img,
#cottage-image-gallery input:nth-of-type(7):checked ~ label:nth-of-type(7) img,
#cottage-image-gallery input:nth-of-type(8):checked ~ label:nth-of-type(8) img
  position: fixed

can be turned into something like this:
#cottage-image-gallery input:nth-of-type(n):checked ~ label:nth-of-type(n) img
  position: fixed

when n equals 1 the same goes to the second variable; when n equals 2 the second variable goes 2; and so on...
The reason I am not using the adjacent selector "+" is that I need to have the inputs under the same parent but all near each other.
Best Regards
Example: https://codepen.io/s3m3nT3s/pen/rYBxLq

A: In Sass, you can use a @for directive to do this.
@for $i from 1 through 8
  #cottage-image-gallery input:nth-of-type(#{$i}):checked ~ label:nth-of-type(#{$i}) img
    position: fixed

Outputs this:
#cottage-image-gallery input:nth-of-type(1):checked ~ label:nth-of-type(1) img {
  position: fixed;
}
#cottage-image-gallery input:nth-of-type(2):checked ~ label:nth-of-type(2) img {
  position: fixed;
}
#cottage-image-gallery input:nth-of-type(3):checked ~ label:nth-of-type(3) img {
  position: fixed;
}
#cottage-image-gallery input:nth-of-type(4):checked ~ label:nth-of-type(4) img {
  position: fixed;
}
#cottage-image-gallery input:nth-of-type(5):checked ~ label:nth-of-type(5) img {
  position: fixed;
}
#cottage-image-gallery input:nth-of-type(6):checked ~ label:nth-of-type(6) img {
  position: fixed;
}
#cottage-image-gallery input:nth-of-type(7):checked ~ label:nth-of-type(7) img {
  position: fixed;
}
#cottage-image-gallery input:nth-of-type(8):checked ~ label:nth-of-type(8) img {
  position: fixed;
}

However, given HTML like this:
<input id="slide1" type="radio" name="cottage-image" data="1">
<input id="slide2" type="radio" name="cottage-image">
<input id="slide3" type="radio" name="cottage-image">
<input id="slide4" type="radio" name="cottage-image">
<input id="slide5" type="radio" name="cottage-image">
<input id="slide6" type="radio" name="cottage-image">
<input id="slide7" type="radio" name="cottage-image">
<input id="slide8" type="radio" name="cottage-image">
<input id="slide0" type="radio" name="cottage-image" checked>

There is simply no way in pure CSS to match input[id="slide1"] with label[for="slide2"], input[id="slide2"] with label[for="slide2"], and so on without repeating yourself a bunch of times like you already are with :nth-child().
The CSS way to do that would be something like:
#cottage-image-gallery input:nth-of-type([id]):checked ~ label:nth-of-type([for]) img

But you can't use attribute selectors inside :nth-child(). Maybe in the future!


text:
Q: Android | loop in onCreate method possible or not? This question extends this thread How to hide ActionBar and NavigationBar after a certain delay time?
This works for my application. But it only runs once. How can I make it to keep executing until a button is pressed (back button)
Btw this is a photoViewer app (part of) like Gmail app on android when you view a photo.
Update1: I actually have a touchListener to show() and hide() the actionBar again. So what I want is when I'm in imageView layout, the actionBar will disappear in 3000ms, then I tap to show(), then after 3000ms it should disappear again. Again, just like Gmail android app when you load a picture from email
@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_ACTION_BAR_OVERLAY); // overlay mode
        setContentView(R.layout.fullscreen_image);

        ActionBar actionBar = getActionBar();
        actionBar.setCustomView(R.layout.actionbar_top);
        actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);

        // time delay to hide actionBar
        Handler h = new Handler();
        h.postDelayed(new Runnable() {
            @Override
            public void run() {
                // DO DELAYED STUFF
                getActionBar().hide();
                getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE);
            }
        }, 3000); // e.g. 3000 milliseconds
....

    Button back = (Button)findViewById(R.id.btnBack);
    back.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            onBackPressed();
        }
    });

A: I think you should move the creation of the timer-thread to your onClick(), so that every time it gets click, a new timer is started.

A: placing your timer in OnCreate ensures it will run once and only once.
If you want it to run everytime place the user rotates the screen, pauses or whatever, put it in onResume. But, as popovitsj suggests, putting on the onClick is likely what you want


text:
Q: Adding provider to config in AngularJs not working With the use of sachinchoolur's angularjs-flash module I want to add flash messages to my application.
The flash messages are working with my setup, but they don't disappear.
In the documentation it says to add a Time Out with a FlashProvider in the app's configuration.
I am trying to do this but whenever I inject the FlashProvider, my AngularJs logic stops working (all logic).
FlashProvider from the 3rd party module: angular-flash.min.js
app.provider('Flash', function () {
    var defaultConfig = {};
    var templatePresets = {
        bootstrap: {
            html: '\n
\n
\n                        ×\n                        Close\n
\n                    \n
',
            transclude: false
        },
        transclude: {
            html: '

',
            transclude: true
        }
    };

    this.setTimeout = function (timeout) {
        if (typeof timeout !== 'number') return;
        defaultConfig.timeout = timeout;
    };
    this.setShowClose = function (value) {
        if (typeof value !== 'boolean') return;
        defaultConfig.showClose = value;
    };
    this.setTemplate = function (template) {
        if (typeof template !== 'string') return;
        defaultConfig.template = template;
    };
    this.setTemplatePreset = function (preset) {
        if (typeof preset !== 'string' || !(preset in templatePresets)) return;

        var template = templatePresets[preset];
        this.setTemplate(template.html);
        defaultConfig.templateTransclude = template.transclude;
    };
    this.setOnDismiss = function (callback) {
        if (typeof callback !== 'function') return;
        defaultConfig.onDismiss = callback;
    };

    this.setTimeout(5000);
    this.setShowClose(true);
    this.setTemplatePreset('bootstrap');

    this.$get = ['$rootScope', '$timeout', function ($rootScope, $timeout) {
        var dataFactory = {};
        var counter = 0;

        dataFactory.setTimeout = this.setTimeout;
        dataFactory.setShowClose = this.setShowClose;
        dataFactory.setOnDismiss = this.setOnDismiss;
        dataFactory.config = defaultConfig;

        dataFactory.create = function (type, text, timeout, config, showClose) {
            if (!text) return false;
            var $this = void 0,
                flash = void 0;
            $this = this;
            flash = {
                type: type,
                text: text,
                config: config,
                id: counter++
            };
            flash.showClose = typeof showClose !== 'undefined' ? showClose : defaultConfig.showClose;
            if (defaultConfig.timeout && typeof timeout === 'undefined') {
                flash.timeout = defaultConfig.timeout;
            } else if (timeout) {
                flash.timeout = timeout;
            }
            $rootScope.flashes.push(flash);
            if (flash.timeout) {
                flash.timeoutObj = $timeout(function () {
                    $this.dismiss(flash.id);
                }, flash.timeout);
            }
            return flash.id;
        };
        dataFactory.pause = function (index) {
            if ($rootScope.flashes[index].timeoutObj) {
                $timeout.cancel($rootScope.flashes[index].timeoutObj);
            }
        };
        dataFactory.dismiss = function (id) {
            var index = findIndexById(id);
            if (index !== -1) {
                var flash = $rootScope.flashes[index];
                dataFactory.pause(index);
                $rootScope.flashes.splice(index, 1);
                if (typeof defaultConfig.onDismiss === 'function') {
                    defaultConfig.onDismiss(flash);
                }
            }
        };
        dataFactory.clear = function () {
            while ($rootScope.flashes.length > 0) {
                dataFactory.dismiss($rootScope.flashes[0].id);
            }
        };
        dataFactory.reset = dataFactory.clear;
        function findIndexById(id) {
            return $rootScope.flashes.map(function (flash) {
                return flash.id;
            }).indexOf(id);
        }

        return dataFactory;
    }];
});

My main module configuration
// public/js/app.js
angular.module('myApp', [
  'ngRoute',
  'ngFlash',
  'myApp.home',
  'myApp.profile',
  'myApp.login',
  'myApp.signup'

])
.config(['$locationProvider', '$routeProvider', 'FlashProvider'
  function($locationProvider, $routeProvider, $httpProvider, FlashProvider) {

    $locationProvider.hashPrefix('!');

    $routeProvider.otherwise({redirectTo: '/home'});
}]);

Javascript reference in the html file

EDIT
According to the documentation to automatically disappear the flashes after a certain amount of time I did this, but they still don't disappear.
html file
<flash-message duration="5000"></flash-message>

config file
.config(['$locationProvider', '$routeProvider', '$httpProvider', 'FlashProvider',
      function($locationProvider, $routeProvider, $httpProvider, FlashProvider) {

        FlashProvider.setTimeout(5000);

A: Duh! The injections are not in order! You had missed $httpProvider. It actually meant FlashProvider was injected as $httpProvider :)
Your config should be like this. And if everything else is in place, this should make it work
.config(['$locationProvider', '$routeProvider', '$httpProvider', 'FlashProvider'
  //---------------------------------------------^^^
  function($locationProvider, $routeProvider, $httpProvider, FlashProvider) {
    $locationProvider.hashPrefix('!');
    $routeProvider.otherwise({redirectTo: '/home'});
}]);


text:
Q: How to convert a date YYYY-MM-DD to epoch in PHP As per title: how to convert a string date (YYYY-MM-DD) to epoch (seconds since 01-01-1970) in PHP

A: Use the strtotime() function:
strtotime('2013-03-13');

A: Perhaps this answers your question
http://www.epochconverter.com/programming/functions-php.php
Here is the content of the link:
There are many options:

*

*Using 'strtotime':

strtotime parses most English language date texts to epoch/Unix Time.
echo strtotime("15 November 2012");
// ... or ...
echo strtotime("2012/11/15");
// ... or ...
echo strtotime("+10 days"); // 10 days from now

It's important to check if the conversion was successful:
// PHP 5.1.0 or higher, earlier versions check: strtotime($string)) === -1
if ((strtotime("this is no date")) === false) {
   echo 'failed';
 }

2. Using the DateTime class:
The PHP 5 DateTime class is nicer to use:
// object oriented
$date = new DateTime('01/15/2010'); // format: MM/DD/YYYY
echo $date->format('U');

// or procedural
$date = date_create('01/15/2010');
echo date_format($date, 'U');

The date format 'U' converts the date to a UNIX timestamp.

*Using 'mktime':

This version is more of a hassle but works on any PHP version.
// PHP 5.1+
date_default_timezone_set('UTC');  // optional
mktime ( $hour, $minute, $second, $month, $day, $year );

// before PHP 5.1
mktime ( $hour, $minute, $second, $month, $day, $year, $is_dst );
// $is_dst : 1 = daylight savings time (DST), 0 = no DST ,  -1 (default) = auto

// example: generate epoch for Jan 1, 2000 (all PHP versions)
echo mktime(0, 0, 0, 1, 1, 2000);

A: use strtotime() it provides you Unix time stamp starting from 01-01-1970

A: Try this :
$date  = '2013-03-13';

$dt   = new DateTime($date);
echo $dt->getTimestamp();

Ref: http://www.php.net/manual/en/datetime.gettimestamp.php


text:
Q: How do I get the height of the recyclerview? In my app I have a GridlayoutManager combined with a recyclerview. What I would like to do is get the height of the recyclerview, since I want to have an even 3x4 grid of imageviews.
The code below gets the height and width of the device.
    WindowManager wm = (WindowManager) someView.getContext().getSystemService(Context.WINDOW_SERVICE);
    Display display = wm.getDefaultDisplay();
    Point size = new Point();
    display.getSize(size);
    int height = (size.y)/4;
    int width = (size.x)/3;

This code sets the parameters (height and width) of the imageview.
Imageview imgView = ...findbyid...;

Imageview imgView.getLayoutParams().height = (size.y)/4;
          imgView.getLayoutParams().width = (size.x)/3;

This works fine for my width, but not for my height. The reason being I can't use the whole screen size, as I have to account for the Toolbar and a sliding tab below it. See image of layout here!!
As you can see from the image I only want the height of the recyclerview.
Any help is much appreciated. Thanks :)


text:
Q: GSuite displaying "via" next to name after DNS change After changing over to Cloudflare GSuite has been adding "via" next to the names of incoming emails. After a quick Google search I found this:
https://support.google.com/mail/answer/1311182?hl=en
However my DMARC reads:
v=DMARC1; p=none;

This is driving me insane and causing a lot of time loss, how can I remedy this problem?

A: check G Suite configuration with this tool
https://toolbox.googleapps.com/apps/checkmx/
Ensure that DKIM and SPF records are properly added to Cloudflare


text:
Q: How do I do a `git checkout` in visual studio 2019? I'd like to go back and look at a commit of the code I previously published. From the command line, it would be git checkout [commit id], but I'd like to do it though Visual Studio (2019) so I don't have to open the command prompt and find/copy the commit id. I don't want to make any permanent changes to the code, I just want to be able to browse/debug the old code.
This seems like it should be a feature in Visual Studio - from the history window, I can see options for Revert, Reset, Cherry-Pick, but I don't think any of those are re-named version of checkout. I tried searching for "visual studio 2019 how do I checkout a previous commit git" (and various wordings), but I can't find the answer.
The solution I've used so far was to make a new branch from the commit I want to look at, then delete the branch when done, but it seems like there must be a better way...
Here is the right-click menu:

A: Currently, there is not any way to do this in VS. You must do it in a command line. There is a ticket in VS community for adding this feature. You can log in and vote for that. Maybe that helps and you may see it in the next version of VS.


text:
Q: Advantages and disadvantages of preventing default event action at start or end of JavaScript function In the following JavaScript code sample:
var myButton = $('#myButton');
myButton.click(function (event) {
    /* stuff... */
    event.preventDefault();
});

What are the advantages and disadvantages of default-preventing the action at the beginning or the end of the function? - supposing the case of unconditionally wanting to prevent it in the end. Is there any technical reason to choose one way?
Surfing the internet I've found only one reference -dead blog, sorry for the Google Cache link-, and points that preventing the default action at the beginning will avoid the action happening in case the js function crashes.
NOTE: I've used jQuery in my example just for familiarity, the question is not about jQuery, the answer for the classical event handling mode will be the same.

A: The final call where to put preventDefault() is totally on developer's choice. Though as it is already pointed in most cases better choice is place it at the very top of code to avoid unpredictable behavior like this:
 $('#one').click(function(ev){
  //ev.preventDefault(); // for 90% this is better choice, consider example below
  alert('no hey!');
  return; // this is very simple example, in more complex code sometimes it could not be such obvious
  ev.preventDefault(); // sometimes though it may be required to keep default action depending on some cases
})

But have to admit that it could occur that you have keep default action depending on something, as my point this is rare situation, but than you may put prevent default at the bottom and use return with some if condition.

A: I put my preventing code at the beginning for the reason you stated. If there is an error earlier in the js earlier in the function, the default action will already have been prevented. This can be desired behavior in production, but can also help in debugging your development code, consider:
$('a').on('click', function(e) {
  console.log('some debugging information here');
  // Other stuff
  e.preventDefault();
});

If an error were to happen, the page could refresh or follow the href of the anchor before you could read the debugging information. Switching the action to the top will make sure you can read the output in the console.
Edit As Axel points out in the comments, another advantage is you immediately grok that the code is replacing the default action and not supplementing it.

A: You don't have any diference, the message queue is trapped in your function.


text:
Q: Purchase of product automatically handled with automatic mail? I will try to be as specific as I can be.
I have a Magento webstore, now I wanted to know, if it is possible when a customer purchases a product, (ie: a license) that said product would be handled automatically, and that the customer will get his license (code or key) delivered by mail automatically without human interference.
Is there a way to make this work? Installing a bot, or a plug-in?
Hopefully one of you can help me out on this!

A: You could follow this way:
Use an observer to add custom option & it's value programmatically.
In Your case Custom option
Title: License Key
Value: xxxxx-xxxxxx-xxxxx-xxxx-xxxxxx

Now default magento by default send the custom option details in order success email.


text:
Q: How do you change the text "Update failed. You are probably offline." <- can't seem to change this default text in my wordpress How do you change the text "Update failed. You are probably offline." <- can't seem to change this default text in my wordpress.
Doing
    grep -rnH 'You are probably offline' .

gets
     ./wp-includes/js/dist/api-fetch.js:856:      message: Object(external_this_wp_i18n_["__"])('You are probably offline.')

and
     ./wp-includes/js/dist/api-fetch.min.js:2:

i edited both text by replacing . with ... BUT it doesnt change at all. can someone try and answer how to get this done? I would like to replace the text with "Please reload." because the firewall is blocking the access after too frequent updates of the wordpress so i would like my user to reload the page instead of this default msg.
     ./wp-includes/js/dist/api-fetch.js:856:      message: Object(external_this_wp_i18n_["__"])('You are probably offline....')

can someone help? thx


text:
Q: How does pnpm's node_modules structure avoid circular symlinks? I'm reading this article explaining the node_modules structure of pnpm.
https://pnpm.js.org/en/symlinked-node-modules-structure
It states next to the bolded text avoid circular symlinks that dependencies of packages are placed in the same folder in which the dependent packages are.
I get the next sentence it doesn't matter which node_modules folder dependencies are in since node will continue to look one level up for a node_modules folder, but I don't get how circular symlinks are avoided.
So how does this avoid circular symlinks?


text:
Q: How to decompose linear function of several variables to partial effects if changes are large?
*

*Suppose we have linear function of two variables: z=f(x,y)

*For simplicity lets take the form: z=x*y (coud be with more variables)

*If both x and y change by significant amount x->x1 and y->y1 then z->z1=x1*y1

*How can we express the total change of z (z-z1) as a sum of partial changes due to x and y?

*Since the formula for total derivative is approximation for small changes, what decomposition should be used when changes are large?

*Is there a generic decomposition, at least for linear functions?

*Is there a general approach for calculating what % of the change in z is due to the change in x and what is due to the change in y?


text:
Q: reloading table I've have a table view that consist of item list that depends on the item that were purchased using in app purchasing.
My question was how can I reload the tableView when the purchasing was completed/(or when new item was added on my list). The response of the storekit takes time to complete. Are there anyways to tell the app that the purchasing was completed and new item was added on my list so that I can reload my tableView.
At this time I reloading my table view by adding [myTableView reloadData] in viewWillAppear method.
But what if the user was already viewing the tableView, I can't reload the tableView because the viewWillAppear had passed.
thanks...

A: You should get a call back when the transaction completes. Put your reloadData call in there.


text:
Q: How do I find the minimum speed of a bullet so that a sphere hanging from a ceiling performs a circular orbit? The problem is as follows:

The diagram from below shows a sphere is hanging from a ceiling by a
  cable whose length is R as is shown in the diagram from below. A
  bullet whose mass is $m$ is fired and has a speed of $v$ and travels
  in a straight line and gets embedded in the sphere whose mass is also
  $m$. As a result of the collision the sphere swings and makes a
  circular orbit. What should be the minimum speed of the bullet
  such the sphere does a circular orbit?.

The alternatives given are as follows:
$\begin{array}{ll}
1.&2\sqrt{2Rg}\\
2.&2\sqrt{Rg}\\
3.&4\sqrt{Rg}\\
4.&3\sqrt{Rg}\\
5.&\sqrt{0.5Rg}\\
\end{array}$
What I thought to solve this problem was that I can relate the momentum before and after the collision and with that speed I can relate it with the conservation of the mechanical energy when the bullet is embedded in the sphere.
This would become into:
$mv= \left(m+m\right) v_f$
$v_f=\frac{1}{2}v$
This speed can be used to relate it with the conservation of mechanical energy as follows:
$E_{k1}=E_u+E_{k2}$
$\frac{2m}{2}\left(\frac{1}{2}v\right)^2=(2m)gR+\frac{2m}{2}v_{t}^2$
$v_{t}=\textrm{Tangential speed when the ball swings}$
Then:
$\frac{v^2}{4} = 2gR+v_{t}^2$
However I end up with not knowing how to get the tangential speed or relating it to the speed which should had the bullet. How can I find it?. I'm guessing that it could be the second option.
But for that to happen would imply that:
$\frac{mu^2}{R}=2mg$
Then
$u=\sqrt{2Rg}$
So by the conservation of momentum would imply:
$p_i=p_f$
Therefore $mv=2mu$
$v=2\sqrt{2Rg}$
So that would mean that is the first option. But would that be the answer?. That would mean that the sphere rises to the top making half a circle.
Can an answer include some drawing to explain for a better view what it was intended in this problem? please. I'm stuck!.

A: The energy the instant after the bullet strikes is purely kinetic energy:
$$E_1 = \frac{1}{2} (2 m) \left( \frac{v}{2} \right)^2$$
The energy when the mass is at the top of the loop is the sum of its kinetic energy and potential energy:
$$E_2 = \underbrace{\frac{1}{2} (2m) V^2}_{kinetic} + \underbrace{(2m)g(2 R)}_{potential}$$
where $V$ is the velocity at the top.
By conservation of energy $E_1 = E_2$.
For the pendulum to make the full circle loop, the centripetal acceleration at the top must equal the acceleration due to gravity.  (Otherwise, there would be tension in the rope and you could find a lower velocity that would enable the looping.)
So we must have $V^2/R = g$.
Put these together and solve for $v$.


text:
Q: Upgraded to Glassfish 4.1 - Now error while deploying EAR with Swing app packaged - Can't find resource for PropertyResourceBundle The full error from the log is:
org.glassfish.deployment.common.DeploymentException: Can't find resource for bundle java.util.PropertyResourceBundle, key enterprise.deployment.appclient.noManifest
The relevant stack trace is:
[2014-09-15T16:28:09.695-0500] [glassfish 4.1] [SEVERE] [] [] [tid: _ThreadID=48 _ThreadName=Thread-9] [timeMillis: 1410816489695] [levelValue: 1000] [[
  org.glassfish.deployment.common.DeploymentException: Can't find resource for bundle java.util.PropertyResourceBundle, key enterprise.deployment.appclient.noManifest
    at org.glassfish.javaee.full.deployment.EarDeployer.prepare(EarDeployer.java:182)
    at com.sun.enterprise.v3.server.ApplicationLifecycle.prepareModule(ApplicationLifecycle.java:925)
    at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:434)
    at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:219)
    at org.glassfish.deployment.admin.DeployCommand.execute(DeployCommand.java:491)

I have a basic EAR with an EJB in it, and a Swing app also in it.
When I deploy with just the EJB, everything works fine. When I add the Swing app, it fails with this error.
It was working before I used this tutorial to change the keystore to have a secure certificate rather than the self signing.
Is it possible that the new signing for java web start is causing the manifest to not be created?


text:
Q: Stanford Engineering Everywhere CS106B Library I  am currently a C# programmer and have been interested in learning more about C++ and data structures.  I found the CS106B class offered free online through the Stanford Engineering Everywhere program which seems like it would be a good fit.
I've tried to install the library files they use for the class and keep getting a message that I have to have visual studio 2005 installed for the setup file to run.  I don't have 2005, but I've tried the express editions of both vc++ 2008 and vc++2005.  Is there any way around this that I can get the proper files installed?
The zip file containing the libraries came with two files, an exe and an msi.

A: Just got it to work by using some information I found here: http://www.functionx.com/visualc/libraries/staticlib.htm
I'm using Visual C++ 2008 Express. Here's how I did it:

*

*Download the PC Starter Code ZIP file for Assignment 1 from the
current semester's CS106B class website.
http://www.stanford.edu/class/cs106b/ In that file you'll find a
folder named "StanfordCPPLib". In that folder, you'll need the
StanfordCPPLib.lib and the *.h files you want to include.

*In Visual Studio, create a new project (File -> New -> Project). Select a Win32
Console Application, choose a name, and click Next.

*When the Application Wizard pops up, click Next (not Finish). In the
Application Settings, check the box marked "Empty Project". Click
Finish.

*In the Solution Explorer, right click on the Source folder and
create a new .cpp file. (Add -> New Item -> Code -> C++ File)

*Find your new project's folder in Windows Explorer. In that folder,
you should be able to find your new .cpp file you just created.

*Paste the StanfordCPPLib.lib and your needed *.h files you
downloaded earlier into the same folder that contains your new .cpp file.

*Finally, you need to add the library to our new project. In Visual Studio, using
the main menu, click Project -> Add Existing Item. The dialog should
default to your project's folder where you just pasted
StanfordCPPLib.lib. Select StanfordCPPLib.lib and click Add.

You should now be able to add an #include "example.h" for whatever .h files you copied into your project folder.
Note: Since you'll be using a newer version of Stanford's custom library, there may be some small differences between the original handouts and the new library. For instance, when using #include "simpio.h", the handouts list a function called GetLine(). In the new library, that function is capitalized differently: getLine(). Make sure you check the header files for correct syntax/usage.

A: Thanks to Dani, with his help, I succeed in installing the library on vs2008(both express and professinal are OK) on win7. With Dani's help,
I have finished the first three assignments in cs106X(winter2010) - life, ADT, boggle - so far.
I'm just a undergraduate in China, thanks so much to the great education of stanford and power of internet.
http://abloggingattempt.blogspot.com/2010/05/stanford-cs106-lib-and-vs2008-express.html
the following are copied mainly from Dani's blog.
Stanford CS106 Lib and VS2008 Express
The CS106B is a great CS Stanford course available online (iTunes e.g.) in video and for free. All assignments and the course itself use an in-house developed library (not sure if it has a name, cslib, cs106 lib, dunno) available in all of the assignment zips as well as installable with the Xcode/VS2005 wizard installs. The problem - the VS custom wizard will install on VS2005 only (could be that a newer version exists but I couldn't find one). So how to port the VS wizard to VS2008 Express(professional)?
- I got the 2005 custom wizard setup, PCLibs-VS2005-ADT-Installer.zip and used a small tool , the LessMSIerables(Universal Extractor also works well) in order to extract the contents of the msi file. The msi contains four folders with all the stuff needed to create a new custom wizard. So, the tool extracted the following:
SourceDir
|- Includes Folder
|- Library Folder
|- Project Folder
|- Wizard Folder

*

*Now some copying:

*

*The CS106CPPInc folder inside the 'Includes Folder' goes to
C:\Program Files\Microsoft Visual Studio 9.0\VC\include (as a subfolder!)

*'Library Folder'\CS106CPPLib.lib goes to
C:\Program Files\Microsoft Visual Studio 9.0\VC\lib

*'Wizard Folder\AppWiz\CS106 Assignment Wizard' to
C:\Program Files\Microsoft Visual Studio 9.0\VC\VCWizards\AppWiz
(meaning CS106... should appear as a sub-folder of AppWiz)

*The three files in 'Project Folder' will go into
C:\Program Files\Microsoft Visual Studio 9.0\VC\Express\VCProjects\Stanford. One of those three files, the CS106 Assignment Wizard.vsz, needs to be edited (a text file) and its second line should become:

Wizard=VsWizard.VsWizardEngine.9.0

A: Was having the same problem. I found both the .h and the .c files online.
You can find them here:
http://www.ime.usp.br/~pf/Roberts/C-library/standard/cslib/

A: I suggest to go to the CS106B page directly:
http://www.stanford.edu/class/cs106b/
And grab newest assignments. They are compatible with VS 2008.
The assignment material from SEE is outdated (VS 2005). The assignments are not discussed in the video, so you won't miss anything by doing that.
Just download from the CS106B page and open in VS 2008, that will work!

A: Reading through handout 5P makes it seem like the installer will expect the file structure VS2005 will create - especially this sentence: "Run (and quit) Visual Studio (you can go ahead and register your copy if it asks you). It is important that you have done this at least once before proceeding to the next step."
Try creating a folder structure like: (under "My Documents") "Visual Studio 2005\Projects" and see if setup.exe will work.

A: I am using visual studio express, and all I did was to just unzip the files it works fine..  here I have done the CS106B assignment with also the full zip'd up files of that assignment as well, all I did was to uncompress the assignment from the cs106b website and open up the sln (solution) file within visual studio express.

A: There is no c++ library available for cs106b in unix system. I hope they publish the library in source.


text:
Q: Keras: ResourceExhaustedError (see above for traceback): OOM when allocating tensor with shape[26671,32,32,64] I am training my network using Keras on tensorflow backend(Keras version 2.1), I have tried many things available on internet, but did not find any solution.
My Training set and labels: 26721(each image have size (32, 32,1)) , (26721, 10)
Validation set and labels:  6680(each image have size(32,32,1), (6680,10)

This is my model so far, I am using Python3.
def CNN(input_, num_classes):

model = Sequential()

model.add(Convolution2D(16, kernel_size=(7, 7),  border_mode='same',
                 input_shape=input_))
model.add(BatchNormalization())
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2), strides=(1, 1) ,  border_mode='same' ))
model.add(Convolution2D(64, (3, 3),  padding ='same'))
model.add(BatchNormalization())
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(3, 3), strides=(1,1),  border_mode='same' ))
model.add(Flatten())
model.add(Dense(96))
model.add(Activation('relu'))

model.add(Dense(num_classes))
model.add(Activation('softmax'))
return model

model = CNN(image_size, num_classes)

model.compile(loss=keras.losses.categorical_crossentropy,
          optimizer=keras.optimizers.SGD(lr=0.01),
          metrics=['accuracy'])

print(model.summary())
csv_logger = CSVLogger('training.log')
early_stop = EarlyStopping('val_acc', patience=200, verbose=1)
model_checkpoint = ModelCheckpoint(model_save_path,
                                    'val_acc', verbose=0,
                                    save_best_only=True)

model_callbacks = [early_stop, model_checkpoint, csv_logger]
# print "len(train_dataset) ", len(train_dataset)
print("int(len(train_dataset)/batch_size) ", int(len(train_dataset)/batch_size))
K.get_session().run(tf.global_variables_initializer())
 model.fit_generator(train,
              steps_per_epoch=np.ceil(len(train_dataset)/batch_size),
              epochs=num_epochs,
              verbose=1,
              validation_data=valid,
              validation_steps=batch_size,
              callbacks=model_callbacks)

Model Summary:
_________________________________________________________________
Layer (type)                 Output Shape              Param #
=================================================================
conv2d_1 (Conv2D)            (None, 32, 32, 16)        800
_________________________________________________________________
batch_normalization_1 (Batch (None, 32, 32, 16)        64
_________________________________________________________________
activation_1 (Activation)    (None, 32, 32, 16)        0
_________________________________________________________________
max_pooling2d_1 (MaxPooling2 (None, 32, 32, 16)        0
_________________________________________________________________
conv2d_2 (Conv2D)            (None, 32, 32, 64)        9280
_________________________________________________________________
batch_normalization_2 (Batch (None, 32, 32, 64)        256
_________________________________________________________________
activation_2 (Activation)    (None, 32, 32, 64)        0
_________________________________________________________________
max_pooling2d_2 (MaxPooling2 (None, 32, 32, 64)        0
_________________________________________________________________
flatten_1 (Flatten)          (None, 65536)             0
_________________________________________________________________
dense_1 (Dense)              (None, 96)                6291552
_________________________________________________________________
activation_3 (Activation)    (None, 96)                0
_________________________________________________________________
dense_2 (Dense)              (None, 10)                970
_________________________________________________________________
activation_4 (Activation)    (None, 10)                0
=================================================================
Total params: 6,302,922
Trainable params: 6,302,762
Non-trainable params: 160

I am sending images according to batch size. This is my generator function:
# Generate images according to batch size

def gen(dataset, labels, batch_size):

images = []
digits = []
i = 0
while True:
    images.append(dataset[i])
    digits.append(labels[i])
    i+=1
    if i == batch_size:
        yield (np.array(images), np.array(digits))
        images = []
        digits = []
    # Generate remaining images also
    if i == len(dataset):
        yield (np.array(images), np.array(digits))
        images, digits = [], []
        i = 0

   train = gen(train_data, train_labels, batch_size)
   valid = gen(valid_data, valid_lables, batch_size)

Error log on terminal:
Please check this link for complete error: Terminal Output
Can anyone please help me, What I am doing wrong here?
Thanks in advance

A: You are training your network on your entire train set, which is too big to fit in memory, and too large for your gpu.
The standard in machine learning is to create small batches of your data and train on those. Batch sizes are usually 16, 32, 64 or some other power of two, but it can be anything, you usually have to find the correct batch size through cross validation.

A:
From the logs you can see that before allocating edge_1094_loss the memory is already full. Check the values Limit ad InUse.
This is perhaps because the memory is consumed by older models. Quick hack to solve this is to simply kill the process. This will release all the memory consumed by older models which are somehow not garbage collected.


text:
Q: Iterator errors with lists So this is my program.  It's pretty self explanatory.  There is one menu that has 4 options.  Each option lets out to a version of two different sub-menus.  I'm dealing with lists and vectors, but right now the lists are giving me errors.  Am I doing something wrong with the iterators?  I'm pretty sure that's what all of my errors are with.
#include <iostream>
#include <vector>
#include <algorithm>
#include <list>
#include <vector>
using namespace std;

template <class T>
void lst(T inglethorp, int a)
{
  list<T> mylist;
  int sel = 10;
  T ins;
  int place;
  list<T>::iterator iter; //is this wrong?
  //error: expected ';' before 'iter'
  //dependent-name 'std::list::iterator' is parsed as a non-type, but instantiation yields a type

  switch(a)
  {
    case 1:
        cout << "What would you like to load to the front?" << endl;
        cin >> ins;
        mylist.push_front(ins);
        cout << endl << endl;
        break;
    case 2:
        cout << "What would you like to load to the back?" << endl;
        cin >> ins;
        mylist.push_back(ins);
        cout << endl << endl;
        break;
    case 3:
        cout << "Where would you like to insert the value?" << endl;
        cin >> place;
        iter = mylist.begin(); //'iter' was not declared in this scope
        for(int i=0; i < place; i++)
            iter++;
        cout << "What would you like to lod at this point?" << endl;
        cin >> ins;
        mylist.insert(iter, ins);
        cout << endl << endl;
        break;
    case 4:
        cout << "What would you like to search for?" << endl;
        cin >> ins;
        iter = find(mylist.begin(), mylist.end(), ins);
        if(iter==mylist.end())
            cout << ins << " was not founf." << endl << endl;
        else
            cout << ins << " is in the list" << endl << endl;
        break;
    case 5:
        cout << "What would you like to remove?" << endl;
        cin >> ins;
        mylist.remove(ins);
        cout << endl << endl;
        break;
    case 6:
        for(iter = mylist.begin(); iter != mylist.end(); iter++)
            cout << *iter << " " << endl << endl;
        break;
    case 0:
        break;
    default:
        cout << "Enter a valid number between 0 and 6" << endl << endl;
        break;
  }
}

void listsub()
{
    cout << endl << endl << "Linked List Sub-Menu" << endl;
    cout << "+++++++++++++++++++++++++++++++++++++++++++++++++" << endl;
    cout << "1. Insert a value at the front of the list" << endl;
    cout << "2. Insert a value at the back of the list" << endl;
    cout << "3. Insert a value at a given position in the list" << endl;
    cout << "4. Search the list for a value" << endl;
    cout << "5. Delete all instances of a value" << endl;
    cout << "6. Print the list contents" << endl << endl;
    cout << "0. Return to main homework menu" << endl;
    cout << "+++++++++++++++++++++++++++++++++++++++++++++++++" << endl;
}

int main()
{
  int sel = 10;
  int subsel = 10;
  int a = 1;
  double b = 1.1;
  int sel2 = 19;
  while(sel != 0)
  {
    sel = 10;
    subsel = 10;
    cout << endl << endl << "Welcome to the CS222 Homework 7 Menu!" << endl;
    cout << "=================================================" << endl;
    cout << "1. Test the vector STL with integers" << endl; //not done yet
    cout << "2. Test the vector STL with doubles" << endl;  //not done yet
    cout << "3. Test the list STL with integers" << endl;
    cout << "4. Test the list STL with doubles" << endl << endl;
    cout << "0. Exit" << endl;
    cout << "=================================================" << endl << endl;

    cin >> sel;

    switch(sel)
    {
        case 1:
            break;
        case 2:
            break;
        case 3:
            while(sel2 != 0)
            {
                listsub();
                cin >> sel2;
                lst(a, sel2);
            }
            sel2 = 12;
            break;
        case 4:
            while(sel2 != 0)
            {
                listsub();
                cin >> sel2;
                lst(b, sel2);
            }
            sel2 = 12;
            break;
        case 0:
            break;
        default:
            cout << "Select 0-4" << endl;
            break;
    }
  }
  return 0;
}

A: You are missing a typename in list<T>::iterator iter which should be:
typename list<T>::iterator iter;

This is because list<T> depends on the template parameter T, and the compiler assumes by default that list<T>::iterator or any other symbol dependant on T is a value and not a type. Using typename informs the compiler that it really is a type and not a value.
For more info, google "dependent name lookup" (e.g. wiki). Basically the problem is that you could specialize, say class list<int> and define iterator as a value, and in the first compiling pass (parsing) T is not instantiated (has no value) and the compiler doesn't know yet about every possible specialization.

A: Put a typename
typename typename list<T>::iterator iter;

A: You need the typename keyword to make it work rigth. But trying to gess what you are doing, I think you will want to make mylist static. Your code work always with a new empty list, with probably is not what you want.
template <class T>
void lst(T inglethorp, int a)
{
  static list<T> mylist;
  int sel = 10;
  T ins;
  int place;
  typename list<T>::iterator iter; //OK

...


text:
Q: Ag-grid React: how can i save new value when i press Escape? Ag-grid React
I need to save the value of my input when pressing the escape key, but I don't know how to do it in ag -grid.
When i press Enter -  i can save new value,
But with Esc - i cant, it just discard the changes
Where and how can I change this behavior?

A: To do this you'll have to implement your own Custom Editor Component, and inside there you can add logic to listen to the keyPresses inside the input element, and save the value before telling the Grid to stop editing.
Please see this implemented in the following plunkr
First, implement suppressKeyboardEvent to tell the grid to ignore the escape key:
Documentation on Suppressing Keyboard Events
            {
                field: 'number',
                suppressKeyboardEvent: ({ editing, event }) =>
                    event.code === KEY_ESCAPE && editing,
                cellEditor: DoublingEditor,
                editable: true,
                width: 300,
            }

Then, inside the custom editor component, you can add a grid event listener to listen to when keys are pressed (you can also use the browser default keydown):
        useEffect(() => {
            props.api.addEventListener('cellKeyDown', onKeyDown);
            return () => {
                props.api.removeEventListener('cellKeyDown', onKeyDown);
            };
        }, [onKeyDown]);

And finally, inside the listener, check if the escape key is pressed and stop editing the cell if it is:
        const onKeyDown = (params) => {
            if (params.event.code === KEY_ESCAPE) {
                params.api.stopEditing();
            }
        };


text:
Q: JSSOR Slider - Call images from album hosted online, possibly through RSS Feed? First, the reason I am looking to do this is that loading images into the slider is really bogging down my site's performance.
I'm wondering if there is a way to pull in images from an album that is hosted externally, specifically through Google Picasa albums (I'm open to other platforms if they are better suited for it). I would just use their slideshow embed code but it's pretty horrendous.
Could this be done by calling an RSS feed within JSSOR Slider?
Would it even improve site performance or would I have the same issues pulling images from elsewhere?
Thanks in advance. Sorry if what I'm asking isn't best practice or if it doesn't make sense to approach it this way, I'm just trying to improve functionality/performance on my personal portfolio.

A: Did you try lazy loading? If not, please try specify src2 attribute instead of src to define a lazy loading image.


text:
Q: Is it possible to get information as byte (or text( variable in the WiFi? Is it possible to receive all bytes which are flowing in WiFi? Can I receive it as a byte or text using (if I know the WiFi passowrd)? The programing language isn't importatant for me. I think that everybody can read the informations which are flowing using the WiFi because they're the electromagnic waves?

A: You can use Wireshark (www.wireshark.org) to decode packets that are flowing in or out of the machine the programme is running on.
To snoop on packets that are passing between other machines you'll need something that can capture raw packets, such as Shark for Root for Android (https://play.google.com/store/apps/details?id=lv.n3o.shark&hl=en)
Of course, if the traffic is encrypted (connected to an HTTPS address or through a VPN for example) then it's a lot more difficult to decode (though the NSA doesn't have much trouble). You'll need to become a "man in the middle" or get hold of the encryption keys somehow.


text:
Q: Where is the source code of libc6-dev-i386 from? I see this. Where the source of libc6-dev-i386 is from?
$ apt-file search /usr/include/sys/socket.h
libc6-dev-i386: /usr/include/sys/socket.h

https://packages.debian.org/search?keywords=libc6
https://www.gnu.org/software/libc/sources.html
Is it from git://sourceware.org/git/glibc.git?

A: It tells you on the page for the package on the right hand side. It gives the origin as the GNU.org, with links to the files needed to build it linked there as well. The .orig.tar.xz is the original source package from the GNU the other two the Debian files used to build the packages with the changes made. This is the same for all packages, lookup their pages and you get the same information.
https://packages.debian.org/sid/libc6


text:
Q: Powershell retrieve credentials from array I am currently using powershell to manage multiple Office 365 tennancies. The biggest time sink is logging out of the Office 365 account in powershell and logging into the different one.
Is there any way I can create a local CSV containing all username and passwords and then when I use Get-Credential, it can look up the CSV for the username and autofill the password?
Any advice or guidance would be appreciated!

A: Short answer: Yes, it is possible.
But it's not advised to keep the passwords in clear text. Perhaps you could write an example of what you want to achieve, and ask for help if you need help debugging it.
Please seek out information on for example this site, which explains the usage, encryption/decryption to and from secure strings
http://www.travisgan.com/2015/06/powershell-password-encryption.html
I recently used the same source of information to build a solution for a problem not unlike the one you describe above.


text:
Q: Problems with running Zest/Dot programs I am trying to create a simple Java program, which uses the Zest framework in order to generate and display graphs from a .dot input graph. I have downloaded the whole gef4 framework into my eclipse and I have created two example java programs to test the visualization of a normal graph and a dot graph. The normal graph is working fine, but when I try to run the dot graph I end up with the following error (which doesn't make much sense for me)
Exception in thread "main" java.lang.NoClassDefFoundError: org/eclipse/emf/ecore/util/Switch
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(Unknown Source)
at java.security.SecureClassLoader.defineClass(Unknown Source)
at java.net.URLClassLoader.defineClass(Unknown Source)
at java.net.URLClassLoader.access$100(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(Unknown Source)
at java.security.SecureClassLoader.defineClass(Unknown Source)
at java.net.URLClassLoader.defineClass(Unknown Source)
at java.net.URLClassLoader.access$100(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at org.eclipse.gef4.zest.dot.DotGraph.<init>(DotGraph.java:37)
at test2.SampleDotGraph.main(SampleDotGraph.java:19)
Caused by: java.lang.ClassNotFoundException: org.eclipse.emf.ecore.util.Switch
at java.net.URLClassLoader$1.run(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
... 26 more

The java code is the following:
import org.eclipse.gef4.zest.dot.DotGraph;

import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;

public class SampleDotGraph {

public static void main(String[] args) {
    Display d = new Display();
    Shell shell = new Shell(d);
    shell.setText("GraphSnippet1");
    shell.setLayout(new FillLayout());
    shell.setSize(400, 400);

    DotGraph graph = new DotGraph("digraph{ 1->2 }", shell, SWT.NONE);
    graph.add("2->3").add("2->4");
    graph.add("node[label=zested]; edge[style=dashed]; 3->5; 4->6");

    shell.open();
    while (!shell.isDisposed()) {
        while (!d.readAndDispatch()) {
            d.sleep();
        }
    }
}

}

Any thoughts?

A: Read the error stack properly
java.lang.ClassNotFoundException: org.eclipse.emf.ecore.util.Switch
at java.net.URLClassLoader$1.run(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)

Application is not able to find the class Switch in URLClassLoader class in run() method.


text:
Q: Прикрепить файл к контактной форме (Magento) Как сделать так, чтобы при прикреплении к форме файла файл отправлялся менеджеру на почту вместе с контактной информацией о заполнявшем её?

A: Вопрос уже староват, но так как ответа нет то напишу.
Если в общем то добавляем в шаблоне формы input[type=file] для выбора файла, переписываем контроллер в котором принимаем файл и атачим его к письму, вот тут в моем гист есть пример как атачить файл к письму ZF/Magento


text:
Q: Add a hyperlink in one of the columns in JQGrid and clicking on Hyperlink should open a new window I have a jqgrid with certain columns and I need hyperlink in one of the columns, clicking on the hyperlink should open a new window, basically call a window.open().
Also when I call the window.open(), I need the hyperlink column value.
Please provide me with some sample code.Anyhelp would be highly appreciated.
Thanks
Oleg, I tried the below code and it is throwing error "object expected" in load().
 {name:'FileName', FileName:'price', width:60, align:"center", formatter:returnMyLink}

    function returnMyLink(cellValue, options, rowdata)
     {
             return "Open Window";

     }
     function load()
      {
         var guid = 'CEF9C407-2500-4619-95E3-8E6227B65954';
  window.open              ('/irj/servlet/prt/portal/prtroot/com.medline.medpack.ExcelViewerPL.ExcelViewer?report=CustomerBenefit&reportId='+guid );
       }

I did try the document.delegate to capture the a href event.
$(document).delegate('#CustomerSavingsView .jqgrow td a[href="#"]', 'click',function()
  {
     alert('test');
  }

I was not able to capture this event either.
   Sorry Im new to Jquery. Please correct me if Im wrong.
Thanks
This is how I solved it. In the grid complete event added the following code.
      hl = "Test";

And then added a event handler for it.
$(document).delegate('#CustomerSavingsView .jqgrow td a[href*="#Test"]', 'click',  function ()
 {

     var guid = 'CEF9C407-2500-4619-95E3-8E6227B65954';
   window.open('/irj/servlet/prt/portal/prtroot/com.medline.medpack.ExcelViewerPL.ExcelViewer?report=CustomerBenefit&reportId='+guid );
 }

This solved the purpose. Thanks again Oleg and Walter.

A: maybe this will be help:
in colModel,define a col: {name:'test',formatter:linkformatter}
and in javascript create a function named linkformatter which returns a link;
like:
function linkformatter( cellvalue, options, rowObject){
  return '';
}

A: The predefined formatter 'showlink' can be used to create the link in the grid column. You can use target property of the formatoptions options to define target of the link.

A: First declare the Jquery JQGrid column definition as follows
   colModel: [{ name: 'Notes/Memos', width: "5", sortable: true, classes: 'ellip', resizable: false, formatter: MethodFormatter }]

The formatter property takes the method name which is invoked with the three parameters which internally having the cells value and its id and the following method returns the hyperlink.
       function MethodFormatter(cellValue, options, rowObject) {
            var selectedRowId = options.rowId;
            return '' + cellValue + '';}

The following JS Function is invoked after clicking the hyperlink which opens up another page in a window.
       function MethodJS(selectedRowId) {
    document.location.href = "ViewContact.aspx?NoteID=" + selectedRowId;
}

A: My approach involves fewer lines of code and gives the solution asked for.  In my grid, a column called Project Number is formatted as a hyper link.  It opens a new page and passes the project number as a parameter.
colNames: ["Project #", ...],

colModel: [
              { name: 'Project Number', index: 'Project Number', width: 80, key: true, formatter: 'showlink', formatoptions: { baseLinkUrl: 'Details.aspx', target: '_new' } },

Note where I have key: true.  Without this, the url returns the row number.  The url returned is http://localhost:57631/Details.aspx?id=2103

I'm using jqGrid version 5.0.1

A: This is my pattern. As I said, it is much more code than Oleg's suggestion of using the showlink formatter, but it is more customizable.
 // bind a live event handler to any elements matching the selector 'a.linkWindowOpener'
 $('a.linkWindowOpener').live('click', linkWindowOpener);

// colModel settings
    { name: 'ItemDescription', index: 'ItemDescription', formatter: itemDescription_formatter, unformat: itemDescription_unformatter },

// custom formatter to create the hyperlink
function itemDescription_formatter(cellvalue, options, rowObject) {

    var html = '';
    var itemID = rowObject.itemID;
    var itemDescription = cellvalue;

    var a = $('')
            .attr('href', '/Forms/WorkOrder/ViewItem.aspx?ItemID=' + itemID)
            .attr('data-itemDescription', itemDescription )
            .html(itemDescription)
            .addClass('linkWindowOpener');

    html = a.getHtml();

    return html;
}

// unformatter to return the raw value
function itemDescription_unformatter( cellvalue, options, cell) {
    return $('a', cell).attr('data-itemDescription');
}

// event handler to call when clicking the hyperlink
function linkWindowOpener(event) {
    event.preventDefault();
    event.stopPropagation();
    var o = $(event.currentTarget);
    var url = o.attr('href');
    window.open(url);
    return false;
}

// jQuery extenision function I wrote to get the HTML of an element
// returns the HTML of an element. It works by wrapping the element
// inside a DIV and calling DIV.html(). It then returns the element back to
// it's original DOM location
jQuery.fn.getHtml = function () {

    var elm = $(this[0]);
    // create a div
    var div = $('
');

    // append it to the parent of the target element
    elm.parent().append(div);
    // append the element to the div
    div.append(elm);

    // get the html of the div
    var html = div.html();

    // move element back to its parent
    div.parent().append(elm);
    div.remove();

    return html;
}


text:
Q: redis error memory > 'maxmemory' but im using less than half of the max I'm trying to load some large csv files into redis. I get the memory > 'maxmemory' error. However, when I check the usage of my database, it says
used_memory_human:4.63M
used_memory_peak_human:9.26G

I don't understand the disconnect there. I'm trying to upload about 5.6gb and it shouldn't come close to 9. Also, the db was completely empty when I started

A: A few things are going on -

*

*The size of your CSV may not have a direct relationship to the memory taken by redis. How much memory redis consumes depends on what data structures you are using.

*While you are writing to redis, redis is also trying to take a full backup of the data to disk. To take a backup, redis forks the existing process and does a copy on write. Now if you are not writing frequently, the forked process does not consume much memory. But you are writing aggressively - so you end up requiring almost double the memory.

Disable RDB persistence during your bulk load and then load your data. Once you have loaded the data, manually take a backup using the bgsave command. Then you can restore your original backup configuration.


text:
Q: Параллельное исполнение двух функций python Я новичок в питоне и при написании маленького udp чата возникло желание параллельно что-то писать в консоль и отправлять это заданной паре (хост,порт) и прослушивать сеть, получая текст сообщений в консоль.
Я новичок и в потоках, кто-то когда-то писал, что нужно делать это с помощью threading или multiprocessing, прошу помочь мне, буду крайне благодарен :)
Ниже привожу свой код, где имею класс и три функции в нем , где две - send_sock() и listen_sock() нужно исполнить параллельно:
import socket as s

class socket_udp:
    host = ''
    port = 0
    sock = s.socket(s.AF_INET, s.SOCK_DGRAM)

def init_socket(self):
    while True:
        print('enter IP : ')
        self.host = str(input())
        if (self.host == '0.0.0.0') or (self.host == 'localhost'):
            break
        else:
            print('host must be localhost or 0.0.0.0')
            continue
    try:
        print('enter PORT : ')
        self.port = int(input())
    except ValueError:
        print('Port must be integer with base 10')
        print('enter PORT : ')
        self.port = int(input())

    self.sock.setsockopt(s.SOL_SOCKET, s.SO_REUSEADDR, 1)
    self.sock.setsockopt(s.SOL_SOCKET, s.SO_BROADCAST, 1)
    self.sock.bind((self.host, self.port))
    print('now listening port ', self.port, ' on IP ', self.host)

def listen_sock(self):
    while 1:
        try:
            msg, addr = self.sock.recvfrom(256)
            msg = str(msg)[2:len(str(msg)) - 1]
            print(msg, 'from :', addr)
        except KeyboardInterrupt:
            print('input was interrupted by user')
            break
def send_sock(self):
  #  while 1:
            print('enter text')
            text = input()
            socket_udp.sock.sendto(text.encode('utf-8'),('0.0.0.0',11719)) #(socket_udp.host, socket_udp.port))

A: Параллельное исполнение двух функций, которые вводом/выводом занимаются:
import threading

threading.Thread(target=loop, daemon=True).start()
read_input()

Полный пример кода (один поток крутит вертушку, а другой ожидает ввод пользователя):
#!/usr/bin/env python3
"""Run two parallel IO functions."""
import itertools
import threading
import time

def loop():
    for c in itertools.cycle('-/|\\'):
        print(c + '\b', flush=True, end='')
        time.sleep(0.3)

def read_input():
    while True:
        try:
            s = input('Input a string to reverse (q to exit):')
        except (KeyboardInterrupt, EOFError):
            break
        if s == 'q':
            break
        print(s[::-1])

threading.Thread(target=loop, daemon=True).start()
read_input()

A: Решение найдено способом, описанным выше. Привожу полный исправленный код с выводом:
import socket as s
import threading

class socket_udp:
host = ''
port = 0
sock = s.socket(s.AF_INET, s.SOCK_DGRAM)

def init_socket(self):
    while True:
        print('enter IP : ')
        self.host = str(input())
        if (self.host == '0.0.0.0') or (self.host == 'localhost'):
            break
        else:
            print('host must be localhost or 0.0.0.0')
            continue
    try:
        print('enter PORT : ')
        self.port = int(input())
    except ValueError:
        print('Port must be integer with base 10')
        print('enter PORT : ')
        self.port = int(input())

    self.sock.setsockopt(s.SOL_SOCKET, s.SO_REUSEADDR, 1)
    self.sock.setsockopt(s.SOL_SOCKET, s.SO_BROADCAST, 1)
    self.sock.bind((self.host, self.port))
    print('now listening port ', self.port, ' on IP ', self.host)

def listen_sock(self):
    while 1:
        try:
            msg, addr = self.sock.recvfrom(256)
            msg = str(msg)[2:len(str(msg)) - 1]
            print(msg, 'from :', addr)
        except KeyboardInterrupt:
            print('input was interrupted by user')
            break
def send_sock(self):
     while 1:
            print('enter text :')
            text = input()
            text = input()
            self.sock.sendto(text.encode('utf-8'),(self.host, self.port))

sck = socket_udp()
sck.init_socket()
threading.Thread(target=sck.listen_sock, daemon=True).start()
sck.send_sock()

Вывод:
enter IP :
0.0.0.0
enter PORT :
11719
now listening port  11719  on IP  0.0.0.0
enter text :
hi
enter text :
hi from : ('127.0.0.1', 11719)
hello world!
enter text :
hello world! from : ('127.0.0.1', 11719)


text:
Q: How to reference own class in scala? class Node(var x: Int, var y: Int, var prev: Node)
{
    def getpath(): String =
    {
        var tempnode = this(prev);
        while(tempnode.prev != null)
        {
            tempnode = tempnode.prev;
        }
        return tempnode
    }
}

This is the code, but it doesn't work, in the method getpath() I want to reference the current node class into a variable and then iterate backwards through the previous nodes, how do I accomplish this in Scala exactly?

A: @jwvh points (all good!) notwithstanding, your code as written seems to be looking for root/head rather than path.
case class Node(x: Int, y: Int, prev: Option[Node]) {
    @tailrec
    def head: Node = prev match {
      case Some(node) => node.head
      case None => this
    }
}

Or if you actually wanted path:
(this is similar to @jwvh's answer, but is tail-recursive, meaning that it gets rewritten as a loop at runtime, which may become important, when the length of your path is huge).
@tailrec
def path(acc: List[Node] = Nil): List[Node] = prev match {
    case Some(node) => node.path(this :: acc)
    case None => this :: acc
}

A: This is Scala. We don't use var. We don't reference null. We don't need semicolons ;, and we don't use return.
case class Node(x: Int, y: Int, prev: Option[Node]) {
  def getpath: String =
    prev.fold(s"($x,$y)")(_.getpath + s" -> ($x,$y)")
}


text:
Q: How to check if the Mobile Phone has used Google Maps at least once I am currently creating an app that has geolocation feature in it. However, I found out that the geolocation using google maps v3 will not work if Google Maps has not been open at least once on the phone. I have tried that and it is true. Is there a way to check if the geolocation in a phone is ready to use? Or if it is not I can just pop an alert that the user needs to use Google Maps to access the feature of Geolocation? Or maybe instead of making the user open Google Maps first is there another workaround on this? Thanks for those who will answer.
:)

A: You should not need to use the Google Maps JavaScript v3 API to use geolocation in a web page. The HTML5 Rocks site has a good introduction on using navigator.geolocation here: http://www.html5rocks.com/en/tutorials/geolocation/trip_meter/
Of note, there are some details on error handling that may be useful in troubleshooting your problem.
window.onload = function() {
   var startPos;
   navigator.geolocation.getCurrentPosition(function(position) {
      // same as above
   }, function(error) {
      alert('Error occurred. Error code: ' + error.code);
      // error.code can be:
      //   0: unknown error
      //   1: permission denied
      //   2: position unavailable (error response from locaton provider)
      //   3: timed out
   });
 };


text:
Q: Easiest way to center multiple objects in PowerPoint Say that in PowerPoint, I have three rectangular shapes of the same size arranged horizontally next to each other and I want to center them on a slide as a group. If I select all three of them and press the Align > Center button, it will align them one by one - each one of them comes to the center so in the end, they will be overlapping each other and only one of them will be visible. What I want is to keep their distribution (gaps between them) and align the group as a whole.
What I currently need to do is:

*

*Select those three objects

*Group them

*Invoke Align > Center

*Ungroup them

Is it possible to somehow avoid the annoying steps two and four? This is a very frequent operation in my case and the default behavior just doesn't do what I want to do 99% of the time. Maybe some settings or a clever macro?
BTW this is PowerPoint 2013 if it makes any difference.

A: You can also use vertical lines on the sides of the slide.  When you want to center the three rectangles.

*

*Highlight all three rectangles and the vertical lines

*Select Distribute Horizontally

*When the slide design is complete, delete the vertical lines.

It's more work if you only do this once, but with multiple objects it will save you time.  You can copy and paste the vertical lines to each slide to save you time as well.

A: You can do this with a macro:
Sub Test()
    Dim shpGroup As ShapeRange
    Set shpGroup = ActiveWindow.Selection.ShapeRange
    shpGroup.Group
    shpGroup.Align msoAlignCenters, msoTrue
    shpGroup.Ungroup
End Sub

Select the shapes you want to do this for, hit F8, and run this macro.
shpGroup.Group groups the object, shpGroup.Align msoAlignCenters, msoTrue aligns the group to the center of the slide, and shpGroup.Ungroup ungroups the selected objects afterwards.
Note: There is absolutely no error handling, so you will run in to all sorts of fun errors if you select nothing, or just one shape, etc. Feel free to add in error handling if needed


text:
Q: What is the difference between these two pieces of code? int[] div = new int[] {2,3,5};
IEnumerable<int> seq = new int[] {10,15,20,25,30};
int x;
for (int i=0; i<div.Length; i++){
  x = div[i];
  seq = seq.Where( s=> s%x ==0);
}
seq = seq.ToList();

AND
int[] div = new int[] {2,3,5};
IEnumerable<int> seq = new int[] {10,15,20,25,30};
for (int i=0; i<div.Length; i++){
  int y = div[i];
  seq = seq.Where( s=> s%y ==0);
}
seq = seq.ToList();

The first seq's final value is 10,15,20,25,30 and the second one's is 30.
I'm a little confused about the difference between int x;
and  int y = div[i]; . Can someone explain this to me?
Thanks!

A: Invoking seq = seq.Where( s=> s%x ==0); does not iterate over elements. It only creates an IEnumarable encapsulating the iteration, that can be iterated in fututre.
So if you declare your x variable before the loop, the lambda, that you passed in Where() uses the same variable. Since you are changing its value in a loop, eventually only the last one will be actually used.
Instead of expression like:
seq.Where( s=> s % 2 == 0).Where( s=> s % 3 == 0).Where( s=> s % 5 == 0);

you get:
seq.Where( s=> s % 5 == 0).Where( s=> s % 5 == 0).Where( s=> s % 5 == 0);

A: The result is different because you are using lambda expression in the LINQ's Where() parameter. The actual execution of the all lambdas in Where()'s is performed on the very last row of both examples - the line where you perform .ToList(). Have a look at the Variable Scope in Lambda Expressions
The difference in the examples is how you initialize x/y.
In the first example there is only one memory slot for the variable x regardless of number of iterations of the foreach. The x always points to the same spot in the memory. Therefore there is only one value of the x on the last row and it is equal to the div[2].
In the second example there is separate memory slot created for y in each iteration of the loop. As the program evaluates, the address where y points to is changed in every iteration of the foreach. You might imagine it as there are multiple y variables like y_1, y_2,... Hence when evaluating the actual lambdas in Where()s the value of the y is different in every one of them.


text:
Q: Reading and storing data from a TCP buffer in C I am reading some HTTP POST data from an HTTP wrapped TCP socket. My apparatus works but there is a strange syndrome. Basically I know what the content length is (via HTTP header Content-length) but I more often than not seem to build up a buffer that is 2-3 bytes longer than expected. I know that I am not setting my buffer size on initialization but when I do I get a lot of compile errors. The following code almost works but often produces more data in the buffer than there should be.
long bytesRead;
unsigned long bytesRemaining;
sbyte *pBuffer;
sbyte *pTmpBuffer;

pBuffer = malloc(contentLength);
memset(pBuffer, 0, contentLength);

pTmpBuffer = pBuffer;
bytesRemaining = contentLength;
while(bytesRemaining > 0){
   if(maxBuffSize < bytesRemaining){
      chunkSize = maxBuffSize;
   }
   else {
      chunkSize = bytesRemaining;
   }

   bytesRead = tcpBlockReader(pHttpData, pTempBuff, chunkSize);
   bytesRemaining -= bytesRead;
   pTempBuff += bytesRead;
}

printf("Data is %s\n", pBuffer);
printf("Length is %d\n", strlen(pBuffer));

Now sometimes it will be perfect, ie
Data is expected+data
Length is 13
And sometimes it will be
Data is expected+data+(weird characters)
Length is 15
So the problem here I think is I don't set a size for the buffer (ie pBuffer[contentLength]). When I do this though I get errors of incompatible types and what not. I am not a well versed C programmer (usually stick to chars and ints). What can I do to ensure that the buffer is not full of extra garbage at the end?

A: I was missing the elusive NULL terminator.
pBuffer = malloc(contentLength + 1)
...
pBuffer[contentLength] = '\0';


text:
Q: Как запросить ссылку на видеофайл в flashplayer'е? Есть видео на сайте внутри флешплеера. Можно ли на пайтон или вручную в хром получить ссылку к этому видеофайлу, чтобы скачать его?

A: Добрый день, ну некоторые ссылки можно увидеть используя средства разработчика Google Chrome, например:
https://i.stack.imgur.com/RQ9CL.png
А далее с помощью любой подходящей библиотеки Python забрать видео по прямой ссылке(например, urllib2).

A: В общем, проблема разрешилась с помощью сервиса ShowMyCode, который был недоступен некоторое время.
Я поковырялся в коде и нашёл там несколько ссылок с указанием какая ссылка за какое качество отвечает.
Среди них были ссылки на всякие манифесты, были массивы из ссылок на сторонние ресурсы (судя по всему, рандомная реклама) и т.д.
Далее я просто воспользовался своим скриптом для скачивания файлов
Но можно и просто вручную открывать ссылку в браузере и нажимать на ПКМ->сохранить как.


text:
Q: In vscode using Python, ctrl+F5 always asks for "select environment" I installed VSCode, downloaded official Python 3.6.4.
VSCode detected and set the environment right - I do see "python.pythonPath" user setting set correctly.
But, when using VS Code using Ctrl+F5to run a Python file, I am always getting asked for "select environment" and it shows me two options
 - Python
 - Python Experimental
What is this "Python Experimental"? How can I get rid of getting interrupted every time I try to run a script?

A: Run > Add Configuration... => Choose one of the two options.
After doing this it will no longer prompt you.

A: Ctrl+F5 is a shortcut to Start without Debugging What you want is just running a file according to your post. To run a python file in the integrated terminal, right-click your editor window and Run Python File in Terminal. It should open up a terminal window within VS Code and run as normal. It also takes into account the environment you are currently using whenever you run it.
To answer your other question about Python Experimental, it is an option to use the experimental debugger, an alternate version of a Python Debugger. You can read the instructions here


text:
Q: Android with fragments, duplicated elements I am building an Android Application (minimum SDK Level 10). When the app is minimized and the user return later to it, the main menu shows buttons and images twice. It only happens when the user uses other apps in the middle, if it happens immediately then the menu is displayed correctly.
Here is the code of the fragment:
public class MainMenuFragment extends Fragment implements OnClickListener {
String mGreeting = "Hello, anonymous user (not signed in)";

public interface Listener {
    public void onStartGameRequested(boolean hardMode);
    public void onShowAchievementsRequested();
    public void onShowLeaderboardsRequested();
    public void onSignInButtonClicked();
    public void onSignOutButtonClicked();
    public void onPlayClicked();
    public void onScoreClicked();
    public void onFeedbackClicked();
}

Listener mListener = null;
boolean mShowSignIn = true;

View v;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    if(v==null){
        v = inflater.inflate(R.layout.fragment_mainmenu, container, false);
        final int[] CLICKABLES = new int[] {
                R.id.show_leaderboards_button,
                R.id.sign_in_button, R.id.sign_out_button, R.id.button_play, R.id.feedback
        };
        for (int i : CLICKABLES) {
            v.findViewById(i).setOnClickListener(this);
        }
    }
    else {
            ((ViewGroup)v.getParent()).removeView(v);
        }
    return v;
}

public void setListener(Listener l) {
    mListener = l;
}

@Override
public void onStart() {
    super.onStart();
    //updateUi();
}

@Override
public void onResume() {
    super.onResume();
    updateUi();
}

@Override
public void onStop() {
    super.onStop();
}

public void setGreeting(String greeting) {
    mGreeting = greeting;
   //updateUi();
}

void updateUi() {
    try{
        if (getActivity() == null) return;

    getActivity().findViewById(R.id.sign_in_button).setVisibility(mShowSignIn ?
            View.VISIBLE : View.GONE);
    getActivity().findViewById(R.id.sign_out_button).setVisibility(mShowSignIn ?
            View.GONE : View.VISIBLE);
    }catch(Exception e){}
}

@Override
public void onClick(View view) {
    switch (view.getId()) {
    case R.id.show_leaderboards_button:
        mListener.onShowLeaderboardsRequested();
        break;
    case R.id.sign_in_button:
        mListener.onSignInButtonClicked();
        break;
    case R.id.sign_out_button:
        mListener.onSignOutButtonClicked();
        break;
    case R.id.feedback:
        mListener.onFeedbackClicked();
        break;
    case R.id.button_play:
        mListener.onPlayClicked();
        break;
    }
}

public void setShowSignInButton(boolean showSignIn) {
    mShowSignIn = showSignIn;
    updateUi();
}
}

Thank you in advance for any help. I cannot see what is called twice, and I have spent more hours than I would to admit.
EDIT 1: Trying Clint Deygoo solution. Defining View v inside the onCreate is not working neither. This is how I did it:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

      View v = inflater.inflate(R.layout.fragment_mainmenu, container, false);
        final int[] CLICKABLES = new int[] {
                R.id.show_leaderboards_button,
                R.id.sign_in_button, R.id.sign_out_button, R.id.button_play, R.id.feedback
        };
        for (int i : CLICKABLES) {
            v.findViewById(i).setOnClickListener(this);
        }
      return v;
}

EDIT 2: SOLVED ISSUE. I removed updateUi() and it stopped happening. I am not sure about why it's working, but it is. Thank you all!

A: The problem is not in your onCreateView (You should use EDIT 1). It's about nested Fragments.
Raneez Ahmed posted a good answer here
Fragments within Fragments


text:
Q: TeamCity Cannot ping server exception Here is the summary of my setup;

*

*I have a TeamCity server installed on a windows machine it's on the node 192.168.10.20

*There is another VM on the node 192.168.8.235 that has a TeamCity agent on it. it should connect to the team city server.

*They're both connected to the same VPN network, meaning that both are on the same network and are accessible. There is no firewall!

And now I'm getting this weird error. I have no clue what could possibly have gone wrong.

[2015-02-06 13:06:52,749]   WARN - buildServer.AGENT.registration - Call http://192.168.10.20:8087/RPC2 buildServer.registerAgent3: org.apache.xmlrpc.XmlRpcException: jetbrains.buildServer.CannotPingAgentException: Unable to ping agent Mac Build Server. Check firewall and/or try to specify 'ownAddress' in the agent configuration. Details: Agent 'Mac Build Server' cannot be accessed by any of the addresses: [192.168.8.235], (port 9090)
[2015-02-06 13:06:52,750]   WARN - buildServer.AGENT.registration - Connection to TeamCity server is probably lost. Will be trying to restore it. Take a look at logs/teamcity-agent.log for details (unless you're using custom logging).

Also I have another question here, does this mean that central build server can't connect to this agent? Where is this exception getting thrown? On the agent machine or on the team city server? I can't imagine not being able to ping yourself.


text:
Q: Python- advancing output to new line with for loop I need to have the saying "It's all done." advance to the next line. I've tried everything I can think of and find in my book but the line is continued on the line of integers. This is my coding so far and everything works but I can't figure out how to advance the saying to the next line. Thanks for your help!
for x in range(100,-1,-10) :
    print(x, end=' ')

print('It\'s all done.')

A: Like this?
for x in range(100,-1,-10) :
    print(x, end=' ')

print('\nIt\'s all done.')


text:
Q: Steps to enable the print screen key using edit registry in window 10 I have disabled the PrintScreen using the link
disable the printscreen keyboard option from windows

A: Assuming nothing else has been changed it should be pretty simple:
Navigate to:
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Keyboard Layout
In the right pane, right-click and delete Scancode Map (so we just remove the thing you added).
Then close and restart.


text:
Q: apache or nginx or lighttpd for group message and chat service i have to host an application where a user posts a lot of text messages, pics ,audio and video files .
Consider it very similar to the fb message service
so we are confused over continuing to use apache or use other options like nginx ,lighttpd
so how to decide and choose one over another and why.
Please help out with your answers

A: You can use nginx as reverse proxy with apache. where nginx will handle static files, and apache handle dynamic files.

A: Your question touches the surface of different webserver architectures, forking versus threading. There's this older article from Philip Greenspun about AOLServer which is nice to read and a more theoretically complete background article that is linked to from the nginx wiki.
While servers like nginx are handy in situations where you have to answer lots of lots of (also very short/small) simultaneous requests and the servers don't waste a lot of memory, things change when it comes to the kind of application you build.
Is it a very big and complex application that runs fine with PHP? You can proxy it and benefit from letting nginx crank out the static files. So Apache and the PHP module do only PHP work and nothing else.  Or do you have long running fast cgi processes that run on their own? Then a pure apache setup (with a lightweight compiled apache with only the needed modules) could also be completely sufficient in your case.
If you do split setups with a frontend server proxy it's sometimes not easy how to develop progress bars for visualizing uploads, btw. Some servers eat the complete upload and put it to the backend in one piece.
But, I can tell that nginx is a good choice as it handles lots of parallel (keepalive) connections very well with little memory, even https connections.


text:
Q: Two PLSQL statements with begin and end, run fine separately but not together? Just wondering if anyone can help with this, I have two PLSQL statements for altering tables (adding extra fields) and they are as follows:
-- Make GC_NAB field for Next Action By Dropdown

begin
if 'VARCHAR2' = 'NUMBER' and length('VARCHAR2')>0 and length('')>0 then
  execute immediate 'alter table "SERVICEMAIL6"."ETD_GUESTCARE" add(GC_NAB VARCHAR2(10, ))';
elsif ('VARCHAR2' = 'NUMBER' and length('VARCHAR2')>0 and length('')=0) or
  'VARCHAR2' = 'VARCHAR2' then
  execute immediate 'alter table "SERVICEMAIL6"."ETD_GUESTCARE" add(GC_NAB VARCHAR2(10))';
else
  execute immediate 'alter table "SERVICEMAIL6"."ETD_GUESTCARE" add(GC_NAB VARCHAR2)';
end if;
commit;
end;

-- Make GC_NABID field for Next Action By Dropdown

begin
if 'NUMBER' = 'NUMBER' and length('NUMBER')>0 and length('')>0 then
  execute immediate 'alter table "SERVICEMAIL6"."ETD_GUESTCARE" add(GC_NABID NUMBER(, ))';
elsif ('NUMBER' = 'NUMBER' and length('NUMBER')>0 and length('')=0) or
  'NUMBER' = 'VARCHAR2' then
  execute immediate 'alter table "SERVICEMAIL6"."ETD_GUESTCARE" add(GC_NABID NUMBER())';
else
  execute immediate 'alter table "SERVICEMAIL6"."ETD_GUESTCARE" add(GC_NABID NUMBER)';
end if;
commit;
end;

When I run these two queries separately, there are no problems. However, when run together as shown above, Oracle gives me an error when it starts the second statement:
Error report:
ORA-06550: line 15, column 1:
PLS-00103: Encountered the symbol "BEGIN"
06550. 00000 -  "line %s, column %s:\n%s"
*Cause:    Usually a PL/SQL compilation error.
*Action:

I'm assuming that this means the first statement is not terminated properly... is there anything I should put in between the statements to make it work properly?

A: Oracle can take one SQL statement or PL/SQL anonymous block at a time. (Unlike SQL Server that can except a batch at a time.) So, you have a couple of options.

*

*Wrap the two anonymous blocks within another anonymous block:
begin
  -- Make GC_NAB field for Next Action By Dropdown
  begin
  if 'VARCHAR2' = 'NUMBER' and length('VARCHAR2')>0 and length('')>0 then
    execute immediate 'alter table "SERVICEMAIL6"."ETD_GUESTCARE" add(GC_NAB VARCHAR2(10, ))';
  elsif ('VARCHAR2' = 'NUMBER' and length('VARCHAR2')>0 and length('')=0) or
    'VARCHAR2' = 'VARCHAR2' then
    execute immediate 'alter table "SERVICEMAIL6"."ETD_GUESTCARE" add(GC_NAB VARCHAR2(10))';
  else
    execute immediate 'alter table "SERVICEMAIL6"."ETD_GUESTCARE" add(GC_NAB VARCHAR2)';
  end if;
  commit;
  end;
  -- Make GC_NABID field for Next Action By Dropdown
  begin
  if 'NUMBER' = 'NUMBER' and length('NUMBER')>0 and length('')>0 then
    execute immediate 'alter table "SERVICEMAIL6"."ETD_GUESTCARE" add(GC_NABID NUMBER(, ))';
  elsif ('NUMBER' = 'NUMBER' and length('NUMBER')>0 and length('')=0) or
    'NUMBER' = 'VARCHAR2' then
    execute immediate 'alter table "SERVICEMAIL6"."ETD_GUESTCARE" add(GC_NABID NUMBER())';
  else
    execute immediate 'alter table "SERVICEMAIL6"."ETD_GUESTCARE" add(GC_NABID NUMBER)';
  end if;
  commit;
  end;
end;

*Tell the tool you are using to submit the PL/SQL to Oracle to send the two block seperately. How to do this will be tool specific. In SQL*PLUS, a / on a line by itself will accomplish this:
  -- Make GC_NAB field for Next Action By Dropdown
  begin
  if 'VARCHAR2' = 'NUMBER' and length('VARCHAR2')>0 and length('')>0 then
    execute immediate 'alter table "SERVICEMAIL6"."ETD_GUESTCARE" add(GC_NAB VARCHAR2(10, ))';
  elsif ('VARCHAR2' = 'NUMBER' and length('VARCHAR2')>0 and length('')=0) or
    'VARCHAR2' = 'VARCHAR2' then
    execute immediate 'alter table "SERVICEMAIL6"."ETD_GUESTCARE" add(GC_NAB VARCHAR2(10))';
  else
    execute immediate 'alter table "SERVICEMAIL6"."ETD_GUESTCARE" add(GC_NAB VARCHAR2)';
  end if;
  commit;
  end;
  /
  -- Make GC_NABID field for Next Action By Dropdown
  begin
  if 'NUMBER' = 'NUMBER' and length('NUMBER')>0 and length('')>0 then
    execute immediate 'alter table "SERVICEMAIL6"."ETD_GUESTCARE" add(GC_NABID NUMBER(, ))';
  elsif ('NUMBER' = 'NUMBER' and length('NUMBER')>0 and length('')=0) or
    'NUMBER' = 'VARCHAR2' then
    execute immediate 'alter table "SERVICEMAIL6"."ETD_GUESTCARE" add(GC_NABID NUMBER())';
  else
    execute immediate 'alter table "SERVICEMAIL6"."ETD_GUESTCARE" add(GC_NABID NUMBER)';
  end if;
  commit;
  end;
  /

A: Yes, you need a slash / on the line after each end;.

A: one can achieve in two ways
1) run the two blocks separately in pl/sql file.
2) in main block you can run two sbu-blocks in this way :
begin  // main block
      begin
       .....   [pl/sql commands]
       ......
      end
      begin
      .......  [pl/sql commands]
      .......
      end
end // main ends


text:
Q: How to apply conditions to vlookup values from another file where there are multiple values between two dates? I have a list of employees id, their employment start date, their employment end date in one file. Another file has their Groups like FT, PT, CS etc with scattered start date and end dates with multiple groups between a specific employee start date and end date.
Dor example -
Employee ID 10 | Employment Start Date 01/01/2011 | Employment  End Date 12/31/2018

Group file consists:
Employee ID 10 | Group Start Date 01/01/2011 | Group End Date 12/31/2015 - Group PT
Employee ID 10 | Group Start Date 01/01/2016 | Group End Date 12/31/2017 - Group FT
Employee ID 10 | Group Start Date 01/01/2018 | Group End Date 12/31/2018 - Group FT

I need to ignore PT and get FT to have this:
Employee ID | Employment Start Date  | Employment  End Date | Group
10            01/01/2011              12/31/2018              FT

How do I get it?
Thanks in advance!

A: Employee ID:
=VALUE(SUBSTITUTE(LEFT(A1,FIND("|",A1,1)-2),"Employee ID ",""))

Group Start Date:
=SUBSTITUTE(MID(A1,FIND("|",A1,1)+2,FIND("|",A1,FIND("|",A1,1)+2)-FIND("|",A1,1)-3),"Group Start Date ","")

Group End Date:
=SUBSTITUTE(MID(A1,FIND("|",A1,FIND("|",A1,1)+2)+2,FIND(" - ",A1,FIND("|",A1,FIND("|",A1,1)+2)+3)-FIND("|",A1,FIND("|",A1,1)+2)-2),"Group End Date ", "")

Group (FT/PT):
=RIGHT(A1,2)

Just use the filter functionality to filter out PT employees.