答:
You can do it like this: Use closest(".row") to get to the closest parent element with the class row and find() to select the options that are related to the input field.

(function($) {
  $('.test2').on('blur', function(e) {
    let inputVal = $(this).val();
    $(this).closest('.row').find('.padalinys option').each(function() {
      if ($(this).val() === inputVal) {
        $(this).prop('selected', true);
      }
    })
  });
})(jQuery);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<script src="https://kit.fontawesome.com/04b00d367c.js"></script>
<div class="row">
  <div class="col-md-2">
    <label class="text-black">Pad. kodas</label>
    <input type="text" name="padkodas[]" class="form-control test2">
  </div>
  <div class="col-md-10">
    <label class="text-black" for="padalinys">Padalinys</label>
    <select class="form-control padalinys" name="padalinys[]">
      <option value="1">test - 1</option>
      <option value="2">test - 2</option>
      <option value="3">test - 3</option>
      <option value="4">test - 4</option>
      <option value="5">test - 5</option>
    </select>
  </div>
</div>
<div class="row">
  <div class="col-md-2">
    <label class="text-black">Pad. kodas</label>
    <input type="text" name="padkodas[]" class="form-control test2">
  </div>
  <div class="col-md-10">
    <label class="text-black" for="padalinys">Padalinys</label>
    <select class="form-control padalinys" name="padalinys[]">
      <option value="1">test - 1</option>
      <option value="2">test - 2</option>
      <option value="3">test - 3</option>
      <option value="4">test - 4</option>
      <option value="5">test - 5</option>
    </select>
  </div>
</div></code>```

Title: How can I select an option based on the value of an input?

Body:
I have similar inputs and a select in my page. If I enter an input value I want to automatically select the option by its value.

The problem is that it works for one input but I have many of those, one the same page and script change values for all of them. What i need achieve that i can enter value for one of them then for second one, but i can't change classes.

//select option from padalinys
(function($) {
  $('.test2').on('blur', function(e) {
    let inputVal = $(this).val();

    $('.padalinys option').each(function() {
      if ($(this).val() === inputVal) {
        $(this).prop('selected', true);
      }
    })
  });
})(jQuery);

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">

    Pad. kodas
    <input type="text" name="padkodas[]" class="form-control test2">

    Padalinys
    <select class="form-control padalinys" name="padalinys[]">
      <option value="1">test - 1</option>
      <option value="2">test - 2</option>
      <option value="3">test - 3</option>
      <option value="4">test - 4</option>
      <option value="5">test - 5</option>
    </select>

    Pad. kodas
    <input type="text" name="padkodas[]" class="form-control test2">

    Padalinys
    <select class="form-control padalinys" name="padalinys[]">
      <option value="1">test - 1</option>
      <option value="2">test - 2</option>
      <option value="3">test - 3</option>
      <option value="4">test - 4</option>
      <option value="5">test - 5</option>
    </select>

    Pad. kodas
    <input type="text" name="padkodas[]" class="form-control test2">

    Padalinys
    <select class="form-control padalinys" name="padalinys[]">
      <option value="1">test - 1</option>
      <option value="2">test - 2</option>
      <option value="3">test - 3</option>
      <option value="4">test - 4</option>
      <option value="5">test - 5</option>
    </select>

Body:
You can do it like this: Use closest(".row") to get to the closest parent element with the class row and find() to select the options that are related to the input field.

(function($) {
  $('.test2').on('blur', function(e) {
    let inputVal = $(this).val();
    $(this).closest('.row').find('.padalinys option').each(function() {
      if ($(this).val() === inputVal) {
        $(this).prop('selected', true);
      }
    })
  });
})(jQuery);

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<script src="https://kit.fontawesome.com/04b00d367c.js"></script>
<div class="row">
  <div class="col-md-2">
    <label class="text-black">Pad. kodas</label>
    <input type="text" name="padkodas[]" class="form-control test2">
  </div>
  <div class="col-md-10">
    <label class="text-black" for="padalinys">Padalinys</label>
    <select class="form-control padalinys" name="padalinys[]">
      <option value="1">test - 1</option>
      <option value="2">test - 2</option>
      <option value="3">test - 3</option>
      <option value="4">test - 4</option>
      <option value="5">test - 5</option>
    </select>
  </div>
</div>
<div class="row">
  <div class="col-md-2">
    <label class="text-black">Pad. kodas</label>
    <input type="text" name="padkodas[]" class="form-control test2">
  </div>
  <div class="col-md-10">
    <label class="text-black" for="padalinys">Padalinys</label>
    <select class="form-control padalinys" name="padalinys[]">
      <option value="1">test - 1</option>
      <option value="2">test - 2</option>
      <option value="3">test - 3</option>
      <option value="4">test - 4</option>
      <option value="5">test - 5</option>
    </select>
  </div>
</div>


来源: stackexchange

问:
Adding two numbers through recursion C++
```<code>#include <iostream>

int sum(int a, int b) {
  if (b != 1) {
    sum(a, b - 1);
  }
  a = a + 1;
  return a;
}

int main() {
  int a = sum(10, 12);
  std::cout << a;
}
</code>```

Basically I am adding two numbers through recursion, so I am recursively calling function by decreasing number b and incrementing number a that much times, but result I get is 11.

答:
Let me rewrite your code just a bit to make the mistake more obvious:

```<code>int partial_result(int a,int b) { /*....*/ }

int sum(int a, int b) {

    if(b != 1){
        partial_result(a, b-1);
    }
    a = a+1;
    return a;
}
</code>```

Calling the partial_result has no influence on what sum returns and sum is the same as

```<code>int sum(int a,int b) {
    return a+1;
}
</code>```

For the recursion you have to actually use the result of the recursive calls:

```<code>int sum(int a, int b) {
    if (b == 1) {
        return a+1;
    } else {
        return sum(a,b-1) + 1;
    }
}
</code>```

...or more similar to your code:

```<code>int sum(int a, int b) {
    if (b != 1) {
        a = sum(a,b-1);
    }
    return a+1;
}
</code>```

Note that recursion will not stop when b is negative. Even if you only ever want to call the function with positives values, it is better to change the condition to if (b <= 2). This will return wrong results for negatives but at least it will return something.

ContentLicense: CC BY-SA 4.0

Body:
#include <iostream>

int sum(int a, int b) {
  if (b != 1) {
    sum(a, b - 1);
  }
  a = a + 1;
  return a;
}

int main() {
  int a = sum(10, 12);
  std::cout << a;
}

Basically I am adding two numbers through recursion, so I am recursively calling function by decreasing number b and incrementing number a that much times, but result I get is 11.

Body:
Let me rewrite your code just a bit to make the mistake more obvious:

int partial_result(int a,int b) { /*....*/ }

int sum(int a, int b) {

    if(b != 1){
        partial_result(a, b-1);
    }
    a = a+1;
    return a;
}

Calling the partial_result has no influence on what sum returns and sum is the same as

int sum(int a,int b) {
    return a+1;
}

For the recursion you have to actually use the result of the recursive calls:

int sum(int a, int b) {
    if (b == 1) {
        return a+1;
    } else {
        return sum(a,b-1) + 1;
    }
}

...or more similar to your code:

int sum(int a, int b) {
    if (b != 1) {
        a = sum(a,b-1);
    }
    return a+1;
}

Note that recursion will not stop when b is negative. Even if you only ever want to call the function with positives values, it is better to change the condition to if (b <= 2). This will return wrong results for negatives but at least it will return something.


问:
Maintaining medium-sized to large JS-heavy web apps
What's the best way to deal with lots of JS in a web front end? Google's Closure compiler can compile and minify JS, which is good for production -- but annoying to have to recompile every time I make a change, and annoying to debug.

What's the best way to be able to organise my JS into many files?

答:
There are actually 2 questions: how to avoid recompiling in development and what's the best way to organize many js files.

Easy answer for the first question is having a variable for production/development modes in your template. In pseudo-template code it may look like this (example is rough, of course it's better to use script loading tool like LABjs etc.):

```<code>{if mode == 'production'}
  <script src="allmyscripts.min.js"></script>
{elseif mode == 'development'}
  <script src="lib.js"></script>
  <script src="plugin1.js"></script>
  <script src="plugin2.js"></script>
  <script src="script1.js"></script>
{/if}
</code>```

So you will only have to compile when switching to production mode.

The second question is far more complicated and answers tend to be opinionated. You may try using existing tools that impose their own file structure, e.g. JavascriptMVC or more lightweight RequireJS.

ContentLicense: CC BY-SA 3.0

Body:
There are actually 2 questions: how to avoid recompiling in development and what's the best way to organize many js files.

Easy answer for the first question is having a variable for production/development modes in your template. In pseudo-template code it may look like this (example is rough, of course it's better to use script loading tool like LABjs etc.):

{if mode == 'production'}
  <script src="allmyscripts.min.js"></script>
{elseif mode == 'development'}
  <script src="lib.js"></script>
  <script src="plugin1.js"></script>
  <script src="plugin2.js"></script>
  <script src="script1.js"></script>
{/if}

So you will only have to compile when switching to production mode.

The second question is far more complicated and answers tend to be opinionated. You may try using existing tools that impose their own file structure, e.g. JavascriptMVC or more lightweight RequireJS.


问:
How to use mongoose model schema with dynamic keys?
i'm using mongoose with nodejs, and i need to create a dynamic schema model,
this is my code:

```<code>schema.add({key : String});
</code>```

key = "user_name", but in my db i found that the model take it as key

```<code>{ key : "Michele" } and not { user_name: "Michele"}
</code>```

What can i do? thank you.

答:
```<code>const options = {};
options[key] = String;

schema.add(options);
</code>```

Body:
i'm using mongoose with nodejs, and i need to create a dynamic schema model,
this is my code:

schema.add({key : String});

key = "user_name", but in my db i found that the model take it as key

{ key : "Michele" } and not { user_name: "Michele"}

What can i do? thank you.


问:
File upload progress using react-dropzone
Using react-dropzone to upload the file, I want to achieve the file progress like in percentage of file transfer or mbs data transfer.

Here is the link of: https://react-dropzone.netlify.com/

```<code>onDrop(acceptedFiles, uploadApi) {
  const filesToBeSent = this.state.filesToBeSent;
  if (acceptedFiles.length) {
    if (acceptedFiles[0].type === FileTypeList.TYPE) {
      filesToBeSent.push(acceptedFiles);
      const formData = new FormData();
      formData.append("file", acceptedFiles[0]);
      uploadApi(formData).then((response) => {
        this.setState({
          filesPreview: [],
          filesToBeSent: [{}],
          showNotification: true,
          uploadResponse: response,
        });
        this.props.fetchHistory();
      });
    } else {
      this.setState({
        fileType: true,
      });
    }
  } else {
    this.setState({
      fileSize: true,
    });
  }
}
</code>```

```<code><Dropzone maxSize={this.props.maxSize} onDrop={(files) => this.onDrop(files, this.props.uploadApi)}>
  {({ getRootProps, getInputProps }) => {
    return (
      <div {...getRootProps()} className={"dropzone"}>
        <UploadPanel id="uploadFileContainerId">
          <p>
            <img id="uploadImage" src={UploadImage} />
          </p>
          <input {...getInputProps()} />
          <div>{t("assets:UPLOAD_FILE")}</div>
          <Note>
            {this.props.maxSizeTitle ? t("workers:UPLOAD_WORKER_FILE_SIZE") : t("assets:UPLOAD_FILE_SIZE")}
          </Note>
        </UploadPanel>
      </div>
    );
  }}
