text:
Q: Error #1065: Variable mx.core::RSLData is not defined I'm attempting to use loadStyleDeclarations on a remote SWF with the following code (using Flex 4.6):
<?xml version="1.0" encoding="utf-8"?>
<s:View xmlns:fx="http://ns.adobe.com/mxml/2009"
        xmlns:s="library://ns.adobe.com/flex/spark" title="HomeView" initialize="GetFonts()">

    <fx:Script>
        public function GetFonts():void {
            styleManager.loadStyleDeclarations("http://dev.mycompany.com/fonts/fonts.swf");
            fontLabel.setStyle('fontFamily', 'Arial');
        }
    </fx:Script>

    <s:Label id="fontLabel" text="This should be Arial!" top="10" />
</s:View>

As a Flex web application, this works perfectly (both the target swf and the consuming application on the same server, different folders). As a Flex mobile (iOS) application, an error is encountered:
ReferenceError: Error #1065: Variable mx.core::RSLData is not defined.
    at style_mx_core_FlexModuleFactory/info()[style_mx_core_FlexModuleFactory.as:77]
    at mx.core::FlexModuleFactory()[E:\dev\4.y\frameworks\projects\framework\src\mx\core\FlexModuleFactory.as:107]
    at style_mx_core_FlexModuleFactory()[style_mx_core_FlexModuleFactory.as:35]
VerifyError: Error #1014: Class mx.modules::ModuleBase could not be found.
VerifyError: Error #1014: Class mx.core::FontAsset could not be found.
ReferenceError: Error #1065: Variable style__embed__font_Arial_medium_normal_657631602 is not defined.
ReferenceError: Error #1065: Variable _class_embed_css_Assets_swf_1392078518_mx_skins_cursor_BusyCursor_762190923 is not defined.

Any ideas? Found one solution to add "-static-link-runtime-shared-libraries=true" to the build path but that did not resolve the issue.


text:
Q: reloading page every time i visit different page in flutter I have made 2 bottom navigation bar and on every page, I am hitting Flask API for getting data from database. the problem occurs after starting the app I switch between tabs. after switching, the card disappears on there own, and to get the data again I have to go and refresh that particular page. I don't know the problem as no error is shown.
can anyone tell me how to solve this problem so that the data remains even if I switch that Tab?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Shell script in ~/bin working, but command not found This is probably a stupid question, so sorry for wasting your time here, but i have run into a problem while creating a shell script.
The script itself does run (for testing purposes it's just an echo), however i want it to run from just its name by placing it in the ~/bin/ folder. This has worked for me in the past, but i seem to have made some kind of mistake.
Console outputs:
johannes@pickle:~$ ~/bin/d
hahaha
johannes@pickle:~$ d
d: command not found

the script I'm using:
#!/bin/sh
echo hahaha

EDIT: rebooting solved it. thank you to dessert for that tip.

A: The ~/bin directory is added to your PATH by the following lines in ~/.profile:
if [ -d "$HOME/bin" ] ; then
    PATH="$HOME/bin:$PATH"
fi

This tests whether the directory exists and adds it, but ~/.profile is only run on login – thus, if you just create ~/bin it is not added to your path before the next login/reboot. You can add it manually by running:
export PATH="$HOME/bin:$PATH"

A: Your script is located in ~/bin/d, it is a local directory (/home/<user>/bin).
It is not added to PATH, so it won't work without a path to the file.


text:
Q: How can I use Linux getrandom system call to generate a random number within a range? I have the following piece of code
#include <unistd.h>
#include <sys/syscall.h>
#include <linux/random.h>

unsigned long int s;
syscall(SYS_getrandom, &s, sizeof(unsigned long int), 1);
std::cout << s << std::endl;

According to GETRANDOM(2) it returns random numbers from /dev/random or /dev/urandom with high entropy.
How can I use it to return numbers within a range? The range I'm using is [0 - 2^125] [0 - 125^2]

A: Assuming that whatever SYS_getrandom uses is a true generator (rather than a pseudorandom one), your best bet in this instance is to recognise that 125 * 125 is very close to the 14th power of 2, and go from there.
So pass a 16 bit unsigned as the buffer, read in 14 bits from the generator, and perform any necessary bitwise operations on the result. This will give you a number in the range 0 to 16383 inclusive.
Resample if the number is outside the desired range: a probability of about 5%.
With a pseudo random number generator, resampling can introduce statistical anomalies (higher moments than the mean go off), but with a true generator it doesn't.


text:
Q: Iphone/IOS - Debugging Application Crashes From what I've read, this topic has come up several times over the last few years and usually with very vague answers, plus there hasn't been a mention of it from what I've found in over a year so I'm hoping there's been progress.
Anyway, I currently have an Iphone 4 with IOS 5.0.1 installed, and am having the issue where most applications installed from the App Store are crashing on splash screen. There are many people who say installing a random application from the App Store, reinstalling the app, or restoring your phone completely will fix this problem, but it doesn't seem to have the same effect anymore (as most of these suggestions were for IOS 4 and 3, not 5).
So, what I've done is just trying to find the source of the issues. I'll be using the popular and well known app UrbanSpoon as my example for the crashes. Below are the syslog and crash report after attempting to run UrbanSpoon. From what I can understand from them, it has something to do with how IOS sandboxes applications, but I can't figure out which part specifically says what could be causing the crash.
Any help on this is greatly appreciated, hoping these answers will benefit everyone having this issues!
SysLog:
(Snipped from log file from when UrbanSpoon was first executed to the last mention of the application)
EDIT:
Syslog is too big to post here, here's a link to it instead.
http://dl.dropbox.com/u/9235267/MyiPhoneSysLogForUrbanSpoon.txt
Crash Report for UrbanSpoon:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>AutoSubmitted</key>
    <true/>
    <key>SysInfoCrashReporterKey</key>
    <string>38f6d9c3d504f902f8dbae968517559766e3092d</string>
    <key>bug_type</key>
    <string>109</string>
    <key>description</key>
    <string>Incident Identifier: 568DB2CE-F9A2-47A7-A427-B5C4DF6A09D0
CrashReporter Key:   38f6d9c3d504f902f8dbae968517559766e3092d
Hardware Model:      iPhone3,1
Process:         urbanspin [282]
Path:            /var/mobile/Applications/42579EAA-3CD0-4B2B-BFF5-5EB1C9297207/urbanspin.app/urbanspin
Identifier:      urbanspin
Version:         ??? (???)
Code Type:       ARM (Native)
Parent Process:  launchd [1]

Date/Time:       2012-01-04 13:22:22.479 -0500
OS Version:      iPhone OS 5.0.1 (9A405)
Report Version:  104

Exception Type:  00000020
Exception Codes: 0x8badf00d
Highlighted Thread:  0

Application Specific Information:
com.urbanspoon.urbanspin failed to launch in time

Elapsed total CPU time (seconds): 20.580 (user 20.580, system 0.000), 100% CPU
Elapsed application CPU time (seconds): 0.511, 2% CPU

Thread 0:
0   ???                             0x34a7f110 0 + 883421456
1   Foundation                      0x32356c92 0x32350000 + 27794
2   AnyRingLib.dylib                0x00379a3e 0x377000 + 10814
3   dyld                            0x2febdf80 0x2feb1000 + 53120
4   dyld                            0x2febdbcc 0x2feb1000 + 52172
5   dyld                            0x2febb7d0 0x2feb1000 + 42960
6   dyld                            0x2febc790 0x2feb1000 + 46992
7   dyld                            0x2feb35c0 0x2feb1000 + 9664
8   dyld                            0x2feb9106 0x2feb1000 + 33030
9   ???                             0x3367b5a4 0 + 862434724
10  SubstrateLoader.dylib           0x000d46ae 0xd3000 + 5806
11  SubstrateLoader.dylib           0x000d4828 0xd3000 + 6184
12  dyld                            0x2febdece 0x2feb1000 + 52942
13  dyld                            0x2febdbd4 0x2feb1000 + 52180
14  dyld                            0x2febb7d0 0x2feb1000 + 42960
15  dyld                            0x2febc790 0x2feb1000 + 46992
16  dyld                            0x2feb35c0 0x2feb1000 + 9664
17  dyld                            0x2feb9106 0x2feb1000 + 33030
18  ???                             0x3367b5a4 0 + 862434724
19  MobileSubstrate.dylib           0x0009aea0 0x9a000 + 3744
20  dyld                            0x2febdece 0x2feb1000 + 52942
21  dyld                            0x2febdbd4 0x2feb1000 + 52180
22  dyld                            0x2febb7d0 0x2feb1000 + 42960
23  dyld                            0x2febc790 0x2feb1000 + 46992
24  dyld                            0x2feb39f0 0x2feb1000 + 10736
25  dyld                            0x2feb7b80 0x2feb1000 + 27520
26  dyld                            0x2feb22ca 0x2feb1000 + 4810
27  dyld                            0x2feb205c 0x2feb1000 + 4188

Thread 1:
0   ???                             0x34a7e3b4 0 + 883418036
1   ???                             0x34beab98 0 + 884911000
2   ???                             0xfffffffc 0 + -4

Thread 2:
0   ???                             0x34a8ecd4 0 + 883485908
1   ???                             0x3626d0a0 0 + 908513440

Thread 3:
0   ???                             0x34a8ecd4 0 + 883485908
1   ???                             0x3626d0a0 0 + 908513440

Unknown thread crashed with unknown flavor: 5, state_count: 1

Binary Images:
    0x1000 -    0x74fff +urbanspin armv7  <0b3e8cdf11113d1abf4c0d83ef1a3ebe> /var/mobile/Applications/42579EAA-3CD0-4B2B-BFF5-5EB1C9297207/urbanspin.app/urbanspin
   0x9a000 -    0x9afff +MobileSubstrate.dylib armv6  <cf2cce379dcd3a4c970e3196b908b0b6> /Library/MobileSubstrate/MobileSubstrate.dylib
   0xd3000 -    0xd4fff +SubstrateLoader.dylib armv6  <30381ec9e24c3c289f447bf428bda2c1> /Library/Frameworks/CydiaSubstrate.framework/Libraries/SubstrateLoader.dylib
   0xf7000 -    0xfafff  libsubstrate.dylib armv6  <d375337d03a7324c9cfb608b7231eeea> /usr/lib/libsubstrate.dylib
  0x300000 -   0x311fff +ActionMenu.dylib armv6  <62581e9bc0d93ef2ab8175cd5e337e62> /Library/MobileSubstrate/DynamicLibraries/ActionMenu.dylib
  0x318000 -   0x321fff +Activator.dylib armv6  <53595f5e871d3d7eac4f8e945b039de3> /Library/MobileSubstrate/DynamicLibraries/Activator.dylib
  0x329000 -   0x365fff +AdBlocker.dylib armv6  <07089bfdb5563a33bee5fc772477dd33> /Library/MobileSubstrate/DynamicLibraries/AdBlocker.dylib
  0x377000 -   0x396fff +AnyRingLib.dylib armv6  <98857b11e0d73e13dfb59d83ed186a0e> /Library/MobileSubstrate/DynamicLibraries/AnyRingLib.dylib
0x2feb1000 - 0x2fed2fff  dyld armv7  <be7c0b491a943054ad12eb5060f1da06> /usr/lib/dyld
0x31933000 - 0x31a78fff  CoreGraphics armv7  <641fb6e558f239588a8bd05dbefff99a> /System/Library/Frameworks/CoreGraphics.framework/CoreGraphics
0x32350000 - 0x324cefff  Foundation armv7  <ce466f428d953caaac6641d186665809> /System/Library/Frameworks/Foundation.framework/Foundation
0x362fd000 - 0x363edfff  QuartzCore armv7  <ff595b1a042933249466e92433e1af6f> /System/Library/Frameworks/QuartzCore.framework/QuartzCore
0x36d54000 - 0x371edfff  UIKit armv7  <97b527cd6fba35c6bb39263e0f362223> /System/Library/Frameworks/UIKit.framework/UIKit
0x378d1000 - 0x3791cfff  CoreLocation armv7  <b640873565a03e45a7d4c38d1b5abade> /System/Library/Frameworks/CoreLocation.framework/CoreLocation
</string>
    <key>displayName</key>
    <string>urbanspin</string>
    <key>name</key>
    <string>urbanspin</string>
    <key>os_version</key>
    <string>iPhone OS 5.0.1 (9A405)</string>
    <key>system_ID</key>
    <string></string>
    <key>version</key>
    <string>??? (???)</string>
</dict>
</plist>

A: The line: "Application failed to launch on time" seems like the root of the whole thing.  It means the application is doing WAY too much work upon startup in the -applicationDidFinishLaunchingWithOptions method.  Combine a high loading time with 100% CPU usage, and the app looks like a thrashing bull in a fine china store.  And those are the kinds of apps the OS just loves to kill.


text:
Q: How do I preselect in a drop down list box? I am trying to preselect like this:
<option selected="yes" value="test1" >test1</option

But I get a message in VS2010 saying "Validation HTML5: The value permitted for this attribute do not include 'yes'.
Am I doing something wrong. I thought the way to preselect was as above.

A: it should be selected="selected"
<option selected="selected" value="test1" >test1</option>

A: Selected attribute only contain selected value, like this:
<option selected="selected" value="test1">test1</option>

A: <option selected="selected">test1</option>

Would be the correct way to do it, AFAIK.

A: try selected="selected" or you can just leave the selected without any value like <option selected>test1</option>


text:
Q: Calling a service inside a Blazor component does not work I have a service that look like this:
namespace Hydra.Services
{
  public class Employee
  {
    public string url { get; set; }

    public async Task<EmployeeModel> GetEmployee(){
      // return JSON data
    }
  }
}

I would like to call the service inside my Commpany component as:
@page "/"

<div> @company ... </div> <!-- OK, company details are rendered -->
<div> @Employee ... </div>  <!-- System.NullReferenceException: 'Object reference not set to an instance of an object.' -->

@code {

  company string;
  emlpoyee string;
  protected override async Task OnInitializedAsync()
    using (HttpClient client = new HttpClient())
    {
      // Get company details

      // HERE is the problem:
      EmployeeModel emp = new Employee();
      emp.url = "http://google.com";
      emlpoyee = await emp.Employee();
    }
  }
}

