问:
Strange character since last update (>4;2m) in vim
I've recently update vim on ubuntu, and since then, a strange character keep appearing at random time at my cursor place. It seems to appear when I do nothing for some seconds. The character is >4;2m and I can't understand the logic of its appearance. Has anyone the same problem ? Switching buffer and coming back to the initial one clean the character.

vim --version :

```<code>VIM - Vi IMproved 8.2 (2019 Dec 12, compilé May 21 2020 15:41:59)
Rustines incluses : 1-803
Modifié par jonathon.fernyhough@york.ac.uk
Compilé par jonathon.fernyhough@york.ac.uk
Énorme version avec interface graphique GTK3.
  Fonctionnalités incluses (+) ou non (-) :
+acl               -farsi             +mouse_sgr         +tag_binary
+arabic            +file_in_path      -mouse_sysmouse    -tag_old_static
+autocmd           +find_in_path      +mouse_urxvt       -tag_any_white
+autochdir         +float             +mouse_xterm       +tcl
-autoservername    +folding           +multi_byte        +termguicolors
+balloon_eval      -footer            +multi_lang        +terminal
+balloon_eval_term +fork()            -mzscheme          +terminfo
+browse            +gettext           +netbeans_intg     +termresponse
++builtin_terms    -hangul_input      +num64             +textobjects
+byte_offset       +iconv             +packages          +textprop
+channel           +insert_expand     +path_extra        +timers
+cindent           +ipv6              +perl              +title
+clientserver      +job               +persistent_undo   +toolbar
+clipboard         +jumplist          +popupwin          +user_commands
+cmdline_compl     +keymap            +postscript        +vartabs
+cmdline_hist      +lambda            +printer           +vertsplit
+cmdline_info      +langmap           +profile           +virtualedit
+comments          +libcall           -python            +visual
+conceal           +linebreak         +python3           +visualextra
+cryptv            +lispindent        +quickfix          +viminfo
+cscope            +listcmds          +reltime           +vreplace
+cursorbind        +localmap          +rightleft         +wildignore
+cursorshape       +lua               +ruby              +wildmenu
+dialog_con_gui    +menu              +scrollbind        +windows
+diff              +mksession         +signs             +writebackup
+digraphs          +modify_fname      +smartindent       +X11
+dnd               +mouse             +sound             -xfontset
-ebcdic            +mouseshape        +spell             +xim
+emacs_tags        +mouse_dec         +startuptime       +xpm
+eval              +mouse_gpm         +statusline        +xsmp_interact
+ex_extra          -mouse_jsbterm     -sun_workshop      +xterm_clipboard
+extra_search      +mouse_netterm     +syntax            -xterm_save
         fichier vimrc système : "$VIM/vimrc"
     fichier vimrc utilisateur : "$HOME/.vimrc"
 2me fichier vimrc utilisateur : "~/.vim/vimrc"
      fichier exrc utilisateur : "$HOME/.exrc"
        fichier gvimrc système : "$VIM/gvimrc"
    fichier gvimrc utilisateur : "$HOME/.gvimrc"
2me fichier gvimrc utilisateur : "~/.vim/gvimrc"
 fichier de valeurs par défaut : "$VIMRUNTIME/defaults.vim"
          fichier menu système : "$VIMRUNTIME/menu.vim"
               $VIM par défaut : "/usr/share/vim"
Compilation : gcc -c -I. -Iproto -DHAVE_CONFIG_H -DFEAT_GUI_GTK  -pthread -I/usr/include/gtk-3.0 -I/usr/include/at-spi2-atk/2.0 -I/usr/include/at-spi-2.0 -I/usr/include/dbus-1.0 -I/usr/lib/x86_64-linux-gnu/dbus-1.0/include -I/usr/include/gtk-3.0 -I/usr/include/gio-unix-2.0/ -I/usr/include/cairo -I/usr/include/pango-1.0 -I/usr/include/harfbuzz -I/usr/include/pango-1.0 -I/usr/include/atk-1.0 -I/usr/include/cairo -I/usr/include/pixman-1 -I/usr/include/freetype2 -I/usr/include/libpng16 -I/usr/include/freetype2 -I/usr/include/libpng16 -I/usr/include/gdk-pixbuf-2.0 -I/usr/include/libpng16 -I/usr/include/glib-2.0 -I/usr/lib/x86_64-linux-gnu/glib-2.0/include -Wdate-time  -g -O2 -fdebug-prefix-map=/build/vim-azHx0p/vim-8.2.0803=. -fstack-protector-strong -Wformat -Werror=format-security -D_REENTRANT -U_FORTIFY_SOURCE -D_FORTIFY_SOURCE=1
Édition de liens : gcc   -L. -Wl,-Bsymbolic-functions -Wl,-z,relro -Wl,-z,now -fstack-protector -rdynamic -Wl,-export-dynamic -Wl,-E  -Wl,-Bsymbolic-functions -Wl,-z,relro -Wl,-z,now -Wl,--as-needed -o vim   -lgtk-3 -lgdk-3 -lpangocairo-1.0 -lpango-1.0 -latk-1.0 -lcairo-gobject -lcairo -lgdk_pixbuf-2.0 -lgio-2.0 -lgobject-2.0 -lglib-2.0 -lSM -lICE -lXpm -lXt -lX11 -lXdmcp -lSM -lICE  -lm -ltinfo  -lselinux  -lcanberra -lacl -lattr -lgpm -ldl  -L/usr/lib -llua5.2 -Wl,-E  -fstack-protector-strong -L/usr/local/lib  -L/usr/lib/x86_64-linux-gnu/perl/5.26/CORE -lperl -ldl -lm -lpthread -lcrypt  -L/usr/lib/python3.6/config-3.6m-x86_64-linux-gnu -lpython3.6m -lpthread -ldl -lutil -lm -L/usr/lib/x86_64-linux-gnu -ltcl8.6 -ldl -lz -lpthread -lm -lruby-2.5 -lpthread -lgmp -ldl -lcrypt -lm
</code>```

答:
It was a problem of modifyOtherKeys. After looking at the doc, putting

```<code>let &t_TI = ""
let &t_TE = ""
</code>```

in my vimrc solved the problem.

Body:
I've recently update vim on ubuntu, and since then, a strange character keep appearing at random time at my cursor place. It seems to appear when I do nothing for some seconds. The character is >4;2m and I can't understand the logic of its appearance. Has anyone the same problem ? Switching buffer and coming back to the initial one clean the character.

vim --version :

VIM - Vi IMproved 8.2 (2019 Dec 12, compilé May 21 2020 15:41:59)
Rustines incluses : 1-803
Modifié par jonathon.fernyhough@york.ac.uk
Compilé par jonathon.fernyhough@york.ac.uk
Énorme version avec interface graphique GTK3.
  Fonctionnalités incluses (+) ou non (-) :
+acl               -farsi             +mouse_sgr         +tag_binary
+arabic            +file_in_path      -mouse_sysmouse    -tag_old_static
+autocmd           +find_in_path      +mouse_urxvt       -tag_any_white
+autochdir         +float             +mouse_xterm       +tcl
-autoservername    +folding           +multi_byte        +termguicolors
+balloon_eval      -footer            +multi_lang        +terminal
+balloon_eval_term +fork()            -mzscheme          +terminfo
+browse            +gettext           +netbeans_intg     +termresponse
++builtin_terms    -hangul_input      +num64             +textobjects
+byte_offset       +iconv             +packages          +textprop
+channel           +insert_expand     +path_extra        +timers
+cindent           +ipv6              +perl              +title
+clientserver      +job               +persistent_undo   +toolbar
+clipboard         +jumplist          +popupwin          +user_commands
+cmdline_compl     +keymap            +postscript        +vartabs
+cmdline_hist      +lambda            +printer           +vertsplit
+cmdline_info      +langmap           +profile           +virtualedit
+comments          +libcall           -python            +visual
+conceal           +linebreak         +python3           +visualextra
+cryptv            +lispindent        +quickfix          +viminfo
+cscope            +listcmds          +reltime           +vreplace
+cursorbind        +localmap          +rightleft         +wildignore
+cursorshape       +lua               +ruby              +wildmenu
+dialog_con_gui    +menu              +scrollbind        +windows
+diff              +mksession         +signs             +writebackup
+digraphs          +modify_fname      +smartindent       +X11
+dnd               +mouse             +sound             -xfontset
-ebcdic            +mouseshape        +spell             +xim
+emacs_tags        +mouse_dec         +startuptime       +xpm
+eval              +mouse_gpm         +statusline        +xsmp_interact
+ex_extra          -mouse_jsbterm     -sun_workshop      +xterm_clipboard
+extra_search      +mouse_netterm     +syntax            -xterm_save
         fichier vimrc système : "$VIM/vimrc"
     fichier vimrc utilisateur : "$HOME/.vimrc"
 2me fichier vimrc utilisateur : "~/.vim/vimrc"
      fichier exrc utilisateur : "$HOME/.exrc"
        fichier gvimrc système : "$VIM/gvimrc"
    fichier gvimrc utilisateur : "$HOME/.gvimrc"
2me fichier gvimrc utilisateur : "~/.vim/gvimrc"
 fichier de valeurs par défaut : "$VIMRUNTIME/defaults.vim"
          fichier menu système : "$VIMRUNTIME/menu.vim"
               $VIM par défaut : "/usr/share/vim"
Compilation : gcc -c -I. -Iproto -DHAVE_CONFIG_H -DFEAT_GUI_GTK  -pthread -I/usr/include/gtk-3.0 -I/usr/include/at-spi2-atk/2.0 -I/usr/include/at-spi-2.0 -I/usr/include/dbus-1.0 -I/usr/lib/x86_64-linux-gnu/dbus-1.0/include -I/usr/include/gtk-3.0 -I/usr/include/gio-unix-2.0/ -I/usr/include/cairo -I/usr/include/pango-1.0 -I/usr/include/harfbuzz -I/usr/include/pango-1.0 -I/usr/include/atk-1.0 -I/usr/include/cairo -I/usr/include/pixman-1 -I/usr/include/freetype2 -I/usr/include/libpng16 -I/usr/include/freetype2 -I/usr/include/libpng16 -I/usr/include/gdk-pixbuf-2.0 -I/usr/include/libpng16 -I/usr/include/glib-2.0 -I/usr/lib/x86_64-linux-gnu/glib-2.0/include -Wdate-time  -g -O2 -fdebug-prefix-map=/build/vim-azHx0p/vim-8.2.0803=. -fstack-protector-strong -Wformat -Werror=format-security -D_REENTRANT -U_FORTIFY_SOURCE -D_FORTIFY_SOURCE=1
Édition de liens : gcc   -L. -Wl,-Bsymbolic-functions -Wl,-z,relro -Wl,-z,now -fstack-protector -rdynamic -Wl,-export-dynamic -Wl,-E  -Wl,-Bsymbolic-functions -Wl,-z,relro -Wl,-z,now -Wl,--as-needed -o vim   -lgtk-3 -lgdk-3 -lpangocairo-1.0 -lpango-1.0 -latk-1.0 -lcairo-gobject -lcairo -lgdk_pixbuf-2.0 -lgio-2.0 -lgobject-2.0 -lglib-2.0 -lSM -lICE -lXpm -lXt -lX11 -lXdmcp -lSM -lICE  -lm -ltinfo  -lselinux  -lcanberra -lacl -lattr -lgpm -ldl  -L/usr/lib -llua5.2 -Wl,-E  -fstack-protector-strong -L/usr/local/lib  -L/usr/lib/x86_64-linux-gnu/perl/5.26/CORE -lperl -ldl -lm -lpthread -lcrypt  -L/usr/lib/python3.6/config-3.6m-x86_64-linux-gnu -lpython3.6m -lpthread -ldl -lutil -lm -L/usr/lib/x86_64-linux-gnu -ltcl8.6 -ldl -lz -lpthread -lm -lruby-2.5 -lpthread -lgmp -ldl -lcrypt -lm

Body:
It was a problem of modifyOtherKeys. After looking at the doc, putting

let &t_TI = ""
let &t_TE = ""

in my vimrc solved the problem.


来源: stackexchange