</Dropzone>
</code>```

答:
Here is another example based on turchak's answer for handling any number of files:</p>

```<code>onDrop(acceptedFiles) {
  const formData = new FormData();
  for (const file of acceptedFiles) formData.append('file', file);

  const xhr = new XMLHttpRequest();
  xhr.upload.onprogress = event => {
   const percentage = parseInt((event.loaded / event.total) * 100);
   console.log(percentage); // Update progress here
  };
  xhr.onreadystatechange = () => {
    if (xhr.readyState !== 4) return;
    if (xhr.status !== 200) {
     console.log('error'); // Handle error here
    }
     console.log('success'); // Handle success here
  };
  xhr.open('POST', 'https://httpbin.org/post', true);
  xhr.send(formData);
}
</code>```

Body:
Using react-dropzone to upload the file, I want to achieve the file progress like in percentage of file transfer or mbs data transfer.

Here is the link of: https://react-dropzone.netlify.com/

onDrop(acceptedFiles, uploadApi) {
  const filesToBeSent = this.state.filesToBeSent;
  if (acceptedFiles.length) {
    if (acceptedFiles[0].type === FileTypeList.TYPE) {
      filesToBeSent.push(acceptedFiles);
      const formData = new FormData();
      formData.append("file", acceptedFiles[0]);
      uploadApi(formData).then((response) => {
        this.setState({
          filesPreview: [],
          filesToBeSent: [{}],
          showNotification: true,
          uploadResponse: response,
        });
        this.props.fetchHistory();
      });
    } else {
      this.setState({
        fileType: true,
      });
    }
  } else {
    this.setState({
      fileSize: true,
    });
  }
}

<Dropzone maxSize={this.props.maxSize} onDrop={(files) => this.onDrop(files, this.props.uploadApi)}>
  {({ getRootProps, getInputProps }) => {
    return (

        <UploadPanel id="uploadFileContainerId">

          <input {...getInputProps()} />

{t("assets:UPLOAD_FILE")}

          <Note>
            {this.props.maxSizeTitle ? t("workers:UPLOAD_WORKER_FILE_SIZE") : t("assets:UPLOAD_FILE_SIZE")}
          </Note>
        </UploadPanel>

    );
  }}
</Dropzone>

Body:
Here is another example based on turchak's answer for handling any number of files:

onDrop(acceptedFiles) {
  const formData = new FormData();
  for (const file of acceptedFiles) formData.append('file', file);

  const xhr = new XMLHttpRequest();
  xhr.upload.onprogress = event => {
   const percentage = parseInt((event.loaded / event.total) * 100);
   console.log(percentage); // Update progress here
  };
  xhr.onreadystatechange = () => {
    if (xhr.readyState !== 4) return;
    if (xhr.status !== 200) {
     console.log('error'); // Handle error here
    }
     console.log('success'); // Handle success here
  };
  xhr.open('POST', 'https://httpbin.org/post', true);
  xhr.send(formData);
}


问:
REST API doesn't trigger DelegatingHandler, only swagger does
I need to log request and responses in my c# API and I tried using a DelegatingHandler class approach.

I also have swashbuckle/swagger running on the API. The handler seems to work fine but it only triggers and logs for swagger calls. It won't trigger when I call any of the the API functions. It won't even trigger when accessing an image located in the server folder. But it will always trigger if the path is swagger related.

```<code>public static void Register(HttpConfiguration config)
    {
        config.MessageHandlers.Add(new MessageLoggingHandler());
        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "{controller}/{id}",
            defaults: new { id = RouteParameter.Optional },
            constraints: null,
            handler: new MessageLoggingHandler()
        );
        config.MapHttpAttributeRoutes();
       }
</code>```

This is what I've got so far. Any clue?

答: I think it won't work with accessing to files, since it is only middleware for controllers methods. Try to call you methods directly - if your handler work. Then for logging requests to files on your server too you need check some "under level" logger for IIS</p>

Body:
I need to log request and responses in my c# API and I tried using a DelegatingHandler class approach.

I also have swashbuckle/swagger running on the API. The handler seems to work fine but it only triggers and logs for swagger calls. It won't trigger when I call any of the the API functions. It won't even trigger when accessing an image located in the server folder. But it will always trigger if the path is swagger related.

public static void Register(HttpConfiguration config)
    {
        config.MessageHandlers.Add(new MessageLoggingHandler());
        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "{controller}/{id}",
            defaults: new { id = RouteParameter.Optional },
            constraints: null,
            handler: new MessageLoggingHandler()
        );
        config.MapHttpAttributeRoutes();
       }

This is what I've got so far. Any clue?


问:
geo-indexing: efficiently calculating proximity based on latitude/longitude
My simple web app (WSGI, Python) supports text queries to find items in the database.
Now I'd like to extend this to allow for queries like "find all items within 1 mile of {lat,long}".

Of course that's a complex job if efficiency is a concern, so I'm thinking of a dedicated external module that does indexing for geo-coordinates - sort of like Lucene would for text.

I assume a generic component like this already exists, but haven't been able to find anything so far. Any help would be greatly appreciated.

答: Have you checked out mongo db, they have a geo indexing feature. http://www.mongodb.org/display/DOCS/Geospatial+Indexing</p>

ContentLicense: CC BY-SA 2.5


问:
dropdown is populating empty list in laravel 6
Laravel Version 6. PHP 7.4.

I simply wants to populate my dropdown values form database table. Initially, It was returning error "variable undefined" but when I enclosed my code into if condition, my error was gone but drop-down list is empty.

Please suggest where I' m stuck.

Route.php

```<code>Route::get('products/qrcodes/basic','niceActionController@getMake');
</code>```

Controller

```<code><?php

namespace App\Http\Controllers;
use \Illuminate\Http\Request;
use App\NiceAction;
use App\NiceActionLogged;

public function getMake()
{
$records = DB::table('users')->get();
return view('products.qrcodes.basic', ['records' => $records]);
}
</code>```

View

```<code><form>
   <select  required>
     @if ((empty($records)))
        Whoops! Something went wrong
     @else
     @foreach ($records as $item)
     <option value="{{ $item->id }}">{{ $item->name }}</option>
     @endforeach
     @endif
   </select>
