text:
Q: Update manager is not working on Efika MX (Ubuntu Maverick) When I try to update using the Update manager, I get the following error message:
Failed to download repository information: Check your Internet connection.
W:Failed to fetch http://ports.ubuntu.com/ubuntu-ports/dists/maverick/main/source/Sources.gz  404  Not Found
, W:Failed to fetch http://ports.ubuntu.com/ubuntu-ports/dists/maverick/restricted/source/Sources.gz  404  Not Found
, W:Failed to fetch http://ports.ubuntu.com/ubuntu-ports/dists/maverick/universe/source/Sources.gz  404  Not Found
, W:Failed to fetch http://ports.ubuntu.com/ubuntu-ports/dists/maverick/multiverse/source/Sources.gz  404  Not Found
, W:Failed to fetch http://ports.ubuntu.com/ubuntu-ports/dists/maverick/main/binary-armel/Packages.gz  404  Not Found
, W:Failed to fetch http://ports.ubuntu.com/ubuntu-ports/dists/maverick/restricted/binary-armel/Packages.gz  404  Not Found
, W:Failed to fetch http://ports.ubuntu.com/ubuntu-ports/dists/maverick/universe/binary-armel/Packages.gz  404  Not Found
, W:Failed to fetch http://ports.ubuntu.com/ubuntu-ports/dists/maverick/multiverse/binary-armel/Packages.gz  404  Not Found
, W:Failed to fetch http://ports.ubuntu.com/ubuntu-ports/dists/maverick-updates/main/source/Sources.gz  404  Not Found
, W:Failed to fetch http://ports.ubuntu.com/ubuntu-ports/dists/maverick-updates/restricted/source/Sources.gz  404  Not Found
, W:Failed to fetch http://ports.ubuntu.com/ubuntu-ports/dists/maverick-updates/universe/source/Sources.gz  404  Not Found
, W:Failed to fetch http://ports.ubuntu.com/ubuntu-ports/dists/maverick-updates/multiverse/source/Sources.gz  404  Not Found
, W:Failed to fetch http://ports.ubuntu.com/ubuntu-ports/dists/maverick-updates/main/binary-armel/Packages.gz  404  Not Found
, W:Failed to fetch http://ports.ubuntu.com/ubuntu-ports/dists/maverick-updates/restricted/binary-armel/Packages.gz  404  Not Found
, W:Failed to fetch http://ports.ubuntu.com/ubuntu-ports/dists/maverick-updates/universe/binary-armel/Packages.gz  404  Not Found
, W:Failed to fetch http://ports.ubuntu.com/ubuntu-ports/dists/maverick-updates/multiverse/binary-armel/Packages.gz  404  Not Found
, W:Failed to fetch http://ports.ubuntu.com/ubuntu-ports/dists/maverick-security/main/source/Sources.gz  404  Not Found
, W:Failed to fetch http://ports.ubuntu.com/ubuntu-ports/dists/maverick-security/restricted/source/Sources.gz  404  Not Found
, W:Failed to fetch http://ports.ubuntu.com/ubuntu-ports/dists/maverick-security/universe/source/Sources.gz  404  Not Found
, W:Failed to fetch http://ports.ubuntu.com/ubuntu-ports/dists/maverick-security/multiverse/source/Sources.gz  404  Not Found
, W:Failed to fetch http://ports.ubuntu.com/ubuntu-ports/dists/maverick-security/main/binary-armel/Packages.gz  404  Not Found
, W:Failed to fetch http://ports.ubuntu.com/ubuntu-ports/dists/maverick-security/restricted/binary-armel/Packages.gz  404  Not Found
, W:Failed to fetch http://ports.ubuntu.com/ubuntu-ports/dists/maverick-security/universe/binary-armel/Packages.gz  404  Not Found
, W:Failed to fetch http://ports.ubuntu.com/ubuntu-ports/dists/maverick-security/multiverse/binary-armel/Packages.gz  404  Not Found
, E:Some index files failed to download, they have been ignored, or old ones used instead.

I know that Maverick is an old and unsupported release but I cannot upgrade to a new release because Efika MX doesn't support them.
I tried to replace "port.ubuntu.com" with "old-releases.ubuntu.com" (as some websites recommended) but it doesn't work either.
What configuration should I change to get updates working properly?

A: The answer was at powerdeveloper.org (as pointed out by the official Genesi support):
deb http://old-releases.ubuntu.com/ubuntu/ maverick main restricted universe multiverse
deb http://old-releases.ubuntu.com/ubuntu/ maverick-updates main restricted universe multiverse
deb http://old-releases.ubuntu.com/ubuntu/ maverick-security main restricted universe multiverse


text:
Q: Compare two files(file1 & file2) and add one column from from file2 to file1 if first column of two files matches I have two files (file1 and file2)
file1
ABC=14.2.0.7.SAMPLE=git.xyz/plugins/gitiles/+/refs/heads/clientpatch/abc/patch142007
DEF=14.3.0.5.SAMPLE=git.xyz/plugins/gitiles/+/refs/heads/clientpatch/def/patch143005
DEF=14.3.0.5.SAMPLE2=git.calypso/plugins/gitiles/+/refs/heads/clientpatch/def/patch14300-calib
HIJ=12.0.0.0.Sp3.SAMPLE3=git.xyz/plugins/gitiles/+/refs/heads/clientpatch/hij/patch120000sp3
MNO=16.1.0.28.SAMPLE=git.xyz/plugins/gitiles/+/refs/heads/clientpatch/mno/patch161028

.......(150 lines)
file2
IJK = open
ABC = closed
PQR = closed
DEF = open
HIJ = open
LMN = closed
MNO = closed
PQR = open

......(> 150 lines)
output file
ABC=14.2.0.7.SAMPLE=git.xyz/plugins/gitiles/+/refs/heads/client/abc/patch142007=closed
DEF=14.3.0.5.SAMPLE=git.xyz/plugins/gitiles/+/refs/heads/client/def/patch143005=open
DEF=14.3.0.5.SAMPLE2=git.xyz/plugins/gitiles/+/refs/heads/client/def/patch14300-calib=open
HIJ=12.0.0.0.Sp3.SAMPLE3=git.xyz/plugins/gitiles/+/refs/heads/client/hij/patch120000sp3=open
MNO=16.1.0.28.SAMPLE=git.xyz/plugins/gitiles/+/refs/heads/client/mno/patch161028=closed

I have tried the following script. But it is not giving me any output. Not even printing anything. No errors
while IFS= read -r line
do
key1=`echo $line | awk -F "=" '{print $1}'` < file1
key2=`echo $line | awk -F "=" '{print $2}'` < file1
key3=`echo $line | awk -F "=" '{print $3}'` < file1
key4=`echo $line | awk -F "=" '{print $1}'` < file2
value3=`echo $line | awk -F "=" '{print $2}'` < file2
if [ "$key1" == "$key4" ]; then
echo "$key1=$key2=$key3=$value3"
fi
done

Giving a brief description for how the code should work.
The code should compare first columns of two files(file1 and file2). If each name matches it should give me output file as listed above. Else go to the next line. I should get output if my two files are either in sorted or unsorted format.
Helps will be appreciated. Thank you

A: Could you please try following.
awk '
BEGIN{
  OFS="="
}
FNR==NR{
  a[$1]=$NF
  next
}
($1 in a){
  print $0,a[$1]
}
'   Input_file2  FS="="  Input_file1

Explanation: Adding detailed explanation for above code.
awk '                   ##Starting awk program from here.
BEGIN{                  ##Starting BEGIN section from here.
  OFS="="               ##Setting OFS as = here for all lines.
}
FNR==NR{                ##Checking condition if FNR==NR which will be TRUE when file2 is being read.
  a[$1]=$NF             ##Creating an array a with index $1 and value is last field.
  next                  ##next will skip all further statements from here.
}
($1 in a){              ##Checking condition if $1 of current line is present in array a then do following.
  print $0,a[$1]        ##Printing current line and value of array a with index $1.
}
'  file2 FS="=" file1   ##Mentioning Input_file file2 and file1 and setting FS="=" for file1 here.

A: Or another approach with awk that stores the file2 values in an array and then appends the correct state to the appropriate line in file1:
awk -F' = ' 'NR==FNR {a[$1]=$2; next} {print $0"="a[$1]}' file2 FS="=" file1

Example Use/Output
$ awk -F' = ' 'NR==FNR {a[$1]=$2; next} {print $0"="a[$1]}' file2 FS="=" file1
ABC=14.2.0.7.SAMPLE=git.xyz/plugins/gitiles/+/refs/heads/clientpatch/abc/patch142007=closed
DEF=14.3.0.5.SAMPLE=git.xyz/plugins/gitiles/+/refs/heads/clientpatch/def/patch143005=open
DEF=14.3.0.5.SAMPLE2=git.calypso/plugins/gitiles/+/refs/heads/clientpatch/def/patch14300-calib=open
HIJ=12.0.0.0.Sp3.SAMPLE3=git.xyz/plugins/gitiles/+/refs/heads/clientpatch/hij/patch120000sp3=open
MNO=16.1.0.28.SAMPLE=git.xyz/plugins/gitiles/+/refs/heads/clientpatch/mno/patch161028=closed

redpajama_set_name: RedPajamaStackExchange


text:
Q: Convert float to rounded decimal equivalent When you convert a float to Decimal, the Decimal will contain as accurate a representation of the binary number that it can. It's nice to be accurate, but it isn't always what you want. Since many decimal numbers can't be represented exactly in binary, the resulting Decimal will be a little off - sometimes a little high, sometimes a little low.
>>> from decimal import Decimal
>>> for f in (0.1, 0.3, 1e25, 1e28, 1.0000000000001):
    print Decimal(f)

0.1000000000000000055511151231257827021181583404541015625
0.299999999999999988897769753748434595763683319091796875
10000000000000000905969664
9999999999999999583119736832
1.000000000000099920072216264088638126850128173828125

Ideally we'd like the Decimal to be rounded to the most likely decimal equivalent.
I tried converting to str since a Decimal created from a string will be exact. Unfortunately str rounds a little too much.
>>> for f in (0.1, 0.3, 1e25, 1e28, 1.0000000000001):
    print Decimal(str(f))

0.1
0.3
1E+25
1E+28
1.0

Is there a way of getting a nicely rounded Decimal from a float?

A: It turns out that repr does a better job of converting a float to a string than str does. It's the quick-and-easy way to do the conversion.
>>> for f in (0.1, 0.3, 1e25, 1e28, 1.0000000000001):
    print Decimal(repr(f))

0.1
0.3
1E+25
1E+28
1.0000000000001

Before I discovered that, I came up with a brute-force way of doing the rounding. It has the advantage of recognizing that large numbers are accurate to 15 digits - the repr method above only recognizes one significant digit for the 1e25 and 1e28 examples.
from decimal import Decimal,DecimalTuple

def _increment(digits, exponent):
    new_digits = [0] + list(digits)
    new_digits[-1] += 1
    for i in range(len(new_digits)-1, 0, -1):
        if new_digits[i] > 9:
            new_digits[i] -= 10
            new_digits[i-1] += 1
    if new_digits[0]:
        return tuple(new_digits[:-1]), exponent + 1
    return tuple(new_digits[1:]), exponent

def nearest_decimal(f):
    sign, digits, exponent = Decimal(f).as_tuple()
    if len(digits) > 15:
        round_up = digits[15] >= 5
        exponent += len(digits) - 15
        digits = digits[:15]
        if round_up:
            digits, exponent = _increment(digits, exponent)
    while digits and digits[-1] == 0 and exponent < 0:
        digits = digits[:-1]
        exponent += 1
    return Decimal(DecimalTuple(sign, digits, exponent))

