text:
Q: Missing Called-Station-Id parameter in "Accounting-Request" FreeRadius UniFi I'm having trouble inserting the "Called-Station-Id" parameter into the radacct table.
After connecting to Unifi (AP AC LITE) in "Access-Request" I get the parameter Called-Station-Id.
However, "Access-Request" is followed by "Accounting-Request" in which the Called-Station-Id parameter is empty. The Called-Staion-Id field in the radacct table is empty.
Could someone tell me why this is happening and how could I insert the Called-Station-Id parameter into the radacct table?
I also use microTik access points and they insert the Called-Station-Id parameter into the radacct table
Below I pasted the radius logs that show "Access-Request" (1) and "Accounting-Request" (2):
(1) Received Access-Request Id 30 from 185.13.190.143:60381 to 148.252.41.12:1812 length 213
(1)  Called-Station-Id = "B4-FB-E4-10-52-47:Hotspot Test"
(1)  Calling-Station-Id = "C4-B3-01-5B-E3-79"
(1)  Acct-Session-Id = "3dr3mfty1bltwpg4"
(1)  NAS-Identifier = "32296af2-4c7c-4492-a02c-9dff3298503d"
(1)  NAS-IP-Address = 10.255.0.104
(1)  Framed-IP-Address = 178.37.87.66
(1)  User-Name = "c4:b3:01:5b:e3:79"
(1)  CHAP-Challenge = 0xfe51d128a7fa49f20a684cb62b33d2cf
(1)  CHAP-Password = 0x26b5e87d6e3ae20e0c9f9b7ec1f3ba1050
(1)  Message-Authenticator = 0x7b2188c4c44c830131d8c6a4d606c36e
(1) # Executing section authorize from file /etc/raddb/sites-enabled/default
(1)  authorize {
(1)   policy filter_username {
(1)    if (&User-Name) {
(1)    if (&User-Name) -> TRUE
(1)    if (&User-Name) {
(1)     if (&User-Name =~ / /) {
(1)     if (&User-Name =~ / /) -> FALSE
(1)     if (&User-Name =~ /@[^@]*@/ ) {
(1)     if (&User-Name =~ /@[^@]*@/ ) -> FALSE
(1)     if (&User-Name =~ /\.\./ ) {
(1)     if (&User-Name =~ /\.\./ ) -> FALSE
(1)     if ((&User-Name =~ /@/) && (&User-Name !~ /@(.+)\.(.+)$/)) {
(1)     if ((&User-Name =~ /@/) && (&User-Name !~ /@(.+)\.(.+)$/))  -> FALSE
(1)     if (&User-Name =~ /\.$/) {
(1)     if (&User-Name =~ /\.$/)  -> FALSE
(1)     if (&User-Name =~ /@\./) {
(1)     if (&User-Name =~ /@\./)  -> FALSE
(1)    } # if (&User-Name) = notfound
(1)   } # policy filter_username = notfound
(1)   [preprocess] = ok
(1)   policy rewrite_called_station_id {
(1)    if (&Called-Station-Id && (&Called-Station-Id =~ /^([0-9a-f]{2})[^0-9a-f]?([0-9a-f]{2})[^0-9a-f]?([0-9a-f]{2})[^0-9a-f]?([0-9a-f]{2})[^0-9a-f]?([0-9a-f]{2})[^0-9a-f]?([0-9a-f]{2})([^0-9a-f](.+))?$/i)) {
(1)    if (&Called-Station-Id && (&Called-Station-Id =~ /^([0-9a-f]{2})[^0-9a-f]?([0-9a-f]{2})[^0-9a-f]?([0-9a-f]{2})[^0-9a-f]?([0-9a-f]{2})[^0-9a-f]?([0-9a-f]{2})[^0-9a-f]?([0-9a-f]{2})([^0-9a-f](.+))?$/i)) -> TRUE
(1)    if (&Called-Station-Id && (&Called-Station-Id =~ /^([0-9a-f]{2})[^0-9a-f]?([0-9a-f]{2})[^0-9a-f]?([0-9a-f]{2})[^0-9a-f]?([0-9a-f]{2})[^0-9a-f]?([0-9a-f]{2})[^0-9a-f]?([0-9a-f]{2})([^0-9a-f](.+))?$/i)) {
(1)     update request {
(1)      EXPAND %{toupper:%{1}:%{2}:%{3}:%{4}:%{5}:%{6}}
(1)       --> B4:FB:E4:10:52:47
(1)      &Called-Station-Id := B4:FB:E4:10:52:47
(1)     } # update request = noop
(1)     if ("%{8}") {
(1)     EXPAND %{8}
(1)      --> Hotspot Test
(1)     if ("%{8}") -> TRUE
(1)     if ("%{8}") {
(1)      update request {
(1)       EXPAND %{8}
(1)        --> Hotspot Test
(1)       &Called-Station-SSID := Hotspot Test
(1)      } # update request = noop
(1)     } # if ("%{8}") = noop
(1)     [updated] = updated
(1)    } # if (&Called-Station-Id && (&Called-Station-Id =~ /^([0-9a-f]{2})[^0-9a-f]?([0-9a-f]{2})[^0-9a-f]?([0-9a-f]{2})[^0-9a-f]?([0-9a-f]{2})[^0-9a-f]?([0-9a-f]{2})[^0-9a-f]?([0-9a-f]{2})([^0-9a-f](.+))?$/i)) = updated
(1)    ... skipping else: Preceding "if" was taken
(1)   } # policy rewrite_called_station_id = updated
(1)   policy rewrite_calling_station_id {
(1)    if (&Calling-Station-Id && (&Calling-Station-Id =~ /^([0-9a-f]{2})[^0-9a-f]?([0-9a-f]{2})[^0-9a-f]?([0-9a-f]{2})[^0-9a-f]?([0-9a-f]{2})[^0-9a-f]?([0-9a-f]{2})[^0-9a-f]?([0-9a-f]{2})$/i)) {
(1)    if (&Calling-Station-Id && (&Calling-Station-Id =~ /^([0-9a-f]{2})[^0-9a-f]?([0-9a-f]{2})[^0-9a-f]?([0-9a-f]{2})[^0-9a-f]?([0-9a-f]{2})[^0-9a-f]?([0-9a-f]{2})[^0-9a-f]?([0-9a-f]{2})$/i)) -> TRUE
(1)    if (&Calling-Station-Id && (&Calling-Station-Id =~ /^([0-9a-f]{2})[^0-9a-f]?([0-9a-f]{2})[^0-9a-f]?([0-9a-f]{2})[^0-9a-f]?([0-9a-f]{2})[^0-9a-f]?([0-9a-f]{2})[^0-9a-f]?([0-9a-f]{2})$/i)) {
(1)     update request {
(1)      EXPAND %{toupper:%{1}:%{2}:%{3}:%{4}:%{5}:%{6}}
(1)       --> C4:B3:01:5B:E3:79
(1)      &Calling-Station-Id := C4:B3:01:5B:E3:79
(1)     } # update request = noop
(1)     [updated] = updated
(1)    } # if (&Calling-Station-Id && (&Calling-Station-Id =~ /^([0-9a-f]{2})[^0-9a-f]?([0-9a-f]{2})[^0-9a-f]?([0-9a-f]{2})[^0-9a-f]?([0-9a-f]{2})[^0-9a-f]?([0-9a-f]{2})[^0-9a-f]?([0-9a-f]{2})$/i)) = updated
(1)    ... skipping else: Preceding "if" was taken
(1)   } # policy rewrite_calling_station_id = updated
(1) chap:  &control:Auth-Type := CHAP
(1)   [chap] = ok
(1)   [mschap] = noop
(1)   [digest] = noop
(1) suffix: Checking for suffix after "@"
(1) suffix: No '@' in User-Name = "c4:b3:01:5b:e3:79", looking up realm NULL
(1) suffix: No such realm "NULL"
(1)   [suffix] = noop
(1) eap: No EAP-Message, not doing EAP
(1)   [eap] = noop
(1)   [files] = noop
(1) sql: EXPAND %{User-Name}
(1) sql:  --> c4:b3:01:5b:e3:79
(1) sql: SQL-User-Name set to 'c4:b3:01:5b:e3:79'
rlm_sql (sql): Reserved connection (6)
(1) sql: EXPAND SELECT id, username, attribute, value, op FROM radcheck WHERE username = '%{SQL-User-Name}' ORDER BY id
(1) sql:  --> SELECT id, username, attribute, value, op FROM radcheck WHERE username = 'c4:b3:01:5b:e3:79' ORDER BY id(1) sql: Executing select query: SELECT id, username, attribute, value, op FROM radcheck WHERE username = 'c4:b3:01:5b:e3:79' ORDER BY id
(1) sql: User found in radcheck table
(1) sql: Conditional check items matched, merging assignment check items
(1) sql:  Cleartext-Password := "c4:b3:01:5b:e3:79"
(1) sql: EXPAND SELECT id, username, attribute, value, op FROM radreply WHERE username = '%{SQL-User-Name}' ORDER BY id
(1) sql:  --> SELECT id, username, attribute, value, op FROM radreply WHERE username = 'c4:b3:01:5b:e3:79' ORDER BY id(1) sql: Executing select query: SELECT id, username, attribute, value, op FROM radreply WHERE username = 'c4:b3:01:5b:e3:79' ORDER BY id
(1) sql: EXPAND SELECT groupname FROM radusergroup WHERE username = '%{SQL-User-Name}' ORDER BY priority
(1) sql:  --> SELECT groupname FROM radusergroup WHERE username = 'c4:b3:01:5b:e3:79' ORDER BY priority
(1) sql: Executing select query: SELECT groupname FROM radusergroup WHERE username = 'c4:b3:01:5b:e3:79' ORDER BY priority
(1) sql: User not found in any groups
rlm_sql (sql): Released connection (6)
Need 1 more connections to reach min connections (3)
rlm_sql (sql): Opening additional connection (7), 1 of 30 pending slots used
rlm_sql_mysql: Starting connect to MySQL server
rlm_sql_mysql: Connected to database 'radius' on Localhost via UNIX socket, server version 5.7.22, protocol version 10
(1)   [sql] = ok
(1)   [expiration] = noop
(1)   [logintime] = noop
(1) pap: WARNING: Auth-Type already set. Not setting to PAP
(1)   [pap] = noop
(1)  } # authorize = updated
(1) Found Auth-Type = CHAP
(1) # Executing group from file /etc/raddb/sites-enabled/default
(1)  Auth-Type CHAP {
(1) chap: Comparing with "known good" Cleartext-Password
(1) chap: CHAP user "c4:b3:01:5b:e3:79" authenticated successfully
(1)   [chap] = ok
(1)  } # Auth-Type CHAP = ok
(1) # Executing section post-auth from file /etc/raddb/sites-enabled/default
(1)  post-auth {
(1)   update {
(1)    No attributes updated
(1)   } # update = noop
(1) sql: EXPAND .query
(1) sql:  --> .query
(1) sql: Using query template 'query'
rlm_sql (sql): Reserved connection (5)
(1) sql: EXPAND %{User-Name}
(1) sql:  --> c4:b3:01:5b:e3:79
(1) sql: SQL-User-Name set to 'c4:b3:01:5b:e3:79'
(1) sql: EXPAND INSERT INTO radpostauth (username, pass, reply, authdate) VALUES ( '%{SQL-User-Name}', '%{%{User-Password}:-%{Chap-Password}}', '%{reply:Packet-Type}', '%S')
(1) sql:  --> INSERT INTO radpostauth (username, pass, reply, authdate) VALUES ( 'c4:b3:01:5b:e3:79', '0x26b5e87d6e3ae20e0c9f9b7ec1f3ba1050', 'Access-Accept', '2019-12-12 09:51:11.859278')
(1) sql: Executing query: INSERT INTO radpostauth (username, pass, reply, authdate) VALUES ( 'c4:b3:01:5b:e3:79', '0x26b5e87d6e3ae20e0c9f9b7ec1f3ba1050', 'Access-Accept', '2019-12-12 09:51:11.859278')
(1) sql: SQL query returned: success
(1) sql: 1 record(s) updated
rlm_sql (sql): Released connection (5)
(1)   [sql] = ok
(1)   [exec] = noop
(1)   policy remove_reply_message_if_eap {
(1)    if (&reply:EAP-Message && &reply:Reply-Message) {
(1)    if (&reply:EAP-Message && &reply:Reply-Message) -> FALSE
(1)    else {
(1)     [noop] = noop
(1)    } # else = noop
(1)   } # policy remove_reply_message_if_eap = noop
(1)  } # post-auth = ok
(1) Sent Access-Accept Id 30 from 148.252.41.12:1812 to 185.13.190.143:60381 length 0
(1) Finished request
Waking up in 0.7 seconds.
(2) Received Accounting-Request Id 112 from 185.13.190.143:47776 to 148.252.41.12:1813 length 69
(2)  User-Name = "c4:b3:01:5b:e3:79"
(2)  Acct-Session-Id = "3dr3mfty1bltwpg4"
(2)  Acct-Status-Type = Start
(2)  Event-Timestamp = "Dec 12 2019 09:51:12 EST"
(2) # Executing section preacct from file /etc/raddb/sites-enabled/default
(2)  preacct {
(2)   [preprocess] = ok
(2)   policy rewrite_called_station_id {
(2)    if (&Called-Station-Id && (&Called-Station-Id =~ /^([0-9a-f]{2})[^0-9a-f]?([0-9a-f]{2})[^0-9a-f]?([0-9a-f]{2})[^0-9a-f]?([0-9a-f]{2})[^0-9a-f]?([0-9a-f]{2})[^0-9a-f]?([0-9a-f]{2})([^0-9a-f](.+))?$/i)) {
(2)    if (&Called-Station-Id && (&Called-Station-Id =~ /^([0-9a-f]{2})[^0-9a-f]?([0-9a-f]{2})[^0-9a-f]?([0-9a-f]{2})[^0-9a-f]?([0-9a-f]{2})[^0-9a-f]?([0-9a-f]{2})[^0-9a-f]?([0-9a-f]{2})([^0-9a-f](.+))?$/i)) -> FALSE
(2)    else {
(2)     [noop] = noop
(2)    } # else = noop
(2)   } # policy rewrite_called_station_id = noop
(2)   policy rewrite_calling_station_id {
(2)    if (&Calling-Station-Id && (&Calling-Station-Id =~ /^([0-9a-f]{2})[^0-9a-f]?([0-9a-f]{2})[^0-9a-f]?([0-9a-f]{2})[^0-9a-f]?([0-9a-f]{2})[^0-9a-f]?([0-9a-f]{2})[^0-9a-f]?([0-9a-f]{2})$/i)) {
(2)    if (&Calling-Station-Id && (&Calling-Station-Id =~ /^([0-9a-f]{2})[^0-9a-f]?([0-9a-f]{2})[^0-9a-f]?([0-9a-f]{2})[^0-9a-f]?([0-9a-f]{2})[^0-9a-f]?([0-9a-f]{2})[^0-9a-f]?([0-9a-f]{2})$/i)) -> FALSE
(2)    else {
(2)     [noop] = noop
(2)    } # else = noop
(2)   } # policy rewrite_calling_station_id = noop
(2)   policy acct_unique {
(2)    update request {
(2)     &Tmp-String-9 := "ai:"
(2)    } # update request = noop
(2)    if (("%{hex:&Class}" =~ /^%{hex:&Tmp-String-9}/) &&    ("%{string:&Class}" =~ /^ai:([0-9a-f]{32})/i)) {
(2)    EXPAND %{hex:&Class}
(2)     -->
(2)    EXPAND ^%{hex:&Tmp-String-9}
(2)     --> ^61693a
(2)    if (("%{hex:&Class}" =~ /^%{hex:&Tmp-String-9}/) &&    ("%{string:&Class}" =~ /^ai:([0-9a-f]{32})/i)) -> FALSE
(2)    else {
(2)     update request {
(2)      EXPAND %{md5:%{User-Name},%{Acct-Session-ID},%{%{NAS-IPv6-Address}:-%{NAS-IP-Address}},%{NAS-Identifier},%{NAS-Port-ID},%{NAS-Port}}
(2)       --> 7db92fee37429b54c2a5c4d942df0351
(2)      &Acct-Unique-Session-Id := 7db92fee37429b54c2a5c4d942df0351
(2)     } # update request = noop
(2)    } # else = noop
(2)   } # policy acct_unique = noop
(2) suffix: Checking for suffix after "@"
(2) suffix: No '@' in User-Name = "c4:b3:01:5b:e3:79", looking up realm NULL
(2) suffix: No such realm "NULL"
(2)   [suffix] = noop
(2)   [files] = noop
(2)  } # preacct = ok
(2) # Executing section accounting from file /etc/raddb/sites-enabled/default
(2)  accounting {
(2) detail: EXPAND /var/log/radius/radacct/%{%{Packet-Src-IP-Address}:-%{Packet-Src-IPv6-Address}}/detail-%Y%m%d
(2) detail:  --> /var/log/radius/radacct/185.13.190.143/detail-20191212
(2) detail: /var/log/radius/radacct/%{%{Packet-Src-IP-Address}:-%{Packet-Src-IPv6-Address}}/detail-%Y%m%d expands to /var/log/radius/radacct/185.13.190.143/detail-20191212
(2) detail: EXPAND %t
(2) detail:  --> Thu Dec 12 09:51:11 2019
(2)   [detail] = ok
(2)   [unix] = ok
(2) sql: EXPAND %{tolower:type.%{Acct-Status-Type}.query}
(2) sql:  --> type.start.query
(2) sql: Using query template 'query'
rlm_sql (sql): Reserved connection (6)
(2) sql: EXPAND %{User-Name}
(2) sql:  --> c4:b3:01:5b:e3:79
(2) sql: SQL-User-Name set to 'c4:b3:01:5b:e3:79'
(2) sql: EXPAND INSERT INTO radacct (acctsessionid,       acctuniqueid,      username, realm,
    nasipaddress,      nasportid, nasporttype,     acctstarttime,     acctupdatetime, acctstoptime,
    acctsessiontime,    acctauthentic, connectinfo_start,    connectinfo_stop,    acctinputoctets, acctoutputoctets,   calledstationid,    callingstationid, acctterminatecause,  servicetype,      framedprotocol, framedipaddress) VALUES ('%{Acct-Session-Id}', '%{Acct-Unique-Session-Id}', '%{SQL-User-Name}', '%{Realm}', '%{NAS-IP-Address}', '%{%{NAS-Port-ID}:-%{NAS-Port}}', '%{NAS-Port-Type}', FROM_UNIXTIME(%{integer:Event-Timestamp}), FROM_UNIXTIME(%{integer:Event-Timestamp}), NULL, '0', '%{Acct-Authentic}', '%{Connect-Info}', '', '0', '0', '%{Called-Station-ID}', '%{Calling-Station-ID}', '', '%{Service-Type}', '%{Framed-Protocol}', '%{Framed-IP-Address}')
(2) sql:  --> INSERT INTO radacct (acctsessionid,       acctuniqueid,      username, realm,
    nasipaddress,      nasportid, nasporttype,     acctstarttime,     acctupdatetime, acctstoptime,
    acctsessiontime,    acctauthentic, connectinfo_start,    connectinfo_stop,    acctinputoctets, acctoutputoctets,   calledstationid,    callingstationid, acctterminatecause,  servicetype,      framedprotocol, framedipaddress) VALUES ('3dr3mfty1bltwpg4', '7db92fee37429b54c2a5c4d942df0351', 'c4:b3:01:5b:e3:79', '', '185.13.190.143', '', '', FROM_UNIXTIME(1576162272), FROM_UNIXTIME(1576162272), NULL, '0', '', '', '', '0', '0', '', '', '', '', '', '')
(2) sql: Executing query: INSERT INTO radacct (acctsessionid,      acctuniqueid,      username, realm,
        nasipaddress,      nasportid, nasporttype,     acctstarttime,     acctupdatetime, acctstoptime,      acctsessiontime,    acctauthentic, connectinfo_start,    connectinfo_stop,    acctinputoctets, acctoutputoctets,   calledstationid,    callingstationid, acctterminatecause,  servicetype,      framedprotocol, framedipaddress) VALUES ('3dr3mfty1bltwpg4', '7db92fee37429b54c2a5c4d942df0351', 'c4:b3:01:5b:e3:79', '', '185.13.190.143', '', '', FROM_UNIXTIME(1576162272), FROM_UNIXTIME(1576162272), NULL, '0', '', '', '', '0', '0', '', '', '', '', '', '')
(2) sql: SQL query returned: success
(2) sql: 1 record(s) updated
rlm_sql (sql): Released connection (6)
(2)   [sql] = ok
(2)   [exec] = noop
(2) attr_filter.accounting_response: EXPAND %{User-Name}
(2) attr_filter.accounting_response:  --> c4:b3:01:5b:e3:79
(2) attr_filter.accounting_response: Matched entry DEFAULT at line 12
(2)   [attr_filter.accounting_response] = updated
(2)  } # accounting = updated
(2) Sent Accounting-Response Id 112 from 148.252.41.12:1813 to 185.13.190.143:47776 length 0
(2) Finished request
(2) Cleaning up request packet ID 112 with timestamp +67
Waking up in 0.7 seconds.

A: Other than asking Ubiquiti to fix the issue, the only other thing you could try is returning the Called-Station-ID value in the Class attribute.  NAS are meant to return this value in the next Accounting-Request, but not all do.
post-auth {
    update reply {
        Class := "%{Called-Station-ID}"
    }

}

preacct {
    if (!&Called-Station-ID && &Class) {
        update request {
            Called-Station-ID := "%{string:Class}"
        }
    }
}


text:
Q: Manual flushing doesn't delete all WAL files in YugabyteDB? I am trying to flush the WAL to SST files using yb-ts-cli --server_address=<> flush_all_tablets. After the flushing is complete, I still see exactly 3G of WAL in two tables. Any ideas knows why that might be the case?

A: Every yb-tserver has these default flags:
--log_min_seconds_to_retain=900
--log_min_segments_to_retain=2

So even if these logs are not needed because this tablet peer's memtables are flushed to SSTables, the database still retains some logs for situations, for example if another peer of this tablet falls behind by a little bit and needs to catch up.
The above two flags also guide log retention (in addition to what's not been flushed).

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to show popup in flutter screen I am new to flutter so can anyone help me with this please.
I wish to add a popup in my flutter screen. Following is the image what I want in my flutter screen:

Can someone help me with this ?

A: Future<void> _showMyDialog() async {
  return showDialog<void>(
    context: context,
    barrierDismissible: false, // user must tap button!
    builder: (BuildContext context) {
      return AlertDialog(
        title: Text('AlertDialog Title'),
        content: SingleChildScrollView(
          child: ListBody(
            children: <Widget>[
              Text('This is a demo alert dialog.'),
              Text('Would you like to approve of this message?'),
            ],
          ),
        ),
        actions: <Widget>[
          TextButton(
            child: Text('Allow'),
            onPressed: () {
              Navigator.of(context).pop();
            },
          ),
          TextButton(
            child: Text('Block'),
            onPressed: () {
              Navigator.of(context).pop();
            },
          )
        ],
      );
    },
  );
}


text:
Q: Why display empty page without variable values in Laravel 5.2 I need to display my users table data in the index.blade.php file, but when I visit the index view it displays an empty page, it does not display the variables data, which I need. (No errors are displayed.)
index.blade.php
@if(isset($users))
@foreach($users as $use)
<h1>{{$use->username}}</h1>

@endforeach
@endif

UsersController.php
<?php

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

use Auth;
use App\User;

use App\Http\Requests;

class UserController extends Controller
{
    public function index()
    {
        $users = User::userr()->get();
        // $users = User::all();

        return view('users.index')->withUser($users);
        //dd($users);
    }
}

User.php Model
<?php

namespace App;
use Auth;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'username', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    public function getAvatarUrl()
    {
        return "http://www.gravatar.com/avatar/" . md5(strtolower(trim($this->email))) . "?d=mm&s=40";
    }

    public function scopeUserr($query)
    {
        return $query->where('username',Auth::user()->id);
    }
}

Can You give me some solutions?

A: May be you have to check if the data passed to your blade,
and try to use
$model = App\Flight::findOrFail(1);

return view('page',compact('var'));

check this
http://www.snippetcase.com/snippet/27/Bind+and+Display+data+in+blade+page+for+laravel


text:
Q: How to use Mobile web to control desktop web page I'm new in Web Develop, I wish to made a web page URL that ask user to launch in mobile and can control the Web page.
For example, user visit at www.abc.com, and it will ask user use mobile to access g.it.com
and there is 3 buttons. So user might choose the 1st button and at desktop will show 1st layout.
I had try on websocket but I have no idea how to made it.
Need Help!!!
Thanks


text:
Q: Clojure : treverse through json and return true or false, depending on the contion check result for each key:value pair in given document I have tried to return true or false depending on the value present in the given hash-map. I have tried using reduced-kv but it really doesn't work.
for eg :
{:address {:zip 411045, :city "pune"}, :coupans ["abc" "def"], :cost 200, :items [{:category "partywear", :name "shirt", :price 50.26} {:category "partywear", :name "trouser", :price 10.26}]}
I want to write a function such that if "items.price" = 50.26
and "items.name" = "shirt",, should return true but "items.price = 10.26 and "items.name" = "shirt" should return false .
I am first flattening the array and then changing the key to regex key
(def compare_str_regex (clojure.string/replace compare_str #"\[\]" "\\\\[\\[0-9\\]+\\\\]"))
for eg : items[].price  -- > items[[0-9]+].price
Then I use reduce-kv to iterate, but the problem is it will check all the doc
it should use the and condition between the two key sent
(reduce-kv (fn [m k v]
             (if (and (re-find (re-pattern compare_str_regex ) k)
                      (op value v))
               (reduced true)
               false))  {} flat_pl_map)

A: If the rule is "return true if there are any entries in the items
collection with :name "shirt" and :price 50.26", then I would write that function like this:
If that's correct, then I would write that function like this:
(fn [{:keys [items]}]
  (some (fn [{:keys [name price]}]
          (and (= "shirt" name) (= 50.26 price)))
        items))


text:
Q: collected image in one unique image java I need an information: I have to do a project for my university's stage. My program allow me to discover an image with circular movement. I have a lot of images that should be collect in a unique "long" image, with black edges. Is it possible?
I searched in the other topic but they are only for iOs or html. My application is an application in java that will be use on the pc.
Sorry for the bad english
Thank's, Elia.

A: Using the dogbane's answer,
You could adapt the code easily to do what you want.
Using Graphics.fillRect to create a rectangle. Just need to set the color to black but you will need to manage the height and width in code.
g.setColor(Color.BLACK);

//Black rectangle on the left edge
g.fillRect(x, y, rectWidth, rectHeight);
x += rectSize;

for(String image : images){
    BufferedImage bi = ImageIO.read(new File(image));
    g.drawImage(bi, x, y, null);
    x += bi.getWidth();
    //Black rectangle on the right
    g.fillRect(x, y, rectWidth, rectHeight);
    x += rectSize;
}

You will see an rectWidth, rectHeight to generate the black square. You have two solutions here,

*

*set it yourself (a parameter that you give from the batch)

*iterate on the image first to get the biggest height of this batch (carefull on the perfs)

Note :

*

*to improve this, you might want to center the image if those have some different sizes ... this will requires somt update to add a black square up above and below. But it's a nice exercice ;)

*The default background is black, so you don't need to create the filled rectangle for a black one (default byte are 0 so black #000000)

*Stangely, a Windows XP tell me the PNG is not valid but on a Seven it works fine, might need to investigate this.

UPDATE :
Since we need the result image height and width on the beginning (didn't though about it), we answer some question

*

*It is easy to update the background color to don't bother with it later (paint the full image at the beginning

*We are force to iterate the image first to do the sum of there width

*We can get the maximum height in the same time


text:
Q: Can we send an automated notification to customer Who sends an email on closed case which is more than 30 day A case is closed and closed more than 30 days ( created a field to calculate - Today - case closed date ) and If Customer sends an email (Email message - incoming true) then send auto notification to customer. I tried created workflow and process builder but this is not working as expected. Can some one help me with a best solution.
If using apex trigger or flows or process builder , any help is appreciated.


text:
Q: aspnetawesome grid databinding not working I have been using AweomeGrid for about 2 mvc4 Projects Now and It has been working fine, However I am completely bumped when I tried the mvc5 Branch. I basically have a grid and controller setup as follows
 @Html.Awe().Grid("grdZone")
    .Groupable(false)
    .Url(Url.Action("ZoneRead", "Setup"))
    .PageSize(20)
    .Columns(
    new Column(){ Name = "Id", Width = 70 },
    new Column(){ Name = "Name" },
    new Column(){ Name = "GCount", Header = "Group Count", Width = 100})

And the controller listing is as follows
 public ActionResult ZoneRead(GridParams g)
        {
            var model = _zoneService.GetAll().Select(i => new ZoneListModel
            {
                Id = i.Id,
                GCount = i.Groups.Count(),
                Name = i.Name
            });
            return Json(new GridModelBuilder<ZoneListModel>(model, g)
            {
                Key = "Id",
                Map = o => new
                {
                    o.Id,
                    o.Name,
                    o.GCount
                }
            }.Build());
        }

The problem is that The controller actually returns the data but somehow strangely, The Grid just displays empty table cells without any values at all. The number of empty rows displayed however corresponda to the records returned by the controller method
Please what Am I doing wrong
A speedy answer will be appreaciated

A: it's possible that on mvc5 you're using minification, and the minification broke the script, try adding AwesomeMvc.js without including it in a script bundle
(btw using version 4.7 this shouldn't happen anymore)


text:
Q: Docker volume mount using CLI command I've created two volumes I wish to use to store content of two folders /etc/php and /var/www inside of container:
$ docker volume create dvwa_etcphp
$ docker volume create dvwa_www

I have a container, which I run using the command:
docker run --rm -it -p 80:80 vulnerables/web-dvwa --name dvwatest \
--mount type=volume,source=dvwa_www,target=/var/www \
--mount type=volume,source=dvwa_etcphp,tagret=/etc/php

$ docker ps
CONTAINER ID        IMAGE                  COMMAND                  CREATED             STATUS              PORTS                NAMES
c700546a86b7        vulnerables/web-dvwa   "/main.sh --name dvw…"   4 minutes ago       Up 4 minutes        0.0.0.0:80->80/tcp   quirky_hawking

But when I do:
$ docker inspect c70

it gives me (I've removed everything that seem to me superfluos):
[
    {
        "Id": "c700546a86b74de5f2f941ee92fd72406e2a29e2e06ca85532658d1fa6ddbae5",
        "Created": "2020-01-22T13:36:23.976013357Z",
        "Path": "/main.sh",
        "Args": [
            "--name",
            "dvwatest",
            "--mount",
            "type=volume,source=dvwa_www,target=/var/www",
            "--mount",
            "type=volume,source=dvwa_etcphp,tagret=/etc/php"
        ],

        "Name": "/quirky_hawking",
        "RestartCount": 0,
        "Driver": "overlay2",
        "Platform": "linux",
        "MountLabel": "",
        "ProcessLabel": "",
        "AppArmorProfile": "docker-default",
        "ExecIDs": null,
        "HostConfig": {
            "VolumeDriver": "",
            "VolumesFrom": null,
            "Name": "overlay2"
        },
        "Mounts": [],
        "Config": {
            "Hostname": "c700546a86b7",
            },
            "Cmd": [
                "--name",
                "dvwatest",
                "--mount",
                "type=volume,source=dvwa_www,target=/var/www",
                "--mount",
                "type=volume,source=dvwa_etcphp,tagret=/etc/php"
            ],
            "Image": "vulnerables/web-dvwa",
            "Volumes": null,
            "WorkingDir": "",
            "Entrypoint": [
                "/main.sh"
            ],
            "OnBuild": null,
            "Labels": {
                "maintainer": "opsxcq@strm.sh"
            }
        },
    }
]

I want to use volumes to save changes in two folders: /etc/php and /var/www. And when I stop container and run a new one I want it to use these two volumes with edited config files.
Docker version is 19.03.2
Thank you!

A: Can you try following the following format for creating:
 docker run -it --mount type=volume,src=<VOLUME-NAME>,dst=<CONTAINER-PATH> --mount type=volume,src=<VOLUME-NAME>,dst=<CONTAINER-PATH> -p host_port:container_port --name myservice <IMAGE>

Edit: Creation command has been edited
The above worked for me:
docker run -ti --mount type=volume,src=cust_vol2,dst=/cust_vol2 --mount type=volume,src=cust_vol1,dst=/cust_vol1  -p 8024:8024  --name mycontainer centos

$docker inspect mycontainer
"Mounts": [
            {
                "Type": "volume",
                "Source": "cust_vol2",
                "Target": "/cust_vol2"
            },
            {
                "Type": "volume",
                "Source": "cust_vol1",
                "Target": "/cust_vol1"
            }
        ]

and provide the verbose output if possible.


text:
Q: unable to get check box value in android public class FragSettings extends SherlockFragment {
    CheckBox notificationcheckbox;
    Button savebutton;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.frag_settings, container, false);
        notificationcheckbox = (CheckBox) container
                .findViewById(R.id.checkBox1);
        savebutton = (Button) container.findViewById(R.id.button1);
        addListenerOnChkWindows();

        return view;
    }

    public void addListenerOnChkWindows() {

        notificationcheckbox.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                if (((CheckBox) v).isChecked()) {
                    Toast.makeText(getActivity(), "Bro, Notifcation:)",
                            Toast.LENGTH_LONG).show();
                }

            }
        });

    }

    public void addListenerOnButton() {
        savebutton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                StringBuffer result = new StringBuffer();
                result.append("Linux check : ").append(
                        notificationcheckbox.isChecked());
                Toast.makeText(getActivity(), result.toString(),
                        Toast.LENGTH_LONG).show();
            }
        });
    }

Here is my code i want set notification value and get in another class. but i am unable to set and get value in another class basically i want to implement setting part in android . please look and tell me solution am trying but its showing Error .

A: update your function:
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.frag_settings, container, false);
    notificationcheckbox = (CheckBox)
            view.findViewById(R.id.checkBox1);
    savebutton = (Button) view.findViewById(R.id.button1);
    addListenerOnChkWindows();

    return view;
 }
 public void addListenerOnChkWindows() {

    notificationcheckbox.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

            if (notificationcheckbox.isChecked()) {
                Toast.makeText(getActivity(), "Bro, Notifcation:)",
                        Toast.LENGTH_LONG).show();
            }

        }
    });

}

A: Change this code, Instead of  using container use inflate view you will get
  notificationcheckbox = (CheckBox) view
            .findViewById(R.id.checkBox1);


text:
Q: Unit test an image resize method Im trying to use PHPUnit in Symfony to test a method which returns a resized image. Ideally, I would be able to mock in image object and set some sizes, then see if the sizes are changed on the return.
The code uses Imagick and decodes the image, Im wondering if this means I will be forced to keep test images on the server for unit testing? Is there a way to mock an image file in code for this purpose?
    $based = base64_decode($content);

    if($based){
        $content = $based;
    }

    $imagick = new \Imagick();

    $imagick->readImageBlob($content);

If the file were to be stored on the server for testing, how would I mock a request object to include said file?

A: I managed to find the correct way to pass a file to Imagick. It requires file_get_contents wrapped in base64_encode
public function setUp(){
    $imagePath = getcwd()."/src/Woodwork/PartnerBundle/Tests/lin.png";
    $this->image = base64_encode(file_get_contents($imagePath));
    $logger = $this->getMockBuilder('Logger')->setMethods(array('debug', 'info', 'error'))->getMock();
    $this->imagickHelper = new ImagickHelper($logger);
}


text:
Q: Conditional Indentation in Vim How would i assign my own indentation margin if a condition is met (ie string is included) on the previous line?
An example would be one space indentation in an if statement. thanks in advance.
input:
`int main(int argc, char **argv) {
if (argc != 1)
    return(2);
if (argc != 2)
   return(3);

for (...)

printf("\n");
}`
output:(using g/if/normal j>>)
shifts to the right every return line
output:(expected)
int main(int argc, char **argv) {
if (argc != 1)
 return(2);

if (argc != 2)
 return(3);

for (...)

printf("\n");
}
In other words the positioning is expected to be relative to the string, and not its previous position. again, thanks for your effort @kev

A: :help indentexpr

You need to create a indent function.
I've used the following reference before.
How to Write a Vim Indent Script
You can also look in the indent folder of your vim install for examples.
on Max OS X
/usr/share/vim/vim73/indent

A: Use these commands to auto indent C source file:
:set syn=cpp

gg=G


text:
Q: Android : Error setting condition to background of listview I've try setting the background using condition when creating custom listview.
Here is the sample code of adapter view for listview :
    public lstViewAdapter(Activity a, ArrayList<HashMap<String, String>> d)
    {
       ......
       ......
       ......
    }

    public View getView(int position, View convertView, ViewGroup parent)

    {

         View vi = convertView;
         if(position % 2 != 0)
         {
        if(convertView==null)
        {
            vi = inflater.inflate(R.layout.list_row,null);

        }
         }
         else
         {
        if(convertView==null)
        {
            vi = inflater.inflate(R.layout.list_row1,null);
        }
         }
         ....
         ....
         ....
     }

It display as normal but when i scroll up and down... it change randomly...
any suggestion would be appreciated...

A: Hope you will find something related here.
http://smartphonebysachin.blogspot.com/2012/03/custom-listview-with-separator-and.html
There you can replace the image with a xml view for the background.

A: I dunno if this is good or not but i fix it by deleting the condition of covertView != null :
if(position % 2 != 0)
         {

            vi = inflater.inflate(R.layout.list_row,null);

         }
         else
         {

            vi = inflater.inflate(R.layout.list_row1,null);
      }


text:
Q: JNI error when directory with .so my .so depends on did not exist Don't ask why I need that, trust me I do Setup is very simple. I have native method which is in libjnitester.so. libjnitester.so depends on libcall.so (libs just simulate real ones). I need to dynamically install the libs to the directory prior to calling native method. I do that by creating the directory with File.mkdris, and then by calling tar to extract tar.gz into that directory (I wait for completion of tar process so files are definitely there by the time I call JNI method). When calling the method, I'm getting:

java.lang.UnsatisfiedLinkError: /.../libjnitester.so: libcall.so:
  cannot open shared object file: No such file or directory

I specify -Djava.library.path and have LD_LIBRARY_PATH defined. I assume problem is in LD_LIBRARY_PATH - as directory did not exist when I started JVM, and has been created only during the execution, it is ignored. If I pre-create the directory (without .so files) then start JVM everything works fine.
Question - how can I dynamically install .so with my JNI method and .so files it depends on, into a new directory?

A: After installing the libraries, call System.load() for each .so file. That should load the libraries dynamically. At this point you should be able to call your native method.


text:
Q: Passing correct properties to popup notification I want to show a notification with the upload status. I took over a project in React & ASP.NET and I am relatively new to this. The question is quite simple, yet I am struggling to solve it: How do I display a popup notification showing which files have been successfully been uploaded and which not?
import * as React from "react";
import { connect } from "react-redux";
import { Form, Select, Button, Upload, message, notification} from 'antd';
import * as Actions from "../actions";

const FormItem = Form.Item;

class UploadFileForm extends React.Component<any, any> {
    constructor(props: any) {
        super(props);
    }
    handleSubmit = (e) => {
        message.config({ top: 0 });
        message.loading('Importing in progress...', 3);
        e.preventDefault();
        this.props.uploadFile(this.props.form.getFieldsValue());
          notification["info"]({
          message: 'Files successfully uploaded',
          description: '', // <-- this line has to be modified
          duration: 10
        });
    }
    render() {
        const { getFieldDecorator } = this.props.form;
        return (
            <Form onSubmit={this.handleSubmit}>
                <FormItem label="File" >
                    {getFieldDecorator('upload', {
                        valuePropName: 'fileList',
                        getValueFromEvent: (e) => e.fileList.slice(-1)
                    })(
                        <Upload name="importFile" action={' '} multiple={false}>
                            <Button> Upload </Button>
                        </Upload>
                        )}
                </FormItem>
                <Button type="primary" htmlType="submit">Import</Button>
            </Form>
        );
    }
}
export default Form.create()(UploadFileForm);

More specifically: How do I have to modify the line description: '', to show me a list of all uploaded files and their status as pure text, e.g. File(s) '1.txt', '2.txt', and '3.txt' have been successfully uploaded. File(s) '4.txt' failed.?
The project documentation says that we are using Redux-Saga, but I am not so maybe that makes the story easier.

A: I guess your this.props.uploadFile method is a promise so considering that you should show notification once that promise is resolved
this.props.uploadFile(this.props.form.getFieldsValue()).then(result => {
    // since your client doesn't know which ones are success/failed, server should return
    // this information when request is finished

   const { successUploads, failUploads } = result;

    notification["info"]({
        message: 'Files successfully uploaded',
        description: `File(s) ${successUploads.join(', ')} have been successfully uploaded. File(s) ${failUploads.join(', ')} failed.`
        duration: 10
     });
});

If you can't control whats returned from the server then you'd need to track uploads on client side, but that would mean having multiple uploads (requests) to the server and your upload method would look something like this:
async function uploadFiles(files) {
    // I've called your server upload uploadService.send(), but replace this with your method
    const results = await Promise.all(
        files.map(file => uploadService.send(file))
             .map(p => p.catch(e => e)
    );

    let successUploads = [];
    let failUploads = [];
    results.forEach((result, idx) => {
        const file = files[idx];
        if (result instanceof Error) {
            failUploads.push(file);
        } else {
            successUploads.push(file);
        }
    });

    return {
        successUploads,
        failUploads
    }
}

Then you could call uploadFiles same way as shown in first snippet.


text:
Q: Search and filter through html table input textbox using input textbox I have a table which contains itemcode field.I want to filter item code. I have bind the item code with input textbox inside html table because item code is editable.
I tried with given below code:
function loadiTems() {
  var table = $('#tblDetItems').DataTable({
    "paging": false,
    "keys": true,
    "retrieve": true,
    "bLengthChange": false,
    "ordering": false,
    "scrollY": 300,
    "scrollX": false
  });

  $('#ContentPlaceHolder1_rptItems_txt_ItemCode_tbl').val('');
  $('#ContentPlaceHolder1_rptItems_txtslno_tbl').bind('keyup', function (e) {
    table.columns(1).search("^" + this.value, true, true, true).draw();
  });
}

the above code worked with normal columns. Please help me to find a solution

      <asp:Repeater runat="server" ID="rptItems">
        <HeaderTemplate>

                  SlNo.

                  Item Code

                  Description

                  Group

                  Supplier

                  Material

                  Scode1

                  Labour1

                  Scode2

                  Labour2

                  Scode3

                  Labour3

                  Scode4

                  Labour4

                  Scode5

                  Labour5

                  A Scode

                  Assembly

                  Replace Cost

                  Total

                  <input type="text" runat="server" style="width: 60px;" id="txtslno_tbl" />

                  <input type="text" runat="server" style="width: 200px;" id="txt_ItemCode_tbl" />

                  <input type="text" runat="server" style="width: 300px;" id="txtDesc_tbl" />

                  <input type="text" runat="server" style="width: 80px;" id="txtGroup_tbl" />

                  <input type="text" runat="server" style="width: 100px;" id="txt_Supplier_tbl" />

                  <input type="text" runat="server" style="width: 100px;" id="txt_Material_tbl" />

                  <input type="text" runat="server" style="width: 100px;" id="txt_SCode1_tbl" />

                  <input type="text" runat="server" style="width: 100px;" id="txt_Labour1_tbl" />

                  <input type="text" runat="server" style="width: 100px;" id="txt_SCode2_tbl" />

                  <input type="text" runat="server" style="width: 100px;" id="txt_Labour2_tbl" />

                  <input type="text" runat="server" style="width: 100px;" id="txt_SCode3_tbl" />

                  <input type="text" runat="server" style="width: 100px;" id="txt_Labour3_tbl" />

                  <input type="text" runat="server" style="width: 100px;" id="txt_SCode4_tbl" />

                  <input type="text" runat="server" style="width: 100px;" id="txt_Labour4_tbl" />

                  <input type="text" runat="server" style="width: 100px;" id="txt_SCode1_tb5" />

                  <input type="text" runat="server" style="width: 100px;" id="txt_Labour1_tb5" />

                  <input type="text" runat="server" style="width: 100px;" id="txt_A_SCode_tbl" />

                  <input type="text" runat="server" style="width: 100px;" id="txt_Assembly_tbl" />

                  <input type="text" runat="server" style="width: 100px;" id="txt_ReplaceCost_tbl" />

                  <input type="text" runat="server" style="width: 100px;" id="txt_Total_tbl" />

            </HeaderTemplate>
          <ItemTemplate>

                <%# Eval("sl_no")%>

                <%# Eval("item_cd")%>

                <input type="text" runat="server" style="width: 290px; text-align: left; height: 13px;"
                       class="fooClass" id="txt_item_desc" value='<%# Eval("item_desc")%>' />

                <input type="text" runat="server" style="width: 70px; text-align: left; height: 13px;"
                       id="txt_gp_cd" value='<%# Eval("gp_cd")%>' />

                <input type="text" runat="server" style="width: 90px; text-align: left; height: 13px;"
                       id="txt_sup_scode" value='<%# Eval("sup_scode")%>' />

                <input type="text" runat="server" style="width: 90px; text-align: right; height: 13px;"
                       maxlength="10" id="txt_material" value='<%# Eval("mtrl_cost")%>' onkeydown='return isNumberKey(event)' />

                <input type="text" runat="server" style="width: 90px; text-align: left; height: 13px;"
                       id="txt_sup_scode1" value='<%# Eval("lbr1_scode")%>' />

                <input type="text" runat="server" style="width: 90px; text-align: right; height: 13px;"
                       maxlength="10" id="txt_labour1" value='<%# Eval("lbr1_cost")%>' onkeydown='return isNumberKey(event)' />

                <input type="text" runat="server" style="width: 90px; text-align: left; height: 13px;"
                       id="txt_sup_scode2" value='<%# Eval("lbr2_scode")%>' />

                <input type="text" runat="server" style="width: 90px; text-align: right; height: 13px;"
                       maxlength="10" id="txt_labour2" value='<%# Eval("lbr2_cost")%>' onkeydown='return isNumberKey(event)' />

                <input type="text" runat="server" style="width: 90px; text-align: left; height: 13px;"
                       id="txt_sup_scode3" value='<%# Eval("lbr3_scode")%>' />

                <input type="text" runat="server" style="width: 90px; text-align: right; height: 13px;"
                       maxlength="10" id="txt_labour3" value='<%# Eval("lbr3_cost")%>' onkeydown='return isNumberKey(event)' />

                <input type="text" runat="server" style="width: 90px; text-align: left; height: 13px;"
                       id="txt_sup_scode4" value='<%# Eval("lbr4_scode")%>' />

                <input type="text" runat="server" style="width: 90px; text-align: right; height: 13px;"
                       maxlength="10" id="txt_labour4" value='<%# Eval("lbr4_cost")%>' onkeydown='return isNumberKey(event)' />

                <input type="text" runat="server" style="width: 90px; text-align: left; height: 13px;"
                       id="txt_sup_scode5" value='<%# Eval("lbr5_scode")%>' />

                <input type="text" runat="server" style="width: 90px; text-align: right; height: 13px;"
                       maxlength="10" id="txt_labour5" value='<%# Eval("lbr5_cost")%>' onkeydown='return isNumberKey(event)' />

                <input type="text" runat="server" style="width: 90px; text-align: left; height: 13px;"
                       id="txt_a_s_scode" value='<%# Eval("assmbly_scode")%>' />

                <input type="text" runat="server" style="width: 90px; text-align: right; height: 13px;"
                       maxlength="10" id="txt_assembly" value='<%# Eval("assmbly_chrge")%>' onkeydown='return isNumberKey(event)' />

                <input type="text" runat="server" style="width: 90px; text-align: right; height: 13px;"
                       maxlength="10" id="txt_replace_cost" value='<%# Eval("replace_cost")%>' onkeydown='return isNumberKey(event)' />

                <%# Eval("purc_rate")%>

          </ItemTemplate>
          <FooterTemplate>

        </FooterTemplate>
  </asp:Repeater>


text:
Q: How to only show dates before character /? I have an array of ISO 8601 dates intervals (start and end date). how do you only select the dates before slash with javascript (start dates)?
var dates = [
2019-12-31T23:45:00.000-03:00/2020-01-01T10:30:00.000+06:00,
2020-01-01T07:15:00.000+07:00/2019-12-31T16:00:00.000-10:00
]

I would like the result to be
[2019-12-31T23:45:00.000-03:00,2020-01-01T07:15:00.000+07:00]

I tried this string-replace method,
let result = dates.replace(/\/.*/g, '');

but it replaces everything after the first bracket.

A: The variables dates is an array, so you should iterate on this.

var dates = [
'2019-12-31T23:45:00.000-03:00/2020-01-01T10:30:00.000+06:00',
'2020-01-01T07:15:00.000+07:00/2019-12-31T16:00:00.000-10:00'
]

// [2019-12-31T23:45:00.000-03:00,2020-01-01T07:15:00.000+07:00]

let result = dates.map(date => date.split('/')[0]);
console.log(result);

But be carefull, in your question, your dates variable is not an array of type string. Maybe it's an array of type Date...

A: I prefer to String.prototype.split() instead of replace. Make an iteration over the array using map(), in every cycle of the iteration split the element (start date / end date) and capture the start date as you expected.

var dates = [
'2019-12-31T23:45:00.000-03:00/2020-01-01T10:30:00.000+06:00',
'2020-01-01T07:15:00.000+07:00/2019-12-31T16:00:00.000-10:00'
]

let results = dates.map(i => i.split('/')[0])

console.log(results)

Output:
[
    "2019-12-31T23:45:00.000-03:00",
    "2020-01-01T07:15:00.000+07:00"
]


text:
Q: .. literalinclude:: from markers I am using python-sphinx for documenting a C code. I am not interested in features offered by doxygen, however I sometime would like to include some snippets from the code-base.
The .. literalinclude:: looks great, but the :lines: option is a bit weak especially if the code is edited afterwards.
I am thinking about a new option such as :marker-start: <<<HERE and :marker-end: <<<END.
What would be the easiest way to achieve this behavior?

A: You can use the start-after and end-before options. Below is an example.
example.txt:
# START
first line
second line
# END
third line

Markup:
.. literalinclude:: example.txt
   :start-after: # START
   :end-before: # END

This will appear in the output:
first line
second line

See https://www.sphinx-doc.org/en/master/usage/restructuredtext/directives.html#directive-literalinclude.


text:
Q: How can I correctly set a nested dict path for a json when querying I am getting the error:
Exception has occurred: KeyError
'Key not exists'
  File "C:\ShopFloor\main.py", line 59, in main
    res = qe.at('vehicledata.result.NUM').where('Status', '=', 1).where('Process', '=', 'SPA').get()
  File "C:\ShopFloor\main.py", line 96, in <module>
    main()

...in the following line:
qe = JsonQ(r"C:\ShopFloor\data.json")
res = qe.at('vehicledata.result.NUM').where('Status', '=', 1).where('Process', '=', 'SPA').get()
pprint(res)
JsonQ.reset(qe)

vehicledata is a string however result.NUM is dynamic, as such there are about 2000 different dicts for result.NUM. My query is aiming at getting all nums where status is 1 and process is SPA: how can I get this to work? I'm thinking it's due to the dynamic dict any help is appreciated
Here is a small sample data from data.json
{
    "vehicledata": [
        {
            "12345678901234567": {
                "Process": "SPA",
                "Status": 0
            }
        },
        {
            "12345678901234567": {
                "Process": "Road",
                "Status": 0
            }
        },

A: Based on the jsonq docs sample you provided you need to change your code to the following:
from pyjsonq import JsonQ
from pprint import pprint
import json

qe = JsonQ("data.json")

res = qe.at('vehicledata').get()
l = list(map(lambda r: r.values()[0], res))
d = {"vehicledata": l}
with open('extarcted_data.json', 'wb') as outfile:
    json.dump(d, outfile)

q = JsonQ("extarcted_data.json")
r = q.at('vehicledata').where('Status', '=', 1).where('Process', '=', 'SPA').get()
print(r)

JsonQ.reset(q)
JsonQ.reset(qe)

The idea is the following you you take all the elements that can change between vehicledata and the object you need. Take the standard json library and wrap your previous object to the new one without extra-layer. After this use JsonQ for convenient search. The code above is the proof of concept and may be not the best solution. Based on the documentation JsonQ doesn't allow skip layers and you have to know your keys in order to retrieve data. In you case you would have to know 12345678901234567 or any number that would be instead of it.
Alternative soltuon
This solution makes usage of JsonQ doubtful. Nevertheless, I will post it here as a reference:
from pyjsonq import JsonQ
from pprint import pprint

qe = JsonQ("data.json")
objs = qe.at('vehicledata').get()

for obj in objs:
    values = obj.values()[0]
    if 'Status' in values and values['Status'] == 1 and 'Process' in values and values['Process'] == 'SPA':
        pprint(values)

JsonQ.reset(qe)

A: Or you can just load it with json package and filter it that way.
import json

with open('data.json', 'r') as f:
    data = json.load(f)

curr_position = data['vehicledata']
result = [key for list_item in curr_position for key in list_item.keys() if list_item[key]['Status'] == 1 and list_item[key]['Process'] == 'SPA']
print(result)

According to the jsonq docs, JsonQ does basically the same thing under the hood.


text:
Q: Zend Framework htaccess Backend / Frontend In my current ZF project, I've two public access points (files) ready to handle & process coming requests, that's: index.php & admin.php
I need all URLs containing '/admin' to be routed to admin.php while any other URLs doesn't contain '/admin' to be routed to index.php
Knowing that default ZF htaccess contains the following rules:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
RewriteRule ^.*$ index.php [NC,L]

How this can be implemented?

A: I want to start by saying that I full heartedly agree with AurelioDeRosa. I do believe that routes will be a better choice. However that is your choice not mine and this .htaccess code should do the trick you want.
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
RewriteRule ^.*(admin).*$ admin.php [NC,L]
RewriteRule ^.*$ index.php [NC,L]

Note however that this script will catch anything that contains admin so it might break your frontend. for example, if you want to list all your users with administrative rights the url yoursite.com/users/listby/admin/ will redirect the request to admin.php, and so will urls like /administrator/ or /adminininini


text:
Q: Java > int to double(Scanner>System.out) It is my first question) Hope someone can help:
I'm trying write next programm:
So i have 1 input and max 2 output
First of all i am checking if input is (int!)
if TRUE i print out message that "YES IT IS INTEGER" and show "saved number in varaible int",
but if i put double, i want to print out message =(" NO it is not INT)  +
and show it in double format!
Everything is ok while i put int but when i put double it is not correct.
public class Scan {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        int check;
            System.out.println("Your number? ");

        if(sc.hasNextInt()){
        check=sc.nextInt();
            System.out.println("OKEI "+check+ " IT IS INTEGER! ");}
        else if(sc.hasNextDouble()){
        check=sc.nextDouble();
            System.out.println("Nooo " + check + " NO it is not INT");
            }
    }

}

A: One solution is having check as a double instead, and change the check to:
if (check == Math.floor(check))

In your solution, you're trying to assign a double to an int. Since it doesn't fit, it'll loose precision and be truncated.
Final solution should look like:
Scanner sc = new Scanner(System.in);
check = sc.nextDouble();
if (check == Math.floor(check)) {
    // an "int"
} else {
    // not integer
}

A: Create a new double variable and assign sc.nextDouble() to that double variable.
Example:
double checkDouble;
....
else if(sc.hasNextDouble()){
    checkDouble=sc.nextDouble();
        System.out.println("Nooo " + check + " NO it is not INT");
        }

A: While trying your code in Eclipse, there was en error using check = sc.nextDouble() (check being an int), you can fix it like that:
  public static void main(final String[] args) {
    System.out.println("Your number? ");
    final Scanner sc = new Scanner(System.in);
    if (sc.hasNextInt()) {
      final int check = sc.nextInt();
      System.out.println("OKEI " + check + " IT IS INTEGER! ");
    } else if (sc.hasNextDouble()) {
      final double check = sc.nextDouble();
      System.out.println("Nooo " + check + " NO it is not INT");
    } else {
      System.out.println("Failed.");
    }
  }

That way, you won't lose any decimal part using Math.floor or a cast.

A: Cast int to double value, It may help.
else if (sc.hasNextDouble()) {
            check = (int) sc.nextDouble();
            System.out.println("Nooo " + check + " NO it is not INT");
        }


text:
Q: Where are Settings values saved in QML? I am using QtCreator for a C++/QML application. I want to save some application settings and I reached this goal using a code that is very similar to the documentation at this link.
...
import Qt.labs.settings 1.0

Settings {
    id: settingsValues
    property int sliderValue: 300000
    property bool checkBoxChecked: true
}
...

Questions
1) Where are these values saved? Maybe is there a file generated expressly for storing these variables? How can I retrieve this file?
2) How the application knows that it has to load these values?

A: Question 1 is answered by the documentation:

The information is stored in the system registry on Windows, and in XML preferences files on macOS. On other Unix systems, in the absence of a standard, INI text files are used. See QSettings documentation for more details.

Question 2: If they exist in the settings, they will be loaded.
The relevant code is (Line 311 as of writing). The if clause decides whether the application loads that value or not:
if (!currentValue.isNull() && (!previousValue.isValid()
        || (currentValue.canConvert(previousValue.type()) && previousValue != currentValue))) {
    property.write(q, currentValue);
    qCDebug(lcSettings) << "QQmlSettings: load" << property.name() << "setting:" << currentValue << "default:" << previousValue;
}

A: I chose to leave the answer of @derM as accepted answer because it was very helpful for the question 2.
Nevertheless I post this answer because it is the correct answer for the question 1 in my situation.
I am using QtCreator on Ubuntu 16.04, so I found the configuration file at the following path:

default_Directory_Of_My_Project/.config/Unknown Organization/myProject.conf

A: I'm on macOS and I did search everywhere I could in my user directory, but never found it.
My code is:
Settings {
        id: settings
        fileName: "settings"
        property alias x: root.x
        property alias y: root.y
}

Finally I found it inside my build directory (to be precise, the path set in Projects > Build Settings > Build directory)
the in the .app/Contents/MacOS/
and the file is named as fileName property (so settings.xml for me)
To recap, on macOS: build_directory/XXX.app/Contents/MacOS/fileName
(for me: XXX.app/Contents/MacOS/settings)


text:
Q: Find index of EditorFor template I have an EditorFor template that looks like this,
@{
Layout = null;

@Html.EditorFor(model => model.Name)
@Html.EditorFor(model => model.Value)

}

for a List of Key/Value pairs.  Here is the Model.
public List<NameValuePair> Parameters { get; set; }

This produces a list of editable boxes. I need to delete a particular element (so when the page refreshes the whole "row" is gone).  I am having trouble finding the index of that element to pass to the delete function in my controller.  Is there an easy way to find a particular index in a EditorFor template?
Update--
This is what the code in the view looks like.  Which displays the list of parameters.
@Html.LabelFor(model => model.Parameters)
@Html.EditorFor(model => model.Parameters)
    <input type="submit" name="command" value="addParam" class="btn btn-default btn-primary" />

And this is what the delete method I am attempting to use in the controller looks like.
public ActionResult DeleteParamaters(long id, int index)
    {
        var templateStep = Biz.GetTemplateStep(id);

        templateStep.Parameters.RemoveAt(index);
        return View("CreateTemplateStep", templateStep);
    }

My end goal is a delete button next to each list item, and when clicked will delete that particular item from the list.

A: You can pass an additionalViewValues object to the EditorFor function.

An anonymous object that can contain additional view data that will be
  merged into the ViewDataDictionary instance that is created
  for the template.

So when you iterate over your list and renders the editor for each then you can pass any data to the template and so you can send it to the controller to identify your data.
There are couple of examples on SO about how to use additional data across templates. For example: Pass Additional ViewData to a Strongly-Typed Partial View


text:
Q: equinox with slf4j can't find logback provider So I have this OSGi project built with equinox with this gradle structure:
> Task :projects

------------------------------------------------------------
Root project 'project'
------------------------------------------------------------

Root project 'project'
No sub-projects

Included builds
+--- Included build ':callable-processor'
+--- Included build ':osgi-sun-misc'
+--- Included build ':path-collector'
+--- Included build ':robot-api'
+--- Included build ':robot-equinox'
+--- Included build ':robot-signal'
+--- Included build ':robot-instance'
+--- Included build ':utils'
\--- Included build ':reactive'

Main bundle is robot-equinox.
On the root (project), I have the following build.gradle configuration:
// project

ext.baseVersion = '2.0.0'
ext.buildTag = "SNAPSHOT"

group 'project'
version "${baseVersion}-${buildTag}"

project {
    quality = ALFA
}

configurations {
    bundleInstall
    bundleStart
    misc
}

dependencies {
    bundleInstall 'ch.qos.logback:logback-classic:1.3.5'
    bundleInstall 'ch.qos.logback:logback-core:1.3.5'
    bundleInstall 'org.slf4j:slf4j-api:2.0.5'

    bundleInstall 'org.apache.aries.spifly:org.apache.aries.spifly.dynamic.bundle:1.3.5'

    bundleInstall 'prodist:callable-processor'
    bundleInstall 'prodist:osgi-sun-misc'
    bundleInstall 'prodist:path-collector'
    bundleInstall 'prodist:reactive'
    bundleInstall 'prodist:robot-api'

    bundleStart 'ch.qos.logback:logback-classic:1.3.5'
    bundleStart 'ch.qos.logback:logback-core:1.3.5'
    bundleStart 'org.slf4j:slf4j-api:2.0.5'
    bundleStart 'prodist:robot-equinox'
}

And under robot-equinox I have the following configuration:
dependencies {
    implementation group: 'prodist', name: 'callable-processor'
    implementation group: 'prodist', name: 'path-collector'
    implementation group: 'prodist', name: 'robot-api'
    implementation group: 'prodist', name: 'reactive'
    implementation group: 'prodist', name: 'robot-instance'
    implementation group: 'prodist', name: 'utils'

    compileOnly group: 'org.osgi', name: 'osgi.core', version: '6.0.0'

    testImplementation group: 'org.hamcrest', name: 'hamcrest', version: '2.2'
    testImplementation group: 'org.mockito', name: 'mockito-core', version: '3.2.4'
    testImplementation group: 'org.reactivestreams', name: 'reactive-streams-tck', version: '1.0.3'
    testImplementation group: 'org.testng', name: 'testng', version: '7.1.0'

    testCompileOnly group: 'org.osgi', name: 'osgi.core', version: '6.0.0'
}

I'll give a sample of my log implementation on the main class, which is present under 'project'.
Application.java

package project.robot.equinox;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.*;
import java.security.SecureRandom;
import java.util.*;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.IntStream;

import org.osgi.framework.BundleContext;
import org.osgi.framework.BundleException;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;

public class Application {

    private static final Logger logger = LoggerFactory.getLogger(Application.class);

    public Application ()
    {
        MDC.put("product.name", ProductInfo.getName());
        MDC.put("product.version", ProductInfo.getVersion());
    }

    public void activate (BundleContext bundleContext)
    {
        logger.atTrace().log(_S("activate: enter"));
    }

    ...
}

But when I start the Application, I'm getting this message on the osgi console:
osgi> SLF4J: No SLF4J providers were found.
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See https://www.slf4j.org/codes.html#noProviders for further details.

My expectation was that by installing both - slf4j and logback, slf4j would recognize logback implementation and would work.
How can I solve this problem?

A: Ok, so I found a solution and I'm going to post it here so it help someone else facing this same issue.
In order to help SLF4J find his provider, I create a new bundle osgi-log - a "log bundle" with this configuration:
group 'project'
version '2.0.0'

dependencies {
    api group: 'org.slf4j', name: 'slf4j-api', version: '2.0.5'

    implementation group: 'ch.qos.logback', name: 'logback-classic', version: '1.3.5'
    implementation group: 'ch.qos.logback', name: 'logback-core', version: '1.3.5'
    implementation group: 'org.ow2.asm', name: 'asm', version: '5.2'
    implementation group: 'org.ow2.asm', name: 'asm-commons', version: '5.2'
    implementation group: 'org.ow2.asm', name: 'asm-util', version: '5.2'
    implementation group: 'org.apache.aries.spifly', name: 'org.apache.aries.spifly.dynamic.bundle', version: '1.3.5'
}

And then, in each bundle who uses log, I added the following dependency:
dependencies {
    (...)

    implementation group: 'project', name: 'osgi-log'
}

And when I started my application, the message about provider was gone and log was being registered as expected.
I came to conclusion that Apache Aries spifly offers a ServiceLoader to SLF4J and helps him find provider, which in my case is logback.


text:
Q: Put loading in email sending I have email function that send 5 person at one time. I call this function in controller called submitemail. I want to put loading when the email function triggered. I want to show message to user that email sending is successful or not. How to do it?

A: Call your controller's action with ajax...show a loading image before ajax call...and hide the loading image in oncomplete event of ajax function...and also show appropriate success and error message.

A: You can use
@using (Ajax.BeginForm("ActionName", null, new AjaxOptions
            {UpdateTargetId = "dialog-model", InsertionMode = InsertionMode.Replace
            }, new { id ="AjaxForm" }))
{
...form here
}

AjaxOptions is an object that can get succes in succes you can show message
new AjaxOptions()
 {
     UpdateTargetId = "divPlaceholder",
     InsertionMode = InsertionMode.Replace,
     OnSuccess = "alert('OnSuccess')",
     OnBegin = "alert('OnBegin')",
     OnComplete = "alert('OnComplete')",
     OnFailure = "alert('OnFailure')"

 }


text:
Q: Rendering Data in Table After each record processing completes I am creating a Spring MVC3 base web application .
The application takes as an input two Dates .
Now for all the records which lies in that date Range , I need to run the compare utility that I have written and will display the comparison result on GUI .
Now , the number of records is fairly large. Hence I don't want that user waits untill application get processed .
Instead I want to display the comparison result on GUI, as soon as it gets finished for the record.
Please suggest , efficient way to do this.


text:
Q: How to strip out 0x0a special char from utf8 file using c# and keep file as utf8? The following is a line from a UTF-8 file from which I am trying to remove the special char (0X0A), which shows up as a black diamond with a question mark below:

2464577 外國法譯評 True    s6620178    Unspecified <1>�1009-672

This is generated when SSIS reads a SQL table then writes out, using a flat file mgr set to code page 65001.
When I open the file up in Notepad++, displays as 0X0A.
I'm looking for some C# code to definitely strip that char out and replace it with either nothing or a blank space.
Here's what I have tried:
        string fileLocation = "c:\\MyFile.txt";
        var content = string.Empty;
        using (StreamReader reader = new System.IO.StreamReader(fileLocation))
        {
            content = reader.ReadToEnd();
            reader.Close();
        }

        content = content.Replace('\u00A0', ' ');
        //also tried: content.Replace((char)0X0A, ' ');
        //also tried: content.Replace((char)0X0A, '');
        //also tried: content.Replace((char)0X0A, (char)'\0');
        Encoding encoding = Encoding.UTF8;
        using (FileStream stream = new FileStream(fileLocation, FileMode.Create))
        {
          using (BinaryWriter writer = new BinaryWriter(stream, encoding))
          {
            writer.Write(encoding.GetPreamble()); //This is for writing the BOM
            writer.Write(content);
          }
        }

I also tried this code to get the actual string value:
byte[] bytes = { 0x0A };
string text = Encoding.UTF8.GetString(bytes);

And it comes back as "\n". So in the code above I also tried replacing "\n" with " ", both in double quotes and single quotes, but still no change.
At this point I'm out of ideas. Anyone got any advice?
Thanks.

A: may wanna have a look at regex replacement, for a good example of this, take a look at the post towards the bottom of this page...
    http://social.msdn.microsoft.com/Forums/en-US/1b523d24-dab6-4870-a9ca-5d313d1ee602/invalid-character-returned-from-webservice

A: You can convert the string to a char array and loop through the array.
Then check what char the black diamond is and just remove it.

A: string content = "blahblah" + (char)10 + "blahblah";

char find = (char)10;

content = content.Replace(find.ToString(), "");


text:
Q: SQL SELECT multiple conditions many to many relationship I am struggling to find an elegant solution to this problem.
I have 5 tables and their relationships are described in the image.

A page can have multiple products and each product can have many ProductRates. A Page with specific Product could have many rates as well. To get around the many to many issue there is table PageToProductToRate.
Users want to query on multiple conditions where the selection could be combination of any:

*

*Product1 + Rate1 + rate attribute1

*Product1 + Rate1 + rate attribute2

*Product1 + Rate2 + rate attribute2

*Product2 + Rate3 + rate attribute1   etc...

This is an example of data and WHERE condition and expected results:

And another:

The query that works for me uses INTERSECT to get the right results. I tried UNION but would get results not matching all of the conditions.
SELECT DISTINCT P.[PageID]
FROM [Page] P
  join PageToProduct p2p on p2p.[PageID] = P.[PageID]
  join Product pr on p2p.[Product] = pr.[Product]
  join PageToProductToRate p2p2r on p2p2r.[PageToProductID] = p2p.[PageToProductID]
  join ProductRates r on r.[ProductRatesID] = p2p2r.[ProductRatesID]
  WHERE (PR.[Product] = 'ALMOND' AND R.CommissionType = 'PREMIUM' AND R.Rate = 0.25)
INTERSECT
SELECT DISTINCT P.[PageID]
FROM [Page] P
  join PageToProduct p2p on p2p.[PageID] = P.[PageID]
  join Product pr on p2p.[Product] = pr.[Product]
  join PageToProductToRate p2p2r on p2p2r.[PageToProductID] = p2p.[PageToProductID]
  join ProductRates r on r.[ProductRatesID] = p2p2r.[ProductRatesID]
  WHERE (PR.[Product] = 'WALNUT' AND R.CommissionType = 'SERVICE FEE' AND R.Rate = 1.25)
INTERSECT
SELECT DISTINCT P.[PageID]
FROM [Page] P
  join PageToProduct p2p on p2p.[PageID] = P.[PageID]
  join Product pr on p2p.[Product] = pr.[Product]
  join PageToProductToRate p2p2r on p2p2r.[PageToProductID] = p2p.[PageToProductID]
  join ProductRates r on r.[ProductRatesID] = p2p2r.[ProductRatesID]
  WHERE (PR.[Product] = 'HAZELNUT' AND R.CommissionType = 'EXCESS' AND R.Rate = 1.68)

Is there a better way of going on around this problem? I could potentially have over a dozen of these conditions and the query with all the joins could get out of the control.

A: SELECT p2p.PageID
FROM
    PageToProduct as p2p
    inner join Product as pr
        on p2p.Product = pr.Product
    inner join PageToProductToRate as p2p2r
        on p2p2r.PageToProductID = p2p.PageToProductID
    inner join ProductRates as r
        on r.ProductRatesID = p2p2r.ProductRatesID
WHERE
          (pr.Product = 'ALMOND' AND r.CommissionType = 'PREMIUM' AND r.Rate = 0.25)
      OR  (pr.Product = 'WALNUT' AND r.CommissionType = 'SERVICE FEE' AND r.Rate = 1.25)
      OR  (pr.Product = 'HAZELNUT' AND r.CommissionType = 'EXCESS' AND r.Rate = 1.68)
GROUP BY p2p.PageID
HAVING COUNT(*) = 3; /* requires all three are present, as long as no rows are duplicate */

A: My best guess.
WITH products AS
(
    SELECT  [Product],
            [ProductRatesID]
    FROM    Product p
            JOIN ProductRates pr ON p.[Product] = pr.[Product]
    WHERE   (p.[Product] = 'ALMOND' AND pr.CommissionType = 'PREMIUM' AND pr.Rate = 0.25)
            OR (p.[Product] = 'WALNUT' AND pr.CommissionType = 'SERVICE FEE' AND pr.Rate = 1.25)
            OR (p.[Product] = 'HAZELNUT' AND pr.CommissionType = 'EXCESS' AND pr.Rate = 1.68)
)
SELECT  P.[PageID]
FROM    [Page] P
        JOIN (
            SELECT  p2p.[PageID], COUNT(*) as ProductCount
            FROM    products pr
                    JOIN PageToProduct p2p ON p2p.[Product] = pr.[Product]
                    JOIN PageToProductToRate p2p2r on p2p2r.[PageToProductID] = p2p.[PageToProductID]
            WHERE   p2p2r.[ProductRatesID] = pr.[ProductRatesID]
            GROUP BY p2p.[PageID]
        ) sq ON sq.[PageID] = p.[PageID]
WHERE   sq.ProductCount = @ProductFilterCount

You'll need to figure out how you want to handle @ProductFilterCount.  It can either be a count of the number filters you're using, or the number of products that actually match those filters
SQL Fiddle

A: I'm not sure what you're asking.. but if you want pages that have product selections then this might work, you'll have to test yourself though
edit- changed to AND because he wants all conditions met
SELECT DISTINCT P.[PageID]
FROM [Page] P
  join PageToProduct p2p on p2p.[PageID] = P.[PageID]
  join Product pr on p2p.[Product] = pr.[Product]
  join PageToProductToRate p2p2r on p2p2r.[PageToProductID] = p2p.[PageToProductID]
  join ProductRates r on r.[ProductRatesID] = p2p2r.[ProductRatesID]
  WHERE (PR.[Product] = 'ALMOND' AND R.CommissionType = 'PREMIUM' AND R.Rate = 0.25)
  AND (PR.[Product] = 'WALNUT' AND R.CommissionType = 'SERVICE FEE' AND R.Rate = 1.25)
  AND (PR.[Product] = 'HAZELNUT' AND R.CommissionType = 'EXCESS' AND R.Rate = 1.68)


text:
Q: Async map for Play Framework Node.js has one thing like this async modules.
Does anyone know - how to organize something like this :
async.map(['file1','file2','file3'], fs.stat, function(err, results){
      // results is now an array of stats for each file
});

Currently I'm using a Play Framework/Scala

A: Provided you find the equivalent of fs.stat (I don't think it is the purpose of your question), you can use Parallel Collections. You would get something like this:
Vector("file1","file2","file3").par.map(f => function(fs.stat(f)))


text:
Q: .less: not to compile variable file On windows I'm using WinLESS to compile my .less files but I've come across a minor issue.
I have several files which import my core variables.less file. It has nothing but variables. When WinLESS compiles, it generates a blank variables.css file as well. Is there a way to stop this blank file from being created?

A: If you have the latest version (1.3.0) then No, I'm afraid there isn't.
But you should raise a bug on https://github.com/dotless/dotless
I am a developer their and I'll look at it soon..
[Edit]
There is some wanted behaviour - if you change a file and it goes from being non-empty to empty, you would want it to update. However if the input file is a wildcard AND the output is empty AND the file doesn't exist, maybe it shouldn't be created.
What if there is just a bug in the less file causing it to output nothing? But this discussion should be moved to a github bug.

A: Are you sure your file is unchecked in winless window?
I use it as in the screenshot below and don't get empty files.


text:
Q: Is there a modern Process Manager supporting things like grouping (Imagine tens of chrome.exe's)?
Possible Duplicate:
Good Alternatives to Windows Task Manager

Hi,
I am tired of using Windows Task Manager. Whenever I look at it, I see tens of Chrome.exe processes there. I am hoping to find a better process manager that is tailored for modern scenarios. I'd like it to group processes with the same name, give the ability to kill the entire group and maybe more.
Is there such a process manager?

A: Process Explorer (part of Windows Sysinternals) does a good job of process management.

A: Process Explorer from Microsoft/Sysinternals will do this, but if you're aiming to reduce clutter, it may still not be ideal for you.  It should allow you to collapse all the chrome processes as they should all have a common parent.


text:
Q: Problema com loop em array - JavaScript Quando tento executar o loop, nem se quer entrar no for, já verifiquei e o array com o objeto não está vazio, mas não executa o loop... Alguma ideia?
var caminho = [];

$.get("http://localhost/crocs/arquivo.json", function(data) {

    data = typeof data == 'string' ? JSON.parse(data) : data;

    data.forEach(function(elementoDaArray) {

        skuid = elementoDaArray.SkuId;
        valor = elementoDaArray.Valor;
        letra = elementoDaArray.Letra;
        imagem = elementoDaArray.Imagem;

        caminho.push({
            img: imagem,
            id: skuid
        })
    });
});

for (var i = 0; i < caminho.length; i++) {
    console.log(products[i].img);
}

A: $.get é uma função assíncrona, ela demora um tempo para buscar a resposta do seu endereço, mas o código não espera a função terminar para continuar rodando.
No caso, você está chamando $.get, e então tentando ler o array antes mesmo de preenche-lo, se você quiser continuar com o seu código apenas depois de receber a resposta de $.get, coloque seu loop dentro da função.
Outras alternativas são trabalhar com callbacks ou promises.


text:
Q: How to change background color of elements in ListView(data from ContentProvider)? I need to change the background color of elements in ListView depends on their status.
lvLinks.getCount() returns the correct value. "If-else" and logs works correctly also. But it doesn't work (doesn't change color of background). Please, help me! Hope you will understand my code.
final Uri CONTACT_URI = Uri.parse("content://com.application.provider.LinkProvider/links");
ListView lvLinks;
Cursor cursor;
SimpleCursorAdapter adapter;

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.history);

    lvLinks = (ListView) findViewById(R.id.lvLinks);
    showListView(null);
    setBackgroundColor();
    lvLinks.setOnItemClickListener(this);
}

public void showListView(String order){
    cursor = getContentResolver().query(CONTACT_URI, null, null,
            null, order);
    startManagingCursor(cursor);

    int to[] = { android.R.id.text1, android.R.id.text2 };
    String from[] = {"ref" , "status"};
    adapter = new SimpleCursorAdapter(this,
            android.R.layout.simple_list_item_2, cursor, from, to);
    lvLinks.setAdapter(adapter);

}

public void setBackgroundColor(){

    for(int i = 0; i < lvLinks.getCount(); i++){
        View v = lvLinks.getAdapter().getView(i, null, null);
        Cursor cursor = (Cursor) lvLinks.getItemAtPosition(i);
        int status = cursor.getInt(cursor.getColumnIndexOrThrow("status"));
        Log.d("MYTAG", String.valueOf(status));
        if (status == 1){
            v.setBackgroundColor(Color.GREEN);
            Log.d("MYTAG", "GREEN");
        } else if (status == 2){
            v.setBackgroundColor(Color.RED);
            Log.d("MYTAG", "RED");
        } else if (status == 3){
            v.setBackgroundColor(Color.GRAY);
            Log.d("MYTAG", "GRAY");
        }
    }
}

A: First: Your adapter should be handling setting the backgroud color of the view when you bind the contact data to that row. SimpleCursorAdapter has no logic to do this. You should extend CursorAdapter and implement bindView() to handle this the way you want.
Second: startManagingCursor() is deprecated. Learn to use the Loader framework, specifically CursorLoader.


text:
Q: Is it possible to allow a path/item to be clicked through? If I have two paths/items with fills (Path A, and Path B), and Path A is on top of Path B... is there a way to allow you to click through Path A and get the Path B click handler to fire?
Example here. I want to be able to see the "bottom clicked" log when clicking on the overlapped corner of topPath.

A: DEMO
http://paperjs.org/reference/path/#locked

Specifies whether the item is locked. When set to true, item interactions with the mouse are disabled.

const bottom = new Rectangle(new Point(10,10), new Point(100,100));
const bottomPath = new Path.Rectangle(bottom);
bottomPath.fillColor = '#999999';
bottomPath.onClick = () => console.log('bottom clicked');

const top = new Rectangle(new Point(60,60), new Point(150,150));
const topPath = new Path.Rectangle({
    rectangle: top,
    locked: true
});
topPath.fillColor = '#cccccc';


text:
Q: How to use RDC with VirtualBox and OSX I'm trying to do some local RDC testing using VirtualBox.  The host is OSX.8, the VM is ubuntu, and VirtualBox is version 4.1.22.
The VM starts fine without any problems.  I shut it down and choose "Enable Server" from the Remote Display section of the Display options and start again, and again it starts fine. Note that the port is left default and the authentication is "null".
I start Microsoft's RDC (v2.1.0) and type in 'localhost' and get: You were disconnected from the Windows-based computer because of network problems.
I try 127.0.0.1 and get the same error.  Then I type in the IP of my (host) computer and get the same error.  I know the loopback address avoids the firewall but I turned it off anyway and got the same error.
I get the same error whether I'm using NAT networking or bridged.  What am I doing wrong?
I should note that this is a vanilla install of VirtualBox and I haven't added any extensions or guest additions or anything like that.
Seems I'm doing everything right.  What am I missing? Thanks for the help!

A: Problem Solved! You have to install the "VirtualBox 4.1.22 Oracle VM VirtualBox Extension Pack" (available on the VB download page) to make RDC work.  I wish it would tell you this when you click "enable server" but I guess that's asking too much.  I hope this helps someone else.


text:
Q: Как установить пароль на сайт которий лежит на хостинге? Как установить пароль на сайт которий лежит на хостинге?
На сервере установлен Ubuntu с apache

A: Создай файл с паролем
htpasswd -c /home/username/example.com/.htpasswd user1
chmod 644 .htpasswd

получится такого вида: user1:$apr1$bkS4zPQl$SyGLA9oP75L5uM5GHpe9A2
Создай файл с правилом .htaccess с таким содержимым
#Protect Directory
AuthName "Введите пароль"
AuthType Basic
AuthUserFile /home/username/example.com/.htpasswd
Require valid-user


text:
Q: Efficient way to fill Numpy Array I'm looking for a more efficient way to fill a 2d numpy array than a double for-loop. The issue I am having is that the array values are dependent on several other arrays.
In the following code k and d are integers, and y and result are arrays. Any help would be greatly appreciated.
for i in xrange(1,d):
    for j in xrange(k-i-1, k+1):
        result[j][i] = ((x - y[j])/(y[j+i] - y[j]))*result[j,i-1] + ((y[j+i+1]-x)/(y[j+i+1] - y[j+1]))*result[j+1,i-1]

A: You seem to be updating your result array one column at a time, using data from the previously updated column. That makes it hard to vectorize the outer loop, I don't think you can do it unless there is some structure to your data that can be exploited. The inner loop is very straightforward to vectorize:
for i in xrange(1, d):
    j = np.arange(k-i-1, k+1)
    result[j, i] = ((x - y[j]) / (y[j+i] - y[j]) * result[j, i-1] +
                    (y[j+i+1] - x) / (y[j+i+1] - y[j+1]) * result[j+1, i-1])

There is some marginal improvement you could get by defining a base_j = np.arange(k-d-2, k+1) array outside the loop, and then slicing it inside the loop with something like j = base_j[d-i+1:].

A: You can get rid of the inner loop via clever broadcasting
tmp = ((x - y[k-i+1:k+1])/(y[k+1:k+1+i] - y[j]))*result[k-i+1:k+1,i-1] + ((y[k+2:k+i+2]-x)/(y[k+2:k+i+2] - y[k-i+2:k+2]))*result[k-i+2:k+2,i-1]
result[k-i+1:k+1, i] = tmp

but because you bounds in the inner loop depend on the outer-loop you can not remove it through broadcasting as well.
I used tmp in an overabundance of caution


text:
Q: Make a folder for the files placed in ListView Whats the procedure to send the files placed in a ListView to a folder.
I need to place all the files in the ListView to a folder on button click event. On button click it should make a folder for all the files in the list view and send them in.
I'm using Winforms in C#.

A: To check if the directory exists, use Directory.Exists Method .
To create the directory if it does not exist, use Directory.CreateDirectory Method.
To get all files in a directory, use Directory.GetFiles Method (String, String).
To move files, use File.Move Method .
To copy files, use File.Copy Method

A: *

*Use Directory.CreateDirectory Method to create a folder.

*Then use FileStream class to create new file in that folder.

*Copy the contents/data of the file from database to the file stream

*When finished close the file stream.

*Repeat 2-4 for each file.


text:
Q: junk characters coming when i export Azure Databricks(ADB) table data in excel When i see my table data in azure databricks , data looks fine.
But when i Export the same data in Excel , i can see some junk characters coming
in databricks -
23/5 DELHI - MATHURA
in excel -
23/5  DELHI - MATHURA
how to make sure that junk character -> Â does not come in excel , i want to do change on databricks side , not on excel side , as excel is just displaying the data.

A: I was able to solve this myself . thing is in spark junk characters are not visible in the output window , but when i download excel , i could see junk characters in them.
since i was getting a junk character at a position where there was empty space visible , so i copied that space and put it in notepad++/google , to check its unicode value , i was able to found the unicode value .
then in source file from where table is getting populated , i replaced that unicode value in whole file


text:
Q: Finding daily maximum and its time-stamp (yyyy:mm:dd hh:mm:ss) in Python Pandas I actually have a 150 MB data of daily minute-wise measurements for everyday for two years. I have given here a sample data. I want to create a new data frame with maximum of each day with its time-stamp.
My sample data is:
    DateTime            Power
01-Aug-16 10:43:00.000  229.9607961
01-Aug-16 10:43:23.000  230.9030781
01-Aug-16 10:44:00.000  231.716212
01-Aug-16 10:45:00.000  232.4485882
01-Aug-16 10:46:00.000  233.2739154
02-Aug-16 09:42:00.000  229.6851724
02-Aug-16 09:43:00.000  230.9163998
02-Aug-16 09:43:06.000  230.9883337
02-Aug-16 09:44:00.000  231.2569098
02-Aug-16 09:49:00.000  229.5774805
02-Aug-16 09:50:00.000  229.8758693
02-Aug-16 09:51:00.000  229.9825204
03-Aug-16 10:09:00.000  231.3605982
03-Aug-16 10:10:00.000  231.6827163
03-Aug-16 10:11:00.000  231.1580262
03-Aug-16 10:12:00.000  230.4054286
03-Aug-16 10:13:00.000  229.6507959
03-Aug-16 10:13:02.000  229.6268353
03-Aug-16 10:14:00.000  230.4584964
03-Aug-16 10:15:00.000  230.9004206
03-Aug-16 10:16:00.000  231.189036

My present code is:
max_per_day = df.groupby(pd.Grouper(key='time',freq='D')).max()
print(max_per_day)

My present output is:
    time
2016-08-01  237.243835
2016-08-02  239.658539
2016-08-03  237.424683
2016-08-04  236.790695
2016-08-05  240.163910

Presently it outputs yyyy:mm:dd and value. But I want even hh:mm (or hh:mm:ss) against each maximum value. I tried following code:
max_pmpp_day = df.loc[df.groupby(pd.Grouper(freq='D')).idxmax().iloc[:,0]]

The output is:
 TypeError: Only valid with DatetimeIndex, TimedeltaIndex or PeriodIndex, but got an instance of 'Int64Index'

I tried @jezrael answer
df['DateTime'] = pd.to_datetime(df['time'])
s = df.groupby(pd.Grouper(key='DateTime', freq='D'))['Pmpp'].transform('max')
df = df[df['Pmpp'] == s]
print(df)

and output is
                     time        Pmpp            DateTime
34    2016-08-01 11:11:00  237.243835 2016-08-01 11:11:00
434   2016-08-02 13:30:02  239.658539 2016-08-02 13:30:02
648   2016-08-03 12:39:00  237.424683 2016-08-03 12:39:00

A: You can use GroupBy.transform or Resampler.transform for return max values in new Series and compare with original column:
df['DateTime'] = pd.to_datetime(df['DateTime'])
s = df.groupby(pd.Grouper(key='DateTime', freq='D'))['Power'].transform('max')
#alternative
#s = df.resample('D', on='DateTime')['Power'].transform('max')
df = df[df['Power'] == s]
print (df)
              DateTime       Power
4  2016-08-01 10:46:00  233.273915
8  2016-08-02 09:44:00  231.256910
13 2016-08-03 10:10:00  231.682716

Or create DatetimeIndex and add column after groupby for check idxmax:
df['DateTime'] = pd.to_datetime(df['DateTime'])
df = df.set_index('DateTime')
df = df.loc[df.groupby(pd.Grouper(freq='D'))['Power'].idxmax()]
print (df)
                          Power
DateTime
2016-08-01 10:46:00  233.273915
2016-08-02 09:44:00  231.256910
2016-08-03 10:10:00  231.682716

Solution of @Jon Clements, thank you:
df = (df.sort_values('Power')
        .groupby(df.DateTime.dt.to_period('D'))
        .last()
        .reset_index(drop=True))


text:
Q: Meteor mongodb: how to get the N th records? I can't find anywhere it has been documented this. By default, the find() operation will get the records from beginning. How can I get the  N th records in meteor mongodb?
for eg : i want to second last record !!

A: You can use the skip option as described here.
Try the following code:
CollectionName.find({...}, {skip : N});


text:
Q: Firebase cloud function; unable to reach firestore database I have a firebase cloud function (http request) in which I want to update a document in my firestore database
const functions = require('firebase-functions')
const admin = require('firebase-admin');
admin.initializeApp();

exports.webhook = functions.https.onRequest(async (req, res) => {
const { id } = req.body

// Create payment
exports.webhook = functions.https.onRequest(async (req, res) => {
    const { id } = req.body

    // Create payment
    try {
      console.log(id)
      console.log('test before db call')

      admin.firestore().collection('payments').doc(id).update(
        {
            status: "paid"
        }
      ).then(() => {
          console.log('success')
      })

      console.log('test after db call')

      res.send('ok')
    } catch (e) {
      res.send('not ok')
    }
  })

Function is deploying, console.log(id) is correct but whenever I call admin.firestore() it doesn't print anything anymore.
Commenting that part prints 'promise resolved'
I have the impression I can't access or use wrong syntax to get to the Firestore db but I can't see why?
Firebase logs are printing:

Function execution started
tr_........ (id)
test before db call
Function execution took 1103 ms, finished with status code: 200

A: You're not using the promise returned by update() correctly.  You need to wait until that promise is resolved before sending the response.  Right now, you are sending the response without waiting for the database update to complete, which means the Cloud Functions could shut down all the asynchronous work after it returns.  then does not block your code.  It merely lets you add a callback to the async work.  You should only sent the response after completion:
  admin.firestore().collection('payments').doc(id).update(
    {
        status: "paid"
    }
  ).then(() => {
      console.log('success')
      res.send('ok')    // send response here
  })


text:
Q: Detect if a 32bit process is running in a 64bit environment under Linux I am distributing a 32bit build of a piece of software.  I want to detect at runtime whether the userland it's running under is 64bit, and capable of running 64bit executable binaries (ELF 64-bit x86-64).
This isn't the same problem as detecting at compile-time whether an architecture is 32bit or 64bit.
I would ideally like to do this in the most portable way possible, so would prefer to avoid doing things like file $(which init) | grep x86-64 which depend on
I don't think reading cpuid is a solution either - it's possible to have a 32bit OS running on a 64bit CPU.
Detecting a 64bit cpu running in long mode doesn't seem to be a solution either, nor does detecting whether the kernel itself is 64bit, as there is the possibility that the OS is a 32bit userland with a 64bit kernel (as is possible with some Debian configurations).
I'm not primarily interested in detecting bitness other than 32 & 64.
One possible robust solution I can think of is to actually include and attempt to call a 64bit ELF binary and see if it runs or not, but this doesn't feel like a very efficient way to do it.  Is there a linux function or something in the stl or boost that could help me find out reliably?
Ironically, for once the equivalent problem is very easy to solve under Windows.

A: You could test for the presence of /lib64/ld-linux-x86-64.so.2. Theoretically this doesn't always work because it's possible for a Linux system to put the dynamic linker somewhere else, but this particular path is by far the most common, plus the path to the dynamic linker is hardcoded into ELF binaries, so this works at least as well as actually bundling a 64-bit library with your software (provided there's a matching libc, anyway).


text:
Q: Can't set image to fit whole div I've wanted to create some header for my website, but I actually can't set background image properly. I'd like from my background image to fill whole header div, but it's actually doesn't even fit whole div. What should I do with it? (Please don't blame me about code quality :D)
HTML
    <!DOCTYPE html>

      <link

 href="css.css" rel="stylesheet" type="text/css"/>

LoremIpsum

LoremIpsum

LoremIpsum

CSS
    body{
    background-color:#666766;
}

.headerContainer{

    height:100vh;
    border:solid 2px;
    background-image:url("https://i2.wp.com/oddshjelpen.com/wp-content/uploads/2018/08/350851-download-free-website-background-1920x1080-for-mobile-hd.jpg?ssl=1");
    background-size: contain;
  background-position: left-top;
  background-repeat:no-repeat;

}
.headerCol1{
    height:100px;
    width:600px;
    background-color:yellow;
    margin:0 auto;
}
.headerCol1 h1{
    text-align:center;
    font-size:40px;
    padding:15px;

    font-size:72px;
    letter-spacing:15px;

}

.headerCol2{
    height:70px;
    width:500px;
    background-color:yellow;
    margin-top:150px;
    float:right;
}

.headerCol2 h1{
    margin:0;
    padding:0;
    text-align:center;
    position:relative;
    top:50%;
    transform:translateY(-50%);
    font-size:62px;

}

.headerCol3{
    height:65px;
    width:550px;
    background-color:yellow;
    margin-top:20px;
    float:right;
}
.headerCol3 h1{
    margin:0;
    padding:0;
    text-align:center;
    position:relative;
    top:50%;
    transform:translateY(-50%);
    font-size:56px;
}

https://jsfiddle.net/48t7xLrg/

A: You have to update background-size to cover Update below css.
.headerContainer {
    height: 100vh;
    border: solid 2px;
    background-image: url(https://i2.wp.com/oddshjelpen.com/wp-content/uploads/2018/08/350851-download-free-website-background-1920x1080-for-mobile-hd.jpg?ssl=1);
    background-size: cover;
    background-position: left-top;
    background-repeat: no-repeat;
}

Fiddle

A: contain fills up one dimension (full width or full height) while cover fills the image up until both dimensions are touching the sides.
Also, don't have a fixed height value, because on smaller screens, your child elements will go outside the header. Replace height with min-height.
.headerContainer{
  /* height:100vh; */
  min-height: 100vh;
  border:solid 2px;
  background-image:url("https://i2.wp.com/oddshjelpen.com/wp-content/uploads/2018/08/350851-download-free-website-background-1920x1080-for-mobile-hd.jpg?ssl=1");
  /* background-size: contain; */
  background-size: cover;
  background-position: left-top;
  background-repeat:no-repeat;
}