So, the logic to show the company works without any issue, the Employee service I am calling inside using() doesn't seem to
work. I don't know what the issue is other than the error.
This is not a problem about forgetting to include models or injecting services.
I am just a beginner so the issue is simpler than that

A: You created the variable:
@emlpoyee

but you are calling @Employee which is going to be null.
Try switching to the variable you actually put the employee into which is:
@emlpoyee

Also I think you spelt the variable wrong. I think you meant @employee perhaps.
You populate everything here:
emlpoyee = await emp.Employee();

so calling @emlpoyee is what makes sense from the code you've provided.
So change <div> @Employee ... </div> to <div> @emlpoyee ... </div>

A: Your codes have not performed the service injection correctly as it should. I present to you the method that I use and it works correctly, I hope it will be useful.
First, you need to create an interface for your service:
namespace Hydra.Services
{
    public interface IEmployee
    {
        Task<EmployeeModel> GetEmployee();
    }
}

Then, you need to modify your service by inheriting from the interface as shown below:
namespace Hydra.Services
{
    public class Employee:IEmployee
    {
        public async Task<EmployeeModel> GetEmployee()
        {
            // return JSON data
        }
    }
}

Now, you should inject the service in Startup.cs or Program.cs as follows:
services.AddScoped<IEmployee,Employee>();

Finally, you should inject your service in the desired component as shown below and use it easily:
@page "/"
@using Hydra.Services
@inherits OwningComponentBase<IEmployee>

<div> @company ... </div> <!-- OK, company details are rendered -->
<div> @Employee ... </div>  <!-- System.NullReferenceException: 'Object reference not set to an instance of an object.' -->

@code {

    private string company;
    private EmployeeModel emlpoyee = new EmployeeModel;

    private IEmployee employeeService => Service;

    protected override async Task OnInitializedAsync()

    // Get company details

    // HERE is the problem:
        EmployeeModel emp = new EmployeeModel();
        emp.url = "http://google.com";
        emlpoyee = await employeeService.GetEmployee();

}

Of course, your code has many structural problems and you probably just wanted to specify the problem in the form of an example code, so I just tried to explain the working method with your own codes so that the example is more concrete for you.


text:
Q: AngularJS Form data is not defined In AngularJS, I have a form, that when submitted, passes data off to a controller and sends it to an API.
Form:
 <form ng-submit="newCompany()">

                ID<input type="text" name="id" id="id" ng-model="newCompany.id" tabindex="1" class="form-control">
                Name<input type="text" name="name" id="name" tabindex="2" ng-model="newCompany.name" class="form-control">
                Primary Contact<input type="text" name="primary_contact" id="primary_contact" tabindex="2" ng-model="newCompany.primary_contact" class="form-control">
                Address<input type="text" name="address" id="address" tabindex="2" ng-model="newCompany.address" class="form-control">
                Function<input type="text" name="function" id="function" tabindex="2" ng-model="newCompany.function" class="form-control">
                Telephone<input type="text" name="telephone" id="telephone" tabindex="2" ng-model="newCompany.phone" class="form-control">
                Fax<input type="text" name="fax" id="fax" tabindex="2" ng-model="newCompany.fax" class="form-control">
                URL<input type="text" name="url" id="url" tabindex="2" ng-model="newCompany.url" class="form-control">

                        <input type="submit" name="add-submit" id="add-submit" tabindex="10" class="form-control btn btn-primary" value="Add Company">

{{ addCompany }}

        </form>

And the controller...
app.controller("CompaniesController", ['$scope', 'Companies', function($scope, Companies) {
    $scope.title = 'Companies';
    $scope.title_sub = 'Add Company';

   $scope.companyData = {
       id: $scope.newCompany.id,
       name: $scope.newCompany.name,
       primary_contact: $scope.newCompany.primary_contact,
       address: $scope.newCompany.address,
       function: $scope.newCompany.function,
       telephone: $scope.newCompany.phone,
       fax: $scope.newCompany.fax,
       url: $scope.newCompany.url
   };

    $scope.newCompany = function() {
        var company = new Companies($scope.companyData);
        company.$save();
    };

    $scope.companies = Companies.query();
}]);

However - I get an error that says "cannot read property 'id' of undefined"
Does anybody know what is wrong here? I thought $scope.[NG-MODEL] gets the form data...

A: *

*You have a $scope.newCompany variable which is a function, not an object.

*When you initialize $scope.companyData, you call  id: $scope.newCompany.id, where $scope.newCompany is undefined. Try define it first with all its properties ($scope.newCompany = {
id : "",
...
})

*Call your submit function something else.

*Do not create a function whose name itself a 'function'. (function: $scope.newCompany.function). This is reserved as a keyword.
These steps may be close to the result you want to see, if not reply back.


text:
Q: tab index on flash movieclip in flex I have a form that pops up in flex, it is a movieclip contained within a UIComponent. Within this movieclip are form fields.
For some reason I can't get the tab button working to be able to tab between the fields.  I set up each field with a tabindex, but that doesn't work.
Is there anything else I need to do besides this?  This is basically all the code I am using:
email.tabIndex = 1;
city.tabIndex = 2;
firstName.tabIndex = 3;
etc.
Is this not working because of flex? And if so, what is a workaround?

A: have you tried adding a new FocusManager instance to the UIComponent that contains the movieclip? I am not sure but maybe.
Also another thing I can think of could be the tabEnabled property of the form elements and the containing Objects.
Hope it gets you closer.
Good luck,
Rob
////////// UPDATE ///////////////
Unfortunately I couldn't make it work, but I send you my code, maybe you can do something with it.
I tried to add a movieclip and the textfields into it, but it's the same, no TAB at all. So I simply added the textfields to the UIComponent and set all the possible tab and focus related properties to true - no luck :(.
<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
               xmlns:s="library://ns.adobe.com/flex/spark"
               xmlns:mx="library://ns.adobe.com/flex/mx">

    <fx:Declarations>
        <!-- Place non-visual elements (e.g., services, value objects) here -->
    </fx:Declarations>

    <fx:Script>
        <![CDATA[
        import mx.core.UIComponent;
            import flash.display.MovieClip;
            import flash.text.TextField;

            protected function init(event:Event):void
            {
                var i:uint = 0;
                var l:uint = 4;
                while (i < l)
                {
                    var tf:TextField = new TextField();
                    tf.name = "tf_" + i;
                    tf.width = 200;
                    tf.height = 21;
                    tf.border = true;
                    tf.type = "input";
                    tf.tabIndex = i;
                    tf.tabEnabled = true;
                    tf.text = "tabIndex = " + String(tf.tabIndex);
                    tf.x = 50;
                    tf.y = tf.height * i + 10 * i + 100;
                    uicomp.addChild(tf);
                    ++i;
                }
            };
        ]]>
    </fx:Script>

    <mx:UIComponent hasFocusableChildren="true" tabChildren="true" tabEnabled="true" tabFocusEnabled="true" id="uicomp" width="100%" height="100%" addedToStage="init(event);" />

</s:Application>

Sorry, that's all I could do for now. If you get the answer please let me know, I am keen.
Cheers,
Rob


text:
Q: Why might the normal force on a box not be equal to its weight? Very simple homework question which I managed to get wrong:

"The weight of a box sitting on the floor points directly down. The normal force of the floor on the box points directly up. Need these two forces have the same magnitude? (y/N)"

