text:
Q: Is this a reliable countdown timer? I want to create a countdown timer that counts down from 60 minutes until it hits 0. I don't need it to be exactly accurate. Just within like 10-15 seconds. Is time.sleep the correct task for the job?
while(hour + minute != 0):

        if minute == 0:
                minute = 59
                hour = hour - 1
        else:
                minute = minute - 1
        time.sleep(1)

A: No, time.sleep() does not provide reliable times. It can sleep to short if any kind of signal interrupts the sleep, but it can also be longer depending on your system load.
I would recommend you to store the current time when you start the countdown using e.g. time.time() (returns current time as floating point decimal in seconds since epoch):
start_time = time.time()

Then compute the time (also in seconds since epoch of course) when the countdown will be over:
target_time = start_time + (hours * 60 + minutes) * 60 + seconds

Now you can start the while loop which checks whether the current time is lower than the target_time. If that's the case, you can use time.sleep(RESOLUTION) to save CPU time. Your countdown will be as exact as you chose RESOLUTION: the time it's running is always greater or equal to the desired time, but lower than the desired time plus RESOLUTION. I would chose a value between 0.1 and 1 seconds.
Here's the full code:
start_time = time.time()
target_time = start_time + (hours * 60 + minutes) * 60 + seconds

while target_time < time.time():

    # do something, e.g. print the remaining time:
    remaining_time = target_time - time.time()
    print("Countdown: {}h {}min {}s remaining".format(
            remaining_time // 3600, remaining_time // 60, remaining_time % 60))

    # sleep a bit to save CPU resources
    time.sleep(0.5)

The advantage is that even if the system is highly loaded or the things you do inside the while loop take very long, the countdown still stays pretty accurate.

A: I think you're overcomplicating this by making a distinction between minutes and seconds. Use a base unit (seconds), then loop backwards over the total and apply the delay there, eg:
for remaining in range(60 * 60, 0, -1):
    mins, secs = divmod(remaining, 60)
    # Probably do something other than print that should take a
    # trivial amount of time... if it takes 10 seconds then things
    # will start to look weird
    print('{}mins and {}secs remaining'.format(mins, secs))
    time.sleep(1)

A: The simple way is to use divmod. Idea is to reduce the counter after a second using sleep for 1 sec.
def counter(total_seconds):
    for rem in range(total_seconds, 0, -1):
        mins, secs = divmod(rem, 60)
        print('{}mins and {}secs remaining'.format(mins, secs))
        time.sleep(1)


text:
Q: Maximum zoom scale on UIButton images? I'm using a pinch gesture recognizer to handle zooming a button that has an image. I established the image using
[self.button setImage:image forState:UIControlStateNormal];
[self.button setImage:image forState:UIControlStateHighlighted];

In my pinch gesture recognizer handler, I'm scaling the button by altering its frame.size:
self.button.frame = [self makeButtonFrame];

where makeButtonFrame uses the current scale (adjusted by the pinch gesture recognizer handler):
- (CGRect) makeButtonFrame {
    CGRect frame = CGRectMake (STROKE_WIDTH + DISTANCE_FROM_STROKE,
                               STROKE_WIDTH + DISTANCE_FROM_STROKE,
                               self.scale * self.defaultWidth,
                               self.scale * self.defaultHeight);
    return frame;
}

I find that I cannot scale the button image beyond a certain point with this technique. And that scale seems to vary dependent on the specific image (double ugh!). That scale seems to be around 3-4.
Currently I'm conservatively limiting the scale to a factor of 3 in my pinch gesture recognizer.
However, I'd like a more analytic means of determining a maximum scale. Instead of just estimating based on a set of images I've tried.

A: Can't say for certain, but I suspect that this 'limit' is actually your image's size. When you set a button's image (as opposed to backgroundImage), your image will be scaled down if it's larger than the frame. If the image is smaller, then it's simply centered in the frame (the frame still governs what area responds to touches, though). I think what you're seeing is your image scaled down when you place it in the button, and it scales up until it reaches it's original size, at which point it scales no further. There are two solutions to this:
1: Use the backgroundImage instead of the image property:
[self.button setBackgroundImage:image forState:UIControlStateNormal];

The background image always expands to fill the frame, no matter how big it is or how much it distorts the image.
2: Use the transform property to scale. This is done like so:
self.button.transform = CGAffineTransformMakeScale(scaleAmountX, scaleAmountY);

This has the advantage that you don't need to adjust your frame at all - not even for the position offset, as scaling using the transform matrix does so from the center rather than from a corner. It should also respond to touches within it's scaled-up area.

redpajama_set_name: RedPajamaStackExchange


text:
Q: stringByRemovingPercentEncoding resulting in null string I've got a file path /Users/alexandra/Downloads/folder%20with%20spaces/ and I want to remove the percent encoding and make it a file URL. Using the method stringByRemovingPercentEncoding  makes the string null.
The documentation says "A new string with the percent-encoded sequences removed, or nil if the receiver contains an invalid percent-encoding sequence.", but I don't see %20 for a space being wrong?

A: You didn't show us your non-working code in Objective-C, but this works fine on my machine (in Swift):
if let path = "/Users/alexandra/Downloads/folder%20with%20spaces/".removingPercentEncoding {
    let url = URL(fileURLWithPath: path)
    print(url) // file:///Users/alexandra/Downloads/folder%20with%20spaces/
}

On the other hand, since you've already wrongly acquired percent encoding in a string pathname, why not just stick file:// in front of it and be done with it?
let path = "/Users/alexandra/Downloads/folder%20with%20spaces/"
if let url = URL(string: "file://" + path) {
    print(url)
}


text:
Q: Reference default path in powershell script Is there a way to call the system path if the path has been changed in the current terminal? i.e.:
$env:Path = "C:\some new path"
#some coding that requires a different path set up
$env:Path = $defaultPath #would have to define $defaultPath by calling the system default path

A: Use the following to reload the $env:PATH environment variable from the registry, as future sessions would see it (assuming no further relevant registry updates are made).
If your current session hasn't made any relevant registry updates, this is the same as getting the value that was in effect on session startup - barring any dynamic additions via a $PROFILE script:
$env:PATH = [Environment]::GetEnvironmentVariable('Path', 'Machine'),
            [Environment]::GetEnvironmentVariable('Path', 'User') -join ';'

Note:

*

*A process' effective $env:PATH value is a composite value of a machine-level and a user-level registry entry, with the machine-level definition taking precedence, as reflected in the two .NET API calls above.

*

*Note that the underlying registry locations - HKEY_LOCAL_MACHIN\System\CurrentControlSet\Control\Session Manager\Environment and HKEY_CURRENT_USER\Environment - are REG_EXPAND_SZ registry values, i.e. they may be defined in terms of other environment variables, such as %SystemRoot% and %ProgramFiles%.

*Both the .NET API calls above - using [Environment]::GetEnvironmentVariable() - and PowerShell's Get-ItemProperty and Get-ItemPropertyValue cmdlets expand (interpolate) such references and return verbatim paths - which is what new processes see by default too.

*Given the above, the only way to robustly retrieve the value that was in effect at session startup time is to save it in a variable at startup time.

A: It's still stored in the registry so you can just query it:

*

*Located: HKLM:\System\CurrentControlSet\Control\Session Manager\Environment
$key = "HKCU:\Environment",
       "HKLM:\System\CurrentControlSet\Control\Session Manager\Environment"

(Get-ItemPropertyValue -Path $key -Name Path) -Join ';'

Querying the key using Get-ItemPropertyValue (as suggested by Mklement) will give you just the property's value.


text:
Q: A question on pseudocompact space The exercise is from the handbook of set-theoretic topology page 161: Assume
$\mathfrak b=\mathfrak c$.
Construct a first countable separable zero-dimensional locally compact pseudocompact space which is not countably compact but which has no uncountable closed discrete subset.
The hint is given: Fisrst construct a space first countable zero-dimensional locally compact space $X$ with underlying set $\mathfrak c$ such that $D=\{\xi: \omega\le \xi < \omega+\omega\}$ is a closed discrete set of cluster points of $\omega$ and such that each countably infinite subset of $X\setminus D$ has a cluster point.
Could anybody help me?
Added: $\mathfrak b$ is the bounding number:
$$\mathfrak b=\min\left\{|F|:F\subseteq{}^\omega\omega\text{ and }\forall f\in{}^\omega\omega\,\exists g\in F\left(g\not\le^* f\right)\right\}\;,$$
where $f\le^*g$ iff there is an $n\in\omega$ such that $f(k)\le g(k)$ for all $k\ge n$. That is, $\mathfrak b$ is the smallest cardinality of an unbounded set in the partial order $\left\langle{}^\omega\omega,\le^*\right\rangle$.


text:
Q: Integration and Measure problem from Shilov and Gurevich Book.(zero measure definition using step functions)) The problem reads:
Let F be the closed interval obtained by removing a countable collection of disjoint open intervals from a closed interval [a,b], where the sum of the lengths of such intervals is b-a. Show that F is of measure zero
Hint: F is covered by the finite collection of intervals obtained by removing a finite number of thos e disjoint intervals from [a,b].
So far, the book has only introduced the notion of Size in R(b-a for any interval [a,b] closed or open) and the definition of Zero Measure set both the classical way(always finding a covering s.t. that covering has size as small has we want) and the equivalent using step function integrals.
A set Z has measure zero in B if for any ε>0 we can find a nondecreasing sequence of step functions with integral(in B) each <ε and for all x in Z exists some order p s.t. n>p implies that h_n(x)>=1(step function).
I can´t seem to find any way to start cracking at this, and i have the feeling it´s pretty obvious.
Any hint would be highly appreciated!


text:
Q: Qt Qml like vars in js This is just a general question.
I have seen a few implementations of code kind of like this but not quite.
So in qt creator if I define two properties like so
property int othervar: 3;
property int val: 1 + othervar;

then the property 'val' will re-evaluate its self when 'othervar' gets changed in any way.
If I was to re-write something like this to work in js how might I go about this?

A: If you want to do so in a QtQuick context, you have basically two ways to handle it. Binding are nicely explained on Qt bindings documentation page.

*

*With a property "changed" signal handler
Item {
    property int othervar: 3

    onOthervarChanged: {
        // Update val
        jsObject.val = 1 + othervar;
    }
}

*By creating a binding from Javascript on an existing property
Item {
    property int othervar: 3
    property int val: 0

    Component.onCompleted: {
        // Create a binding dynamically
        val = Qt.binding(function() { return 1 + othervar })
    }
}

It is important to note that when assiging to a property that previously had a binding, for example by doing val = 3, the existing binding is removed, and the value will no more be updated automatically.

A: Notifications and bindings work only for QML properties, there is no such functionality readily available in JS. You can emulate it, but it will take some extra syntax. It will not be elegant and convenient.
While it is possible to implement signals, and incorporate them by using setter functions instead of the = operator, the actual binding expressions will be tricky. This happens automatically in QML, if you'd do it manually, you'd have to manually connect the notify signal of every value used in the particular expression to a function that reevaluates it. It would be fairly easy for trivial expression like in the question, but for anything complex it is just not applicable.
So in short:

If I was to re-write something like this to work in js how might I go
  about this?

You mightn't! It requires support at "language" level. Such things are not even available in Qt from C++, they are facilitated by QML.


text:
Q: MenuItem.setIcon() method doesn't work I've tried already all possible solutions. Here's my code:
private Menu mMenu;

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(R.menu.fragment_article_detail_menu, menu);
    mMenu = menu;
}

