text:
Q: Detect the BuildType in Dotnet Core 2.0 I am looking to have a condition in my .csproj whereby I detect the buildType. Is there a property that gives me this information?
For example, I am wanting to detect when a build is triggered from dotnet build or dotnet publish
<Target Name="DebugRunWebpack" BeforeTargets="Build" Condition="'$(BuildType)' != 'publish'">
...
</Target>


text:
Q: Multi-Dimension length array reflection java How do I find the length of a multi-dimensional array with reflection on java?

A: There is no such thing as "length" for multi-dimensional array; it may not be rectangular. I'm guessing you're talking about the number of dimensions. You need to descend into it iteratively and count.
public int getDimensionCount(Object array) {
  int count = 0;
  Class arrayClass = array.getClass();
  while ( arrayClass.isArray() ) {
    count++;
    arrayClass = arrayClass.getComponentType();
  }
  return count;
}

A: Java arrays have lengths per instance, not all arrays in the same dimension have to have equals lengths. That said, you can get the lengths of instances in the.
Dimensions can be counted by the number of '[' in their name, this is quicker than descending the type hierarchy. The following code:
        int[][][] ary = {{{0},{1}}};

        Class cls = ary.getClass();

        boolean isAry = cls.isArray();
        String clsName = cls.getName();

        System.out.println("is array=" + isAry);
        System.out.println("name=" + clsName);

        int nrDims = 1 + clsName.lastIndexOf('[');

        System.out.println("nrDims=" + nrDims);

        Object orly = ary;

        for (int n = 0; n < nrDims; n++) {

            int len = Array.getLength(orly);

            System.out.println("dim[" + n + "]=" + len);

            if (0 < len) {
                orly = Array.get(orly, 0);
            }
        }