My answer was yes, the correct answer is no. I must be missing some important concept here, may someone help me think of a realistic scenario in which the magnitudes are not equal?

A: There are various possible reasons why the normal force of the floor on the box might not equal the weight of the box.  For example:

*

*There could be another box on top of the box being asked about.

*The floor could be the floor of an elevator that is accelerating (so the net force on the box would not be zero).

*The "floor" could be a board, with a C-clamp pressing the box to the board.

*The "floor" could be the bottom of a tank of water (so there would be a buoyant force on the box).
And of course you could put these together in combinations.

A: Sometimes questions like this are asked to make the point that mechanical equilibrium (ME) should not always be assumed as a given. And also that the definition of ME states that both the net forces and net torques must total to zero. The question does not explicitly state that the system is in mechanical equilibrium, and it says nothing about the shape of the box.
If the system is not in ME, then there is no reason for the forces to have to be equal. The box could be in a state of translational or rotational acceleration.
Note there may be no ME even if the normal force on the floor and the weight are equal and opposite. The box could be tipping over because it has an asymmetric shape that causes the force normal to the floor to not be directly in line with the center of mass. The resulting net torque on the box could be tipping it over.
I voted up the previous answer because I liked its elegance (stack on a second box,) but decided to post this anyways because I suspect (hope) the question was suppose to be more about physics than a trick.


text:
Q: Make createElement return function/true for fake tag How can I make return "Function" for this request:
document.createElement("MY_FAKE_TAG").canThisRun

Now its return: undefined

A: You could extend the HTMLUnknownElement's prototype, but I really wonder if it's a good idea...

HTMLUnknownElement.prototype.canThisRun = function(){console.log('hi')};

document.createElement('foo').canThisRun();

A: Does this help you?

var element = document.createElement("MY_FAKE_TAG");
element.canThisRun = (function(){
    //your logic here then return
    return true;
})();
console.log( element.canThisRun );


text:
Q: SwiftUI Text unexpected padding bottom and top I need precise control over the area taken by Text. I created the most basic program that shows unexpected top and bottom spacing being added to a text. Where is this extra padding coming from? How to get rid of it?
@main
struct myApp: App {

    init() {    }

    var body: some Scene {
        WindowGroup {
            Text("80")
                .font(.system(size: 30, weight: .bold, design: .default))
                .background(Color.red)
        }
    }
}

A: Text seems to have default padding as seen here

You can get past that by adjusting the padding to a negative amount
Replace your code with this
Text("80")
        .font(.system(size: 30, weight: .bold, design: .default))
        .padding(.vertical, -6)
        .background(Color.red)

Here is a solution if you want to make it dynamic
  struct TestView: View {
    var fontSize: CGFloat = 110
    var paddingSize: CGFloat {
        -(fontSize * 0.23)
    }
    var body: some View {
        Text("80")
            .font(.system(size: fontSize, weight: .bold, design: .default))
            .padding(.vertical, paddingSize)
            .background(Color.red)
        Text("Hello")
    }
}

So even with a large font size of 110 like in the picture you can render it how you like

You'll need to tweak the multiplier how you see fit

A: Turns out that the padding top and bottom is actually not there at all. In my example with numbers this looks like wasted space, but actually certain characters do need this room as can be seen on this picture:
Since I am only going to show numbers I have used the solution by @Sergio to correct for this overspace.

A: For everyone still struggling with this, let me add my approach to the list. I know it's not wasted space considering characters like Ö and g, but when designing with a grid, you usually want to use the cap height of a font.
My approach is still kinda hacky, but I didn't want to use magic numbers. The trick is, using the boundingRect String function, you can get the exact height of a single line of text including the padding:
let uiFont = UIFont.systemFont(ofSize: 40, weight: .semibold)

let heightOfOneLine = "X".boundingRect(
    with: CGSize(width: CGFloat(10), height: .greatestFiniteMagnitude),
    options: .usesLineFragmentOrigin,
    attributes: [.font: uiFont],
    context: nil
).size.height

You can use this to then compute the vertical padding based on the cap height of the font:
let padding = (heightOfOneLine - uiFont.capHeight) / 2

This is the vertical padding that you need to subtract to get an area with exactly the cap height:
.padding(.vertical, -padding)

Make sure to either use the UIFont for your text by converting it to a Font or to create a Font with the same properties. It's unfortunate that there is still no way to get the UIFont out of a Font and that you can only use a UIFont for these computations.
You can test all this, using the following View:
struct TestView: View {
    private let uiFont = UIFont.systemFont(ofSize: 200, weight: .semibold)

    var body: some View {
        Text("X")
            .font(Font(uiFont))
            .padding(.vertical, -getPadding())
            .background(.red)
    }

    private func getPadding() -> CGFloat {
        let heightOfOneLine = "X".boundingRect(
            with: CGSize(width: CGFloat(10), height: .greatestFiniteMagnitude),
            options: .usesLineFragmentOrigin,
            attributes: [.font: uiFont],
            context: nil
        ).size.height

        return (heightOfOneLine - uiFont.capHeight) / 2
    }
}


text:
Q: Angular, Promises, foreach in textarea, and keeping processing order I am new to Angular, but not to programming. Trying to teach an old dog new tricks :)
I have a textarea where the user enters a list of dictionary words to lookup. There are currently 3 places where it uses their API via $http get and pulls the response from the API. Say I have these in the textarea:
computer
fragment
teleport

It loops through the textarea and runs "lookupWord()" for each word. All 3 API results are combined, and I generate my own unique ID, as well as including the word at the top of the object. This is so I can put the results in a table, and make the table row's (tr) id the unique ID I generated. There is a "view" button for each row, where when they click it, it pops up a modal with all the details. This process just makes it super simple to match the result in the array of objects, especially if there was a duplicate word.
My Problem
My hang up right now, is looping through the textarea and keeping processing order. When they click the start button, I want to disable the textarea and checkboxes on the form, so nothing can be changed in the middle of processing. When it is done, it needs to unlock the form and alert the user it is done.
I don't have it disabling the elements yet, but I am trying to get it to say "Done" after it has looped through and looked up each word. It reports "Done" before everything is actually done :(
Here is some code:
HTML
<textarea ng-model="wordlistTextarea" ng-list="
" ng-trim="false" class="form-control" id="wordsTextarea" placeholder="words to research..." rows="10"></textarea>
<input ng-model="checkboxSources.webster" type="checkbox" id="webster-api"> Merriam Webster (Dictionary API)
<input ng-model="checkboxSources.oxford" type="checkbox" id="oxford-api"> Oxford American College Dictionary (Google)
<input ng-model="checkboxSources.forvo" type="checkbox" id="forvo-api"> Forvo Pronunciation Dictionary

<button ng-disabled="!wordlistTextarea" ng-click="startProcessing()" class="btn btn-success" id="pronunciation-submit" preventDefault>Search</button>

JS
$scope.searchResults = [];    // holds array of objects for later use
$scope.baseApiUri = 'http://apibase.com/api/here';
$scope.checkboxSources = {
    webster : true,
    oxford : true,
    forvo : true
};

$scope.startProcessing = function() {
    var promises = [];
    angular.forEach($scope.wordlistTextarea, function(value, key){
        //$scope.lookupWord(value.trim());
        promises.push($scope.lookupWord(value.trim()));
    });

    $q.all(promises).then(function(results) {
        console.dir(results);
    })
    .then(function(data) {
        console.log('DONE!!');
    });
};

$scope.lookupWord = function($word) {
    Q.all([$scope.getWebster($word), $scope.getOxford($word), $scope.getForvo($word)])
    .spread(function (resultWebster, resultOxford, resultForvo) {
        var randomId = $scope.getRandomId();
        var result = {
            'word': $word,
            'id': randomId,
            'sources': {
                'webster': resultWebster.data,
                'oxford': resultOxford.data,
                'forvo': resultForvo.data,
            },
        };
        $scope.addToResults(result);
    })
    .done();
};

$scope.downloadPart = function(myUrl) {
    return $http({
        method: 'GET',
        url: myUrl,
    });
};

$scope.addToResults = function(data) {
    console.log('Adding Result:');
    console.dir(data);
    $scope.searchResults.push(data);
};

// -- API SOURCES --

$scope.getWebster = function(word) {
    if ( $scope.checkboxSources.webster == true ) {
        var url = $scope.baseApiUri + '/dictionary?word=' + word;
        return $scope.downloadPart(url);
    } else {
        return null;
    }
};

$scope.getOxford = function(word) {
    if ( $scope.checkboxSources.oxford == true ) {
        var url = $scope.baseApiUri + '/oxford?word=' + word;
        return $scope.downloadPart(url);
    } else {
        return null;
    }
};

$scope.getForvo = function(word) {
    if ( $scope.checkboxSources.forvo == true ) {
        var url = $scope.baseApiUri + '/forvo?word=' + word;
        return $scope.downloadPart(url);
    } else {
        return null;
    }
};

Overview
Again, my issue is when I click the button for startProcessing, it needs to do stuff first (disable the form), loop through the textarea and lookup the words. When done, I need to do more stuff (like enable elements on form, alert Done!, etc).
Additionally, I want to replace the Q (I have the library included) for the $q included with Angular. I used Q because it has spread. As you can see, I use spread to put the results specifically into the object. I don't know if I can use $q.all() instead and use $result[0], $result[1], etc?
Any questions, let me know. I wrote this quick because I am about to take the kids trick or treating :)
Thanks in advance!
PS: Feel free to correct me on bad Angular, or how I should do it better (or correctly). It's the only way to learn and get better ;)

A: The issue is that the promise array is not actually an array of promises.
Your lookupWord function needs to return the promise it created so it can be watched.
Just add a return for the promise it creates.
$scope.lookupWord = function($word) {
    return Q.all([$scope.getWebster($word), $scope.getOxford($word), $scope.getForvo($word)])
    .spread(function (resultWebster, resultOxford, resultForvo) {
        var randomId = $scope.getRandomId();
        var result = {
            'word': $word,
            'id': randomId,
            'sources': {
                'webster': resultWebster.data,
                'oxford': resultOxford.data,
                'forvo': resultForvo.data,
            },
        };
        $scope.addToResults(result);
    })
    .done();
};


text:
Q: UWP - Button flyout is somehow height locked I can't figure this bug out, so I stripped it to the simplest version where it still happens.
This is my XAML code:
<Grid>
    <Button x:Name="button1" Content="Button" VerticalAlignment="Top">
        <Button.Flyout>
            <Flyout Placement="Right">
                <Flyout.FlyoutPresenterStyle>
                    <Style TargetType="FlyoutPresenter">
                        <Setter Property="Padding" Value="0"/>
                        <Setter Property="Margin" Value="0"/>
                        <Setter Property="BorderThickness" Value="0"/>
                    </Style>
                </Flyout.FlyoutPresenterStyle>
                <Grid Name="PopupGrid" Background="Aqua"/>
            </Flyout>
        </Button.Flyout>
    </Button>
