I wrote simple https client program for tests. It should work in keep-alive mode and not keep-alive. And it leaks badly.. In keep-alive mode it leaks twice slower.
This is sample working program.
package main
import (
"bytes"
"fmt"
"net/http"
"time"
"io/ioutil"
"os"
"crypto/tls"
)
func main() {
if len(os.Args) < 3 {
fmt.Println("Usage: cl <url> <close>")
return
}
url := os.Args[1]
tr := &http.Transport{
TLSClientConfig: &tls.Config{},
DisableCompression: true,
}
client := &http.Client{Transport: tr, Timeout: time.Second}
for {
buf := bytes.NewBuffer([]byte(`Sed ut perspiciatis, unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam
eaque ipsa, quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt, explicabo. Nemo enim ipsam
voluptatem, quia voluptas sit, aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos, qui ratione
voluptatem sequi nesciunt, neque porro quisquam est, qui dolorem ipsum, quia dolor sit, amet, consectetur, adipisci
velit, sed quia non numquam eius modi tempora incidunt, ut labore et dolore magnam aliquam quaerat voluptatem.
Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea
commodi consequatur? Quis autem vel eum iure reprehenderit, qui in ea voluptate velit esse, quam nihil molestiae
consequatur, vel illum, qui dolorem eum fugiat, quo voluptas nulla pariatur? At vero eos et accusamus et iusto
odio dignissimos ducimus, qui blanditiis praesentium voluptatum deleniti atque corrupti, quos dolores et quas
molestias excepturi sint, obcaecati cupiditate non provident, similique sunt in culpa, qui officia deserunt
mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio.
Nam libero tempore, cum soluta nobis est eligendi optio, cumque nihil impedit, quo minus id, quod maxime
placeat, facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam
et aut officiis debitis aut rerum necessitatibus saepe eveniet, ut et voluptates repudiandae sint et
molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus
maiores alias consequatur aut perferendis doloribus asperiores repellat.`))
req, err := http.NewRequest("POST", url, nil)
if err != nil {
fmt.Println(err)
return
}
req.Header.Add("Content-Type", "application/json")
if os.Args[1] != "0" {
req.Close = true
}
req.Body = ioutil.NopCloser(buf)
fmt.Printf("Sending to %s: \n%s\n=================\n", url, string(buf.Bytes()))
if resp, err := client.Do(req); err != nil {
fmt.Println(err, "\n")
buf.Reset()
} else {
fmt.Printf("Response: %s\n\n", resp.Status)
resp.Body.Close()
buf.Reset()
}
time.Sleep(50 * time.Millisecond)
}
}
I'm creating new buffer every time because in real program this message is always new string.
Usage example: so https://youtube.com 1
So the question is what am I doing wrong?
Related
I have created an API for returning website articles :
public function showAllArticles(){
return Article::paginate(10);
}
in the article I have a text body (description) that may have a long text that I won't need, how can I put a str_limit to it ?
Default Output :
{
"current_page": 1,
"data": [
{
"id": 1,
"title": "Ut veniam dolorem et quia. Reprehenderit eum sed doloremque qui est. Sit rerum vel ex quia.",
"slug": "dignissimos-rerum-doloribus-necessitatibus-sit-autem-ad-fuga-cum",
"description": "Deleniti in soluta beatae id ipsa. Quia exercitationem est possimus reiciendis tempora odio. Et perspiciatis dolores dignissimos aperiam voluptatum.\n\nVoluptatem est in maiores porro error qui assumenda. Quaerat eaque vitae neque molestiae laboriosam quis necessitatibus. Vero ut qui sunt. Reiciendis dolorem enim eius recusandae praesentium repellendus.\n\nAd minima deleniti et placeat. Nisi veritatis neque et nobis voluptas. Doloremque officia aperiam aliquid repellendus nesciunt omnis.\n\nEt corrupti et totam est quod dolorum aliquam. Quo sit sequi distinctio inventore eveniet et ut. Ad voluptas perspiciatis incidunt sit. Voluptatem voluptas exercitationem debitis.\n\nEt hic beatae ducimus ad eligendi suscipit. Aut facilis magnam sequi id et ut. Reiciendis sequi iusto maiores nam delectus quasi.\n\nEt in officia earum dolores sunt et. Corrupti voluptatem delectus voluptates exercitationem molestiae aspernatur omnis corrupti. Consectetur sint quos vero nulla id alias. Possimus nam eius molestiae facere et non a.\n\nSint autem debitis corporis animi et beatae et. Aut occaecati nihil et temporibus perferendis. Commodi eligendi quo non et soluta. Vitae dolor sed qui distinctio numquam ad nihil.",
"user_id": 13,
"special": 0,
"image": null,
"created_at": "2021-10-27T21:36:37.000000Z",
"updated_at": "2021-10-27T21:36:37.000000Z"
}, ...
I want to make my "description" to have a lenth limit and add a extra "..." at the end of it.
I have tried this :
$data = Article::paginate(10);
$data->each(function($article){
// I can access each article with $article but I dont know how to modify it in $data
});
You can create an Eloquent: API Resource:
php artisan make:resource ArticleResource
And use the Str::limit helper for that property:
<?php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;
class ArticleResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
public function toArray($request)
{
return [
'id' => $this->id,
'title' => $this->title,
'slug' => $this->slug,
'description' => Str::limit($this->description, 50),
//...
];
}
}
Then in your controller return the resource collection:
use App\Http\Resources\ArticleResource;
use App\Models\User;
//...
public function showAllArticles(){
return ArticleResource::collection(Article::paginate(10));
}
You should use the collection function map instead of each, here you can find the documentation for the function: https://laravel.com/docs/8.x/collections#method-map
The map method iterates through the collection and passes each value to the given callback. The callback is free to modify the item and return it, thus forming a new collection of modified items
EDIT: There is another solution to your issue that would be better in regard of performance, and that is to make the shortening procedure in your query instead of handling it in PHP. Solution can be found here: https://laracasts.com/discuss/channels/laravel/how-to-get-trimmed-value-via-eloquent?page=1&replyId=435130
One solution would be with Custom Resources (like porloscerros already answeared) and one with Accesor. With accesors: You can add the method in your Article model:
use Illuminate\Support\Str;
public funtion getDescriptionAttribute($value)
{
$words = 20;
return Str::of($value)->words($words, ' >>>');
}
server and normally I got it to work. However this time there is an boundary I want to save some time.
I have the following json file:
{ "posts": [
{
"id": 1,
"title": "React",
"category": "React-Development",
"imageUrl": "https://cdn.pixabay.com/photo/2015/04/23/22/00/tree-736885_1280.jpg",
"text": "Lorem ipsum dolor sit amet consectetur adipisicing elit. Maxime mollitia, molestiae quas vel sint commodi repudiandae consequuntur voluptatum laborum numquam blanditiis harum quisquam eius sed odit fugiat iusto fuga praesentium optio, eaque rerum! Provident similique accusantium nemo autem. Veritatis obcaecati tenetur iure eius earum ut molestias architecto voluptate aliquam nihil, eveniet aliquid culpa officia aut! Impedit sit sunt quaerat, odit,tenetur error, harum nesciunt ipsum debitis quas aliquid. Reprehenderit, quia. Quo neque error repudiandae fuga? Ipsa laudantium molestias eos sapiente officiis modi at sunt excepturi expedita sint? Sed quibusdam recusandae alias error harum maxime adipisci amet laborum. Perspiciatis minima nesciunt dolorem! Officiis iure rerum voluptates a cumque velit ",
"date": "23/34/2021"
},
{
"id": 2,
"title": "React",
"category": "React-Development",
"imageUrl": "https://cdn.pixabay.com/photo/2015/04/23/22/00/tree-736885_1280.jpg",
"text": "Lorem ipsum dolor sit amet consectetur adipisicing elit. Maxime mollitia, molestiae quas vel sint commodi repudiandae consequuntur voluptatum laborum numquam blanditiis harum quisquam eius sed odit fugiat iusto fuga praesentium optio, eaque rerum! Provident similique accusantium nemo autem. Veritatis obcaecati tenetur iure eius earum ut molestias architecto voluptate aliquam nihil, eveniet aliquid culpa officia aut! Impedit sit sunt quaerat, odit,tenetur error, harum nesciunt ipsum debitis quas aliquid. Reprehenderit, quia. Quo neque error repudiandae fuga? Ipsa laudantium molestias eos sapiente officiis modi at sunt excepturi expedita sint? Sed quibusdam recusandae alias error harum maxime adipisci amet laborum. Perspiciatis minima nesciunt dolorem! Officiis iure rerum voluptates a cumque velit ",
"date": "23/34/2021"
},
], "category": [
"React-Development",
"Vue3-Topics",
"Angular",
"Backend",
"Vue-Development",
"Angular-Development" ] }
I tried to post with and without Id. Should also work without Id I suppose.
{
"id": 99,
"title": "React",
"category": "React-Development",
"imageUrl": "https://cdn.pixabay.com/photo/2015/04/23/22/00/tree-736885_1280.jpg",
"text": "Hello World",
"date": "23/34/2021"
}
However the result I got after a couple of tries.
{
"id": 9
}
Found it! Most likely you didn't change to JSON in the dropdown menu to the right of Body's options row.
My problem is, that coreui in laravel does render the components, but none of them are interactive. For example when I use Tabs (CTabs), then it gets displayed correctly, but I cannot switch the tabs.
This is how I load coreui and the components:
import CoreuiVue from '#coreui/vue';
Vue.use(CoreuiVue);
// Registering a single component
import { CSwitch, CButton, CTabs, CTab, CCarousel, CCarouselItem } from '#coreui/vue';
Vue.component('CTabs', CTabs)
Vue.component('CTab', CTab)
Vue.component('CCarousel', CCarousel)
Vue.component('CCarouselItem', CCarouselItem)
// globally
Vue.directive('c-emit-root-event', CEmitRootEvent)
export default {
components: {
CTabs, CTab, CCarousel, CCarouselItem
},
directives: {
'c-tooltip': CTooltip
},
}
Vue.component(
'example-component',
require('./components/ExampleComponent.vue').default
);
const app = new Vue({
el: '#my-app',
data(){
}
});
Then the ExampleComponent.vue
<template>
<div>
<CTabs variant="pills" :active-tab="0">
<CTab title="Home">
1. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore
et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum
dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui
officia deserunt mollit anim id est laborum.
</CTab>
<CTab title="Profile">
2. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore
et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum
dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui
officia deserunt mollit anim id est laborum.
</CTab>
<CTab title="Disabled" >
Text will not be shown.
</CTab>
</CTabs>
<CCarousel
arrows
indicators
animate
height="450px"
>
<CCarouselItem
captionHeader="First Slide"
image="https://picsum.photos/1024/480/?image=52"
captionText="Nulla vitae elit libero, a pharetra augue mollis interdum."
/>
<CCarouselItem
captionHeader="Blank page"
:image="{ placeholderColor: 'grey' }"
captionText="Nulla vitae elit libero, a pharetra augue mollis interdum."
/>
<CCarouselItem
image="https://picsum.photos/1024/480/?image=54"
/>
</CCarousel>
</div>
</template>
<script>
module.exports = {
data: function () {
return {
message : 'Hello Vue!!'
}
},
name: 'example-component'
}
</script>
and the view file
<div id="my-app">
<example-component></example-component>
</div>
Any ideas?
I simply had to wrap the Vue Object into DOMContentLoaded to make sure that the DOM is ready before attaching vue.js.
document.addEventListener("DOMContentLoaded", function(event) {
const app = new Vue({
el: '#my-app',
data(){
}
});
})
I created 2 documents of autogenerated test data in an index/type using:
POST /mymixedata/lists-and-nums/
{
"pat_first_name": "Balduin",
"pat_last_name": "Goodbairn",
"gender": "Male",
"diag_codes": "T84028D",
"prov_first_name": "Dwight",
"prov_last_name": "Croutear",
"prov_addr": "617 Monterey Drive",
"rand_list": [
123,
456,
123
],
"notes": "Quisque porta volutpat erat. Quisque erat eros, viverra eget, congue eget, semper rutrum, nulla. Nunc purus."
}
POST mymixedata/lists-and-nums
{
"pat_first_name": "Goorbi",
"pat_last_name": "Goorbson",
"gender": "Female",
"diag_codes": "S22039D",
"prov_first_name": "Tarrah",
"prov_last_name": "Jimeno",
"prov_addr": "13483 Walton Road",
"rand_list": 100,
"notes": "Phasellus sit amet erat. Nulla tempus. Vivamus in felis eu sapien cursus vestibulum.\n\nProin eu mi. Nulla ac enim. In tempor, turpis nec euismod scelerisque, quam turpis adipiscing lorem, vitae mattis nibh ligula nec sem.\n\nDuis aliquam convallis nunc. Proin at turpis a pede posuere nonummy. Integer non velit.\n\nDonec diam neque, vestibulum eget, vulputate ut, ultrices vel, augue. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Donec pharetra, magna vestibulum aliquet ultrices, erat tortor sollicitudin mi, sit amet lobortis sapien sapien non mi. Integer ac neque.\n\nDuis bibendum. Morbi non quam nec dui luctus rutrum. Nulla tellus.\n\nIn sagittis dui vel nisl. Duis ac nibh. Fusce lacus purus, aliquet at, feugiat non, pretium quis, lectus."
}
Notice that for the field rand_list, one doc has an array of nums and the other has a single num. Querying the index/type like so:
{
"query": {
"bool": {
"must": [
{
"range": {
"rand_list": {
"gt": "50"
}
}
}
]
}
}
}
I get back both of the documents, which seems like the behavior that I want (assuming its checking the array of nums in the fist doc and the single num in the second to determine if they contain a value > 50).
Other than here, I can't find much documentation on how elastic treats fields that sometimes have arrays and sometimes have single values.
Can anyone explain what's going on? Do single values count as arrays even when they don't have surrounding brackets (ie. is field: 123 same as field: [123] in a doc)?
Thanks :)
Guess I just did not read the docs close enough. Turns out that yes, can have either arrays or single values of same datatype for the same fields in documents.
I would like to get rid of the close/X button on the top right corner of my Google Closure dialog.
I am browsing the documentation (http://closure-library.googlecode.com/svn-history/r8/trunk/closure/goog/docs/class_goog_ui_Dialog.html) and cannot find the method to do so.
The method is there! See http://closure-library.googlecode.com/svn/docs/class_goog_ui_Dialog.html
dialog.setHasTitleCloseButton(false);
Regards,
Rene
The goog.ui.Dialog title-bar close button can be disabled by first calling goog.ui.Dialog.prototype.getTitleCloseElement() followed by goog.style.showElement(el, display).
Example
var dialog = new goog.ui.Dialog();
dialog.setContent('Lorem ipsum dolor sit amet, consectetuer' +
'adipiscing elit. Aenean sollicitudin ultrices urna. Proin vehicula ' +
'mauris ac est. Ut scelerisque, risus ut facilisis dictum, est massa ' +
'lacinia lorem, in fermentum purus ligula quis nunc. Duis porttitor ' +
'euismod risus. Nam hendrerit lacus vehicula augue. Duis ante.');
dialog.setTitle('Lorem ipsum');
dialog.setButtonSet(goog.ui.Dialog.ButtonSet.createYesNo());
var titleCloseEl = dialog.getTitleCloseElement();
goog.style.showElement(titleCloseEl, false);