</form>
</code>```

I also tried "dd($records);" but nothing happens.

答:
I'm happy to announce that @Khalid Khan has helped me to solved my issue. What he identified is I had defined two identical routes mistakenly. Upon pasting my latest route above previous one, my code worked.

Previous route:

```<code>    Route::get('products/qrcodes/{firstQR}
</code>```

Latest route:

```<code>    Route::get('products/qrcodes/basic','niceActionController@getMake');
</code>```

Body:
Laravel Version 6. PHP 7.4.

I simply wants to populate my dropdown values form database table. Initially, It was returning error "variable undefined" but when I enclosed my code into if condition, my error was gone but drop-down list is empty.

Please suggest where I' m stuck.

Route.php

Route::get('products/qrcodes/basic','niceActionController@getMake');

Controller

<?php

namespace App\Http\Controllers;
use \Illuminate\Http\Request;
use App\NiceAction;
use App\NiceActionLogged;

public function getMake()
{
$records = DB::table('users')->get();
return view('products.qrcodes.basic', ['records' => $records]);
}

View

<form>
   <select  required>
     @if ((empty($records)))
        Whoops! Something went wrong
     @else
     @foreach ($records as $item)
     <option value="{{ $item->id }}">{{ $item->name }}</option>
     @endforeach
     @endif
   </select>
</form>

I also tried "dd($records);" but nothing happens.

Body:
I'm happy to announce that @Khalid Khan has helped me to solved my issue. What he identified is I had defined two identical routes mistakenly. Upon pasting my latest route above previous one, my code worked.

Previous route:

    Route::get('products/qrcodes/{firstQR}

Latest route:

    Route::get('products/qrcodes/basic','niceActionController@getMake');


问:
Export users data from outlook global address list to text or excel or csv file
we have to export users data like name, mobile number, title etc. from outlook application Address Book (From 2 Global address list Group) by using power shell script  or batch file, to output file might be a CSV or text or excel. please help me any one by providing required power shell  script to solve this problem.

thanks

答: You can automate Outlook from PowerShell to export contacts. See Outlook Email Automation with PowerShell to get started quickly. </p>


问:
Building and shifting numpy array
I have such a numpy array:

And I want to shift this array with N so I can get a new array, such that first 4 rows will be the first 4 rows from the beginning array, and the below rows will be the rows from the previous step.

I dont know how to explain it correctly, but look at the example where I shift with 1 (not the whole array, but I would like to do this for the whole array):

And when I shift with 2 (not the whole array, but I would like to do this for the whole array):

And if I shift with 3, I will have 12 zeros in first column, and 3 previous rows ..

And here's the code:

```<code>import numpy as np
import numpy

def shift_one(arr):
  arrT = arr.transpose()
  arrT_shape = arrT.shape[0]

  col1 = arrT[:, [0]]
  prev1 = numpy.zeros([arrT_shape, 1])
  x1 = numpy.vstack([col1, prev1])

  col2 = arrT[:, [1]]
  prev2 = arrT[:, [0]]
  x2 = numpy.vstack([col2, prev2])

  col3 = arrT[:, [2]]
  prev3 = arrT[:, [1]]
  x3 = numpy.vstack([col3, prev3])

  col4 = arrT[:, [3]]
  prev4 = arrT[:, [2]]
  x4 = numpy.vstack([col4, prev4])

  col5 = arrT[:, [4]]
  prev5 = arrT[:, [3]]
  x5 = numpy.vstack([col5, prev5])

  # ... and so on, until we have index [23] and [22] and x24

  res = numpy.hstack([x1, x2, x3, x4, x5])
  return res

def shift_two(arr):
    arrT = arr.transpose()
    arrT_shape = arrT.shape[0]
    new_size = 2 * arrT_shape

    col1 = arrT[:, [0]]
    prev1 = numpy.zeros([new_size, 1])
    x1 = numpy.vstack([col1, prev1])

    col22 = arrT[:, [1]]
    col21 = arrT[:, [0]]
    prev2 = numpy.zeros([arrT_shape, 1])
    x2 = numpy.vstack([col22, col21, prev2])

    col32 = arrT[:, [2]]
    col31 = arrT[:, [1]]
    col30 = arrT[:, [0]]
    x3 = numpy.vstack([col32, col31, col30])

    col42 = arrT[:, [3]]
    col41 = arrT[:, [2]]
    col40 = arrT[:, [1]]
    x4 = numpy.vstack([col42, col41, col40])

    col52 = arrT[:, [4]]
    col51 = arrT[:, [3]]
    col50 = arrT[:, [2]]
    x5 = numpy.vstack([col52, col51, col50])

    # ... and so on, until we have index [23], [22], [21] and x24

    res = numpy.hstack([x1, x2, x3, x4, x5])
    return res

arr1 = np.array([[0,   2,   0, 324],
        [1, 2, 0,324],
        [2, 2, 0, 324],
        [3, 2, 0, 324],
        [4, 2, 0, 324],
        [5, 2, 0, 324],
        [6, 2, 0, 324],
        [7, 2, 0, 324],
        [8, 2, 0, 324],
        [9, 2, 0, 324],
        [ 10, 2, 0, 324],
        [ 11, 2, 0, 324],
        [ 12, 2, 0, 324],
        [ 13, 2, 0, 324],
        [ 14, 2, 0, 324],
        [ 15, 2, 0, 324],
        [ 16, 2, 0, 324],
        [ 17, 2, 0, 324],
        [ 18, 2, 0, 324],
        [ 19, 2, 0, 324],
        [ 20, 2, 0, 324],
        [ 21, 2, 0, 324],
        [ 22, 2, 0, 324],
        [ 23, 2, 0, 324]])

print(arr1)

print('\n\n')
one = shift_one(arr1)
print(one)

print('\n\n')
two = shift_two(arr1)
print(two)
</code>```

Basically, I have a problem how to write a function, which will shift it with a given N ... I know how to write it step by step as I did, but I have a problem transforming it into something more usable. Thank you.

So again, an example for array with 5 columns (the original array has 24 columns):

Title: Building and shifting numpy array

Body:
I have such a numpy array:

And I want to shift this array with N so I can get a new array, such that first 4 rows will be the first 4 rows from the beginning array, and the below rows will be the rows from the previous step.

I dont know how to explain it correctly, but look at the example where I shift with 1 (not the whole array, but I would like to do this for the whole array):

And when I shift with 2 (not the whole array, but I would like to do this for the whole array):

And if I shift with 3, I will have 12 zeros in first column, and 3 previous rows ..

And here's the code:

import numpy as np
import numpy

def shift_one(arr):
  arrT = arr.transpose()
  arrT_shape = arrT.shape[0]

  col1 = arrT[:, [0]]
  prev1 = numpy.zeros([arrT_shape, 1])
  x1 = numpy.vstack([col1, prev1])

  col2 = arrT[:, [1]]
  prev2 = arrT[:, [0]]
  x2 = numpy.vstack([col2, prev2])

  col3 = arrT[:, [2]]
  prev3 = arrT[:, [1]]
  x3 = numpy.vstack([col3, prev3])

  col4 = arrT[:, [3]]
  prev4 = arrT[:, [2]]
  x4 = numpy.vstack([col4, prev4])

  col5 = arrT[:, [4]]
  prev5 = arrT[:, [3]]
  x5 = numpy.vstack([col5, prev5])

  # ... and so on, until we have index [23] and [22] and x24

  res = numpy.hstack([x1, x2, x3, x4, x5])
  return res

def shift_two(arr):
    arrT = arr.transpose()
    arrT_shape = arrT.shape[0]
    new_size = 2 * arrT_shape

    col1 = arrT[:, [0]]
    prev1 = numpy.zeros([new_size, 1])
    x1 = numpy.vstack([col1, prev1])

    col22 = arrT[:, [1]]
    col21 = arrT[:, [0]]
    prev2 = numpy.zeros([arrT_shape, 1])
    x2 = numpy.vstack([col22, col21, prev2])

    col32 = arrT[:, [2]]
    col31 = arrT[:, [1]]
    col30 = arrT[:, [0]]
    x3 = numpy.vstack([col32, col31, col30])

    col42 = arrT[:, [3]]
    col41 = arrT[:, [2]]
    col40 = arrT[:, [1]]
    x4 = numpy.vstack([col42, col41, col40])

    col52 = arrT[:, [4]]
    col51 = arrT[:, [3]]
    col50 = arrT[:, [2]]
    x5 = numpy.vstack([col52, col51, col50])

    # ... and so on, until we have index [23], [22], [21] and x24

    res = numpy.hstack([x1, x2, x3, x4, x5])
    return res

arr1 = np.array([[0,   2,   0, 324],
        [1, 2, 0,324],
        [2, 2, 0, 324],
        [3, 2, 0, 324],
        [4, 2, 0, 324],
        [5, 2, 0, 324],
        [6, 2, 0, 324],
        [7, 2, 0, 324],
        [8, 2, 0, 324],
        [9, 2, 0, 324],
        [ 10, 2, 0, 324],
        [ 11, 2, 0, 324],
        [ 12, 2, 0, 324],
        [ 13, 2, 0, 324],
        [ 14, 2, 0, 324],
        [ 15, 2, 0, 324],
        [ 16, 2, 0, 324],
        [ 17, 2, 0, 324],
        [ 18, 2, 0, 324],
        [ 19, 2, 0, 324],
        [ 20, 2, 0, 324],
        [ 21, 2, 0, 324],
        [ 22, 2, 0, 324],
        [ 23, 2, 0, 324]])

print(arr1)

print('\n\n')
one = shift_one(arr1)
print(one)

print('\n\n')
two = shift_two(arr1)
print(two)

Basically, I have a problem how to write a function, which will shift it with a given N ... I know how to write it step by step as I did, but I have a problem transforming it into something more usable. Thank you.

So again, an example for array with 5 columns (the original array has 24 columns):

Body:
If the data is not too humongous concatenating a couple of times will work:

>>> x
array([[  0,   1,   2,   3,   4],
       [  2,   2,   2,   2,   2],
       [  0,   0,   0,   0,   0],
       [324, 324, 324, 324, 324]])
>>> np.concatenate([x] + [np.concatenate([np.zeros(x.shape[0]*i).reshape(-1, i), x[: , i:]] ,axis=1) for i in range(1,x.shape[1])], axis=0)
array([[  0.,   1.,   2.,   3.,   4.],
       [  2.,   2.,   2.,   2.,   2.],
       [  0.,   0.,   0.,   0.,   0.],
       [324., 324., 324., 324., 324.],
       [  0.,   1.,   2.,   3.,   4.],
       [  0.,   2.,   2.,   2.,   2.],
       [  0.,   0.,   0.,   0.,   0.],
       [  0., 324., 324., 324., 324.],
       [  0.,   0.,   2.,   3.,   4.],
       [  0.,   0.,   2.,   2.,   2.],
       [  0.,   0.,   0.,   0.,   0.],
       [  0.,   0., 324., 324., 324.],
       [  0.,   0.,   0.,   3.,   4.],
       [  0.,   0.,   0.,   2.,   2.],
       [  0.,   0.,   0.,   0.,   0.],
       [  0.,   0.,   0., 324., 324.],
       [  0.,   0.,   0.,   0.,   4.],
       [  0.,   0.,   0.,   0.,   2.],
       [  0.,   0.,   0.,   0.,   0.],
       [  0.,   0.,   0.,   0., 324.]])

Each time I generate a 4xi matrix of zeros, and take the i+1: columns from the original matrix to generate the next part. Finally, I concatenate all these arrays.


问:
Eclipse - Can not reach market place
I am trying to install glassfish on my Eclipse but I have an issue each time I try to access it :

Resource not found: http://marketplace.eclipse.org/api/p?client=org.eclipse.epp.mpc.core&client.version=1.8.2.v20200210-1402&os=win32&ws=win32&nl=fr_FR&java.version=1.8.0_231&product=org.eclipse.epp.package.jee.product&product.version=4.15.0.I20200305-0155&runtime.version=3.17.100.v20200203-0917&platform.version=4.15.0.v20200305-0155
http://marketplace.eclipse.org/api/p?client=org.eclipse.epp.mpc.core&client.version=1.8.2.v20200210-1402&os=win32&ws=win32&nl=fr_FR&java.version=1.8.0_231&product=org.eclipse.epp.package.jee.product&product.version=4.15.0.I20200305-0155&runtime.version=3.17.100.v20200203-0917&platform.version=4.15.0.v20200305-0155

I can reach web page from inside eclipse web browser and I can reach the market place with my browser I guess it is coming from eclipse but I don't know how to solve it.

I tried to change the Network Connections settings from Native to Manual but no luck so far.

If anyone as an idea ?

Here is the stack trace :

```<code>eclipse.buildId=4.15.0.I20200305-0155
java.version=1.8.0_231
java.vendor=Oracle Corporation
BootLoader constants: OS=win32, ARCH=x86_64, WS=win32, NL=fr_FR
Framework arguments:  -product org.eclipse.epp.package.jee.product
Command-line arguments:  -os win32 -ws win32 -arch x86_64 -product org.eclipse.epp.package.jee.product

org.eclipse.epp.mpc.core
Error
Tue Jun 02 10:54:16 CEST 2020
Failed to stream using org.eclipse.epp.internal.mpc.core.transport.httpclient.HttpClientTransport@27a4a153 - falling back to org.eclipse.epp.internal.mpc.core.util.TransportFactory$$Lambda$811/602501626@46a0adaa: Connection failed

This is most often caused by a problem with your internet connection. Please check your internet connection and retry.

org.eclipse.core.runtime.CoreException: Connection failed

This is most often caused by a problem with your internet connection. Please check your internet connection and retry.
    at org.eclipse.epp.internal.mpc.core.transport.httpclient.HttpClientTransport.stream(HttpClientTransport.java:119)
    at org.eclipse.epp.internal.mpc.core.util.FallbackTransportFactory$FallbackTransport.stream(FallbackTransportFactory.java:71)
    at org.eclipse.epp.internal.mpc.core.service.RemoteMarketplaceService.processRequest(RemoteMarketplaceService.java:165)
    at org.eclipse.epp.internal.mpc.core.service.RemoteMarketplaceService.processRequest(RemoteMarketplaceService.java:130)
    at org.eclipse.epp.internal.mpc.core.service.RemoteMarketplaceService.processRequest(RemoteMarketplaceService.java:117)
    at org.eclipse.epp.internal.mpc.core.service.DefaultMarketplaceService.news(DefaultMarketplaceService.java:788)
    at org.eclipse.epp.internal.mpc.core.service.DefaultMarketplaceService.news(DefaultMarketplaceService.java:1)
    at org.eclipse.epp.internal.mpc.core.service.CachingMarketplaceService.news(CachingMarketplaceService.java:405)
    at org.eclipse.epp.internal.mpc.ui.catalog.MarketplaceDiscoveryStrategy.performNewsDiscovery(MarketplaceDiscoveryStrategy.java:947)
    at org.eclipse.epp.internal.mpc.ui.catalog.MarketplaceCatalog.performNewsDiscovery(MarketplaceCatalog.java:584)
    at org.eclipse.epp.internal.mpc.ui.wizards.MarketplaceWizard.lambda$3(MarketplaceWizard.java:944)
    at org.eclipse.jface.operation.ModalContext$ModalContextThread.run(ModalContext.java:122)
Caused by: java.net.SocketTimeoutException: Read timed out
    at java.net.SocketInputStream.socketRead0(Native Method)
    at java.net.SocketInputStream.socketRead(Unknown Source)
    at java.net.SocketInputStream.read(Unknown Source)
    at java.net.SocketInputStream.read(Unknown Source)
    at org.apache.http.impl.io.SessionInputBufferImpl.streamRead(SessionInputBufferImpl.java:137)
    at org.apache.http.impl.io.SessionInputBufferImpl.fillBuffer(SessionInputBufferImpl.java:153)
    at org.apache.http.impl.io.SessionInputBufferImpl.readLine(SessionInputBufferImpl.java:280)
    at org.apache.http.impl.conn.DefaultHttpResponseParser.parseHead(DefaultHttpResponseParser.java:138)
    at org.apache.http.impl.conn.DefaultHttpResponseParser.parseHead(DefaultHttpResponseParser.java:56)
    at org.apache.http.impl.io.AbstractMessageParser.parse(AbstractMessageParser.java:259)
    at org.apache.http.impl.DefaultBHttpClientConnection.receiveResponseHeader(DefaultBHttpClientConnection.java:163)
    at org.apache.http.impl.conn.CPoolProxy.receiveResponseHeader(CPoolProxy.java:157)
    at org.apache.http.protocol.HttpRequestExecutor.doReceiveResponse(HttpRequestExecutor.java:273)
    at org.apache.http.protocol.HttpRequestExecutor.execute(HttpRequestExecutor.java:125)
    at org.apache.http.impl.execchain.MainClientExec.execute(MainClientExec.java:272)
    at org.apache.http.impl.execchain.ProtocolExec.execute(ProtocolExec.java:186)
    at org.apache.http.impl.execchain.RetryExec.execute(RetryExec.java:89)
    at org.apache.http.impl.execchain.RedirectExec.execute(RedirectExec.java:110)
    at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:185)
    at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:83)
    at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:56)
    at org.apache.http.client.fluent.Request.internalExecute(Request.java:173)
    at org.apache.http.client.fluent.Executor.execute(Executor.java:262)
    at org.eclipse.epp.internal.mpc.core.transport.httpclient.HttpClientTransport.execute(HttpClientTransport.java:93)
    at org.eclipse.epp.internal.mpc.core.transport.httpclient.RequestTemplate.executeImpl(RequestTemplate.java:96)
    at org.eclipse.epp.internal.mpc.core.transport.httpclient.RequestTemplate.execute(RequestTemplate.java:55)
    at org.eclipse.epp.internal.mpc.core.transport.httpclient.HttpClientTransport.stream(HttpClientTransport.java:104)
    ... 11 more