问:
illegal 0000-00-00 00:00:00 timestamp being sent by php to mysql using codeigniter
here is a Database_update_entry function in my CodeIgniter model which gets executed upon successful form submission.

```<code><?php
    function update_entry(){
        $data = array(
            'sl' => $this->input->post('item_sl'),
            'item_name' => $this->input->post('item_name'),
            'img_url' => $this->input->post('img_url'),
            'sound_url' => $this->input->post('sound_url'),
            'price' => $this->input->post('price'),
            'unit' => $this->input->post('unit'),
            'timestamp' => time(),
        );
        echo "current time: ".  time();
        $this->db->update(MY_TABLE_NAME, $data);
    }
?>
</code>```

the database query gets executed fine.... but the time that gets set into the mysql table is
0000-00-00 00:00:00 whereas the <?php echo time() ?> statement shows 1307018223 in the browser.... which is a valid UNIX timestamp... you can check the timestamp validity here.

here is a screenshot of the table that takes data from mySQL table after successful update_queryhttp://s3.amazonaws.com/awesome_screenshot/658523?AWSAccessKeyId=0R7FMW7AXRVCYMAPTPR2&Expires=1307020816&Signature=AncPjnzG9p9QTX7zebZp7c9teB0%3D

what am i doing wrong??? how can i pass a legal timestamp from my php to mySQL?
[p.s. i have checked that the timestamp field in my mysql table is a timestamp field]

答:
Use date('Y-m-d H:i:s', time());

;)

ContentLicense: CC BY-SA 3.0

Body:
here is a Database_update_entry function in my CodeIgniter model which gets executed upon successful form submission.

<?php
    function update_entry(){
        $data = array(
            'sl' => $this->input->post('item_sl'),
            'item_name' => $this->input->post('item_name'),
            'img_url' => $this->input->post('img_url'),
            'sound_url' => $this->input->post('sound_url'),
            'price' => $this->input->post('price'),
            'unit' => $this->input->post('unit'),
            'timestamp' => time(),
        );
        echo "current time: ".  time();
        $this->db->update(MY_TABLE_NAME, $data);
    }
?>

the database query gets executed fine.... but the time that gets set into the mysql table is
0000-00-00 00:00:00 whereas the <?php echo time() ?> statement shows 1307018223 in the browser.... which is a valid UNIX timestamp... you can check the timestamp validity here.

here is a screenshot of the table that takes data from mySQL table after successful update_queryhttp://s3.amazonaws.com/awesome_screenshot/658523?AWSAccessKeyId=0R7FMW7AXRVCYMAPTPR2&Expires=1307020816&Signature=AncPjnzG9p9QTX7zebZp7c9teB0%3D

what am i doing wrong??? how can i pass a legal timestamp from my php to mySQL?
[p.s. i have checked that the timestamp field in my mysql table is a timestamp field]

Body:
Use date('Y-m-d H:i:s', time());

;)


问:
how to get max time from a report
i want to filter my report and only show that row which has maximum time
 first i use

enddate = fr.First().EndDate

but it given me first value occured not the maximum time
i try to use

endDate = fr.Max().EndDate

but failed.

答:
I want to filter my report and only show that row which has maximum time.

So your report is a sequence of Rows, where every Row has a property EndTime. And you want the one and only Row that has the largest value for EndTime.

```<code>class Row
{
    public DateTime EndTime {get; set;}
    ... // other properties
}

IEnumerable<Row> report = ...
</code>```

Are you sure there is only one Row with the largest EndTime? There are no double EndTimes?

If you are sure, or if you don't care which Row you get, as long as it has the largest value for EndTime, you can sort it in descending EndTime order, then select the properties you want, and finally take the FirstOrDefault:

```<code>var rowWithLargestEndTime = report.OrderByDescending(row => row.EndTime)

    // Select the row properties you want in your end result:
    .Select(row => new
    {
        ...
    })
    .FirstOrDefault();
</code>```

If you want the complete Row in your end result, you don't have to do the Select. If you only want the end time:

```<code>.Select(row => row.EndTime).FirstOrDefault();
</code>```

This solution is the best, if a database management system has to do this for you. DBMS are optimized for sorting. However, if your local process has to do this, then it would be a waste to sort all elements if you will be using only the first one. In that case, consider using one of the overloads of Enumerable.Aggregate

The simplest overload, defines the first row as the one with the largest EndTime. Compare the row with the largest EndTime with every other Row, and keep the one which has the largest EndTime.

If your Report has no Rows at all, you have to decide what you want as result.

```<code>Row rowWithLargestEndTime = report.Aggregate(
    // parameter accumulator function:
    // compare the largest found EndTime with the next EndTime
    // keep the one with the largest EndTime
    (rowWithLargestEndTime, nextRow) => (rowWithLargesEndTime.EndTime < nextRow.EndTime) ?
     nextRow :
     rowWithLargestEndTime);
</code>```

The nice thing is that Aggregate will have to enumerate your sequence only once. OrderBy will enumerate many times.

ContentLicense: CC BY-SA 4.0

Title: how to get max time from a report

Body:
I want to filter my report and only show that row which has maximum time.

So your report is a sequence of Rows, where every Row has a property EndTime. And you want the one and only Row that has the largest value for EndTime.

class Row
{
    public DateTime EndTime {get; set;}
    ... // other properties
}

IEnumerable<Row> report = ...

Are you sure there is only one Row with the largest EndTime? There are no double EndTimes?

If you are sure, or if you don't care which Row you get, as long as it has the largest value for EndTime, you can sort it in descending EndTime order, then select the properties you want, and finally take the FirstOrDefault:

var rowWithLargestEndTime = report.OrderByDescending(row => row.EndTime)

    // Select the row properties you want in your end result:
    .Select(row => new
    {
        ...
    })
    .FirstOrDefault();

If you want the complete Row in your end result, you don't have to do the Select. If you only want the end time:

.Select(row => row.EndTime).FirstOrDefault();

This solution is the best, if a database management system has to do this for you. DBMS are optimized for sorting. However, if your local process has to do this, then it would be a waste to sort all elements if you will be using only the first one. In that case, consider using one of the overloads of Enumerable.Aggregate

The simplest overload, defines the first row as the one with the largest EndTime. Compare the row with the largest EndTime with every other Row, and keep the one which has the largest EndTime.

If your Report has no Rows at all, you have to decide what you want as result.

Row rowWithLargestEndTime = report.Aggregate(
    // parameter accumulator function:
    // compare the largest found EndTime with the next EndTime
    // keep the one with the largest EndTime
    (rowWithLargestEndTime, nextRow) => (rowWithLargesEndTime.EndTime < nextRow.EndTime) ?
     nextRow :
     rowWithLargestEndTime);

The nice thing is that Aggregate will have to enumerate your sequence only once. OrderBy will enumerate many times.


问:
Convert space separated string of coordinates into JavaScript object array
This space separated string:

```<code>const polygon = "42.44492,75.637764 42.445503,75.64534 42.433681,75.6604"
</code>```

..should be converted to array consisting objects:

```<code>const polygon = [
    { lat: 42.44492, lng: 75.637764 },
    { lat: 42.445503, lng: 75.64534 },
    { lat: 42.433681, lng: 75.6604 }
]
</code>```

What is the most simplest (beautiful) way to achieve this with JavaScript? Is there a nice one liner for this? The initial string can consist any amount coordinate pairs.

答:
You can use split to get every row and then map every row to split by comma:

const polygon = "42.44492,75.637764 42.445503,75.64534 42.433681,75.6604";
const formated = polygon.split(' ').map((item) => {
  const [ lat, lng ] = item.split(',');
  return { lat, lng };
});
console.log(formated);```
</div>
</div>
</p>

<p>If you wish to parse the values you should use let instead:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const polygon = "42.44492,75.637764 42.445503,75.64534 42.433681,75.6604";
const formated = polygon.split(' ').map((item) => {
  let [ lat, lng ] = item.split(',');
  lat = parseFloat(lat); // or any other transformation you wish to make
  lng = parseFloat(lng);
  return { lat, lng };
});
console.log(formated);</code>```

Body:
This space separated string:

const polygon = "42.44492,75.637764 42.445503,75.64534 42.433681,75.6604"

..should be converted to array consisting objects:

const polygon = [
    { lat: 42.44492, lng: 75.637764 },
    { lat: 42.445503, lng: 75.64534 },
    { lat: 42.433681, lng: 75.6604 }
]

What is the most simplest (beautiful) way to achieve this with JavaScript? Is there a nice one liner for this? The initial string can consist any amount coordinate pairs.

Body:
You can use split to get every row and then map every row to split by comma:

const polygon = "42.44492,75.637764 42.445503,75.64534 42.433681,75.6604";
const formated = polygon.split(' ').map((item) => {
  const [ lat, lng ] = item.split(',');
  return { lat, lng };
});
console.log(formated);

If you wish to parse the values you should use let instead:

const polygon = "42.44492,75.637764 42.445503,75.64534 42.433681,75.6604";
const formated = polygon.split(' ').map((item) => {
  let [ lat, lng ] = item.split(',');
  lat = parseFloat(lat); // or any other transformation you wish to make
  lng = parseFloat(lng);
  return { lat, lng };
});
console.log(formated);


问:
Django - (Restrict content from blocked users) Cannot unpack non-iterable ManyRelatedManager object
Hey guys I want the view to not show contents of blocked users, but I am getting an error like this:
How can I restrict the content from not showing in the template? Please have a look at the views.

```<code>TypeError at /videos/all_videos/
cannot unpack non-iterable ManyRelatedManager object
Request Method: GET
Request URL:    http://127.0.0.1:8000/videos/all_videos/
Django Version: 3.0.5
Exception Type: TypeError
Exception Value:
cannot unpack non-iterable ManyRelatedManager object
</code>```

views

```<code>class AllVideoView(ListView, LoginRequiredMixin):
    model = VideoPost
    template_name = 'videos/users/all_video_view.html'
    paginate_by = 20

    def get_context_data(self, **kwargs):
        context = super(AllVideoView, self).get_context_data(**kwargs)
        current_user = self.request.user
        video_list = VideoPost.objects.exclude(current_user.profile.blocked).order_by('-post_date')
        paginator = Paginator(video_list, self.paginate_by)
        page = self.request.GET.get('page')
        try:
            videos = paginator.page(page)
        except PageNotAnInteger:
            videos = paginator.page(1)
        except EmptyPage:
            videos = paginator.page(paginator.num_pages)
        context = {
             'page':page,
             'videos':videos,
             }
        return context
</code>```

I understood one thing that I called the video_list wrong. can anyone tell me how to properly do that?

Thanks

答:
I just solved the problem.

```<code>    blocked_ids = self.request.user.profile.blocked.values_list('id',flat=True)
    video_list = VideoPost.objects.exclude(user_id__in=blocked_ids).order_by('-post_date')
</code>```

changed the video_list like this to restrict the blocked content.

Body:
Hey guys I want the view to not show contents of blocked users, but I am getting an error like this:
How can I restrict the content from not showing in the template? Please have a look at the views.

TypeError at /videos/all_videos/
cannot unpack non-iterable ManyRelatedManager object
Request Method: GET
Request URL:    http://127.0.0.1:8000/videos/all_videos/
Django Version: 3.0.5
Exception Type: TypeError
Exception Value:
cannot unpack non-iterable ManyRelatedManager object

views

class AllVideoView(ListView, LoginRequiredMixin):
    model = VideoPost
    template_name = 'videos/users/all_video_view.html'
    paginate_by = 20

    def get_context_data(self, **kwargs):
        context = super(AllVideoView, self).get_context_data(**kwargs)
        current_user = self.request.user
        video_list = VideoPost.objects.exclude(current_user.profile.blocked).order_by('-post_date')
        paginator = Paginator(video_list, self.paginate_by)
        page = self.request.GET.get('page')
        try:
            videos = paginator.page(page)
        except PageNotAnInteger:
            videos = paginator.page(1)
        except EmptyPage:
            videos = paginator.page(paginator.num_pages)
        context = {
             'page':page,
             'videos':videos,
             }
        return context