void changeStar(boolean added) {
    if (mMenu != null) {
        MenuItem item = mMenu.findItem(R.id.favourites_item);
        if (added) {
            Log.d(LOG_TAG, "Set full icon");
            item.setIcon(getResources().getDrawable(R.drawable.star_full));
        } else {
            Log.d(LOG_TAG, "Set empty icon");
            item.setIcon(getResources().getDrawable(R.drawable.star_empty));
        }
    }
}

Here is my menu xml file:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context="ssidit.pp.ua.payspacereader.ArticleDetailActivity">
    <item
        android:id="@+id/refresh_item"
        android:title="@string/refresh"
        app:showAsAction="never"></item>

    <item
        android:id="@+id/favourites_item"
        android:icon="@drawable/star_empty"
        android:title="@string/add_to_favourite"
        app:showAsAction="ifRoom"></item>

    <item
        android:id="@+id/share_item"
        android:icon="@drawable/ic_share"
        android:title="@string/share"
        app:actionProviderClass="android.support.v7.widget.ShareActionProvider"
        app:showAsAction="ifRoom"></item>
</menu>

invalidateMenu() method doesn't help. When I call setIcon method, nothing changes on my android device.
Here is my code:
private boolean isFavourite;

 private void setValues(Cursor cursor) {

    Log.d(LOG_TAG, "Setting values");

    setData(titleTextView, CursorUtility.getTitle(cursor));
    setData(dateTextView, CursorUtility.getDateText(cursor));
    setData(timeTextView, CursorUtility.getTimeText(cursor));
    isFavourite = CursorUtility.isFavourite(cursor);
    getActivity().invalidateOptionsMenu();
}

@Override
public void onPrepareOptionsMenu(Menu menu) {
    super.onPrepareOptionsMenu(menu);
    Log.d(LOG_TAG, "OnPrepareOptionsMenu");
    MenuItem item = menu.findItem(R.id.favourites_item);
    if (isFavourite) {
        Log.d(LOG_TAG, "Set full icon");
        item.setIcon(R.drawable.star_full);
    } else {
        Log.d(LOG_TAG, "Set empty icon");
        item.setIcon(R.drawable.star_empty);
    }
}

As you can see, everything is logged. So there can't be mistake if some method doesn't call. Also I checked item by getting title of it. It is right item. Just some kind of black magic.

A: Try using invalidateOptionsMenu and move your changeStar logic to onPrepareOptionsMenu. From Android documentation:
public boolean onPrepareOptionsMenu (Menu menu)

Added in API level 1
  Prepare the Screen's standard options menu to be displayed. This is called right before the menu is shown, every time it is shown. You can use this method to efficiently enable/disable items or otherwise dynamically modify the contents.
The default implementation updates the system menu items based on the activity's state. Deriving classes should always call through to the base class implementation.

A: Firstly: make a global variable of menu
Secondly: wherever in activity you want to change the icon just get that menu item by global variable menu using getItem() method instead of findItem.
Thirdly: set the icon to your menuItem returned by getItem() as follow menuItem.setIcon(res)


text:
Q: my socket on connect and disconnect functions arent working (js and html/css) this is my code; why doesn't it send the message on connect/disconnect? when the user leaves or enters the chatroom, it is supposed to send user joined the chatroom or user left the chatroom
back end
io.on('connection', socket => {
    console.log(socket.id, "connected");
    socket.on("chat", (chat) => {
        io.sockets.emit("chat", chat);
    //msg.push([{ name: "x", key: "val" }]);
    //await db.set('messages', msg);
  });
    socket.on("connect", () => {

      var u = socket.username;
      socket.emit('joinedUser', u);
      const users = db.get('onlineUsers');
      users.push(socket.username);
      db.set('onlineUsers', users);
});
    socket.on("disconnect", () => {

      var u = socket.username;

      socket.emit('leftUser', u);
      const users = db.get('onlineUsers');
      const index = users.toString().indexOf(socket.username);
      if (index > -1) {
        users.splice(index, 1); // 2nd parameter means remove one item only
      }
});
});

front end
socket.on('joinedUser', (user) => {
var div = document.getElementById('messages-container')
div.innerHTML += `

Server

${user.username} joined the chatroom

`;
  div.scrollTop = div.scrollHeight;
});

socket.on("leftUser", (user) => {
  var div = document.getElementById('messages-container')
    div.innerHTML += `

Server

${user.username} left the chatroom

`;
div.scrollTop = div.scrollHeight;
});


text:
Q: block ads from url loaded in WKWebView I am loading url in webView and now I want to block ads from url in webView. How can I achieve this?
[_webVw loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:page_url]]];

A: You need to use the webView:shouldStartLoadWithRequest:navigationType: method from UIWebViewDelegate and do your validation with black list of URL to block. If you want an inspiration or similar process you can see this library Ad Blocker iOS
--- EDIT ---
This is my code to Ads Blocking WKWebView from NSString.
//
//  ViewController.m
//  WKWebView
//
//  Created by Carlos Landaverde on 6/21/18.
//

#import "ViewController.h"

#define NSStringMultiline(...) [[NSString alloc] initWithCString:#__VA_ARGS__ encoding:NSUTF8StringEncoding]

static NSString *rexKey1 = @"rexKey1";

@interface ViewController () <WKNavigationDelegate, WKUIDelegate>
@property (nonatomic) WKWebView *webView;
@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self.view setBackgroundColor: [UIColor whiteColor]];

    dispatch_group_t dispatchGroup = dispatch_group_create();
    __weak typeof(self) weakSelf = self;

    [NSUserDefaults.standardUserDefaults registerDefaults: @{ rexKey1: @NO }];
    [NSUserDefaults.standardUserDefaults synchronize];

    _webView = [[WKWebView alloc] initWithFrame: self.view.bounds];
    [_webView setNavigationDelegate: self];
    [_webView setUIDelegate: self];
    [_webView setAllowsBackForwardNavigationGestures: YES];
    [self.view addSubview: _webView];

    // If you want to remove previous WKContentRuleList
    // [_webView.configuration.userContentController removeAllContentRuleLists];

    dispatch_group_enter(dispatchGroup);
    [self setupContentBlockFromStringLiteral: ^{
        dispatch_group_leave(dispatchGroup);
    }];

    dispatch_group_notify(dispatchGroup, dispatch_get_main_queue(), ^{
        [weakSelf beginLoading];
    });
}

- (void)beginLoading
{
    NSURLRequest *urlReq = [[NSURLRequest alloc] initWithURL: [NSURL URLWithString: @"https://www.google.com"]];
    [_webView loadRequest: urlReq];
}

- (void)setupContentBlockFromStringLiteral: (void (^)(void))callback
{
    /*
     Or you can block from a JSON file
     */
    NSString *jsonStr = NSStringMultiline([{
        "trigger": {
            "url-filter": "://googleads\\\\.g\\\\.doubleclick\\\\.net.*"
        },
        "action": {
            "type": "block"
        }
    }]);

    if ([[NSUserDefaults.standardUserDefaults objectForKey: rexKey1] boolValue]) {
        [WKContentRuleListStore.defaultStore compileContentRuleListForIdentifier: rexKey1 encodedContentRuleList: jsonStr completionHandler: ^(WKContentRuleList *contentRuleList, NSError *err) {

            if (err != nil) {
                NSLog(@"Error on content rule list compiled");
                [NSUserDefaults.standardUserDefaults setObject: @NO forKey: rexKey1];
                return;
            }

            if (contentRuleList) {
                [_webView.configuration.userContentController addContentRuleList: contentRuleList];
                callback();
            }
        }];
    }
    else {
        [WKContentRuleListStore.defaultStore compileContentRuleListForIdentifier: rexKey1 encodedContentRuleList: jsonStr completionHandler: ^(WKContentRuleList *contentRuleList, NSError *err) {

            if (err != nil) {
                NSLog(@"Error on content rule list not compiled");
            }

            if (contentRuleList) {
                [_webView.configuration.userContentController addContentRuleList: contentRuleList];
                [NSUserDefaults.standardUserDefaults setObject: @YES forKey: rexKey1];
                callback();
            }
        }];
    }
}

@end

A: Assuming you don't mind ads being served to iOS 10 or earlier, then iOS 11 and later include content blocking rules.
Overview
Suppose I have a UIViewController subclass which has a webView property pointing to my WKWebView instance. I implement a custom method called goHome which visits some defined "home" URL. Before I do this, though, I might want to load content blocking rules into my web view. I get things started with something like this:
- ( void ) viewDidLoad
{
    [ super viewDidLoad ];

    // (other setup stuff here...)

    [ self reloadContentBlockingRulesAndGoHome ];
}

The 'reload blocking rules' stuff loads rules if I'm on iOS 11 or later. If you need support for other versions of iOS, see other answers. Forgive the white space layout oddities here, I have a quirky coding style when it comes to Objective C messages that include blocks in the parameters:
- ( void ) reloadContentBlockingRulesAndGoHome
{
    if ( @available( iOS 11, * ) )
    {
        [
            WKContentRuleListStore.defaultStore
                compileContentRuleListForIdentifier: @"ContentBlockingRules"
                             encodedContentRuleList: @"...see below!..."
                                  completionHandler: ^ ( WKContentRuleList * ruleList, NSError * error )
            {
                [ super viewDidLoad ];

                if ( error == nil )
                {
                    [ self.webView.configuration.userContentController addContentRuleList: ruleList ];
                    [ self goHome ];
                }
            }
        ];
    }
    else
    {
        [ self goHome ];
    }
}

That encodedContentRuleList parameter takes a JSON string. I tend to put that in its own method for clarity, so the code above might actually say:
[ WKContentRuleListStore.defaultStore
     compileContentRuleListForIdentifier: @"ContentBlockingRules"
                  encodedContentRuleList: [ self contentBlockingRules ]
                       completionHandler: ^ ( WKContentRuleList * ruleList, NSError * error ) { ... } ];