Contains: Connection failed

This is most often caused by a problem with your internet connection. Please check your internet connection and retry.
java.net.SocketTimeoutException: Read timed out
    at java.net.SocketInputStream.socketRead0(Native Method)
    at java.net.SocketInputStream.socketRead(Unknown Source)
    at java.net.SocketInputStream.read(Unknown Source)
    at java.net.SocketInputStream.read(Unknown Source)
    at org.apache.http.impl.io.SessionInputBufferImpl.streamRead(SessionInputBufferImpl.java:137)
    at org.apache.http.impl.io.SessionInputBufferImpl.fillBuffer(SessionInputBufferImpl.java:153)
    at org.apache.http.impl.io.SessionInputBufferImpl.readLine(SessionInputBufferImpl.java:280)
    at org.apache.http.impl.conn.DefaultHttpResponseParser.parseHead(DefaultHttpResponseParser.java:138)
    at org.apache.http.impl.conn.DefaultHttpResponseParser.parseHead(DefaultHttpResponseParser.java:56)
    at org.apache.http.impl.io.AbstractMessageParser.parse(AbstractMessageParser.java:259)
    at org.apache.http.impl.DefaultBHttpClientConnection.receiveResponseHeader(DefaultBHttpClientConnection.java:163)
    at org.apache.http.impl.conn.CPoolProxy.receiveResponseHeader(CPoolProxy.java:157)
    at org.apache.http.protocol.HttpRequestExecutor.doReceiveResponse(HttpRequestExecutor.java:273)
    at org.apache.http.protocol.HttpRequestExecutor.execute(HttpRequestExecutor.java:125)
    at org.apache.http.impl.execchain.MainClientExec.execute(MainClientExec.java:272)
    at org.apache.http.impl.execchain.ProtocolExec.execute(ProtocolExec.java:186)
    at org.apache.http.impl.execchain.RetryExec.execute(RetryExec.java:89)
    at org.apache.http.impl.execchain.RedirectExec.execute(RedirectExec.java:110)
    at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:185)
    at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:83)
    at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:56)
    at org.apache.http.client.fluent.Request.internalExecute(Request.java:173)
    at org.apache.http.client.fluent.Executor.execute(Executor.java:262)
    at org.eclipse.epp.internal.mpc.core.transport.httpclient.HttpClientTransport.execute(HttpClientTransport.java:93)
    at org.eclipse.epp.internal.mpc.core.transport.httpclient.RequestTemplate.executeImpl(RequestTemplate.java:96)
    at org.eclipse.epp.internal.mpc.core.transport.httpclient.RequestTemplate.execute(RequestTemplate.java:55)
    at org.eclipse.epp.internal.mpc.core.transport.httpclient.HttpClientTransport.stream(HttpClientTransport.java:104)
    at org.eclipse.epp.internal.mpc.core.util.FallbackTransportFactory$FallbackTransport.stream(FallbackTransportFactory.java:71)
    at org.eclipse.epp.internal.mpc.core.service.RemoteMarketplaceService.processRequest(RemoteMarketplaceService.java:165)
    at org.eclipse.epp.internal.mpc.core.service.RemoteMarketplaceService.processRequest(RemoteMarketplaceService.java:130)
    at org.eclipse.epp.internal.mpc.core.service.RemoteMarketplaceService.processRequest(RemoteMarketplaceService.java:117)
    at org.eclipse.epp.internal.mpc.core.service.DefaultMarketplaceService.news(DefaultMarketplaceService.java:788)
    at org.eclipse.epp.internal.mpc.core.service.DefaultMarketplaceService.news(DefaultMarketplaceService.java:1)
    at org.eclipse.epp.internal.mpc.core.service.CachingMarketplaceService.news(CachingMarketplaceService.java:405)
    at org.eclipse.epp.internal.mpc.ui.catalog.MarketplaceDiscoveryStrategy.performNewsDiscovery(MarketplaceDiscoveryStrategy.java:947)
    at org.eclipse.epp.internal.mpc.ui.catalog.MarketplaceCatalog.performNewsDiscovery(MarketplaceCatalog.java:584)
    at org.eclipse.epp.internal.mpc.ui.wizards.MarketplaceWizard.lambda$3(MarketplaceWizard.java:944)
    at org.eclipse.jface.operation.ModalContext$ModalContextThread.run(ModalContext.java:122)