gives the following output:
is array=true
name=[[[I
nrDims=3
dim[0]=1
dim[1]=2
dim[2]=1

A: Class clazz = Class.forName("ReflectionTest");
Method m = clazz.getDeclaredMethod("getArray");
Object o1 = m.invoke(o, arg);
int array[][] = (int[][])o1;
System.out.println("Array length: " + array.length);
System.out.println("Array length: " + array[0].length);

A: Use java.lang.reflect.Array.getLength(obj).

A: If you like me were trying to get the number of dimensions and the size of them then:
private static int[] getDimentionsOf(final Object expectedArray) {
    if (!expectedArray.getClass().isArray()) {
        return new int[0];
    }
    final int dimensionSize = Array.getLength(expectedArray);
    final int[] innerDimensions =
                    (expectedArray.getClass().getComponentType().isArray())
                                    ? getDimentionsOf(Array.get(expectedArray, 0))
                                    : new int[0];
    final int lenghtPlusOne = innerDimensions.length + 1;
    final int[] newDimensions = new int[lenghtPlusOne];
    System.arraycopy(innerDimensions, 0, newDimensions, 1, innerDimensions.length);
    newDimensions[0] = dimensionSize;
    return newDimensions;
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: HTML5, Jquery Mobile i am using html5 and jquerymobile framework 1.1 for creating this app.
i need to pop up mobile keypad when click on the orange button next input box
can any one let me know how to fix this?

   Monthly Income

         <input data-theme="c"  type="number" min="500" max="10000" name="monthly-income" id="monthly-income" value=""  >
                     </input>

A: If you give focus to the input box as you "click" the image would that suffice?


text:
Q: Error while removing stopwords text in Python I am trying to remove stopwords from text in Python using nltk.stopwords.
I used following code
[w for w in imdb['Comment'] if w not in stopwords.words('english')]

However, I got following error and stopwords are not removed.
C:\Users\XYZ\Anaconda2\lib\site-packages\ipykernel\__main__.py:1:     UnicodeWarning: Unicode equal comparison failed to convert both arguments to     Unicode - interpreting them as being unequal

Then it says
if __name__ == '__main__':

and gives text back without dropping the stopwords.
The database I was working is IMDB database containing rating and comments. I have input file as follows.
imdb= pd.read_csv("C:\Users\XYZ\Text Analytics\imdb.csv")
Do I need to have some encoding while inputting file? What could be the issue? Any help welcome.
Thanks
Nin


text:
Q: Brute Force Permutation Swapping I've been working on a brute force algorithm to generate all permutations of a given set. Eventually, I want to feed each of these permutations into a nxn matrix to test if it is a valid magic square or not.
--I KNOW THAT THERE IS A WAY TO GENERATE A MAGIC SQUARE EASILY--
That is not what I want to do, though. I'm focusing on the brute force aspect of it.
For a set of 3 elements, it works wonderfully. However, once I use 4 or more elements, I lose out on a few permutations. Just from looking at the output of 4, I am missing 7 permutations.
#include <stdio.h>
#include <iostream>

using namespace std;

//ms = magic square
//n = size
void perm(int ms[], int n) {
    int pivot = 0;
    int index = 0;
    int pivBit = 1;
    int fin = 0;
    int hold = 0;

    //While we are not finished
    while (fin == 0)  {
        //Incriment the index
        ++index;
        if (index >= n) {
            index = 0;
        }
        //if index is equal to the pivot
        if (index == pivot) {
            //Is this the first time visiting the pivot?
            if (pivBit == 0) {
                //Are we at the beginning again?
                if (index == 0 && pivot == 0)
                {
                    fin = 1;
                }
                pivBit = 1;
                ++index;
            }
            //Second time visiting?
            else {
                pivBit = 0;
                ++pivot;
                if (pivot >= n) {
                    pivot = 0;
                }
            }
        }

        //If we are out of bounds
        if (index >= n) {
            index = 0;
        }

        //swap
        hold = ms[index];
        ms[index] = ms[pivot];
        ms[pivot] = hold;

        for (int i = 0; i < n; ++i) {
            cout << ms[i];
            if (i < n - 1) {
                cout << ", ";
            }
            else {
                cout << endl;
            }

        }

    }

}

int main() {

    cout << "Are you ready to brute force, my brother?" << endl;

    //Set
    int magicsquare[] = { 1, 2, 3, 4};
    int size = 4;

    perm(magicsquare, size);

    getchar();
    return 0;
}

My output is:
2 1 3 4
3 1 2 4
4 1 2 3
1 4 2 3
1 2 4 3
1 3 4 2
3 1 4 2
3 4 1 2
3 4 2 1
2 4 3 1
2 3 4 1
2 3 1 4
4 3 1 2
4 2 1 3
4 2 3 1
1 2 3 4
2 1 3 4

Looking at it, I can already see that I am missing both 1 4 3 2 and 1 3 2 4.
Where've I gone wrong in my algorithm?

A: The simplest way to generate all permutations is recursive. For each i, swap the i'th element to the 0 position.  Then recursively find all permutations of of the remaining array.
int buf[1000], n;  // better to wrap these in a class...

void permute(int *a, int a_len) {
  if (a_len == 1) {
    for (int i = 0; i < n; i++) printf("%d ", buf[i]);
    printf("\n");
  } else {
    for (int i = 0; i < a_len; i++) {
      swap(a, 0, i);
      permute(a + 1, a_len - 1);
      swap(a, 0, i);
    }
  }
}

void run(int buf_len) {
  for (int i = 0; i < buf_len; i++) buf[i] = i + 1;
  n = buf_len;
  permute(buf, buf_len);
}

This assumes no repeated elements in the original array.  It's not to hard to have it take repeated elements into account.

A: The wiki article on permutation includes a common algorithm used to produce all permutations in lexicographic order, starting with an array of sequentially increasing integers, ending with that array reversed. wiki next permutation.
If dealing with an array of objects, you can generate an array of indices 0 through n-1 and use next permutation on the indices to produce all permutations of the array of objects.
You can also do a web search for next permutation to find similar algorithms. The recursive ones produce all permutations, but not in lexicographic order.


text:
Q: Accuracy of htaccess testing tools I trying to improve my understanding of htaccess rewrite rules and used a couple of online testing tools to verify a simple rewrite I did, but I don't understand why the returned url is repeated. I'm questioning if my rule is wrong of if there is something inherently wrong with this tool?
All I am trying to do is redirect all requests to a .com domain to the same page on a .com.au domain.
RewriteCond %{HTTP_HOST} ^domain\.com$ [OR]
RewriteCond %{HTTP_HOST} ^www\.domain\.com$
RewriteRule .? "https://domain.com.au%{REQUEST_URI}" [L,R=301]

So as I understand, this says:

*

*Conditions: If the host is domain.com OR www.domain.com

*Rule: match anything or nothing as the requested uri and redirect to https://domain.com.au/whatever-the-request-uri-is
But when I test this using https://htaccess.madewithlove.be for example, the returned url repeats like https://domain.com.au/bloghttps://domain.com.au/bloghttps://domain.com.au/blog...
However on the web server it appears to work fine.
The other rule I tried was:
RewriteRule ^(.*)$ https://domain.com.au/$1 [R=301,L]

And this returns a single correct result using the testing tool, but I read that it's preferable to use the server variables.
So is there something wrong with my first rule or is that testing tool broken?

A: This works according to my tests:
RewriteCond %{HTTP_HOST} ^(www\.)?example\.com$
RewriteRule ^ https://example.com.au%{REQUEST_URI} [L,R=301]

I am currently unable to explain why your own attempt does not, though. Sorry! I have the impression that this is indeed a bug inside the test utility, assuming that you used https://htaccess.madewithlove.be/ ...


text:
Q: Break tie using other column value and remove row Table
I have the following table above. Each year is supposed to have 2 rows one for lgID = NL and one for lgIG = AL. I want to break any ties in the HR column based on the RBI value. Higher RBI stays and lower gets dropped.
so for example the year 1932 in NL player ottme01 should be dropped because he has a lower RBI value than kleinch01.
for 1934 in NL colliri02 should be dropped because he has a lower rbi value than ottme01
trying to do this in mysql
Id like to convert this

year
lgID
playerID
HR
RBI

1934
NL
colliri02
35
128

1934
AL
gehrilo01
49
165

1934
NL
ottme01
35
135

1934
AL
troskha01
35
142

into this

year
lgID
playerID
HR
RBI

1934
AL
gehrilo01
49
165

1934
NL
ottme01
35
135

A: We can use ROW_NUMBER here:
WITH cte AS (
    SELECT t.*, ROW_NUMBER() OVER (PARTITION BY yearID, IgID
                                   ORDER BY HR DESC, RBI DESC) rn
    FROM yourTable t
)

SELECT *
FROM cte
WHERE rn = 1;


text:
Q: Windows: Force specific network adapter Specs:
Windows 8 server (x64) with two connections/adapters, 1 is wired and 1 is a tethered connection through my phone.
Question:
How can I force my browser(chrome) to connect over the wired connection only?
I've tried:
Looking at previous answers (all unsatisfactory), a program called ForceBindIp (didn't work for my platform) and googeling for a proxy that could route traffic through a specified interface (anybody know a proxy that can do this?)

A: for that you need a third party software, and configure rules for incoming / outgoing connections for every network connection BlindIP seems to be tour best shot, because windows doesn't allow such configurations


text:
Q: Error to create user with API Google Admin-sdk I have the following code which me serves to get information such as mailing list etc ... But when I try to create a new mails (user) I get the following error, hope you can help me I tried to find more information but only find old api . This is the error-> : http://i.stack.imgur.com/ZBoqa.png
C:\xampp\php>php -f "c:\Users\Eldelaguila77\Desktop\proyectocorreos\quickstart1.php"

Error calling POST https://www.googleapis.com/admin/directory/v1/users: (403) Insufficient Permission

And this is my code
<?php
    require __DIR__ . '/vendor/autoload.php';

    define('APPLICATION_NAME', 'Directory API PHP Quickstart');
    define('CREDENTIALS_PATH', '~/.credentials/admin-directory_v1-php-quickstart.json');
    define('CLIENT_SECRET_PATH', __DIR__ . '/client_secret1.json');
    // If modifying these scopes, delete your previously saved credentials
    // at ~/.credentials/admin-directory_v1-php-quickstart.json
    define('SCOPES', implode(' ', array(
      //Google_Service_Directory::ADMIN_DIRECTORY_USER_READONLY)
      Google_Service_Directory::ADMIN_DIRECTORY_USER)
    ));

    if (php_sapi_name() != 'cli') {
      throw new Exception('This application must be run on the command line.');
    }

    /**
     * Returns an authorized API client.
     * @return Google_Client the authorized client object
     */
    function getClient() {
      $client = new Google_Client();
      $client->setApplicationName(APPLICATION_NAME);
      $client->setScopes(SCOPES);
      $client->setAuthConfigFile(CLIENT_SECRET_PATH);
      $client->setAccessType('offline');

      // Load previously authorized credentials from a file.
      $credentialsPath = expandHomeDirectory(CREDENTIALS_PATH);
      if (file_exists($credentialsPath)) {
        $accessToken = file_get_contents($credentialsPath);
      } else {
        // Request authorization from the user.
        $authUrl = $client->createAuthUrl();
        printf("Open the following link in your browser:\n%s\n", $authUrl);
        print 'Enter verification code: ';
        $authCode = trim(fgets(STDIN));

        // Exchange authorization code for an access token.
        $accessToken = $client->authenticate($authCode);

        // Store the credentials to disk.
        if(!file_exists(dirname($credentialsPath))) {
          mkdir(dirname($credentialsPath), 777, true);
        }
        file_put_contents($credentialsPath, $accessToken);
        printf("Credentials saved to %s\n", $credentialsPath);
      }
      $client->setAccessToken($accessToken);

      // Refresh the token if it's expired.
      if ($client->isAccessTokenExpired()) {
        $client->refreshToken($client->getRefreshToken());
        file_put_contents($credentialsPath, $client->getAccessToken());
      }
      return $client;
    }

    /**
     * Expands the home directory alias '~' to the full path.
     * @param string $path the path to expand.
     * @return string the expanded path.
     */
    function expandHomeDirectory($path) {
      $homeDirectory = getenv('HOME');
      if (empty($homeDirectory)) {
        $homeDirectory = getenv("HOMEDRIVE") . getenv("HOMEPATH");
      }
      return str_replace('~', realpath($homeDirectory), $path);
    }

    // Get the API client and construct the service object.
    $client = getClient();
    $service = new Google_Service_Directory($client);

    //enviar creacion de usuario
    $user = new Google_Service_Directory_User();
    $name = new Google_Service_Directory_UserName();
    // SET THE ATTRIBUTES
    $name->setGivenName('pruebanueve');
    $name->setFamilyName('Testerton');
    $user->setName($name);
    $user->setHashFunction("MD5");
    $user->setPrimaryEmail("prueba@dom.com");
    $user->setPassword(hash("md5","holamundo"));

    try
    {
        $createUserResult = $service -> users -> insert($user);
        var_dump($createUserResult);
    }
    catch (Google_IO_Exception $gioe)
    {
        echo "Error in connection: ".$gioe->getMessage();
    }
    catch (Google_Service_Exception $gse)
    {
        echo $gse->getMessage();
    }

    //print $results;

    // Print the first 10 users in the domain.
    /*$optParams = array(
      'customer' => 'my_customer',
      'maxResults' => 10,
      'orderBy' => 'email',
    );
    $results = $service->users->listUsers($optParams);

    if (count($results->getUsers()) == 0) {
      print "No users found.\n";
    } else {
      print "Users:\n";
      foreach ($results->getUsers() as $user) {
        printf("%s (%s) (%s) \n", $user->getPrimaryEmail(),
            $user->getName()->getFullName(),
            $user->getlastLoginTime());
      }
    }*/
    ?>

A: To create a user account using one of your domains, use the following POST request and include the authorization described in Authorize requests.
POST https://www.googleapis.com/admin/directory/v1/users

Please note that every request your application sends to the Directory API must include an authorization token.

A: Your question helped me a lot. I was doing exactly what you was doing, but trying to do the JSON by hand. Anyways, I solved your problem:
You have to delete the ~/.credentials/admin-directory_v1-php-quickstart.json (you created it with the ADMIN_DIRECTORY_USER_READONLY scope, which is now not sufficient any more. Once you deleted it, the script will generate a new one for you. And then it all works. (users end up being suspended though) Add a
$user->setSuspended(false);


text:
Q: Animate div from middle of div to bottom right of screen into a fixed position What I am trying to figure out is how to animate a div that will start out in the middle of a div that is in the middle of a page. The div originally should not have a position: absolute. Unless it is not possible, I would like it not to start with that because it seems very tough to have any data below it. It's not going to be that big of a box. I am guessing anywhere between the height of 100px and 600px, with a width between 400px and 800px.
I originally found this JsFiddle Example that does a great job and almost exactly what I need. But the div starts with an absolute position and it is already located at the bottom right of the page to be animated.
Once the div is at the bottom right of the page, it needs to be fixed there so that I can scroll up and down the page without it moving. At this point I am not worried about being able to push it back up to the spot in which it came.
A couple things I tried: Lining it up in the position I desired, and then on the click of a button, add a class with the attribute position: absolute and calling the animate function like this:
chatWindow.stop().animate({
         bottom: 0
       , right: 0
    }, 2000);

But my guess is that it originally needs to the the position set as in top: 0; left: 0 and that's why it won't work.
I already have it working without any animation and would love to be able to figure out how to animate this thing. Without animation, it's as simple as toggling a class with it's normal positions attributes with one that has a position: fixed; bottom: 0; right: 0.
Here is a Codepen Example that I created to show really what I need other than right animation part not being there. Any help would be awesome as I've been toying with this for quite some time now.

A: If you want an animation from left to right, you will have to play with left and top values. But the negative point is that will cause a weird animation because you want to keep a relative position of the box in the beginning.
So when you will do the animation, it will start from the very top left on the window, which is not good.
Like this
To avoid that, you will have to use absolute position in the beginning state. You said in your question you doesn't want it but I think it is required to get the wanted visual effect.
See here the live example with good effect
However, to keep a pretty nice animation, but I know it is not what you want, you can play with right and bottom values. It will make the box appears from the right and bottom corners of the window.
Like this

A: One possibility, still using absolute positioning, based on what's going on in your codepen example, would be to fake the current positioning by adding the following CSS:
.container {
  padding-top: 250px;
}
.center-window {
  position: absolute;
  right: 50%;
  margin-right: -200px; /* i.e. half of its width */
  bottom: 100%;
  margin-bottom: -250px; /* i.e. its height */
}

Then you could animate the right, bottom, and margin properties accordingly.  See https://codepen.io/anon/pen/RaOJYY (though it doesn't currently do anything with the padding).  Of course, if your not sure of the dimensions of .center-window, perhaps this solution won't quite work.


text:
Q: Adding values to ggplot points I am using ggplot in R on a Mac, doing a line graph using the group option. I want to add the values that correspond to the end points for each of the lines. This is part of the data I am using:
  Year Foundation Type No. of Houses Percent Shares
1 2000     Crawl Space        209529       16.84583
2 2001     Crawl Space        206431       16.58441
3 2002     Crawl Space        204327       15.58577
4 2003     Crawl Space        213328       15.39025
5 2004     Crawl Space        224195       14.63272
6 2005     Crawl Space        258254       15.91873

I run the following code:
ggplot(USbyFoundType, aes(x=Year, y=`Percent Shares`,
            group=`Foundation Type`, color=`Foundation Type`)) +
  geom_line()

I get this chart. I want to place the value at the end of each of the lines.

Thanks for any help

A: It would be nice to have a reproducible example, but something like:
endpts <- (USbyFoundType
      %>% group_by(`Foundation Type`)
      %>% filter(Year == max(Year))
)

Then add
+ geom_text(data = endpts, aes(x = Year, y = `Percent Shares`,
          colour = `Foundation Types`,
          label = `Percent Shares`)

You'll probably have to play with horizontal justification (hjust), spacing (nudge_x), and margins (e.g. + expand_limits(y=2030)).
This question is about plotting labels (not values) at the end of the lines, but contains lots of useful information about adjusting positioning, margins, clipping etc.


text:
Q: getBoundingClientRect is inaccurate My goal is to inject an element right before it's on the viewport (depending on the lazy data attribute, default is 100px before the element is on the viewport). And how I do it is by using getBoundingClientRect();
const LAZY_THRESHOLD_DEFAULT = 100;
TestBox.isOnScreen = function(element) {
    const reservedDistance = parseInt(element.getAttribute(THRESHOLD) || LAZY_THRESHOLD_DEFAULT, 10);
    const rect = el.getBoundingClientRect();
    return (
        rect.top >= 0 &&
        rect.left >= 0 &&
        rect.bottom <= $(window).height() &&
        rect.right <= $(window).width()
}

And I use it like this
$(window).scroll(function() {
  if (TestBox.isOnScreen(element)) {
    // Inject the element
  }
});

One major thing I find out is (I console log the $(window).scrollTop() together with console log when TestBox.isOnScreen(element): The moment when the element is detected to be on the viewport is not always accurate. Sometimes by 14px, 5px or exactly good.
Does anyone ever experience this issue? Or am I implementing it wrong?


text:
Q: gRPC HealthCheck reports SERVING even when it is defined as NOT_SERVING I am trying to create a server with two services and a HealthCheck in each one, so I can check them independently and use reflection to know the methods exposed in each one. I have hardcoded one service as NOT_SERVING to test it, however, for some reason, it is not working. I would appreciate some help.
I have created a short script to reproduce this result.
The proto file definition:
syntax = "proto3";

package test;

service Greeter {
    rpc SayHello (HelloRequest) returns (HelloReply) {}
}

message HelloRequest {
    string name = 1;
}

message HelloReply {
    string message = 1;
}

service Byeer {
    rpc SayBye (ByeRequest) returns (ByeReply) {}
}

message ByeRequest {
    string name = 1;
}

message ByeReply {
    string message = 1;
}

The Python server:
from concurrent import futures
import grpc
from grpc_health.v1 import health, health_pb2, health_pb2_grpc
from grpc_reflection.v1alpha import reflection
import test_pb2_grpc
import test_pb2

class Greeter(test_pb2_grpc.GreeterServicer):

    def SayHello(self, request, context):
        return test_pb2.HelloReply(message='Hello, %s!' % request.name)

    def Check(self, request, context):
        return health_pb2.HealthCheckResponse(status=health_pb2.HealthCheckResponse.SERVING)

    def Watch(self, request, context):
        return health_pb2.HealthCheckResponse(status=health_pb2.HealthCheckResponse.UNIMPLEMENTED)

class Byeer(test_pb2_grpc.ByeerServicer):

    def SayBye(self, request, context):
        return test_pb2.HelloReply(message='Bye, %s!' % request.name)

    def Check(self, request, context):
        return health_pb2.HealthCheckResponse(status=health_pb2.HealthCheckResponse.NOT_SERVING)

    def Watch(self, request, context):
        return health_pb2.HealthCheckResponse(status=health_pb2.HealthCheckResponse.UNIMPLEMENTED)

def run_server():
    server = grpc.server(futures.ThreadPoolExecutor(max_workers=None))
    server.add_insecure_port('[::]:8000')

    test_pb2_grpc.add_GreeterServicer_to_server(Greeter(), server)
    health_pb2_grpc.add_HealthServicer_to_server(Greeter(), server)

    test_pb2_grpc.add_ByeerServicer_to_server(Byeer(), server)
    health_pb2_grpc.add_HealthServicer_to_server(Byeer(), server)

    services = tuple(service.full_name for service in health_pb2.DESCRIPTOR.services_by_name.values())
    services += tuple(service.full_name for service in test_pb2.DESCRIPTOR.services_by_name.values())
    services += (reflection.SERVICE_NAME,)
    reflection.enable_server_reflection(services, server)

    server.start()
    server.wait_for_termination()

if __name__ == "__main__":
    run_server()

When I test the reflection and the server methods, it works:
grpcurl -plaintext localhost:8000 list
grpcurl -plaintext localhost:8000 list test.Byeer
grpcurl -plaintext localhost:8000 list test.Greeter
grpcurl --plaintext -d '{"name": "John Doe"}' localhost:8000 test.Greeter/SayHello
grpcurl --plaintext -d '{"name": "John Doe"}' localhost:8000 test.Byeer/SayBye

The reflections report the proper methods and the server the correct response.
The HealthCheck on the server and the Greeter service work too:
grpcurl --plaintext -d '' localhost:8000 grpc.health.v1.Health/Check
grpcurl --plaintext -d '{"service": "test.Greeter"}' localhost:8000 grpc.health.v1.Health/Check

So, it reports SERVING as expected.
However, the HealthCheck on the Byeer service, and whatever other name I use, also reports SERVING:
grpcurl --plaintext -d '{"service": "test.Byeer"}' localhost:8000 grpc.health.v1.Health/Check
grpcurl --plaintext -d '{"service": "xxx"}' localhost:8000 grpc.health.v1.Health/Check

And I would expect NOT_SERVING since the Check methods for the Byeer has been hardcoded as NOT_SERVING.
Any idea?
Thanks in advance.

A: OK, here's a working example that excludes the reflection (my laziness):
from concurrent import futures
import grpc

from grpc_health.v1.health import HealthServicer
from grpc_health.v1 import health_pb2, health_pb2_grpc

import test_pb2_grpc
import test_pb2

class Greeter(test_pb2_grpc.GreeterServicer):

    def __init__(self,health):
        super().__init__()
        self.health=health

    def SayHello(self, request, context):
        self.health.set(
            "greeter-eater",
            health_pb2.HealthCheckResponse.ServingStatus.Value("SERVING"),
        )
        return test_pb2.HelloReply(message='Hello, %s!' % request.name)

class Byeer(test_pb2_grpc.ByeerServicer):

    def __init__(self,health):
        super().__init__()
        self.health=health

    def SayBye(self, request, context):
        self.health.set(
            "byeer-flyer",
            health_pb2.HealthCheckResponse.ServingStatus.Value("NOT_SERVING"),
        )
        return test_pb2.HelloReply(message='Bye, %s!' % request.name)

def main():
    server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))

    server.add_insecure_port('[::]:50051')

    # As with any other Servicer implementations, register it
    health = HealthServicer()

    # Provide other services with a way to update health
    greeter = Greeter(health)
    byeer = Byeer(health)

    test_pb2_grpc.add_GreeterServicer_to_server(
        greeter,
        server,
    )
    test_pb2_grpc.add_ByeerServicer_to_server(
        byeer,
        server,
    )
    health_pb2_grpc.add_HealthServicer_to_server(
        health,
        server,
    )

    server.start()
    server.wait_for_termination()

if __name__ == "__main__":
    main()

Without reflection, I needed to grab a copy of health.proto and:
# Invoke Greeter/SayHello
grpcurl \
--plaintext \
-d '{"name": "Freddie"}' \
-import-path ${PWD}/protos \
-proto health.proto \
-proto test.proto \
localhost:50051 test.Greeter/SayHello
{
  "message": "Hello, Freddie!"
}

# Invoke Byeer/SayBye
grpcurl \
--plaintext \
-d '{"name": "Freddie"}' \
-import-path ${PWD}/protos \
-proto health.proto \
-proto test.proto \
localhost:50051 test.Byeer/SayBye
{
  "message": "Bye, Freddie!"
}

# Health/Check Greeter service aka "greeter-eater"
grpcurl \
--plaintext \
-d '{"service":"greeter-eater"}' \
-import-path ${PWD}/protos \
-proto health.proto \
-proto test.proto \
localhost:50051 grpc.health.v1.Health/Check
{
  "status": "SERVING"
}

# Health/Check Byeer service aka "byeer-flyer"
grpcurl \
--plaintext \
-d '{"service":"byeer-flyer"}' \
-import-path ${PWD}/protos \
-proto health.proto \
-proto test.proto \
localhost:50051 grpc.health.v1.Health/Check
{
  "status": "NOT_SERVING"
}

Explanation:

*

*You need only register HealthServicer once per server.

*As with any gRPC server, it (HealthServicer), when you invoke its methods (e.g. Check), you need to provide it with some context. In this case, which service.

*The service names aren't bound to the proto packages but to an arbitrary string that you define when you set(SERVICE,health_pb2.HealthCheckResponse.ServingStatus)

*Because you can register multiple distinct gRPC services (Greeter,Byeer) with a single server, these need to be able to provide health context back to HealthServicer

*In order for other gRPC services to update the healthcheck service, we need to share some of the healthcheck service's context with the other services; here I'm using the Servicer itself.

*Other services may update their status by using set and providing some (preferably) unique identifier; there's no need for this to match the server's proto package/Service (but that may be a good strategy).

*In practice you would not set with static ServingStatus.Value's but would accurately reflect that service's status


text:
Q: Big-O & Little-O Notation and Matrices I wonder how the Big Oh and Little Oh notation works while working with matrices. The wikipedia page doesn't list any matrix results, and so do the sources of this question.
As a remainder:
(D1) $a_n = O(b_n)$ if there exist a $M > 0$ and $N$ such that $|a_n/b_n| < M$ for $n > N$
(D2) $a_n = o(b_n)$ if for any $M > 0$, there exists a $N_M$ such that $|a_n/b_n| < M$ for $n > N$
Consider vector $v_n$ and $w_n$, sequences of matrices ${\bf A}_n$ and ${\bf B}_n$ and $||{\bf A}||$ the sup norm of ${ \bf A}$ and $|{\bf A}|$ the determinant. I assume them commutative as needed. Of course, there is the obvious,
(1) If $||{\bf A}_n|| = O(1),||{\bf B}_n|| = O(1)$  then $|| { \bf A } _n { \bf B }_n || = O(1)$
(2) If $||{\bf A}_n|| = O(1)$, $v_n = O(1)$, and $w_n = O(1)$, then $v_n{\bf A}_n w_n = O(1) $
Both (1) and (2) can be proved easily by taking the max over each element.
(3) I also found out recently that
If $||{\bf A}_n^{-1}|| = O(a_n)$, $a_n \to \infty$, and $||{\bf B}_n|| = o(1)$ , then $||[{ \bf A}_n + { \bf B}_n]^{-1}|| = O(a_n)$
(4) For semidefinite $k\times k$ matrices ${\bf A}_n$, $tr({\bf A}_n) = O(a_n)$ iff $\lambda_{n}^L = O(a_n)$ iff $||{\bf A}_n|| = O(a_n)$, with $\lambda_n^L$ the largest eigenvalue of ${\bf A}_n$. Also, these imply $|{\bf A}_n| = O(a_n^k)$ and, for positive definite matrices, $log(|{\bf A}_n|) = O(a_n)$.
(5?) However, a book I recently read implicitly uses a result that I find dubious,
If $|{\bf A}_n| = O(1)$ and $v_n = O(1)$, then $v'_n{\bf A} v_n = O(1)$
Statement (5) seems very suspicious since for a given determinant you can have a norm arbitrarily large. However, maybe it is somehow true for (semi)-positive definite matrices?
In any case I wonder if someone compiled a list of nice results of the $O(1)$ and $o(1)$ notation for matrices.

A: If $|A_n|$ is the determinant, (5) is false even for PD matrices. Take simply
$$
A = \begin{bmatrix}\frac1\varepsilon & 0\\ 0 & \varepsilon\end{bmatrix}, \quad v = \begin{bmatrix}1\\0\end{bmatrix}.
$$
As for a list of big-O results, I don't know of one, and I think it would be too big to be remotely useful.


text:
Q: ¿Cómo generar numero incremental en sql server 2008, C# o JQuery? Hola a todos tengo una consulta y es la siguiente:
Quiero hacer un número correlativo y que aumente de 1 en 1 como por ejemplo identity(1,1) pero en este caso con este formato TCK000000001 si se pudiese en sql o sino también un método en Jquery o C# que me permita generar un número correlativo y poder insertarlo en la base de datos.
Tabla Ticket
create table tb_ticket
(
num_ticket varchar(20) primary key not null,
desc_ticket varchar(500),
Especialista varchar(20)
)

A: Al menos desde la versión 2008, dispones de columnas calculadas. Si te sirve el identity como numerador, puedes reformular la columna del número de la siguiente forma:
create table tb_ticket
(
  id int identity,
  num_ticket as 'TK' +  right('00000000' + convert(varchar, id), 8),
  desc_ticket varchar(500),
  Especialista varchar(20)
);

En este caso num_ticket es una columna virtual, no existe físicamente, se calcula  al vuelo cuando la necesites. No olvides que el identity tiene algunas limitaciones como numerador: a) Las transacciones que se deshace pueden terminar dejando huecos b) hay un feo comportamiento del motor ante ciertos reinicios en se pueden generar huecos de mayor tamaño.


text:
Q: Putting a port in a remote server SSH tunneling I need to know if is possible to put a local port in a remote machine via ssh tunneling
Example
Machine A: port 80
Machine B: Nothing

Inside Machine A (important, because A can see B, but B can't see A)
A>  ssh -f -N -? 80:B:8585 user@B

result
Machine A: port 80
Machine B: port 8585 (really A:80)

Thanks in Advance

A: You need the -R switch
ssh -f -N -R 8585:localhost:80 user@B

localhost is from A's perspective, so it means to forward port 8585 on B to port 80 on A.
See also the RemoteForward setting in your ~/.ssh/config.


text:
Q: Null reference exception in c# when am running the following code I am just a learner.I am getting null reference exception for the following snippet.Please correct the mistake and tell me what's wrong with this code.
  class Program
    {
        static void Main(string[] args)
        {
            Company objcompany = new Company();

            Employee obj1 = new Employee(101, "Test1");
            Employee obj2=  new Employee(102, "Test2");
            Employee obj3 = new Employee(103, "Test3");

            objcompany.EmpList.Add(obj1);
            objcompany.EmpList.Add(obj2);
            objcompany.EmpList.Add(obj3);

            foreach (var emp in objcompany.EmpList)
            {
                Console.WriteLine(emp.EmpId + " " + emp.EmpName);
            }

            Console.ReadKey();
        }
    }

    class Company
    {
        public List<Employee> EmpList { get; set; }
    }

    class Employee
    {
        public int EmpId { get; set; }
        public string EmpName { get; set; }

        public Employee(int empid, String empname)
        {
            this.EmpId = empid;
            this.EmpName = empname;
        }
    }

i have created 3 classes.[Employee,Company,Program].I want to add employees into the collection.I am processing the code in the program class.

A: You have not initialized EmpList. I would suggest you to initialize it in Company class constructor
class Company
{
    public Company()
    {
         EmpList = new List<Employee>();
    }
    public List<Employee> EmpList { get; set; }
}


text:
Q: Laptop power options while flying I have noticed some laptop power supplies include a plug that allows you to connect it to a power source while flying.  If I was going to go out and buy a laptop power supply for this purpose, which one should I consider?

A: *

*The Ultimate Guide to In-Seat Laptop Power Ports

*Another interesting read at Google Answers Laptop power on an airplane

*Some brand wise references at this commercial site.


text:
Q: I want to create controls and position them where I want Programatically I have the below FormReport.aspx. I want to create a replica of what is inside of the div class=employeebox> but Programmatically when addrow_clic is click ? Any help would be appreciated
FormReport.aspx
<%@ Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true"  CodeBehind="FormReport.aspx.cs" Inherits="Tardy_Absentee_Report.FormReport" %>
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">

</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

<fieldset>
<legend>Supervisor information </legend>

Supervisor Name:

        <asp:TextBox ID="txtsupervisorname" runat="server" Width="103px"></asp:TextBox>

Department:

        <asp:DropDownList ID="DDownDepartment" runat="server" Height="24px" Width="154px">
        </asp:DropDownList>

Supervisor Number:

        <asp:TextBox ID="txtSupervisorNumber" runat="server" Width="103px"></asp:TextBox>

Date of Incident:

        <asp:TextBox ID="txtDate" runat="server"></asp:TextBox>

</fieldset>

<fieldset>
<legend> Employee Information</legend>

Employee Number

Employee Name

Reason Code

<asp:TextBox ID="TextBox4" runat="server"></asp:TextBox>

    <asp:TextBox ID="TextBox5" runat="server"></asp:TextBox>

    <asp:DropDownList ID="DDownResoncode1" runat="server" Width="153px">
    </asp:DropDownList>

<asp:TextBox ID="TextBox7" runat="server"></asp:TextBox>

    <asp:TextBox ID="TextBox8" runat="server"></asp:TextBox>

    <asp:DropDownList ID="DDownResoncode2" runat="server" Height="20px" Width="153px">
</asp:DropDownList>

<asp:TextBox ID="TextBox10" runat="server"></asp:TextBox>

    <asp:TextBox ID="TextBox11" runat="server"></asp:TextBox>

    <asp:DropDownList ID="DDownResoncode3" runat="server" Width="153px"></asp:DropDownList>

<asp:TextBox ID="TextBox13" runat="server"></asp:TextBox>

    <asp:TextBox ID="TextBox14" runat="server"></asp:TextBox>

        <asp:DropDownList ID="DDownResoncode4" runat="server" Height="16px" Width="153px">
</asp:DropDownList>

    <asp:Button ID="addrow" runat="server" Text="AddRow" onclick="addrow_Click" />

    <asp:Button ID="Button1" runat="server" Text="Submit" onclick="Button1_Click" />

</fieldset>

</asp:Content>

FormReport.aspx.cs
protected void addrow_Click(object sender, EventArgs e)
    {
        TextBox newtextbox = new TextBox();
        Panel panel1 = new Panel();
        panel1.Controls.Add(panel1);
    }

A: You can use HtmlGenericControl to create a div inside panel or add a panel inside parent panel
and to add a style you can using control.Style.Add("style", "value")
ASPX:
 or you can use placeholder
C#
protected void addrow_Click(object sender, EventArgs e)
{
    Panel pnlEmployeeBox = new Panel();
    pnlEmployeeBox.CssClass = "pnlEmployeeBox";

    HtmlGenericControl columnLeft2= new HtmlGenericControl("div");
columnLeft2.CssClass = "column-left2";
        TextBox txt1 = new TextBox();
columnLeft2.Controls.Add(txt1);

pnlEmployeeBox.Controls.Add(columnLeft2);

 columnLeft2 = new HtmlGenericControl("div");

        txt1 = new TextBox();

    pnlEmployeeBox.Controls.Add(columnLeft2);

// and same goes for the dropdown list

}


text:
Q: Get CS:GO Inventory from Steam API for my React APP Since requesting the Inventory from https://api.steampowered.com/IEconItems_730/GetPlayerItems/v1/ is permanently disabled I have to use https://steamcommunity.com/profiles/<steam_id>/inventory/json/2
Because of CORS I have to use my backend to provide the requested data. But when I do requests too often, my requests get rejected and my app cannot work on a large scale.
So the question should be simple: How can I avoid the rejection of my requests?
Any ideas and suggestions welcome.

A: Steam inventory endpoints are pretty heavily rate-limited, but there are a few different endpoints that you can use.
Trade offer endpoint
https://steamcommunity.com/tradeoffer/new/partnerinventory
This is the endpoint that's used when you open a trade offer with someone. It can be used to fetch both your own inventory as well as a trade partners. Required parameters are partner which is the user's Steam 64 Id, appid which is 730 in the case of CS:GO, and contextid which is 2 for most valve games. I don't know the exact limit, but I've been hitting this endpoint about once a second for a month with minimal 429 responses. To use this endpoint, you need to have a valid steam session and send the proper cookies along with the request. This will also only return tradable items.
Inventory endpoint #1
http://steamcommunity.com/inventory/STEAM64ID/APPID/CONTEXTID
Another inventory endpoint which has the same parameters but in the URL. I use this endpoint as a fallback to the first, but I've found that if the first endpoint is rate limited then this one will be too. That said, this one becomes limited much faster so it's best to use the first one instead.
Inventory endpoint #2
http://steamcommunity.com/profiles/STEAM64ID/inventory/json/APPID/CONTEXTID
The endpoint you're using. I don't use this one at all, but it could be worth knowing as another fallback.

Not all of them return the same data format, so be mindful. One inventory a second is a pretty solid rate for any decently sized site, especially if you limit user's ability to refresh inventories. If you need more though, you'll have to start looking into proxies.


text:
Q: Getting "Undefined Javascript/css file" while using grunt to build source in angular project While trying to run my angular project, I used the following command
grunt --force

It automatically build a "dist" folder from where I am trying to run app pointing to "index.html"
But in index .html, the source of files created by grunt is giving "undefined file" error, and giving a 404 while running in browser.
The follwoing is my project structure.
myapp
app
dist
 scripts
   scripts.2ffedse.js
 styles
   main.f1de5fr6.css
 index.html

index.html
<link rel="stylesheet" href="styles/main.f1de5fr6.css"> --->giving error here

<div>
<!--  html code -->
</div>
<script src="scripts/scripts.2ffedfse.js"></script> -->giving error here

though the files are present in the src location it is still giving error.
The follwing is from cmd
/myapp/dist$ http-server -o
Starting up http-server, serving ./
Available on:
  http://127.0.0.1:8080

Can someone help me understand what exactly is this error with grunt.


text:
Q: Change Panel color with if statement I'm having an issue with changing the background color in aspx
My code
`<Div class="panel-<%=i >= 100 ? "Red" c >= 1 ? "Blue" : "green"%> "onclick= window.location = 'xxx.aspx';">`

For some reason it goes red when i is less them 100 and Green when i is greater but when c is grater then 1 it doesn't change
The red green and blue is CSS.

A: I think you haven't escaped your quotes properly:
Edit: I think another quote was missing. Try this:
<Div class="panel-<%=i >= 100 ? \"Red\" : c >= 1 ? \"Blue\" : \"green\"%>" onclick="window.location = 'xxx.aspx'">


text:
Q: ThriftCLIService: Error fetching results Any idea why in my log: spark-ubuntu-org.apache.spark.sql.hive.thriftserver.HiveThriftServer2-1-group-3-vm1.out I see this?
02:19:16 WARN ThriftCLIService: Error fetching results:
org.apache.hive.service.cli.HiveSQLException: Couldn't find log associated with operation handle: OperationHandle [opType=EXECUTE_STATEMENT, getHandleIdentifier()=2ea77d80-34f7-4b00-a8f1-7d544e9317a5]
        at org.apache.hive.service.cli.operation.OperationManager.getOperationLogRowSet(OperationManager.java:229)
        at org.apache.hive.service.cli.session.HiveSessionImpl.fetchResults(HiveSessionImpl.java:687)
        at sun.reflect.GeneratedMethodAccessor34.invoke(Unknown Source)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:606)
        at org.apache.hive.service.cli.session.HiveSessionProxy.invoke(HiveSessionProxy.java:78)
        at org.apache.hive.service.cli.session.HiveSessionProxy.access$000(HiveSessionProxy.java:36)
        at org.apache.hive.service.cli.session.HiveSessionProxy$1.run(HiveSessionProxy.java:63)
        at java.security.AccessController.doPrivileged(Native Method)
        at javax.security.auth.Subject.doAs(Subject.java:415)
        at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1628)
        at org.apache.hive.service.cli.session.HiveSessionProxy.invoke(HiveSessionProxy.java:59)
        at com.sun.proxy.$Proxy31.fetchResults(Unknown Source)
        at org.apache.hive.service.cli.CLIService.fetchResults(CLIService.java:454)
        at org.apache.hive.service.cli.thrift.ThriftCLIService.FetchResults(ThriftCLIService.java:672)
        at org.apache.hive.service.cli.thrift.TCLIService$Processor$FetchResults.getResult(TCLIService.java:1553)
        at org.apache.hive.service.cli.thrift.TCLIService$Processor$FetchResults.getResult(TCLIService.java:1538)
        at org.apache.thrift.ProcessFunction.process(ProcessFunction.java:39)
        at org.apache.thrift.TBaseProcessor.process(TBaseProcessor.java:39)
        at org.apache.hive.service.auth.TSetIpAddressProcessor.process(TSetIpAddressProcessor.java:56)
        at org.apache.thrift.server.TThreadPoolServer$WorkerProcess.run(TThreadPoolServer.java:285)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
        at java.lang.Thread.run(Thread.java:745)
~


text:
Q: How to validate a text with a custom regex validation with return type as true or false in Angular 7 I am new to Angular development. I have the following requirements.
In case of text field, we need to validate the data entered in the text field with a regular expression with some extra validation. In the .html file, the existing code is like this.
<input type="text" id="domainName" [pattern]="validateDomain()" [placeholder]="ComputeIPAddressMessages.DOMAIN_NAME_PLACEHOLDER" name="domainName" class="form-control"
              [(ngModel)]="computeIPAddress.domainName" [disabled]="disabledComponent" #domainNameModel="ngModel"
               size="20" required>

            {{ComputeIPAddressMessages.INVALID_DOMAIN_NAME}}

In the corresponding .ts file, the code is like this.
public validateDomain(): any {
    return CommonConstants.DOMAIN_NAME_REGEX;
  }

There are few new requirements so that I have to strip the contents of the html text and I have to do some manipulations before performing regular expression match.
SO I want to write method like this.
public validateDomain(): any {
        // Check if the domain name already exists or not
        // If the domain name start with .(period) or -(hyphen), remove it
        // Other check

        // perform some regular expression validation
       // Return either true or false
        return true or false;
      }

Is it possible in case of Angular 7 ? Please suggest and help me to achieve it. This is the way I want to do custom regex validation instead of directly passing a regular expression.

A: It is not possible to give extra validations aside from regex patterns in [pattern] or pattern attribute in Angular as per my knowledge. The best way to handle it is using traditional (change) event in the html input tag and corresponding function call from component file. Add a boolean flag isInvalidDomain which will set to true when the pattern along with your conditions after doing your manipulations are not matching and set to false if validations are matching.
sample.html
<input type="text" id="domainName" (change)="validateDomain()" [placeholder]="ComputeIPAddressMessages.DOMAIN_NAME_PLACEHOLDER" name="domainName" class="form-control" [(ngModel)]="computeIPAddress.domainName" [disabled]="disabledComponent" #domainNameModel="ngModel" size="20" required>
 {{ComputeIPAddressMessages.INVALID_DOMAIN_NAME}}

yourcomponent.ts
isInvalidDomain :boolean = false;
    validateDomain(){
       if(condition1 == true){
          if(computeIPAddress.domainName.test(CommonConstants.DOMAIN_NAME_REGEX)){
              this.isInvalidDomain = false;
            // success condition code
          } else {
              this.isInvalidDomain = true;
           }
       } else {
              this.isInvalidDomain = true;
       }
    }


text:
Q: Ignore changes in file under TFS I got some file Foo under TFS source control.
Foo is always modified by my script when i build my project (its related to project installer).
So for now i always need to check-out Foo to build my project, then discard any changes made in file before check-in to keep original default version.
Is there any way to have Foo under source control, but always ignore any changes made in this file and never check-out it even when i change it (check-out only if i forcely choose it).

A: there's a .tfignore file available?


text:
Q: Logo image in html I try to put logo using html and css .. here is the code which i try
<!Doctype html>

<link rel="stylesheet" type="text/css" href="Assignment/css">

I use sublime text editor so after this when i open index file this is what i see
image
sublime text

A: You need to use absolute path for image and css if you want that image will be displayed in text editor like http://www.yourdomain.com/Assignment/images/logo.png

A: Make sure that the image path is correct. For example, if your folder structure is:
|-Assignment
|----images
|--------logo.png
|----css
|----index.html

... then the path to your image should be images/logo.png.


text:
Q: React Native to limit lines in TextInput If set multiline as true, React Native will accept unlimited lines in TextInput, there has maxLength but it just limits the maximum number of characters, so how to set maximum lines on TextInput?

A: I created a simple version to extend the TextInput to give the maxLines feature.
import React, { Component } from "react";
import { TextInput } from "react-native";
import PropTypes from "prop-types";

export default class MultiLine extends Component {
  static propTypes = {
    maxLines: PropTypes.number
  };

  constructor(props) {
    super(props);
    this.state = {
      value: props.value || ""
    };
  }

  onChangeText = text => {
    const { maxLines, onChangeText } = this.props;
    const lines = text.split("\n");

    if (lines.length <= (maxLines || 1)) {
      onChangeText(text);
      this.setState({ value: text });
    }
 };

 render() {
   const { onChangeText, multiline, value, ...other } = this.props;
   return (
     <TextInput
       {...other}
       multiline={true}
       value={this.state.value}
       onChangeText={this.onChangeText}
     />
   );
 }
}

A example:
<Multiline
  value={this.state.testeText}
  maxLines={10}
  onChangeText={text => {
    this.setState({ testeText: text });
  }}
/>

A: I have implemented the following component for an app I'm the owner. It is tested only on a restricted environment, so it probably has to be adapted to your need. I am sharing here with the hope it helps the community.
react-native: 0.46.3
import React, { Component } from 'react'
import { TextInput, Platform } from 'react-native'

const iosTextHeight = 20.5
const androidTextHeight = 20.5
const textHeight = Platform.OS === 'ios' ? iosTextHeight : androidTextHeight

class TextInputLines extends Component {
  state = { height: textHeight * 2, lines: 1 }

  componentWillReceiveProps (nextProps) {
    if (nextProps.value === '') {
      this.setState({ height: textHeight * 2, lines: 1 })
    }
  }

  render () {
    const {style, value, placeholder, numberOfLines = 8, autoFocus = true, onChangeText} = this.props

    return (
      <TextInput
        style={[style, { height: this.state.height }]}
        multiline
        autoFocus={autoFocus}
        value={value}
        placeholder={placeholder}
        onChangeText={(text) => onChangeText(text)}
        onContentSizeChange={(event) => {
          const height = Platform.OS === 'ios'
            ? event.nativeEvent.contentSize.height
            : event.nativeEvent.contentSize.height - androidTextHeight
          const lines = Math.round(height / textHeight)
          const visibleLines = lines < numberOfLines ? lines : numberOfLines
          const visibleHeight = textHeight * (visibleLines + 1)
          this.setState({ height: visibleHeight, lines: visibleLines })
        }}
        underlineColorAndroid='transparent'
      />
    )
  }
}

export default TextInputLines

How to use:
import TextInputLines from './TextInputLines'

Within your render() method:
<TextInputLines
   style={textStyle}
   autoFocus={true}
   value={this.state.value}
   placeholder={textPlaceholder}
   onChangeText={onChangeText}
   numberOfLines={10}
/>

A: You can use maxHeight and minHeight to accept what you want. For standard text fontSize, giving maxHeight={60} will make TextInput scrollable after 3 lines. This is good for IOS - for Android you can use numberOfLines prop.

A: I don't think you can on iOS. As mentioned, Android has the prop numberOfLines. The closest I can think of would be to try to estimate the width of your input and limit the characters based on that dimension but it's my opinion that it may be a dark path to go down.
Should you choose to do so, someone was trying to get the number of lines here. A combination of the onLayout function to get the width of your TextInput and onChangeText to limit it might work.

A: It seems no props or packages to quickly implement checking number of lines, so I use javascript function match to get the number from TextInput, then if the number reach the max value, do something to limit it.

A: numberOfLines doesn't nothing in android too
You can do something like this
In Component state
this.state = {height: 35};

In JSX TextInput declaration
style={[styles.default, {height: Math.min(Math.max(35, this.state.height),120)}]}

A: I solved the limit issue using maxHeight,numberOfLine and multiline prop
<TextInput placeholder="description here" numberOfLines={3} maxHeight={60} onChangeText={t => setDescription(t)} multiline={true} style={{ margin: 10, borderRadius: 20, padding: 5, borderWidth: 1 }} />

A: I was solving this same issue. Here's what I came up with.
You can either remove the last trailing newline, or all of them. Both work differently, so use accordingly to how you want yours to function. I personally chose the remove last trailing newline alternative:
function onChangeText(text) {
    if (props.multiline) {
        const newlines = (text.match(/\n/g) || '').length + 1;
        if (newlines > MAX_LINES) {
            props.setState(text.replace(/\n$/, "")); // Remove last trailing newline
            // props.setState(text.replace(/\n+$/, "")); // Remove all trailing newlines
            return;
        }
    }
    props.setState(text);
    return;
};


text:
Q: Spring Cloud Docker Keycloak HTTP 401 Unauthorized error from API Gateway to Service I have a problem about creating user through Keycloak in my Spring Cloud example which runs on Docker.
When I make a request through this url http://localhost:8600/api/v1/users/signup (from api gateway to user service), I got this issue on the console.
Here is the error shown below.
2022-08-24 10:45:22.610  INFO 1 --- [nio-9000-exec-1] c.s.u.controller.UserController          : UserController | signUpUser is started
2022-08-24 10:45:22.610  INFO 1 --- [nio-9000-exec-1] c.s.u.controller.UserController          : UserController | signUpUser | SignUpRequest role : ROLE_USER
2022-08-24 10:45:22.610  INFO 1 --- [nio-9000-exec-1] c.s.u.controller.UserController          : UserController | signUpUser | SignUpRequest email : springbootmicroserviceuser@user.com
2022-08-24 10:45:22.611  INFO 1 --- [nio-9000-exec-1] c.s.u.controller.UserController          : UserController | signUpUser | SignUpRequest name : Micro User
2022-08-24 10:45:22.623  INFO 1 --- [nio-9000-exec-1] c.s.u.service.impl.UserServiceImpl       : UserServiceImpl | signUpUser is started
2022-08-24 10:45:22.627  INFO 1 --- [nio-9000-exec-1] c.s.u.service.impl.KeycloakServiceImpl   : KeycloakServiceImpl | createUserWithKeycloak is started
2022-08-24 10:45:22.763 ERROR 1 --- [nio-9000-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw excepti
on [Request processing failed; nested exception is javax.ws.rs.ProcessingException: javax.ws.rs.NotAuthorizedException: HTTP 401 Unauthorized] with root cause

javax.ws.rs.NotAuthorizedException: HTTP 401 Unauthorized

Here is the keycloak configuration class defined in user service.
@Configuration
public class KeycloakConfig {

    public final static String serverUrl = "http://keycloak:8080";
    public final static String realm = "master";
    public final static String clientId = "spring-boot-microservice-keycloak";
    public final static String clientSecret = "ZDyqUYwec1qUeTdxiM2Ym99KiPE73vzU";
    final static String userName = "admin";
    final static String password = "admin";

    @Bean
    public KeycloakConfigResolver keycloakConfigResolver(){
        return new KeycloakSpringBootConfigResolver();
    }

    @Bean
    public Keycloak keycloak(){
          return Keycloak.getInstance(serverUrl,
                realm,
                userName,
                password,
                clientId,
                clientSecret);
    }
}

Here is the keycloak part of docker-compose.yml
keycloak:
    image: quay.io/keycloak/keycloak:18.0.2
    environment:
      - KEYCLOAK_ADMIN=admin
      - KEYCLOAK_ADMIN_PASSWORD=admin
    ports:
      - "8181:8080"
    networks:
      - backend
    command:
      - start-dev

Here is my project Link : Link

A: You're trying to call on different port (8080) than Keycloak is exposed (8181). Try with changing serverUrl to "http://keycloak:8181".


text:
Q: python - How to count number of files recursively in a path using multiprocessing Lets suppose I have a single node with infinite number of CPUs and infinite I/O resources. I would like to write a python script which uses multiprocessing and calculates the total amount of files in a given path and all the subdirectories
example:
I run a script which generates millions of files in a given path:
#!/usr/bin/env bash

NUMDIRS=300000
NUMFILES=10

myPath="/tmp/test"

echo "Working on path: $myPath"

for directory in `seq 1 $NUMDIRS`
do
    mkdir -p "$myPath/$directory"
    cd $myPath/$directory
    for file in `seq 1 $NUMFILES`
    do
        touch "file_$file.txt"
        echo "Path:       $myPath/$directory" >> file_$file.txt
        echo "Filename:   file_$file.txt" >> file_$file.txt
        echo "Created on: `date +"%Y%m%d-%H%M%S"`" >> file_$file.txt
    done
done

Even if this is not the best example to use multiprocessing, just for learning purposes, I would like to know how I could write a python piece of code to use multiprocessing and return 3000000 following the provided example (300000 directories x 10 files per directory).
EDIT:
A first unsuccessful approach:
#!/usr/bin/env python3

import os
import multiprocessing

path = "/tmp/test"

def count_single_process(path):
    cpt = sum([len(files) for r, d, files in os.walk(path)])
    return cpt

def walkingThePath(path):
    for r, d, f in os.walk(path):
        return len(f)

def main():
    cpu_number = multiprocessing.cpu_count()
    with multiprocessing.Pool(cpu_number) as Pool:
        print(Pool.map(walkingThePath, path))

if __name__ == '__main__':
    main()


text:
Q: Display Special Character in Repeater Based on the DataItem Value I'm calling a stored procedure by passing the input from the webpage and saving the results in ArrayList. Each record in the ArrayList has column with name: type. If type is "A",
then I need display a special character on web page for the column value for the associated row.For the remaining type records in the results ArrayList,
i don't need to display anything for the associated rows..
in code behind file:
Dim array As New ArrayList

            array = outPutFromTheSporedProcedure
              repeater1.DataSource = array
            repeater1.DataBind()

On aspx.page:
<asp:Repeater ID="repeater1" runat="server">
                            <HeaderTemplate>

                                                 type

                            </HeaderTemplate>
                            <ItemTemplate>

                                        <asp:Label ID="lbl123" runat="server"><%#DataBinder.Eval(Container.DataItem, "type")%></asp:Label>

                            </ItemTemplate>
                            <FooterTemplate>

                            </FooterTemplate>
                        </asp:Repeater>

On Aspx Page
I have a repeater and binding a data item to repeater in itemTemplate.
Now i need to display special character(i.e *, $, &, basically to differentiate from other type of rows)
for type of rows "A", for remaining rows, i need to display nothing for the records for the associated column.
Please let me know how to solve this one. Thanks in Advance!

A: Since you want to display nothing for the non-special conditions you must first change this:
<asp:Label ID="lbl123" runat="server"><%#DataBinder.Eval(Container.DataItem, "type")%></asp:Label>

To This:
<asp:Label ID="lbl123" runat="server"></asp:Label>

Now, set your special character in the Repeater_ItemDataBound Event Handler if the conditions are met:
Private Sub repeater1_ItemDataBound(sender As Object, e As RepeaterItemEventArgs) Handles repeater1.ItemDataBound

    If e.Item.ItemType = ListItemType.AlternatingItem OrElse e.Item.ItemType = ListItemType.Item Then

        If CType(e.Item.DataItem, UnderlyingTypeOfArrayList).type = "A" Then

            CType(e.Item.FindControl("lbl123"), Label).Text = "*" 'Special Character

        End If

    End If

End Sub

You see above that I check for the correct RepeaterItemType, if tghe DataItem's type Property = A, and if so, I get an instance of the label using FindControl and Casting to set its Text to the special character.
Note: You'll have to change UnderlyingTypeOfArrayList to the Type contained in the ArrayList.


text:
Q: What's a good global exception handling strategy for Unity3D? I'm looking into doing some Unity3D scripting stuff, and I'd like to set up global exception handling system. This is not for running in the release version of the game, the intention is to catch exceptions in user scripts and also in editor scripts and make sure they are forwarded to a database for analysis (and also to send email to relevant devs so they can fix their shizzle).
In a vanilla C# app I'd have a try-catch around the Main method. In WPF I'd hook one or more of the unhandled exception events. In Unity...?
So far the best I've been able to come up with is something like this:
using UnityEngine;
using System.Collections;

public abstract class BehaviourBase : MonoBehaviour {

    // Use this for initialization
    void Start () {

    }

    // Update is called once per frame
    void Update () {
        try
        {
            performUpdate();
            print("hello");
        }
        catch (System.Exception e)
        {
            print(e.ToString());
        }

    }

    public abstract void performUpdate();

}

In other scripts, I derive BehaviourBase instead of MonoBehavior and implement performUpdate() instead of Update(). I haven't implemented a parallel version for Editor clases but I assume I'd have to do the same thing there.
I don't like this strategy, however, because I'll have to backport it to any scripts we grab from the community (and I'll have to enforce it on the team). The Editor scripts don't have a single point of entry comparable to MonoBehavior either, so I assume I'd have to implement exception safe versions of wizards, editors and so on.
I've seen suggestions about catching log messages (as opposed to exceptions) using  Application.RegisterLogCallback, but this makes me uncomfortable because I'd need to parse the debug log string rather than having access to the actual exceptions and stacktraces.
So... what's the right thing to do?

A: Unity devs just do not provide us with tools like that. They catch exceptions internally in framework here and there and log them as strings, giving us Application.logMessageReceived[Threaded]. So, if you need exceptions to happen or be logged with your own processing (not unity's) I can think of:

*

*do not use framework mechanics, but use your own so exception is not caught by framework

*make your own class implementing UnityEngine.ILogHandler:
public interface ILogHandler
{
    void LogFormat(LogType logType, Object context, string format, params object[] args);
    void LogException(Exception exception, Object context);
}

And use it as said in official docs to log your exceptions. But that way you do not receive unhandled exceptions and exceptions logged from plugins (yes, someone do log exceptions in frameworks instead of throwing them)

*Or you can make a suggestion/request to unity to make Debug.unityLogger (Debug.logger is deprecated in Unity 2017) have setter or other mechanism so we can pass our own.

*Just set it with reflection. But it's temporary hack and will not work when unity change code.
var field = typeof(UnityEngine.Debug)
    .GetField("s_Logger", BindingFlags.Static | BindingFlags.NonPublic);
field.SetValue(null, your_debug_logger);

Note: To get correct stacktraces you need to set StackTraceLogType in editor settings/code to ScriptOnly (most times it's what you need, I wrote an article on how it work) And, when building for iOS, it is said that Script call optimization must be set to slow and safe
If interested, you can read how popular crash analytics tool works. If you look into crashlytics (crash report tool for android/ios), than you'll find out that it internally uses Application.logMessageReceived and AppDomain.CurrentDomain.UnhandledException events to log managed C# exceptions.
If interested in examples on unity framework catching exceptions, you may look at ExecuteEvents.Update And another article from me with testing it catching exception in button click listener can be found here.
Some summary on official ways to log unhandled exception:
I. Application.logMessageReceived is fired when exception happens on main thread. There are ways for it to happen:

*

*exception caught in c# code and logged through Debug.LogException

*exception caught in native code (probably c++ code when using il2cpp). In that case native code calls Application.CallLogCallback which results in firing Application.logMessageReceived
Note: StackTrace string will contain "rethrow" when original exception have inner exceptions
II. Application.logMessageReceivedThreaded is fired when exception happens on any thread, including main (it's said in docs) Note: it must be thread-safe
III. AppDomain.CurrentDomain.UnhandledException for example is fired when:
You call the following code in editor:
 new Thread(() =>
    {
        Thread.Sleep(10000);
        object o = null;
        o.ToString();
    }).Start();

But it causes crash on android 4.4.2 release build when using Unity 5.5.1f1
Note: I reproduced some bugs with unity missing stackframes when logging exceptions and assertions. I submited one of them.

A: Create an empty GameObject in your scene and attach this script to it:
using UnityEngine;
public class ExceptionManager : MonoBehaviour
{
    void Awake()
    {
        Application.logMessageReceived += HandleException;
        DontDestroyOnLoad(gameObject);
    }

    void HandleException(string logString, string stackTrace, LogType type)
    {
        if (type == LogType.Exception)
        {
             //handle here
        }
    }
}

make sure there is one instance.
The rest is up to you. You can also store the logs in file system, web server or cloud storage.

Note that DontDestroyOnLoad(gameObject) makes this GameObject persistent, by preventing it from being destroyed in case of scene change.

A: You mentioned Application.RegisterLogCallback, have you tried implementing it?  Because the logging callback passes back a stack trace, an error, and an error type (warning, error, etc).
The strategy you outline above would be tough to implement because MonoBehaviours don't just have a single entry point.  You'd have to handle OnTriggerEvent, OnCollisionEvent, OnGUI, and so on.  Each one wrapping its logic in an exception handler.
IMHO, exception handling is a bad idea here. If you don't immediately re-throw the exception, you'll end up propagating those errors in weird ways.  Maybe Foo relies on Bar, and Bar on Baz.  Say Baz throws an exception that is caught and logged.  Then Bar throws an exception because the value it needs from Baz is incorrect.  Finally Foo throws an exception because the value it was getting from Bar is invalid.

A: There is a working implementation of RegisterLogCallback that I found here: http://answers.unity3d.com/questions/47659/callback-for-unhandled-exceptions.html
In my own implementation I use it to call my own MessageBox.Show instead of writing to a log file. I just call SetupExceptionHandling from each of my scenes.
    static bool isExceptionHandlingSetup;
    public static void SetupExceptionHandling()
    {
        if (!isExceptionHandlingSetup)
        {
            isExceptionHandlingSetup = true;
            Application.RegisterLogCallback(HandleException);
        }
    }

    static void HandleException(string condition, string stackTrace, LogType type)
    {
        if (type == LogType.Exception)
        {
            MessageBox.Show(condition + "\n" + stackTrace);
        }
    }

I also now have the error handler email me via this routine, so I always know when my app crashes and get as much detail as possible.
        internal static void ReportCrash(string message, string stack)
    {
        //Debug.Log("Report Crash");
        var errorMessage = new StringBuilder();

        errorMessage.AppendLine("FreeCell Quest " + Application.platform);

        errorMessage.AppendLine();
        errorMessage.AppendLine(message);
        errorMessage.AppendLine(stack);

        //if (exception.InnerException != null) {
        //    errorMessage.Append("\n\n ***INNER EXCEPTION*** \n");
        //    errorMessage.Append(exception.InnerException.ToString());
        //}

        errorMessage.AppendFormat
        (
            "{0} {1} {2} {3}\n{4}, {5}, {6}, {7}x {8}\n{9}x{10} {11}dpi FullScreen {12}, {13}, {14} vmem: {15} Fill: {16} Max Texture: {17}\n\nScene {18}, Unity Version {19}, Ads Disabled {18}",
            SystemInfo.deviceModel,
            SystemInfo.deviceName,
            SystemInfo.deviceType,
            SystemInfo.deviceUniqueIdentifier,

            SystemInfo.operatingSystem,
            Localization.language,
            SystemInfo.systemMemorySize,
            SystemInfo.processorCount,
            SystemInfo.processorType,

            Screen.currentResolution.width,
            Screen.currentResolution.height,
            Screen.dpi,
            Screen.fullScreen,
            SystemInfo.graphicsDeviceName,
            SystemInfo.graphicsDeviceVendor,
            SystemInfo.graphicsMemorySize,
            SystemInfo.graphicsPixelFillrate,
            SystemInfo.maxTextureSize,

            Application.loadedLevelName,
            Application.unityVersion,
            GameSettings.AdsDisabled
        );

        //if (Main.Player != null) {
        //    errorMessage.Append("\n\n ***PLAYER*** \n");
        //    errorMessage.Append(XamlServices.Save(Main.Player));
        //}

        try {
            using (var client = new WebClient()) {
                var arguments = new NameValueCollection();
                //if (loginResult != null)
                //    arguments.Add("SessionId", loginResult.SessionId.ToString());
                arguments.Add("report", errorMessage.ToString());
                var result = Encoding.ASCII.GetString(client.UploadValues(serviceAddress + "/ReportCrash", arguments));
                //Debug.Log(result);
            }
        } catch (WebException e) {
            Debug.Log("Report Crash: " + e.ToString());
        }
    }

A: You can use a plugin called Reporter to receive an email of Debug Logs, Stack trace and screen capture on the moment of unhandled Error. Screen capture and stack trace are usually enough to figure out the reason of the Error. For stubborn sneaky Errors you should log more of suspicious data, build and wait again for the error.I Hope this helps.


text:
Q: Hotcakes Commerce Extending the DrillDown ViewModel I'm using v 1.10.3 of HC and I'm trying to extend the ViewModel for the drilldown view. I want to add a new boolean property to the products so that I can check it and add some html to the view as necessary. So inside of Category.js I thought I'd loop through the data, and add the new property to the ViewModel so that it could be used in the View. The loop is where I'm having a problem. When I debug the code, the loop adds the property as expected, but when the page finishes loading and I check the source, none of the modifications are present in the Json object.
function HcDrillDownFilterViewModel(data, $form, catId, modId) {
var DECIMAL_SEP = ".";
var self = this;

for (var i = 0; i < data.Products.length; i++) {
    var p = data.Products[i];
    if (p.ProductName.toLowerCase().indexOf('nike') > -1) {
        p.NikeBrand = true;
    } else {
        p.NikeBrand = false;
    }
}
    // Binding
    self.model = ko.observable();
    self.minPrice = ko.observable(data.SelectedMinPrice);
    self.maxPrice = ko.observable(data.SelectedMaxPrice);

Any ideas on what I'm missing to get these changes to persist to the ViewModel?

A: What you're running into is simply a tiny learning curve with how KnockoutJS works.  Since it's a framework with a lot of bindings and other things working, you need to work with it.  Oftentimes, this means a raw JS snippet may not work as expected.
To be honest, I rarely touch this view myself, because I'm not very well versed in KO either, but I managed to get a proof of concept working based upon your question.
First, in your code, you're updating the array objects, but you're only updating it in one of the places that binds to the view.  It needs to be done in two places.  This is the primary reason you don't see your updates applied.
In place of your original snippet, I've put this call to a method I created in the same JS file.
// update Products how you'd like
data.Products = parseProducts(data.Products);

Then, I did the same in the top of the handleDrillDown() function.
// this needs to get called here too
data.Products = parseProducts(data.Products);

Now, there may be a better way to do this, but the final update in this file did all the work by adding the function you see below.  In my case, I used the sample products that come out-of-the-box and simply checked for the Brown Fedora.  You'll also notice that I'm using the built-in foreach that Knockout provides.  You should do this whenever using a framework.
function parseProducts(products) {
    // instantiate a local array of products to work with
    var arrProducts = products;
    // loop through and apply your changes
    ko.utils.arrayForEach(arrProducts, function (p) {
        // check your condition
        if (p.ProductName.toLowerCase().indexOf("fedora") > -1) {
            p.CoolHat = true; // new property that wasn't there before
        } else {
            p.CoolHat = false; // new property that wasn't there before
        }
    });
    // send back the new array
    return arrProducts;
}

Finally, I updated the drilldown Razor view markup to see if my changes were reflected as I expected, by adding this snippet after the product name.
This is a really cool hat!

The result was that only the Fedora was getting "tagged" with this text.


text:
Q: loop running continuously when using keys[pygame.K_SPACE] Python/Pygame I'm a grade 10 student working on a simple video game project in Python with Pygame.
When I press the spacebar this code should execute:
if keys[pygame.K_SPACE]:

    shotflag = True

    shotX = shipX+((shipwidth/2)-(shotwidth/2))

    shotY = shipY - 10

The problem is ... it executes continuously until I take my finger off the spacebar. I only want it to execute once.
Is there a better way to do this?  Can I use a spacebar RELEASED event?  So it only fires once?
Thanks in advance.
Matthew

A: Adding on to Ianin Shelvington's answer, you should be handling events in your main game loop.
More information in the pygame docs :here
for event in pygame.event.get():
    if event.type == pygame.QUIT:
        running = False
    if event.type == pygame.KEYDOWN:
        if event.key == pygame.K_SPACE:
            #TODO


text:
Q: Rails validation for has_one relation I have two model like:
class Employee
  field :name
  field :login, type: Boolean
  has_one :user
end

class User
  field :username
  field :email
  belongs_to :employee
  validates_presence_of :username
end

I want to create an user account when create employee if check box of login field is checked. For this my new action of employees controller is:
def index
    @employee = Employee.new
    @employee.build_user
end

For this my form code is:
<%= simple_form_for(@employee) %>
<%= f.input :login, :as => :boolean, :label => "Create User" %>
<div class="create-user" style="display: none">
  <%= f.simple_fields_for :user do |u| %>
    <%= render 'user_fields', {f: u} %>
  <% end %>
</div>
    <button class="btn btn-info">Save Change</button>
 <% end %>

and the _user_fields.html.erb is:
<%= f.input :username %>

I want to validate the user model when check_box of :login field is checked. On unchecked condition the form should be submit. What is the better solution.

A: Maybe you can move your user validation into employer model ?
something like code below should solve your problems
validates_presence_of :username, :if => login?

What do you think?

A: maybe use validates_associated:
http://guides.rubyonrails.org/active_record_validations_callbacks.html#validates_associated
or delegation + validates presence might also work

delegate :username, to: :user, allow_nil: true
validates :username, presence: true, if: :login

A: Finally I got its solution:
class Employee
  field :name
  field :login, type: Boolean
  has_one :user
  has_one :user, :class_name => "User", :dependent => :destroy
  accepts_nested_attributes_for :user, :reject_if => :login_blank
  def login_blank
    return false if self.login == true
    return true if self.login == false
  end
end


text:
Q: extract json to excel table using vba I try to extract json data to excel table using vba. I have installed VBA-JSON and turned on Microsoft Scripting Runtime.
the json request delivers:
{
  "STATUS": "SUCCESS",
  "RESULT": {
    "aid": "17903",
    "ean": 4003483179030,
    "title": " Manzanita, sandgestrahlt, verzweigt, 90-100 cm",
    "shortdesc": " Echte Äste direkt aus der Natur, ca. 90-100 Zentimeter lang. Wunderschön für natürliche Dekorationen oder als Kontrast zu Pflanzgefäßen und Vasen aus anderen Materialien. Sauber, da sandgestrahlt. Jedes Stück ein Unikat (Abbildungen beispielhaft).",
    "longdesc": "Ein besonderer Blickfang sind Dekorationen aus echten, natürlichen Materialien wie MANZANITA Zweigen. Die echten Zweige eignen sich perfekt als Kontrast zu Pflanzgefäßen und Vasen aus anderen Materialien. Sauber, da sandgestrahlt. Jedes Stück ein Unikat (Abbildungen beispielhaft).",
    "length": "0",
    "width": "0",
    "height": "90",
    "weight": "1",
    "pic01": "17903_manzanitasandblastedbranchy.jpg",
    "pic02": "17903_manzanitasandblastedbranchy~01.jpg",
    "pic03": "17903_manzanitasandblastedbranchy~02.jpg",
    "pic04": "",
    "pic05": "",
    "pic06": "",
    "pic07": "",
    "pic08": "",
    "pic09": "",
    "pic10": "",
    "pic11": "",
    "pic12": "",
    "attributes": [
      {
        "id": "oxattribute1013",
        "title": "Aktueller Katalog",
        "value": "1"
      },
      {
        "id": "oxattribute1021",
        "title": "Aktueller Katalog - Seitenzahl",
        "value": "238-1"
      },
      {
        "id": "oxattribute1007",
        "title": "Paket - Versand",
        "value": "1"
      },
      {
        "id": "oxattribute1020",
        "title": "Serie",
        "value": "MANZANITA"
      },
      {
        "id": "oxattribute1019",
        "title": "Funktionsname",
        "value": "Ast"
      },
      {
        "id": "oxattribute1018",
        "title": "Farbbezeichnung",
        "value": "sandgestrahlt"
      },
      {
        "id": "oxattribute1005",
        "title": "Speditionsversand",
        "value": "1"
      }
    ]
  }
}
i wrote it in a excel cell (1,1) and parsed it using jsonconverter.
with the code
Sub Jsonauslesenbenny()

Dim jsonText As String
Dim jsonObject As Object

Dim i As Long
Dim ws As Worksheet

Set ws = Worksheets("Tabelle1")

jsonText = ws.Cells(1, 1)

Set jsonObject = JsonConverter.ParseJson(jsonText)

i = 3

For Each item In jsonObject("RESULT")
Sheets(1).Cells(i, 1).Value = item("aid")
Sheets(1).Cells(i, 2).Value = item("ean")
Sheets(1).Cells(i, 3).Value = item("title")

i = i + 1
Next

End Sub

in that way the items "aid" to "pic12" can be written in excel cell.
I dont get it work to write the items after "attributes" in excel table cells.
how can I write "id", "title" and "value" from the json data to the excel table?

A: Try this code
Sub Jsonauslesenbenny()
    Dim ws As Worksheet, jsonObject As Object, jsonText As String, i As Long

    Set ws = Worksheets("Tabelle1")
    jsonText = ws.Cells(1, 1)
    Set jsonObject = JSONConverter.ParseJson(jsonText)
    i = 3

    With Sheets(1)
        .Cells(i, 1).Value = jsonObject("RESULT")("aid")
        .Cells(i, 2).Value = jsonObject("RESULT")("ean")
        .Cells(i, 3).Value = jsonObject("RESULT")("title")
    End With
End Sub

To get the attibutes
Sub GetAttributes()
    Dim itm, ws As Worksheet, jsonObject As Object, jsonText As String, i As Long

    Set ws = Worksheets("Tabelle1")
    jsonText = ws.Cells(1, 1)
    Set jsonObject = JSONConverter.ParseJson(jsonText)
    i = 3

    For Each itm In jsonObject("RESULT")("attributes")
        With Sheets(1)
            .Cells(i, 1).Value = itm("id")
            .Cells(i, 2).Value = itm("title")
            .Cells(i, 3).Value = itm("value")
        End With
        i = i + 1
    Next itm
End Sub


text:
Q: Drawing a cuboid with CSS I'm trying to draw a cuboid with css (like this http://upload.wikimedia.org/wikipedia/commons/d/dc/Cuboid.png but ONLY 3 visible faces needed)
Lots of stuff checked, but nothing found exactly :S
Can anyone help?
SOLVED. The code is:

A: If you're ok with css3, you can use transforms. Have 3 separate div elements and apply the transformations on each.
Something like this in Mozilla
-moz-transform:    rotate(15deg)
                   translateX(230px)
                   scale(1.5);

And Like this in IE
-ms-filter: "progid:DXImageTransform.Microsoft.Matrix(M11=1.4488887394336025, M12=-0.388228567653781, M21=0.388228567653781, M22=1.4488887394336025, SizingMethod='auto expand')";

Alternatively try :
http://www.useragentman.com/tests/cssSandpaper/cube3.html


text:
Q: Tracking a users position and showing it on the map for all other users - Android I was searching for hours, but I can't find an answer on this topic. I have managed to set up an application which shows my position, tracks it and updates my marker whenever my position changes.
I would like to do the same for all other users (for finding friends), but I don't understand the right way this has to be done.
Should I upload each users Lat and Lng to a server, then downloading it while placing markers on the map? This way I may not get fast location updates, or does the Google Map Api contain some tools to achieve this in the right way?
I would really appreciate some help.
E.
UPDATE
After doing some more resources, I realised that an online database is the way to go for this task.
Steps I made to read save and retrieve users positions:

*

*Create an online (mysql) database

*in my android project I have implemented: GooglePlayServicesClient.ConnectionCallbacks,GooglePlayServicesClient.OnConnectionFailedListener. But most important is LocationListener - to receive the current location coordinates each time the user changes position.

*I then uploaded the coordinates using the HttpUrlConnection via POST method, and adding them to the database using php.

*back in the app I create a new instance of the GoogleMap class, and the same way as I have uploaded I download all other users coordinates via HttpUrlConnection, iterate over the JSON response and placing markers on the map in the same time.

Everything works like it should, there may be other ways but I think this is the most straight forward solution. Hope this small guide will help.


text:
Q: Understanding wildcard-constraint  super T> I can work with basic generic expression but the wildcard-constraints just mess with my mind.
Info: Student extends Person and Person extends Animal
 List<? super Animal> aList= new ArrayList<>();

       // does not compile as expected,
       // since the list is restricted to something that has Animal as superclass.
       // aList.add(new Object());

    aList.add(new Animal()); // I can add animal
    aList.add(new Person()); // I can add Person
    aList.add(new Student()); // I can add Student

    Animal a = new Animal();
    Animal b = new Animal();
    Person p = new Person();
    Student s = new Student();
    // test
    a = b; //I can assign an animal to another animal
    a = p; // I can assign a person to an animal
    a = s; // I can assign a student to an animal

    Animal animal = aList.get(0); // DOES NOT COMPILE, WHY ?

QUESTION: I don't understand why the last assignment does not work. The examples above show, that anything in that list is definitely an animal, yet I can't get an animal from that list.
MORE SPECIFIC: When I know that I can add only types which have Animal as superclass, why can't I expect to remove objects from type Animal ?
FACT: I can ONLY add objects which extend Animal! I just tried to add a car object and it does not work !
I am starting to doubt my sanity, I hope you can help me. Thank You
Additionally:
Object animal = aList.get(0); // works

Why does this statement work even though I know that I can't add an Object-Type ?
SOLUTION: (Based on the accepted answer)
I misunderstood the meaning of <? super Animal>
What I thought it means: Any class which has Animal as superclass.
What it (apparently) means: Any Class which is  superclass of Animal.
Therefore a List might also contain objects of type Object which is why Animal animal = aList.get(0); fails.
Cheers

A: List<? super Animal> means a list of any superclass of Animal. If Animal is a subclass of LivingThing, then List<? super Animal> can be a list of Animals, a list of LivingThings, or a list of Object. In the last two cases, the assignment Animal x = aList.get(0) would of course be illegal, because you cannot assign a LivingThing to a reference of type Animal.
Consider the following method (it will not compile):
void f(List<? super Animal> list) {
    Animal a = list.get(0); // line 1
    list.add(new Object()); // line 2
}

The method call
List<Object> list = new ArrayList<>();
list.add(new Object());
f(list);

is correct, because Object is a superclass of Animal. However, if the method f would compile, you would try to assign in Line 1 an Object to an Animal reference, so it would not be type safe.
On the other, hand consider the method call:
f(new List<Animal>());

If the method f would compile, we would now be adding an Object instance to a list which should only contain Animals.
That's why both Line 1 and Line 2 are not allowed. If you have a class
public class A<T> {
    public put(T in) { }
    public T get() { }
}

then for the type A<? super Animal> the method get will return a Object (not an Animal), while the method put expects a parameter of type Animal.

A: The other answers here are right, but not stated clearly enough, which is where the confusion is coming from.
A List<? extends Animal> does not mean "A list of things that all extend Animal."  It means "A list of some type T, which I won't tell you what it is, but I know that T extends Animal."  (In type theory, these are called existential types -- there exists a type T for which our List is a List<T>, but we don't necessarily know what T is.)
The difference is important.  If you have "a list of things that all extend Animal", then it would be safe to add a Dog to the list -- but this is not what wildcards express.  A List<? extends Animal> means "List of something, where that something extends Animal".  It might be a List<Animal>, or a List<Dog>, or a List<Cat> -- we don't know.  So we have no reason to think that its safe to add a Dog to that list -- because maybe my List is a List<Cat>.
In your example, you have a List<? super Animal>.  This means, a list of some type T, where T is one of the supertypes of Animal.  It might be a List<Object>, or a List<Animal>, or if Animal has a supertype HasLegs, it might be a List<HasLegs>.  Here, it's safe to put a Dog into this list -- because whatever its a List of, Dog is definitely one of those (Animal, Object, etc), but when you take something out of the list, you have no idea whether its a Dog, an Animal, or just an Object.

A: List<? super Animal> aList is reference which can be used to handle List<Animal> , it can also be any superclass of Animal such as List<Object>.
In other words List<? super Animal> aList
 - is not reference to some list which can store any supertype of Animal.
 + it is reference to list of some specific type which is supertype of Animal (including Animal itself) but you don't know which type it is exactly.
So it could be
List<Object> someList = new ArrayList<>();
someList.add(new Car());//OK since Car is a Object
List<? super Animal> aList = someList;// OK since Object is supertype of Animal

Because of that, code
Animal a = aList.get(0);//and where did that Car come from?

is not safe. Only safe type to store the result of get(0) is Object so you either need
Object o = aList.get(0);

or if you want to make sure that get will return Animal, change the type of your aList reference to List<Animal> or even List<? extends Animal>.


text:
Q: How can we upload multiple html files and replace the text inside and get the output html pages with the help of javascript From following code it accepts Single File and process it & display output.but can it be possible to accept multiple files and process & then return output.

       Choose file
       <input id="text" type="file" name="photo">

    <textarea id="finalHTML" style="height:200px;width:80%">

    </textarea>

<button id="save">Save</button>

I am not able to accept multiple files and process on it,and return Output.
Any one can help me out please.

A: You used input type 'file' there is an attribute multiple ="multiple" which allows you to select multiple file at once. How to handle those files using JavaScript? you can look at this link ...Multiple-files-selected
try this and look at the for loop block... I'm not tasted it...
$('input').change(function(){
for(var i = 0; i<= files.length; i++){
  if (this.files && this.files[i]) {
var reader = new FileReader();
reader.onload = function (e) {
console.log(e);
selectedImage = e.target.result;
var rawData = reader.result;
console.log(rawData);

  var array = {
    'j':'⇔',
    'C':'C',
    'g':'œ',
    'i':'~',

}

var originalText = rawData.toString();
var finalText = originalText;

for (var val in array)
   finalText = finalText.replace(new RegExp(val, "g"), array[val]);

console.log(finalText);

$('#finalHTML').text(finalText);

  };

  reader.readAsBinaryString(this.files[i]);
 //reader.readAsDataURL(this.files[0]);

  }
}
});


text:
Q: Can page be used synonymous for section in webdesign? On some freelancer pages, webdesigner are payed per section of a webpage. However, I found many webdesigner who use pages or screen synonymously for section, especially non-native freelancer from Sri Lanka / Pakistan / Bangladesh. I wonder, is this correct usage? Or is this a  common non-native English speaker issue?
Example: One webpage with 3 sections:

Some examples of webdesign offers on freelancer page:

A: I'm not sure how well this answers the technical problem that you have, but yes, page screen and section all have rather different meanings to me, as an IT Pro.
However the problem that you have, is that the meaning depends on context (doesn't everything?) So, for example, a single PHP file may produce every single visible page on a particular website, so to the site owner, there may be thousands of pages, but to a back-end developer there is only one page, producing loads of screens.
'Section' is a little harder - it could mean a small part of a page (there is an HTML element precisely for this) or it could be the equivalent of a chapter in a book, i.e. a whole bunch of URL's.
In older (pre-internet) applications, the usual term for what we might now call a page is screen, since the exact size of the screen was usually well defined.


text:
Q: Nginx as Reverse SSL Proxy and browser freeze on redirect The set-up:
Nginx 0.8.54 serves as a reverse SSL proxy to Apache.
Web application being served is used in this way - we upload multiple text files, process them and re-direct user to a page displaying processed results.
The problem:
On uploading files the re-direct starts but then a web browser freezes for a few seconds (eventually coming back to life). After that the re-direct successfully completes.
Since there is no problem of this kind when going directly through Apache the bottleneck must be in Nginx's proxy settings.
I've looked here http://wiki.nginx.org/HttpProxyModule and here http://wiki.nginx.org/HttpCoreModule#client_max_body_size.
Could you, guys, help to pinpoint which of the settings need adjusting to prevent browsers from freezing?

A: I don't think it's a buffer size issue since both the upload and the redirect are both working. I would suspect some misconfiguration in reverse proxy config, maybe in rewriting, so the first step I would take to debug this problem is check HTTP traffic with httpfox or similar tool and see where the time is going


text:
Q: Fail installing Streamlit in Professional Laptop I am quite new using Python and Streamlit.
For a professional project, I need to use streamlit. The main problem is that in my personal laptop, I was able to install everything as it appears in the website (https://docs.streamlit.io/library/get-started/installation). The main problem is that in my professional laptop that it doesn't work.
When I apply the command "pip install streamlit" in my professional laptop, it appears this error:
"Collecting streamlit
Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ReadTimeoutError("HTTPSConnectionPool(host='pypi.org', port=443): Read timed out. (read timeout=15)")': /simple/streamlit/
Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ReadTimeoutError("HTTPSConnectionPool(host='pypi.org', port=443): Read timed out. (read timeout=15)")': /simple/streamlit/
Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ReadTimeoutError("HTTPSConnectionPool(host='pypi.org', port=443): Read timed out. (read timeout=15)")': /simple/streamlit/
Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ReadTimeoutError("HTTPSConnectionPool(host='pypi.org', port=443): Read timed out. (read timeout=15)")': /simple/streamlit/
Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ReadTimeoutError("HTTPSConnectionPool(host='pypi.org', port=443): Read timed out. (read timeout=15)")': /simple/streamlit/
Could not find a version that satisfies the requirement streamlit (from versions: )
No matching distribution found for streamlit"
Could someone recommend me what should I do? Again I am so sorry if I am doing a stupid mistake, I am quite new and I don't have anyone to ask. Thank you so much in advance.