So what would [ self contentBlockingRules ] do? That just returns an NSString giving the content blocking data. Without integrating with some kind of third party ad block service, all you can do is inspect individual pages of interest and start noticing common class names or IDs of HTML elements that contain adverts, plus notice (from e.g. the Safari Web inspector's "Network" tab) all the domains from which advertising material is pulled. It's an illuminating, if somewhat depressing process, once you realise just how much advertising material is included on a typical web site now.
Rules JSON example
Read this carefully:

*

*https://developer.apple.com/library/archive/documentation/Extensions/Conceptual/ContentBlockingRules/CreatingRules/CreatingRules.html
Here's an example that includes some CSS selector blocking stuff, blocks a particular URL from the server itself (e.g. some custom ad code they might be serving themselves), plus some rules for generalised third party domains you want to block (I use these a lot).
- ( NSString * ) contentBlockingRules
{
    return @" \
    [ \
      { \
        \"trigger\": { \
          \"url-filter\": \".*\" \
        }, \
        \"action\": { \
          \"type\": \"css-display-none\", \
          \"selector\": \".some_css_class, .some_other_class, #some_css_id\" \
        } \
      }, \
      { \
        \"trigger\": { \
          \"url-filter\": \"\\/some\\/very-specific-filename\\\\.js\", \
          \"resource-type\": [ \"script\" ] \
        }, \
        \"url-filter-is-case-sensitive\": true, \
        \"action\": { \
          \"type\": \"block\" \
        } \
      }, \
      { \
        \"trigger\": { \
          \"url-filter\": \".*\", \
          \"if-domain\": [ \"doubleclick.net\", \"adservice.google.com\", \"etc\" ], \
          \"resource-type\": [ \"script\" ] \
        }, \
        \"action\": { \
          \"type\": \"block\" \
        } \
      } \
    ]";
}

It's nasty taking JSON and encoding it into an NSString - as you can see, the result is messy with an awful lot of escaping going on, especially for some of the URL parts which are escaped once for JSON, then escaped again for the NSString literal. There are probably cleaner ways to do this that make maintenance of the JSON data much easier.
Final thoughts
Due to the sheer volume of advertising and tracking code on many sites, the difference in page load speed when you block stuff can be dramatic. It's worth the effort to give your users a better experience and hit their mobile data less, BUT:

*

*You might be breaching terms and conditions of service on sites you visit

*If the sites update their code then you might end up missing some ads you intended to block

*There's a somewhat worse risk that a site update or too-general blocking rule may accidentally hide "legitimate" non-advert page content.

Rather than just copy and paste anything above, please instead carefully read the Apple Developer Documentation on the various techniques and framework methods above, so that you understand limitations, error handling requirements and so-forth. The above examples are just to get you started on the concepts, but it's important to write real code from a position of fully understanding the things you are doing - your app users deserve a stable experience :-)


text:
Q: Confusion about for loop, sequence with decimals I formulate my question by the following simple code. The elements of vector a were initially assigned to be 0, and we use a for loop to reassign values. All the elements of a are supposed to be 1. However, the 7-th element is unchanged. Can anyone explain why this happens in R.
> (s = seq(0.01,.1,0.01))
 [1] 0.01 0.02 0.03 0.04 0.05 0.06 0.07 0.08 0.09 0.10
> (a = rep(0,length(s)))
 [1] 0 0 0 0 0 0 0 0 0 0
> for (i in s)  a[i*100] = 1
> a
 [1] 1 1 1 1 1 1 0 1 1 1

A: Some sort of floating point rounding magic.
See:
as.integer(s[7]* 100)
# [1] 6
# as.integer(s * 100)
# [1]  1  2  3  4  5  6  6  8  9 10

So that 7th index is actually 6.
It is safer to loop over integers and index in to s rather than relying on casting floating-point things to integer.
for (i in seq_along(s))
    a[i] = 1 # or possibly something involving s[i] for your application


text:
Q: Android device compatibility with Samsung galaxy S3 after publishing I have an issue on my application after I published it on the play store (Beta test).
I've tested the app-debug and the app-release apks on multiple AVDs and even on my S3 mobile, everything worked fine. Then I load the app-release.apk file for Beta test and my S3 mobile is no more compatible with the app.
Do you have any suggestion? I added several layout and values files but no result.  Here are my manifest file and a capture of the project
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="com.xxxxx">

    <uses-feature android:name="android.hardware.touchscreen" android:required="false"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme">
        <activity
            android:name=".MainActivity1"
            android:label="@string/app_name"
            android:launchMode="singleTask"
            android:logo="@mipmap/ic_launcher"
            android:theme="@style/AppTheme.NoActionBar">

        </activity>

I also tried this but i got the same results
<supports-screens android:resizeable="true"
      android:smallScreens="true"
      android:normalScreens="true"
      android:largeScreens="true"
      android:xlargeScreens="true"
      android:anyDensity="true" />

You can find the project structure here:

Here is the content of the build.gradle
compileSdkVersion 23
    buildToolsVersion "21.1.2"
    defaultConfig {
        applicationId "com."
        minSdkVersion 9
        targetSdkVersion 23
        versionCode 9
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'),     'proguard-rules.pro'
            signingConfig signingConfigs.config
        }
        debug {
            signingConfig signingConfigs.config
        }
    } }

A: "One cannot purchase his own app on Google Play on all his proper devices (devices associated with his developper account."
This is against policies


text:
Q: В каких случая лучше применять Template Method, а в каких Strategy В каких случая лучше применять Template Method, а в каких Strategy?

A: Используйте паттерн стратегия, когда:
    имеется много родственных классов, отличающихся только поведением. Стратегия позволяет сконфигурировать класс, задав одно из возможных поведений;
    вам нужно иметь несколько разных вариантов алгоритма. Например, можно определить два варианта алгоритма, один из которых требует больше времени, а другой - больше памяти.Стратегии разрешается применять, когда варианты алгоритмов реализованы в виде иерархии классов.
    в алгоритме содержаться данные о которых клиент не должен знать. Используйте паттерн стратегия, чтобы не раскрывать сложные, специфичные для алгоритма структуры данных;
    в классе определено много поведений, что представлено разветвленными условными операторами. В этом случае проще перенести код из ветвей в отдельные классы стратегий.
Паттерн шаблонный метод следует использовать:
    чтобы однократно использовать инвариантные части алгоритма, оставляя реализацию изменяющего поведения на усмотрение подклассов;
    когда нужно вычленить и локализовать в одном классе поведение, общее для всех подклассов, дабы избежать дублирования кода;
    для управления расширениями подклассов. Можно определить шаблонный метод так, что он будет вызывать операции-зацепки в определенных точках, разрешив тем самым расширение только в этих точках.
подробнее можете прочитать например здесь https://systems-ez.ru/index.php/ru/patterns/template-method


text:
Q: Finding Tomcat Document Root I'm trying to test a php app I'm working on in my Netbeans environment, but I've been thus far unable to test it on the Tomcat server I have on my machine.
After doing some research on the problem, I found this earlier question which suggests that I need to copy my project files to the document root. The problem is, I can't seem to find the document root for my server.
What's the best way of locating the document root? I don't think I've changed the location from the default, but I can't seem to find it. Thanks in advance.

A: First of all, Tomcat is a Servlet/JSP container but not to be thought as a web server.
Based on your description, I took a wild guess that your project was created or later configured as "Run As: Local Web Site (running on local web server)".
FYI, other Run As methods shown (as of 7.4) below:

You mentioned

I can't seem to find the document root for my server.

so the question from me is: do you have a web server, such as Apache httpd, installed locally!? If not, you can get one here; I'd suggest picking the version identical to the deployment environment or at least close to it.
If local web server is installed and is functioning properly, you must have a working DOCUMENT_ROOT. To locate the path of DOCUMENT_ROOT (demonstrated w/ Apache httpd under Windows™):

*

*Navigate to the installation directory (or folder, if you prefer) and you shall see a sub-directory named "conf".

*In the conf directory look for a file called "httpd.conf" and open it w/ your favorite text editor.

*

*Caveat: Normally there's only one site in the default configuration. Chances are it was installed before and multiple VirtualHost were created; if that's the case, you might need to look under "conf/extra/httpd-vhosts.conf".

*One more caveat: The value of the DOCUMENT_ROOT could be relative, you might need to prepend the installation path in order to use it somewhere else (NetBeans IDE in our case).

*Search for the line that begins w/ "DocumentRoot", and the followed value is what you are looking for.

*Use that value in your project, don't forget to click on "Copy files from Sources Folder to another location" first.

Futhermore, there is a way to make Tomcat to be able to interpret PHP scripts: Quercus from Caucho Technology; although there's a catch - it doesn't support UTF-8 very well (較客氣的說法)!
I understand this is a 6-month old question, I hope the above information is still useful to you.


text:
Q: Binding through UserControl breaks when changing values in UserControl I have the following UserControl and Window, each with a slider which should be bound to the same Property, here defined in the window as a dependency property. When I move the slider in the main window, the slider in the UserControl follows. If I touch the slider in the UserControl, the slider in the main window won't change and the binding breaks, as the slider in the UserControl won't follow the one in the main window anymore. The slider in the main window doesn't loose it's binding. What am I doing wrong?
The Window
public partial class Window1 : Window
{
    public Window1()
    {
        InitializeComponent();
    }

    public static readonly DependencyProperty ValueProperty =
        DependencyProperty.Register("Value", typeof(float), typeof(Window1),
                                    new FrameworkPropertyMetadata());

    public float Value {
        get { return (float)GetValue(ValueProperty); }
        set { SetValue(ValueProperty, value); }
    }
}

<Window
    x:Class="UserControlBindingDemo.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:user="clr-namespace:UserControlBindingDemo"
    Title="UserControlBindingDemo"
    Height="300"
    Width="300"
    x:Name="wndw">
    <Grid>
        <Slider
            Grid.Column="0"
            Grid.Row="0"
            Value="{Binding Path=Value, ElementName=wndw}" />
        <user:UserControl1
            Grid.Column="0"
            Grid.Row="1"
            Value="{Binding Path=Value, ElementName=wndw}" />
    </Grid>
</Window>

The UserControl
public partial class UserControl1 : UserControl
{
    public UserControl1()
    {
        InitializeComponent();
    }

    public static readonly DependencyProperty ValueProperty =
        DependencyProperty.Register("Value", typeof(float), typeof(UserControl1),
                                    new FrameworkPropertyMetadata());

    public float Value {
        get { return (float)GetValue(ValueProperty); }
        set { SetValue(ValueProperty, value); }
    }
}

<UserControl x:Class="UserControlBindingDemo.UserControl1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    x:Name="uc">
    <Grid>
        <Slider
            Value="{Binding Path=Value, ElementName=uc}" />
    </Grid>
</UserControl>

A: The DependencyProperty you have created in the UserControl does not update the source of the binding by default.
So when you change Value via the UserControls slider, the binding will not automatically change Value in the Window.
To fix it you can set the Mode property of the Binding to TwoWay.
This will make sure that changes to the binding-target (Value in UserControl) will update the binding-source (Value in Window)
<user:UserControl1
    Grid.Column="0"
    Grid.Row="1"
    Value="{Binding Path=Value, ElementName=wndw, Mode=TwoWay}" />


text:
Q: MIME Types and url_for in Rails I have a nice RESTful controller in my Rails application that uses responds_to to distinguish between requests for HTML and CSV requests, serving the HTML if one uses the URL normally, and the CSV if one adds ".csv" to the end of the URL.
In my view layer ERB file, I want to have a link to the CSV. I could just get the URL for the appropriate action normally and then just add ".csv" to the end of it, but that seems kinda hacky. I don't, however, see anthing in the url_for docs that would allow me to do this more cleanly.
Is there something I'm missing, or am I just stuck with something like this?
<a href="<%= url_for @topic%>.csv">Download CSV

Thanks for any insight!

A: url_for @topic, :format => :csv

is probably what you are looking for


text:
Q: Ways to integrate spring MVC with Restful web services I am trying to understand Spring MVC Restful architecture. Want to know how many ways are there to integrate spring MVC with Restful web services. I can see one of it is using Rest Template.
Is it the only way to use rest web services in Spring MVC.
Can we develop web application using spring MVC alone without consuming any web services.
Please correct me if am wrong .
Thanks for the help.