</Grid>

And then I have one event for that page:
private void Page_SizeChanged(object sender, SizeChangedEventArgs e)
{
    PopupGrid.Height = Window.Current.Bounds.Height;
}

So the expected behavior for that code is as follows: Upon pressing the button, a popup opens, which is vertically stretched across the window. And this works flawlessly, until I make my window too tall. Here's a GIF of what I'm describing.
As you can see, the popup clearly thinks that it should be the height of the window, but for some reason it just stops expanding at some point, and adds a scrollbar.
Am I just not seeing something here? Or do these Flyouts have some arbitrary maximum height that I've never heard of?

A: Flyout does have a max height limitation. In FlyoutPresenter styles and templates, you can find FlyoutPresenter has a MaxHeight property set to FlyoutThemeMaxHeight:
<Setter Property="MinWidth" Value="{ThemeResource FlyoutThemeMinWidth}"/>
<Setter Property="MaxWidth" Value="{ThemeResource FlyoutThemeMaxWidth}"/>
<Setter Property="MinHeight" Value="{ThemeResource FlyoutThemeMinHeight}"/>
<Setter Property="MaxHeight" Value="{ThemeResource FlyoutThemeMaxHeight}"/>

And FlyoutThemeMaxHeight is a theme resource represents 758:
<x:Double x:Key="FlyoutThemeMaxHeight">758</x:Double>

You can try to reset FlyoutPresenter's MaxHeight to  PositiveInfinity (which can be set in XAML as simply "Infinity") like following then the grid should be able to vertically stretched across the window.
<Button x:Name="button1" VerticalAlignment="Top" Content="Button">
    <Button.Flyout>
        <Flyout Placement="Right">
            <Flyout.FlyoutPresenterStyle>
                <Style TargetType="FlyoutPresenter">
                    <Setter Property="Padding" Value="0" />
                    <Setter Property="Margin" Value="0" />
                    <Setter Property="BorderThickness" Value="0" />
                    <Setter Property="MaxHeight" Value="Infinity" />
                </Style>
            </Flyout.FlyoutPresenterStyle>
            <Grid Name="PopupGrid" Background="Aqua" />
        </Flyout>
    </Button.Flyout>
</Button>


text:
Q: CSV database style changes in python like switching data into a file I'm having troubles coming up with a way to change data of a certain row in a csv file to the new value assigned through the script itself.
I hope you guys could help me with this problem.
Here is my code:
import csv

def Toevoeging_methode_plus(key_to_find, definition):
    if key_to_find in a:
        current = a[key_to_find]
        a[key_to_find] = int(current) + aantaltoevoeging

def Toevoeging_methode_minus(key_to_find, definition):
    if key_to_find in a:
        current = a[key_to_find]
        a[key_to_find] = int(current) - aantaltoevoeging
a = {}

with open("variabelen.csv") as csvfile:
    reader = csv.DictReader(csvfile)
    for row in reader:
        a[row['Product']] = row['Aantal']
        print a

print("""
1. Toevoegen
2. Aftrek
3. Check
""")
askmenu = int(raw_input("Menu Nummer? "))
if askmenu is 1:
    toevoegproduct = raw_input("Productnummer > ")
    aantaltoevoeging = int(raw_input("Hoeveel > "))
    Toevoeging_methode_plus(toevoegproduct, aantaltoevoeging)
    print a

elif askmenu is 2:
    toevoegproduct = raw_input("Productnummer > ")
    aantaltoevoeging = int(raw_input("Hoeveel > "))
    Toevoeging_methode_minus(toevoegproduct, aantaltoevoeging)
    print a

elif askmenu is 3:
    checknummer = raw_input("Productnummer > ")
    if checknummer in a:
        print a[checknummer]

else:
    print "oops"

A: I made a csv file variabelen.csv from the link you provided(you need to convert to your Excel-File to csv file).
Product,Aantal
233,60
2234,1

I added comma delimiter in your with open block:
with open("variabelen.csv") as csvfile:
    reader = csv.DictReader(csvfile, delimiter=',')
    for row in reader:
        a[row['Product']] = row['Aantal']
        print a

Output:
{'233': '60'}
{'2234': '1', '233': '60'}

1. Toevoegen
2. Aftrek
3. Check

Menu Nummer? 1
Productnummer > 233
Hoeveel > 1
{'2234': '1', '233': 61}

Now the value of 233 is becoming 61 which is expected


text:
Q: Making changes to my program after updating my database? Sorry if my question is not specific or if it has been answered before. I tried looking for it and for a better way to ask but this is the most accurate way.
I have developed a program in Java in which I insert a new row into my database in the following way:
INSERT INTO table_name VALUES (?,?,?)
The thing is that I have this query in many parts of the program, and now I decided to add a fourth column to my table. Do I have to update EVERY SINGLE query with a new question mark in the program? If I dont, it crashes.
What is the best way to proceed in these cases?

A: YES.
you need to add extra ? (parameter placeholder) because you are using implicit INSERT statement. That means that you didn't specify the column names of the table to which the values will be inserted.
INSERT INTO table_name VALUES (?,?,?)
// the server assumes that you are inserting values for all
// columns in your table
// if you fail to add value on one column. an exception will be thrown

The next time you create an INSERT statement, make sure that you specify the column names on it so when you alter the table by adding extra column, you won't update all your place holders.
INSERT INTO table_name (Col1, col2, col3) VALUES (?,?,?)
// the server knows that you are inserting values for a specific column

A:
Do I have to update EVERY SINGLE query with a new question mark in the program?

Probably. What you should do, while you're updating every single one of those queries, is to encapsulate them into an object, probably using a Data Source pattern such as a Table Data Gateway or a Row Data Gateway. That way you Don't Repeat Yourself and the next time you update the table, you only have one place to update the query.

A: Because of the syntax you've used, you might run some issues. I've referring to the lack of column names. Your INSERT queries will start failing as soon as you change your table structure.
If you had used the following syntax:
INSERT INTO table_name (C1, C2, C3) VALUES (?,?,?)
assuming your new column has a proper default value, then it would've work fine.


text:
Q: Find TIMESTAMP format in Python This is my time stamp which I mentioned below,
can someone tell me how to what is the format of it?
date_time_str = '2017-08-24T05:16:36.085Z date_time_obj = datetime.datetime.strptime(date_time_str, '%Y-%m-%d T%H:%M:%S.%f')
I tried this one, it gives error.
2nd question,
As a Type of date_time_str is STRING, can we make it to TIMESTAMP?
is it possible in python?
because I want to add it into SQL as it needs type as "TIMESTAMP".
Thanks.

A: If you just need to add a timestamp value to a TIMESTAMP field in sql you can do this.
import datetime

my_timestamp = datetime.datetime.now()

update your db with something like this...
f"UPDATE my_sql_table
SET Timfield = {my_timestamp} where id = 1"


text:
Q: How to use localhost site from my android phone? I am building a website and I am using wampserver 3.0.6 to build it in localhost.
I was able to access wampserver homepage from Android phone Chrome browser by following https://stackoverflow.com/a/24011132 answer for WAMPServer 3 and above. But how can I access my localhost website from wampserver homepage? I typed my laptop's ipv4 address into my android phone chrome browser and was able to get to wampserver homepage, but how to go to localhost site?

A: This is how I do it:
My wamp server www root:
c:\wamp64\www
My index.php is here:
c:\wamp64\www\test\index.php
From browser goto:
http://'ip to wamp server'/test/index.php
Hope it helps.


text:
Q: How to install and manage multiple versions of R I am working on a machine that has older version of R. I don't have root access on the machine, and the sys admin is on a vacation.
So the question I have is, how can I install and manage (the packages, especially) the latest version of R? Obviously I need to download the R package and install it, but a few detailed instructions from the community will help.
R noob here. Help will be greatly appreciated. Thanks


text:
Q: Call the constructor of the unknown children I want to call the constructor;
class anAbstractClass
{
 public: anAbstractClass(inputdatatype){/*blablabla*/}
};

class aChield : public anAbstactClass
{
/*
...
*/
}

void _engine::initShader(_anAbstractClass** inShader)
{
    *inShader = new /*???*/(inputdata for the construcor)
}

aChield* theChield;
_engine* myEngine = new _engine();
myEngine->initShader(&theChield);

So, how can I call the constructor at the /???/?
Thx ahead for the answers!

A: You cannot do that.  How is initShader going to know which child constructor to call, when all it knows is the base class?
What I think you want here, is a templated function:
template <typename T>
void _engine::initShader(T ** inShader)
{
    *inShader = new T(inputdata for the construcor)
}

A: Nice idea, but there is no support to get the exact type of a pointer at runtime.
In your initShader method, inShader is of type anAbstractClass** and there is no way to get the information that it was a pointer to pointer to a derived class before the method call.
So you need the change your code, maybe you can use some Factory or something like this.


text:
Q: $\text{Cov}[X,Y]$ if $\mathbb{E}[X^2]<\infty$ but $\mathbb{E}[Y^2]=\infty$ What can be said about $\text{Cov}[X,Y]$ if $\mathbb{E}[X^2]<\infty$ but  $\mathbb{E}[Y^2]=\infty$?
Intuitively, I've always thought of $\text{Cov}[X,Y]$ as the measure by which two R.V.s "change together". I'd like to say, then, that the covariance of $X$ and $Y$ is bounded by the finite variance of $X$, though that doesn't sound right to me...
Any ideas?

A: You can't bound covariance by the variance of one of the variables in general.
For an example, consider $X$ with density
$$f(x) = (\alpha-1)/x^\alpha \quad \mbox{ for }x\geq 1$$
and some $\alpha\in(7/2,4)$. Clearly $\mathbf E X^k < \infty$ iff $\alpha - 1 > k$, so $\mathbf E X^2 < \infty$. Take now $Y = X^{3/2}$. Then $\mathbf E Y = \mathbf E X^{3/2} < \infty$ and $\mathbf E Y^2 = \mathbf E X^3 = \infty$ and
$$ Cov(X,Y) = \mathbf E XY - \mathbf E X \, \mathbf E Y = \mathbf E X^{5/2} - \mathbf E X \, \mathbf E X^{3/2} = \infty. $$
On the other hand if $Z$ is taken independent of $X$ but having the same law as $Y$, since $\mathbf E Z = \mathbf E X^{3/2} < \infty$ we have that
$$ Cov(X,Z) = \mathbf E X \, \mathbf E Z - \mathbf E X \, \mathbf E Z = 0.$$