</code>```

I have the same issue from Help->Marketplace and from the welcome menu.

Thx

UPDATE : I manage to make it work again by deleting all the . folder (.me2, .plguings ...)

答: When installing, it can be an effect if using JDK instead of JRE on the installation. That Update/Marketplace will not work then.</p>

Title: Eclipse - Can not reach market place

Body:
I am trying to install glassfish on my Eclipse but I have an issue each time I try to access it :

Resource not found: http://marketplace.eclipse.org/api/p?client=org.eclipse.epp.mpc.core&client.version=1.8.2.v20200210-1402&os=win32&ws=win32&nl=fr_FR&java.version=1.8.0_231&product=org.eclipse.epp.package.jee.product&product.version=4.15.0.I20200305-0155&runtime.version=3.17.100.v20200203-0917&platform.version=4.15.0.v20200305-0155
http://marketplace.eclipse.org/api/p?client=org.eclipse.epp.mpc.core&client.version=1.8.2.v20200210-1402&os=win32&ws=win32&nl=fr_FR&java.version=1.8.0_231&product=org.eclipse.epp.package.jee.product&product.version=4.15.0.I20200305-0155&runtime.version=3.17.100.v20200203-0917&platform.version=4.15.0.v20200305-0155

I can reach web page from inside eclipse web browser and I can reach the market place with my browser I guess it is coming from eclipse but I don't know how to solve it.

I tried to change the Network Connections settings from Native to Manual but no luck so far.

If anyone as an idea ?

Here is the stack trace :

eclipse.buildId=4.15.0.I20200305-0155
java.version=1.8.0_231
java.vendor=Oracle Corporation
BootLoader constants: OS=win32, ARCH=x86_64, WS=win32, NL=fr_FR
Framework arguments:  -product org.eclipse.epp.package.jee.product
Command-line arguments:  -os win32 -ws win32 -arch x86_64 -product org.eclipse.epp.package.jee.product

org.eclipse.epp.mpc.core
Error
Tue Jun 02 10:54:16 CEST 2020
Failed to stream using org.eclipse.epp.internal.mpc.core.transport.httpclient.HttpClientTransport@27a4a153 - falling back to org.eclipse.epp.internal.mpc.core.util.TransportFactory$$Lambda$811/602501626@46a0adaa: Connection failed

This is most often caused by a problem with your internet connection. Please check your internet connection and retry.

org.eclipse.core.runtime.CoreException: Connection failed

This is most often caused by a problem with your internet connection. Please check your internet connection and retry.
    at org.eclipse.epp.internal.mpc.core.transport.httpclient.HttpClientTransport.stream(HttpClientTransport.java:119)
    at org.eclipse.epp.internal.mpc.core.util.FallbackTransportFactory$FallbackTransport.stream(FallbackTransportFactory.java:71)
    at org.eclipse.epp.internal.mpc.core.service.RemoteMarketplaceService.processRequest(RemoteMarketplaceService.java:165)
    at org.eclipse.epp.internal.mpc.core.service.RemoteMarketplaceService.processRequest(RemoteMarketplaceService.java:130)
    at org.eclipse.epp.internal.mpc.core.service.RemoteMarketplaceService.processRequest(RemoteMarketplaceService.java:117)
    at org.eclipse.epp.internal.mpc.core.service.DefaultMarketplaceService.news(DefaultMarketplaceService.java:788)
    at org.eclipse.epp.internal.mpc.core.service.DefaultMarketplaceService.news(DefaultMarketplaceService.java:1)
    at org.eclipse.epp.internal.mpc.core.service.CachingMarketplaceService.news(CachingMarketplaceService.java:405)
    at org.eclipse.epp.internal.mpc.ui.catalog.MarketplaceDiscoveryStrategy.performNewsDiscovery(MarketplaceDiscoveryStrategy.java:947)
    at org.eclipse.epp.internal.mpc.ui.catalog.MarketplaceCatalog.performNewsDiscovery(MarketplaceCatalog.java:584)
    at org.eclipse.epp.internal.mpc.ui.wizards.MarketplaceWizard.lambda$3(MarketplaceWizard.java:944)
    at org.eclipse.jface.operation.ModalContext$ModalContextThread.run(ModalContext.java:122)
Caused by: java.net.SocketTimeoutException: Read timed out
    at java.net.SocketInputStream.socketRead0(Native Method)
    at java.net.SocketInputStream.socketRead(Unknown Source)
    at java.net.SocketInputStream.read(Unknown Source)
    at java.net.SocketInputStream.read(Unknown Source)
    at org.apache.http.impl.io.SessionInputBufferImpl.streamRead(SessionInputBufferImpl.java:137)
    at org.apache.http.impl.io.SessionInputBufferImpl.fillBuffer(SessionInputBufferImpl.java:153)
    at org.apache.http.impl.io.SessionInputBufferImpl.readLine(SessionInputBufferImpl.java:280)
    at org.apache.http.impl.conn.DefaultHttpResponseParser.parseHead(DefaultHttpResponseParser.java:138)
    at org.apache.http.impl.conn.DefaultHttpResponseParser.parseHead(DefaultHttpResponseParser.java:56)
    at org.apache.http.impl.io.AbstractMessageParser.parse(AbstractMessageParser.java:259)
    at org.apache.http.impl.DefaultBHttpClientConnection.receiveResponseHeader(DefaultBHttpClientConnection.java:163)
    at org.apache.http.impl.conn.CPoolProxy.receiveResponseHeader(CPoolProxy.java:157)
    at org.apache.http.protocol.HttpRequestExecutor.doReceiveResponse(HttpRequestExecutor.java:273)
    at org.apache.http.protocol.HttpRequestExecutor.execute(HttpRequestExecutor.java:125)
    at org.apache.http.impl.execchain.MainClientExec.execute(MainClientExec.java:272)
    at org.apache.http.impl.execchain.ProtocolExec.execute(ProtocolExec.java:186)
    at org.apache.http.impl.execchain.RetryExec.execute(RetryExec.java:89)
    at org.apache.http.impl.execchain.RedirectExec.execute(RedirectExec.java:110)
    at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:185)
    at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:83)
    at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:56)
    at org.apache.http.client.fluent.Request.internalExecute(Request.java:173)
    at org.apache.http.client.fluent.Executor.execute(Executor.java:262)
    at org.eclipse.epp.internal.mpc.core.transport.httpclient.HttpClientTransport.execute(HttpClientTransport.java:93)
    at org.eclipse.epp.internal.mpc.core.transport.httpclient.RequestTemplate.executeImpl(RequestTemplate.java:96)
    at org.eclipse.epp.internal.mpc.core.transport.httpclient.RequestTemplate.execute(RequestTemplate.java:55)
    at org.eclipse.epp.internal.mpc.core.transport.httpclient.HttpClientTransport.stream(HttpClientTransport.java:104)
    ... 11 more
Contains: Connection failed

This is most often caused by a problem with your internet connection. Please check your internet connection and retry.
java.net.SocketTimeoutException: Read timed out
    at java.net.SocketInputStream.socketRead0(Native Method)
    at java.net.SocketInputStream.socketRead(Unknown Source)
    at java.net.SocketInputStream.read(Unknown Source)
    at java.net.SocketInputStream.read(Unknown Source)
    at org.apache.http.impl.io.SessionInputBufferImpl.streamRead(SessionInputBufferImpl.java:137)
    at org.apache.http.impl.io.SessionInputBufferImpl.fillBuffer(SessionInputBufferImpl.java:153)
    at org.apache.http.impl.io.SessionInputBufferImpl.readLine(SessionInputBufferImpl.java:280)
    at org.apache.http.impl.conn.DefaultHttpResponseParser.parseHead(DefaultHttpResponseParser.java:138)
    at org.apache.http.impl.conn.DefaultHttpResponseParser.parseHead(DefaultHttpResponseParser.java:56)
    at org.apache.http.impl.io.AbstractMessageParser.parse(AbstractMessageParser.java:259)
    at org.apache.http.impl.DefaultBHttpClientConnection.receiveResponseHeader(DefaultBHttpClientConnection.java:163)
    at org.apache.http.impl.conn.CPoolProxy.receiveResponseHeader(CPoolProxy.java:157)
    at org.apache.http.protocol.HttpRequestExecutor.doReceiveResponse(HttpRequestExecutor.java:273)
    at org.apache.http.protocol.HttpRequestExecutor.execute(HttpRequestExecutor.java:125)
    at org.apache.http.impl.execchain.MainClientExec.execute(MainClientExec.java:272)
    at org.apache.http.impl.execchain.ProtocolExec.execute(ProtocolExec.java:186)
    at org.apache.http.impl.execchain.RetryExec.execute(RetryExec.java:89)
    at org.apache.http.impl.execchain.RedirectExec.execute(RedirectExec.java:110)
    at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:185)
    at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:83)
    at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:56)
    at org.apache.http.client.fluent.Request.internalExecute(Request.java:173)
    at org.apache.http.client.fluent.Executor.execute(Executor.java:262)
    at org.eclipse.epp.internal.mpc.core.transport.httpclient.HttpClientTransport.execute(HttpClientTransport.java:93)
    at org.eclipse.epp.internal.mpc.core.transport.httpclient.RequestTemplate.executeImpl(RequestTemplate.java:96)
    at org.eclipse.epp.internal.mpc.core.transport.httpclient.RequestTemplate.execute(RequestTemplate.java:55)
    at org.eclipse.epp.internal.mpc.core.transport.httpclient.HttpClientTransport.stream(HttpClientTransport.java:104)
    at org.eclipse.epp.internal.mpc.core.util.FallbackTransportFactory$FallbackTransport.stream(FallbackTransportFactory.java:71)
    at org.eclipse.epp.internal.mpc.core.service.RemoteMarketplaceService.processRequest(RemoteMarketplaceService.java:165)
    at org.eclipse.epp.internal.mpc.core.service.RemoteMarketplaceService.processRequest(RemoteMarketplaceService.java:130)
    at org.eclipse.epp.internal.mpc.core.service.RemoteMarketplaceService.processRequest(RemoteMarketplaceService.java:117)
    at org.eclipse.epp.internal.mpc.core.service.DefaultMarketplaceService.news(DefaultMarketplaceService.java:788)
    at org.eclipse.epp.internal.mpc.core.service.DefaultMarketplaceService.news(DefaultMarketplaceService.java:1)
    at org.eclipse.epp.internal.mpc.core.service.CachingMarketplaceService.news(CachingMarketplaceService.java:405)
    at org.eclipse.epp.internal.mpc.ui.catalog.MarketplaceDiscoveryStrategy.performNewsDiscovery(MarketplaceDiscoveryStrategy.java:947)
    at org.eclipse.epp.internal.mpc.ui.catalog.MarketplaceCatalog.performNewsDiscovery(MarketplaceCatalog.java:584)
    at org.eclipse.epp.internal.mpc.ui.wizards.MarketplaceWizard.lambda$3(MarketplaceWizard.java:944)
    at org.eclipse.jface.operation.ModalContext$ModalContextThread.run(ModalContext.java:122)

I have the same issue from Help->Marketplace and from the welcome menu.

Thx

UPDATE : I manage to make it work again by deleting all the . folder (.me2, .plguings ...)


答:
if you want to do a very simple filter for users that have fallen out as of today you can simply add:

having max(date)<current_date

to your query but this will also include previous fallouts like the first one for user_id=2

but if you want forward looking (like for user id=1) and filter out only the last fallout you need to have a better "gaps and islands" query with lag function, if you check for more "gaps and islands" solutions you will find it... generally, lag(currrent_plan) over (partition by id order by date) gives you the previous day's plan for every day, this way you can identify fallout dates and then rank them over the same window to get the last one for every ID

Title: Finding groups of rows with consecutive identical values that have a defined end (SQL Redshift)

Body:
I have a table that has the subscription state of users on any given day. The data looks like this

+------------+------------+--------------+
| account_id |    date    | current_plan |
+------------+------------+--------------+
| 1          | 2019-08-01 | free         |
| 1          | 2019-08-02 | free         |
| 1          | 2019-08-03 | yearly       |
| 1          | 2019-08-04 | yearly       |
| 1          | 2019-08-05 | yearly       |
| ...        |            |              |
| 1          | 2020-08-02 | yearly       |
| 1          | 2020-08-03 | free         |
| 2          | 2019-08-01 | monthly      |
| 2          | 2019-08-02 | monthly      |
| ...        |            |              |
| 2          | 2019-08-31 | monthly      |
| 2          | 2019-09-01 | free         |
| ...        |            |              |
| 2          | 2019-11-26 | free         |
| 2          | 2019-11-27 | monthly      |
| ...        |            |              |
| 2          | 2019-12-27 | monthly      |
| 2          | 2019-12-28 | free         |
| 3          | 2020-05-31 | monthly      |
| 3          | 2020-06-01 | monthly      |
| 4          | 2019-08-01 | yearly       |
| ...        |            |              |
| 4          | 2020-06-01 | yearly       |
+------------+------------+--------------+

I would like to have a table that gives the start and end dates of a subscription. It would look something like this. Please note importantly, that account_ids 3 and 4 are not included in this table because they are still in a subscription as of today (6/1/2020).  I only would like a summary of people who have moved out of a subscription.

+------------+------------+------------+-------------------+
| account_id | start_date |  end_date  | subscription_type |
+------------+------------+------------+-------------------+
|          1 | 2019-08-03 | 2020-08-02 | yearly            |
|          2 | 2019-08-01 | 2019-08-31 | monthly           |
|          2 | 2019-11-27 | 2019-12-27 | monthly           |
+------------+------------+------------+-------------------+

Currently I have the following which is very close, but still gives me users that have not fallen out of a subscription

select account_id, current_plan, min(date), max(date)
from (select d.*,
             row_number() over (partition by account_id order by date) as seqnum,
             row_number() over (partition by account_id, current_plan order by date) as seqnum_2
      from data d
     ) d
where current_plan not in ('free', 'trial')
group by account_id, current_plan, (seqnum - seqnum_2);


问:
Upload from offline HTML5 app when network available
Wow, my problem seems like it must be so common that I must just be missing something really obvious but here goes:

Is there any way to trigger/schedule a dormant offline HTML5 app to run either:

when network comes available,

or regularly.

I want to create an offline HTML5 app that will record details of a delivery (item description, recipient's name, photo, timestamp, etc). The data will be written to local storage (the photo converted to base64). If the app has network then the delivery data will be uploaded to a remote server. If the app does not have network then, even if the user powers the device down, next time the device is up and has network, I need the app to do the upload without any action by the user.

I've searched and found nothing. I'm guessing that offline apps only get run-time when in the foreground? If someone could confirm that then that would at least be good to know, even if it's not what I'd like to hear.

Thanks

答:
Background sync, exactly what I was after (although in 2016 it was Chrome-only):
https://developers.google.com/web/updates/2015/12/background-sync</p>


问:
Ingesting csv data to hadoop
Currently I'm trying to ingesting data to hdfs. The type of data i was trying to ingest is csv.
Hadoop 3.1.1 installed on ubuntu.
data sample stored on /home/hadoop/test.csv

I've Tried

source1

```<code>hadoop@ambari:~$ hdfs dfs -put /home/hadoop/test.csv user/data/test.csv
put: `user/data/test.csv': No such file or directory: `hdfs://xxxx:8020/user/hadoop/user/data/test.csv'
</code>```

so i modify it into just test.csv and it returns

```<code>hadoop@ambari:~$ hdfs dfs -put /home/hadoop/test.csv test.csv
put: `test.csv': No such file or directory: `hdfs://xxxx:8020/user/hadoop/test.csv'
</code>```

because It is written that no directory i follow another source to make a directory
source2
source3

```<code>hadoop@ambari:~$ hadoop fs -mkdir bdp
mkdir: `hdfs://xxxx:8020/user/hadoop': No such file or directory
hadoop@ambari:~$ hadoop fs -mkdir /user/hadoop/in
mkdir: `hdfs://xxxx:8020/user/hadoop': No such file or directory