A: Spring MVC is a framework and does not always require web services to develop web application.
A web service is a function that can be accessed by other programs over the web (Http or in simple words any piece of software that makes itself available over the internet and uses a standardized messaging system.
So, if you want to communicate with another application which either exposes or consume web service then you will integrate web service in your application.
Rest Template is one of the best ways to work with Restful webservice.


text:
Q: Iterating diagonally through a 2d array I have to iterate through an 2D array of chars. I already have the code to iterate / but I'm lost when it comes to .
Here is my 2d array:
a,v,i,o,n,l
t,o,t,o,l,l
m,a,r,c,o,e
s,a,g,r,c,i
o,e,n,z,o,g
s,t,r,a,r,u

I already have:
a
tv
moi
....

and I need:
l
nl
ole
....

Here is the code to iterate / :
int size = 6;

for (int k = 0 ; k < size ; k++) {
    for (int j = 0 ; j <= k ; j++) {
        int i = k - j;
        System.out.print( lista[i][j] + " " );
    }
    System.out.println();
}

for (int k = size - 2 ; k >= 0 ; k--) {
    for (int j = 0 ; j <= k ; j++) {
        int i = k - j;
        System.out.print(lista[size - j - 1][size - i - 1] + " " );
    }
    System.out.println();
}

A: Try this:
public class Matrix {
    public static void main(String[] args) {
        char[][] arr = {
                { 'a', 'v', 'i', 'o', 'n', 'l' },
                { 't', 'o', 't', 'o', 'l', 'l' },
                { 'm', 'a', 'r', 'c', 'o', 'e' },
                { 's', 'a', 'g', 'r', 'c', 'i' },
                { 'o', 'e', 'n', 'z', 'o', 'g' },
                { 's', 't', 'r', 'a', 'r', 'u' } };
        for (int n = -arr.length; n <= arr.length; n++) {
            for(int i = 0; i < arr.length; i++){
                if((i-n>=0)&&(i-n<arr.length)){
                    System.out.print(arr[i][i-n]);
                }
            }
            System.out.println();
        }
    }
}

A: You can use your own code. The only thing you need to do is transpose your matrix first. I have written and tested it for you. myArray is the array you gave us as input and yourArray is the one you need to use in for your code as lista.
for (int i = 5; i >= 0; i--) {
    for (int j = 0; j <= 5; j++) {
       yourArray[5 - i][j] = myArray[j][i];
    }
}


text:
Q: transform array of strings to array of objects I have an array of strings (strings have an object shape). I would like to convert it to an array of objects.
I tried with JSON.parse but am not successful.
let a=["{Axis:1,Value:-74}", "{Axis:2,Value:7}", "{Axis:3,Value:-47}", "{Axis:4,Value:85}"]

Desired result
a=[{Axis:1,Value:-74}, {Axis:2,Value:7}, {Axis:3,Value:-47}, {Axis:4,Value:85}]

A: There are a couple of issues here.
The first is that you won't be able to call JSON.parse on a because JSON.parse can only parse strings containing properly formatted JSON.
The second issue is that the strings in your array are not properly formatted JSON.
The solution for this would be to make the strings properly formatted JSON, as follows:
let a=['{"Axis":1,"Value":-74}", '{"Axis":2,Value:7}', '{"Axis":3,"Value":-47}', '{"Axis":4,"Value":85}'];

Then to create an array of those objects, you'll have to use Array.map, as follows:
a = a.map(e => JSON.parse(e));

A: You could evaluate the objects, because they are not formatted as JSON standard.

let a = ["{Axis:1,Value:-74}", "{Axis:2,Value:7}", "{Axis:3,Value:-47}", "{Axis:4,Value:85}"],
    result = a.map(s => eval(`(${s})`));

console.log(result);


text:
Q: Doubt on choice of $L_1$ regularization parameter for lasso In this paper, on page $14$, I have some doubts in "How to choose $\lambda$" part. The author says

Let $\beta^{(−i)}_{lasso}$ be the LASSO solution obtained using $(X^{(−i)},y^{(−i)})$.

How can we solve the LASSO even after partitioning the data if we still don't have $\lambda$? What value of $\lambda$ do we use here?

A: The optimal $\lambda$ is picked as "the one that  minimizes  the
average cross validated mean squared error" (quote from the linked paper). In addition to that, through the CV partitioning we can still pick a "candidate" $\lambda$ (and the associated $\beta^{(-i)}$) such that it minimises the MSE within the particular $i$-th fold. The author could be a bit more specific as to the fact that multiple candidate $\lambda$'s are used sequentially and/or that  $\beta^{(-i)}$ minimizes the error against $y^{(-1)}$ but the overall paragraph is not wrong. :)


text:
Q: Memory Management of UnManaged Objects I have one query regarding release of unmanaged objects. As unmanaged objects are not directly under control of CLR so CLR can't release it directly and for that we call dispose command but if we didn't use dispose command in our application for that unmanaged object then how resource occupied by that objects will release .
For Ex. If in C# code I am using connection objects as
try
{
    string strConnectionString = "";
    strConnectionString = "Server=FTSPROD\\FTS_PROD;Database=tdps_uat;User ID=txnapp;password=txnapp;Min Pool Size=5;Max Pool Size=10000;";
    for (int i = 0; i < 10000; i++)
    {
        SqlConnection cnUpdateTransaction;
        cnUpdateTransaction = new SqlConnection(strConnectionString);
        cnUpdateTransaction.Open();
        cnUpdateTransaction.
        //cnUpdateTransaction.Close();
    }
}
catch (Exception Ex)
{

}

Here i am opening 10000 instances of connection objects and just leaving it for garbage collection. Now as they are unmanaged objects and i am not calling close or dispose then finally how this objects will be released. Whether operating system will do something for this and when. Please share your with some document link for this issue.

A: When implementing IDisposable and the class has unmanaged resources you should implement a Finalizer that calls the Dispose method.  That way if the user of the class fails to call Dispose unmanaged resources will (eventually) be released when the GC runs.  See Implement IDisposable correctly for a good example.
If the object contains references to unmanaged resources and does not contain a finalizer and Dipose is not called then that memory will not be reclaimed automatically.  Basically, there is a memory leak.  The memory won't be reclaimed until the process is shut down.  See Identify And Prevent Memory Leaks In Managed Code for some interesting reading.


text:
Q: Two independent events For two independent events $A$ and $B$
We know $P(A\cap B)  = P(A).P(B)$.
Here what does this '$P(A\cap B)$' signifies?
And for these events what does this $P(A\cup B)$ signifies?
If possible explain with an example.

A: The fact that the probability of the intersection of independent events $A$ and $B$ is the product of their probabilities is actually the definition of independent events.
An example maybe: Suppose the probability of a person being left handed is $\frac{1}{5}$ and that of being blue-eyed is $\frac{1}{3}$. The intersection of these two events is thus being "left handed and blue eyed". If the events are independent, the proportion of blue-eyed people among the left-handed people is the same as the proportion of blue-eyed people among the whole population, i.e. $\frac{1}{3}$. Thus $\frac{1}{3}$ of $\frac{1}{5}$ or $\frac{1}{3} \times \frac{1}{5} = \frac{1}{15}$ is thus both left handed and blue eyed.

A: Events are sets of outcomes.    $\cap, \cup$ are set operators, representing intersection and union respectively; which should be familiar from primary school; recall set theory, Venn Diagrams, and such.

Here what does this 'P(A∩B)' signifies?

The probability that events $A$ and $B$ occur.   The probability that the outcome is in the intersection of events $A, B$

And for these events what does this 'P(A∪B)'
  signifies?

The probability that events $A$ or $B$ occur.  The probability that the outcome is in the union of events $A, B$.

A: In general A∩B is the group with all elements that are both in A and in B.
So here P(A∩B) signifies the probability that both events A and B happen.
P(A∪B) signifies the probability that either even A or event B or both happen.
A and B being independent means intuitively that they do not affect each other- for example if A is the event "today is Friday" and B is the event "it rained yesterday".
So in cases like this we get that the probability that both A and B happen is
 P(A∩B) = P(A)*P(B)


text:
Q: Dynamic Link in UFT automation? I want to write a dynamic VBScript for my web automation in UFT 12.02. I would like to pass a dynamic value as part of the link. here is my sample Line code:
set ObjExcel = CreateObject("Excel.application")
ObjExcel.workbooks.open "F:\Automation\Web\Business\WebTestData.xls"

For Curr= 1 To 20
    USD = ObjExcel.sheets(1).cells(Curr,1).Value
    If Browser("...").Page("...").Exist Then
       Browser("...").Page("...").WebElement("WebElement").Click
       'Attempt to click on Drop Down Link
       Browser("...").Page("...").Link("USD").Click
    End If
Next

"USD" will keep changing, i.e. I will be picking it from Excel.
Expected Result:
Generate a script that will attempt to click on different links as below:
Browser("...").Page("...").Link("EURO").Click
Browser("...").Page("...").Link("BP").Click
Browser("...").Page("...").Link("AED").Click
Browser("...").Page("...").Link("KSH").Click
Browser("...").Page("...").Link("IR").Click

A: Yes, you should use USD without double quote.
Dim currType, ObjExcel

set ObjExcel = CreateObject("Excel.application")
ObjExcel.workbooks.open "F:\Automation\Web\Business\WebTestData.xls"

For Curr= 1 To 20
   currType = ObjExcel.sheets(1).cells(Curr,1).Value
   If Browser("...").Page("...").Exist Then
      Browser("...").Page("...").WebElement("WebElement").Click
      'Attempt to click on Drop Down Link
      Browser("...").Page("...").Link(currType).Click
   End If
Next

set ObjExcel = Nothing

Note: I've changed USD with currType.

A: I have zero experience with UFT, but shouldn't using the variable USD instead of the string "USD" do what you want?
For Curr= 1 To 20
  USD = ObjExcel.sheets(1).cells(Curr,1).Value
  If Browser("...").Page("...").Exist Then
    Browser("...").Page("...").WebElement("WebElement").Click
    'Attempt to click on Drop Down Link
    Browser("...").Page("...").Link(USD).Click
  End If
Next


text:
Q: Convert vector to binary I have a vector<bool> that contains 10 elements. How can I convert it to a binary type;
vector<bool> a={0,1,1,1,1,0,1,1,1,0}

I want to get binary values, something like this:
long long int x = convert2bin(s)
cout << "x = " << x << endl

x = 0b0111101110
Note: the size of vector will be change during run time, max size = 400.
0b is important, I want to use the gcc extension, or some literal type.

A: std::vector<bool> a = { 0, 1, 1, 1, 1, 0, 1, 1, 1, 0 };
std::string s = "";
for (bool b : a)
{
    s += std::to_string(b);
}
int result = std::stoi(s);

A: As I understood of comment

Yes it can even hold 400 values

And in question

0b is important

You need to have string, not int.
std::string convert2bin(const std::vector<bool>& v)
{
    std::string out("0b");
    out.reserve(v.size() + 2);
    for (bool b : v)
    {
        out += b ? '1' : '0';
    }
    return i;
}

A: If you really want to do this, you start from the end. Although I support Marius Bancila and advise to use a bitset instead.
int mValue = 0
for(int i=a.size()-1, pos=0; i>=0; i--, pos++)
    {
        // Here we create the bitmask for this value
        if(a[i] == 1)
        {
            mask = 1;
            mask << pos;
            myValue |= mask;
        }
    }

A: Your x is just an integer form from a, so can use std::accumulate like following
long long x = accumulate(a.begin(), a.end(), 0,
                   [](long long p, long long q)
                   { return (p << 1) + q; }
                  );

For a 400 size, you need a std::string though

A: First of all the result of the conversion is not a literal. So you may not use prefix 0b applied to variable x.
Here is an example
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <numeric>
#include <vector>
#include <iterator>
#include <limits>

int main()
{
    std::vector<bool> v = { 0, 1, 1, 1, 1, 0, 1, 1, 1, 0 };

    typedef std::vector<bool>::size_type size_type;
    size_type n = std::min<size_type>( v.size(),
                                       std::numeric_limits<long long>::digits + 1 );

    long long x = std::accumulate( v.begin(), std::next( v.begin(), n ), 0ll,
                                   []( long long acc, int value )
                                   {
                                     return acc << 1 | value;
                                   } );

    for ( int i : v ) std::cout << i;
    std::cout << std::endl;

    std::cout << std::hex << x << std::endl;

    return 0;
}

The output is
0111101110
1ee

A: vector<bool> is already a "binary" type.
Converting to an int is not possible for more bits than available in an int. However if you want to be able to print in that format, you can use a facet and attach it to the locale then imbue() before you print your vector<bool>. Ideally you will "store" the locale once.
I don't know the GNU extension for printing an int with 0b prefix but you can get your print facet to do that.
A simpler way is to create a "wrapper" for your vector<bool> and print that.
Although vector<bool> is always internally implemented as a "bitset" there is no public method to extract the raw data out nor necessarily a standard representation for it.
You can of course convert it to a different type by iterating through it, although I guess you may have been looking for something else?

A: If the number of bits is known in advance and by some reason you need to start from an std::array rather than from an std::bitset directly, consider this option (inspired by this book):
#include <sstream>
#include <iostream>
#include <bitset>
#include <array>
#include <iterator>

/**
 * @brief Converts an array of bools to a bitset
 * @tparam nBits the size of the array
 * @param bits the array of bools
 * @return a bitset with size nBits
 * @see https://www.linuxtopia.org/online_books/programming_books/c++_practical_programming/c++_practical_programming_192.html
 */
template <size_t nBits>
std::bitset<nBits> BitsToBitset(const std::array<bool, nBits> bits)
{
    std::ostringstream oss;
    std::copy(std::begin(bits), std::end(bits), std::ostream_iterator<bool>(oss, ""));
    return std::bitset<nBits>(oss.str());
}

int main()
{
    std::array<bool, 10> a = { 0, 1, 1, 1, 1, 0, 1, 1, 1, 0 };
    unsigned long int x = BitsToBitset(a).to_ulong();
    std::cout << x << std::endl;
    return x;
}


text:
Q: setRetainDays in embedded jetty not working I'm using embedded jetty 9.2.22 and found that the http access logs are not getting deleted , even if i set the retaindays as 0 or 1. After setting 0 or 1 for the retaindays , i have changed the system time and started the jetty and found that the http access logs are not getting deleted.
RequestLogHandler requestLogHandler = new RequestLogHandler();
NCSARequestLog requestLog = new NCSARequestLog();

String filename = System.getProperty("user.dir") "/logs/http-yyyy_mm_dd.log";
File file = new File(filename);
file.getParentFile().mkdirs();
requestLog.setFilename(filename);
requestLog.setAppend("true");
requestLog.setExtended("false");
requestLog.setLogCookies(false));
requestLog.setLogTimeZone("GMT");
requestLog.setRetainDays(0);
requestLogHandler.setRequestLog(requestLog);
handlers.addHandler(requestLogHandler);

A: A retainDays of 0 effectively disables the entire retainDays logic and no files ever get deleted.
https://github.com/eclipse/jetty.project/blob/jetty-9.4.9.v20180320/jetty-util/src/main/java/org/eclipse/jetty/util/RolloverFileOutputStream.java#L333
The smallest legal value is 1.
Alternate option is to use org.eclipse.jetty.server.Slf4jRequestLog instead of NCSARequestLog and have your logging library of choice do the file rotation, archiving, and retain on any configuration of your choice.


text:
Q: Como chamar um som ao clicar no botão android Olá, gostaria de saber como chamar um som mais eficiente?
Pois estou utilizando este método :
Button button1;
MediaPlyer mp;
button1 = (Button)findViewById(R.id.button1);
button1.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {

    mp = MediaPlayer.create(Teste.this, R.raw.som);
    mp.start();

    }

});