text:
Q: How do I send results(rows) of sql query to view and display in table in ASP.NET I have this method in controller:
public ActionResult Report()
    {
        string sql = System.IO.File.ReadAllText(AppDomain.CurrentDomain.BaseDirectory + "../00002165_Report.sql");

        using (NpgsqlConnection con = new NpgsqlConnection("Server=127.0.0.1;Port=5432;User Id=postgres;Password=6060;Database=hotelreal;"))
        {
            NpgsqlCommand cmd = new NpgsqlCommand(sql, con);
            con.Open();
            NpgsqlDataReader reader = cmd.ExecuteReader();
            try
            {
                while (reader.Read())
                {
                    Console.WriteLine(String.Format("{0}, {1}, {2}", reader["fName"], reader["lName"], reader["preference"]));
                }
            }
            catch (Exception e)
            {

            }
        }

        return View();
    }

As you can see, it executes the sql query and writes the results in console. But what I want to do is something like this:
Save the results returned from the query in an array. Send  this array to view and display it in a table.
How can I do that?

A: Make a model class for example Report and give 3 properties which are FName, LName and Preference
public class Report
{
  public String FName {get; set;}
  public String LName {get; set;}
  public String Preferences {get; set;}
}

Collect the data from database and assign it to a list
List<Report> Reports=new List<Report>();
Report r;
while (reader.Read())
{
  r=new Report();
  r.FName=reader["fName"];
  r.LName=reader["lName"];
  r.Preferences=reader["preference"];
  Reports.Add(r);
}

And finally pass the list to the view at the very bottom of your code
return View(Reports);

A: I just say create a model as below:
public class ReportDataModel
{
   public string fName{get; set;}
   public string lName{get; set;}
   public string preferences{get;set;}
}

Next create List of that model in your controller as below:
public ActionResult Report()
{
     string sql = System.IO.File.ReadAllText(AppDomain.CurrentDomain.BaseDirectory + "../00002165_Report.sql");
     List<ReportDataModel> model=new List<ReportDataModel>();
     using (NpgsqlConnection con = new NpgsqlConnection("Server=127.0.0.1;Port=5432;User Id=postgres;Password=6060;Database=hotelreal;"))
     {
            NpgsqlCommand cmd = new NpgsqlCommand(sql, con);
            con.Open();
            NpgsqlDataReader reader = cmd.ExecuteReader();
            try
            {
                while (reader.Read())
                {
                    model.Add(
                       new ReportDataModel() {
                           fName = reader["fName"],
                           lName = reader["lName"],
                           preferences= reader["preference"]
                       });
                }
            }
            catch (Exception e)
            {

            }
     }

     return View(model);
}

in your view create IEnumerable list of model and display through looping as below:
@model IEnumerable<ReportDataModel>

@foreach(var report in Model)
{
    //display report.fName
    //display report.lName
    //display report.preferences

}


text:
Q: C чем связано снижение производительности приложений, написанных на Java? Привет всем!
Собственно вопрос в заголовке. Я не особо силен в таких тонкостях, поэтому прошу тут помощи. В чем же проблема? Это связано с высокоуровневостью языка? С тем, что в приложение  дописывается куча каких-то дополнительных проверок? С тем, что типы данных "не легкие"?
Заранее благодарен за ответы. )
A: Если Вы серьезно, то насколько я понял Вы спрашиваете почему Java медленнее С/С++ работает ?
Если Вы это и имели ввиду, тогда давайте по порядку.
Во-первых языки бывают компилируемые и интерпретируемые. Java является интерпретируемым(если не вдаваться во все тонкости). Чтобы не повторяться по поводу определений позаимствую из просторов интернета.

Программа на компилируемом языке при
помощи специальной программы
компилятора преобразуется
(компилируется) в набор инструкций для
данного типа процессора (машинный код)
и далее записывается в исполняемый
файл, который может быть запущен на
выполнение как отдельная программа.
Другими словами, компилятор переводит
программу с языка высокого уровня на
низкоуровневый язык, понятный
процессору.
Если программа написана на
интерпретируемом языке, то
интерпретатор непосредственно
выполняет (интерпретирует) ее текст
без предварительного перевода. При
этом программа остается на исходном
языке и не может быть запущена без
интерпретатора. Можно сказать, что
процессор компьютера — это
интерпретатор машинного кода.

Думаю здесь все понятно должно быть.

*

*Есть такое понятие как виртуальная машина. Это абстракция которая по сути эмитирует реальный компьютер. В ней тоже есть основные узлы такие как управления памятью, потоками... Можете считать что это компьютер в компьютере. Такие машины обычно пишутся на языках низкого уровня для достижения быстродействия.

*Возьмем за основу Java Virtual Machine Hotspot. Это "программа" написанная на языке С++. Она предоставляет собой набор различных компонентов (Execution Engine, JIT, Class Loader). Можете об этом почитать в интернете. Можете запустить любое приложение на Java и увидите что у Вас в процессах висит процесс Java (jvm запущенный с определенными ключами).Это и есть инстанс Вашей JVM.

*Язык. Java в данном случае. Высокоуровневые языки придумали не для компьютера, а для человека. Для того чтобы можно было быстро реализовать задачи бизнес приложений. Не будете же Вы на ассемблере писать код для такого рода задач. Еще одним преимуществом есть читабельность. Если код хорошо написанный, то его можно читать как книгу, без избыточности конструкций определенного языка. Все внутренне сложности,связь с железом инкапсулированы внутри реализации виртуальной машины. Вам предоставлен интерфейс, если можно так сказать.

*Программа на таких языках компилируется не в машинный код определенной архитектуры, а в промежуточный, так называем байт код, который затем уже интерпретируется.

*В JVM Hotspot присутствует множество оптимизаций по улучшению быстродействия,например, динамическая компиляции JIT и адаптивная оптимизация.

В чем же преимущество таких языков ?
В том что Вы пишете такой код, который будет работать на любой машине где есть установленная ВМ(JVM в данном случае).Вам не нужно знать какие инструкции поддерживает та или иная архитектура процессора и другие мелочи.
Ну и собственно ответ на Ваш вопрос.
Проигрыш в быстродействии относительно компилируемых языков в том, что вводятся дополнительные уровни абстракции(виртуальные машины). В данном случае. Исполняемый код для определенной архитектуры Вам выдает интерпретатор.
EDIT
Дополнение по поводу Android
Если брать Android Dalvik VM. То тут все практически также как и Java VM. Написанием Dalvik VM для определенной архитектуры занимается разработчик данной архитектуры или же производитель телефонов. При наличии достаточных аппаратных средств Вы можете написать свою виртуальную машину для холодильника ,микроволновки, стиралки (кстати такое можно встретить).
По поводу нативных модулей. В Java присутствует такой механизм под названием JNI (Java Native Interface). Это интерфейс для связи с нативным кодом( написанным на Assembler, C++,C ..) из Java. Примером может служить тот же hashCode метод в классе Object, там стоит ключевое слово native. То есть данный метод будет вызываться из библиотеки скомпилированной нативными компиляторами с помощью интерфейса JNI.
В таких случаях такой код Вы компилируете с помощью нативных компиляторов. Например, для Андроида Вы создаете make-файл, который служит для компилятора нативного кода. Кстати, для Андроида существует обертка утилиты GNU make и имеет название ndk-build . Он в свою очередь вызывает компилятор g++/gcc заточенный под архитектуры используемые на устройствах вот пример Android.mk
LOCAL_PATH := $(call my-dir)

    include $(CLEAR_VARS)

    LOCAL_MODULE := test
    LOCAL_SRC_FILES := main.cpp
    LOCAL_CPPFLAGS := -std=gnu++0x -Wall         # whatever g++ flags you like
    LOCAL_LDLIBS := -L$(SYSROOT)/usr/lib -llog   # whatever ld flags you like

    include $(BUILD_EXECUTABLE)    # <-- Use this to build an executable.

Еще существует файл для задания архитектур для которых нужно скомпилировать выполняемый файл. Application.mk
APP_ABI := all // Для всех архитектур

Это если кратко. Тут очень много чего можно изучать, но как говориться, это уже другая история.
A:
Рассматриваю, но можно посерьезней?)

как раз-таки это и был самый серьезный вариант. В 99,9% случаев проблемы с производительностью - это именно вопрос кривизны рук разработчика. Сам язык и платформа за 20 лет своей истории были оптимизированы настолько, насколько это возможно, и грещшить на них в вопросе производительности чаще всего не стоит
A: Встречный вопрос: что конкретно подразумевается под снижением производительности? Прогресс бар медленнее бегает? Файлы долго читаются? Запрос по сети отрабатывает дольше?
Общий ответ - да, в любом высокоуровневом языке в среднем производится больше операций, чем в низкоуровневых. Однако, как правило, это незаметно для пользователя, экономит время разработки и вносит куда меньший impact, чем прорубленная молотком архитектура.


text:
Q: TypeError: this.prototype is undefined when calling Function.prototype.method() I am reading the book "Javascript: The good parts".
Now I am reading chapter about Augmenting Types:
Function.prototype.method = function (name, func) {
   this.prototype[name] = func;
   return this;
};

UPDATE:
Why following code does not work?
js> Function.prototype.method("test", function(){print("TEST")});
typein:2: TypeError: this.prototype is undefined

But following code works without problems:
js> Function.method("test", function(){print("TEST")});
function Function() {[native code]}

Why this code works?
js> var obj = {"status" : "ST"};
js> typeof obj;
"object"
js> obj.method = function(){print(this.status)};
(function () {print(this.status);})
js> obj.method();
ST

"obj" is object.
But I can call method "method" on it.
What is the difference between Function.prototype.method and obj.method?

A: Because:
Function instanceof Function           // <--- is true
Function.prototype instanceof Function // <-- is false

*

*Function.prototype is an Object, and does not inherit anything from the Function contructor.

*Function is a constructor, but also a function, so it inherits methods from Function.prototype.

*When calling Function.method, you're calling the method method of an instance of Function. So, this points to the created instance of Function.

*When calling Function.prototype.method, you're invoking an ordinary method of an object. this points to Function.prototype.

To clarify, here's an example:
Function.method()                // is equivalent to
(function Function(){}).method()
(new Function).method()          // Because Function is also a function

Function.prototype.method // No instance, just a plain function call

A: this refers to Function.prototype because you called .method on that. So, you're using Function.prototype.prototype which does not exist.
Either use Function.method(...) or this[name] = ... to eliminate one of the .prototypes.

A: prototype is only used when you are declaring the function, but not when you are calling it. Prototype makes the function a member of the object that gets created with every instance of that object.


text:
Q: nextjs links without strings Im new to nextjs, and Im checking if it will be good for the app that will have pretty complex and messy internal navigation. Just checked their documentation and I see that they recommend usage
of Link component like this  <Link href="/your_path">Path</Link>. A bit scary is that I have to provide 'your_path' as a string so every time i change page file name I have to manually update code that redirects to this page.  Is there any solution that allows me to define routing on my own so I can write something like (pseudocode)
routes = [
...
{
   page : 'page_name',
   path : 'path_to_page'
}
...
]