</code>```

答:
@yuliansen

The command to copy a file from local disk to hdfs is as follows:

```<code>hdfs dfs -copyFromLocal /home/hadoop/test.csv /user/data/
</code>```

If the folder is not created as hdfs or root user execute:

```<code>hdfs dfs -mkdir /user/data
</code>```

If you are executing the hdfs dfs -copyFromLocal command as the user "data" then do this:

```<code>hdfs dfs -chown data:hdfs /user/data
</code>```

If you are executing the command as user "hadoop" then you will need to make sure that /home/hadoop/test.csv and /user/data are both chowned to user hadoop:

```<code>chown hadoop:hadoop /home/hadoop/test.csv
hdfs dfs -chown hadoop:hdfs /user/data
</code>```

Once you have the source file and hdfs location owned correct, then you can execute the hdfs dfs -copyFromLocal

Title: Ingesting csv data to hadoop

Body:
Currently I'm trying to ingesting data to hdfs. The type of data i was trying to ingest is csv.
Hadoop 3.1.1 installed on ubuntu.
data sample stored on /home/hadoop/test.csv

I've Tried

source1

hadoop@ambari:~$ hdfs dfs -put /home/hadoop/test.csv user/data/test.csv
put: `user/data/test.csv': No such file or directory: `hdfs://xxxx:8020/user/hadoop/user/data/test.csv'

so i modify it into just test.csv and it returns

hadoop@ambari:~$ hdfs dfs -put /home/hadoop/test.csv test.csv
put: `test.csv': No such file or directory: `hdfs://xxxx:8020/user/hadoop/test.csv'

because It is written that no directory i follow another source to make a directory
source2
source3

hadoop@ambari:~$ hadoop fs -mkdir bdp
mkdir: `hdfs://xxxx:8020/user/hadoop': No such file or directory
hadoop@ambari:~$ hadoop fs -mkdir /user/hadoop/in
mkdir: `hdfs://xxxx:8020/user/hadoop': No such file or directory

Body:
@yuliansen

The command to copy a file from local disk to hdfs is as follows:

hdfs dfs -copyFromLocal /home/hadoop/test.csv /user/data/

If the folder is not created as hdfs or root user execute:

hdfs dfs -mkdir /user/data

If you are executing the hdfs dfs -copyFromLocal command as the user "data" then do this:

hdfs dfs -chown data:hdfs /user/data

If you are executing the command as user "hadoop" then you will need to make sure that /home/hadoop/test.csv and /user/data are both chowned to user hadoop:

chown hadoop:hadoop /home/hadoop/test.csv
hdfs dfs -chown hadoop:hdfs /user/data

Once you have the source file and hdfs location owned correct, then you can execute the hdfs dfs -copyFromLocal


问:
how do you read the unique ID of an NFC tag on android?
```<code>Tag myTag = (Tag) intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
Log.i("tag ID", myTag.getId().toString());
</code>```

This gives me an ID like "[B@40521c40" but this ID changes every read.

Any help would be greatly appreciated.

Thanks.

答:
Kotlin

I solved this by passing the byte-array ID to following function:

```<code>private fun ByteArrayToHexString(inarray: ByteArray): String? {
    var i: Int
    var j: Int
    var `in`: Int
    val hex = arrayOf(
        "0",
        "1",
        "2",
        "3",
        "4",
        "5",
        "6",
        "7",
        "8",
        "9",
        "A",
        "B",
        "C",
        "D",
        "E",
        "F"
    )
    var out = ""
    j = 0
    while (j < inarray.size) {
        `in` = inarray[j].toInt() and 0xff
        i = `in` shr 4 and 0x0f
        out += hex[i]
        i = `in` and 0x0f
        out += hex[i]
        ++j
    }
    return out
}
</code>```

Source of this function in java:
https://gist.github.com/luixal/5768921

Body:
Tag myTag = (Tag) intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
Log.i("tag ID", myTag.getId().toString());

This gives me an ID like "[B@40521c40" but this ID changes every read.

Any help would be greatly appreciated.

Thanks.

Body:
Kotlin

I solved this by passing the byte-array ID to following function:

private fun ByteArrayToHexString(inarray: ByteArray): String? {
    var i: Int
    var j: Int
    var `in`: Int
    val hex = arrayOf(
        "0",
        "1",
        "2",
        "3",
        "4",
        "5",
        "6",
        "7",
        "8",
        "9",
        "A",
        "B",
        "C",
        "D",
        "E",
        "F"
    )
    var out = ""
    j = 0
    while (j < inarray.size) {
        `in` = inarray[j].toInt() and 0xff
        i = `in` shr 4 and 0x0f
        out += hex[i]
        i = `in` and 0x0f
        out += hex[i]
        ++j
    }
    return out
}

Source of this function in java:
https://gist.github.com/luixal/5768921


问:
QR Code generation in shell / mac terminal
I want to create QR codes for a project I'm working on in applescript the resulting qr will be placed in the indesign document. I have found that there is a plugin for indesign but I suspect that requires user interaction.

So I've been search for how to generate the qr using a shell command. I've found things related to php and rails and even coldfusion but none of those will fit the bill on this. I need to generate them using shell command so image events or perl basically anything I can run from the command line that comes with the mac os

thanks for your help.

antotheer

I wonder if I could call a url using curl or somthing to get one ?

答:
For doing something similar, we use libqrencode.

It's a c library for generating QR codes, but it comes with a command line utility (called qrencode) which lets you generate QR codes from a string, e.g.:

./qrencode -o /tmp/foo.png "This is the input string"

It supports most options you'd probably want (e.g. error correction level, image size, etc.).

We've used it in production for a year or two, with no problems.

I've only run it on linux systems, but there's no reason you shouldn't be able to compile it on Mac OS, assuming you have a compiler and build tools installed (and any libraries it depends on of course).


问:
Is there a way to tell lerna/npm to 'really look in my own node_modules for those peer dependencies'?
I have a fairly standard lerna monorepo that will look like this:

```<code>packages/
    main/  - This is the main deployable application, it depends on both dep and react-dep
    dep/   - Just some pure functions, no problems here
    react-dep/ - A design system built with react, this is where we have problems.

</code>```

So a really common problem that happens, is as soon as you start using hooks in your dependency library, you get this message:

```<code>Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
See https://reactjs.org/warnings/invalid-hook-call-warning.html for tips about how to debug and fix this problem.
</code>```

Which is because there are two version of React in your app, one from the main application, and one from the dependency.

Now - a common solution, that I've used, and works, is to declare react and any other shared/peer dependencies as externals in your webpack configuration. Eg, as suggested here. or look at this Github issues thread from react.

However, I'm not a fan of this solution, firstly, what if I'm not using webpack, and secondly I shouldn't have to manually keep track of which dependencies I need to mark as external.

I think what should work is:

In react-dep I declare react in both devDependencies and peerDependencies. The reason I put it in devDependencies is because my dependency library is likely using storybook or similar to develop the components, so I do need react around in development.

I think that this should work if I'm publishing react-dep to npm and consuming the compiled code from npm in main, because only dependencies are going to be fetched.

However, I think due to the lerna symlinking, what happens in this case is that the dev dependency is still around and we get this error.

Is there a way to solve this issue for a lerna monorepo?

Here's github repo that demonstrates this issue: https://github.com/dwjohnston/lerna-react-monorepo

答:
As I see this problem potentially can be solved using lerna, npm, yarn or webpack.

I want to propose one more webpack solution there, opened a pr to your repo. If a webpack solution is a bad fit for you - just ignore this answer.

It is a little better than externals mechanism, because it will track overlapping peer dependencies automatically.

```<code>module.exports = function(config) {
    config.plugins.push(
        new NormalModuleReplacementPlugin(re, function(resource) {
            // first, remove babel and other loaders paths
            const requestWithoutLoaderMeta = resource.request.split('!');
            const requestPath = requestWithoutLoaderMeta.length && requestWithoutLoaderMeta[requestWithoutLoaderMeta.length - 1];

            if (requestPath) {
                // looking for a dependency and package names
                const packagesPath = resolve(__dirname, '../') + '/';
                const requestPathRel = requestPath.replace(packagesPath, '');
                const [packageName, _, depName] = requestPathRel.split('/');

                // if the main package has this dependency already - just use it
                if (dependencies[packageName]) {
                    console.log('\x1b[35m%s\x1b[0m', `[REPLACEMENT]: using dependency <${depName}> from package [main] instead of [${packageName}]`);
                    resource.request = resource.request.replace(`${packageName}/node_modules/${depName}`, `main/node_modules/${depName}`)
                }
            }
        })
    );

    return config;
}
</code>```

This code will resolve your peer dependencies from main package using webpack.NormalModuleReplacementPlugin.

Note about webpack: since all three frontend kings use it in their CLI (angular, react, vue) I think you can use it easily and safely for such customizations.

I'm happy to hear about alternative technologies (eg. yarn) to solve this problem.

Give @nrwl/nx a try for your next monorepo instead of lerna.

The main difference there is that nrwl projects usually have ONE package.json only (using Google experience), so you need to install the dependencies once for all packages and will not face the problem you described.

Body:
I have a fairly standard lerna monorepo that will look like this:

packages/
    main/  - This is the main deployable application, it depends on both dep and react-dep
    dep/   - Just some pure functions, no problems here
    react-dep/ - A design system built with react, this is where we have problems.

So a really common problem that happens, is as soon as you start using hooks in your dependency library, you get this message:

Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
See https://reactjs.org/warnings/invalid-hook-call-warning.html for tips about how to debug and fix this problem.

Which is because there are two version of React in your app, one from the main application, and one from the dependency.

Now - a common solution, that I've used, and works, is to declare react and any other shared/peer dependencies as externals in your webpack configuration. Eg, as suggested here. or look at this Github issues thread from react.

However, I'm not a fan of this solution, firstly, what if I'm not using webpack, and secondly I shouldn't have to manually keep track of which dependencies I need to mark as external.

I think what should work is:

In react-dep I declare react in both devDependencies and peerDependencies. The reason I put it in devDependencies is because my dependency library is likely using storybook or similar to develop the components, so I do need react around in development.

I think that this should work if I'm publishing react-dep to npm and consuming the compiled code from npm in main, because only dependencies are going to be fetched.

However, I think due to the lerna symlinking, what happens in this case is that the dev dependency is still around and we get this error.

Is there a way to solve this issue for a lerna monorepo?

Here's github repo that demonstrates this issue: https://github.com/dwjohnston/lerna-react-monorepo

Body:
As I see this problem potentially can be solved using lerna, npm, yarn or webpack.

I want to propose one more webpack solution there, opened a pr to your repo. If a webpack solution is a bad fit for you - just ignore this answer.

It is a little better than externals mechanism, because it will track overlapping peer dependencies automatically.

module.exports = function(config) {
    config.plugins.push(
        new NormalModuleReplacementPlugin(re, function(resource) {
            // first, remove babel and other loaders paths
            const requestWithoutLoaderMeta = resource.request.split('!');
            const requestPath = requestWithoutLoaderMeta.length && requestWithoutLoaderMeta[requestWithoutLoaderMeta.length - 1];

            if (requestPath) {
                // looking for a dependency and package names
                const packagesPath = resolve(__dirname, '../') + '/';
                const requestPathRel = requestPath.replace(packagesPath, '');
                const [packageName, _, depName] = requestPathRel.split('/');

                // if the main package has this dependency already - just use it
                if (dependencies[packageName]) {
                    console.log('\x1b[35m%s\x1b[0m', `[REPLACEMENT]: using dependency <${depName}> from package [main] instead of [${packageName}]`);
                    resource.request = resource.request.replace(`${packageName}/node_modules/${depName}`, `main/node_modules/${depName}`)
                }
            }
        })
    );

    return config;
}