e estou com problemas, pois funciona, ao clicar varias vezes tem hora que o som não sai mais.

A: Fiz uns testes aqui e descobri que esse erro (error (-19,0)) acontece quando você cria diversas instâncias do MediaPlayer e não chama release() em nenhuma delas.
Adicione isso depois de MediaPlayer.create(...):
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
    @Override
    public void onCompletion(MediaPlayer mp) {
        if(mp != null) {
            mp.release();
            mp = null;
        }
    }
});

O exemplo acima libera o MediaPlayer logo depois de terminar de reproduzir o som.
O ideal seria você inicializar esse MediaPlayer somente uma vez (no seu OnCreate, por exemplo) e reusar a mesma instância até não precisar mais.

A:
Então acrescente esse código:
private void playSound() {
   MediaPlayer mediaPlayer = MediaPlayer.create(this, R.raw.beep);
   mediaPlayer.start();
}

Coloquei seu áudio na pasta raw com o nome beep ou altere o ´beep´ pelo nome do seu arquivo no código acima.
Agora é só chamar o método playSound() no evento OnClickListener do seu botão.


text:
Q: How to keep  with XPATH? I use XPATH to remove untidy HTML tags,
$nodeList = $xpath->query("//*[normalize-space(.)='' and not(self::br)]");
    foreach($nodeList as $node)
    {
        $node->parentNode->removeChild($node);
    }

will remove the horrible input like these,

but it also removes the img tag like blow that I want to keep,

How can I keep the img tag input with XPATH?

A: Use:
//p[not(descendant::*[self::img or self::br]) and normalize-space()='']

A: Maybe you could use an XPath 1.0 expression like the one below to remove unwanted paragraphs:
//p[count(text())=0 and count(img)=0]


text:
Q: How can I seach for multiple values of a single field in youtrack? I'm trying to do the equivalent of a "where in" search in youtrack. I have a list of values and I want to know how to do that other than just saying:
field: value or field: value2 or field: value3

A: A shortcut form would be #value1 #value2 #value3. The thing is that when you enumerate several values belonging to the same catogory (say, values of a field), the values are ORed.


text:
Q: I running a console application via Windows Task Scheduler but it is taking more time while running it? I am facing an issue but I couldnt able to find out the root cause of this. First of all sorry I am not clear on this.
I have an application which do call some scripts and gets the sql data from one server and add it to another server. While running it will take around 50 minutes to complete.
But when I call this application via windows task scheduler. Its running for half n hour as expected and for some reason the application is been hanged or paused (not sure what is happening) for 7 hours and after that its getting resumed and takes another 20 minutes to complete. Is there any possibility of the windows task scheduler being paused for 7 hours and resuming back? Like due to log off or any other way?
Below are the settings that is used.
  <Settings>
    <MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>
    <DisallowStartIfOnBatteries>true</DisallowStartIfOnBatteries>
    <StopIfGoingOnBatteries>true</StopIfGoingOnBatteries>
    <AllowHardTerminate>true</AllowHardTerminate>
    <StartWhenAvailable>false</StartWhenAvailable>
    <RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable>
    <IdleSettings>
      <StopOnIdleEnd>true</StopOnIdleEnd>
      <RestartOnIdle>false</RestartOnIdle>
    </IdleSettings>
    <AllowStartOnDemand>true</AllowStartOnDemand>
    <Enabled>true</Enabled>
    <Hidden>false</Hidden>
    <RunOnlyIfIdle>false</RunOnlyIfIdle>
    <WakeToRun>false</WakeToRun>
    <ExecutionTimeLimit>P3D</ExecutionTimeLimit>
    <Priority>7</Priority>
  </Settings>

Thanks in Advance

A: Sounds like a virus, user config issue, or version issue. If possible, I would move the app to a different box, window version different and try again. Your new friend is Task Manager, for which you will need admin rights on most versions of windows. Find task manager under control panel. more info: on Microsoft site, keywords "task schedule", "thread priority". A more elaborate solution is to build your own baby task scheduler as a service. Said service to simply invoke you app based on current date time. An even simpler solution is to create a tiny ALWAYS RUNNING app that invokes you present app whenever by whatever rule(s) you code. [i.e. skip learning about sevices, configuring task scheduler, etc ]


text:
Q: How to iterate over and print a binary tree? I have coded a binary tree structure in python. I could enter the data for each nodes but could not iterate it once insertion process is over (like in Java 12) and print it in the tree format.
class Tree:
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None

def Insert(i, p):
    if i == 4:
        return
    else:
        p.left = Tree(input("Enter Value for left node\n"))
        p.right = Tree(input("Enter Value for right node\n"))
        Insert(i+1, p.left, )
        Insert(i+1, p.right, )

root = Tree(1)
Insert(0, root)
print(root)

When I print the root, I get its location in memory (something like: <__main__.Tree object at 0x036D45D0>).
Is it possible to print all the values of the each node?

A: The algorithm for printing a tree, in order, is actually quite simple. It's almost the same thing as what you're currently doing for insertion. Here's an example of an in-order traversal (the difference in ordering is whether print(root.data) goes before (preorder), between (in-order), or after (postorder) the recursive calls to its children).
def Print_Tree(root):
    if root is None:
        return
    Print_Tree(root.left)
    print(root.data)
    Print_Tree(root.right)


text:
Q: Define Eventhandler with EventArgs and Event to work in multiple classes I have my custom EventArgs in a separate class file that I can reference it later from different classes:
using System;
using System.Collections.Generic;

namespace SplitView
{
    public class RowSelectedEventArgs:EventArgs {
        public Patient selectedRow { get; set; }

        public RowSelectedEventArgs(Patient selectedRow) : base(){
            this.selectedRow = selectedRow;
        }
    }
}

In my MasterViewController I defined my event
public event EventHandler<RowSelectedEventArgs> RowClicked;

In DataSource which is in MasterViewController I can raise the event:
if (this.controller.RowClicked != null) {
    this.controller.RowClicked (this, new RowSelectedEventArgs (this.controller.list [indexPath.Row]));
}

As you can see I have a field (controller) in my DataSource with which I reference the event. Now I have a SearchSource with the same concept (also field called controller). Now in SearchSource I want to raise the event:
if (this.controller.RowClicked != null) {
    this.controller.RowClicked (this, new RowSelectedEventArgs (this.list [indexPath.Row]));
}

But I get

The event 'SplitView.MasterViewController.RowClicked' can only appear
  on the left hand side of += or -= when used outside of the type
  'SplitView.MasterViewController'

The only difference is that SearchSource is not part of the class MasterViewController (as it is with DataSource). But the event is public so it should work?
How can I raise the same event from different classes?

A: You can't directly raise an event outside of the type, which defines this event.
All you can do, is a method, which will raise event from outside:
public sealed class MyClass
{
    // this should be called from inside
    private void OnSomeEvent()
    {
        var handler = SomeEvent;
        if (handler != null)
        {
            handler(this, EventArgs.Empty);
        }
    }

    // this should be called from outside
    public void RaiseSomeEvent()
    {
        OnSomeEvent();
    }

    public event EventHandler SomeEvent;

    // other code here...
}

A: Is the field conroller in SearchSource also fo type MasterViewController?
It seems that it is a different type.


text:
Q: How to configure Devise email with Heroku and Sendgrid in Rails? I've got a simple Rails 3.2.7 app with Devise added that is deployed to Heroku with Sendgrid added. It works fine on heroku for everything except when it needs to do a password retrieve which requires sending an email. From all the posts i have read i suspect i am somehow setting up the mail parameters incorrectly. Any suggestions are appreciated.
For config/environments/production.rb i added
config.action_mailer.default_url_options = { :host => 'smtp.sendgrid.net'}