So instead of using string I can do  <Link href="{route.path}">Path</Link> or Im condemned to use this file-system based router with all consequences?

A: The simple answer is yes!
When you want to change a user route in NextJs you have 2 options,
The first is with the <Link> Element that you can specify a href to where it directs.
And you also have a useRouter hook for more complex routing for example if the user does an action that requires moving him into a different route you can do it internally in your handlers.
For more information about useRouter hook.
What I usually do is storing my routes in an object
const ROUTES = {
  HOME: "/",
  ABOUT: "/about"
}

and wherever you call routes you just use the object so F.E
With Link tag
<Link href={ROUTES.ABOUT}>ABOUT PAGE</Link>`

with useRouter hook
// Inside a React Component
const router = useRouter();

const handleNavigateToAbout = () => {
  router.push(ROUTES.ABOUT);
}

return (
// SOME JSX
<button onClick={handleNavigateToAbout}> Go to about page! </button>
)


text:
Q: Set jPicker field to empty value Im using jPicker as color selector in a form.
All I have to do is clear its value then set its window/icon to 'no color selected' state.
I've tried the following:
$(':input[name="color"]').val(''); //Access its value directly. (Does not affect jPicker)

2:
$.jPicker.List[0].color.active.val('hex', '', this); //Set color to black and input value to 000000, instead of empty string

3:
$.jPicker.List[0].color.active.val(null, '', this); //Does nothing

None of the 3 methods seems to behave properly.
Thanks in advance.

A: This works for me :)
$.jPicker.List[0].color.active.val('v', null);

Here is the example: http://jsfiddle.net/3Up7n/


text:
Q: Async method throw exception without default proxy web api .NET I working with some API that need to run with async (an await in body also) but it throw an exception like this:

System.NullReferenceException: Object reference not set to an instance
  of an object.

when I call that api without define defaultProxy in WebConfige. But in my solution I cannot define defaultProxy because it will interrupt some other process.
I also read this post but cannot find the solution :(
So do we have anyway to run the async method without await like create background thread to run some method like ReadAsStreamAsync (just an example).


text:
Q: selenium cucumber.io get the reports link in Java or Bash (if Bash, still console ouput), so it can be used else where (like slack) When we run tests using Cucumber, we have the option to use an ENV variable and publish the results to cucumber.io, or even without an ENV variable eg:
View your Cucumber Report at:
https://reports.cucumber.io/reports/some-uuid
This report will self-destruct in 24h.
Keep reports forever: https://reports.cucumber.io/profile

This works great!!!! But I would like to grab that "some-uuid" and send it to slack (and other places) so others can use it
I can not see a way of getting this with Java using a Hook or Listeners (I think it gets sent back to maven)
I trigger the tests with a bash script, and I was hoping the uuid could be grabbed using something like:
mvn test -Dtest=jRunnerMyTest -Dcucumber.filter.tags="$TAGS" ...| tee log.txt

However, in this case, within the log.txt, the above does not capture that bit of text containing the reports url (I dont really know why), if it did, I could regex the output and grab that url
I have also tried using --log-file, eg:
mvn test --log-file log.txt -Dtest=jRunnerMyTest -Dcucumber.filter.tags="$TAGS" ...

In this case, within the log.txt, it DOES capture the uuid, However when the tests run, there is no command output. I really need that command output, since testers use it while running the tests.
How can I get the reports url (https://reports.cucumber.io/reports/some-uuid ) and keep the console output?

A: I have done this (a long time ago now)
You can just get the response from a text file and strip it out in bash:
cmd="mvn test --log-file log.txt -Dtest=x -Dcucumber.filter.tags='"$TAGS"'
reportsUrl=$(grep -hr "reports.cucumber" log.txt | grep -v "profile" | grep -Eo 'http[^ \[U>]+'| sed 's/[^a-z0-9\.\/\-\:-]//g')
testLine=$(grep -hr "Tests run" log.txt | grep -v "FAILURE" | grep -v "Time elapsed")


text:
Q: How to parse a string given the following? I'm new with python, given this list:
a_list=['''('string','string'),...,('string','string'), 'STRING' ''']

How can I drop the quotes, parenthesis, and leaving out 'STRING' in order to get a string like this:
string string ... string

This is what I all ready tried:
new_list = ''.join( c for c in ''.join(str(v) for v
                                              in a_list)
                           if c not in ",'()")
print new_list

A: I know that the other answer is the perfect one, But as you wanted to learn more about string techniques rather than using the present libraries then this will also work.
Do note that this is a VERY BAD way to solve your problem.
a_list=['''('string','string'),...,('string','string'), 'STRING' ''']
new_list = []
for i in a_list:
    j = i.replace("'",'')
    j = j.replace('(','')
    j = j.replace(')','')
    j = j.replace(',',' ')
    j = j.replace('STRING','')
    j = j.strip()
    new_list.append(j)

print new_list

It will output
'string string ... string string'

A: If your string doesn't have a literal ..., you can use ast.literal_eval here. That will convert your string into a tuple (whose elements are 2-tuples and strings), since it basically is the string representation of a tuple. After that, it's a simple matter of iterating over the tuple and converting it to the form you want.
>>> import ast
>>> x = '''('string','string'), ('string2','string3'), ('string','string'), 'STRING' '''
>>> y = ast.literal_eval(x); print(y)
(('string', 'string'), ('string2', 'string3'), ('string', 'string'), 'STRING')
>>> ' '.join( ' '.join(elem) if type(elem) is tuple else '' for elem in y )
'string string string2 string3 string string '


text:
Q: Maximum Path from start node to end node given a specific number of steps Currently I have an implementation of Dijkstra's shortest path algorithm. Given a maze, the shortest path algorithm provides the fastest way to exit the maze from the entrance to the exit in the smallest amount of steps taken. However, I would like to find a method that, given a certain n steps, what is the maximum path possible inside the maze? (You can reach a deadend and turn back around, and it counts as additional steps)

A: I suppose you could do an inverse of Dijkstra's shortest path algorithm. Instead of iterating and taking the shortest option, have your program take the longest path at each location along the way to the destination node.


text:
Q: How to map a dictionary with a complex key type (CultureInfo) using FluentNHibernate I have dictionary which I'm mapping using Fluent NHibernate. The dictionary has a complex key type CultureInfo. My database can't store that type so I want to use a string representation of it.
In mappings other than dictionary mappings, I can successfully map CultureInfo-properties using a user type convention. Now I wonder how to do it for dicationary mappings.
Here's the entity that contains the dictionary:
public class MultilingualPhrase : Entity
{
    private IDictionary<CultureInfo, string> languageValues;

    public virtual IDictionary<CultureInfo, string> LanguageValues
    {
        get
        {
            return languageValues;
        }
    }
}

And here's the auto mapping override for the entity:
public void Override(AutoMapping<MultilingualPhrase> mapping)
{
    mapping
        .HasMany(n => n.LanguageValues)
        .Access.ReadOnlyPropertyThroughCamelCaseField()
        .AsMap<string>("CultureName")
        .Element("Phrase")
        .Table("MultilingualPhraseValues");
}

This mapping (obviously) causes the following error:

Failed to convert parameter value from a CultureInfo to a String.

I know NHibernate has a type custom type implementation for CultureInfo (I'm using it for mapping properties) but how do I specify it in my mapping override?

A: This works fine with FNH ClassMap (not sure about automapping) in NH 3.1 and FNH 1.2:
HasMany(n => n.LanguageValues)
    .Access.ReadOnlyPropertyThroughCamelCaseField()
    .AsMap<CultureInfo>("CultureName")
    .Element("Phrase")
    .Table("MultilingualPhraseValues");


text:
Q: is there any solution for authentication with vuejs and django? I use the Django framework as backend and vue.js and webpack for the frontend. to implement authentication, send a request via ajax to Django and want to keep session for next requests but can not keep session.
I use the request node module for send request and use the jar to keep session but get error 403 again. it means jar does not keep the session for this user.
in vuejs:
var request = require('request');

get_jar(){
    if(this.jar){
        return this.jar;
    }
    this.jar = request.jar();
    return this.jar;
}

send_ajax(url, data, method, callback){
    request(
        {
            url: url,
            method: method,
            form: data,
            jar: this.get_jar(),
        },
        function(err, res, body){
            callback(err, res, body)
        });
}

in django:
@method_decorator(csrf_exempt, 'dispatch')
class Login(View):
    @staticmethod
    def post(request):
        email = request.POST.get('email', None)
        password = request.POST.get('password', None)
        user = authenticate(request, username=email, password=password)
        if user is None:
            return JsonResponse({'message': 'incorrect username or password'}, status=403)
        else:
            login(request, user)
            return JsonResponse({'message': 'user logged in'})

a decorator for check user log in:
def user_login_required(method):
    @wraps(method)
    def wrap(request, *args, **kwargs):
        if request.user.is_authenticated:
            return method(request, *args, **kwargs)
        else:
            return JsonResponse({'message': 'user not recognized'}, status=403)
    return wrap

can somebody help me, please?


text:
Q: 'a' does not contain a definition for 'b' and no extenstion method error So, I'm getting a bunch of different errors and being new to C#, I'm not sure what I am doing wrong.
I am creating a new method "method A" inside my ImportDefinitionData class like shown below. It does not like the way I've defined the Area-description variable. I get a "classa.field A" cannot declare instance members in a static class error.
Then, when I try to call that method from another class, I get a red squiggly line under the method name and the error states "Definitiondata does not contain a definition for Phase1Additionalparameters and no extension method accepting a first argument of type Definition data could be found.

A: Indeed there is a bunch of errors.
First you can´t use this in a static member (in your case a static method). Furthermore you can´t define an member (static or not) within another one, this is you can´t use public within a method.
So to shortcome this use the following:
public static class ImportDefinitionData
{
    public string AREA_DESCRIPTION;

    public static DefinitionData Import(string DefinitionFile)
    {
        DefinitionData definitionData = XMLDefinitionFile.Read(DefinitionFile);
        return definitionData;
    }

    public static void Phase1AdditionalParameters()
    {

        AREA_DESCRIPTION = string.Format("{0} {1}", AREA_NAME, AREA_TYPE);
    }
}

However I´m not quite sure where AREA_NAME and AREA_TYPE come from, so you might expect further errors here.
Anyway you should definitly have a look at access-modifiers and principles of OOP, in particular what an instance of a class means and how to use the this-pointer.

A: It's because of the line below
this.AREA_DESCRIPTION = string.Format(...

Which should just be below since it's a local parameter
AREA_DESCRIPTION = string.Format(...


text:
Q: synchronize () behaves badly here. Can any one fix this? I have the following class behaving so bad. It consists of 3 thread classes and the sequence is not correct and also the output. Anyone has any idea how to correct ?
OUTPUT -
ANOTHER MY_INT to 1
Got Change for MY_INT : 1
Incrementing MY_INT to 1
Incrementing MY_INT to 2
Got Change for MY_INT : 2
ANOTHER MY_INT to 2
Incrementing MY_INT to 3
ANOTHER MY_INT to 3
Got Change for MY_INT : 3
Incrementing MY_INT to 4
Got Change for MY_INT : 4
ANOTHER MY_INT to 4
Incrementing MY_INT to 5
ANOTHER MY_INT to 5
Got Change for MY_INT : 5
MY_INT:: 5

Code:
public class VolatilityTest {

private static int MY_INT = 0;

/**
 * @param args
 * @throws InterruptedException
 */
public static void main(String[] args) throws InterruptedException {

    VolatilityTest vt = new VolatilityTest();
    vt.changeListener.start();
    vt.changeMaker.start();
    vt.anotherChangeMaker.start();

    /*new VolatilityTest().changeListener.start();
    new VolatilityTest().changeMaker.start();
    new VolatilityTest().anotherChangeMaker.start();*/
}

Thread changeListener = new Thread(new Runnable() {

    @Override
    public void run() {
            synchronized (this) {
                int local_value = MY_INT;
                while (local_value < 5) {
                    if (local_value != MY_INT) {
                        System.out.println("Got Change for MY_INT : "
                                + MY_INT);
                        local_value = MY_INT;
                    }
                }
            }
        }
});

Thread changeMaker = new Thread(new Runnable() {

    @Override
    public void run() {
            synchronized (this) {
                int local_value = MY_INT;
                while (MY_INT < 5) {
                    System.out.println("Incrementing MY_INT to "
                            + (local_value + 1));
                    MY_INT = ++local_value;
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                }
            }
            System.out.println("MY_INT:: "+MY_INT);
    }
});

Thread anotherChangeMaker = new Thread(new Runnable() {

    @Override
    public void run() {
            synchronized (this) {
                int local_value = MY_INT;
                while (MY_INT < 5) {
                    System.out.println("ANOTHER MY_INT to "
                            + (local_value + 1));
                    MY_INT = ++local_value;
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
    }
});

}

A: You are using each thread to synchronize its critical section. You must use a shared object, otherwise being in the critical section of a thread won't stop the other threads to entering theirs.
That is, in two different threads
// Thread 1
synchronize(this) {
    pointA
}

// Thread 2
synchronize(this) {
    pointB
}

Means that the program can be in pointA and pointB simultaneously.
Use a shared object to lock the critical sections from each other.
Additionally, think that synchronizing the critical sections will only prevent being executed at the same time, but it will not force them to execute in a given order.
UPDATE:
What you need to do to synchronize add
// add; any object can be used
private static Object sync_instance = new Object();

// and each synchronized section
synchronized(sync_instance) {...}

A: as you are synchronizing on this each Thread will get independent lock ( this points to enclosing anonymous Runnable() instance). So there are 3 locks for 3 Threads, hence one thread can execute independent of another in any order.
What you need is a common lock to protect your shared variable MY_INT. Either you can use VolatilityTest.class as lock to guard MY_INT static variable.
Object lock = VolatilityTest.class;

Much preferably use a separate lock Object
Object lock = new Object();
.
.
.
synchronized(lock)

In order to synchronize order of execution
you Also need to use wait
synchronized(lock)
while(condition)lock.wait();

in each thread to await for a particular condition and notify when done
synchronized(lock)
lock.notifyAll()

This is traditional way of concurrent programming with implicit locking. However you might consider newer High level java.util.concurrent constructs before deciding. In particular see CyclicBarrier to control order of evaluation

A: If I understand you correctly, you want a threadsafe counter.
If so, don't try to synchronize the threads that fiddle with the counter. Instead, use an AtomicInteger which in itself is threadsafe. So you can remove the synchronized statements from the threads.
private static AtomicInteger MY_INT = new AtomicInteger(0);

In the changelistener, use:
int local_value = MY_INT.get();

And the changemakers do
System.out.printline( "Incremented to " + MY_INT.incrementAndGet());


text:
Q: How to get all previous weeks How to get all weeks of month with date,I am doing like this
  calendar.add(Calendar.DAY_OF_WEEK, calendar.getFirstDayOfWeek() - calendar.get(Calendar.DAY_OF_WEEK));
    String[] weekly = new String[7];
    Arrays.fill(weekly, "");
    int today = calendar.getInstance().get(Calendar.DAY_OF_WEEK);
    for (int i = 0; i < 7; i++) {
        Date dt = calendar.getTime ();
        // now format it using SimpleDateFormat
        DateFormat df = new SimpleDateFormat("dd-MM-yyyy", Locale.ENGLISH);

        String val = df.format (dt);
        weekly[i] = val;
        calendar.add (Calendar.DAY_OF_WEEK, 2);
        Log.d("valueweek",""+weekly[i]);

    }

output
26-11-2017
27-11-2017
28-11-2017
29-11-2017
30-11-2017
01-12-2017
02-12-2017
But i also want all previous weeks of this month

A: java.time
First, do consider to drop the long outmoded classes Calendar, Date and DateFormat. Today we have so much better in java.time, the modern Java date and time API also known as JSR-310. On Android too, I will return to that. The modern API is so much nicer to work with.
If I understand your request correctly, this should give you what you want:
    DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("dd-MM-uuuu");
    WeekFields localWeekFields = WeekFields.of(Locale.getDefault());
    LocalDate today = LocalDate.now(ZoneId.of("Europe/Helsinki"));
    Month thisMonth = today.getMonth();
    LocalDate weekStart = today.withDayOfMonth(1)
            .with(TemporalAdjusters.previousOrSame(localWeekFields.getFirstDayOfWeek()));
    // Iterate over weeks
    do {
        System.out.println("Here's a week:");
        // Iterate over days in week
        LocalDate day = weekStart;
        for (int i = 0; i < 7; i++) {
            System.out.println(day.format(dateFormatter));
            day = day.plusDays(1);
        }
        weekStart = weekStart.plusWeeks(1);
    } while (weekStart.getMonth().equals(thisMonth));

Running this snippet on my computer today it prints the days of 5 weeks, so I will only show you the first and the last lines of output:
Here's a week:
30-10-2017
31-10-2017
01-11-2017
02-11-2017
…
Here's a week:
27-11-2017
28-11-2017
29-11-2017
30-11-2017
01-12-2017
02-12-2017
03-12-2017

Since in my locale the week starts on Monday, the above weeks go from Monday to Sunday. If you run the same code in a locale where Sunday is the first day of the week, they should go from Sunday to Saturday.
A little explanation: WeekFields.of(Locale.getDefault()) gives us a WeekFields object of the current locale. We use this a few lines down to determine the first day of the week. Then we query today's date in your desired time zone — please fill the desired time zone in if you don't want Europe/Helsinki. To iterate over the weeks, we initialize a LocalDate to the first day of the first week by first finding the first day of this month and then going back to the first day of the week (possibly going into the previous month). To determine which is the first day of the week, we query the WeekFields object that we got a few lines earlier as the one belonging to the current locale (you can fill in a different locale if desired, or just a different WeekFields object).
In the loop over weeks we first print the week and then add one week to weekStart, so we're ready for next week. The loop condition is that we're within the current month. To make sure the loop makes its first iteration even if we started on one of the last days of the previous month, I use a do-while loop rather than a while loop.
Will this work on Android?
You certainly can use the modern API on Android too. You need to get ThreeTenABP, the backport of the modern API to Android (that's ThreeTen for JSR-310 and ABP for Android Backport). It's all well and thoroughly explained in this question: How to use ThreeTenABP in Android Project.


text:
Q: Serialize Angular Component I need to serialize the reference (not an instance) of an angular component. For example, if I have the following Component:
@Component({
  selector: 'component-selector',
  template: ...
})
export class CustomComponent {

I need to save a reference to it like this:
class CustomClass {
  component: Type<CustomComponent> = CustomComponent;

  ...
}

At this point, everything works as expected, and I can use the component as I need. The problem now is that I need to serialize the CustomClass and save it to a file.
When I try to do JSON.stringify(customClass), the field component is disappearing and if I try to parse the string with JSON.parse, results in a customClass instance with undefined component.
I found this gist in order to serialize and deserialize a function, but it didn't work for me (I guess although Type interface extends from Function, is not the same, isn't it?)
How can I serialize the Angular Component?

A: I found a workaround (the only solution I found for this) and is creating a mapping from a string (identifier) to the component. For example, in some part of the code we have something like this:
let mapping = [
  {name: 'component1', component: Component1},
  {name: 'component1', component: Component1},
  ...
]

So, when the object is stringified, you can save the string that identifies the component, and when you convert it into an object again, you look in the map for the component reference. It works perfectly!


text:
Q: Replicating result from dplyr::mutate_at() using base R I am trying to replicate a result of dplyr::mutate_at() using base R. I am fairly new to writing functions myself and I was wondering whether the function I came up with is (a) reasonable and (b) how can I have the cbind() call inside the function and also keep all variables from the diamonds dataset.
First the dplyr::mutate_at() call:
require(tidyverse)

diamonds %>%
  mutate_at(.funs = funs(relative = ./price), .vars = c("x", "y", "z"))
# A tibble: 53,940 x 13
   #carat cut       color clarity depth table price     x     y     z x_relative y_relative z_relative
   #<dbl> <ord>     <ord> <ord>   <dbl> <dbl> <int> <dbl> <dbl> <dbl>      <dbl>      <dbl>      <dbl>
 #1 0.23  Ideal     E     SI2      61.5    55   326  3.95  3.98  2.43     0.0121     0.0122    0.00745
 #2 0.21  Premium   E     SI1      59.8    61   326  3.89  3.84  2.31     0.0119     0.0118    0.00709
 #3 0.23  Good      E     VS1      56.9    65   327  4.05  4.07  2.31     0.0124     0.0124    0.00706
 #4 0.290 Premium   I     VS2      62.4    58   334  4.2   4.23  2.63     0.0126     0.0127    0.00787
 #5 0.31  Good      J     SI2      63.3    58   335  4.34  4.35  2.75     0.0130     0.0130    0.00821
 #6 0.24  Very Good J     VVS2     62.8    57   336  3.94  3.96  2.48     0.0117     0.0118    0.00738
 #7 0.24  Very Good I     VVS1     62.3    57   336  3.95  3.98  2.47     0.0118     0.0118    0.00735
 #8 0.26  Very Good H     SI1      61.9    55   337  4.07  4.11  2.53     0.0121     0.0122    0.00751
 #9 0.22  Fair      E     VS2      65.1    61   337  3.87  3.78  2.49     0.0115     0.0112    0.00739
#10 0.23  Very Good H     VS1      59.4    61   338  4     4.05  2.39     0.0118     0.0120    0.00707
# ... with 53,930 more rows

This is the function I came up with to replicate the result in base R:
rel_fun <- function(x, y){
  out <- x / y
  colnames(out) <- (paste(colnames(x), "relative", sep = "_"))
  out
}

And here the result:
df_out <- rel_fun(diamonds[c("x", "y", "z")], diamonds$price)
df_out2 <- cbind(diamonds, df_out)
head(df_out2)
  #carat       cut color clarity depth table price    x    y    z x_relative y_relative  z_relative
#1  0.23     Ideal     E     SI2  61.5    55   326 3.95 3.98 2.43 0.01211656 0.01220859 0.007453988
#2  0.21   Premium     E     SI1  59.8    61   326 3.89 3.84 2.31 0.01193252 0.01177914 0.007085890
#3  0.23      Good     E     VS1  56.9    65   327 4.05 4.07 2.31 0.01238532 0.01244648 0.007064220
#4  0.29   Premium     I     VS2  62.4    58   334 4.20 4.23 2.63 0.01257485 0.01266467 0.007874251
#5  0.31      Good     J     SI2  63.3    58   335 4.34 4.35 2.75 0.01295522 0.01298507 0.008208955
#6  0.24 Very Good     J    VVS2  62.8    57   336 3.94 3.96 2.48 0.01172619 0.01178571 0.007380952

It all works fine, I would say, but as I mentioned above how can I keep all variables of the diamonds dataset while having cbind() in the function?
I tried the following but I won't get the other variables of the diamonds dataset because I didn't add them in the function. I only added the ones I needed for the calculation, i.e diamonds[c("x", "y", "z")]. Is there a way to add something in the function that allows me to keep other variables of the original dataset?
rel_fun <- function(x, y){
  out <- x / y
  colnames(out) <- (paste(colnames(x), "relative", sep = "_"))
  out2 <- cbind(x, out)
  out2
}

df_out3 <- rel_fun(diamonds[c("x", "y", "z")], diamonds$price)
head(df_out3)
#     x    y    z x_relative y_relative  z_relative
#1 3.95 3.98 2.43 0.01211656 0.01220859 0.007453988
#2 3.89 3.84 2.31 0.01193252 0.01177914 0.007085890
#3 4.05 4.07 2.31 0.01238532 0.01244648 0.007064220
#4 4.20 4.23 2.63 0.01257485 0.01266467 0.007874251
#5 4.34 4.35 2.75 0.01295522 0.01298507 0.008208955
#6 3.94 3.96 2.48 0.01172619 0.01178571 0.007380952

A: The pipe operator %>% implicitly passes your data frame diamonds as the first argument to mutate_at(). To mimic its behavior, you need to do the same with your function. Because you will be passing the entire data frame to the function, you can also just pass the column names as x:
rel_fun <- function(.data, x, y){
  out <- .data[x] / y
  colnames(out) <- (paste(x, "relative", sep = "_"))
  out2 <- cbind(.data, out)
  out2
}

rel_fun( diamonds, c("x", "y", "z"), diamonds$price )    # Works as desired


text:
Q: Отображение файлов на память Дано два файла, нужно переписать содержимое одного в другой. При этом надо переписывать по 1024 байта.
void FileCopy(int size)
{
HANDLE startMap, endMap;
HANDLE start = CreateFile(L"Test1.txt", GENERIC_READ, FILE_SHARE_READ,
    NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL,
    NULL);
HANDLE end = CreateFile(L"Test2.txt", GENERIC_WRITE, FILE_SHARE_WRITE, NULL,
    CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);

startMap = CreateFileMapping(start, NULL, PAGE_READONLY, 0, 0, NULL);
endMap = CreateFileMapping(end, NULL, PAGE_READWRITE, 0, size*1024*1024, NULL);

     char buf[1024];

}

size - размер файла в мегабайтах.
Запись должна производиться в массив buf, а потом в файл и так до тех пор, пока один файл не будет полностью скопирован, т.е. поблочное копирование. Застрял на этом моменте, не подскажите. как делать дальше?

A: После CreateFileMapping вызывайте MapViewOfFile и получите указатель на отображение файла в памяти. Потом копирование и освобождение ресурсов в обратном порядке.


text:
Q: Python: lists, mutation, recursion issue What I'm trying to do is create a final function inbounds that consumes a list of int (values) and two integers lower and upper. It produces an integer of the total numbers in values that are less than lower and greater than upper. It also mutates values. If there is an int in values that is less than lower it will mutate that value to lower and is there is an int in values that is greater than upper it will mutate that value to upper.
ex:  listin=[-3,82,105,86,-10,119,100,70] inbounds (listint, 0, 100) => 4, and v is mutated to [0,82,100,86,0,100,100,70].
So I have tried two things so far:
The first thing I tried is:
def inbounds(values, lower, upper):
    if values == []:
        return 0
    elif lower <= values[0] <= upper:
        return inbounds(values[1:], lower, upper)
    elif lower > values[0]:
        values[0] = lower
        return inbounds(values[1:], lower, upper) + 1
    else:
        values[0] = upper
        return inbounds(values[1:],lower, upper) + 1

This does return 4 but the problem with this is that I realized it would only mutate values[0] so then I tried my 2nd attempt to solve this by creating another function that has pos instead of 0 and I add 1 to pos each time it recurses:
def inbounds_from(values, lower, upper, pos):
    if pos < len(values):
        return 0
    elif lower <= values[pos] <= upper:
        return inbounds(values, lower, upper, pos+1)
    elif lower > values[pos]:
        values[pos] = lower
        return inbounds(values, lower, upper, pos+1) + 1
    else:
        values[pos] = upper
        return inbounds(values,lower, upper, pos+1) + 1

def inbounds(values, lower, upper):
    inbounds_from(values, lower, upper, 0)

Issue with is is that inbounds does nothing!!? Why? I don't get 4 when I test the example and I get the original inlist without any mutations...
edit: Also I tried changing the base case of pos <= len(values) and that still doesn't work

A: Problem is in the first condition. if pos < len(values) should be pos >= len(values) instead.
Another approach will be to use list comprehensions:
count = sum(upper <= v <= lower for v in values)
values = [min(upper, max(v, lower)) for v in values]  # mutate

A: There were few problems with your second attempt. Your base-case is wrong - it should be if pos >= len(values). Also, you were recursing on the wrapper function, not the helper/inside function. Finally, you need to return the call to your helper function in your wrapper function. See the following:
In [4]: def inbounds_from(values, lower, upper, pos):
   ...:     if pos >= len(values):
   ...:         return 0
   ...:     elif lower <= values[pos] <= upper:
   ...:         return inbounds_from(values, lower, upper, pos+1)
   ...:     elif lower > values[pos]:
   ...:         values[pos] = lower
   ...:         return inbounds_from(values, lower, upper, pos+1) + 1
   ...:     else:
   ...:         values[pos] = upper
   ...:         return inbounds_from(values,lower, upper, pos+1) + 1
   ...:
   ...: def inbounds(values, lower, upper):
   ...:     return inbounds_from(values, lower, upper, 0)
   ...:

In [5]: test = [-3,82,105,86,-10,119,100,70]

In [6]: inbounds(test, 0, 100)
Out[6]: 4

In [7]: test
Out[7]: [0, 82, 100, 86, 0, 100, 100, 70]

However, in general, recursion is to be avoided in Python. Here is a Pythonic way borrowing Marat's clever min(max()) trick:
In [8]: def in_bounds_iter(values, lower, upper):
   ...:     count = 0
   ...:     for i, val in enumerate(values):
   ...:         if not(lower <=  val <= upper):
   ...:             count += 1
   ...:             values[i] = min(upper, max(val, lower))
   ...:     return count
   ...:

In [9]: test = [-3,82,105,86,-10,119,100,70]

In [10]: in_bounds_iter(test, 0, 100)
Out[10]: 4

In [11]: test
Out[11]: [0, 82, 100, 86, 0, 100, 100, 70]


text:
Q: cannot instantiate service object I'm trying to do some refactoring for my Rails application.
I have created a QuizCompletion service object (app/services/quiz_completion.rb):
class QuizCompletion
  def initialize(quiz, user)
    @quiz = quiz
    @user = user
  end

  def pass?
    wrong_answers = 0
    @quiz.questions.each do |question|
      answer = @user.answers.where("question_id = ?", question.id).first
      if !answer.correct
        wrong_answers += 1
      end
    end
    if wrong_answers > 2
      return false
    else
      return true
    end
  end
end

Then in my QuestionsController I try to instantiate the Service Object:
class QuestionsController < ApplicationController
  before_filter :require_user
  def show
    @quiz = Quiz.find(params[:quiz_id])
    @question = Question.next(params[:id])
    if @question != nil
      redirect_to quiz_path(@quiz.id, question_id: @question.id)
    else
      evaluation = QuizCompletion.new(@quiz, current_user)  #instantiate Service Object!
      if evaluation.pass?
        Quiz.complete(current_user, @quiz)
        redirect_to quiz_complete_path(@quiz.id)
      else
        redirect_to quiz_fail_path(@quiz.id)
      end
    end
  end

private
end
However, when I run the controller test, I'm getting this error:
Failure/Error: get :show, quiz_id: @quiz.id, id: question3.id
 NoMethodError:
   undefined method `stringify_keys' for #<Quiz:0x007fd781515300>

Does someone has an idea what's going on? Why can't I instantiate a QuizCompletion object in my QuestionsController?
Thanks for your help,
Anthony

A: Found the issue, apparently the problem was with the naming of my service object. The rails framework got confused about the quiz_completion.rb name because there already exist a Quiz (quiz.rb) model.
So I changed the name of my service object to Evaluation (evaluation.rb):
class Evaluation
  def initialize(quiz, user)
    @quiz = quiz
    @user = user
  end

  def pass?
    wrong_answers = 0
    @quiz.questions.each do |question|
      answer = @user.answers.where("question_id = ?", question.id).first
      if !answer.correct
        wrong_answers += 1
      end
    end
    if wrong_answers > 2
      return false
    else
      return true
    end
  end
end

this name also makes more sense when I call it from the QuestionsController:
evaluation = Evaluation.new(@quiz, current_user)
  if evaluation.pass?
    Quiz.complete(current_user, @quiz)
    redirect_to quiz_complete_path(@quiz.id)
  else
    redirect_to quiz_fail_path(@quiz.id)
  end

A: I also could not instantiate my first service object- I got this error
uninitialized constant MyServiceObject (NameError)

I was using spring and had to stop it with: spring stop . After that it worked.