This code will resolve your peer dependencies from main package using webpack.NormalModuleReplacementPlugin.

Note about webpack: since all three frontend kings use it in their CLI (angular, react, vue) I think you can use it easily and safely for such customizations.

I'm happy to hear about alternative technologies (eg. yarn) to solve this problem.

Give @nrwl/nx a try for your next monorepo instead of lerna.

The main difference there is that nrwl projects usually have ONE package.json only (using Google experience), so you need to install the dependencies once for all packages and will not face the problem you described.


问:
SQL using 0 row from where as 0 rows to group by instead of nothing
This is my table

I am using the next query

```<code>    SELECT XFailTbl.id,
       xfail,
       yfail
FROM   (SELECT Count(*) AS XFail,
               [id]
        FROM   [table]
        WHERE  ( x < xmin
                  OR x > xmax )
        GROUP  BY [id]) AS XFailTbl
       JOIN (SELECT Count(*) AS YFail,
                    [id]
             FROM   [table]
             WHERE  ( y < ymin
                       OR y > ymax )
             GROUP  BY [id]) AS YFailTbl
         ON XFailTbl.id = YFailTbl.id
</code>```

I got the next result

my expecting result is

I understand that I cant using the condition of  (Y<Ymin OR Y>YMax) because I get 0 rows to the group by and it can't count the 0 rows because it doesn't know it exists
But what is the way to get the expecting result?  I have no idea...

Thanks

答:
You just want conditional aggregation:</p>

```<code>select id,
       sum(case when X < Xmin or X > XMax then 1 else 0 end) as xfail,
       sum(case when Y < Ymin or Y > YMax then 1 else 0 end) as yfail
from
group by id;
</code>```

Body:
This is my table

I am using the next query

    SELECT XFailTbl.id,
       xfail,
       yfail
FROM   (SELECT Count(*) AS XFail,
               [id]
        FROM   [table]
        WHERE  ( x < xmin
                  OR x > xmax )
        GROUP  BY [id]) AS XFailTbl
       JOIN (SELECT Count(*) AS YFail,
                    [id]
             FROM   [table]
             WHERE  ( y < ymin
                       OR y > ymax )
             GROUP  BY [id]) AS YFailTbl
         ON XFailTbl.id = YFailTbl.id

I got the next result

my expecting result is

I understand that I cant using the condition of  (Y<Ymin OR Y>YMax) because I get 0 rows to the group by and it can't count the 0 rows because it doesn't know it exists
But what is the way to get the expecting result?  I have no idea...

Thanks

Body:
You just want conditional aggregation:

select id,
       sum(case when X < Xmin or X > XMax then 1 else 0 end) as xfail,
       sum(case when Y < Ymin or Y > YMax then 1 else 0 end) as yfail
from
group by id;


问:
Open Leaflet Popup fullscreen in smartphones
I can not figure out how to configure CSS to make popups open fullscreen in my Leaflet App in case people access it from devices with small screens. Everything I found out so far is how to adjust the size of the popup-wrapper. "width:100%, height:100%" doesn't work for me.  </p>

```<code>.popupCustom{
    font-family: Verdana;
    font-size: 13px;
    width: 330px;
}
@media (min-width: 768px) and (max-width: 991px) {
    .leaflet-popup-content-wrapper {
        width: 250px;} }
@media (min-width: 992px) and (max-width: 1199px) {
    .leaflet-popup-content-wrapper {
        width: 280px; } }
@media (min-width: 1200px) {
    .leaflet-popup-content-wrapper {
        width: 330px; }
}
</code>```

答:
Cannot be done. A Leaflet popup is contained within block elements which have a CSS transform applied to them (i.e. the map panes), so the usual technique of setting CSS position property to fixed won't be able to get the popup away from its containing block.

You'll have to resort to alternative solutions, such as having another HTML block element outside of the map container, updating its contents to mimic the contents of the popup, and conditionally showing said element or the popup depending on the viewport size, e.g.:

```<code><!-- HTML -->
<div id='map'></div>
<div id='fullScreenInfo'></div>
</code>```

```<code>/* CSS */
#fullScreenInfo { display: none; }
@media (max-width: 768px) { #fullScreenInfo.visible { display:fixed; left:0; right: 0; top:0; bottom: 0; } }
</code>```

```<code>/* JS */
map.on('popupopen', function(ev){
  var el = document.getElementById('fullScreenInfo');
  el.innerHTML = ev.popup.getContent();
  el.classList.add('visible');
});
map.on('popupclose', function(ev){
  var el = document.getElementById('fullScreenInfo');
  el.classList.remove('visible');
});
</code>```

Plus you should add some UI element for the user to close the "fullscreen popup" when shown (which should likely call map.closePopup()).

Body:
I can not figure out how to configure CSS to make popups open fullscreen in my Leaflet App in case people access it from devices with small screens. Everything I found out so far is how to adjust the size of the popup-wrapper. "width:100%, height:100%" doesn't work for me.

.popupCustom{
    font-family: Verdana;
    font-size: 13px;
    width: 330px;
}
@media (min-width: 768px) and (max-width: 991px) {
    .leaflet-popup-content-wrapper {
        width: 250px;} }
@media (min-width: 992px) and (max-width: 1199px) {
    .leaflet-popup-content-wrapper {
        width: 280px; } }
@media (min-width: 1200px) {
    .leaflet-popup-content-wrapper {
        width: 330px; }
}

Body:
Cannot be done. A Leaflet popup is contained within block elements which have a CSS transform applied to them (i.e. the map panes), so the usual technique of setting CSS position property to fixed won't be able to get the popup away from its containing block.

You'll have to resort to alternative solutions, such as having another HTML block element outside of the map container, updating its contents to mimic the contents of the popup, and conditionally showing said element or the popup depending on the viewport size, e.g.:

<!-- HTML -->
<div id='map'></div>
<div id='fullScreenInfo'></div>