for config/initializers/devise.rb i added
config.mailer_sender = "mail-to-send@from.com"

and for config/environments.rb i added
ActionMailer::Base.smtp_settings = {
:address        => 'smtp.sendgrid.net',
:port           => '587',
:authentication => :plain,
:user_name      => ENV['SENDGRID_USERNAME'],
:password       => ENV['SENDGRID_PASSWORD'],
:domain         => 'heroku.com',
:enable_starttls_auto => true
}

A: So, your problem is you were referencing the wrong environment variables.  Heroku stores your SendGrid credentials in ENV['SENDGRID_USERNAME'] and ENV['SENDGRID_PASSWORD'].  You were using your actual username and password as the key names.
This will work:
ActionMailer::Base.smtp_settings = {
  :address        => 'smtp.sendgrid.net',
  :port           => '587',
  :authentication => :plain,
  :user_name      => ENV['SENDGRID_USERNAME'],
  :password       => ENV['SENDGRID_PASSWORD'],
  :domain         => 'heroku.com',
  :enable_starttls_auto => true
}


text:
Q: How to replace the items from given dictionary? I am a newbie in python. I was playing with dictionaries and wanted to know the solution to the given problem
list_ = [['any', 'window', 'says', 'window'], ['dog', 'great'], ['after', 'end', 'explains', 'income', '.', '?']]

dictionary=[('dog', 'cat'), ('window', 'any')]

def replace_matched_items(word_list, dictionary):
    int_word = []
    int_wordf = []
    for lst in word_list:
        for ind, item in enumerate(lst):
            for key,value in dictionary:
                if item in key:
                    lst[ind] = key
                else:
                    lst[ind] = "NA"
        int_word.append(lst)
    int_wordf.append(int_word)
    return int_wordf
list_ = replace_matched_items(list_, dictionary)
print(list_ )

Output generated is:
[[['NA', 'window', 'NA', 'window'], ['NA', 'NA'], ['NA', 'NA', 'NA', 'NA', 'NA', 'NA']]]

The expected output is:
 [[['NA', 'window', 'NA', 'window'], ['dog', 'NA'], ['NA', 'NA', 'NA', 'NA', 'NA', 'NA']]]

I am using python 3
Thanks in advance

A: Some quick introduction to data structures in python just to clarify your question.

*

*A list is similar to your arrays, where they can be accessed via their index and are mutable meaning items within the list can be changed. Lists are generally identified by brackets [].
For example:

my_array = [4, 8, 16, 32]
print(my_array[0]) # returns 4
print(my_array[3]) # returns 32

my_array[2] = 0
print(my_array) # returns [4, 8, 0, 32]

*

*A tuple is similar to a list, however, the main difference is that they are immutable meaning items within the tuple cannot be changed. Items can still be accessed via their index. They are generally identified by parenthesis ().
For example:

my_tuple = ('this', 'is', 'a', 'tuple', 'of', 'strings')
print(my_tuple[0]) # returns 'this'
my_tuple[1] = 'word' # throws a 'TypeError' as items within tuples cannot be changed.

*

*A dictionary uses a key and value pair to access, store, and change data in a dictionary. Similar to lists, they are mutable, however, each value has their own unique key. To access a value in the dictionary, you have to pass the key within the dictionary. Dictionaries are generally identified by curly braces {}.
For Example:

my_dictionary = {'John':13, 'Bob':31, 'Kelly':24, 'Ryan':17}
print(my_dictionary['Kelly']) # Returns 24

my_dictionary['Kelly'] = 56 # Assigns 56 to Kelly
print(my_dictionary['Kelly']) # Returns 56

The key:value takes this form within the dictionary, and each subsequent key-value pairs are separated by commas.
I would highly suggested reading the official documentation on the Data Structures available for python: Link Here

To answer the question
From your code given, you've used a tuple with your key-value pair encapsulated the tuple in a list as your dictionary data structure.
Your expected output is a result of you iterating through the entire dictionary, and did not handle what will occur once you've found the key for your dictionary. This can be fixed by adding a break statement within your if-statement once a key has been found.
The break statement, will exit your for loop once a key has been found and, will continue onto the next list item.
Your function will end up looking like:
def replace_matched_items(word_list, dictionary):
    int_word = []
    int_wordf = []
    for lst in word_list:
        for ind, item in enumerate(lst):
            for key,value in dictionary:
                if item in key:
                    lst[ind] = key
                    break
                else:
                    lst[ind] = "NA"
        int_word.append(lst)
    int_wordf.append(int_word)
    return int_wordf

Suggested to use a Dictionary
Using a Dictionary data structure for your key and value pairs will let you have access to methods that'll let you check whether a key exists inside your dictionary.
If you have a list of keys, and you'd like to check if a dictionary key exists within a list:
this_list = ['any', 'window', 'says', 'window', 'dog',
'great', 'after', 'end', 'explains', 'income', '.', '?']

dictionary = {'dog':'cat', 'window':'any'}

matched_list = []
for keys in dictionary:
    if keys in this_list:
        matched_list.append(keys) # adds keys that are matched
    else:
        # do something if the key is in not the dictionary

print(matched_list)
# Returns ['dog', 'window']


text:
Q: SwiftUI Picker blocking input when clipped The code example below shows 2 rows as HStacks.
The second row contains a Picker which is clipped to 40 x 80
For some reason, it's still creating an invisible view which is blocking user interaction with the button in row 1.
The Toggle switch is drawn above the invisible view, so that works. But the button is drawn beneath it and doesn't work.
If you swap the order of Toggle and Button so Button is on the left, the Button functions normally.
Video example here - https://www.loom.com/share/83542e34b9a546439ad4d99128ff51b6
Very grateful to anyone who can help me figure this out.
import SwiftUI

struct ContentView: View {

    @State private var repSelection = 1
    @State private var toggleOn = false
    var body: some View {
        VStack {
            VStack {

                //Row 1
                //If the Button is on the right, it's covered by the invisible Picker view and doesn't work. If the button is on the left, it works.
                //The Toggle seems to be drawn above the invisible view and works in either position
                HStack {

                    Toggle("Switch", isOn: $toggleOn)

                    Button("Done"){ print("Tapped Done Button") }.padding().background(Color.gray)

                }

                //Row 2
                HStack {

                    Spacer()

                    //For some reason, even though the Picker is clipped, it produces an invisible view that covers the button in Row 1,
                    Picker("Reps", selection:$repSelection){
                        ForEach(1...20, id:\.self) {
                            Text("\($0)")
                        }
                    }
                    .frame(maxWidth: 40, maxHeight: 80)
                    .compositingGroup()
                    .clipped()
                    .background(Color.green)

                }.background(Color.purple)
            }

        }
    }

}

struct PlaylistItemAdder_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

A: This is pretty strange behavior. I guess even though you clip the picker, the background is technically still drawn but not visible. Anyway, it seems to work if you disable Hit Testing on the background layer of the Picker:
          Picker("", selection:$repSelection){
                ForEach(1...20, id:\.self) {
                    Text("\($0)")
                }
            }
            .allowsHitTesting(true) // <-- allow clicking on picker
            .frame(width: 40, height: 80)
            .clipped()
            .background(Color.green)
            .allowsHitTesting(false) // <-- remove clicking on background


text:
Q: UML child parent relationship I have a class named car and it is a child class of vehicle.
Now I want to create an UML class diagram of car without having to draw vehicle and pointing a derivation arrow to it.
I want all the derivation information directly in the car class diagram.
Does a notation for that purpose exist in UML?
Best regards,
Cookie

A: The proper way to represent this is a generalization link.
But depending of your tool, you may have this kind of information inside another window...

A: I think it is not possible to indicate that Car inherits from Vehicle while not drawing Vehicle, but note that you can omit the information that is not relevant. In this case, since you are modelling Car, you may omit the attributes and operation compartments of Vehicle, like this:

The UML specification gives the following guideline: "show full attributes and operations when needed and suppress them in other contexts or when merely referring to a class and says that "any compartment may be suppressed. A separator line is not drawn for a suppressed compartment. If a compartment is suppressed, no inference can be drawn about the presence or absence of elements in it."
(UML Superstructure Specification, v2.4.1; pag 50 and 54).

A: Draw two diagrams, on the first one draw generalization relationship between classes and on the second one draw classes only to design your models.


text:
Q: How can we connect an frontend react application with another application running on tomcat server for backend accessibility on production? How can we connect an frontend react application with another application running on tomcat server for backend accessibility on production?
We have created an react app for frontend and our backend code is deployed on tomcat server.
On devlopment mode, we are able to access backend code from react application using proxy. But when we are trying to deploy the same on production, we are getting 404 error.
It will be helpfull if somebody can guide us with the deployment process.


text:
Q: Storing multiple GeoTiffs in HDF5 file in Python I want to store multiple GeoTiff files in one HDF5 file to use it for further analysis since the function I am supposed to use can just deal with HDF5 (so basically like a raster stack in R but stored in a HDF5). I have to use Python. I am relatively new to HDF5 format (and geoanalysis in Python generally) and don't really know how to approach this issue. Especially keeping the geolocation/projection inforation seems tricky to me. So far I tried:
import h5py
import rasterio

r1 = rasterio.open("filename.tif")
r2 = rasterio.open("filename2.tif")

with h5py.File('path/test.h5', 'w') as hdf:
    hdf.create_dataset('GeoTiff1', data=r1)
    hdf.create_dataset('GeoTiff2', data=r2)

Yielding the following errror:
TypeError: Object dtype dtype('O') has no native HDF5 equivalent

I am pretty sure this not at all the correct approach and I'm happy about any suggestions.

A: What you can try is to do this:
import numpy as np
spec_dtype = h5py.special_dtype(vlen=np.dtype('float64'))

Just make a spec_dtype variable with float64 type then apply this to create_dataset:
with h5py.File('path/test.h5', 'w') as hdf:
    hdf.create_dataset('GeoTiff1', data=r1,, dtype=spec_dtype)
    hdf.create_dataset('GeoTiff2', data=r2,, dtype=spec_dtype)

Apply these and hopefully it will work.

A: Using HDFql in Python, your use-case could be solved as follows:
import HDFql

HDFql.execute("SHOW FILE SIZE filename.tif, filename2.tif")

HDFql.cursor_next()

HDFql.execute("CREATE DATASET path/test.h5 GeoTiff1 AS OPAQUE(%d) VALUES FROM BINARY FILE filename.tif" % HDFql.cursor_get_bigint())

HDFql.cursor_next()

HDFql.execute("CREATE DATASET path/test.h5 GeoTiff2 AS OPAQUE(%d) VALUES FROM BINARY FILE filename2.tif" % HDFql.cursor_get_bigint())