>>> for f in (0.1, 0.3, 1e25, 1e28, 1.0000000000001):
    print nearest_decimal(f)

0.1
0.3
1.00000000000000E+25
1.00000000000000E+28
1.0000000000001

Edit: I discovered one more reason to use the brute-force rounding. repr tries to return a string that uniquely identifies the underlying float bit representation, but it doesn't necessarily ensure the accuracy of the last digit. By using one less digit, my rounding function will more often be the number you would expect.
>>> print Decimal(repr(2.0/3.0))
0.6666666666666666
>>> print dec.nearest_decimal(2.0/3.0)
0.666666666666667

The decimal created with repr is actually more accurate, but it implies a level of precision that doesn't exist. The nearest_decimal function delivers a better match between precision and accuracy.

A: I have implemented this in Pharo Smalltalk, in a Float method named asMinimalDecimalFraction.
It is exactly the same problem as printing the shortest decimal fraction that would be re-interpreted as the same float/double, assuming correct rounding (to nearest).
See my answer at  Count number of digits after `.` in floating point numbers? for more references


text:
Q: Retrieve UITextfField values and convert to inches with decimal? If I have formatting for a textfield like:
//Formats the textfield based on the pickers.
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {

NSString *result = [feetArray objectAtIndex:[feetPicker selectedRowInComponent:0]];

result = [result stringByAppendingFormat:@"%@ft", [feetArray objectAtIndex:[feetPicker selectedRowInComponent:1]]];
result = [result stringByAppendingFormat:@" %@", [inchArray objectAtIndex:[inchesPicker selectedRowInComponent:0]]];
result = [result stringByAppendingFormat:@"%@", [inchArray objectAtIndex:[inchesPicker selectedRowInComponent:1]]];
result = [result stringByAppendingFormat:@" %@in", [fractionArray objectAtIndex:[fractionPicker selectedRowInComponent:0]]];

myTextField.text = result;
}

Which display's in the textfield like 00ft 00 0/16in How can I change that all to inches with decimal? I'll need to take the ft, and multiply by 12 = variable.Then add that to inches, as well as take my fraction 1/16 and divide that by 16 to get my decimal value and then add that to the inches so it shows like 1234.0625 in order to make my calculation. Can someone help me accomplish this? Thank you in advance!

A: NSString * theString = RiseTextField.text;
NSString * feetString = [theString substringWithRange:NSMakeRange(0, 2)];
NSString * inchesString = [theString substringWithRange:NSMakeRange(5, 2)];
NSUInteger rangeLength = ([theString length] == 14) ? 1 : 2;
NSString * fractionString = [theString substringWithRange:NSMakeRange(8, rangeLength)];

double totalInInches = [feetString doubleValue] * 12 + [inchesString doubleValue] + [fractionString doubleValue] / 16;

A: You can easily get the number that you want by doing the calculations with the numbers you have there. Once you've got the actual number, you should use a NSNumberFormatter to present it with the desired amount of decimals and format.
This should solve your problem. Or did you need help converting the strings to numbers so that you can add them together?


text:
Q: Handshake error in client : CERTIFICATE_VERIFY_FAILED Self signed certificate in flutter I am making an https post Request from my flutter app. as there I am using a self signed SSL certificate in server so when I hit the API I am receiving status code as 405, that I am not able to connect,
If I used HTTP package, I am getting bellow exception,
HandshakeException: Handshake error in client (OS Error: I/flutter ( 7107): CERTIFICATE_VERIFY_FAILED: self signed certificate(handshake.cc:352))

when I tried with deo package I am getting 405 status code, below is the code for that,
Response response;
    final Dio dio = Dio();
    (dio.httpClientAdapter as DefaultHttpClientAdapter).onHttpClientCreate =
    (HttpClient client) {
  client.badCertificateCallback =
      (X509Certificate cert, String host, int port) => true;
  return client;
};
  response = await dio.post(loginURL, data: {"username": username, "password": password});
  print(response.data.toString());
  print(response.statusCode);

I tried to avoid the SSL handshake by making
 client.badCertificateCallback =
          (X509Certificate cert, String host, int port) => true;

Still its not working any other solution?

A: This works for me
void main() {
  HttpOverrides.global = new MyHttpOverrides();
  runApp(MyApp());
}

class MyHttpOverrides extends HttpOverrides{
  @override
  HttpClient createHttpClient(SecurityContext context){
    return super.createHttpClient(context)
      ..badCertificateCallback = (X509Certificate cert, String host, int port)=> true;
  }
}

class MyApp extends StatelessWidget {
.....

A:     DioForNative dio = DioForNative();
    DefaultHttpClientAdapter httpClient = dio.httpClientAdapter;
    httpClient.onHttpClientCreate = (HttpClient client) {
      client.badCertificateCallback =
          (X509Certificate cert, String host, int port) {
        return true;
      };
    };

and then you  can make dio.post and dio.get requests.

A: As previously mentioned in the comments, the HTTP request gets through since it returns a 405 error. HTTP error 405 usual points is usually defined as "Method not allowed", and commonly caused by incorrect request method. You may want to check with the server if it can receive the request that you're sending.


text:
Q: @include makes empty line above my navbar I want to include script in head of every blade.php. I tried that with @include but then that makes and empty row above mine navbar. That script doesn't contain anything else but .
Here is the screenshot.
Picture
Here is the code.
<head>
    <meta charset="utf-8">
    <title>Company listing</title>
    @include('includes.script');
  </head>

A: I found the mistake. When you put ';' at the end of include it will add that empty row. After deleting it there is no more empty row.
<head>
    <meta charset="utf-8">
    <title>Company listing</title>
    @include('includes.script')
  </head>


text:
Q: knockout js , for each loop issue with custom array I'm trying to get color_name from colors.standard.
I have try as given below html but both are showing same array.
HTML - not working

HTML Not Working

Console
JS Array:
{
    "style_id": "3",
    "name": "Rockford",
    "colors": {
        "standard": {
            "27": {
                "style_id": "3",
                "color_id": "27",
                "color_name": "White",
                "color_group": "1",
                "sort_order": "2",
                "defaultStyleId": "4"
            },
            "28": {
                "style_id": "3",
                "color_id": "28",
                "color_name": "Cloud White",
                "color_group": "1",
                "sort_order": "1",
                "defaultStyleId": "4"
            }
        },
        "doorcolor": {
            "18": {
                "style_id": "3",
                "cabinet_line_id": "1",
                "door_id": "1",
                "meta_keywords": null,
                "meta_description": null,
                "price_id": "3",
                "color_id": "18",
                "color_name": "Carbon",
                "color_group": "2",
                "sort_order": "8"
            }
        },
       }
    }
}

How can i get color_name from colors.standard?
for now it's showing array, if i add one more foreach loop it's still giving array.

A: Knockout's foreach needs an iterable to be able to repeat the template you give it and render its UI.
Javascript objects are not iterable by default. Your colors.standard property holds an object, so knockout does not know how to loop it.
In this particular case, you probably want to loop over the values of your object. To get an array of the object's values, you can use:
data: Object.values(column.colors.standard)
Other strategies could be:

*

*Loop over an object's keys by using Object.keys

*Loop over an object's entries ([key, value] pairs) by using Object.entries
Note that the order of the values/keys/entries typically relies on the order in which they were defined. Unlike arrays, an object doesn't let you easily re-order. That's why you often see a .sort chained behind Object.values.