/* CSS */
#fullScreenInfo { display: none; }
@media (max-width: 768px) { #fullScreenInfo.visible { display:fixed; left:0; right: 0; top:0; bottom: 0; } }

/* JS */
map.on('popupopen', function(ev){
  var el = document.getElementById('fullScreenInfo');
  el.innerHTML = ev.popup.getContent();
  el.classList.add('visible');
});
map.on('popupclose', function(ev){
  var el = document.getElementById('fullScreenInfo');
  el.classList.remove('visible');
});

Plus you should add some UI element for the user to close the "fullscreen popup" when shown (which should likely call map.closePopup()).


问:
Where is the IPA on the Mac (when it's used as a build server)?
On Visual Studio version 16.6.1 (on Windows), when building a Xamarin.iOS app with a Mac as a build server, the "Show IPA File on Build Server" option is grayed out.

So where can I find the IPA on the Mac?

(I already searched in the Mac's HD -> Library -> Caches , but there is no "Xamarin" folder there.)

答:
You are using the wrong Library folder.

You need to go to ~/Library/Caches/Xamarin/. Then the builds will be in mtbs/builds folder.

Where ~ is your user's base directory.

NB: Keep in mind that the user's Library folder is hidden, so you will need to either show the hidden files (cmd + shift + .), or to navigate through the terminal or with Finder's Go to folder... options (cmd + shift + G or through the menu Go --> Go To Folder...).


问:
How to access broadcast variable from a udf and broadcast variable is defined in another class where this udf is being called
How to access the broadcast variable from a UDF and broadcast variable is defined in another class where this UDF is being called.

```<code>    /* this udf is in different file */
    package com.abc
     public class JavaClass{
        public static UserDefinedFunction getvalue = udf((String param) -> {

        return "String value";
        }, DataTypes.StringType);

    }
**/* below code is in different file */**
    package com.xyz;
    import com.abc.JavaClass;
     public class AnotherClassToCallUDF{
        pubic static void main(String args[]) {
    Dataset<Row> abc = .......;

    abc.withColoumn("new-col",JavaClass.getvalue.apply("passing some value"));
    }

    }

    **/* in the above code , how to pass broadcast variable while calling udf...since udf accepts only col typ`enter code here`e and lit type ..it does not accept anything else..then how to access broadcast variable which is defined in main class and accessing in another class..
*/**
</code>```

答:
Try this-

1. create UDF

class MyUDF implements UDF1<Long, String> {
        private Map<Long, String> broadCastMap;
        public MyUDF(Broadcast<Map<Long, String>> broadCastMap) {
           this.broadCastMap = broadCastMap.value();
        }
        public String call(Long id) {
            return id +" -> " + broadCastMap.getOrDefault(id, "No mapping");
        }
    }
```

<h2>2. Use udf to pass the broadcast and use it</h2>

<pre class="lang-java prettyprint-override"><code>Dataset<Row> inputDf = spark.range(1, 5).withColumn("col1", lit("a"));
        inputDf.show(false);
        inputDf.printSchema();
        /**
         * +---+----+
         * |id |col1|
         * +---+----+
         * |1  |a   |
         * |2  |a   |
         * |3  |a   |
         * |4  |a   |
         * +---+----+
         *
         * root
         *  |-- id: long (nullable = false)
         *  |-- col1: string (nullable = false)
         */

        // Create broadcast
        Map<Long, String> map = new HashMap<>();
        map.put(1L, "b");
        map.put(2L, "c");
        Broadcast<Map<Long, String>> broadCastMap = new JavaSparkContext(spark.sparkContext()).broadcast(map);

        UserDefinedFunction myUdf = udf(new MyUDF(broadCastMap), DataTypes.StringType);

        spark.sqlContext().udf().register("myUdf", myUdf);

        inputDf.withColumn("new_col", callUDF("myUdf",
                JavaConverters.asScalaBufferConverter(Collections.singletonList(col("id"))).asScala()))
                .show();
        /**
         * +---+----+---------------+
         * | id|col1|        new_col|
         * +---+----+---------------+
         * |  1|   a|         1 -> b|
         * |  2|   a|         2 -> c|
         * |  3|   a|3 -> No mapping|
         * |  4|   a|4 -> No mapping|
         * +---+----+---------------+
         */

</code>```

3. Without registering the UDF to FunctionRegistry

 inputDf.withColumn("new_col", myUdf.apply(col("id")))
                .show();
        /**
         * +---+----+---------------+
         * | id|col1|        new_col|
         * +---+----+---------------+
         * |  1|   a|         1 -> b|
         * |  2|   a|         2 -> c|
         * |  3|   a|3 -> No mapping|
         * |  4|   a|4 -> No mapping|
         * +---+----+---------------+
         */
```

Body:
How to access the broadcast variable from a UDF and broadcast variable is defined in another class where this UDF is being called.

    /* this udf is in different file */
    package com.abc
     public class JavaClass{
        public static UserDefinedFunction getvalue = udf((String param) -> {

        return "String value";
        }, DataTypes.StringType);

    }
**/* below code is in different file */**
    package com.xyz;
    import com.abc.JavaClass;
     public class AnotherClassToCallUDF{
        pubic static void main(String args[]) {
    Dataset<Row> abc = .......;

    abc.withColoumn("new-col",JavaClass.getvalue.apply("passing some value"));
    }

    }

    **/* in the above code , how to pass broadcast variable while calling udf...since udf accepts only col typ`enter code here`e and lit type ..it does not accept anything else..then how to access broadcast variable which is defined in main class and accessing in another class..
*/**

Body:
Try this-

1. create UDF

class MyUDF implements UDF1<Long, String> {
        private Map<Long, String> broadCastMap;
        public MyUDF(Broadcast<Map<Long, String>> broadCastMap) {
           this.broadCastMap = broadCastMap.value();
        }
        public String call(Long id) {
            return id +" -> " + broadCastMap.getOrDefault(id, "No mapping");
        }
    }

2. Use udf to pass the broadcast and use it

Dataset<Row> inputDf = spark.range(1, 5).withColumn("col1", lit("a"));
        inputDf.show(false);
        inputDf.printSchema();
        /**
         * +---+----+
         * |id |col1|
         * +---+----+
         * |1  |a   |
         * |2  |a   |
         * |3  |a   |
         * |4  |a   |
         * +---+----+
         *
         * root
         *  |-- id: long (nullable = false)
         *  |-- col1: string (nullable = false)
         */

        // Create broadcast
        Map<Long, String> map = new HashMap<>();
        map.put(1L, "b");
        map.put(2L, "c");
        Broadcast<Map<Long, String>> broadCastMap = new JavaSparkContext(spark.sparkContext()).broadcast(map);

        UserDefinedFunction myUdf = udf(new MyUDF(broadCastMap), DataTypes.StringType);

        spark.sqlContext().udf().register("myUdf", myUdf);

        inputDf.withColumn("new_col", callUDF("myUdf",
                JavaConverters.asScalaBufferConverter(Collections.singletonList(col("id"))).asScala()))
                .show();
        /**
         * +---+----+---------------+
         * | id|col1|        new_col|
         * +---+----+---------------+
         * |  1|   a|         1 -> b|
         * |  2|   a|         2 -> c|
         * |  3|   a|3 -> No mapping|
         * |  4|   a|4 -> No mapping|
         * +---+----+---------------+
         */

3. Without registering the UDF to FunctionRegistry

 inputDf.withColumn("new_col", myUdf.apply(col("id")))
                .show();
        /**
         * +---+----+---------------+
         * | id|col1|        new_col|
         * +---+----+---------------+
         * |  1|   a|         1 -> b|
         * |  2|   a|         2 -> c|
         * |  3|   a|3 -> No mapping|
         * |  4|   a|4 -> No mapping|
         * +---+----+---------------+
         */


问:
How to use a InfluxDB-tag value in a grafana legend?
I have a InfluxDB dataseries. It stores one information about mulitple machines. I distingsh between these machines with a tag. I can display the information for all three machines at once using a "Group by tag(machine)" clause. the name of the legends is "table.derivative {machine: 1}", "table.derivative {machine: 2}" and so on. How can I change it to "machine 1", "machine 2" and so on?

So far I came across this suggesting to use $groupby (or $g ?), but both are just added a literally.

答: For me $_tag_TAGNAME worked ... none of the above worked for me ( even though I saw it in the help section of my instance of Grafana ...)


问:
how to show upload progress for each image upload
I am using react-dropzone for multiple image upload. The image upload is working but the upload progress is not showing. I could not find on the documentation clearly about showing upload progress. How can we show upload progress in react-dropzone?

I have created a codesandbox too. Here is the link

https://codesandbox.io/s/8BEmjLmo

Here is the code too

```<code>onDrop = (accepted, rejected) => {
    this.setState({
      accepted,
      rejected
    });
  };

  showFiles() {
    const { accepted } = this.state;
    return (
      <div>
        <h3>Dropped files: </h3>
        <ul className="gallery">
          {accepted.map((file, idx) => {
            return (
              <div className="col-md-3" key={idx}>
                <li>
                  <img
                    src={file.preview}
                    className="img-fluid img-responsive"
                    width={200}
                    alt={file.name}
                  />
                  <i
                    className="fa fa-remove"
                    onClick={e => this.handleRemove(file)}
                  />
                  <div className="imageName">{file.name}</div>
                </li>
              </div>
            );
          })}
        </ul>
      </div>
    );
  }
  render() {
    const { accepted } = this.state;
    return (
      <div style={styles}>
    <Hello name="CodeSandbox" />
    <Dropzone
      onDrop={this.onDrop}
      style={style}
      activeStyle={activeStyle}
      multiple
      accept="image/*"
    >
      Try Dropping file
        </Dropzone>
   {accepted.length !== 0 && this.showFiles()}
    </div>
    );
  }
}
</code>```

答:
Here is my full example that I use with react-dropzone:</p>

```<code>onDrop(acceptedFiles) {
  const formData = new FormData();
  for (const file of acceptedFiles) formData.append('file', file);

  const xhr = new XMLHttpRequest();
  xhr.upload.onprogress = event => {
   const percentage = parseInt((event.loaded / event.total) * 100);
   console.log(percentage); // Update progress here
  };
  xhr.onreadystatechange = () => {
    if (xhr.readyState !== 4) return;
    if (xhr.status !== 200) {
     console.log('error'); // Handle error here
    }
     console.log('success'); // Handle success here
  };
  xhr.open('POST', 'https://httpbin.org/post', true);
  xhr.send(formData);
}
</code>```

Body:
I am using react-dropzone for multiple image upload. The image upload is working but the upload progress is not showing. I could not find on the documentation clearly about showing upload progress. How can we show upload progress in react-dropzone?

I have created a codesandbox too. Here is the link

https://codesandbox.io/s/8BEmjLmo

Here is the code too

onDrop = (accepted, rejected) => {
    this.setState({
      accepted,
      rejected
    });
  };

  showFiles() {
    const { accepted } = this.state;
    return (

Dropped files:

          {accepted.map((file, idx) => {
            return (

                   this.handleRemove(file)}
                  />

{file.name}

            );
          })}

    );
  }
  render() {
    const { accepted } = this.state;
    return (

    <Hello name="CodeSandbox" />
    <Dropzone
      onDrop={this.onDrop}
      style={style}
      activeStyle={activeStyle}
      multiple
      accept="image/*"
    >
      Try Dropping file
        </Dropzone>
   {accepted.length !== 0 && this.showFiles()}

    );
  }
}

Body:
Here is my full example that I use with react-dropzone:

onDrop(acceptedFiles) {
  const formData = new FormData();
  for (const file of acceptedFiles) formData.append('file', file);

  const xhr = new XMLHttpRequest();
  xhr.upload.onprogress = event => {
   const percentage = parseInt((event.loaded / event.total) * 100);
   console.log(percentage); // Update progress here
  };
  xhr.onreadystatechange = () => {
    if (xhr.readyState !== 4) return;
    if (xhr.status !== 200) {
     console.log('error'); // Handle error here
    }
     console.log('success'); // Handle success here
  };
  xhr.open('POST', 'https://httpbin.org/post', true);
  xhr.send(formData);
}


问:
ora-28040 no matching authentication protocol from Oracle client 12C to Oracle Database 19c
We recently migrated our database to 19c. Have a few .net applications which connect to Oracle db using system.data.oracleclient. The version of Oracle client installed is 12C. After the database upgrade, .net applications are unable to connect to the database due to the ORA-28040 No matching authentication protocol error.</p>

答:
Your Oracle client is not compatible by default with the upgraded database; it isn't hashing your password to the latest, most secure standard. You either need to upgrade your client to 12cR2 or later, or add the following lines to sqlnet.ora on your database server to force it to accept older (less secure) password hashes:

```<code>sqlnet.allowed_logon_version_server=12
sqlnet.allowed_logon_version_client=12
</code>```

If that still doesn't work, you can try setting the values to "11", but don't go any lower than that for security reasons.

Note that you must reset the password of the user you want to use after applying these configurations.

Body:
Your Oracle client is not compatible by default with the upgraded database; it isn't hashing your password to the latest, most secure standard. You either need to upgrade your client to 12cR2 or later, or add the following lines to sqlnet.ora on your database server to force it to accept older (less secure) password hashes:

sqlnet.allowed_logon_version_server=12
sqlnet.allowed_logon_version_client=12

If that still doesn't work, you can try setting the values to "11", but don't go any lower than that for security reasons.

Note that you must reset the password of the user you want to use after applying these configurations.


问:
RegEx in Java: how to deal with newline
I am currently trying to learn how to use regular expressions so please bear with my simple question. For example, say I have an input file containing a bunch of links separated by a newline:

www.foo.com/Archives/monkeys.htm

Description of Monkey's website.

www.foo.com/Archives/pigs.txt

Description of Pig's website.

www.foo.com/Archives/kitty.txt

Description of Kitty's website.

www.foo.com/Archives/apple.htm

Description of Apple's website.

If I wanted to get one website along with its description, this regex seems to work on a testing tool: .*www.*\\s.*Pig.*

However, when I try running it within my code it doesn't seem to work. Is this expression correct? I tried replacing "\s" with "\n" and it doesn't seem to work still.

答:
```<code>String str="I am  a   "+"\n  Man    of  Peace"+"\t"+"   .";

str=str.replaceAll("[\\s|\\t|\\r\\n]+"," ").trim();
System.out.println(str);
</code>```

This above example works for tabSpaces, newLines, and normal spaces.
And I have used the trim method of java.lang.String to remove all the additional spaces in 'str'. I hope this helps you and other amazing people here.

Title: RegEx in Java: how to deal with newline

Body:
String str="I am  a   "+"\n  Man    of  Peace"+"\t"+"   .";

str=str.replaceAll("[\\s|\\t|\\r\\n]+"," ").trim();
System.out.println(str);

This above example works for tabSpaces, newLines, and normal spaces.
And I have used the trim method of java.lang.String to remove all the additional spaces in 'str'. I hope this helps you and other amazing people here.


问:
How to load Image with Picasso using base64?
Picasso documentation

As you can see using the link that, Picasso has only 3 options to load an image. My question is how to load an image if you have a base64 string parsed from JSON response from an api?

答:
There are no additional methods to do this process in Picasso, you can use the native Java method to convert Base64 text to bytes array then simply get the job done.

You can get the Bitmap image so you can run Picasso using Bitmap as well.

The Base64 text should be formatted as: data:image/png;base64,iV....

```<code>String base64Image = base64Text.split(",")[1];
byte[] imageAsBytes = Base64.decode(base64Image.getBytes(), Base64.DEFAULT);
img.setImageBitmap(BitmapFactory.decodeByteArray(imageAsBytes, 0, imageAsBytes.length));
</code>```

Body:
There are no additional methods to do this process in Picasso, you can use the native Java method to convert Base64 text to bytes array then simply get the job done.

You can get the Bitmap image so you can run Picasso using Bitmap as well.

The Base64 text should be formatted as: data:image/png;base64,iV....

String base64Image = base64Text.split(",")[1];
byte[] imageAsBytes = Base64.decode(base64Image.getBytes(), Base64.DEFAULT);
img.setImageBitmap(BitmapFactory.decodeByteArray(imageAsBytes, 0, imageAsBytes.length));