text:
Q: change basic DOM to jQuery So I would like to change the container variable in the following code to be a JQuery object. The method I am using is not working.... The container doesn't load. The init() function is not called.
EDIT: I've trimmed down the code in the .js file.
letterpaint.js:
(function(){

  /* Get container elements */

  //var container = document.querySelector('#container');
  var charscontainer = document.querySelector('#chars');

  var container = $('#container'); //************//
  //var charscontainer = $("#chars");

  /* Prepare canvas */
  var c = document.querySelector('canvas');
  //var c = $('canvas')[0];
  var cx = c.getContext('2d');
  var letter = null;
  var fontsize = 300;
  var paintcolour = [240, 240, 240];
  var textcolour = [255, 30, 20];
  var xoffset = 0;
  var yoffset = 0;
  var linewidth = 20;
  var pixels = 0;
  var letterpixels = 0;

  /* Overall game presets */
  var state = 'intro';
  var currentstate;

  function init() {
    var temp = container.offset();
    xoffset = temp.left;
    yoffset = temp.top;
    fontsize = container.offsetHeight / 1.5;
    linewidth = container.offsetHeight / 19;

    /*
    xoffset = container.offsetLeft;
    yoffset = container.offsetTop;
    fontsize = container.offsetHeight / 1.5;
    linewidth = container.offsetHeight / 19;
    */
    paintletter();
    setstate('intro');
  }

  function setstate(newstate) {
    state = newstate;
    container.removeClass('container').addClass(newState.toString());
    //container.className = newstate;
    currentsate = state;
  }
  function moreneeded() {
    setstate('play');
    mousedown = false;
  }
  function retry(ev) {
    mousedown = false;
    oldx = 0;
    oldy = 0;
    paintletter(letter);
    //start the timer
    timer = 10;
    startTimer = true;
  }
  function winner() {
    score +=1;
    //reset timer
    timer = 10;
    //start timer again
    startTimer = true;
    //$("#score").html(score.toString());
    document.getElementById("score").innerHTML = score.toString();
    paintletter();
  }
  function start() {
    paintletter(letter);
    startTimer = true;
  }
  function cancel() {
    //reset timer
    timer = 10;
    paintletter();
  }
  function paintletter(retryletter) {
    var chars = charscontainer.innerHTML.split('');
    letter = retryletter ||
             chars[parseInt(Math.random() * chars.length,10)];
    c.width = container.offsetWidth;
    c.height = container.offsetHeight;
    cx.font = 'bold ' + fontsize + 'px Open Sans';
    cx.fillStyle = 'rgb(' + textcolour.join(',') + ')';
    cx.strokeStyle = 'rgb(' + paintcolour.join(',') + ')';
    cx.shadowOffsetX = 2;
    cx.shadowOffsetY = 2;
    cx.shadowBlur = 4;
    cx.shadowColor = '#666';

    cx.textBaseline = 'baseline';
    cx.lineWidth = linewidth;
    cx.lineCap = 'round';
    cx.fillText(
      letter,
      (c.width - cx.measureText(letter).width) / 2,
      (c.height / 1.3)
    );
    pixels = cx.getImageData(0, 0, c.width, c.height);
    letterpixels = getpixelamount(
      textcolour[0],
      textcolour[1],
      textcolour[2]
    );
    cx.shadowOffsetX = 0;
    cx.shadowOffsetY = 0;
    cx.shadowBlur = 0;
    cx.shadowColor = '#333';
    setstate('play');
  }

  function getpixelamount(r, g, b) {
    var pixels = cx.getImageData(0, 0, c.width, c.height);
    var all = pixels.data.length;
    var amount = 0;
    for (i = 0; i < all; i += 4) {
      if (pixels.data[i] === r &&
          pixels.data[i+1] === g &&
          pixels.data[i+2] === b) {
        amount++;
      }
    }
    return amount;
  }

  function paint(x, y) {
    var rx = x - xoffset;
    var ry = y - yoffset;
    var colour = pixelcolour(x, y);
    if( colour.r === 0 && colour.g === 0 && colour.b === 0) {
      showerror();
      //stop timer
      startTimer = false;
    } else {
      cx.beginPath();
      if (oldx > 0 && oldy > 0) {
        cx.moveTo(oldx, oldy);
      }
      cx.lineTo(rx, ry);
      cx.stroke();
      cx.closePath();
      oldx = rx;
      oldy = ry;
    }
  }

  function pixelcolour(x, y) {
    var index = ((y * (pixels.width * 4)) + (x * 4));
    return {
      r:pixels.data[index],
      g:pixels.data[index + 1],
      b:pixels.data[index + 2],
      a:pixels.data[index + 3]
    };
  }

  function pixelthreshold() {
    if (state !== 'error') {
      if (getpixelamount(
        paintcolour[0],
        paintcolour[1],
        paintcolour[2]
      ) / letterpixels > 0.35) {
       setstate('win');
       if (sound) {
         winsound.play();
         //stop the timer
         startTimer = false;
       }
      }
    }
  }

  /* Mouse event listeners */

  function onmouseup(ev) {
    ev.preventDefault();
    oldx = 0;
    oldy = 0;
    mousedown = false;
    pixelthreshold();
  }
  function onmousedown(ev) {
    ev.preventDefault();
    mousedown = true;
  }
  function onmousemove(ev) {
    ev.preventDefault();
    if (mousedown) {
      paint(ev.clientX, ev.clientY);
      ev.preventDefault();
    }
  }

  window.addEventListener('load',init, false);
  window.addEventListener('resize',init, false);

  //added for timer count every second
  window.setInterval(function(){timerCount()}, 1000);

})();

letterpaint.html:
<!DOCTYPE HTML>

  <meta name="viewport" content="width=device-width">
  <meta charset="UTF-8">
  <title>letterpaint</title>
  <link rel="stylesheet" type="text/css" href="letterpaint.css">

ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz123456789

    <canvas></canvas>

letterpaint

Paint over the letter you see on the screen. Can you write it without going outside of it?

      <button class="actionbutton">➜</button>

    <button id="sound" class="navbutton">♬</button>
    <button id="infos" class="navbutton">i</button>
    <button id="quit" class="navbutton">q</button>

Good job!

      <button class="actionbutton">➜</button>

You painted outside the letter!

      <button class="actionbutton">➜</button>

letterpaint

version 1.0-2406-1

Written by Chris Heilmann

modified by Anil Somayaji

Original version here (CC BY-SA 3.0).

    <button class="actionbutton undo" id="reload">X</button>

        0

        0

  <audio src="win.ogg" id="winsound"></audio>

  <audio src="error.ogg" id="errorsound"></audio>

   //unsure if this is needed

letterpaint.css:
@font-face {
  font-family: 'Open Sans';
  font-style: normal;
  font-weight: 400;
  src: local('Open Sans'), local('OpenSans'), url(opensans.ttf) format('truetype');
}
@font-face {
  font-family: 'Open Sans';
  font-style: normal;
  font-weight: 700;
  src: local('Open Sans Bold'), local('OpenSans-Bold'), url(opensans-bold.ttf) format('truetype');
}

body, html {
  width: 100%;
  height: 100%;
  background: #000;
  color: #000;
  margin: 0;
  padding: 0;
  font-family: 'Open Sans', times, arial, sans-serif;
}
.container {
  width: 100%;
  height: 100%;
  margin: 0 auto;
  position: relative;
  overflow: hidden;
}
canvas {
  background: #ccc;
  background: linear-gradient(to top, #fc6, #ffc);
  display: block;
  width: 100%;
  height: 100%;
}
.gamedata {
  display: none;
}
.cover {
  position: absolute;
  top: 80px;
  left: 10px;
  right: 10px;
  bottom: 20px;
  z-index: 2;
  border-radius: 10px;
  background: #ccc;
  background: rgba(255,255,255,0.9);
  transition: transform 0.5s;
  -webkit-transform: translate(-120%,0);
  transform: translate(-120%,0);
}

.info #info {
  -webkit-transform: translate(0, 0);
  transform: translate(0, 0);
}

.win #win {
  -webkit-transform: translate(0, 0);
  transform: translate(0, 0);
}
.error #error {
  -webkit-transform: translate(0, 0);
  transform: translate(0, 0);
}
.intro #intro {
  -webkit-transform: translate(0, 0);
  transform: translate(0, 0);
}
.cover p {
  text-align: center;
  z-index: 2;
  padding: 10px;
  font-size: 6vw;
}
.navbutton {
  position: absolute;
  top: 5px;
  display: block;
  right: 5px;
  line-height: 40px;
  font-size: 30px;
  border: none;
  width: 40px;
  height: 40px;
  text-align: center;
  background: #060;
  color: #fff;
  border-radius: 50% 50%;
  transition: 0.5s;
}
.navbuttonoff {
  position: absolute;
  top: 5px;
  display: block;
  right: 5px;
  line-height: 40px;
  font-size: 30px;
  border: none;
  width: 40px;
  height: 40px;
  text-align: center;
  background: #666;
  color: #ccc;
  border-radius: 50% 50%;
  transition: 0.5s;
}
.actionbutton {
  position: absolute;
  bottom: 20px;
  display: block;
  right: 20px;
  line-height: 60px;
  font-size: 50px;
  border: none;
  width: 60px;
  height: 60px;
  text-align: center;
  background: #060;
  color: #fff;
  border-radius: 50% 50%;
  transition: 0.5s;
}
.inlinebutton {
  float: right;
  background: #060;
  color: #fff;
  border-radius: 5px;
  border: none;
  padding: 5px 10px;
  margin-right: 20px;
  font-size: 3vw;
}
#infos {
  font-weight: bold;
  right: 55px;
}

#quit {
  font-weight: bold;
  right: 105px;
}
.score {
  position: absolute;
  bottom: 5px;
  right: 100px;
  font-size: 2vw;
  font-weight: normal;
  padding: 0 10px;
}

.timer {
  position: absolute;
  bottom: 50px;
  right: 100px;
  font-size: 5vw;
  font-weight: normal;
  padding: 0 10px;
}

.message {
  position: absolute;
  top: 50px;
  left: 10px;
  font-size: 3vw;
  font-weight: normal;
  padding: 0 10px;
}

.actionbutton.undo {
  background: #900;
  color: #fff;
  left: -100px;
  font-weight: bold;
  text-shadow: 2px 2px #000;
  box-shadow: 2px 2px 4px #333;
}
.play .undo {
  left: 10px;
}

.check p::after {
  content: '✔';
  font-size: 20vw;
  position: absolute;
  top: 10vh;
  z-index: 1;
  left: 60%;
  color: #060;
  color: rgba(0,200,0,0.4);
}