I understood one thing that I called the video_list wrong. can anyone tell me how to properly do that?

Thanks

Body:
I just solved the problem.

    blocked_ids = self.request.user.profile.blocked.values_list('id',flat=True)
    video_list = VideoPost.objects.exclude(user_id__in=blocked_ids).order_by('-post_date')

changed the video_list like this to restrict the blocked content.


问:
SpringBoot with MariaDB: The driver has not received any packets from the server
I have a MariaDB, when connecting with sequel Pro I use this credentials and I can connect

with SpringBoot I use

```<code>spring.datasource.url=jdbc:mysql://172.105.50.55:3306/pradera_db
spring.datasource.username=pradera_usr
spring.datasource.password=Mddejh847h$#@
</code>```

but I have this error:

```<code>Caused by: java.net.ConnectException: Connection refused (Connection refused)
    at java.base/java.net.PlainSocketImpl.socketConnect(Native Method)
    at java.base/java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:400)
    at java.base/java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:243)
    at java.base/java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:225)
    at java.base/java.net.SocksSocketImpl.connect(SocksSocketImpl.java:402)
    at java.base/java.net.Socket.connect(Socket.java:591)
    at com.mysql.cj.protocol.StandardSocketFactory.connect(StandardSocketFactory.java:155)
    at com.mysql.cj.protocol.a.NativeSocketConnection.connect(NativeSocketConnection.java:65)
    ... 81 common frames omitted
2020-05-31 12:30  [restartedMain] INFO  com.zaxxer.hikari.HikariDataSource - HikariPool-1 - Starting...
2020-05-31 12:30  [restartedMain] ERROR com.zaxxer.hikari.pool.HikariPool - HikariPool-1 - Exception during pool initialization.
com.mysql.cj.jdbc.exceptions.CommunicationsException: Communications link failure

The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
</code>```

this is the dependency in the pom.xml:

```<code><dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
</code>```

答:
On the machine that's running your database add your ip as an allowed connection on the port 3306

Linux:

```<code>iptables -I INPUT -p tcp -s your.ip.address.here --dport 3306 -j ACCEPT
</code>```

Windows:
Open the start menu, write in the search bar: Windows firewall, open advanced settings on the left, select inbound rules, press new rule button on the right, Select port and press next, select tcp and specify the port 3306, press next, Allow the connection and after that just finish by selecting Domain, private, public and choosing a name for the rule itself.

Check if the service is running and enable/start it.

Linux:

```<code>sudo systemctl status mariadb
sudo systemctl enable mariadb
sudo systemctl start mariadb
</code>```

Windows: Open the start menu, search for Services.msc, inside the services tab find your mariadb service and modify it's status by right clicking it.

Hope it helps.

Body:
I have a MariaDB, when connecting with sequel Pro I use this credentials and I can connect

with SpringBoot I use

spring.datasource.url=jdbc:mysql://172.105.50.55:3306/pradera_db
spring.datasource.username=pradera_usr
spring.datasource.password=Mddejh847h$#@

but I have this error:

Caused by: java.net.ConnectException: Connection refused (Connection refused)
    at java.base/java.net.PlainSocketImpl.socketConnect(Native Method)
    at java.base/java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:400)
    at java.base/java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:243)
    at java.base/java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:225)
    at java.base/java.net.SocksSocketImpl.connect(SocksSocketImpl.java:402)
    at java.base/java.net.Socket.connect(Socket.java:591)
    at com.mysql.cj.protocol.StandardSocketFactory.connect(StandardSocketFactory.java:155)
    at com.mysql.cj.protocol.a.NativeSocketConnection.connect(NativeSocketConnection.java:65)
    ... 81 common frames omitted
2020-05-31 12:30  [restartedMain] INFO  com.zaxxer.hikari.HikariDataSource - HikariPool-1 - Starting...
2020-05-31 12:30  [restartedMain] ERROR com.zaxxer.hikari.pool.HikariPool - HikariPool-1 - Exception during pool initialization.
com.mysql.cj.jdbc.exceptions.CommunicationsException: Communications link failure

The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.

this is the dependency in the pom.xml:

<dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>

Body:
On the machine that's running your database add your ip as an allowed connection on the port 3306

Linux:

iptables -I INPUT -p tcp -s your.ip.address.here --dport 3306 -j ACCEPT

Windows:
Open the start menu, write in the search bar: Windows firewall, open advanced settings on the left, select inbound rules, press new rule button on the right, Select port and press next, select tcp and specify the port 3306, press next, Allow the connection and after that just finish by selecting Domain, private, public and choosing a name for the rule itself.

Check if the service is running and enable/start it.

Linux:

sudo systemctl status mariadb
sudo systemctl enable mariadb
sudo systemctl start mariadb

Windows: Open the start menu, search for Services.msc, inside the services tab find your mariadb service and modify it's status by right clicking it.

Hope it helps.


答:
In one transaction first UPDATE the values then do the INSERT.

```<code>UPDATE branchservices
       SET sortvalue = sortvalue + 1
       WHERE sortvalue >= 1;

INSERT INTO branchservices
            (fkbranchid,
             fkserviceid,
             sortvalue)
            VALUES (1,
                    106,
                    1);
</code>```

Title: How to increment row values by 1 when inserting

Body:
I have a table called LocationProduct and its structure is as follows,

+--------------+-------------+-----------+
| FkLocationId | FkProductId | SortValue |
+--------------+-------------+-----------+
| 1            | 100         | 1         |
+--------------+-------------+-----------+
| 1            | 101         | 2         |
+--------------+-------------+-----------+
| 1            | 102         | 3         |
+--------------+-------------+-----------+
| 1            | 103         | 4         |
+--------------+-------------+-----------+
| 1            | 104         | 5         |
+--------------+-------------+-----------+
| 1            | 105         | 6         |
+--------------+-------------+-----------+
| 2            | 100         | 1         |
+--------------+-------------+-----------+
| 2            | 101         | 2         |
+--------------+-------------+-----------+
| 2            | 102         | 3         |
+--------------+-------------+-----------+
| 2            | 103         | 4         |
+--------------+-------------+-----------+
| 2            | 104         | 5         |
+--------------+-------------+-----------+
| 2            | 105         | 6         |
+--------------+-------------+-----------+

Now I need to increment SortValue column's value by one when I insert a new row. As an example,

INSERT INTO BranchServices(FkBranchId,FkServiceId,SortValue)
VALUES(1,106,1)

I need to update FkLocationId = 1 related SortValue by one, I need the following output,

+--------------+-------------+-----------+
| FkLocationId | FkProductId | SortValue |
+--------------+-------------+-----------+
| 1            | 100         | 2         |
+--------------+-------------+-----------+
| 1            | 101         | 3         |
+--------------+-------------+-----------+
| 1            | 102         | 4         |
+--------------+-------------+-----------+
| 1            | 103         | 5         |
+--------------+-------------+-----------+
| 1            | 104         | 6         |
+--------------+-------------+-----------+
| 1            | 105         | 7         |
+--------------+-------------+-----------+
| 1            | 106         | 1         |
+--------------+-------------+-----------+

Here you can see I updated each old records SortValue by one. How can I do this?

Body:
In one transaction first UPDATE the values then do the INSERT.

UPDATE branchservices
       SET sortvalue = sortvalue + 1
       WHERE sortvalue >= 1;

INSERT INTO branchservices
            (fkbranchid,
             fkserviceid,
             sortvalue)
            VALUES (1,
                    106,
                    1);


问:
ORM for CodeIgniter 2.0
What are some recommended ORM's for CodeIgniter? I have heard of Data Mapper and Propel. What are some that people have used and would recommend?</p>

答:
CI comes bundled with an Active Record class -- which is confusing because the Active Record pattern is technically an ORM, however the class is not -- it is merely a query builder.  With that said, for basic websites I'd highly suggest using it.

Which ORM to actually use with CI is more a matter of personal preference though, DataMapper is more of a basic ORM and was actually written specifically for CI, but it won't give you all of the functionality found in something like Doctrine which I tend to think is one of the most full featured ORM's for PHP.

Overall you'll likely want to try out a few and find out which one suits your needs the best, there is a lot of information about ORM's for PHP on the PHP Info page right here on StackOverflow.

Title: ORM for CodeIgniter 2.0


问:
is an API project as a lambda a good idea?
So we are deciding on an architecture for a rewrite of an existing API microservice.

The discussion came up to port it to AWS Lambda's but I have a bunch of questions concerning this approach.

Is it at all a good idea to have a full microservice as lambda functions?
These would be used by several different FE projects so the calls to those lambdas would be substantial.

So basically the question I'm posing is:
Is it a good idea to have a microservice with a bunch of API endpoints all created as lambdas when used often or is it generally a better idea to, in this case, have a lightweight nodejs-express server running? And why?

Edit: it would also partially be react serverside rendering

答:
This is a primary opinion based question (as @freakish said), someone it's going to say yes others are going to say nope.

That being sad here's my 2 cents. I think the real question, that perhaps, you are asking yourself relies in this line:

These would be used by several different FE projects so the calls to
those lambdas would be substantial.

That means that you are calling the lambda, let's say, constantly. Thus you might be asking yourself: does it make sense to trade off a little bit of performance? (cold starts).

The first thing I'd to think about is pre-warming a set of functions, so you can avoid cold starts. Of course you should monitor your traffic to see if this is a constant or you have one, or multiple, peeks during the day.

Also ask yourself about concurrency, here's somewhere you can start from LINK.

AWS Lambda (as other FaaS) comes with this really interesting "things":

Don't have to manage servers anymore

Auto scaling built in

Security built in (less surface attack), but don't give it as guaranteed, you still have to think about it properly. But yeah the attackable surface is much smaller.

Pay for value

The last point, pay for value, is really interesting. For instance, let's say your audience is mainly based in US, that means that probably you are not going to have everything "up & running" during the night time, thus cutting expenses.

Some gotchas

Of course there are some paint point that you might not have thought about as you first enter this fancy world of serverless:

How are you going to handle versioning and ENVs? Try to understand it

How are you going to debug it?

What about CI/DI?

As you see this is really broad topic, and we can go and on talking about all the PROs and CONs. You have to do your own searches, and see what really fits better the needs of your architecture.

Talking about the SSR of your react app that's another topic but, personally, I'd not put in a lambda fn, as you are going to have larger packages and that affects cold starts. Perhaps I'd go for AWS EB, or put up an NGINX server with reverse proxy to server multiple apps (if you really need to tear down a FE monolith to micro frontends).

Good luck!


问:
How to limit the ::selection selector?
I want to limit ::selection to a li. I mean affect on li box that contain an a tag.

```<code><ul class="report-box">
    <li>
        <a class="password">our pass: www.mysite.com</a>
    </li>
</ul>
</code>```

I want clients when selecting the password with the mouse ::selection to become red. By default for whole the page, it’s blue.

```<code>::selection {
    background: #03a9f4;
    color: #fff;
}
li .report-box ::selection  {
    background: #03A9F4;
    color: #fff;
 }
</code>```

Sorry, I am new in CSS. Is there any way to do that?

答:
Don't give a space between attributes while defining selector

```<code>div .report-box::selection  {
    background: #03A9F4;
    color: #fff;
}
</code>```

with a space the selector will apply to all child elements of div and report-box class.

Also if the report-box class is meant to be on div you can just remove the space between div and report-box too like

```<code>div.report-box::selection  {
</code>```

demo