text:
Q: How do you tell the Visual Studio project type from an existing Visual Studio project Using Visual Studio 2005.
Is there anything in the .sln or .vcproj files (or anywhere else) that defines the project type / subtype?
Edit: What I mean is that when you create a project, you first choose a language (e.g. Visual C#), then a project type (e.g. Windows) and then a subtype (e.g. Console Application).
Where is this information stored within the VS files?

A: *

*Right Click on Project of a solution.

*Open Properties -> Application Tab.

*On the right you can see 'Output Type' which defines your project type of an existing solution.

A: In the project XML files:
Console applications contain:
<OutputType>Exe</OutputType>

WinForms applications contain:
<OutputType>WinExe</OutputType>

Library (.dll) projects contain:
<OutputType>Library</OutputType>

and do NOT contain a
<ProjectTypeGuids>

ASP.NET and WCF projects contain:
<ProjectTypeGuids>{603c0e0b-db56-11dc-be95-000d561079b0};{349c5851-65df-11da-9384-00065b846f21};{fae04ec0-301f-11d3-bf4b-00c04f79efbc}</ProjectTypeGuids>
<OutputType>Library</OutputType>

The GUIDs do something to define exactly what type of project it is. The ones above were taken from an ASP.NET app.  They exist in WCF projects too, and flipping around the GUIDs can fool Vis Studio into changing the project type when you open it.

A: Some further research and I found this:
INFO: List of known project type Guids.
My .sln file contains:
Visual Studio 2005
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AddNumbers", "AddNumbers.csproj", "{2C81C5BB-E3B0-457E-BC02-73C76634CCD6}"
The link shows:
Project Type Description Project Type Guid
Windows (C#) {FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}
So it's Windows C# and the subtype is as per @HardCode's reply. In my case, it's "Console Application".

A: The .vproj file defines the project type, for example, the following defines a C++ project.
<VisualStudioProject
   ProjectType="Visual C++"

The project tag also includes the compiler version.

A: Double-click on "My Project" in the Solution Explorer, and look at the "Application type:" ComboBox. It tells you (and lets you change) the project type.

A: Easy solution.
If you want to know if it's a WCF Project or ASP.NET Web Service simply open your project's folders in File Explorer. You can hover over the icon with your mouse and a tooltip will display the project type as shown in the picture. Also, you can look under the Type column in File Explorer and it shows it there as well.
WCF Web Service Project:

ASP.NET Web Service Project:

Also to note, if your project has a Resources.Designer.cs or Settings.Designer.cs in its Properties folder it's likely a WinForms application.

A: If you are interested in finding subtypes of a project i.e. Under C# Windows Project Category, checking whether it is a Windows Form Application or WPF
Try adding new item in the project and it will show you the items specific to that project type along with default options.
For instance if there is a WPF project it shows the WPF related options like 'Window' , 'Page' 'User Control' ... In case of Window Form Application it Shows 'Window Form' etc.....

A: Follow:
Solution Explorer -> hover/right click over your project item ( not the project folder. Check the Properties view to find if you clicked on the folder or the project) -> Properties.
Then all information is available for the project.

A: Right click on solution and click open folder in file explorer. Navigate to Project file. hover on it, tool tip displays the type of project file.


text:
Q: Returning pointer to an array of struct with single or double pointer The objective of my code is as follows:

*

*Return a pointer to the array of innerStruct either through single or double pointer (I believe I should use double pointer)

*Pass that pointer to a function that modifies the value
It seems that I get a seg fault in the online compiler.
#include <stdio.h>

typedef struct
{
    int innerVal;

} innerStruct;

typedef struct
{
    int           a;
    innerStruct * inner[3];

} myStruct;

static myStruct * m1;

innerStruct ** getInnerPtrToArray()
{
    return &(m1->inner);
}

void processInnerStruct(innerStruct * array_ptr[])
{
    for(int i=0; i<3; i++)
    {
        array_ptr[i]->innerVal = i;
    }
}

int main()
{
    innerStruct ** array_ptr = getInnerPtrToArray();
    processInnerStruct(array_ptr);

    return 0;
}

Online compiler: https://onlinegdb.com/r1z0DPICb

A: Since inner is an array of pointers, you need to allocate memory for them to point to. You also need to allocate memory for m1 to point to.
int main()
{
    m1 = malloc(sizeof(myStruct));
    for (int i = 0; i < 3; i++) {
        m1->inner[i] = malloc(sizeof(innerStruct));
    }
    innerStruct ** array_ptr = getInnerPtrToArray();
    processInnerStruct(array_ptr);

    return 0;
}

A: Here is a second cut on what you were doing. Rather than allocating, you can also change myStruct to simply contain an array of innerStruct rather than an array of pointers to innerStruct. Then no allocation is needed, e.g.
#define NINNER 3    /* if you need a constant, define one */
...
typedef struct {
    int           a;
    innerStruct inner[NINNER];   /* you are not allocating */
} myStruct;

note: avoid the use of globals, they are not needed. Declare your variables in main() and pass as parameters as required.
Putting it altogether, adjusting types as required, and including further notes as comments in-line below, you could do something like the following:
#include <stdio.h>

#define NINNER 3    /* if you need a constant, define one */

typedef struct {
    int innerVal;
} innerStruct;

typedef struct {
    int a;
    innerStruct inner[NINNER];   /* you are not allocating */
} myStruct;

/* takes pointer to m1, returns address of array of 3 innerStruct */
innerStruct *getInnerPtrToArray (myStruct *innerptr)
{
    return innerptr->inner;
}

/* takes pointer to array of innerStruct, fills */
void processInnerStruct (innerStruct *array_ptr)
{
    for (int i = 0; i < NINNER; i++)
        array_ptr[i].innerVal = i;
}

int main (void) {

    myStruct m1 = { .a = 10 };  /* don't use globals */
    /* pass the address of m1 */
    innerStruct *array_ptr = getInnerPtrToArray (&m1);
    processInnerStruct (array_ptr);

    printf ("m1.a: %d\n", m1.a);        /* output values */
    for (int i = 0; i < NINNER; i++)
        printf ("  .inner[%d]: %d\n", i, m1.inner[i].innerVal);

    return 0;
}

Example Use/Output
$ ./bin/inner
m1.a: 10
  .inner[0]: 0
  .inner[1]: 1
  .inner[2]: 2

It's up to you to determine whether you intended to allocate for each of the 3 innerStruct in myStruct, but from my reading of what you were attempting to do, and with no stdlib.h included, it appeared your intent was to handle the array without allocation. Let me know if you have further questions.


text:
Q: kapt doesn't resolve protobuf-generated classes I get such error during the build:
e: /Users/some/path/SomeClass.java:86: error: cannot find symbol
e:
e:     static ConnectionType getConnectionType(Context context) {
e:            ^
e:   symbol:   class ConnectionType
e:   location: class SomeClass

Where ConnectionType is class generated by protobuf. So it looks like kapt doesn't resolve generated classes.
What I've tried?
At first I added kotlin-apt plugin:
apply plugin: 'kotlin-kapt'

Then I added brotobuf-generated classes to source set:
sourceSets {
    main.java.srcDirs += 'src/main/kotlin'
    main.java.srcDirs += 'build/generated/source/proto/main/java'
}

And also I want to have generated classes before kapt starts it's work. So I order gradle tasks this way:
afterEvaluate {
    def protoTasks = []
    tasks.each { task ->
        if (task.name.contains('proto') || task.name.contains('Proto')) {
            protoTasks.push(task)
        }
    }

    tasks.each { task ->
        if (task.name.startsWith('kapt')) {
            task.dependsOn protoTasks
        }
    }
}

But all these things don't help, I still got the same error. How to solve it?

A: The error was caused by wrong path to protobuf source set. I had to use correct flavor name in it, like:
sourceSets {
    // ...
    main.java.srcDirs += 'build/generated/source/proto/flavor/java'
}

instead of
sourceSets {
    // ...
    main.java.srcDirs += 'build/generated/source/proto/main/java'
}

A: No need to specify the sourceDir, if you want do so, you must specify all possible path which the Java file (maybe from Protobuf) or Kotlin file contained. In fact, the default sourceDir contains all possible paths.


text:
Q: django leaflet - adding/removing controls on HTML page button click I am currently using django-leaflet and leaflet-draw controls. I want to make the draw controls available (add to map) on a certain event such as a toggle button.
I currently have a simple jQuery skeleton:
$("#mode").on("click", function() {

    if(document.getElementById('mode').checked) {
        $("#save").removeClass("hidden");
        alert("Edit Mode");
        //event where I want to add controls to map
        //map.addControl(drawControl);

       } else {
        $("#save").addClass("hidden");
        alert("View Mode");
        //event where I want to remove controls from map
        //map.removeControl(drawControl);
    }
});

I have my map.js external from the html file and I call this in my template with only this line (as instructed in django-leaflet):
{% leaflet_map "mapdiv" callback="leafletinit" %}

Note: I also tried to include the drawControl variable available on the same page but I don't think I'm doing it correctly... My map.js is loading correctly as it does load the map and the controls on a straight forward no event view

A: Have you tried it without django?
Simply adding:
<Div id = 'map'> </ div>

Var map = L.map ( 'map')

I've never set the template variable in Django when it came to Leaflet. I keep the common "leaflet javascript" way for the best!
Especially when it comes to add some addons / plugins / extensions to Leaflet.
If you prefer Django, it would be good if you could publish your whole template (html)!


text:
Q: How to build a plot that evaluates the Xth percentile in R I have a single column data frame of race times called RaceTimes, with the data frame called R5.
I don't know what ggplot to use and how to get the percentile on the x-axis.


text:
Q: How to wrap a database function inside active record class in rails I have a Postgres database function with a signature account_lives('1', '1', '1'), I want to wrap the DB function under an active record class. any idea how I can do that? just make sure my Database function expects parameter.
I don't want to execute raw SQL from rails.

A: ActiveRecord doesn't have a specific interface for working with database functions. ActiveRecord::Calculations contains a few (very useful) wrappers  for aggregate functions like count(),max()/min() etc, but beyond that you're on your own. You can drop in your function call wherever AR allows you to substitute in SQL fragments, for example #select, #count, #group, #having etc, assuming the database allows the function to be used in that context.


text:
Q: Replace Helvetica Neue with a different font in firefox Is there a way to replace the font 'Helvetica Neue' with 'Verdana' in firefox via the userchrome.css, usercontent.css, or user.js? I find this font extremely hard to read without zooming the content. Thanks.

A: would -moz-font-family not work? I've never tried myself but you could give it a shot.


text:
Q: Java primitives support elimination? and exact purpose of retaining with new Java version release Though we move ahead with Java versions, why are we maintaining support of primitives ( which are not objects consitituting to not making 100% OOP language ).
Wrapper classes around the primitives comes with support of auto boxing & unboxing as well.
Few main reasons I could think of are :

*

*Though conversion happens automatically with (un)boxing support, behind the scenes it still does run .intValue() to get its associated primitive value to perform calculation & then stores back to its corresponding Integer object.
Integer a=3,b=5;
// Below will do a.intValue()+b.intValue() & then store/display, if I am correct.
System.out.println(a+b);

And also using wrapper class objects consumes heap space as opposed to performing arithematic operations using primitives on stack space.

*

*I read something stating : its for support of some Enumeration classes as a backward compatibility reason?

Is above listed reasons not leading to non-elimination / making deprecated on primitives usage?.


text:
Q: Cover div with child after child rotation I have a div containing an image, I want to rotate the image. After rotation the image should cover the parent div, overflow would be hidden. I have two pictures of what I get and what I want (lack of reputation doesn't allow me to embed the pictures):

.parent {
    position:relative;
    display:inline-block;
    width:100%;
    max-width:480px;
    overflow:hidden;
}

.background{
    width:100%;
    height:auto;
}

.grafic {
    position:absolute;
    z-index:1;
    top:0;
    left:0;
    width:100%;
    max-height:360px;
    height:auto;
    -webkit-transform: rotate(45deg);
    -moz-transform: rotate(45deg);
    -o-transform: rotate(45deg);
    -ms-transform: rotate(45deg);
    transform: rotate(45deg);
}

    <img class="grafic" alt="" src="img.gif"

As you can see, I can rotate the image, but the image isn't fully covering the parent div. I couldn't find anything to this exact problem.
Some thoughts:
One could use JQuery to calculate the necessary height/width to cover the parent div, but I hate using JS/JQuery if a pure CSS solution is possible (I can do a JS solution by myself, but I still suck at CSS).
I use PHP (I'll know the degree), so precalculating stuff can be done, but the parent div becomes smaller on smaller screens. A fix width would kinda suck then..

A: I can't think of CSS-only solution, so here's something with JS that I've used before.
You don't need to do the maths yourself in order to get the dimensions of your transformed object.
Instead you can use the Element.getBoundingClientRect() method which returns the height and width of the element after the transformation.
Once you have the dimensions, it should be easy to adapt the parent dimensions to fit the rotated image.
Here's a DEMO.
Also this other question has working solution which does what you want.
I hope it points you in the right direction.

A: I do not required reputation for posting a comment so I am posting as a comment. I am only addressing the sizing options for the image.
Say your image has width=w and height=h. Then if the size of the outer quadrilateral will have size
sqrt(w*w + h*h)

. Please note that the outer image will not be a square if inner image is not a square.


text:
Q: Обработка возврата на шаг назад между двумя активити Подскажите пожалуйста, как можно избежать следующей ошибки: При нажатии на стандартную клавишу "Back" возврата на шаг назад эмулятора или смартфона приложение вылетает.
Лог пишет:
java.lang.NullPointerException
В коде подчёркивает вот эту строку - if (myWebView.canGoBack() == true) {
public class FourActivity extends Activity implements OnClickListener {

WebView myWebView;
public static String ONE = "ONE";
final String LOG_TAG = "myLogs";

@SuppressLint("SetJavaScriptEnabled")
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_third);

    // Получаем данные от деятельности ThirdActivity
    Intent intent = getIntent();
    int one = intent.getIntExtra(ONE, R.raw.money);

    WebView myWebView = (WebView) findViewById(R.id.webView);

    WebSettings settings = myWebView.getSettings();
    settings.setDefaultTextEncodingName("utf-8");
    myWebView.getSettings().setLayoutAlgorithm(
            WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
    myWebView.setBackgroundColor(0x00000000);
    myWebView.setLayerType(WebView.LAYER_TYPE_SOFTWARE, null);
    myWebView.getSettings().setCacheMode(
            WebSettings.LOAD_CACHE_ELSE_NETWORK);
    myWebView.getSettings().setJavaScriptEnabled(true);
    myWebView.getSettings().setBuiltInZoomControls(true);
    myWebView.getSettings().setSupportZoom(true);
    myWebView.getSettings().setDomStorageEnabled(true);

    myWebView(getResources().getString(one));

    // получаем контекст
    Context context = getBaseContext();
    String text_one = readRawTextFile(context, one);

    // Получаем доступ к WebView и загружаем туда HTML страницу
    String sum_one = "<!Doctype html><meta charset=utf-8>"
            + text_one + "";

    myWebView
            .loadDataWithBaseURL(null, sum_one, "text/html", "utf-8", null);

}

private void myWebView(String string) {
    // TODO Auto-generated method stub
}

// читаем текст из raw
public static String readRawTextFile(Context ctx, int resId) {
    InputStream inputStream = ctx.getResources().openRawResource(resId);

    InputStreamReader inputreader = new InputStreamReader(inputStream);
    BufferedReader buffreader = new BufferedReader(inputreader);
    String line = null;
    StringBuilder text = new StringBuilder();

    try {
        while ((line = buffreader.readLine()) != null) {
            text.append(line);
            text.append("<!Doctype html><meta charset=utf-8>"
                    + "");
        }
    } catch (IOException e) {
        return line;
    }
    return text.toString();
}

// обработка возврата на шаг назад
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (event.getAction() == KeyEvent.ACTION_DOWN) {
        switch (keyCode) {
        case KeyEvent.KEYCODE_BACK:
            if (myWebView.canGoBack() == true) {
                myWebView.goBack();
            } else {
                finish();
            }
            return true;
        }

    }
    return super.onKeyDown(keyCode, event);
}

public void onClick(View v) {
    finish();
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // добавляем элементы в акшион бар
    getMenuInflater().inflate(R.menu.third, menu);
    return true;
}

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
    // Проверяем ориентацию экрана
    if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {

    } else if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {

    }
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {

    case R.id.item_1: {
        Intent intent = new Intent(this, FirstActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
                | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        setResult(RESULT_OK, intent);
        startActivity(intent);
        return false;
    }
    default:
        return super.onOptionsItemSelected(item);

    }

}

public WebView getMyWebView() {
    return myWebView;
}

public void setMyWebView(WebView myWebView) {
    this.myWebView = myWebView;
}

public String getLOG_TAG() {
    return LOG_TAG;
}

public static String getONE() {
    return ONE;
}

public static void setONE(String oNE) {
    ONE = oNE;
}

A: @Override
public void onBackPressed() {
    if (webview.canGoBack()) {
        webview.goBack();
    } else {
        super.onBackPressed();
    }
}

A: замените
WebView myWebView = (WebView) findViewById(R.id.webView);

на
myWebView = (WebView) findViewById(R.id.webView);

Локальная переменная у вас имеет то же имя что и переменная класса.


text:
Q: Javascript function not working properly in Safari 5.1.7 On Load of Access.aspx a javascript function is called.
<head>
<title>access</title>
<meta content="Microsoft Visual Studio .NET 7.1" name="GENERATOR">
<meta content="Visual Basic .NET 7.1" name="CODE_LANGUAGE">
<meta content="JavaScript" name="vs_defaultClientScript">
<meta content="http://schemas.microsoft.com/intellisense/ie5" name="vs_targetSchema">
<link href="rtsBanner.css" type="text/css" rel="stylesheet">

<script language="JavaScript" type="text/javascript" src="winopen.js"> </script>

<script type="text/javascript" language="javascript">
    function openLogin(site, pass) {
        var loginUrl = 'login.aspx';
        if (site != '' && pass != '') {
            loginUrl += '?SITE=' + site + '&PASS=' + pass;
        }
        else if (site != '') {
            loginUrl += '?SITE=' + site;
        }
        var popUpFeatures = 'dialogHeight: 385px; dialogWidth: 600px; edge: Raised; center: Yes; help: No; resizable: No; scroll: Yes; status: No;';
        var RetVal = window.showModalDialog(loginUrl, 'null', popUpFeatures);
        if (typeof (RetVal) == 'undefined') {
            top.window.close();
        }
        else {
            var RetArray = RetVal.split(',')
            var ValidLogon = RetArray[0];
            var MUName = RetArray[1];
            if (ValidLogon == 1) {
                document.location.href = 'newRequest.aspx?desc=' + MUName;
            }
            else {
                top.window.close();
            }
        } // else(typeof(RetVal)
    }
</script>

</head>
<body ms_positioning="GridLayout" onload="openLogin('<%=Request("SITE")%>','<%=Request("PASS")%>');">
<form id="Form1" method="post" runat="server">

</form>
</body>
</html>

This code works perfectly in IE but in safari on the login screen after I enter site name and password and hit login button it doesn't redirect me to the newRequest.aspx page instead just closes the login popup and shows a blank access.aspx page.
Editted:
This is the code on btnLogin_Click on Login.aspx.vb page
If txtSiteName.Text = "" And txtPassPhrase.Text = "" Then Return
        If ValidateSiteAndPass(txtSiteName.Text, txtPassPhrase.Text) = False Then
            Throw New Exception("OOPS!!! Either SiteName or Pass Phrase is Invalid, please check")
        Else
            Session("valid") = "true"
            Response.Write("<script language='javascript'>{window.returnValue='1," + txtSiteName.Text + "'; self.close();}</script>") '''document.Form1.submit();")
            Response.End()
        End If

Please suggest
Thanks,
Kavita

A: I found the solution here.
http://forums.asp.net/t/1400811.aspx/1
The problem was due to window.showModalDialog. It doesn't work properly in Safari.. I replaced it with window.open
Thanks,
Kavita


text:
Q: Game Simulation in Java im kinda new in java and im doing an multithtreading resource-game where i have 3 classes.

*

*
Playground class (where resources are held ...gold,wood,food)

*
Animat class (where i have animats that use the resources when i want to)

*
Game(Main) class (to run the game)

Can anyone tell me how can i use a thread so i can make an Animat reduce Resources from the playground class?
...Actually i want to know if i can make threads to run methods and how...

A:  The Thread type
A thread is another execution call, that runs in parallel to the thread that called it. Every Java program starts out with the main thread. Here is the documentation.
 Writing a class to use the Thread type
When you write your class, you can attach the keyword extends to the header, along with the class name. In this case, Thread.
public class A extends Thread

At this point, you'll be asked to implement a method, run. This is the loop that will be executed for the lifetime of the thread.
public void run()
{
    // Some code.
}

 In your case
You want to use resources from another class, so it might be wise to pass in a reference to this other class, via A's constructor.
public A(Playground playground)
{
    this.playground = playground;
    // Assumes a field of type Playground called playground.
}

In your run method, you'll want to be decrementing some values. This is nice and simple.
public void run()
{
    while(gameIsNotOver)
    {
        // Loop assumes some boolean value, gameIsNotOver.
        playground.methodCall();
        // Call some method that will perform the requested calculations on the values.
    }
}

 Using the thread
In your main class, when you want to start this thread, do NOT call the run method. This will not start an asynchronous execution. You should call the start method. This will start the thread, and it will begin decrementing values.


text:
Q: Save multiple custom UIImageViews I was recently examining the project "Demo Photo Board" found here.
This is a simple demonstration of adding UIImageViews to the screen that have UIGestureRecognizers added to them...allowing the user to manipulate the various UIImageViews.
I add the view like so:
    - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {

UIImage *image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];

imageview = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, image.size.width, image.size.height)];
imageview.userInteractionEnabled = YES;
[imageview setImage:image];

UIPinchGestureRecognizer *pinchRecognizer = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(scale:)];
[pinchRecognizer setDelegate:self];
[imageview addGestureRecognizer:pinchRecognizer];

UIRotationGestureRecognizer *rotationRecognizer = [[UIRotationGestureRecognizer alloc] initWithTarget:self action:@selector(rotate:)];
[rotationRecognizer setDelegate:self];
[imageview addGestureRecognizer:rotationRecognizer];

UIPanGestureRecognizer *panRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(move:)];
[panRecognizer setMinimumNumberOfTouches:1];
[panRecognizer setMaximumNumberOfTouches:1];
[panRecognizer setDelegate:self];
[imageview addGestureRecognizer:panRecognizer];

[self.view addSubview:imageview];  }

I can even save the view like so:
NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:[NSKeyedArchiver archivedDataWithRootObject:imageview] forKey:@"imageViewSaved"];

Now my question: The following method saves only the last imageview added to the screen. Anyone know how to save all of the imageviews that are on the screen...if the user adds more than one?

A: I really don't think you want to be saving the entire UIImageView object to the user defaults. Instead, try saving a list of UIImage objects, which will be much more lightweight. (And which make much more sense to serialize.)
You can do this like so:
NSUserDefaults *defs = [NSUserDefaults standardUserDefaults];
NSArray *savedArray = [defs objectForKey:@"SAVED_IMAGES"];
// Create a mutable version in case the serialized copy is an NSArray
NSMutableArray *mutableImages = savedArray ? [NSMutableArray arrayWithArray:savedArray] : [NSMutableArray array];
[mutableImages addObject:image];
[defs setObject:mutableImages forKey:@"SAVED_IMAGES"];
[defs save];

A: To distinguish the UIImageViews on the screen you can do the following.
Define the start ImageView Tag number
#define kImageViewTag 3000

Define an instance var for number of images added to the screen.
NSUInteger numberOfImage = 0

Whenever you create a new UIImageView, increase the count and add it with the kImageViewTag and assign it to the tag property.
imageview = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, image.size.width, image.size.height)];
imageview.userInteractionEnabled = YES;
[imageview setImage:image];
numberOfImage += 1;
imageView.tag = kImageViewTag + numberOfImage;

Whenever you enumerate the screen subviews, if the class is UIImageView with the tag >= kImageViewTag, you know those are the images added to the screen from the UIImagePickerController.


text:
Q: PHP 7 PSR-7 response test if script can resize image with GD in conditions of limited memory I use PHP 7.1 with GD library.
My script downloads images and resizes it before saving. Server has 256MB of memory (can't increase).
Some of images have large physical size (not file size), greater than 50Mpx. When I try to resize it with GD, memory limit error raises in this line:
<?php
$image = imagecreatefromjpeg($file);

Script gets images in form of PSR-7 HTTP-response. Before resizing image I need to test it if it's enough memory to resize image?
I've tried to test images by file size, but it discards images with ok physical size, but large file size:
<?php
$fileIsOk = (int)$response->getBody()->getSize() <= SOME_MAGIC_SIZE_IN_BYTES;
if ($fileIsOk) {
    // do the stuff
}

For example, my script fails with image 50.2Mpx 1.51MB, but ok with 3.6Mpx 1.02MB.
My idea is to test image by getting Mpx count:

So I need to test if script can resize image in conditions of limited memory based on Mpx count. How can I get it from PSR-7 response object?

A: You can convert the response body to string and use getimagesizefromstring() on that
<?php
$imageData = (string) $response->getBody();
[$width, $height] = getimagesizefromstring($imageData);
$px = $width * $height;


text:
Q: golang парсинг xml получить значение поля Как теперь мне прочитать само значение поля (не атрибут)? Это где циферки =)
package main

import (
    "encoding/xml"
    "fmt"
)

var xmlContent = `
<?xml version="1.0" encoding="UTF-8"?>
 <lists>
  <paragraph>
<list href="href12" listAtr="wwwww">2332</list>
<lists href="href13" listAtr="sssss">4554</lists>
<lists href="href21" listAtr="fffff">1111</lists>
<lists href="href22" listAtr="ggggg">1122</lists>
  </paragraph>
  <paragraph>
<list href="href12" listAtr="wwwww">2332</list>
    <lists href="href13" listAtr="sssss">4554</lists>
    <lists href="href21" listAtr="fffff">1111</lists>
    <lists href="href22" listAtr="ggggg">1122</lists>
  </paragraph>
</lists>
`

type lists struct {
    XMLName  xml.Name    `xml:"lists"`
    Paragraf []paragraph `xml:"paragraph"`
}

type paragraph struct {
    //XMLName  xml.Name
    ListTop  []List     `xml:"list"`
    ListsDoc []ListsStr `xml:"lists"`
}

type List struct {
    HrefList string `xml:"href,attr"`
    List     string `xml:"listAtr,attr"`
}

type ListsStr struct {
    HrefLists string `xml:"href,attr"`
    Lists     string `xml:"listAtr,attr"`
}

func main() {
    str := lists{}
    err := xml.Unmarshal([]byte(xmlContent), &str)
    if err != nil {
        panic(err)
    }
    fmt.Println(str)
    fmt.Println("\n-------")
    for inx, _ := range str.Paragraf {
        fmt.Println("Top: ", str.Paragraf[inx].ListTop)
        for _, k := range str.Paragraf[inx].ListsDoc {
            fmt.Println("Doc", k)
        }
        fmt.Println("-------\n")
    }

}

A: Попробуйте добавить в структуры List и ListsStr
Поле с атрибутом ",innerxml" или ",chardata", например
type ListsStr struct {
    HrefLists string `xml:"href,attr"`
    Lists     string `xml:"listAtr,attr"`
    Value    string `xml:",chardata"`
}

https://play.golang.org/p/sIKjkn9pZ0
https://golang.org/pkg/encoding/xml/#Unmarshal


text:
Q: How To: Delete a Facebook Test User I was wondering if anyone happened to know how to delete a facebook test user. I've been perusing through this site for quite awhile now and haven't been able to uncover anything related besides a single unanswered post regarding deleting a facebook test user associated with 2+ apps. Facebook now offers a UI within their dev site which allows this functionality; however, I'm trying to perform the same operation through a C# script utilizing the Graph API and issuing the relevant HTTP commands. Tried monitoring the requests made through the UI using netmon/Fiddler but wasn't able to uncover anything useful. Help, any & all will be greatly appreciated.

A: See https://developers.facebook.com/docs/test_users/ - the section marked 'Deleting':
https://graph.facebook.com/TEST_USER_ID?
  method=delete
  &access_token=TEST_USER_ACCESS_TOKEN (OR) APP_ACCESS_TOKEN

A: I was not able to get the TEST_USER_ACCESS_TOKEN to work. I did get the APP_ACCESS_TOKEN to work. Here is what worked for me.
https://graph.facebook.com/<TEST_USER_ID>?method=delete&access_token=<APP_ID>%7C<APP_ACCESS_TOKEN>

A: Use FB graph API as follows:
https://graph.facebook.com/v2.8/{test-user-id}?method=delete&access_token={user-access-token}
You should get the following response:
{"success":true}


text:
Q: Python typing for enum type in function argument I have this python enum
from enum import Enum

class TypeItem(Enum):
    ITEM_1 = 'revenue'
    ITEM_2 = 'net_income_after_taxes'

I want to use it as a function argument. The function will look something like this;
def function_use(type_item: TypeItem) -> None:
    return None

type_item: TypeItem is probably wrong. What should be the correct typing for TypeItem enum?
I am using python 3.7

A: I will answer my own question. Thanks to the comments from ForceBru and Georgy, the correct answer is already in the question.
def function_use(type_item: TypeItem) -> None:
    return None


text:
Q: What coordinate system does a depth texture use? I have a depth texture and I would like to know in which coordinate system are the values stored inside the depth texture. Homogeneous coordinates, camera coordinates, world coordinates or model coordinates?
I also would like to know what values are stored in the depth texture and what do they mean.
Thanks.

A: This should be a value in range [min, max] where min is either -1.0 or 0.0 and max is 1.0 though what you get from the texture might simply be an integer value which might need to be transformed (from 24-bit to 32-bit). If none confirms any of these you will need to test it yourself.
Anyway, these values min and max should represent the clipping planes so min = near and max = far due to the depth buffer optimisation. To get the true Z value from texture coordinate ZT then:
Z = near + ((far-near) * ((ZT-min)/(max-min)))

This Z then represents the distance from (0,0,0) from the user perspective this is the distance between object and the camera position.
Try looking for some literature.


text:
Q: Is there an advantage of using Firestore's "date" type over a number? In Firestore, you can store datetimes in their proprietary "date" format or as the number of milliseconds since 1970. The first one requires you to specifically call the toDate() method to turn it into a Date, but the second one is already widely accepted as a way of storing dates. Is there any advantage of using the first method as both methods provide the same functionality?

A: I assume you're referring to the Firestore ServerTimestamp. There is a great article written about this topic by Doug here
To sum it up:
The Firestore Timestamp gets calculated server side, ensuring that it captures the exact moment in time the server received the request. Since it's calculated on the server, it's also easy to write security rules without the worry of the end user manipulating the Timestamp they submit in their request.

A: Firestore's Timestamp type has microsecond (instead of millisecond) accuracy and (as Huydra also said in their excellent answer) can be set automatically to the current value by the server.
Typically the microsecond vs millisecond precision is not a big deal, but the ability to have the server set/validate the current time means you no longer have to depend on the client to send an accurate time (which in reality: they won't).


text:
Q: Defining ghost methods for attributes in Ruby on Rails I want to be able to dynamically add to when there is no corresponding attribute in the database
attr_accessor

This overwrote the attributes I currently had:
def method_missing(method, arg)
  self.class.attr_accessor.send(method) || super
end

I also tried loading the variables into the singleton class, but that gave me a 0 for 1 argument error.

A: That is you want?
def method_missing(method, *args)
  if method.to_s['=']
    self.define_singleton_method(method) do |*args|
      self.instance_variable_set("@#{method[0..-2]}", args.first)
    end
  else
    self.define_singleton_method(method) do
      self.instance_variable_get("@#{method}")
    end
  end
  self.send(method, *args) rescue super
end


text:
Q: REST Assured doesn't accept curly brackets Unable to use query in my Endpoint URL
I have tried using .queryParams() but it does not seem to work . I am getting the following error

java.lang.IllegalArgumentException: Invalid number of path parameters.
  Expected 1, was 0.Undefined path parameters are:
  cycle-id[12345];test.name[Validate_REST_Assured_Curly_Brackets].

Can someone help me out
almQuery=https://{almurl}/qcbin/rest/domains/{domain}/projects/{project}/test-instances?query={cycle-id[12345];test.name[Validate_REST_Assured_Curly_Brackets]}

Response response = RestAssured.given().relaxedHTTPSValidation()
.contentType("application/xml")
.cookie(cookie)             .get(getEntityEndpoint(almQuery)).then().extract().response();

A: This is how RestAssured implementation works. Whenever your url contains curly braces it will expect path param with for that. For example, if your url contains {project} you should provide a path param with name project.
The only way to avoid it is by manually encoding { and } characters in your url. You could use URLEncoder.encode(), but it will mess your other characters so try simply replacing all { and } with encoded values:
public class App {

  public static void main(String[] args) {
    String url = "http://www.example.com/path/{project}";
    String encoded = encodeUrlBraces(url);
    RestAssured.given()
        .when()
        .get(encoded);
  }

  private static String encodeUrlBraces(String url) {
    return url.replaceAll("\\{", "%7B").replaceAll("}", "%7D");
  }
}

Here's an answer for this from Rest Assured founder and contributor https://github.com/rest-assured/rest-assured/issues/682


text:
Q: how to use hough circles in cv2 with python? I have the following code and I want to detect the circle.
   img = cv2.imread("act_circle.png")
   gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
   circles = cv2.HoughCircles(gray,cv2.CV_HOUGH_GRADIENT)

it looks like it does not have the attribute and the error is the following
'module' object has no attribute 'CV_HOUGH_GRADIENT'

Does anybody know where this hidden parameters is?
Thanks

A: if you use OpenCV 3, then use this code :
img = cv2.imread("act_circle.png")
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
circles = cv2.HoughCircles(gray,cv2.HOUGH_GRADIENT) # change here

A: CV_HOUGH_GRADIENT belongs to the cv module, so you'll need to import that:
import cv2.cv as cv

and change your function call to
circles = cv2.HoughCircles(gray,cv.CV_HOUGH_GRADIENT)

Now in current cv2 versions:
import cv2
cv2.HOUGH_GRADIENT

A: In my case, I am using opencv 3.0.0 and it worked the following way:
circles = cv2.HoughCircles(gray_im, cv2.HOUGH_GRADIENT, 2, 10, np.array([]), 20, 60, m/10)[0]

i.e. instead of cv2.cv.CV_HOUGH_GRADIENT, I have used just cv2.HOUGH_GRADIENT.


text:
Q: SelectSingleNode method on XmlNode returns undefined value I have a simple xml, I created a XmlDocument out of it and used Xpath to fetch a node, I need to pass this node to other parts of the code where I may use further xpath functions on the XmlNode object to get other sub nodes. But in the code below
string xmlString = "<catalog><music><cds><cd><title>First Title</title><author>Author    1</author></cd><cd><title>Second Title</title><author>Author 2</author></cd></cds></music></catalog>";
XmlDocument xmlDocument = new XmlDocument();
xmlDocument.LoadXml(xmlString);
XmlNode musicNode = xmlDocument.SelectSingleNode("/catalog/music");
XmlNode cdsNode = musicNode.SelectSingleNode("/cds");

when I print the name of the musicNode, I am getting "music", so I assume that I have the  "music" node. So I again applied xpath expression "/cds" on the music node assuming I would get the "cds" XmlNode, but cdsNode in the code returns undefined value, but if I do
XmlNode cdsNode = musicNode.SelectSingleNode("/catalog/music");

I am getting a valid value for cdsNode that is the "music" node again, I suppose musicNode represents the XmlDocument instead of the "music" XmlNode??? Am I missing something, I am from Java and in Java navigating to subnodes from Node is possible using xpath, like an xpath expression "/cds" on the musicNode would have returned a valid cdNode

A: / will always go back to the root of the underlying XmlDocument, irrespective of the current node.
Drop the / and navigate a relative path, and you should be good, i.e.
XmlNode musicNode = xmlDocument.SelectSingleNode("/catalog/music");
XmlNode cdsNode = musicNode.SelectSingleNode("cds");

or just walk the whole path again
XmlNode cdsNode = xmlDocument.SelectSingleNode("/catalog/music/cds");


text:
Q: Can a binominal (or multinomial) coefficient be computed efficiently? It would seem that a preceding query would be on point, but not really for me.  One of the answers comes close, but it isn't complete as is.  Since the answer is going to be an integer, all the factors in the denominator will cancel.  Prime factors can be eliminated by any factor in the numerator that is a multiple.  The problem is composites; canceling them out may involve multiple numerator factors that share primes.  And there's the auxiliary problem of determining prime factors from composite ones (i.e. which composite factor(s) in the numerator should I cancel a composite factor in the denominator against).
I'm thinking of an analogy with computing the greatest common divisor of two positive integers.  You could determine GCD by breaking both arguments into their prime factorizations, then use the minimum exponent for each prime.  But using something like Euclid's algorithm is a lot easier.  For a multinomial coefficient, I could run a Sieve of Eratosthenes up to the numerator's maximum factor, use that table to get all the applicable prime factorizations, then do a bunch of cancelling, but that seems like a lot of work.  Is there a procedure similar to Euclid's GCD one that we can make for binomial coefficients?

A: Perhaps what you are looking for is Kummer's theorem. From the Wikipedia article:

Kummer's theorem states that for given integer $\,n\ge m\ge 0\,$ and a
  prime number $\,p\,$, the $p$-adic valuation $\,\nu_p({n \choose m})\,$
  is equal to the number of carries when $\,m\,$ is added to $\,n-m\,$ in
  base $\,p.\,$

All that is now needed to calculate $\,N:={n\choose m}\,$ is
the list of all primes $\,p\le n\,$ and thus
$$ N = \prod_{p\le n} p^{\nu_p(N)}. $$
It is well known (see multinomial theorem) that any multinomial coefficient is a
product of binomial coefficients and thus the $p$-adic valuation of a
multinomial coefficient is the sum of $p$-adic valuations of some
well defined binomial coefficents.
Of course, there are more elementary ways to compute binomial coefficients
without depending on prime factorizations. Just use one of several kinds
of recurrence relations. It all depends on your use case.

A: If you want to do this fast, use prime factorisation, Kummer's theorem, and a balanced multiplication strategy. See e.g. https://codegolf.stackexchange.com/q/37270/194
If you want to keep it simple, the decomposition $$\binom{n}{k} = \frac{n-k+1}{k} \binom{n}{k-1}$$ and variants give some simple loops which don't require keeping track of what to cancel. E.g.
result = 1
for i = 0 to k-1:
    result = result * (n-i) / (i+1)


text:
Q: Expand range to an undefined range I have a large number of xml files in one folder.
The below code, looks for specific xml files by searching a field in the XML file and comparing it to a range in the Excel sheet.
It then copies the matching xml files to a new folder and renames them for readability.
Everything is working, except very slow.
It looks at a very small range. I would like to extend the range to a pivot table with values from F4 and down, if there is data in the cells.
Global so1, so2, so3, so4, so5, so6, so7, so8, so9, so10, so11, so12, so13, so14, so15, so16, so17, so18 As String
Global Myfile As String
Global WholeOrderNumber As String
Global NewFile As String
Global Myfiletemp As String
Global FileName As String
Global TempFolder As String
Global OrderNumber As String
Global TempOrdernumber As String
Global TempMonth As String
Global Month As String

Sub Find_Delivery_XML()
'******************************************************************
'loop trough folder
'and locate ordre numbers in XML Files in range "C4" to "C21"
'if found then call loadXML and copyit to copy the files
'******************************************************************
 Application.EnableEvents = True
 Application.Calculation = xlCalculationAutomatic
 Application.ScreenUpdating = True

Worksheets("Main").Select ' pick Main sheet
so1 = Range("C4")
so2 = Range("C5")
so3 = Range("C6")
so4 = Range("C7")
so5 = Range("C8")
so6 = Range("C9")
so7 = Range("C10")
so8 = Range("C11")
so9 = Range("C12")
so10 = Range("C13")
so11 = Range("C14")
so12 = Range("C15")
so13 = Range("C16")
so14 = Range("C17")
so15 = Range("C18")
so16 = Range("C19")
so17 = Range("C20")
so18 = Range("C21")

'In Case of Cancel
NextCode:

  TempFolder = "C:\xml_found\"
  myPath = "C:\xml_all\"
  myExtension = "DK2W_PJ_SO_*.xml*"
  Myfile = Dir(myPath & myExtension)

'Loop through each file in folder
  Do While Myfile <> ""
  Myfiletemp = "C:\xml_all\" & Myfile

loadXML

If s18 = OrderNumber Then
  copyit
End If
If so17 = OrderNumber Then
  copyit
End If
If so16 = OrderNumber Then
  copyit
End If
If so15 = OrderNumber Then
  copyit
End If
If so14 = OrderNumber Then
  copyit
End If
If so13 = OrderNumber Then
  copyit
End If
If so12 = OrderNumber Then
  copyit
End If
If so11 = OrderNumber Then
  copyit
End If
If so10 = OrderNumber Then
  copyit
End If
If so9 = OrderNumber Then
  copyit
End If
If so8 = OrderNumber Then
  copyit
End If
If so7 = OrderNumber Then
  copyit
End If
If so6 = OrderNumber Then
  copyit
End If
If so5 = OrderNumber Then
  copyit
End If
  If so4 = OrderNumber Then
copyit
End If
If so3 = OrderNumber Then
  copyit
End If
If so2 = OrderNumber Then
  copyit
End If
If so1 = OrderNumber Then
  copyit
End If

DoEvents

Myfile = Dir

  Loop

  MsgBox "Done"

ResetSettings:
  'Reset Macro Optimization Settings
    Application.EnableEvents = True
    Application.Calculation = xlCalculationAutomatic
    Application.ScreenUpdating = True

End Sub

Sub loadXML()
'******************************************************************
'load XML files and get ordernumber from XML files
' located in = xobject.ChildNodes.Item(1).Text
'******************************************************************

Dim strPath As String
Dim XDoc As Object
Set XDoc = CreateObject("MSXML2.DOMDocument")
XDoc.async = False
XDoc.validateOnParse = False
XDoc.Load (Myfiletemp)
Set xObjDetails = XDoc.ChildNodes(0)
Set xobject = xObjDetails.FirstChild
TempOrdernumber = xobject.ChildNodes.Item(1).Text
TempMonth = xobject.ChildNodes.Item(2).Text
OrderNumber = Mid(TempOrdernumber, 8, 7)
WholeOrderNumber = TempOrdernumber
Month = Mid(TempMonth, 4, 2)
NewFile = WholeOrderNumber & "_" & Mid(Myfiletemp, 24, 27)

End Sub

Sub copyit()
'******************************************************************
'copy files to DIR "C2" and rename them to the new filename "NewFile"
'NewFile = WholeOrderNumber + "_" + last 27 characters of Myfiletemp
'******************************************************************
    Dim oFSO As Object
    Set oFSO = CreateObject("Scripting.FileSystemObject")
    Call oFSO.CopyFile(Myfiletemp, TempFolder & Range("C2") & "\" & NewFile, True)

End Sub

A: Maybe this will work, i just put the repeating parts of your code into loops...
Global so() As String
Global Myfile As String
Global WholeOrderNumber As String
Global NewFile As String
Global Myfiletemp As String
Global FileName As String
Global TempFolder As String
Global OrderNumber As String
Global TempOrdernumber As String
Global TempMonth As String
Global Month As String

    Sub Find_Delivery_XML()
Dim lastRow As long
Dim firstRow As long
Dim i as long
Dim col as long
'******************************************************************
'loop trough folder
'and locate ordre numbers in XML Files in column C
'if found then call loadXML and copyit to copy the files
'******************************************************************
 Application.EnableEvents = True
 Application.Calculation = xlCalculationAutomatic
 Application.ScreenUpdating = True

Worksheets("Main").Select ' pick Main sheet

firstRow = 4 '<----first row of data here, i put it to 4 because in your example it starts at C4
i = firstRow
col = 6 'Set Column Number here. Since F is number 6 in the Alphabet thats the default i set it to now
With Application.Worksheets("Main")
    Do Until .Cells(i, col) = "" and i > firstRow
        i = i + 1
    Loop
    lastRow = i - 1
    ReDim so(lastRow)

    For i = firstRow To lastRow
        so(i) = .Cells(i, col)
    Next i
End With

'In Case of Cancel
NextCode:

  TempFolder = "C:\xml_found\"
  myPath = "C:\xml_all\"
  myExtension = "DK2W_PJ_SO_*.xml*"
  Myfile = Dir(myPath & myExtension)

'Loop through each file in folder
  Do While Myfile <> ""
  Myfiletemp = "C:\xml_all\" & Myfile

loadXML

For i = firstRow To lastRow
    If so(i) = OrderNumber Then
      copyit
    End If
Next i

DoEvents

Myfile = Dir

  Loop

  MsgBox "Done"

ResetSettings:
  'Reset Macro Optimization Settings
    Application.EnableEvents = True
    Application.Calculation = xlCalculationAutomatic
    Application.ScreenUpdating = True

End Sub

Sub loadXML()
'******************************************************************
'load XML files and get ordernumber from XML files
' located in = xobject.ChildNodes.Item(1).Text
'******************************************************************

Dim strPath As String
Dim XDoc As Object
Set XDoc = CreateObject("MSXML2.DOMDocument")
XDoc.async = False
XDoc.validateOnParse = False
XDoc.Load (Myfiletemp)
Set xObjDetails = XDoc.ChildNodes(0)
Set xobject = xObjDetails.FirstChild
TempOrdernumber = xobject.ChildNodes.Item(1).Text
TempMonth = xobject.ChildNodes.Item(2).Text
OrderNumber = Mid(TempOrdernumber, 8, 7)
WholeOrderNumber = TempOrdernumber
Month = Mid(TempMonth, 4, 2)
NewFile = WholeOrderNumber & "_" & Mid(Myfiletemp, 24, 27)

End Sub

Sub copyit()
'******************************************************************
'copy files to DIR "C2" and rename them to the new filename "NewFile"
'NewFile = WholeOrderNumber + "_" + last 27 characters of Myfiletemp
'******************************************************************
    Dim oFSO As Object
    Set oFSO = CreateObject("Scripting.FileSystemObject")
    Call oFSO.CopyFile(Myfiletemp, TempFolder & Range("C2") & "\" & NewFile, True)

End Sub


text:
Q: Find the laurent series find the laurent series centered at $z=0$ for the rational functions below. Determine the largest open set in $C$ for which each series converges
  $$\frac{1}{(z^2-1)(z^2-4)}.$$
I have no idea how to do this.

A: $$\frac{1}{(z-1)(z+1)(z-2)(z+2)}=\frac{A}{z-1}+\frac{B}{z+1}+\frac{C}{z-2}+\frac{D}{z+2}\Longrightarrow$$
$$1=A(z+1)(z^2-4)+B(z-1)(z^2-4)+C(z+2)(z^2-1)+D(z-2)(z^2+1)$$
The last equality above is one between polynomials so it must be true for any values of $\,z\,$, so for example:
$$z=-2\Longrightarrow 1=-20D\Longrightarrow D=-\frac{1}{20}$$
$$z=2\Longrightarrow 1=12C\Longrightarrow C=\frac{1}{12}$$
and etc. Thus, you can develop around $\,z=0\,$ as, for instance:
$$\frac{2}{z+2}=\frac{1}{1+\frac{z}{2}}=1-\frac{z}{2}+\frac{z^2}{4\cdot2!}-\frac{z^3}{8\cdot 3!}+\ldots$$
The above is valid whenener $\displaystyle{\left|\frac{z}{2}\right|<1\Longleftrightarrow |z|<2}\,$ , and etc.
At the end "glue" everything together putting attention on the values of $\,z\,$ for which your development are valid.


text:
Q: clearing serial buffer in matlab i am simply printing there floats form my arduino or any other serial output device... in matlab i am receiving them and plotting them. it is being printed in arduino very fast but in matlab it is slower and after a a minute or so the plot is not reacting to the numbers from arduino fast... it seams matlab is slower and it is keeping the records in buffer? how can i clear it and get the fresh data plotted?
one more thing  does it make sense that matlab can't import and plot a few numbers in 100Hz? What i am doing wrong or inefficient ?
clc
clear all
h = figure(1);
set(h,'UserData',1);

s=serial('/dev/tty.usbmodem1411','BaudRate',115200);
set(s,'DataBits',8);
set(s,'StopBits',1);
fopen(s);
s.ReadAsyncMode='continuous';
readasync(s);
tStart = tic;
xplot=subplot(3,1,1);
hold on;
xlabel('time(ms)');
ylabel('X angle(deg)');
yplot=subplot(3,1,2);
hold on;
xlabel('time(ms)');
ylabel('Y angle(deg)');
zplot=subplot(3,1,3);
hold on;
xlabel('time(ms)');
ylabel('Z angle(deg)');

cont=true;
xAngle = zeros(1,1000000);
 yAngle = zeros(1,1000000);
zAngle = zeros(1,1000000);
i=0;
while(true)
i=i+1;
    t = toc(tStart);
%angle = fscanf(s, '%f');
[x y z] = strread(fgetl(s,s.BytesAvailable),'%f %f %f');
plot(xplot,t,x,'.');

plot(yplot,t,y,'.');

plot(zplot,t,z,'.');

drawnow;

end
   fclose(s);

A: It is likely that the speed of the 'plot' command is the problem. Creating a new plot is a slow operation, and so after you have received a few points, the time it takes to create the plot gets large. If you want to plot "real time" data in matlab, you will need to use some methods such as discussed in this question.
You can investigate the situation by changing your loop code to read data from the device and just print the line on the screen without plotting it. I expect you will see that the numbers can be printed as fast as they are received.


text:
Q: PowerAMC do simple action with script I'm a beginner in powerAMC.
PowerAMC offer to see and save a XSD file of your Model component :

I need to get automatically that XSD content for all models in the project. So I need to do it by script.
I can't find a way to get that content (XSD of the picture).
Anybody no a way ? By calling a PowerAmc Fonction ? Get a specific property of the model ? another way ?
Thx !

A: I guess that would the Preview (string) property, available for all NamedObject.


text:
Q: Cross-platform timezone serialization I need to save timezones - along with other data - to a file and read the file from multiple platforms (Linux, WinRT, Windows Phone 8, OS X, Android, iOS). Likely languages are C++, C#, Java, and Objective-C.
Saving the timezone offset as a double is insufficient for my needs, because this loses daylight savings information, which is important. Depending on the date and the timezone, 2 am + 2 hours could be 3 am, 4 am, or 5 am.
Is there a universally supported serializable timezone format?

A: It seems the best answer is to use IANA/Olson/TZDB time zones (which are supported on the Unix based systems), and convert them for the Windows-based platforms. 2-way conversion seems to be unreliable, so the most feasible option seems to be to replace the default datetime framework in .NET with NodaTime, as described in multiple related questions:

*

*Time Zone Mapping from iPad (Objective C) to MVP Web API (C#)

*How to translate between Windows and IANA time zones?

*Converting Olson TZID to Windows Time Zone

*How to convert a time zone information in C# to a time zone information in Java?


text:
Q: How can I create the detection for this javascript program of mine? I've been building on top of an assignment we did in class and I'm stumped at the detection part.
I want my Mew to be "caught" when he stands on top of the pokeball, the player moves the keyboard to control the Mew and the pokeball randomly repositions on a time delay.
How can I create a function that will detect when the mew.gif is in overlap with the pokeball?
var _stage = document.getElementById("stage");
var _Mew = document.querySelector("img");
var _PokeBall = document.getElementById("PokeBall");

_stage.style.width = "800px";
_stage.style.height = "600px";
_stage.style.backgroundColor = "black";
_stage.style.marginLeft = "auto";
_stage.style.marginRight = "auto";

_Mew.style.position = "relative"; // Uses top and left from parent
_PokeBall.style.position = "relative"; // Uses top and left from parent

var leftPressed = false;
var rightPressed = false;
var upPressed = false;
var downPressed = false;

var player = [ 400, 300 ]; // Left, Top
var PokeBall = [100, 100];// Top, Left
var uIval = setInterval(update, 22.22); // 30fps update loop

var map = [];  // empty Map Array

window.addEventListener("keydown", onKeyDown);
window.addEventListener("keyup", onKeyUp);
var Pval= setInterval(MovePokeball, 2000);

function generateMap()
{
    for (var row = 0; row < 2; row++)
    {
        for(var col = 0; col <8; col++)
        {
        console.log("In row "+row);
        }
    }
}
/*map[row] = []; // Creating new array in specified row
                for (var col = 0; col <8; col++)
                    {
                    console.log("In row "+row+"doing col"+col);
                    }
*/
function onKeyDown(event)
{
    switch(event.keyCode)
    {
        case 37: // Left.
                if ( leftPressed == false )
                    leftPressed = true;
                break;
        case 39: // Right.
                if ( rightPressed == false )
                    rightPressed = true;
                break;
        case 38: // Up.
                if ( upPressed == false )
                    upPressed = true;
                break;
        case 40: // Down.
                if ( downPressed == false )
                downPressed = true;
                break;
        default:
                console.log("Unhandled key.");
                break;
    }
}

function onKeyUp(event)
{
    switch(event.keyCode)
    {
        case 37: // Left.
                leftPressed = false;
                break;
        case 39: // Right.
                rightPressed = false;
                break;
        case 38: // Up.
                upPressed = false;
                break;
        case 40: // Down.
                downPressed = false;
                break;
        default:
                console.log("Unhandled key.");
                break;
    }
}

function update() // Going to run 30fps
{
    movePlayer();
    // move enemies
    // collision check
    // animate sprites
    PlayerCaught();
    render();
}

function movePlayer()
{
    if ( leftPressed == true && player[0] >= _Mew.width/2)
            player[0] -= 10;
    if ( rightPressed == true && player[0] < 800 - _Mew.width/2)
        player[0] += 10;
    if ( upPressed == true && player[1] >= _Mew.height/2 )
        player[1] -= 10;
    if ( downPressed == true && player[1] < 600 - _Mew.width/2)
        player[1] += 10;
}

function render()
{
    _Mew.style.left = player[0]-_Mew.width/2+"px";
    _Mew.style.top = player[1]-_Mew.width/2+"px";

}

function PlayerCaught()
{
    if (_PokeBall [100,100] = player [100,100])
    window.alert("Mew Has Been Captured!")

}

function MovePokeball()
{
    _PokeBall.style.left= Math.floor(Math.random()*801)+"px";
    _PokeBall.style.top= Math.floor(Math.random()*601)+"px";
}

A: You're asking about collision detection. This is done by determining if two polygons intersect. Since your program is very simplified, I'm offering a very simplified solution. We're going to determine if the graphics intersect. This is not the ideal way to do it. Normally, graphics and physics are completely separated. But this will work (mostly), and hopefully it'll encourage you to continue to experiment.
First, we need the height and width of both images so we can do our geometric magic. This can be easily set in JavaScript, just like you did for _stage. However, you've already defined the src of your images elsewhere (probably in HTML), so it would be best to define the height and width there.
HTML Example:
<img id="PokeBall" src="pokeball.png" style="width:50px; height:50px" />

Note: This uses "inline CSS" which is another bad practice. But this works, and I don't want to overcomplicate simple things right now.
Now your PlayerCaught method has all the information it needs to do it's job, so how do we detect collisions? If we're working with rectangles, it's very simple. We just determine if any of the corners of one object are inside the other object. So how do we do that? Basically, we see if they intersect on both the X and Y axes.
Take two rectangles: A and B. Both have four edges: top, left, right, and bottom. The edges top and bottom are Y values, and the edges left and right are X values. The two rectangles intersect if any of the following is true:
(
    A.left < B.left < A.right
    OR A.left < B.right < A.right
) AND (
    A.top < B.top < A.bottom
    OR A.top < B.bottom < A.bottom
)

Translate that into JavaScript and you've got your collision detection function. To get the edges in your program, use the following:
function findEdges(img){
    var result = [];
    result["left"] = parseInt(img.style.left, 10);
    result["top"] = parseInt(img.style.top, 10);
    result["right"] = result["left"] + parseInt(img.style.width, 10);
    result["bottom"] = result["top"] + parseInt(img.style.height, 10);
    return result;
}

You can see that we are using the inline style that we set earlier for the width and height as well as the top and left you are already using for rendering.
SPOILER...
Putting all the pieces together might look like:
function PlayerCaught(){
    if (detectImgCollision(_PokeBall, _Mew)){
        window.alert("Mew Has Been Captured!")
    }
}

function detectImgCollision(imgA, imgB){
    var A = findEdges(imgA);
    var B = findEdges(imgB);
    return detectRectCollision(A, B);
}

function detectRectCollision(A, B){
    return (
        isBetween(A.left, B.left, A.right)
        || isBetween(A.left, B.right, A.right)
    ) && (
        isBetween(A.top, B.top, A.bottom)
        || isBetween(A.top, B.bottom, A.bottom)
    );
}

function isBetween(low, middle, high){
    return (low <= middle && middle <= high);
}


text:
Q: Angular Express js boton crear resultado Hola buenas tengo un problema ya hice el endpoint para el backend y comunique el front end con el back end con el https , ademas de que ya la variable resultado esta  tomando esa información pero lo que me falta hacer es que el boton de cargar resultado cuando le haga click lo muestre en pantalla.
cualquier otra informacion que necesiten tengo el github o si no les contesto.
HTML app.component

           Resultado

 {{ resultado }}

           Cargar resultado

app.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable()
export class AppService {
    constructor(private http: HttpClient) { }

    numberBet() {
        return this.http.post('http://localhost:3000/bet', {});
    }

}

app.component.ts
import { Component } from '@angular/core';
import { AppService } from './app.services';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent {
  title = 'frontend';
  dateYear: number = new Date().getFullYear();
  resultado: string = "" ;

  constructor(public services: AppService){
    this.services.numberBet().subscribe((res: any) => {
      console.log(this.resultado = res.bet);
    }
    );
  }

}

express js back end
const express = require('express');
const cors = require('cors')
const app = express();
const port = 3000;

app.use(cors());

app.get('/', (req, res) => {
  res.send('Welcome to backend!');
});

app.post('/bet', (req, res) => {
  res.json({
     bet: parseInt(Math.random() * (99 - 10) + 20)

   });
});

app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`);
});


text:
Q: What do we mean by the "probabilty of two independent events happening together(intersection)"? Suppose a sample space 'S'. Suppose 'E1' and 'E2' be two event sets on 'S'. Probability of 'E1' is the sum of probabilities of all sample points which are present in 'E1' (similar for E2). If E1 and E2 are independent, then the intersection of E1 and E2 be a null set isn't it ?
I cannot understand, why we are we multiplying to find intersection probability, also since the intersection is a null set , probability should be zero ? I cannot understand where my reasoning is going wrong ?

A: Independence does not mean the intersection is a null set.  It means the chance of one event is not influenced by whether the other happens or not.  Let us throw a coin and a six sided die.  E1 is the event that the coin comes up heads.  E2 is the event the die shows a $6$.  The two events are independent because the chance of heads is the same whatever the die shows and the die does not change probabilities based on the coin.  E1 has probability $\frac 12$, E2 has probability $\frac 16$ and the chance of both is $\frac 12 \cdot \frac 16=\frac 1{12}$

A:
If $E_1$ and $E_2$ are independent, then the intersection of $E_1$ and $E_2$ be a null set isn't it?

NO, it isn't. You're confusing two different concepts: independent events and mutually exclusive events. (If it's any consolation, this is an extremely common mistake among students, although I don't really understand why…)

*

*If the intersection of two events is the empty set, then this is precisely the definition of these two events being mutually exclusive. Informally speaking: as the name suggests, either one of these events excludes the possibility of the other event happening.

*But it's a completely different concept for two events to be independent. Even before we state any definition of independence, it's very important to remember that it's not the same as being mutually exclusive, i.e. it's not at all about the empty intersection, but rather it's something else and unrelated.
Now, what does it mean for two events $A$ and $B$ to be independent? As a formula, the definition says that two events $A$ and $B$ are independent if and only if $P(A\cap B)=P(A)\cdot P(B)$. I'm not going to redo the whole discussion that can be found in any standard textbook and in a lot of places online (such as Wikipedia). But informally speaking, independence means that the knowledge about one of them happening or not gives us no additional information about the chances of the other one happening.
Note that, in particular, this implies that two mutually exclusive events can't be independent. If we know that $A$ and $B$ are mutually exclusive, i.e. that $A\cap B=\varnothing$, and that event $A$ has happened, then event $B$ definitely cannot happen. (Strictly speaking, we also need to assume that both $P(A),P(B)\neq0$ for this reasoning to work.) So knowing something about one of them gives us a lot of information about the other one — which is the exact opposite of being independent!


text:
Q: Prevent vertical scrollbar from sliding with fancybox slides I've encountered an issue where the browser's vertical scrollbar will, if visible, move along with a fancybox slide during the slide event. If you run the code snippet, adjust the height so that the vertical scrollbar becomes visible, and then click on the next/previous fancybox buttons to observe the sliding scrollbar behavior.

$(".fancybox").fancybox({
    type: "inline",
    speed: 2000
});
<!DOCTYPE html>

  <link href="https://cdnjs.cloudflare.com/ajax/libs/fancybox/3.0.47/jquery.fancybox.min.css" rel="stylesheet" />

  Inline Content 1

  Inline Content 2

Login to Join The Community

This is a sample login form, but you may put any HTML here.

Is this a bug? Any idea on a workaround? I tried hiding/showing the scrollbar before and after the slide transition, but this didn't work:
$(".fancybox").fancybox({
    type: "inline",
    speed: 2000,

    beforeMove: function (instance, slide) {
        document.body.style.overflow = "hidden";
    },

    afterMove: function (instance, slide) {
        document.body.style.overflow = "";
    }
});

A: After a bit of tweaking I managed to find this solution, though I'm not sure of a better one, which involves accessing the actual slide's (and previous slide's) elements and hiding/showing their scrollbars via CSS overflow:
$(".fancybox").fancybox({
    type: "inline",

    beforeMove: function (instance, slide) {
        // Hide scrollbar for fancybox bug fix
        instance.slides[instance.prevIndex].$slide.css("overflow", "hidden");
        slide.$slide.css("overflow", "hidden");
    },

    afterMove: function (instance, slide) {
        // Restore scrollbar for fancybox bug fix
        instance.slides[instance.prevIndex].$slide.css("overflow", "");
        slide.$slide.css("overflow", "");
    }
});


text:
Q: Why wordpress Houzez's theme's Search feature not working? I have installed the wordpress theme Houzez for my website. Then I have imported the demo contents into that. But the Search feature in the theme is not working. When I use the search button the attributes sending to the same page itself, so the same page keep reloading. This is my website address.

A: you need to create a page that you set as "Advanced Search Results" so it can show the search results.
What is happening is that when you click search, the theme does not know where to show the results, because the page of results does not exist, so he goes back to the homepage.


text:
Q: Why is this the wrong?(python) with open("info.txt", "r") as file:
for line in file:
    (name, weight, height) = line.strip().split(", ")
    if (not name) or (not weight) or (not height):
        continue

    bmi = int(weight) / ((int(height) / 100) **2)
    result = ""
    if 25 <= bmi:
        result = "과체중"
    elif 18.5 <= bmi:
        result = "정상 체중"
    else:
        result = "저체중"

    print('\n'.join([
        "이름: {}",
        "몸무게: {}",
        "키: {}",
        "BMI: {}",
        "결과: {}"
    ]).format(name, weight, height, bmi, result))
    print()

error message:
Traceback (most recent call last):
File "c:\Users\cnhan\My_project\python\tempCodeRunnerFile.py", line 4, in
(name, weight, height) = line.strip().split(", ")
ValueError: too many values to unpack (expected 3)

A: Check what is the length of array returned by line.strip().split(", "). The error occured because it returned more than 3 values (name, weight, height).
If it happens that some lines may return more than 3 values, but you want only the first three then you can add the * operator in the end.
Like this
(name, weight, height, *_) = line.strip().split(", ")


text:
Q: Matrix Multiplication using CUDA + MPI I'm doing a research about gpu in cluster environments using mpi to communicate.
In order to compare speed up, I think in create:
A Multiplication of matrix just for GPU, ok.
Now just CPU MatrixMulti, ok.
But I can't find a nice implementation of CUDA + MPI matrix multiplication.
Anyone have some hint about where I can fin this? Or suggest one implementation.

A: there is not much around. Your best bet is actually write a block matrix multiplication over MPI had have each node do the block multiplication locally on GPU.

A: The MTL4 Matrix Template Library can be a great starting point. Right now MTL4 has multi-core,  DMM, and we are almost done with a full GPU implementation. Peter and I have been talking about distributed GPU algorithms, but since our focus is driven by PDE solvers for the moment, distributed GPU algorithms are difficult to make competitive against robust DMM.
However, I am working on a new geophysics/medical imaging solver set that is more conducive for distributed GPU computes as the data sets are more modest and the video capabilities of the GPU are beneficial.
To get started, take a look at the MTL4 tutorial

A: The Combinatorial BLAS is a templated C++ MPI code that has a sparse matrix-matrix multiply operation. It uses a sqrt(p)-by-sqrt(p) processor grid and the SUMMA algorithm for matrix multiplication. One of the template arguments is a "sequential" component which is the matrix local to one process. You may be able to use it directly with a finnagled template argument that's your CUDA structure, but at least it can serve as a reference for your own code.


text:
Q: How to move marker from one location to another location when we have a list of locations on google map android i am creating google map with multiple markers.Now i want to move a car icon between that markers.Using this  Move markers in google map v2 android
I can move a car icon between from first point to second point.But it is not moving from second to third.When i used for loop for this it strightly goes to final point.I added delay also but nothing else worked for me.
Thanks in advance.
This is my code::
public void setAnimation(GoogleMap myMap, final List<LatLng> directionPoint) {

        anim_map = myMap;

        anim_marker = myMap.addMarker(new MarkerOptions()
                .icon(BitmapDescriptorFactory.fromResource(R.drawable.bus_icon))
                .position(directionPoint.get(0))
                .flat(true));

        myMap.animateCamera(CameraUpdateFactory.newLatLngZoom(directionPoint.get(0), 10));

        if (directionPoint.size() >= 2) {

            for (int i = 0; i < directionPoint.size() - 1; i++) {
                h.post(new Runnable() {
                    @Override
                    public void run() {
                        animateMarker(anim_map, anim_marker, directionPoint, false);

                    }
                });

            }

        }

    }

private void animateMarker(GoogleMap myMap, final Marker marker, final List<LatLng> directionPoint,
                               final boolean hideMarker) {

        final long start = SystemClock.uptimeMillis();
        final long duration = 350000;
        final Interpolator interpolator = new LinearInterpolator();

        h.post(new Runnable() {
            int i = 0;

            @Override
            public void run() {
                long elapsed = SystemClock.uptimeMillis() - start;
                float t = interpolator.getInterpolation((float) elapsed
                        / duration);

                //  Log.e("T Location", t + "");

                double lng = t * directionPoint.get(i + 1).longitude + (1 - t) * directionPoint.get(i).longitude;
                double lat = t * directionPoint.get(i + 1).latitude + (1 - t) * directionPoint.get(i).latitude;
                marker.setPosition(new LatLng(lat, lng));

                if (t < 1.0) {
                    h.postDelayed(this, 1);
                } else {
                    if (hideMarker) {
                        marker.setVisible(false);
                    } else {
                        marker.setVisible(true);
                    }
                }

            }
        });

    }

A: You can go try this way to make marker move in GoogleMap similar to live driving direction tracking
    private Marker mCurrentMarker;
    private float ZOOMLEVEL=18.0f;
    private LatLng previousLatLon;
    private Handler mLocalHandler;
    private GoogleMap mGoogleMap;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mLocalHandler = new Handler();
        previousLatLon=new LatLng(45.320372, 2.460161);
        //Initialize Marker once Google Map object is created
        mMarkerOptions = new MarkerOptions().icon(BitmapDescriptorFactory.fromResource(R.drawable.custom_marker_icon));
        mMarkerOptions.position(previousLatLon);
        mCurrentMarker = mGoogleMap.addMarker(mMarkerOptions);

    }

    /**
     * Call this method to move marker in map to new location in map with updated location
     * @param marker
     * @param toPosition
     * @param fromPosition
     */
    public void animateMarker(final Marker marker, final LatLng toPosition,final LatLng fromPosition) {

        final long duration = 500;
        final Interpolator interpolator = new LinearInterpolator();

        mLocalHandler.post(new Runnable() {
            @Override
            public void run() {
                long elapsed = SystemClock.uptimeMillis() - mStartTime;
                float t = interpolator.getInterpolation((float) elapsed
                        / duration);
                marker.setPosition(toPosition);
                marker.setAnchor(Constants.MAPANCHOR, Constants.MAPANCHOR);
                mGoogleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(toPosition, ZOOMLEVEL));
                if (t < 1.0) {
                    // Post again 16ms later.
                    mLocalHandler.postDelayed(this, 16);
                } else {
                    marker.setVisible(true);
                }
                }
            }
        });
        previousLatLon=toPosition;// reassign the previous location to current location
    }

Go through my answer for more details here
In your case put a sleep for some milliseconds after for loop
for (int i = 0; i < directionPoint.size() - 1; i++) {
try {
 Thread.sleep(5000);
} catch (InterruptedException e)
{
 e.printStackTrace();
}
// rest of your code

A: Finally, i came up with this answer.
We have to update all the values with respect to the size of arraylist.
  public void setAnimation(GoogleMap myMap, final List<LatLng> directionPoint) {

        anim_map = myMap;

        anim_marker = myMap.addMarker(new MarkerOptions()
                .icon(BitmapDescriptorFactory.fromResource(R.drawable.bus_icon))
                .position(directionPoint.get(0))
                .flat(true));

        myMap.animateCamera(CameraUpdateFactory.newLatLngZoom(directionPoint.get(0), 10));

        animateMarker(anim_map, anim_marker, directionPoint, false);

    }

    private void animateMarker(GoogleMap myMap, final Marker marker, final List<LatLng> directionPoint,
                               final boolean hideMarker) {

        final long start = SystemClock.uptimeMillis();
        long duration = 3500;
        final Interpolator interpolator = new LinearInterpolator();

        float t = 0;

        for (int j = 0; j < directionPoint.size() - 1; j++) {
            Log.e("Location Value", j + " " + directionPoint.get(j).latitude + ", " + directionPoint.get(j).longitude + " : " + directionPoint.get(j + 1).latitude + ", " + directionPoint.get(j + 1).longitude);
            while (t < j + 1) {
                t = t - j;
                double lng = t * directionPoint.get(j + 1).longitude + (1 - t) * directionPoint.get(j).longitude;
                double lat = t * directionPoint.get(j + 1).latitude + (1 - t) * directionPoint.get(j).latitude;
                LatList.add(new LatLng(lat, lng));
                long elapsed = SystemClock.uptimeMillis() - start;
                t = interpolator.getInterpolation((float) elapsed / duration);
            }
        }
        Log.e("LatList value", LatList.size() + "");
        h.post(new Runnable() {
            int i = 0;

            @Override
            public void run() {
                marker.setPosition(LatList.get(i));
                if ((LatList.size() - 1) > i)
                    h.postDelayed(this, 1);
                Log.e("I value", i + "");
                i++;
            }
        });

    }


text:
Q: Why is `gcloud init` not displaying all texts? I installed Google Cloud SDK and I'm initializing, ie running gcloud init, per the instructions on Windows 10 in Git Bash. However, the output text seems to be cut off.
This is the only output
$ gcloud init
Welcome! This command will take you through the configuration of gcloud.

Settings from your current configuration [viviangmail] are:
core:
  account: example@google.com
  disable_usage_reporting: 'True'

When I run the same command in Command Prompt, it works fine. See the full output below. But I don't want to use Command Prompt. I'm used to Git Bash.
C:\Users\Vivian>gcloud init
Welcome! This command will take you through the configuration of gcloud.

Settings from your current configuration [viviangmail] are:
core:
  account: example@google.com
  disable_usage_reporting: 'True'

Pick configuration to use:
 [1] Re-initialize this configuration [viviangmail] with new settings
 [2] Create a new configuration
 [3] Switch to and re-initialize existing configuration: [default]
Please enter your numeric choice:

Why is gcloud init not working in Git Bash?

A: As an alternative, you could use a Windows Subsystem for Linux (WSL) session and see if the issue persists there.
Regarding the bash session, try and type git bash --login -i in a CMD where you have set first a simplified PATH:
set PATH=C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\
set GH=C:\path\to\git
set PATH=%GH%\bin;%GH%\usr\bin;%GH%\mingw64\bin;%PATH%

See if the issue persists then (using the latest Git 2.21 for Windows)