.toppanel {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  font-size: 30px;
  margin: 0;
  padding: 5px 10px;
  background: #000;
  background: linear-gradient(to top, #000, #333);
  color: #fff;
  font-weight: normal;
}
.infopanel h1 {
  font-size: 5vw;
  font-weight: normal;
  padding: 0 10px;
}
.infopanel p {
  font-size: 3vw;
  text-align: left;
  padding: 0 10px;
}
@media all and (max-width: 320px) {
  .infopanel h1 {
    font-size: 8vw;
    font-weight: normal;
    padding: 0 10px;
  }
  .infopanel p {
    font-size: 5vw;
    text-align: left;
    padding: 0 10px;
  }
}

I am unsure why my code for var containter = $('#container') is not working. I've also tried '.container' but can't get that to work either.
I've tried to just change a button (like startbutton) to JQuery as well but have had the same problem. The init function (window eventhandler) is not being called...Why?
There are no console errors.
Any help would be appreciated!
Thank you.

A: Your letterpaint.js script is called and executed before jquery-1.10.2.min.js, so the jQuery functionality in your custom script isn't working because jQuery is not loaded yet.
Just move  above  in the markup.
It might be a good idea to load jQuery in the head, and load other scripts at the end of the body like you do now (this is what I do on most sites that I build that are heavily dependent on jQuery).  You can also move both scripts to be in the head but you'd need to wrap the code in letterpaint.js in a $(document).ready() function like so:
$(document).ready(function() {
    // your custom letterpaint.js code here
}


text:
Q: permission denied trying to download certificate from webstie using openssl, sudo I want to download ssl certificate in my linux server for which I am using this command
echo -n | openssl s_client -connect HOST:PORTNUMBER | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' > /tmp/$SERVERNAME.cert

I need help in using sudo for the above command, I tried adding sudo  at the start but its failing with permission denied, need help with using sudo when using sed in command.

A: Why do you need sudo(1) to do this?  Your example works fine for me accessing www.oracle.com:443 like this:
echo -n | openssl s_client -connect www.oracle.com:443 | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p'


text:
Q: KernelPCA from sklearn doesn't return original data If I do a transform and then an inverse_transform using PCA, I of course get the original data back.  If I do the same for KernelPCA, I don't.  Is this a property of kernelPCA or a shortcoming of the implementation?  Code is here:
import numpy as np
from sklearn.decomposition import PCA, KernelPCA
pca = PCA(n_components=2, copy=True)
kpca = KernelPCA(n_components=5,
             kernel='rbf',
             gamma=1.0, # default 1/n_features
             kernel_params=None,
             fit_inverse_transform=True,
             eigen_solver='auto',
             tol=0,
             max_iter=None)
train_set = np.random.rand(5,2)
k_transformed = kpca.fit_transform(train_set)
k_orig =  kpca.inverse_transform(k_transformed)
p_transformed = pca.fit_transform(train_set)
p_orig =  pca.inverse_transform(p_transformed)
print "Original Data"
print train_set
print "PCA"
print p_orig
print "KPCA"
print k_orig

Output  is here:
Original Data
[[ 0.60102465  0.37562677]
 [ 0.78281304  0.20575771]
 [ 0.55120131  0.31717359]
 [ 0.48216065  0.85297703]
 [ 0.77400554  0.86559728]]
PCA
[[ 0.60102465  0.37562677]
 [ 0.78281304  0.20575771]
 [ 0.55120131  0.31717359]
 [ 0.48216065  0.85297703]
 [ 0.77400554  0.86559728]]
KPCA
[[ 0.53530411  0.3594765 ]
 [ 0.51250412  0.25227312]
 [ 0.51253417  0.32343322]
 [ 0.45231888  0.55243246]
 [ 0.49755706  0.55221213]]

A: From wikipedia - " Because we are never working directly in the feature space, the kernel-formulation of PCA is restricted in that it computes not the principal components themselves, but the projections of our data onto those components. " .  So kernel PCA only computes the final step which is the projection onto the a subspace.  There is never a unique way to recover a vector from it's projection.

A: Read the documentation for KernelPCA around inverses: there is no analytical inverse depending on the kernel, and so they approximate the inverse transform by learning a ridge regression between the PC basis and the original feature space.  You can adjust the regularization parameter for that regression using the parameter alpha; setting alpha=0 in your example produces (nearly, as in np.allclose) equal k_orig as train_set (though presumably a less-faithful inverse for data that isn't your training data).


text:
Q: NVARCHAR variable not working in Where clause In SQL Server (2018 I think? I don't know how to tell) my variable isn't working in WHERE clauses for NVARCHAR. The comparison should return values but it returns nothing. If I just type the declared text in manually it suddenly works and returns values. There's no logical reason this should be any different, the types are both NVARCHARS. It is working for dates and numbers for me.
The following SQL Server code works properly and returns results:
SELECT * FROM table WHERE Column = 'text'

The following code fails however by coming up empty when I use an initial declare statement:
DECLARE @Class AS NVARCHAR = 'text'

SELECT * FROM table WHERE Column = @Class

I can't get the variable to work in the WHERE clause even though I have confirmed that column is an NVARCHAR. Other parameters I'm declaring work just fine it just seems to be NVARCHAR giving me issues.
Is there something I'm missing?

A: This does not do what you think it does:
DECLARE @Class AS NVARCHAR = 'text';

*

*You must specify the length parameter n with varchar(n), nvarchar(n), and varbinary(n) column types, because if you don't it's equivalent to n = 1.

*So DECLARE @Class AS NVARCHAR = 'text' is the same as:

*

*DECLARE @Class AS nvarchar(1) = 'text'

*Which means @class = N't' and not N'text' (but it would be if you put DECLARE @Class AS nvarchar(4).

You can see it by running this:
DECLARE @Class AS NVARCHAR = 'text'
SELECT @class;

...which gives you t as output:

Therefore, change your SQL to this:
DECLARE @class nvarchar(4) = N'text';

SELECT * FROM table WHERE Column = @class;

Also, don't forget to always schema-qualify your object-names: i.e. prefer dbo.table to just table.

A: You need to declare the length of nvarchar. For example:
DECLARE @Class AS NVARCHAR(10) = 'text'

You can check the value of @Class by running 'select @Class' to see what it contains.


text:
Q: How to count number of parts within single multi part? Using below code I am getting count of all the parts of MIME message,
But what my requirement is to get count of part within a single multi part body,
Can some one please help?
void testFunc() {
            GMimeStream* stream;
            GMimeParser* parser;
            GMimeMessage* msg;
            GMimeObject* root = NULL;

            stream = g_mime_stream_fs_new(fd); // Fd is the email file
            parser = g_mime_parser_new_with_stream(stream);
            g_object_unref(stream);
            msg = g_mime_parser_construct_message(parser);
            g_object_unref(parser);
            if (msg) {
                root = g_mime_message_get_mime_part(msg);
                int part_count=0;
                scan_part(root, &scan_data, &part_count);
            }
}

static void scan_part(GMimeObject *part, struct scan_part_data *scan_data, int *part_count) {
    gboolean is_multipart = GMIME_IS_MULTIPART(part);
    if (is_multipart) {
        GMimeMultipart* mpart = GMIME_MULTIPART(part);
        int count = g_mime_multipart_get_count(mpart);
        int i;

        for (i = 0; i < count; i++) {
            GMimeObject* subpart = g_mime_multipart_get_part(mpart, i);
            scan_part(subpart, scan_data, part_count);
            return;
        }
    } else if (GMIME_IS_MESSAGE_PART(part)) {
        GMimeMessage* msg = g_mime_message_part_get_message(GMIME_MESSAGE_PART(part));
        GMimeObject* subpart = g_mime_message_get_mime_part(msg);
        scan_part(subpart, scan_data, part_count);
        return;
    }

    gboolean is_part = GMIME_IS_PART(part);
    if (is_part || is_multipart) {
        (*part_count)++;
        // some code;
    }
}

A: To get the count for a single multipart, just do this:
int count = g_mime_multipart_get_count (multipart);

A: I got the answer of my question,
static void scan_part(GMimeObject *part, struct scan_part_data *scan_data, int *part_count) {
    gboolean is_multipart = GMIME_IS_MULTIPART(part);
    if (is_multipart) {
        GMimeMultipart* mpart = GMIME_MULTIPART(part);
        int count = g_mime_multipart_get_count(mpart);
+++     (*part_count)++;
        int i;

        for (i = 0; i < count; i++) {
            GMimeObject* subpart = g_mime_multipart_get_part(mpart, i);
            scan_part(subpart, scan_data, part_count);
            return;
        }
    } else if (GMIME_IS_MESSAGE_PART(part)) {
        GMimeMessage* msg = g_mime_message_part_get_message(GMIME_MESSAGE_PART(part));
        GMimeObject* subpart = g_mime_message_get_mime_part(msg);
        scan_part(subpart, scan_data, part_count);
        return;
    }

    gboolean is_part = GMIME_IS_PART(part);
    if (is_part || is_multipart) {
---     (*part_count)++;
        // some code;
    }
}


text:
Q: infinite loop in python? I've been working on the Knapsack problem implementation, but I could not implement it right  the code just keeps going into this infinite loop of while(true)
here's the code:
class KSBB:
    global x
    global y
    x=[]
    y=[]
    global sp
    sp=0
    global cw
    global cp
    global nw
    global np
    cw,cp,nw,np=0,0,0,0
    global k
    k=0
    global pi
    pi=0
def __init__(self,a,b,c):
    self.weights=a
    self.values=b
    self.c=c
    x=len(self.weights)
    y=len(self.weights)

Bound method:
def bound(self):
    global cp
    found=False
    bv=0
    n=len(self.weights)
    np=cp
    nw=cw
    pi=k
    while(pi < n and ~found):
        if(nw+self.weights[pi] <= self.c):
            nw+=self.weights[pi]
            np+=self.values[pi]
            y.append(1)
        else:
            bv=np+((self.c-nw)*(self.values[pi]/self.weights[pi]))
            found=True
            #y.append(0)
        pi+=1
    if found:
        pi-=1
        return bv
    else:
        return np

Branching Method:
def Knapsack(self):
    n=len(self.weights)
    while True:
        global sp
        while (self.bound() <= sp):
            while(k !=0 and y[k] !=1):
                k-=1
            if (K==0):return
            y[k]=0
            cw-=self.weights[k]
            cp-=self.values[k]
        cw=nw
        cp=np
        k=pi
        print k
        if (k==n):
            sp=cp
            x=y
            k=n-1
        else:
            y[k]=0

Output Method:
def output(self):return sp

A: if (K==0)

should probably be
if (k==0)

Just a typo...
It is easy to localize this problem - you know where you want to terminate your loop and the only thing which can go wrong is your if statement. Spotting such things is easy and one of the most basic things to master in programming. You need to learn debugging as soon as your programs start to be longer than 5 lines.

A: ~found is a bitwise complement. I think you mean not found!
>>> ~False
-1             # True
>>> ~True
-2             # also True!


text:
Q: Iterar con ngFor un json con clave numero ¿Cómo puedo iterar con un ngFor una clave numerica? Enlace codebeautify,
estoy intentando hacer lo siguiente pero obviamente me muestra error:

        {{referencia.2}}*

quiero pintar en una tarjeta el nombre

A: Creo que el enlace está roto, pero si referencias.rows es un objeto en lugar de 2 escribe el nombre de la clave que tiene el valor que buscas, por ejemplo: {{referencia.name}}, {{referencia.id}} etc
Saludos


text:
Q: How to retrofit I'm new to NodeJS and Retrofit and I can't seem to get POST/PUT/DELTE to work.
For example, my back-end end point:
routes.post('/createGame', async (req, res) => {
  const game = await models.game.model.create({
    name: req.body.name,
    description: req.body.description,
    rules: req.body.rules,
    requirements: req.body.requirements,
    type: req.body.type
  });
  res.send(game);
});

as for my retrofit request, I've tried with FormUrlEncoded:
    @POST("createGame")
    @FormUrlEncoded
    fun createGame(
        @Field("name") name: String,
        @Field("description") description: String,
        @Field("rules") rules: String,
        @Field("requirements") requirements: String,
        @Field("type") type: GameType
    ): Deferred<Game>

I've done this without using any tags and I've tried with @Body for every parameter but that's not how body works (I don't want to pass it as an object)
How can I fix this?

A: Basically @Field annotation has an option field for encoding:
encoded: can be either true or false; default is false
The encoded option defines whether your provided key-value-pair is already url encoded. To specify the encoded option value, you need to pass it within the @Field annotation. The example below illustrates a code examples and sets the encoded option to true.
@Field(value = "title", encoded = true) String title

More information on working with Retrofit could be found here.