div.report-box::selection  {
    background: orange;
    color: #fff;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="report-box">Some test</div></code>```

Title: How to limit the ::selection selector?

Body:
I want to limit ::selection to a li. I mean affect on li box that contain an a tag.

        our pass: www.mysite.com

I want clients when selecting the password with the mouse ::selection to become red. By default for whole the page, it’s blue.

::selection {
    background: #03a9f4;
    color: #fff;
}
li .report-box ::selection  {
    background: #03A9F4;
    color: #fff;
 }

Sorry, I am new in CSS. Is there any way to do that?

Body:
Don't give a space between attributes while defining selector

div .report-box::selection  {
    background: #03A9F4;
    color: #fff;
}

with a space the selector will apply to all child elements of div and report-box class.

Also if the report-box class is meant to be on div you can just remove the space between div and report-box too like

div.report-box::selection  {

demo

div.report-box::selection  {
    background: orange;
    color: #fff;
}

<div class="report-box">Some test</div>


答:
mysql timestamp field accept yyyy-mm-dd H:i:s format of date so you have to pass date into this format not the UNIX timestamp

instead of this

```<code>'timestamp' => time()
</code>```

Use

```<code>'timestamp' => date('Y-m-d H:i:s')
</code>```

If you really want to store UNIX time stamp change the field type to CHAR

Title: illegal 0000-00-00 00:00:00 timestamp being sent by php to mysql using codeigniter

Body:
mysql timestamp field accept yyyy-mm-dd H:i:s format of date so you have to pass date into this format not the UNIX timestamp

instead of this

'timestamp' => time()

Use

'timestamp' => date('Y-m-d H:i:s')

If you really want to store UNIX time stamp change the field type to CHAR


问:
How to get selected radio button from ToggleGroup
I an working on JavaFX 8 and SceneBuilder. I created some radio buttons in the FXML File and specified a toggleGroup name to a radio button list in that. So, now I want to get the toggleGroup's selected radio button in my controller, do I need to make all the radio buttons again as fields in the controller, or just the toggleGroup object will get me the selected radio button (the text of that radio button only, not the button object).

答:
The solution I got is:

ToggleGroup toggleGroup = new ToggleGroup();

Then set toggleGroup to the radio button; let's say r1 and r2

```<code>r1.setToggleGroup(toggleGroup);

r2.setToggleGroup(toggleGroup);

toggleGroup.setUserData(toggleGroup.getSelectedToggle().toString());
</code>```

To print the data of RadioButton:

```<code>System.out.println("Selected Radio Button is " + toggleGroup.getUserData().toString());
</code>```

Body:
The solution I got is:

ToggleGroup toggleGroup = new ToggleGroup();

Then set toggleGroup to the radio button; let's say r1 and r2

r1.setToggleGroup(toggleGroup);

r2.setToggleGroup(toggleGroup);

toggleGroup.setUserData(toggleGroup.getSelectedToggle().toString());

To print the data of RadioButton:

System.out.println("Selected Radio Button is " + toggleGroup.getUserData().toString());


问:
Better way to expose functions in NodeJS?
I have a directory where I am keeping all of my DAO files which contains methods to interact with MySQL server.

My DAO directory looks like this

```<code>| -- dao
  | -- user.dao.ts
  | -- employee.dao.ts
</code>```

I have my controllers directory that looks like this

```<code>| -- controller
  | -- user.controller.ts
  | -- employee.controller.ts
</code>```

Each DAO file contains functions which may have same names like:

function insertOne() {}

function insertMany() {}
```

<p>I am utilising these DAO functions in my controller file, I am importing multiple DAO files in one controller file as I want to use multiple DAO functions in one controller</p>

<p>I have two ways to export the functions from DAO files:</p>

<p>First Approach:</p>

<pre class="lang-js prettyprint-override"><code>export function insertOne() {}

export function insertMany() {}
</code>```

Second Approach:

function insertOne() {}

function insertMany() {}

export default {
  insertOne,
  insertMany
};
```

<p>I know it is better to export individual functions, as we can import only the functions that we need in that file, but in my case, the function names would clash, so, what should be the best approach to deal with this ?</p>

<p>If I use first approach I would do something like this in my controller</p>

<pre class="lang-js prettyprint-override"><code>import * as userDAO from "../dao/user.dao.ts";
import * as empDAO from "../dao/emp.dao.ts";

// import { insertOne } from "../dao/user.dao.ts"; // can't do this as name would clash

userDAO.insertOne();
empDAO.insertOne();
</code>```

If I use second approach I would do something like this in my controller

import userDAO from "../dao/user.dao.ts";
import empDAO from "../dao/emp.dao.ts";

userDAO.insertOne();
empDAO.insertOne();
```

Am I doing anything wrong by keeping the same name methods in every DAO file? Looking for suggestions and similar approaches I can add to my code.

答:
Nothing wrong in second approach, i dont think you have thousands of files. So what is wrong if you will export a couple of functions which will not be used? People are importing lodash library, using 5 percents of it. I guess you pay too much attention to this.

But my suggestion is to create classes. Make one

```<code>class DAOModel {
  insertOne () {}
  insertMany () {}
}
</code>```

and in your files create classes inheriting DAOModel and pass an instance of this class, may be making all methods static

or creating just objects

```<code>const personsDAO = {
  insertOne() {...},
  insertMany() {...},
}

export default personsDAO
</code>```

then you will forget your headache

Body:
I have a directory where I am keeping all of my DAO files which contains methods to interact with MySQL server.

My DAO directory looks like this

| -- dao
  | -- user.dao.ts
  | -- employee.dao.ts

I have my controllers directory that looks like this

| -- controller
  | -- user.controller.ts
  | -- employee.controller.ts

Each DAO file contains functions which may have same names like:

function insertOne() {}

function insertMany() {}

I am utilising these DAO functions in my controller file, I am importing multiple DAO files in one controller file as I want to use multiple DAO functions in one controller

I have two ways to export the functions from DAO files:

First Approach:

export function insertOne() {}

export function insertMany() {}

Second Approach:

function insertOne() {}

function insertMany() {}

export default {
  insertOne,
  insertMany
};

I know it is better to export individual functions, as we can import only the functions that we need in that file, but in my case, the function names would clash, so, what should be the best approach to deal with this ?

If I use first approach I would do something like this in my controller

import * as userDAO from "../dao/user.dao.ts";
import * as empDAO from "../dao/emp.dao.ts";

// import { insertOne } from "../dao/user.dao.ts"; // can't do this as name would clash

userDAO.insertOne();
empDAO.insertOne();

If I use second approach I would do something like this in my controller

import userDAO from "../dao/user.dao.ts";
import empDAO from "../dao/emp.dao.ts";

userDAO.insertOne();
empDAO.insertOne();

Am I doing anything wrong by keeping the same name methods in every DAO file? Looking for suggestions and similar approaches I can add to my code.

Body:
Nothing wrong in second approach, i dont think you have thousands of files. So what is wrong if you will export a couple of functions which will not be used? People are importing lodash library, using 5 percents of it. I guess you pay too much attention to this.

But my suggestion is to create classes. Make one

class DAOModel {
  insertOne () {}
  insertMany () {}
}

and in your files create classes inheriting DAOModel and pass an instance of this class, may be making all methods static

or creating just objects

const personsDAO = {
  insertOne() {...},
  insertMany() {...},
}

export default personsDAO

then you will forget your headache


问:
starting container process caused "exec: \"/tmp/installer.sh\": permission denied"
I have a base image (named @release_docker//image) and I'm trying to install some apt packages on it (alongside my built binary). Here is what it looks like:

```<code>load("@io_bazel_rules_docker//docker/package_managers:download_pkgs.bzl", "download_pkgs")
load("@io_bazel_rules_docker//docker/package_managers:install_pkgs.bzl", "install_pkgs")

download_pkgs(
    name = "downloaded-packages",
    image_tar = "@release_docker//image",
    packages = [
        "numactl",
        "pciutils",
        "python",
    ],
)

install_pkgs(
    name = "installed-packages",
    image_tar = "@release_docker//image",
    installables_tar = ":downloaded-packages.tar",
    output_image_name = "release_docker_with_packages"
)

cc_image(
    name = "my-image",
    base = ":installed-packages",
    binary = ":built-binary",
)
</code>```

But inside the build docker (a docker image which the build command runs in), when I run bazel build :my-image --action_env DOCKER_HOST=tcp://192.168.1.2:2375, it errors:

```<code>+ DOCKER=/usr/bin/docker
+ [[ -z /usr/bin/docker ]]
+ TO_JSON_TOOL=bazel-out/host/bin/external/io_bazel_rules_docker/docker/util/to_json
+ source external/io_bazel_rules_docker/docker/util/image_util.sh
++ bazel-out/host/bin/external/io_bazel_rules_docker/contrib/extract_image_id bazel-out/k8-fastbuild/bin/external/release_docker/image/image.tar
+ image_id=b55375fc9c651e1eff0428490d01b4883de0fca62b5b18e8ede9f3d812b3fc10
+ /usr/bin/docker load -i bazel-out/k8-fastbuild/bin/external/release_docker/image/image.tar
+++ pwd
+++ pwd
++ /usr/bin/docker run -d -v /opt/bazel-root-directory/...[path-to].../downloaded-packages.tar:/tmp/bazel-out/k8-fastbuild/bin/marzban/downloaded-packages.tar -v /opt/bazel-root-directory/...[path-to].../installed-packages.install:/tmp/installer.sh --privileged b55375fc9c651e1eff0428490d01b4883de0fca62b5b18e8ede9f3d812b3fc10 /tmp/installer.sh
/usr/bin/docker: Error response from daemon: OCI runtime create failed: container_linux.go:345: starting container process caused "exec: \"/tmp/installer.sh\": permission denied": unknown.
+ cid=ce62e444aefe1f32a20575750a6ee1cc9c2f79d46f2f60187a8bc23f87b5aa25
</code>```

答:
I came across the same issue and it took some time for me to find the actual cause.

As you conjectured, there is a bug in your version of rules_docker repo. The actual problem is the assumption that a local folder can be directly mounted into the target image. Obviously, the assumption fails in the case of DIND (Docker-In-Docker).

Fortunately, this bug has been already fixed as part of install_pkgs uses named volumes to work with DIND. As the title suggests, the solution is to use a named volume instead of short -v src:dst.

So, the solution is to upgrade to v0.13.0 or newer.

 rules_docker$ git tag --contains 32f12766248bef88358fc1646a3e0a66efd0e502 | head -1
v0.13.0

```

Body:
I have a base image (named @release_docker//image) and I'm trying to install some apt packages on it (alongside my built binary). Here is what it looks like:

load("@io_bazel_rules_docker//docker/package_managers:download_pkgs.bzl", "download_pkgs")
load("@io_bazel_rules_docker//docker/package_managers:install_pkgs.bzl", "install_pkgs")

download_pkgs(
    name = "downloaded-packages",
    image_tar = "@release_docker//image",
    packages = [
        "numactl",
        "pciutils",
        "python",
    ],
)

install_pkgs(
    name = "installed-packages",
    image_tar = "@release_docker//image",
    installables_tar = ":downloaded-packages.tar",
    output_image_name = "release_docker_with_packages"
)

cc_image(
    name = "my-image",
    base = ":installed-packages",
    binary = ":built-binary",
)

But inside the build docker (a docker image which the build command runs in), when I run bazel build :my-image --action_env DOCKER_HOST=tcp://192.168.1.2:2375, it errors:

+ DOCKER=/usr/bin/docker
+ [[ -z /usr/bin/docker ]]
+ TO_JSON_TOOL=bazel-out/host/bin/external/io_bazel_rules_docker/docker/util/to_json
+ source external/io_bazel_rules_docker/docker/util/image_util.sh
++ bazel-out/host/bin/external/io_bazel_rules_docker/contrib/extract_image_id bazel-out/k8-fastbuild/bin/external/release_docker/image/image.tar
+ image_id=b55375fc9c651e1eff0428490d01b4883de0fca62b5b18e8ede9f3d812b3fc10
+ /usr/bin/docker load -i bazel-out/k8-fastbuild/bin/external/release_docker/image/image.tar
+++ pwd
+++ pwd
++ /usr/bin/docker run -d -v /opt/bazel-root-directory/...[path-to].../downloaded-packages.tar:/tmp/bazel-out/k8-fastbuild/bin/marzban/downloaded-packages.tar -v /opt/bazel-root-directory/...[path-to].../installed-packages.install:/tmp/installer.sh --privileged b55375fc9c651e1eff0428490d01b4883de0fca62b5b18e8ede9f3d812b3fc10 /tmp/installer.sh
/usr/bin/docker: Error response from daemon: OCI runtime create failed: container_linux.go:345: starting container process caused "exec: \"/tmp/installer.sh\": permission denied": unknown.
+ cid=ce62e444aefe1f32a20575750a6ee1cc9c2f79d46f2f60187a8bc23f87b5aa25


问:
Groovy script for modifying Jenkins nodes labels
All!!
Let's say I have Jenkins with few slave nodes (Slave1, Slave2 & Slave3).
Each slave have few labels associated with it, i.e Slave1 (test build python), Slave2 (develop update clean)...

I'm looking for groovy script that I can run from Jenkins Script Console to modify labels on given slaves at once by adding/removing "-offline" suffix for each label on each slave, i.e Slave1 will have (test-offline build-offline python-offline) & Slave2 (develop-offline update-offline clean-offline).

I need this functionality in order to prevent next job start running on these slaves (let's say I want to set them offline for maintenance, once all jobs finished on these nodes). And once I done with maintenance on these slaves, I need to run another groovy script which set back all labels as they was configured before, i.e Slave1 (test build python), Slave2 (develop update clean).

So far I've found old topic about similar issue. The bellow code can return all labels for chosen slave, but its adding "offline" as additional label and not as a suffix for each existing label:

```<code>hudson = hudson.model.Hudson.instance
hudson.slaves.findAll { it.nodeName.equals("slave1") }.each { slave ->
  print "Slave  $slave.nodeName : Labels: $slave.labelString"
  slave.labelString = slave.labelString + " " + "offline"
  println "   --> New labels: $slave.labelString"
}
hudson.save()
</code>```

So I have few questions:

How to use list of nodes (slave1,slave2, slave3...) and not single node slave1

How to add/remove"-offline" suffix to/from labels? It can be two different script for adding and removing labels suffix.

Any help & suggestions are much appreciated.

Regrads,
Igor.

答:
I think there is some issue in the script.

```<code>hudson = hudson.model.Hudson.instance
hudson.slaves.findAll { it.nodeName.equals("slave1") }.each { slave ->
    print "Slave  $slave.nodeName : Labels: $slave.labelString"
    labels = aSlave.getLabelString()
    labels = labels + "-offline"
    aSlave.setLabelString(labels)
    println "   --> New labels: $slave.labelString"
}
hudson.save()
</code>```

Here too the assumption is that there is only one lable. Then only this will work.

if there are multiple labels

```<code>labels = aSlave.getLabelString()
labelList = labels.split(' ') //This is a list
labelList[0] = labelList[0]+"-offline"
labels = labelList.join(' ')
</code>```

You will have to split the labelString by space and then work on them.

And to get all slaves you can create a loop as follows

```<code>for (aSlave in hudson.model.Hudson.instance.slaves) {
    if(aSlave.name == "")//here you can pass a list or a single node for which changes needs to be done
    println "${aSlave.name}"
}
</code>```

I would do something like this for multiple nodes

```<code>hudson = hudson.model.Hudson.instance
for (aSlave in hudson.slaves) {
   labels = aSlave.getLabelString()
   labelList = labels.split(' ') //This is a list
   i = 0
   for (individualLabel in labelList) {
       if(individualLabel == "python") {
            labelList[i] = labelList[i]+"-offline"
       }
       i++
   }
   labels = labelList.join(' ')
   aSlave.setLabelString(labels)
 }
 hudson.save()
</code>```

You can also add a condition on name of the slave if this has to be done for a particular slave.

let me know if this works

Body:
All!!
Let's say I have Jenkins with few slave nodes (Slave1, Slave2 & Slave3).
Each slave have few labels associated with it, i.e Slave1 (test build python), Slave2 (develop update clean)...

I'm looking for groovy script that I can run from Jenkins Script Console to modify labels on given slaves at once by adding/removing "-offline" suffix for each label on each slave, i.e Slave1 will have (test-offline build-offline python-offline) & Slave2 (develop-offline update-offline clean-offline).

I need this functionality in order to prevent next job start running on these slaves (let's say I want to set them offline for maintenance, once all jobs finished on these nodes). And once I done with maintenance on these slaves, I need to run another groovy script which set back all labels as they was configured before, i.e Slave1 (test build python), Slave2 (develop update clean).

So far I've found old topic about similar issue. The bellow code can return all labels for chosen slave, but its adding "offline" as additional label and not as a suffix for each existing label:

hudson = hudson.model.Hudson.instance
hudson.slaves.findAll { it.nodeName.equals("slave1") }.each { slave ->
  print "Slave  $slave.nodeName : Labels: $slave.labelString"
  slave.labelString = slave.labelString + " " + "offline"
  println "   --> New labels: $slave.labelString"
}
hudson.save()

So I have few questions:

How to use list of nodes (slave1,slave2, slave3...) and not single node slave1

How to add/remove"-offline" suffix to/from labels? It can be two different script for adding and removing labels suffix.

Any help & suggestions are much appreciated.

Regrads,
Igor.

Body:
I think there is some issue in the script.

hudson = hudson.model.Hudson.instance
hudson.slaves.findAll { it.nodeName.equals("slave1") }.each { slave ->
    print "Slave  $slave.nodeName : Labels: $slave.labelString"
    labels = aSlave.getLabelString()
    labels = labels + "-offline"
    aSlave.setLabelString(labels)
    println "   --> New labels: $slave.labelString"
}
hudson.save()

Here too the assumption is that there is only one lable. Then only this will work.

if there are multiple labels

labels = aSlave.getLabelString()
labelList = labels.split(' ') //This is a list
labelList[0] = labelList[0]+"-offline"
labels = labelList.join(' ')

You will have to split the labelString by space and then work on them.

And to get all slaves you can create a loop as follows

for (aSlave in hudson.model.Hudson.instance.slaves) {
    if(aSlave.name == "")//here you can pass a list or a single node for which changes needs to be done
    println "${aSlave.name}"
}

I would do something like this for multiple nodes

hudson = hudson.model.Hudson.instance
for (aSlave in hudson.slaves) {
   labels = aSlave.getLabelString()
   labelList = labels.split(' ') //This is a list
   i = 0
   for (individualLabel in labelList) {
       if(individualLabel == "python") {
            labelList[i] = labelList[i]+"-offline"
       }
       i++
   }
   labels = labelList.join(' ')
   aSlave.setLabelString(labels)
 }
 hudson.save()

You can also add a condition on name of the slave if this has to be done for a particular slave.

let me know if this works


问:
How to link files directly from Github (raw.github.com)
Are we allowed to link files directly from Github ?

<link rel="stylesheet" href="https://raw.github.com/username/project/master/style.css"/>

```

I know this is allowed on Google Code. This way I don't have to worry about updating a local file.

答:
Use jsdelivr.com

Copied directly from https://www.jsdelivr.com/?docs=gh:

load any GitHub release, commit, or branch

note: we recommend using npm for projects that support it

https://cdn.jsdelivr.net/gh/user/repo@version/file

load jQuery v3.2.1

https://cdn.jsdelivr.net/gh/jquery/jquery@3.2.1/dist/jquery.min.js

use a version range instead of a specific version

https://cdn.jsdelivr.net/gh/jquery/jquery@3.2/dist/jquery.min.js

https://cdn.jsdelivr.net/gh/jquery/jquery@3/dist/jquery.min.js

omit the version completely to get the latest one

you should NOT use this in production

https://cdn.jsdelivr.net/gh/jquery/jquery/dist/jquery.min.js

add ".min" to any JS/CSS file to get a minified version

if one doesn't exist, we'll generate it for you

https://cdn.jsdelivr.net/gh/jquery/jquery@3.2.1/src/core.min.js

add / at the end to get a directory listing

https://cdn.jsdelivr.net/gh/jquery/jquery/

Body:
Are we allowed to link files directly from Github ?

<link rel="stylesheet" href="https://raw.github.com/username/project/master/style.css"/>

I know this is allowed on Google Code. This way I don't have to worry about updating a local file.


问:
Where to get models for TransferLearning based on topics
Suppose you're searching for a pretrained model for e.g. human gender recognition, or age estimation (Transfer Learning).
So, you'd want a net that is trained on, ideally, human faces and not on stuff like the ImageNet dataset.

I know that there are two big starting points for the search:

Keras applications

TensorHub

Now, the best I've found is to use the search tool of the TensorHub website, like here.

That gives me some models trained on the CelebA-HQ dataset, which is something I was searching for.

But, it didn't give any results for e.g. the keywords "sport", "food" or "gun".

So, what is a good way to find pretrained models for a desired "topic"?

答:
It's hard to find a model for each topic at a single place.

The general strategy could be searching in GitHub with the relevant tags ["tensorflow", "sport"].

You can generally find many models on model-zoo websites: https://modelzoo.co/

This is also useful: https://github.com/tensorflow/models

If you need code (probably with pre-trained weights): paperswithcode.com is a good place to search.


问:
How to automate this process?
It involves rewriting .htm to .txt (output file)

then using a parser (stanford grammar parser) (output file)

for all the files in a directory.

MY QUESTION: I would like to get all the files in the directory, without doing it manually, and find a way to run the parser, without having to type it into the Terminal for each file.

Here is my code:

```<code>#!/usr/bin/perl
use strict;
use warnings;
use HTML::FormatText;
use HTML::TreeBuilder;

my $tree = HTML::TreeBuilder->new->parse_file("chpt15Intro.htm");

use HTML::FormatText;

my $formatter = HTML::FormatText->new(leftmargin => 0, rightmargin => 1000);
   #print $formatter->format($tree); is replaced by push
push (my @files, $formatter->format($tree));
foreach my $files (@files) {
    $files =~ s/^\s+//mg;
    open MYFILE, ">ch15Intro.txt";
    select MYFILE;
    print $files;
}
</code>```

In the Terminal, after getting the html file converted, I write:

```<code>script parsedch15Intro.txt ./lexparser.csh ch15Intro.txt
</code>```

to save the output of the parser. This step still needs automation.

I'm a beginner so thanks for any advice.

答:
UPDATE: Here is the answer to automating the parser: (similar to TLP and outis' solutions)

```<code>#!/usr/bin/perl
use strict;
use warnings;

for my $file (@ARGV) {
    next unless ($file =~ /^(.+).txt*$/i); ##file name ends in txt
    my $outfile = "parsed$1".".txt";
    qx/script -q \/Users\/jon\/Desktop\/stanford-postagger-full-2011-04-20\/$outfile \.\/lexparser.csh $file/;
}
##First in Terminal cd /Users/jon/Downloads/chpt1-8 or whichever directory this perl script and all texfiles and parser files are
##Called in Terminal by ==>  perl auto_parse.pl *.txt

##This saves the output to directory spedicifed. The output is the parsed files
##Required: stanford parser files in same directory as this script
</code>```

Title: How to automate this process?

Body:
It involves rewriting .htm to .txt (output file)

then using a parser (stanford grammar parser) (output file)

for all the files in a directory.

MY QUESTION: I would like to get all the files in the directory, without doing it manually, and find a way to run the parser, without having to type it into the Terminal for each file.

Here is my code:

#!/usr/bin/perl
use strict;
use warnings;
use HTML::FormatText;
use HTML::TreeBuilder;

my $tree = HTML::TreeBuilder->new->parse_file("chpt15Intro.htm");

use HTML::FormatText;

my $formatter = HTML::FormatText->new(leftmargin => 0, rightmargin => 1000);
   #print $formatter->format($tree); is replaced by push
push (my @files, $formatter->format($tree));
foreach my $files (@files) {
    $files =~ s/^\s+//mg;
    open MYFILE, ">ch15Intro.txt";
    select MYFILE;
    print $files;
}

In the Terminal, after getting the html file converted, I write:

script parsedch15Intro.txt ./lexparser.csh ch15Intro.txt

to save the output of the parser. This step still needs automation.

I'm a beginner so thanks for any advice.

Body:
UPDATE: Here is the answer to automating the parser: (similar to TLP and outis' solutions)

#!/usr/bin/perl
use strict;
use warnings;

for my $file (@ARGV) {
    next unless ($file =~ /^(.+).txt*$/i); ##file name ends in txt
    my $outfile = "parsed$1".".txt";
    qx/script -q \/Users\/jon\/Desktop\/stanford-postagger-full-2011-04-20\/$outfile \.\/lexparser.csh $file/;
}
##First in Terminal cd /Users/jon/Downloads/chpt1-8 or whichever directory this perl script and all texfiles and parser files are
##Called in Terminal by ==>  perl auto_parse.pl *.txt

##This saves the output to directory spedicifed. The output is the parsed files
##Required: stanford parser files in same directory as this script


问:
Getting error when use Android Koush Ion to call Laravel route
I'm trying to learn android development, I'm using Android Studio. I need to access an external database (to insert, get itens ... CRUD) and I've found a tutorial that tells me to use koush ion, from Android using Ion, I call a web page that is a Laravel 7 Route. When I call without parameters, it works very well and I can get in Android the returned value. But when I use "setBodyParameter", I get the following error:

```<code>java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.gson.JsonElement com.google.gson.JsonObject.get(java.lang.String)' on a null object reference
</code>```

My laravel route just calls this function:

```<code>function cadastrar(){
    date_default_timezone_set('America/Sao_Paulo');
    $resposta = array();
    $myUser = null;

    $nome = isset($_POST['nome']) ? $_POST['nome'] : 'Teste 2';
    $email = isset($_POST['email']) ? $_POST['email'] : 'teste@gmail.com';

    $myUser = new Usuario;
    $myUser->nome = $nome;
    $myUser->email = $email;
    $myUser->save();

    $resposta = array('id' => strval($myUser->id_usuario), 'nome' => $myUser->nome, 'email' => $myUser->email);

    return json_encode($resposta);
}
</code>```

My Laravel route is Route::get (but when I change it to Route::post I get an error too).

And my Android code that calls this page is:

```<code>final TextView txtErro = (TextView) findViewById(R.id.textView4);
txtErro.setText("");
final String strNome = nome.getText().toString();
final String strEmail = email.getText().toString();
String url = "**My URL to the route in laravel**";
Ion.with(MainActivity.this)
     .load(url)
     .setBodyParameter("nome", strNome)
     .setBodyParameter("email", strEmail)
     .asJsonObject()
     .setCallback(new FutureCallback<JsonObject>() {
         @Override
         public void onCompleted(Exception e, JsonObject result) {
             try {
                 txtErro.setText(result.get("id").getAsString());
             } catch (Exception erro) {
                 txtErro.setText(erro.toString());
             }
         }
     });
</code>```

When I comment the two lines of ".setBodyParameter", I get the returned value from laravel (if laravel route is Route::get). When I change the line of "load" to "load("POST", url)", I get an error.

I tried something related to CORS that I found here in StackOverflow and in my Laravel Kernel.php I commented the line that calls "VerifyCsrfToken", but still didn't working.

(Finally, I'm sorry if have something wrong in my english)

答:
Did you try logging the Exception e and JsonObject result?
or set logging for the request and watch it in logcat

.setLogging("MyLogs", Log.DEBUG)

Body:
I'm trying to learn android development, I'm using Android Studio. I need to access an external database (to insert, get itens ... CRUD) and I've found a tutorial that tells me to use koush ion, from Android using Ion, I call a web page that is a Laravel 7 Route. When I call without parameters, it works very well and I can get in Android the returned value. But when I use "setBodyParameter", I get the following error:

java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.gson.JsonElement com.google.gson.JsonObject.get(java.lang.String)' on a null object reference

My laravel route just calls this function:

function cadastrar(){
    date_default_timezone_set('America/Sao_Paulo');
    $resposta = array();
    $myUser = null;

    $nome = isset($_POST['nome']) ? $_POST['nome'] : 'Teste 2';
    $email = isset($_POST['email']) ? $_POST['email'] : 'teste@gmail.com';

    $myUser = new Usuario;
    $myUser->nome = $nome;
    $myUser->email = $email;
    $myUser->save();

    $resposta = array('id' => strval($myUser->id_usuario), 'nome' => $myUser->nome, 'email' => $myUser->email);

    return json_encode($resposta);
}

My Laravel route is Route::get (but when I change it to Route::post I get an error too).

And my Android code that calls this page is:

final TextView txtErro = (TextView) findViewById(R.id.textView4);
txtErro.setText("");
final String strNome = nome.getText().toString();
final String strEmail = email.getText().toString();
String url = "**My URL to the route in laravel**";
Ion.with(MainActivity.this)
     .load(url)
     .setBodyParameter("nome", strNome)
     .setBodyParameter("email", strEmail)
     .asJsonObject()
     .setCallback(new FutureCallback<JsonObject>() {
         @Override
         public void onCompleted(Exception e, JsonObject result) {
             try {
                 txtErro.setText(result.get("id").getAsString());
             } catch (Exception erro) {
                 txtErro.setText(erro.toString());
             }
         }
     });

When I comment the two lines of ".setBodyParameter", I get the returned value from laravel (if laravel route is Route::get). When I change the line of "load" to "load("POST", url)", I get an error.

I tried something related to CORS that I found here in StackOverflow and in my Laravel Kernel.php I commented the line that calls "VerifyCsrfToken", but still didn't working.

(Finally, I'm sorry if have something wrong in my english)


问:
android webrtc rotate VideoFrame
I try below code to rotate VideoFrame by 90 degree but it doesn't work:

```<code>private VideoFrame rotateFrame(VideoFrame inVideoFrame) {
    VideoFrame outVideoFrame = new VideoFrame(
            inVideoFrame.getBuffer(),
            90, inVideoFrame.getTimestampNs());
    return outVideoFrame;
}
</code>```

What's correct logic to rotate a videoFrame?

答:
I have same problem but your code it's work for me.

I publish stream to Wowza Streaming Engine using webRTC and I try to debug my code while video frame publish to wowza. The orientation is 270. When I received this orientation back from service. it's 0 I try to change it before pass this frame to SurfaceViewRenderer. It's work.

```<code>remoteVideoTrack.addSink {
   remoteView?.onFrame(VideoFrame(it.buffer, 270, -1))
 }
</code>```

Title: android webrtc rotate VideoFrame

Body:
I try below code to rotate VideoFrame by 90 degree but it doesn't work:

private VideoFrame rotateFrame(VideoFrame inVideoFrame) {
    VideoFrame outVideoFrame = new VideoFrame(
            inVideoFrame.getBuffer(),
            90, inVideoFrame.getTimestampNs());
    return outVideoFrame;
}

What's correct logic to rotate a videoFrame?

Body:
I have same problem but your code it's work for me.

I publish stream to Wowza Streaming Engine using webRTC and I try to debug my code while video frame publish to wowza. The orientation is 270. When I received this orientation back from service. it's 0 I try to change it before pass this frame to SurfaceViewRenderer. It's work.

remoteVideoTrack.addSink {
   remoteView?.onFrame(VideoFrame(it.buffer, 270, -1))
 }


问:
Cannot change Java source level to 1.7 in Eclipse with Maven
I tried using a multi-catch statement in my Java Project. It doesn't give any errors in the IDE, but when I do Run As->Maven Install I get the following error (removed personal file paths as those are not relevant I think):

```<code>Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.1:compile (default-compile) on project: Compilation failure
MyClass.java:[137,39] multi-catch statement is not supported in -source 1.5
[ERROR] (use -source 7 or higher to enable multi-catch statement)
</code>```

As per the other answers on this site, I tried changing the Java version in my project properties. However, everything was already set to Java 1.7. My Java Build Path

My Java Compiler settings:

What should I change to be able to use Java 1.7 properly?

答:
Okay somehow I missed this post before. I didn't come up at all when googling about the exact error strangely enough.
To fix it I simply had to add:

```<code><properties>
        <maven.compiler.source>1.7</maven.compiler.source>
        <maven.compiler.target>1.7</maven.compiler.target>

</properties>
</code>```

to my project's pom.xml as maven was not using the java version from my eclipse project settings.

Body:
I tried using a multi-catch statement in my Java Project. It doesn't give any errors in the IDE, but when I do Run As->Maven Install I get the following error (removed personal file paths as those are not relevant I think):

Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.1:compile (default-compile) on project: Compilation failure
MyClass.java:[137,39] multi-catch statement is not supported in -source 1.5
[ERROR] (use -source 7 or higher to enable multi-catch statement)

As per the other answers on this site, I tried changing the Java version in my project properties. However, everything was already set to Java 1.7. My Java Build Path

My Java Compiler settings:

What should I change to be able to use Java 1.7 properly?

Body:
Okay somehow I missed this post before. I didn't come up at all when googling about the exact error strangely enough.
To fix it I simply had to add:

<properties>
        <maven.compiler.source>1.7</maven.compiler.source>
        <maven.compiler.target>1.7</maven.compiler.target>

</properties>

to my project's pom.xml as maven was not using the java version from my eclipse project settings.


问:
Cannot add Expires headers in WordPress
Been trying to get rid of the "Add Expires headers" in GTmatrix, with no success. I've installed the WP Fastest Cache plugin and tried a bunch of different variations to .htaccess that I found on stackoverflow and some other websites where people had similar questions, with no success - GTmatrix still shows the same error.

This is my current .htaccess:

```<code># BEGIN WpFastestCache
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{HTTPS} =on
RewriteCond %{HTTP_HOST} ^domain.com
# Start WPFC Exclude
# End WPFC Exclude
# Start_WPFC_Exclude_Admin_Cookie
RewriteCond %{HTTP:Cookie} !wordpress_logged_in_[^\=]+\=username
# End_WPFC_Exclude_Admin_Cookie
RewriteCond %{HTTP_HOST} ^domain.com
RewriteCond %{HTTP_USER_AGENT} !(facebookexternalhit|Twitterbot|LinkedInBot|WhatsApp|Mediatoolkitbot)
RewriteCond %{HTTP_USER_AGENT} !(WP\sFastest\sCache\sPreload(\siPhone\sMobile)?\s*Bot)
RewriteCond %{REQUEST_METHOD} !POST
RewriteCond %{REQUEST_URI} !(\/){2}$
RewriteCond %{REQUEST_URI} \/$
RewriteCond %{QUERY_STRING} !.+
RewriteCond %{HTTP:Cookie} !comment_author_
RewriteCond %{HTTP:Cookie} !woocommerce_items_in_cart
RewriteCond %{HTTP:Cookie} !safirmobilswitcher=mobil
RewriteCond %{HTTP:Profile} !^[a-z0-9\"]+ [NC]
RewriteCond %{DOCUMENT_ROOT}/wp-content/cache/all/$1/index.html -f [or]
RewriteCond /home/user/public_html/wp-content/cache/all/$1/index.html -f
RewriteRule ^(.*) "/wp-content/cache/all/$1/index.html" [L]
</IfModule>
<FilesMatch "index\.(html|htm)$">
AddDefaultCharset UTF-8
<ifModule mod_headers.c>
FileETag None
Header unset ETag
Header set Cache-Control "max-age=0, no-cache, no-store, must-revalidate"
Header set Pragma "no-cache"
Header set Expires "Mon, 29 Oct 1923 20:30:00 GMT"
</ifModule>
</FilesMatch>
# END WpFastestCache
#Customize expires cache start - adjust the period according to your needs
<IfModule mod_expires.c>
  FileETag MTime Size
  AddOutputFilterByType DEFLATE text/plain text/html text/xml text/css application/xml application/xhtml+xml application/rss+xml application/javascript application/x-javascript
  ExpiresActive On
  ExpiresByType text/html "access 600 seconds"
  ExpiresByType application/xhtml+xml "access 600 seconds"
  ExpiresByType text/css "access 1 month"
  ExpiresByType text/javascript "access 1 month"
  ExpiresByType text/x-javascript "access 1 month"
  ExpiresByType application/javascript "access 1 month"
  ExpiresByType application/x-javascript "access 1 month"
  ExpiresByType application/x-shockwave-flash "access 1 month"
  ExpiresByType application/pdf "access 1 month"
  ExpiresByType image/x-icon "access 1 year"
  ExpiresByType image/jpg "access 1 year"
  ExpiresByType image/jpeg "access 1 year"
  ExpiresByType image/png "access 1 year"
  ExpiresByType image/gif "access 1 year"
  ExpiresDefault "access 1 month"
</IfModule>
#Expires cache end
# BEGIN Cache-Control Headers
<IfModule mod_expires.c>
  <IfModule mod_headers.c>
    <filesMatch "\.(ico|jpe?g|png|gif|swf)$">
      Header append Cache-Control "public"
    </filesMatch>
    <filesMatch "\.(css)$">
      Header append Cache-Control "public"
    </filesMatch>
    <filesMatch "\.(js)$">
      Header append Cache-Control "private"
    </filesMatch>
    <filesMatch "\.(x?html?|php)$">
      Header append Cache-Control "private, must-revalidate"
    </filesMatch>
  </IfModule>
</IfModule>
# LBROWSERCSTART Browser Caching
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/gif "access 1 year"
ExpiresByType image/jpg "access 1 year"
ExpiresByType image/jpeg "access 1 year"
ExpiresByType image/png "access 1 year"
ExpiresByType image/x-icon "access 1 year"
ExpiresByType text/css "access 1 month"
ExpiresByType text/javascript "access 1 month"
ExpiresByType text/html "access 1 month"
ExpiresByType application/javascript "access 1 month"
ExpiresByType application/x-javascript "access 1 month"
ExpiresByType application/xhtml-xml "access 1 month"
ExpiresByType application/pdf "access 1 month"
ExpiresByType application/x-shockwave-flash "access 1 month"
ExpiresDefault "access 1 month"
</IfModule>
# END Caching LBROWSERCEND

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

# END WordPress
</code>```

答:
I solved the problem with the following steps:
First checked my apache site configuration and make sure AllowOverride all present like below.

```<code><Directory /var/www/mysite>
    AllowOverride all
</Directory>
</code>```

Then tried the following commands:

```<code>sudo a2enmod rewrite
sudo a2enmod headers
sudo a2enmod expires
sudo service apache2 restart
</code>```

Title: Cannot add Expires headers in WordPress

Body:
Been trying to get rid of the "Add Expires headers" in GTmatrix, with no success. I've installed the WP Fastest Cache plugin and tried a bunch of different variations to .htaccess that I found on stackoverflow and some other websites where people had similar questions, with no success - GTmatrix still shows the same error.

This is my current .htaccess:

# BEGIN WpFastestCache
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{HTTPS} =on
RewriteCond %{HTTP_HOST} ^domain.com
# Start WPFC Exclude
# End WPFC Exclude
# Start_WPFC_Exclude_Admin_Cookie
RewriteCond %{HTTP:Cookie} !wordpress_logged_in_[^\=]+\=username
# End_WPFC_Exclude_Admin_Cookie
RewriteCond %{HTTP_HOST} ^domain.com
RewriteCond %{HTTP_USER_AGENT} !(facebookexternalhit|Twitterbot|LinkedInBot|WhatsApp|Mediatoolkitbot)
RewriteCond %{HTTP_USER_AGENT} !(WP\sFastest\sCache\sPreload(\siPhone\sMobile)?\s*Bot)
RewriteCond %{REQUEST_METHOD} !POST
RewriteCond %{REQUEST_URI} !(\/){2}$
RewriteCond %{REQUEST_URI} \/$
RewriteCond %{QUERY_STRING} !.+
RewriteCond %{HTTP:Cookie} !comment_author_
RewriteCond %{HTTP:Cookie} !woocommerce_items_in_cart
RewriteCond %{HTTP:Cookie} !safirmobilswitcher=mobil
RewriteCond %{HTTP:Profile} !^[a-z0-9\"]+ [NC]
RewriteCond %{DOCUMENT_ROOT}/wp-content/cache/all/$1/index.html -f [or]
RewriteCond /home/user/public_html/wp-content/cache/all/$1/index.html -f
RewriteRule ^(.*) "/wp-content/cache/all/$1/index.html" [L]
</IfModule>
<FilesMatch "index\.(html|htm)$">
AddDefaultCharset UTF-8
<ifModule mod_headers.c>
FileETag None
Header unset ETag
Header set Cache-Control "max-age=0, no-cache, no-store, must-revalidate"
Header set Pragma "no-cache"
Header set Expires "Mon, 29 Oct 1923 20:30:00 GMT"
</ifModule>
</FilesMatch>
# END WpFastestCache
#Customize expires cache start - adjust the period according to your needs
<IfModule mod_expires.c>
  FileETag MTime Size
  AddOutputFilterByType DEFLATE text/plain text/html text/xml text/css application/xml application/xhtml+xml application/rss+xml application/javascript application/x-javascript
  ExpiresActive On
  ExpiresByType text/html "access 600 seconds"
  ExpiresByType application/xhtml+xml "access 600 seconds"
  ExpiresByType text/css "access 1 month"
  ExpiresByType text/javascript "access 1 month"
  ExpiresByType text/x-javascript "access 1 month"
  ExpiresByType application/javascript "access 1 month"
  ExpiresByType application/x-javascript "access 1 month"
  ExpiresByType application/x-shockwave-flash "access 1 month"
  ExpiresByType application/pdf "access 1 month"
  ExpiresByType image/x-icon "access 1 year"
  ExpiresByType image/jpg "access 1 year"
  ExpiresByType image/jpeg "access 1 year"
  ExpiresByType image/png "access 1 year"
  ExpiresByType image/gif "access 1 year"
  ExpiresDefault "access 1 month"
</IfModule>
#Expires cache end
# BEGIN Cache-Control Headers
<IfModule mod_expires.c>
  <IfModule mod_headers.c>
    <filesMatch "\.(ico|jpe?g|png|gif|swf)$">
      Header append Cache-Control "public"
    </filesMatch>
    <filesMatch "\.(css)$">
      Header append Cache-Control "public"
    </filesMatch>
    <filesMatch "\.(js)$">
      Header append Cache-Control "private"
    </filesMatch>
    <filesMatch "\.(x?html?|php)$">
      Header append Cache-Control "private, must-revalidate"
    </filesMatch>
  </IfModule>
</IfModule>
# LBROWSERCSTART Browser Caching
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/gif "access 1 year"
ExpiresByType image/jpg "access 1 year"
ExpiresByType image/jpeg "access 1 year"
ExpiresByType image/png "access 1 year"
ExpiresByType image/x-icon "access 1 year"
ExpiresByType text/css "access 1 month"
ExpiresByType text/javascript "access 1 month"
ExpiresByType text/html "access 1 month"
ExpiresByType application/javascript "access 1 month"
ExpiresByType application/x-javascript "access 1 month"
ExpiresByType application/xhtml-xml "access 1 month"
ExpiresByType application/pdf "access 1 month"
ExpiresByType application/x-shockwave-flash "access 1 month"
ExpiresDefault "access 1 month"
</IfModule>
# END Caching LBROWSERCEND

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

# END WordPress

Body:
I solved the problem with the following steps:
First checked my apache site configuration and make sure AllowOverride all present like below.

<Directory /var/www/mysite>
    AllowOverride all
</Directory>

Then tried the following commands:

sudo a2enmod rewrite
sudo a2enmod headers
sudo a2enmod expires
sudo service apache2 restart


问:
Convert space separated string of coordinates into JavaScript object array
This space separated string:

```<code>const polygon = "42.44492,75.637764 42.445503,75.64534 42.433681,75.6604"
</code>```

..should be converted to array consisting objects:

```<code>const polygon = [
    { lat: 42.44492, lng: 75.637764 },
    { lat: 42.445503, lng: 75.64534 },
    { lat: 42.433681, lng: 75.6604 }
]
</code>```

What is the most simplest (beautiful) way to achieve this with JavaScript? Is there a nice one liner for this? The initial string can consist any amount coordinate pairs.

答:
use map function along with split function

const polygon = "42.44492,75.637764 42.445503,75.64534 42.433681,75.6604";

const res = polygon.split(' ').map(s => {
  const [lat, lng] = s.split(',');
  return { lat: Number(lat), lng: Number(lng) };
});

console.log(res);```

Body:
This space separated string:

const polygon = "42.44492,75.637764 42.445503,75.64534 42.433681,75.6604"

..should be converted to array consisting objects:

const polygon = [
    { lat: 42.44492, lng: 75.637764 },
    { lat: 42.445503, lng: 75.64534 },
    { lat: 42.433681, lng: 75.6604 }
]

What is the most simplest (beautiful) way to achieve this with JavaScript? Is there a nice one liner for this? The initial string can consist any amount coordinate pairs.


问:
Extension Method for Polly Policy
I am trying to find the best way to write an extension method for Polly Policy

I have the following

```<code>public static async Task<IPollyDto> RunAsync(this IPolicy dtoClass, Func<Task<IDto>> action)
{
    return
        await Policy
            .Handle<ApiException>(ex => ex.StatusCode == HttpStatusCode.RequestTimeout)
            .RetryAsync(3,
                async (exception, retryCount) => await Task.Delay(200))
            .ExecuteAsync(async () => await action.Invoke().ConfigureAwait(false))
            .ConfigureAwait(false);
}

public interface IPollyDto {}
public interface IPolicy {}
</code>```

Then I call the code as follows

```<code>public class DtoTest : IPollyDto
{
}

public class TestA
{
    public static async Task<DtoTest> GetItem(string datasetName)
    {
        return await Task.Run(() => new DtoTest()) ;
    }
}

public class PollyTest : IPolicy
{
    public async Task<DtoTest> TestMe(string dataset)
    {
       return (DtoTest) await this.RunAsync(() => Task.Run(() => (IPollyDto) TestA.GetItem(dataset)));
    }
}
</code>```

I get an error resolving types.

答:
You are missing async-await in your  this.RunAsync(() => Task.Run(() => (IPollyDto) TestA.GetItem(dataset))) call. Change it to:

```<code>this.RunAsync(() => Task.Run(async () => (IPollyDto)(await TestA.GetItem(dataset))));
</code>```

Or just:

```<code>this.RunAsync(async () => (IPollyDto)(await TestA.GetItem(dataset)))
</code>```

Title: Extension Method for Polly Policy

Body:
I am trying to find the best way to write an extension method for Polly Policy

I have the following

public static async Task<IPollyDto> RunAsync(this IPolicy dtoClass, Func<Task<IDto>> action)
{
    return
        await Policy
            .Handle<ApiException>(ex => ex.StatusCode == HttpStatusCode.RequestTimeout)
            .RetryAsync(3,
                async (exception, retryCount) => await Task.Delay(200))
            .ExecuteAsync(async () => await action.Invoke().ConfigureAwait(false))
            .ConfigureAwait(false);
}

public interface IPollyDto {}
public interface IPolicy {}

Then I call the code as follows

public class DtoTest : IPollyDto
{
}

public class TestA
{
    public static async Task<DtoTest> GetItem(string datasetName)
    {
        return await Task.Run(() => new DtoTest()) ;
    }
}

public class PollyTest : IPolicy
{
    public async Task<DtoTest> TestMe(string dataset)
    {
       return (DtoTest) await this.RunAsync(() => Task.Run(() => (IPollyDto) TestA.GetItem(dataset)));
    }
}

I get an error resolving types.

Body:
You are missing async-await in your  this.RunAsync(() => Task.Run(() => (IPollyDto) TestA.GetItem(dataset))) call. Change it to:

this.RunAsync(() => Task.Run(async () => (IPollyDto)(await TestA.GetItem(dataset))));

Or just:

this.RunAsync(async () => (IPollyDto)(await TestA.GetItem(dataset)))


问:
rewrite the url in .htaccess
i have a link like

```<code>http://for.example.com/?type=foo-bar
</code>```

and i want it to be displayed in the address bar like this

```<code>http://for.example.com/foo-bar
</code>```

so when the user types

```<code>http://for.example.com/foo-bar
</code>```

it should re-direct to

```<code>http://for.example.com/?type=foo-bar
</code>```

without the user knowing about the backend query string processing

plz help...

答:
```<code>RewriteEngine On
RewriteBase /

RewriteRule ^foo-bar?$  index.php?type=foo-bar [QSA,L]
</code>```

Or if you want to use different variables (values) instead of "bar"

```<code>RewriteRule ^foo-([A-Za-z0-9_]+)?$  index.php?type=foo&someVar=$1 [QSA,L]
</code>```

But you couldn't use dash (-) after "foo-", only alphanumeric and underscore.

Title: rewrite the url in .htaccess

Body:
i have a link like

http://for.example.com/?type=foo-bar

and i want it to be displayed in the address bar like this

http://for.example.com/foo-bar

so when the user types

http://for.example.com/foo-bar

it should re-direct to

http://for.example.com/?type=foo-bar

without the user knowing about the backend query string processing

plz help...

Body:
RewriteEngine On
RewriteBase /

RewriteRule ^foo-bar?$  index.php?type=foo-bar [QSA,L]

Or if you want to use different variables (values) instead of "bar"

RewriteRule ^foo-([A-Za-z0-9_]+)?$  index.php?type=foo&someVar=$1 [QSA,L]

But you couldn't use dash (-) after "foo-", only alphanumeric and underscore.


问:
Logging to tricky site with python
I am trying to scrape servers list from https://www.astrill.com/member-zone/tools/vpn-servers which is for members only. Username, password and captcha are required. Everything works if I login with browser and copy 'PHPSESSID' cookie, but I want to log in with Python. I am downloading capthca and enter it manually. But anyway I am not able to login. Login URL: https://www.astrill.com/member-zone/log-in
Could anybody help me, please?</p>

```<code>SERVERS_URL = 'https://www.astrill.com/member-zone/tools/vpn-servers'
LOGIN_URL = 'https://www.astrill.com/member-zone/log-in'

def get_capcha(url):
    print(f'Scraping url: {url}')
    try:
        response = requests.get(url)
        response.raise_for_status()
    except Exception as e:
        print(type(e), e)
    if response.status_code == 200:
        print('Success!')
    page = response.content
    soup = bs4.BeautifulSoup(page, 'html.parser')
    captcha_url = (soup.find('img', alt='captcha')['src'])
    captcha_file = os.path.join(BASE_FOLDER, 'captcha.jpg')
    id = soup.find(id='csrf_token')
    print(id['value'])
    print(f'Captcha: {captcha_url}')
    print(response.headers)
    urlretrieve(captcha_url, captcha_file)
    return id['value']

def login(url, id):
    captcha_text = input('Captcha: ')
    print(id)
    payload = {
        'action': 'log-in',
        'username': 'myusername@a.com',
        'password': '1111111',
        'captcha': captcha_text,
        '_random': 'l4r1b7hf4g',
        'csrf_token': id
    }

    session = requests.session()
    post = session.post(url, data=payload)
    r = session.get(SERVERS_URL)
    print(r.text)
    print(r.cookies)

if __name__ == '__main__':
    id = get_capcha(LOGIN_URL)
    login(LOGIN_URL, id)
</code>```

答:
First of all I was not sure about payload fields to POST. They can be easily discovered with Firefox Developer Tools - Network. You can find what does your browser actually post there. Second thing which I discovered was that I need to request capthca file within the session with my headers and cookies. So my code looks like following now and it works! (probably some header fields can be removed)</p>

```<code>cookies = {}

headers = {
        'Host': 'www.astrill.com',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:76.0) Gecko/20100101 Firefox/76.0',
        'Accept': 'application/json, text/javascript, */*; q=0.01',
        'Accept-Language': 'ru-RU,ru;q=0.8,en-US;q=0.5,en;q=0.3',
        'Accept-Encoding': 'gzip, deflate, br',
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
        'X-Requested-With': 'XMLHttpRequest',
        'Content-Length': '169',
        'Origin': 'https://www.astrill.com',
        'Connection': 'keep-alive',
        'Referer': 'https://www.astrill.com/member-zone/log-in',
    }

payload = {
    'action': 'log-in',
    'username': 'myusername@a.com',
    'password': '1111111',
    'remember_me': 0,
    'captcha': '',
    '_random': 'somerandom1',
    'csrf_token': ''
    }

def get_capcha(url):
    print(f'Scraping url: {url}')
    try:
        response = session.get(url)
        response.raise_for_status()
    except Exception as e:
        print(type(e), e)
    if response.status_code == 200:
        print('Success!')
    page = response.content
    soup = bs4.BeautifulSoup(page, 'html.parser')
    captcha_url = (soup.find('img', alt='captcha')['src'])
    captcha_file = os.path.join(BASE_FOLDER, 'captcha.jpg')
    payload['csrf_token'] = soup.find(id='csrf_token')['value']
    print(f'csrf_token: {payload["csrf_token"]}')
    print(f'Captcha: {captcha_url}')
    cookies.update(response.cookies)
    captcha_img = session.get(captcha_url, headers=headers, cookies=cookies)
    file = open(captcha_file, "wb")
    file.write(captcha_img.content)
    file.close()
    payload['captcha'] = input('Captcha: ')
    return

def login(url):
    post = session.post(url, data=payload, headers=headers, cookies=cookies)
    print(post.text)
    r = session.get(SERVERS_URL, cookies=cookies)
    print(r.text)
    print(r.cookies)

def main():
    get_capcha(LOGIN_URL)
    login(LOGIN_URL)

if __name__ == '__main__':
    main()
</code>```

Title: Logging to tricky site with python

Body:
I am trying to scrape servers list from https://www.astrill.com/member-zone/tools/vpn-servers which is for members only. Username, password and captcha are required. Everything works if I login with browser and copy 'PHPSESSID' cookie, but I want to log in with Python. I am downloading capthca and enter it manually. But anyway I am not able to login. Login URL: https://www.astrill.com/member-zone/log-in
Could anybody help me, please?

SERVERS_URL = 'https://www.astrill.com/member-zone/tools/vpn-servers'
LOGIN_URL = 'https://www.astrill.com/member-zone/log-in'

def get_capcha(url):
    print(f'Scraping url: {url}')
    try:
        response = requests.get(url)
        response.raise_for_status()
    except Exception as e:
        print(type(e), e)
    if response.status_code == 200:
        print('Success!')
    page = response.content
    soup = bs4.BeautifulSoup(page, 'html.parser')
    captcha_url = (soup.find('img', alt='captcha')['src'])
    captcha_file = os.path.join(BASE_FOLDER, 'captcha.jpg')
    id = soup.find(id='csrf_token')
    print(id['value'])
    print(f'Captcha: {captcha_url}')
    print(response.headers)
    urlretrieve(captcha_url, captcha_file)
    return id['value']

def login(url, id):
    captcha_text = input('Captcha: ')
    print(id)
    payload = {
        'action': 'log-in',
        'username': 'myusername@a.com',
        'password': '1111111',
        'captcha': captcha_text,
        '_random': 'l4r1b7hf4g',
        'csrf_token': id
    }

    session = requests.session()
    post = session.post(url, data=payload)
    r = session.get(SERVERS_URL)
    print(r.text)
    print(r.cookies)

if __name__ == '__main__':
    id = get_capcha(LOGIN_URL)
    login(LOGIN_URL, id)

Body:
First of all I was not sure about payload fields to POST. They can be easily discovered with Firefox Developer Tools - Network. You can find what does your browser actually post there. Second thing which I discovered was that I need to request capthca file within the session with my headers and cookies. So my code looks like following now and it works! (probably some header fields can be removed)

cookies = {}

headers = {
        'Host': 'www.astrill.com',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:76.0) Gecko/20100101 Firefox/76.0',
        'Accept': 'application/json, text/javascript, */*; q=0.01',
        'Accept-Language': 'ru-RU,ru;q=0.8,en-US;q=0.5,en;q=0.3',
        'Accept-Encoding': 'gzip, deflate, br',
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
        'X-Requested-With': 'XMLHttpRequest',
        'Content-Length': '169',
        'Origin': 'https://www.astrill.com',
        'Connection': 'keep-alive',
        'Referer': 'https://www.astrill.com/member-zone/log-in',
    }

payload = {
    'action': 'log-in',
    'username': 'myusername@a.com',
    'password': '1111111',
    'remember_me': 0,
    'captcha': '',
    '_random': 'somerandom1',
    'csrf_token': ''
    }

def get_capcha(url):
    print(f'Scraping url: {url}')
    try:
        response = session.get(url)
        response.raise_for_status()
    except Exception as e:
        print(type(e), e)
    if response.status_code == 200:
        print('Success!')
    page = response.content
    soup = bs4.BeautifulSoup(page, 'html.parser')
    captcha_url = (soup.find('img', alt='captcha')['src'])
    captcha_file = os.path.join(BASE_FOLDER, 'captcha.jpg')
    payload['csrf_token'] = soup.find(id='csrf_token')['value']
    print(f'csrf_token: {payload["csrf_token"]}')
    print(f'Captcha: {captcha_url}')
    cookies.update(response.cookies)
    captcha_img = session.get(captcha_url, headers=headers, cookies=cookies)
    file = open(captcha_file, "wb")
    file.write(captcha_img.content)
    file.close()
    payload['captcha'] = input('Captcha: ')
    return

def login(url):
    post = session.post(url, data=payload, headers=headers, cookies=cookies)
    print(post.text)
    r = session.get(SERVERS_URL, cookies=cookies)
    print(r.text)
    print(r.cookies)

def main():
    get_capcha(LOGIN_URL)
    login(LOGIN_URL)

if __name__ == '__main__':
    main()


问:
Pandas - Get two digit year out of a date
I have a date column in a pandas DataFrame which shows the date that the future contract expires. I need to use that information to create a new column with a name that my back tester accepts. The format I need it in is:

```<code>metadata['backtester_name'] = 'NF' + month_code + 2_digit_year
</code>```

I know how to get the month_code, I need help to figure out how to get the 2_digit_year for this column.

This is what the expiry column looks like, it's formatted as an object by default:

```<code>expiry
2009-01-29
2010-01-28
2011-01-27
</code>```

This is the formula that I'm playing around with:

```<code>metadata['backtesting_name'] = 'NF' + pd.DatetimeIndex(metadata['expiry']).month.map(month_code) + str(pd.to_datetime(metadata['expiry']))[2:]
</code>```

My issue is that the year is not getting captured correctly, it returns some kind of series:

```<code>backtesting_name
0    NFF0     2009-01-29\n1     2010-01-28\n2     2...
1    NFF0     2009-01-29\n1     2010-01-28\n2     2...
2    NFF0     2009-01-29\n1     2010-01-28\n2     2...
3    NFF0     2009-01-29\n1     2010-01-28\n2     2...
4    NFF0     2009-01-29\n1     2010-01-28\n2     2...
</code>```

Your help would be appreciated, let me know if I need to share any other information.

答:
Use Series.dt.strftime with %y for YY format, also is possible create helper varaible for Series of datetimes and reuse it:

```<code>dates = pd.to_datetime(metadata['expiry'])
metadata['backtesting_name'] = 'NF' + dates.month.map(month_code) + dates.dt.strftime('%y')
</code>```

Body:
I have a date column in a pandas DataFrame which shows the date that the future contract expires. I need to use that information to create a new column with a name that my back tester accepts. The format I need it in is:

metadata['backtester_name'] = 'NF' + month_code + 2_digit_year

I know how to get the month_code, I need help to figure out how to get the 2_digit_year for this column.

This is what the expiry column looks like, it's formatted as an object by default:

expiry
2009-01-29
2010-01-28
2011-01-27

This is the formula that I'm playing around with:

metadata['backtesting_name'] = 'NF' + pd.DatetimeIndex(metadata['expiry']).month.map(month_code) + str(pd.to_datetime(metadata['expiry']))[2:]

My issue is that the year is not getting captured correctly, it returns some kind of series:

backtesting_name
0    NFF0     2009-01-29\n1     2010-01-28\n2     2...
1    NFF0     2009-01-29\n1     2010-01-28\n2     2...
2    NFF0     2009-01-29\n1     2010-01-28\n2     2...
3    NFF0     2009-01-29\n1     2010-01-28\n2     2...
4    NFF0     2009-01-29\n1     2010-01-28\n2     2...

Your help would be appreciated, let me know if I need to share any other information.

Body:
Use Series.dt.strftime with %y for YY format, also is possible create helper varaible for Series of datetimes and reuse it:

dates = pd.to_datetime(metadata['expiry'])
metadata['backtesting_name'] = 'NF' + dates.month.map(month_code) + dates.dt.strftime('%y')