text:
Q: cannot access node values of xml in php I am trying to access node values of xml using php. But I could not access any of them. However, the url is returning response. I am using cURL to send post request.
My code looks like
     $url = (some url);
  $postDatas = 'CompanyCode=' . urlencode($companyCode) . '&ServiceCode=' . urlencode($serviceCode) . '&Account=' .urlencode($account) . '&Special1=' .urlencode($special1) . '&Special2=' .urlencode($special2) . '&ExternalDate=' .urlencode($externalDate) . '&ExternalId=' .urlencode($externalId) . '&SalesPointType=' .urlencode($salesPointType) . '&UserName=' .urlencode($userName) . '&UserPassword=' .urlencode($userPassword);
                        $ch = curl_init( $url );
                        curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
                        curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0);
                        curl_setopt( $ch, CURLOPT_POST, 1);
                        curl_setopt( $ch, CURLOPT_POSTFIELDS, $postDatas);
                        curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, 1);
                        curl_setopt( $ch, CURLOPT_HEADER, 0);
                        curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1);
                        $response = curl_exec( $ch );
                        curl_close ($ch);
                        print_r($response);

When doing print_r($response), I am getting such xml response.
  <PPResponse Type="Check" Key="182f55a7-ed3f-e511-940e-005056b219f6" Result="000" OperationId="61289766243683">
      <ResultMessage>Operation was successfully completed.</ResultMessage>
      <ProviderInfo Code="962" Name="BSNL" Country="356" Currency="356">
        <PackagesList>
          <Package ServiceId="1" Name="Package 1.1" Value="110" Description="1.1 USD" />
          <Package ServiceId="1" Name="Package 2.2" Value="220" Description="2.2USD" />
          <Package ServiceId="1" Name="Package 4.4" Value="440" Description="4.4USD" />
        </PackagesList>
      </ProviderInfo>
    </PPResponse>

But when I do $xml = simplexml_load_string($response) and view it using print_r($xml), I only get Operation is completed successfully and nothing else. But I want to access the value of all Result, OperationId and ResultMessage from this xml response.
But when I save the same xml response in my local computer and try to fetch the data, I can fetch all node values but its not happening from url. I would like to know whats the problem with this?

A: I run this code and get a nice XML ObjectSimpleXMLElement Object:

$string = '<PPResponse Type="Check" Key="182f55a7-ed3f-e511-940e-005056b219f6" Result="000" OperationId="61289766243683">
      <ResultMessage>Operation was successfully completed.</ResultMessage>
      <ProviderInfo Code="962" Name="BSNL" Country="356" Currency="356">
        <PackagesList>
          <Package ServiceId="1" Name="Package 1.1" Value="110" Description="1.1 USD" />
          <Package ServiceId="1" Name="Package 2.2" Value="220" Description="2.2USD" />
          <Package ServiceId="1" Name="Package 4.4" Value="440" Description="4.4USD" />
        </PackagesList>
      </ProviderInfo>
    </PPResponse>';
$text = simplexml_load_string($string);
echo "<pre>".print_r($text, true)."</pre>";

Result:
SimpleXMLElement Object
(
    [@attributes] => Array
        (
            [Type] => Check
            [Key] => 182f55a7-ed3f-e511-940e-005056b219f6
            [Result] => 000
            [OperationId] => 61289766243683
        )

    [ResultMessage] => Operation was successfully completed.
    [ProviderInfo] => SimpleXMLElement Object
        (
            [@attributes] => Array
                (
                    [Code] => 962
                    [Name] => BSNL
                    [Country] => 356
                    [Currency] => 356
                )

            [PackagesList] => SimpleXMLElement Object
                (
                    [Package] => Array
                        (
                            [0] => SimpleXMLElement Object
                                (
                                    [@attributes] => Array
                                        (
                                            [ServiceId] => 1
                                            [Name] => Package 1.1
                                            [Value] => 110
                                            [Description] => 1.1 USD
                                        )

                                )

                            [1] => SimpleXMLElement Object
                                (
                                    [@attributes] => Array
                                        (
                                            [ServiceId] => 1
                                            [Name] => Package 2.2
                                            [Value] => 220
                                            [Description] => 2.2USD
                                        )

                                )

                            [2] => SimpleXMLElement Object
                                (
                                    [@attributes] => Array
                                        (
                                            [ServiceId] => 1
                                            [Name] => Package 4.4
                                            [Value] => 440
                                            [Description] => 4.4USD
                                        )

                                )

                        )

                )

        )

)

Make sure you print the decoded xml variable, not the response.


text:
Q: Is there any way to automatically find the local IP address for use with TcpListener? Using VC++ 2010, .NET 4
Is there any way to automatically find the local IP address for use with TcpListener?  I can now put one in manually:
Int32 port = 36457;
IPAddress^ localAddr = IPAddress::Parse("192.168.1.254");
TcpListener^ server = gcnew TcpListener(localAddr, port);

But opening on a different machine will then fail.

A: There is no real way to find the local IP address for a machine as it can be part of multiple networks and can have multiple IP-addresses per network. (My computer has about 10 networks and I have server with 4 IP-addresses on a single network)
The only portable addresses to bind are 0.0.0.0 and the 127.0.0.1 network. Binding to 127.0.0.1 (also known under the alias localhost makes it only reachable from the machine itself and not from the network. Binding to 0.0.0.0 makes it reachable on every address on every network. Firewall rules must be set accordingly. Instead of 0.0.0.0 you can also use IPAddress.Any .
Most application let the user set this via configuration file, command line parameter or asking the user directly.

A: As long als you want to listen on all networks you are connected to, you can use "localhost" instead of the ip adress.

A: Why not use IPAddress.Any, or IPAddress.IPv6Any? This way, your network situation will be detected automatically. In generally, I wouldn't use a specific IP Address unless you know in advance which server with a static IP is being used, and even then I'd limit myself to one specified in a config file of some sort.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Space saving and loops in TikZ There are two main problems with the source/output pair of mine below (which is meant to be used for Hex games listings) :
1) In my printout at least, there's an unnecessary left margin and a top margin (I don't know where they come from) so the right and bottom part get eaten out.
2) My ugly 11-line code snippet whose intended meaning is a loop on a-b-c-...-k can surely can be replaced by a one-line smart loop ?
Any ideas on how to fix those issues ?
\documentclass{article}
\usepackage{amssymb}
\usepackage{mathrsfs}
\usepackage{pifont}
\usepackage{xcolor}
\usepackage{tikz}
\usepackage[a4paper,nohead,nofoot]{geometry}

\addtolength{\textwidth}{4cm}
\addtolength{\textheight}{4cm}

\addtolength{\hoffset}{-2cm}
\addtolength{\voffset}{-2cm}

\begin{document}

\pagestyle{empty}

\begin{tikzpicture}
\path (-1,0) coordinate (Z);
\path (Z)++(0.2,0) coordinate (Y);
\foreach \bx in {0,5.5,11,16.5}
{
\foreach \by in {0,-6,-12,-18,-24}
{
\path (Y) ++(\bx,\by)  coordinate (X);

\draw (X)  ++(0.2,0.2) node[anchor=south east] {$a$};
\draw (X)  ++(0.6,0.2) node[anchor=south east] {$b$};
\draw (X)  ++(1.0,0.2) node[anchor=south east] {$c$};
\draw (X)  ++(1.4,0.2) node[anchor=south east] {$d$};
\draw (X)  ++(1.8,0.2) node[anchor=south east] {$e$};
\draw (X)  ++(2.2,0.2) node[anchor=south east] {$f$};
\draw (X)  ++(2.6,0.2) node[anchor=south east] {$g$};
\draw (X)  ++(3.0,0.2) node[anchor=south east] {$h$};
\draw (X)  ++(3.4,0.2) node[anchor=south east] {$i$};
\draw (X)  ++(3.8,0.2) node[anchor=south east] {$j$};
\draw (X)  ++(4.2,0.2) node[anchor=south east] {$k$};
\foreach \x in {1,2,...,11}
{
\draw (X)++(\x*0.2,-\x*0.4) ++(-0.2,0.4) node[anchor=east] {$\x$};
\foreach \y in {0,0.2,...,2}
{
\draw (X) ++(-0.4,0) ++(\x*0.4,0) ++(\y,-\y*2)  -- ++(0,0.2) -- ++(0.2,0.2) -- ++(0.2,-0.2)  -- ++(0,-0.2) -- ++(-0.2,-0.2) --cycle;
}
}
}
}

\end{tikzpicture}

\end{document}

A: For the record, here's a fix following the suggestions in Schrödinger's cat's comment :
\documentclass{article}
\usepackage{amssymb}
\usepackage{mathrsfs}
\usepackage{pifont}
\usepackage{xcolor}
\usepackage{tikz}
\usepackage[a4paper,nohead,nofoot,margin=0pt]{geometry}
\begin{document}
\pagestyle{empty}
\begin{tikzpicture}
\path (-1,0) coordinate (Z);
\path (Z)++(0.2,0) coordinate (Y);
\foreach \bx in {0,5.5,11}
{
\foreach \by in {0,-6,-12,-18,-24}
{
\path (Y) ++(\bx,\by)  coordinate (X);
\foreach \Label [count=\X] in {a,...,k} {\draw (X) ++(-0.2+\X*0.4,0.2) node[anchor=south east] {$\Label$};}
\foreach \x in {1,2,...,11}
{
\draw (X)++(\x*0.2,-\x*0.4) ++(-0.2,0.4) node[anchor=east] {$\x$};
\foreach \y in {0,0.2,...,2}
{
\draw (X) ++(-0.4,0) ++(\x*0.4,0) ++(\y,-\y*2)  -- ++(0,0.2) -- ++(0.2,0.2) -- ++(0.2,-0.2)  -- ++(0,-0.2) -- ++(-0.2,-0.2) --cycle;
}}}}
\end{tikzpicture}
\end{document}


text:
Q: Ruby SHA1 RSA signing different from command line OpenSSL? I'm trying to implement RSA SHA1 signature verification.
To my surprise, command line OpenSSL tool doesn't generate the same key as the Ruby OpenSSL.
If I run those commands :
MacBook-Pro-de-Geoffrey:ssl_tests Escaflowne$ cat data.txt
000
MacBook-Pro-de-Geoffrey:ssl_tests Escaflowne$ openssl dgst -sha1 -binary -sign prvkey.pem -out sig.bin data.txt
MacBook-Pro-de-Geoffrey:ssl_tests Escaflowne$ openssl base64 -in sig.bin -out sig64.txt
MacBook-Pro-de-Geoffrey:ssl_tests Escaflowne$ cat sig64.txt
AJEh2kA7O3j624Kdl7UCGN1HiEk/v2LQudB+cjxw1CfmRTjcSPBjUE/EAwy8NEut
K4zYgfRwwTs7NY3AwYiUEtAe5yohUM0Qv17qSDW+G4IWjwe9PKE7Sl00umiMdszA
q/1hqeQlHKgjme7YO7H6i1UcAXmriOOjn+ySRaovsHw=

So final base64 result in command line is :
AJEh2kA7O3j624Kdl7UCGN1HiEk/v2LQudB+cjxw1CfmRTjcSPBjUE/EAwy8NEut
K4zYgfRwwTs7NY3AwYiUEtAe5yohUM0Qv17qSDW+G4IWjwe9PKE7Sl00umiMdszA
q/1hqeQlHKgjme7YO7H6i1UcAXmriOOjn+ySRaovsHw=
Now, if I try signing it through my ruby script :
def sign_message(message)
    privkey = OpenSSL::PKey::RSA.new(File.read(Rails.root.join('lib', 'payment', 'prvkey.pem')))

    digest = OpenSSL::Digest.new('sha1')

    expected_sign = privkey.sign(digest, message)
    base_64_expected_sign = [expected_sign].pack('m')

    puts "Expected Signature"
    puts expected_sign
    puts "Base 64 Expected Signature"
    puts base_64_expected_sign

    return base_64_expected_sign
  end

And calling the function like this :
  def test_sign
    message = "000"
    message_signature = sign_message(message)
    puts "Message Signature : #{message_signature}"

    puts "Valid : #{verify_signature(message_signature, message)}"
  end

I get the output :
Expected Signature
??|??n?^~?T_1Y@??BR??u???k      x?*????S?L?:.7
                          t??tc?)崪? ?}DMp?p2??4?D-f??jT;!e
                                                              ?k??5??
Base 64 Expected Signature
QjhL1zQoUdGFLVCMg06/CKeE/HdhRTOhJ/p09wkWeK0qD/afsxfcU7tMtDou
Nw3rwXw/5W68XhZ+BK1UXwIxWUDbFYlCUpu6HnWTmI5rC3QP+f50Y8kp5bSq
gQkekH1ETXDmcDKvExeSNKVELWYe3uwTalQ7IWUMyWvnF541rvo=
Message Signature : QjhL1zQoUdGFLVCMg06/CKeE/HdhRTOhJ/p09wkWeK0qD/afsxfcU7tMtDou
Nw3rwXw/5W68XhZ+BK1UXwIxWUDbFYlCUpu6HnWTmI5rC3QP+f50Y8kp5bSq
gQkekH1ETXDmcDKvExeSNKVELWYe3uwTalQ7IWUMyWvnF541rvo=

So final ruby OpenSSL signature is :
QjhL1zQoUdGFLVCMg06/CKeE/HdhRTOhJ/p09wkWeK0qD/afsxfcU7tMtDou
Nw3rwXw/5W68XhZ+BK1UXwIxWUDbFYlCUpu6HnWTmI5rC3QP+f50Y8kp5bSq
gQkekH1ETXDmcDKvExeSNKVELWYe3uwTalQ7IWUMyWvnF541rvo=
Versus command line :
AJEh2kA7O3j624Kdl7UCGN1HiEk/v2LQudB+cjxw1CfmRTjcSPBjUE/EAwy8NEut
K4zYgfRwwTs7NY3AwYiUEtAe5yohUM0Qv17qSDW+G4IWjwe9PKE7Sl00umiMdszA
q/1hqeQlHKgjme7YO7H6i1UcAXmriOOjn+ySRaovsHw=
I've been struggling with this for some time now and I don't understand what could be making a difference!
UPDATE :
Well, apparently results match if I replace my message variable with File.read(Rails.root.join('lib', 'payment', 'data.txt'))
So basically, using a string with the same value as what's in the text file doesn't give the same result.
This means it's encoding related right ?
UPDATE 2 :
So the file says its encoded in us-ascii if I run file -I data.txt
However, if I do message.encoding.name it says its loaded as UTF-8
Also, message.encode('ascii') does not alter the result of the generated signature, it still corresponds with the command line openssl.
As soon as I switch to a string "000".encode('utf-8') or "000".encode('ascii'), the signatures don't match anymore.
So encoding doesn't seem to play a role at all.
How come there's a difference between the exact same content whether it comes from reading a file or written as a string ?

A: The file data.txt has a trailing newline that you are not taking into account in your code. Using
message = "000\n"

should work.
You could also do
message = File.binread("data.txt")

to make sure you get the exact data as the command line.


text:
Q: Unable to mount DVDs on Gentoo I'm unable to mount any dvd on my HP 6735s laptop running Gentoo (with combined stable (+) and testing (~) ebuilds). Here's everything that I can come up with:
$uname -a
Linux aiur 2.6.32.6-aiur-r5 #6 SMP Thu Jan 28 17:02:59 CET 2010 x86_64 AMD Turion(tm)X2 Dual Core Mobile RM-70 AuthenticAMD GNU/Linux

NOTE: -aiur-r5 is my custom kernel name. I am having this problem with all the kernels since 2.6.31. I use the vanilla kernels from www.kernel.org and compile them with some custom settings using menuconfig.
$ ls -l /dev/{cd,dvd,scd,sr}*
lrwxrwxrwx 1 root root      3 Jan 28 17:37 /dev/cdrom -> sr0
lrwxrwxrwx 1 root root      3 Jan 28 17:37 /dev/cdrw -> sr0
lrwxrwxrwx 1 root root      3 Jan 28 17:37 /dev/dvd -> sr0
lrwxrwxrwx 1 root root      3 Jan 28 17:37 /dev/dvdrw -> sr0
lrwxrwxrwx 1 root root      3 Jan 28 17:37 /dev/scd0 -> sr0
brw-rw---- 1 root cdrom 11, 0 Jan 28 17:37 /dev/sr0

$ grep aatiis /etc/group
disk::6:root,adm,haldaemon,aatiis
audio::18:aatiis
cdrom::19:haldaemon,aatiis
dialout::20:root,aatiis
video::27:root,aatiis
cdrw::80:haldaemon,aatiis
usb::85:haldaemon,aatiis
aatiis:x:1000:
vboxusers:x:1006:aatiis
wireshark:x:1010:aatiis
games:x:35:aatiis

$ dmesg | grep -i dvd
ata2.00: ATAPI: HL-DT-ST DVDRAM GT20L, DC03, max UDMA/100
scsi 1:0:0:0: CD-ROM            HL-DT-ST DVDRAM GT20L     DC03 PQ: 0 ANSI: 5
sr0: scsi3-mmc drive: 24x/24x writer dvd-ram cd/rw xa/form2 cdda tray

$ lsmod | grep udf

NOTE: No UDF module. I compiled it into the kernel this time; however, I was having the same problem when I compiled as a module...
$ lsmod | grep dvd
pktcdvd                20840  0

I guess I need the pktcdvd module for writing DVD's?
$ sudo mount /dev/dvd /media/cdrom
mount: /dev/sr0: unknown device
$ sudo mount -t udf /dev/dvd /media/cdrom
mount: no medium found on /dev/sr0
$ sudo mount -o ro -t udf /dev/dvd /media/cdrom
mount: no medium found on /dev/sr0
$ sudo mount -t iso9660 /dev/dvd /media/cdrom
mount: no medium found on /dev/sr0

Of course, the DVDs are working on other computers. They are not CSS-encrypted. Some of them were burnt by this same dvd burner when I had Debian.
Also, DVD burning is not working either. It doesn't even recognizes a blank DVD when I insert it (I like to use the new K3B alpha, but brasero and the other burner tools don't work either).
Anyone having this problem? I'm reading forums for a couple of days now as I really need to burn some DVDs. What should I try to do? Any help or suggestion is welcome.
EDIT:
$ sudo rc-update -s
           acpid | boot
       alsasound |      default
             atd | boot
        bootmisc | boot
         checkfs | boot
       checkroot | boot
           clock | boot
     consolefont | boot
            dbus |      default
           fcron | boot
            hald |      default
        hostname | boot
         keymaps | boot
           local |      default nonetwork
      localmount | boot
         modules | boot
           mysql |      default
          net.lo | boot
            ntpd |      default
  postgresql-8.4 |      default
       rmnologin | boot
            sshd |      default
       syslog-ng | boot
  udev-postmount |      default
         urandom | boot
             xdm |      default

So, I have udev-postmount here.
$ dmesg | grep udev
udev: starting version 150
udev: starting version 151

I might have updated it with a recent emerge --update --newuse --deep world --ask, so I guest that's why I have two versions of it?
$ cat /etc/fstab
# /etc/fstab: static file system information.
#
# (some more comments here, I omitted them for clarity)

# <fs>                  <mountpoint>    <type>          <opts>          <dump/pass>

/dev/sda1               /               ext3            noatime         0 1
/dev/sda5               none            swap            sw              0 0
/dev/sda6               /mnt/data       ext4            user,rw,exec    0 2

# glibc 2.2 and above expects tmpfs to be mounted at /dev/shm for
# POSIX shared memory (shm_open, shm_unlink).
# (tmpfs is a dynamically expandable/shrinkable ramdisk, and will
#  use almost no memory if not populated with files)
shm                     /dev/shm        tmpfs           nodev,nosuid,noexec     0 0

Note that /dev/sda1 (my root partition) is also ext4, but I use the ext3 driver right now.
$ dmesg | grep sr
sr0: scsi3-mmc drive: 24x/24x writer dvd-ram cd/rw xa/form2 cdda tray
sr 1:0:0:0: Attached scsi CD-ROM sr0
sr 1:0:0:0: Attached scsi generic sg1 type 5

Thanks for the responses. Any more info I can provide?

A: When you do the mount command is there any message after it in dmesg?

A: I'm surprised to see sr0 instead of plain /dev/dvd .. In your /etc/rc.conf (or /etc/conf.d/rc, I can never remember), are you doing "use_device_tarball = yes" ? Are you using UDEV all the way? Please show us your fstab.

A:
I am having this problem with all the kernels since 2.6.31

does that mean that if you boot 2.6.30 the drive works, or that you've had this problem since 2.6.31 came out.
it sounds like your drive could just be dead.  When you try to mount a disk, does the drive even spin up?


text:
Q: Using useListController inside ListContextProvider doesn't provide the data I am using react-admin and I am encountering the Problem that useListController does not provide any data inside ListContextProvider even though useListContext does.
  const query = useQuery({
    type: 'getList',
    resource: 'dashboard/summary',
    payload: {
      pagination: { page, perPage },
      sort: { field: 'createdAt', order: 'DESC' },
      filter
    },
  });
  // more code ....
  return (
      <ListContextProvider
        value={{
          ...query,
          setPage,
          basePath,
          data: keyBy(query.data, 'id'),
          ids: query.data.map(({ id }) => id),
          currentSort: { field: 'id', order: 'ASC' },
          selectedIds: [],
          resource,
          page,
          perPage,
          setFilters
        }}
      >
        <SummaryList onSearch={onSearch} filter={filter} />
      </ListContextProvider>
  );

Inside SummaryList
  const context = useListContext();
  const cp = useListController(context);
  console.log(context);
  console.log(cp);

The controller Object
basePath: "/dashboard/summary"
currentSort: Object { field: "id", order: "ASC" }
data: Object {  }
defaultTitle: "Dashboard/summaries"
displayedFilters: Object {  }
error: null
exporter: function defaultExporter(data, _, __, resource)
filter: undefined
filterValues: Object {  }
hasCreate: undefined
hideFilter: function hideFilter(filterName)
ids: Array []
loaded: true
loading: false
onSelect: function select(newIds)
onToggleItem: function toggle(id)
onUnselectItems: function clearSelection()
page: 1
perPage: 10
resource: "dashboard/summary"
selectedIds: Array []
setFilters: function setFilters(filter, displayedFilters, debounce)
setPage: function setPage(newPage)
setPerPage: function setPerPage(newPerPage)
setSort: function setSort(sort, order)
showFilter: function showFilter(filterName, defaultValue)
total: undefined

The context Object
{
  "data": {
  // the data which I omitted
  },
  "total": 4,
  "loading": false,
  "loaded": true,
  "basePath": "/dashboard/summary",
  "ids": [
    "2021-05-01",
    "2021-05-02",
    "2021-05-03",
    "2021-05-04"
  ],
  "currentSort": {
    "field": "id",
    "order": "ASC"
  },
  "selectedIds": [],
  "resource": "dashboard/summary",
  "page": 1,
  "perPage": 10
}

How am I supposed to use useListController ?

A: useListController takes the List props (and location parameters), uses it to fetch data from the dataProvider, and passes it to the ListContext.
By calling useListContext(), you're accessing the values and callbacks built by useListController.
In your example, you're building the ListContext by hand, so you don't need useListController at all.


text:
Q: CosmosDB is returning more than the default number of records I'm using go1.18 and go-cosmosdb to fetch records from CosmosDB:
opts := cosmosapi.QueryDocumentsOptions{
    IsQuery:              true,
    ContentType:          cosmosapi.QUERY_CONTENT_TYPE,
    ConsistencyLevel:     cosmosapi.ConsistencyLevelStrong,
    EnableCrossPartition: false,
}

resp, err := c.client.QueryDocuments(ctx, DatabaseName, ContainerName, query, &res, opts)

The query is a simple select * query.
Since I'm not setting opts.MaxItemCount, it should default to 0, and the returned documents should be up to a 100 according to the azure docs:

Query requests support pagination through the x-ms-max-item-count and
x-ms-continuation request headers. The x-ms-max-item-count header
specifies the maximum number of values that can be returned by the
query execution. This can be between 1 and 1000, and is configured
with a default of 100.

But it weirdly returns more than a 100. I'm not sure if this is a new change? I'm pretty sure I used this before and it used to return only a hundred records.
Any thoughts?


text:
Q: How to rewrite a URI in Grails within UrlMappings.groovy I would like to basically do a URL rewrite in UrlMappings.groovy, for example:
"/pub/cdn/$version/**"(uri: request.forwardURI.replaceFirst("/pub/cdn/[0-9]*", ""))

So that a request for:
/pub/cdn/1327516405188/css/login.css

for example, would get translated to:
/css/login.css

The idea is to take the original URI and strip out some of the path, and pass along the new URI.
However, using the above code, I get the error:
>    org.springframework.beans.factory.BeanCreationException: Error
>    creating bean with name 'grailsUrlMappingsHolder': Cannot resolve
>    reference to bean 'urlMappingsTargetSource' while setting bean
>    property 'targetSource'; nested exception is
>    ...
>    groovy.lang.MissingPropertyException: No such property: forwardURI for
>    class: java.lang.String

which seems to imply that the request object is a String. Is there a way to obtain the original URI in UrlMappings.groovy?
The "/old/path"(uri: "/new/path") method does work as long as the new path is hard coded, but I can't figure out how to access the original requested path as a variable inside the UrlMappings class.
P.S. I tried having UrlMappings call a controller:
"/pub/cdn/$version/**" {
    controller = "image"
    action = "cdnRedirect"
}

and in the Controller:
def cdnRedirect = {
    def newUri = request.forwardURI?.toString().replaceFirst("/pub/cdn/[0-9]*", "")
    return redirect(uri: newUri)
}

While the controller closure gets called correctly, and the URI gets translated correctly, the redirect does not seem to do anything at all.

A: Based on your example, it sounds to me like you are solving the wrong issue.  The real issue here is seems to be that you are using relative links (e.g. css/login.css) to static content.  When the browser picks up a relative link, it uses the current url to determine the file's path.
However, if you use Grails' resource tag, grails will generate a URL that is anchored to the root of the URL.  For example, your css/login.css link would become /myAppName/css/login.css.
Usage is like so:
<link type="text/css" href="${resource(dir: 'css', file: 'login.css')}" />

This guarantees that, no matter the controller, action, or other ID information, the link to the CSS file will always be correct.

As for why your UrlMapping isn't working, it's because it isn't dynamically processed.  It's processed during application startup, and so the request object doesn't even exist at that time.
If you absolutely need a URL rewriting system, and using a controller to process the resources is too complex for this purpose, I recommend putting your servlet engine (i.e. Tomcat) behind Apache and just using mod_rewrite.  Properly designed, however, this really shouldn't be necessary.

Edit
Just for complete information, to get dynamic control of the mapping is to use the syntax specified in Dynamic Controller and Action Names.  However, this is somewhat limited, and you still can't use it to perform a redirect.


text:
Q: Eslint Typescript "No Implicit Any" rule I am setting up a new typescript project with eslint. I am trying to setup eslint rules correctly so that the tsc command runs without errors. I have the problem with the "noImplicitAny" rule, which I use in tsconfig.json, but I am unable check for this in eslint.
.eslintrc.js:
module.exports = {
    extends: [
        "eslint:recommended",
        "plugin:@typescript-eslint/eslint-recommended",
        "plugin:@typescript-eslint/recommended",
    ],
    parser: "@typescript-eslint/parser",
    parserOptions: {
        project: ["tsconfig.json"],
        sourceType: "module",
    },
    rules: {
        "no-undef": "warn",
    },
    plugins: ["@typescript-eslint"],
    settings: {
        "import/resolver": {
            node: {
                extensions: [".js", ".ts"],
            },
        },
    },
};

tsconfig.json:
{
  "compilerOptions": {
    "target": "es5",
    "module": "ES6",
    "declaration": true,
    "outDir": "./lib",
    "strict": true,
    "noImplicitAny": true
  },
  "include": ["src/**/*.ts"],
  "exclude": ["node_modules", "**/__tests__/*"]
}

In short I want the eslint to check for the implicit any and warn about its usage. How can I configure the rules in .eslintrc.js to achieve this?

A: There are a number of no-unsafe-* rules that have been implemented in TypeScript-ESLint:

*

*no-unsafe-call - forbids calling an expression typed as any

*no-unsafe-member-access - forbids using any as a member name

*no-unsafe-argument - forbids passing any as a function parameter

*no-unsafe-assignment - forbids using any in an assignment

These are all standalone rules, but they've also all been integrated into
Typescript-ESLint's official
recommended-requiring-type-checking config.
extends: [
    'plugin:@typescript-eslint/recommended-requiring-type-checking',

On a similar note, there's no-explicit-any. Put all of these together, and you should be fully protected against any problems.

A: eslint refuses to add a no-implicit-any due to the fact it duplicates a typescript rule.
They did however make a transition rule that should not be used permanently which does what you wanted.  You should remove this rule once you can turn these options on in your tsconfig file.
This allows warning for implicit parameters or arguments in normal and arrow functions.  There are more options than the ones commented out, documentation linked below.
    '@typescript-eslint/typedef': [
      'warn',
      {
        parameter: true,
        arrowParameter: true,
        // variableDeclaration: true,
        // memberVariableDeclaration: true,
        // objectDestructuring: true,
      },
    ],

link to github issue not allowing no-implicit-any
https://github.com/typescript-eslint/typescript-eslint/issues/3979
doucmentation for typedef information
https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/eslint-plugin/docs/rules/typedef.md


text:
Q: Using python with selenium webdriver doesn't work with every wireless connection my script works very well when I use it at my offices (wifi connection). But when I get home and I use my personal wifi or any other wifi, it doesn't work...
Could you please help me ??
Extracted from general.log
ERROR [2018-08-11 21:31:18] [mehdidouache] Message: Can not connect to the Service /Users/Mehdi/Desktop/InstaPy/assets/chromedriver
Traceback (most recent call last):
File "/Users/Mehdi/Desktop/InstaPy/instapy/instapy.py", line 299, in set_selenium_local_session
chrome_options=chrome_options)
File "/usr/local/lib/python3.6/site-packages/selenium/webdriver/chrome/webdriver.py", line 62, in init
self.service.start()
File "/usr/local/lib/python3.6/site-packages/selenium/webdriver/common/service.py", line 102, in start
raise WebDriverException("Can not connect to the Service %s" % self.path)
selenium.common.exceptions.WebDriverException: Message: Can not connect to the Service /Users/Mehdi/Desktop/InstaPy/assets/chromedriver


text:
Q: Sufficient condition to be a countable set Let $A$ a non empty set. Which of the following conditions is sufficient because A is a countable set:

*

*$A \subset \mathbb N$

*$\mathbb N \subset A$

*exists a surjective function $f: \mathbb N \rightarrow A$ and $A$ is infinite

*exists a succession $a_n$ so that $\{a_n:n \in \mathbb N\}=A$
My attemp:

*

*is false because if the set $A$ is finite I can't find a bijective function fraom $\mathbb N$ to $A$

*is false because if I take $A=\mathbb R$ is not countable
but for the other cases?

A:

*It is true. For each $a\in A$, let $n_a=\min f^{-1}(\{a\})$. Then $\Bbb N_A=\{n_a\mid a\in A\}$ is an infinite set of natural numbers and the map from $A$ to $\Bbb N_A$ defined by $f(a)=n_a$ is a bijection. Furthermore any infinite subset of $\Bbb N$ is countable.

*It is false. If $A=\{1\}$, take $a_n=1$ form each natural $N$.

A: Only 3 is true.
Since $f:\mathbb N\rightarrow A$ is onto hence $|A|\le |\mathbb N|$. Now given that $A$ is infinite which restricts us to the condition $|A|=|\mathbb N|$. Thus $f$ is a bijection which implies $A$ is countable.


text:
Q: How to hide unwanted element on the embed website by using script? Faced with necessity to hide unwanted element on embed website. There's piece of HTML code:

Problem: Manipulate with CSS does not work due to 'display: block' written inline in HTML body.
Question: Is there any way how to remove this element OR rewrite 'display: block' TO 'display: none' with Java script OR jQuery?
May be it worth, here's exact piece of code that necessary to rewrite from 'display: block' to 'display: hide':

The task is to add some script that will force native code to be rewritten from display: block; to display: hide;
Thanks!

A: Try in java script..
document.getElementById('#ElementId').style.display = 'block';//show
document.getElementById('#ElementId').style.display = 'none';//hide

and with jQuery..
$("#ElementId").hide();
$("#ElementId").show();

Hope this helps...

A: There needs to be some user interaction to make to toggle between being visible and hidden, i will be assuming it to be a click event on a button with id button.

or if your set up requires it to be hidden always just have
document.getElementsByClass("className")[0].style.display = "none";

A: you are going to need to manipulate the JavaScript style proprieties here did you try this:
element.style.display = 'none';           // Hide
element.style.display = 'block';          // Show
element.style.display = 'inline';         // Show
element.style.display = 'inline-block';   // Show

remember to create an getelementID(div ID around or into section tag)
function hide (elements) {
  elements = elements.length ? elements : [elements];
  for (var index = 0; index < elements.length; index++) {
    elements[index].style.display = 'none';
  }
}

in JQuery use this to hidden/show div block:
$(".divIDClass").hide(); // hidden

$(".divIDClass").hide(); // show

A: There is 2 way to hide the section

*

*override the style attribute.

*Use jQuery hide() and show()

If the section is dynamic loaded then you have to use jquery on function .
code:

*

*$(document).on('load','section[class="class Name"]',function()
{
$(this).css('style','display:none');
});

*$(document).on('load','section[class="class Name"]',function()
{
$(this).hide();
});

If not dynamic loaded
code:

*

*$('section[class="class Name"]').css('style','display:none');

*$('section[class="class Name"]').hide();


text:
Q: Is it possible to add a white space at start of my commands? I would tweak my custom commands using a whitespace in Linux terminal. I have used echo "    " + cmd but it doesn't works. If someone has any hint, would be great,
thanks.

A: Try to type like this:
echo " "$(command)


text:
Q: Dynamic Ajax Content Icelandic charset issue I'm working on a double drop down menu a'la http://http://www.coursesweb.net/ajax/multiple-select-dropdown-list-ajax_t  See http://www.hafdal.dk/testing/test.php
I'm working with Icelandic characters - my database has utf8_icelandic_ci encoding and my php files have
"meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" in the header.
I had some problems initially to get the Icelandic characters to display in the first dropdown menu but the charset definition in the 2 php files, solved that problem.
The problem now is that apparently ajax does not recognise the string that is loaded into the dropdown menu - an encoding problem again I suspect.
This is my ajax_select.js file:
Thanks in advance for taking a look at this :-)
    // Multiple select lists - www.coursesweb.net/ajax/

    // function used to remove the next lists already displayed when it chooses other options
    function removeLists(colid) {
      var z = 0;
      // removes data in elements with the id stored in the "ar_cols" variable
      // starting with the element with the id value passed in colid
      for(var i=1; i<ar_cols.length; i++) {
        if(ar_cols[i]==null) continue;
        if(ar_cols[i]==colid) z = 1;
        if(z==1) document.getElementById(preid+ar_cols[i]).innerHTML = '';
      }
    }

    // create the XMLHttpRequest object, according browser
    function get_XmlHttp() {
      // create the variable that will contain the instance of the XMLHttpRequest object (initially with null value)
      var xmlHttp = null;

      if(window.XMLHttpRequest) { xmlHttp = new XMLHttpRequest(); }     // for Forefox, IE7+, Opera, Safari
      else if(window.ActiveXObject) { xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
    }              // IE5 or 6

              return xmlHttp;
    }

    // sends data to a php file, via POST, and displays the received answer
     function ajaxReq(col, wval)
    {
      removeLists(col);           // removes the already next selects displayed

      // if the value of wval is not '- - -' and '' (the first option)
      if(wval!='- - -' && wval!='') {
        var request =  get_XmlHttp();             // call the function with the      XMLHttpRequest instance
        var php_file = 'select_list.php';     // path and name of the php file

        // create pairs index=value with data that must be sent to server
        var  data_send = 'col='+col+'&wval='+wval;

        request.open("POST", php_file, true);           // set the request

        document.getElementById(preid+col).innerHTML = 'Loadding...';   // display a loading notification

// adds a header to tell the PHP script to recognize the data as is sent via POST
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.send(data_send);            // calls the send() method with data_send

// Check request status
// If the response is received completely, will be added into the tag with id value of "col"
request.onreadystatechange = function() {
  if (request.readyState==4) {
    document.getElementById(preid+col).innerHTML = request.responseText;
  }
}
      }
    }

A: I would recommend you to use UTF-8 for everything. UTF-8 handles all non-English characters you'll need and since your database is in UTF-8, there is not reason not to switch. I've used countless hours trying to fix problems like this. The soulution is always UTF-8.
Here is a few other answers on this topic:

*

*jQuery AJAX Character Encoding Problem

*Accent ajax encoding issue
If you provide a working code, I can look over it and maybe help you out.

A: I managed to figure this out by myself (believe it or not!).
I added utf8_encode() to each of my outputs. F.ex.
echo utf8_encode("<option value=$nt[id]>$nt[name]</option>");

I hope this helps others with similar problems.


text:
Q: How to refresh datagridview after pressing a button Hello I am making a small winforms app for a school with a local SQL database.I am using DataGridView to display the Data,but after I add a new student the DataGridView doesn't refresh.
        con.Open();
        MessageBox.Show("Connection Open");
        SqlCommand cm = new SqlCommand("INSERT INTO Students(Grade,Class,Name,sName) VALUES (@Grade,@Class,@Name,@sName)", con);
        cm.Parameters.AddWithValue("@Grade", cbGrade.Text);
        cm.Parameters.AddWithValue("@Class", comboClass.Text);
        cm.Parameters.AddWithValue("@Name", tbFName.Text);
        cm.Parameters.AddWithValue("@sName", tbSName.Text);

try
        {
            int exec = cm.ExecuteNonQuery();
            if(exec>0)
            {
                MessageBox.Show("Added");

            }
            else
            {
                MessageBox.Show("Not added");
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show("Something went wrong");
            con.Close();
        }
        finally
        {
            con.Close();
        }

A: Everything works.
            string query = "select * from students";
            SqlCommand cmd = new SqlCommand(query,con);
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataTable dt = new DataTable();
            da.Fill(dt);
            DGVStudents.DataSource = dt;


text:
Q: Removing limit from Binary column for PostgreSQL in datamapper I'm trying to create a model with a Binary field in Datamapper for Rails 3 that looks like so:
class Image

  include DataMapper::Resource

  # attributes
  property :id, Serial
  property :url, String
  property :file_name, String
  property :content_type, String
  property :data, Binary
  property :created_at, DateTime
  property :updated_at, DateTime

end

However, when I try to migrate I get the following:
ERROR:  type modifier is not allowed for type "bytea"
LINE 1: ..." VARCHAR(50), "content_type" VARCHAR(50), "data" BYTEA(50),...

I can't seem to find a way to remove the limit of 50 that datamapper is placing upon the field. Anybody know how to do this or fix the problem?

A: This is a bug in DataMapper. Check out this thread. It has already been fixed in GitHub, but it hasn't made it to a release yet. If you're ok with it, it's very easy to patch dm-migrations to fix it. In "dm-migrations/adapters/dm-do-adapter.rb", you find the line that says
if dump_class.equal?(String) && schema_primitive != 'TEXT' && schema_primitive != 'CLOB' && schema_primitive != 'NVARCHAR'

and append
&& schema_primitive != 'BYTEA'

to the end of it.
I tested your code here and it works with the patch applied.


text:
Q: How many skill points does it take to level up? It doesn't seem to be consistent how many skills I must level up in order to gain a character level. It also doesn't seem to be a whole number, since I currently have about 2 pixels of bar left to get from level 3 to level 4. What is the formula like for determining when the character gains a level, based on what skills level?

A: So I read through GoblinLord's accepted answer and tested it. It all works great and matches my own character. I just want to add some supplementary information, but I realize that doing so would really change the content of his post. This is about what the mechanics mean in practical terms.
The one thing that I found most interesting is how the actual math explains several things.
The soft cap
It exists insofar as leveling becomes progressively more difficult, but there is no mathematical change at any point. However, as you near 100 in your favorite skills, it becomes essential to start leveling the more underused skills. You need around the same number of new skill ranks to level up, but those ranks are harder (or at least more time-consuming) to achieve. But there's only a small difference between going from 49 to 50 and 50 to 51.
Skill level vs character level
If you level all skills equally, there's an almost linear relationship between average skill level and character level. If you go the opposite direction, there can be a pretty huge difference. It's worth comparing to Oblivion, where 10 ranks meant one new level; in Skyrim you can have a considerably lower average skill level than a character at a higher level, and vice versa.

How many skill levels
As opposed to focusing on skill points, you can look at levels. Again, assuming you level everything equally, after around level 25 you start needing around 20 additional skill ranks for one more level up. (You can cut that in half if you're leveling only your best skills.)

A: There is a fairly comprehensive article about Skyrim's Leveling up on UESP.
Excerpt from the article:

Leveling up low level skills offers a low amount of 'skill exp' towards your level up while  leveling up high level skills offers more skill exp. Each character level gain causes the needed skill exp to level up to increase. This has been done in order to place a sort of level cap around level 80.

A: I think the mathmatical answer to this question is actually a formula (that I don't know) as Todd Howard, Bethesda's game director, says

The levelling is faster. Oblivion and Fallout 3, we think of them as 1-25 games. This is a 1-50. But what that means is we just sped it up. It's not like it's going to take you longer. There are so many perks and the power really comes from the perks, we wanted to get it going faster. You level faster in the beginning and then it slows down.

As found in this article.

A: Every time you level a skill you earn the level you earned in XP to level.
Skill level earned = XP gained toward next level
Example:  You just earned level 26 in Smithing.  This will give you 26 points of XP toward your next level.
The number of XP to level for a specific level is equal to the following:
25x(Current Level - 1)+100 = XP to level
Example:  You are level 32 trying to level to 33.
25x(32-1)+100= 875 XP required
This would mean that you would require 875 XP from leveling skills to reach level 33.  One thing to remember is you will probably almost never start a level at 0 XP because of XP earned from the last level.  This means that while 875 XP would be required it will take slightly less than that to actually level.
Just a notice... I did not come up with this information but as far as I can tell it seems exactly correct.  I found the information here:
Leveling information
Note:  I am using the term XP arbitrarily seeing as there is not any place within the game (that I am aware of) that actually refers to XP.
Note 2:  I think the difficulty with leveling over 50 is that 50 is not very far from being half way to earning the Max number of Skill levels earned.  I think the number 50 was probably just a rough estimate (being a "nicer" number than say 53 or something like that).  Also, considering if a player would normally focus on less than half of the skills than after maxing some you would begin leveling lower level skills around this point.  This would amplify the perceived needed skill levels to level because you would be gaining less XP toward your next level from these lower level skills.  All of these things combined would mean that to a player the perceived XP to level would seem higher.  This perception could be offset a bit leveling all of the skills evenly while progressing through the game.  Though... it is still only perception really and it could have other implications like some of your skills being to weak for the current progression point that the enemies are at.
As for leveling skills my guess it is probably the same type of linear increase for XP to level but that information would be much more difficult to derive.  Now... if there were only a console command that would spit out these values.
Edit: MORE TESTING
Since this was not marked as an answer and rightly so... I decided to do some testing... actually reversing the entire calculation using my skill levels to which... in theory... should give me exactly what level and how far I am to the next level.  Though I have no way of knowing exactly what percent I am to the next level... judging from how far the bar is... it seems exactly correct.
To get the the Total XP required to reach a level I came up with this additional formula (which I simplified as much as i could):
(n-2)(n-1)(12.5)+100(n-1)=Total XP to Level
n = Level
Also, to get the Base XP you start with in the game (because skill levels do not start at 0) I came up with the value 2815.
So... to test with your own character... calculate the acquired XP from every skill.  Add them all together.  Subtract the starting value (because this xp did not get earned and did not count toward level 2 (from starting at level 1).
(Skill XP Total - Base XP)
Calculate the amount of XP that was required to get to your current level... then calculate the next level.  Your current XP value should fall between these 2 values.  You can also easily calculate the percentage you are to the next level using what you have and compare your calculation to an approximation by looking at your bar in game.  Just for notes I will also post my scrap notes from my calculations when I did it for my character.
1 skill at 25    325xp x 1  = 325xp
5 skills at 20   210xp x 5  = 1050xp
12 skills at 15  120xp x 12 = 1440xp
Base XP 2815
16  = 16x17x0.5   = 136
34  = 34x35x0.5   = 595
47  = 47x48x0.5   = 1128
20  = 20x21x0.5   = 210
30  = 30x31x0.5   = 465
16  = 16x17x0.5   = 136
100 = 100x101x0.5 = 5050
22  = 22x23x0.5   = 253
100 = 100x101x0.5 = 5050
100 = 100x101x0.5 = 5050
84  = 84x85x0.5   = 3570
19  = 19x20x0.5   = 190
18  = 18x19x0.5   = 171
74  = 74x75x0.5   = 2775
29  = 29x30x0.5   = 435
16  = 16x17x0.5   = 136
17  = 17x18x0.5   = 153
41  = 41x42x0.5   = 861
26364 total xp
26364-2815 = 23,549  Actual earned XP
(n-2)(n-1)(12.5)+100(n-1)=Total XP to Level
level 41 = 23500xp
level 42 = 24600xp

Another way to compute this :
When you try to estimate how many XP you earned from a skill you just need to add each skill level above the starting skill level :
Exemple :
A skill started at 15 and now is 18 so :
18+17+16 = 51xp
So now if we consider that we have a skill at N level we have :
1+2+3...+N xp
but we need to substract the "starting skill xp"
1+2+3...+15 xp = 120xp
if we consider S the starting skill level we obtain :
(1+2+3...+N) - (1+2+3...+S)
Now we know a math formula that will help us :
Add the N firsts integers is equivalent to
(1+2+3...+N) = (N+1)+((N-1)+2)+((N-2)+3)... = (N+1)*(N/2)
so we can replace the approximation formula (n-2)(n-1)(12.5)+100(n-1) by (N+1)(N/2)-(S+1)(S/2) which is the exact formula
where N is current skill level and S is starting skill level.


text:
Q: Audio Toolbox sound change problem i'm new in iphone programin and i wrote a little animation program. i used audiotoolbox frame for sound and it was working.
But when i change the sound file. (deleted exfile from resources and folder and add the other file with the same name, same path)
but after changing sound is not working.
i also rechanged sound file with ex-file.But even ex file is not working.
(both are  .wav type)
if you want i can write codes here.
thx for your help.

A: Have you tried rewriting the code?
You could also try using the AVFoundation Framework instead.
.h
#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>

@interface AudioPlayerViewController : UIViewController {
    AVAudioPlayer *audioPlayer;
}

@end

.m
- (void)viewDidLoad {
    [super viewDidLoad];

    NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/audiofile.mp3", [[NSBundle mainBundle] resourcePath]]];

    NSError *error;
    audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];

    if (audioPlayer == nil)
        NSLog([error description]);
    else
        [audioPlayer play];

}


text:
Q: Trying to use a session variable to export a gridview to Excel I have a report that is generated by passing a few variables via a SQL string.  The problem is, when I try to export the resulting gridview to Excel, the gridview blanks itself out.  I'm trying to use session variables to store the dataset but I don't understand them too well.  Can someone help?
This is the code that runs on page load:
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            SqlConnection sqlconnectionStatus = new SqlConnection(str);
            string DDL_Value = Convert.ToString(Request.QueryString["DDL_Val"]);
            string Val_Value = Convert.ToString(Request.QueryString["Val_Val"]);
            string Trk_Value = Convert.ToString(Request.QueryString["Trk_Val"]);
            string Acct_Value = Convert.ToString(Request.QueryString["Acct_Val"]);
            //Use the ClassTesting class to determine if the dates are real, and fill in today's date if they're blank
            string StDt_Value = ClassTesting.checkFields(Request.Form["txtStartDate"], "Date");
            string EnDt_Value = ClassTesting.checkFields(Request.Form["txtEndDate"], "Date");

            //string StDt_Value = Convert.ToString(Request.QueryString["StDt_Val"]);
            //string EnDt_Value = Convert.ToString(Request.QueryString["EnDt_Val"]);

            string BTN_Value;
            // Because the date is stored as an INT, you have to request the string and then
            //   convert it to an INT
            string StDT_Vals = Request.QueryString["StDt_Val"].ToString();
            string EnDT_Vals = Request.QueryString["EnDt_Val"].ToString();

            string sqlquery;

            if (String.IsNullOrEmpty(Acct_Value))
            {
                if (String.IsNullOrEmpty(DDL_Value))
                {
                    BTN_Value = "2";
                }
                else
                {
                    BTN_Value = "1";
                }
            }
            else
            {
                BTN_Value = "3";
            }
            // Check to see if a specific Agent is being requested
            if (BTN_Value == "1")
            {
                // int StDT_Value = Convert.ToInt32(StDT_Vals);
                // int EnDT_Value = Convert.ToInt32(EnDT_Vals);

                sqlquery = "Select DISTINCT PL.PROC_NM as Agent_Name, CCM.UNIQUE_CLAIM_ID as Issue_Number, CCM.CLAIM_ID as Claim_Number, ";
                sqlquery = sqlquery + "CCM.SOCSEC as Employee_Last_Digit, CONVERT(VARCHAR(10), CCM.DATE_IMPORTED, 101) AS Import_Date, CONVERT(VARCHAR(10), CCM.Orig_Open_Date, 101) as Original_Review_Date, ";
                sqlquery = sqlquery + "AGL.ACCT_GRP as Account_Name, AL.ACCT_NUM as Account_Number, CCM.CDBBEN as Benefit_Option, BT1.StatusText as BenType1, ";
                sqlquery = sqlquery + "BT2.StatusText as BenType2, BT3.StatusText as BenType3, CCM.Cmplt as Review_Validated, CCM.Vldtn_Cmmnts as Validation_Comments, ";
                sqlquery = sqlquery + "CCM.Gtkpr_Cmmnts as Gatekeeper_Comments, TS.StatusText as Tracking_Status ";
                sqlquery = sqlquery + "from ClosedClaims_MERGE CCM ";
                sqlquery = sqlquery + "LEFT JOIN PROC_LIST PL ON CCM.Spare = PL.LOGIN ";
                sqlquery = sqlquery + "LEFT JOIN ACCT_LIST AL ON AL.ACCT_NUM = CCM.CDBACC ";
                sqlquery = sqlquery + "LEFT JOIN ACCT_GRP_LIST AGL ON AGL.ACCT_GRP_PK = AL.ACCT_GRP_FK ";
                sqlquery = sqlquery + "LEFT JOIN TrackingStatus TS ON TS.StatusCode = CCM.TrackingStatus ";
                sqlquery = sqlquery + "LEFT JOIN BenefitType_v3 BT1 ON BT1.StatusCode = CCM.BENEFIT_TYPE1 ";
                sqlquery = sqlquery + "LEFT JOIN BenefitType_v3 BT2 ON BT2.StatusCode = CCM.BENEFIT_TYPE2 ";
                sqlquery = sqlquery + "LEFT JOIN BenefitType_v3 BT3 ON BT3.StatusCode = CCM.BENEFIT_TYPE3  ";
                sqlquery = sqlquery + "WHERE CCM.Spare " + (DDL_Value == "" ? "IS NULL" : "LIKE '" + DDL_Value + "'") + " AND CCM.Cmplt " + (Val_Value == "" ? "IS NULL" : "LIKE '" + Val_Value + "'") + " AND CCM.TrackingStatus IN (" + Trk_Value + ") AND CCM.SpareFinished >= '" + StDt_Value + "' AND CCM.SpareFinished <= '" + EnDt_Value + "'";
            }
            else
            {
                if (BTN_Value == "2")
                {
                    sqlquery = "Select DISTINCT PL.PROC_NM as Agent_Name, CCM.UNIQUE_CLAIM_ID as Issue_Number, CCM.CLAIM_ID as Claim_Number, ";
                    sqlquery = sqlquery + "CCM.SOCSEC as Employee_Last_Digit, CONVERT(VARCHAR(10), CCM.DATE_IMPORTED, 101) AS Import_Date, CONVERT(VARCHAR(10), CCM.Orig_Open_Date, 101) AS Original_Review_Date, ";
                    sqlquery = sqlquery + "AGL.ACCT_GRP as Account_Name, AL.ACCT_NUM as Account_Number, CCM.CDBBEN as Benefit_Option, BT1.StatusText as BenType1, ";
                    sqlquery = sqlquery + "BT2.StatusText as BenType2, BT3.StatusText as BenType3, CCM.Cmplt as Review_Validated, CCM.Vldtn_Cmmnts as Validation_Comments, ";
                    sqlquery = sqlquery + "CCM.Gtkpr_Cmmnts as Gatekeeper_Comments, TS.StatusText as Tracking_Status ";
                    sqlquery = sqlquery + "from ClosedClaims_MERGE CCM ";
                    sqlquery = sqlquery + "LEFT JOIN PROC_LIST PL ON CCM.Spare = PL.LOGIN ";
                    sqlquery = sqlquery + "LEFT JOIN ACCT_LIST AL ON AL.ACCT_NUM = CCM.CDBACC ";
                    sqlquery = sqlquery + "LEFT JOIN ACCT_GRP_LIST AGL ON AGL.ACCT_GRP_PK = AL.ACCT_GRP_FK ";
                    sqlquery = sqlquery + "LEFT JOIN TrackingStatus TS ON TS.StatusCode = CCM.TrackingStatus ";
                    sqlquery = sqlquery + "LEFT JOIN BenefitType_v3 BT1 ON BT1.StatusCode = CCM.BENEFIT_TYPE1 ";
                    sqlquery = sqlquery + "LEFT JOIN BenefitType_v3 BT2 ON BT2.StatusCode = CCM.BENEFIT_TYPE2 ";
                    sqlquery = sqlquery + "LEFT JOIN BenefitType_v3 BT3 ON BT3.StatusCode = CCM.BENEFIT_TYPE3  ";
                    sqlquery = sqlquery + "WHERE CCM.Cmplt " + (Val_Value == "" ? "IS NULL" : "LIKE '" + Val_Value + "'") + " AND CCM.TrackingStatus IN (" + Trk_Value + ") AND CCM.SpareFinished >= '" + StDt_Value + "' AND CCM.SpareFinished <= '" + EnDt_Value + "'";
                }
                else
                {
                    sqlquery = "Select DISTINCT PL.PROC_NM as Agent_Name, CCM.UNIQUE_CLAIM_ID as Issue_Number, CCM.CLAIM_ID as Claim_Number, ";
                    sqlquery = sqlquery + "CCM.SOCSEC as Employee_Last_Digit, CONVERT(VARCHAR(10), CCM.DATE_IMPORTED, 101) AS Import_Date, CONVERT(VARCHAR(10), CCM.Orig_Open_Date, 101) AS Original_Review_Date, ";
                    sqlquery = sqlquery + "AGL.ACCT_GRP as Account_Name, AL.ACCT_NUM as Account_Number, CCM.CDBBEN as Benefit_Option, BT1.StatusText as BenType1, ";
                    sqlquery = sqlquery + "BT2.StatusText as BenType2, BT3.StatusText as BenType3, CCM.Cmplt as Review_Validated, CCM.Vldtn_Cmmnts as Validation_Comments, ";
                    sqlquery = sqlquery + "CCM.Gtkpr_Cmmnts as Gatekeeper_Comments, TS.StatusText as Tracking_Status ";
                    sqlquery = sqlquery + "from ClosedClaims_MERGE CCM ";
                    sqlquery = sqlquery + "LEFT JOIN PROC_LIST PL ON CCM.Spare = PL.LOGIN ";
                    sqlquery = sqlquery + "LEFT JOIN ACCT_LIST AL ON AL.ACCT_NUM = CCM.CDBACC ";
                    sqlquery = sqlquery + "LEFT JOIN ACCT_GRP_LIST AGL ON AGL.ACCT_GRP_PK = AL.ACCT_GRP_FK ";
                    sqlquery = sqlquery + "LEFT JOIN TrackingStatus TS ON TS.StatusCode = CCM.TrackingStatus ";
                    sqlquery = sqlquery + "LEFT JOIN BenefitType_v3 BT1 ON BT1.StatusCode = CCM.BENEFIT_TYPE1 ";
                    sqlquery = sqlquery + "LEFT JOIN BenefitType_v3 BT2 ON BT2.StatusCode = CCM.BENEFIT_TYPE2 ";
                    sqlquery = sqlquery + "LEFT JOIN BenefitType_v3 BT3 ON BT3.StatusCode = CCM.BENEFIT_TYPE3  ";
                    sqlquery = sqlquery + "WHERE AL.ACCT_GRP_FK " + (Acct_Value == "" ? "IS NULL" : "LIKE '" + Acct_Value + "'") + " AND CCM.Cmplt " + (Val_Value == "" ? "IS NULL" : "LIKE '" + Val_Value + "'") + " AND CCM.TrackingStatus IN (" + Trk_Value + ") AND CCM.SpareFinished >= '" + StDt_Value + "' AND CCM.SpareFinished <= '" + EnDt_Value + "'";
                }
            }

            SqlConnection con = new SqlConnection(str);
            SqlCommand cmd = new SqlCommand(sqlquery, con);
            SqlDataAdapter adapter = new SqlDataAdapter(cmd);

            // Fill the DataSet.
            DataSet ds = new DataSet();
            adapter.Fill(ds, "dailyview");

            // Store the dataset in a session variable
            Session["SSQualOfSub"] = ds;

            // Perform the binding.
            GVQualOfSub.DataSource = ds;
            GVQualOfSub.DataBind();
        }

    }

And here is the code I'm using to export:
    private void ExportGridView()
    {
        // Exports the data in the GridView to Excel
        // First call the session variable to refill the gridview
        DataTable gridDataSource = (DataTable)Session["SSQualOfSub"];

        GVQualOfSub.Visible = true;
        GVQualOfSub.DataSource = gridDataSource;
        GVQualOfSub.DataBind();

        string attachment = "attachment; filename=Qual_Of_Subs.xls";
        Response.ClearContent();
        Response.AddHeader("content-disposition", attachment);
        Response.ContentType = "application/ms-excel";
        StringWriter sw = new StringWriter();
        HtmlTextWriter htw = new HtmlTextWriter(sw);
        GVQualOfSub.RenderControl(htw);
        Response.Write(sw.ToString());
        Response.End();

    }

I'm getting an error when I try to export.
Unable to cast object of type 'System.Data.DataSet' to type 'System.Data.DataTable'.
My apologies, I'm somewhat new to C#.  Any help is appreciated.

A: You are storing a DataSet in Session and later you are trying to access it as DataTable.
You should do:
DataSet gridDataSource = (DataSet)Session["SSQualOfSub"];

instead of
DataTable gridDataSource = (DataTable)Session["SSQualOfSub"];

I am not sure about your particular scenario, but usually it is not a good idea to store large amount of data in Session, as it is maintained per user on the server.
Apart from the current error, you should use SqlParameter with your SqlCommand, you are concatenating queries and prone to SQL Injection


text:
Q: Filtering with conditional conditions (pandas) I have an array with multiple strings, some of them are none(0 or ''), and each of them should have their own conditions if exists. if the array at its position is none, I don't have to apply the filtering.
# df.columns = ['a','b','c','d','e']

# Case 1
l = ['A', 'B', '','' , 123]
## DESIRED FILTERING
df[ (df.a=='A') & (df.b=='B') & (df.e == 123)]

# Case 2
l = ['z','' ,'' ,'', 123]
## DESIRED FILTERING
df[ (df.a=='z') & (df.e == 123) ]

This is my attempt, yet it failed cuz (df.col_name == 'something') returns a series.
#Case 1 for example

check_null = [ i!='' for i in l ]       # ->returns [true,false,...]
conditions = [ (df.a==l[0]),(df.b==l[1]),(df.c==l[2]), (df.d==l[3]), (df.e==l[4])]
filt = [conditions[i] for i in range(len(check_null)) if check_null[i]]

df[filt]

How do I manage to get this work?

A: Create dictionary for non empty values, convert to Series and filtering in boolean indexing:
df = pd.DataFrame(columns = ['a','b','c','d','e'])
df.loc[0] = ['A', 'B','g' ,'h' , 123]
df.loc[1] = ['A', 'B','g' ,'h' , 52]

l = ['A', 'B','' ,'' , 123]

s = pd.Series(dict(zip(df.columns, l))).loc[lambda x: x != '']

df  = df[df[s.index].eq(s).all(axis=1)]
print (df)
   a  b  c  d    e
0  A  B  g  h  123

l = ['A', 'B', '','', '']
s = pd.Series(dict(zip(df.columns, l))).loc[lambda x: x != '']

df  = df[df[s.index].eq(s).all(axis=1)]
print (df)
   a  b  c  d    e
0  A  B  g  h  123
1  A  B  g  h   52

A: You can use a Series for comparison.
Either ensure that the value matches the Series (df.eq(s)), or (|) that the Series contains a empty string (s.eq('')). Broadcasting magic will do the rest ;)
s = pd.Series(l, index=df.columns)

df2 = df[(df.eq(s)|s.eq('')).all(1)]

Example with ['A', 'B', '', '', 123]:
# input
   a  b  c  d    e
0  A  B  C  D  123
1  A  X  C  D  456

# output
   a  b  c  d    e
0  A  B  C  D  123


text:
Q: Drawing line in flash- via Action script I need to draw a line in ActionScript(based on calculated conditions for length and rotation)
I tried the following code- the triangle with the fill appears- but not the line with the lineStyle- Could you pls help me out on this... c is defined as UIComponent
var myShape:Shape=new Shape();
myShape.graphics.moveTo(100,100);
myShape.graphics.lineTo(200,200);
myShape.graphics.lineStyle(2,0xFF0000,.75);
c.addChild(myShape);

var triangleHeight:uint = 100;
var triangle:Shape = new Shape();
// red triangle
triangle.graphics.beginFill(0xFF0000);
triangle.graphics.moveTo(triangleHeight/2, 200);
triangle.graphics.lineTo(triangleHeight, triangleHeight);
triangle.graphics.lineTo(0, triangleHeight);
triangle.graphics.lineTo(triangleHeight/2, 200);
c.addChild(triangle);

A: You should declare line style before your drawing.


text:
Q: How to re-open modal window after ModalState is invalid with the errors shown? I have a login modal window which has validation. The problem is that I can not re-open the modal window when the validation fails.
So, I have this controller: Index() which returns the View of the homepage. On that homepage, I have the modal window which has the validation.
But after clicking the submit button (Login() controller), and after validation failure, the URL is /Index/Login and I can not pass ViewBag value which tells the modal to re-open.
Here is the code from both controllers:
public ActionResult Index()
 {
   return View();
 }

[HttpPost]
public ActionResult Login(Users user)
{
 if (ModelState.IsValidField("username") && ModelState.IsValidField("password"))
    {
      if (Users.Login(user))
          {
           //some custom logic
           return RedirectToAction("../Dashboard/Dashboard");
          }
          else
          {
              ViewBag.LoginError = "Wrong username/password";
          }
      }
      else
      {

      }
      return View("Index");
  }

I really need help guys. I am trying to solve this the whole day!
PS: I work with Razor syntax on the front.

A: If you have the section scripts in your _Layout.cshtml which is in the /Views/Shared/_Layout.cshtml then paste the below code at the end of the /Views/Home/Index.cshtml.
@section scripts
{
    <script>

        @if(ViewBag.LoginError == "Wrong username/password")
        {
            WriteLiteral("$('#login-modal').modal('show');");
        }
    </script>
}

This can be done ajax way too however above is the solution to your question.
If the section scripts is not defined in _Layout.cshtml, then define this section at the end of the _Layout.cshtml just like below.
@RenderSection("scripts", required: false)


text:
Q: Can we put /boot and /root on separate drives? In my laptop, I've 2 drives. 1 is NVMe Intel Optane SSD of 16Gb and another is 1TB HDD. Currently, /home is mounted to 1TB HDD and Linux File system is mounted on SSD. I want to mount only /boot to the SSD and everything else (/root and /home) to HDD. Is it possible that out of entire Linux, /boot is on SSD and /root (and everything else) is on separate HDD? During installation of Ubuntu, can I select /boot to be on SSD and / (just slash) to be on HDD?
(16GB is very less and I can very quickly fill that if I install good amount of apps. But the SSD is fast, so I want /boot on that and everything else on HDD)

A: First, a little deduction: The question's confusion between /root (the root account's directory) and / (the filesystem root directory, which has nothing to do with the root account) suggests that you are a new user.
The phrasing of the question suggests that you are in the process of making a classic new-user mistake: Over-planning and over-partitioning. Your previous Windows experience will generally lead you to wrong answers, since Windows and Linux work quite differently.
Advice #1: Make your first install successful, not perfect. Keep it simple. Go with the installer defaults, even if they are not quite what you want yet. Once you can successfully install, then turn-round and use your experience to re-install with the customizations or additional complexity that you want.
Advice #2: New power-users coming from Windows often love that Linux distros let you see and poke all the spinning gears. However, poking your finger into spinning gears will injure your finger and break the machine. So keep your hands in your pockets and don't poke something until you have researched what you are poking and what the consequences are. And keep proper backups so you can restore the machine when you break it.
Advice #3: Many new power-users who customize their install decide to backup-and-repartition after a few months of experience. Their partition usage sizes don't match their original estimates, so one partition is full while another is nearly empty. Be prepared to admit that your guesses about the future might not be accurate predictions, and prepare accordingly.
Advice #4: Most laptop users suspend or hibernate rather than fully poweroff or reboot. With longer battery life, I've seen suspend replace hibernation among my peers. So maybe a /boot partition on SSD is important...and maybe it's not. Keep in mind that the /boot partition contains ONLY the Linux kernel --and not the many GB of the rest of the operating system-- so putting it on the SSD may not speed your boot as much as you hope. You have all the tools you need to try /boot on both SSD and HDD, to time each method, and make your own decision...if you know how to use those tools.
Advice #5: For most general-purpose users, 16GB is plenty for everything outside of your /home directory. /home is where you store all your movies and music and mail and other voluminous data. So /home on the big HDD and everything else on the smaller SSD. Try that simple configuration before diving too deep into more complex alternatives.


text:
Q: ActiveJDBC - how to define models you are trying to work with models, but no models are found. Maybe you have no models in project, or you did not instrument the models. It is expected that you have a file activejdbc_models.properties on classpath
Caused by: activejdbc.InitException: you are trying to work with models, but no models are found. Maybe you have no models in project, or you did not instrument the models. It is expected that you have a file activejdbc_models.properties on classpath
at activejdbc.ModelFinder.findModels(ModelFinder.java:46)
at activejdbc.Registry.init(Registry.java:97)
at activejdbc.Model.<clinit>(Model.java:53)
... 2 more

thanks,

A: this has already been answered:
Can't get activejdbc working?
Basically, you are missing an instrumentation step after compilation. If you are using Maven see this simple example: https://github.com/javalite/simple-example
if you are using Ant, see this: https://github.com/javalite/ant-example
Refer:
     http://javalite.io/getting_started
thanks


text:
Q: EndSale() function in Solidity fails I have the following solidity code:
function endSale() public {
    require(msg.sender == admin);
    require(tokenContract.transfer(admin, tokenContract.balanceOf(address(this))));

    // UPDATE: Let's not destroy the contract here
    // Just transfer the balance to the admin
    msg.sender.transfer(address(this).balance);
}

For some reason, it fails when I invoke the function. I'm using pragma solidity 0.6.0;
Could you please help? Thanks!

A: Firstly, this line of code
require(tokenContract.transfer(admin, tokenContract.balanceOf(address(this))));

tells your contract to transfer its entire balance to the admin address, requiring that the result of the call to transfer evaluates to true, otherwise the function fails and the state reverts, preventing further execution.
Then, calling:
msg.sender.transfer(address(this).balance);

attempts to transfer the total balance of this contract, again.
One thing to note, require statements can ensure the conditions of the contract's state are met before the body of the function is even executed, when declared and used as a modifier statement declared in the contract.
The other thing is, calls to .transfer do not return anything, they only propagate errors that occur. There is an alternative work around using the function .send() which does return a bool but it is not very syntactically appealing and its use is not recommended, unless necessary or you know what you are doing, since the programmer is required to explicitly required to call revert() in the event the call returns false and can cause severe bugs if neglected.
so in effect, calling
require(tokenContract.transfer(admin, tokenContract.balanceOf(address(this))));

should always terminate with an exception, since it neither evaluates to true nor false and solidity has no concept of the ubiquitous NULL value in most other programming languages.
You can determine if this is the case by adding a string as the second parameter to the  require call, which will output a log message when the condition evaluates to false.
Then, if for some reason that isn't what is terminating execution, you are also attempting to transfer the balance of your contract, before calling your method to transfer its balance, again.
This is a major logical error/bug and would attempt to cause a transfer of the same amount again (after the contract has already done so) which is referred to as a double payment, but it should no longer have a balance, since it has been transferred to the admin, via the previous call inside require();.
A reasonable solution then might look similar to this:
modifier onlyAdmin(){
    require(msg.sender == admin, "only an admin may access this method");
    _;
}

modifier nonZeroBalance(){
    require(tokenContract.balanceOf(address(this)) > 0 wei, "contract requires a non-zero balance to execute");
    _;
}

function endSale() public onlyAdmin nonZeroBalance {
    //
    // require this contract to have a non-zero balance (or any other appropriate value as required) before accepting transfers since,
    // it's a waste of gas to transfer nothing
    //
    // now transfer should work alright and will throw and exception,
    // should .transfer fail in any way
    uint256 previousBalance = address(this).balance;
    //
    msg.sender.transfer(previousBalance);
    //
    //transaction complete, this contract's balance is now 0
    //
    //perform additional sanity checks to ensure this contract and the admin's
    //state are what should be expected, otherwise call revert() or throw()
}


text:
Q: Set "human" app name for facebook app I have created a Facebook app that is accessible at https://apps.facebook.com/12345678 , but I only have a URL with a cryptic app id. Where can I set a name for the app so that I have a nice URL like https://apps.facebook.com/onthefarm ?
Thank you!

A: Yes you can  :)

*

*Go to https://developers.facebook.com/apps/{your app id}/summary

*Edit the "App Namespace" field.

*Save


text:
Q: Accessing FacesContext from Web Service I'm developing a Web Service which will be called by clients which are written by me. In the web service I need to use application-wide objects which eases the load of application on the system. I have implemented my application-wide objects as shown in this question.
I can use my object in a jsf page with no problem as follows.
MyObject mo = (MyObject) FacesContext.getCurrentInstance().getExternalContext().getApplicationMap().get("MyObjectsName");

But when it comes to use it in a Web Service Request FacesContext.getCurrentInstance() returns null. Is there any way to use the FacesContext in a web service.

A: It is null, because web services don't come through the Faces Servlet. And this is the way it should be, because web services have nothing to do with JSF.
In case you are using a jax-ws implementation, you can use:
@Resource
WebServiceContext context;

This will inject the WebServiceContext, by which you can:
ServletContext servletContext = (ServletContext)
     context.getMessageContext().get(MessageContext.SERVLET_CONTEXT);

And having the ServletContext, you can access your application-scope objects.


text:
Q: Where should macros like HAVE_SYS_UIO_H be defined? I need to include a header file which needs HAVE_SYS_UIO_H to be defined. My system do actually have sys/uio.h, but the macro isn't defined automatically. For the moment, I can define it before including the header, but this is obviously a bad idea.
What do I need to do to get HAVE_SYS_UIO_H (and other macros like it) to be defined correctly?

A: Usually things like "HAVE_SOMETHING" are defined in Makefiles generated by "./configure" script which actually makes test programs and tries to compile and run them to figure out whether a particular system has a particular thing or not.

A: Have some logic in your makefile that checks for the presence of the header and adds -DHAVE_SYS_UIO_H if so. Using automake may make this easier or prompt the user to provide the values (e.g. via make CONFIGURE).


text:
Q: Android: inverted color on dark mode I have troubles with some imageview on certain Android phones.
It seems that the dark mode invert the color of certains assets (not all, it seems only black/dark gray ones)
An example.

I cannot find a way to avoid this. Is there some kind of properties that protect the image from being inverted?

A: you can use
setForceDarkAllowed(false)
if you just want to apply this to one View.
Or you can change the attributes/colors in your res/values-night folder, which holds all colors that are used in case the dark mode is activated.

A: You can disable Dark mode on your app by using:
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO)

If you want to disable it on a view, you can

*

*Use light style for a specific view

*Use android:forceDarkAllowed="false"


text:
Q: Can't perform Really Simple Firebase Database update using Angular 4 and Firebase 2 The web app I'm building is incredibly simple, and uses Angular 4 and firebase2. It lists a table with songs (Title, Artist, <3 icon and number of likes)
I made an object/array on Firebase with the list of of songs, each being an object with the 3 aforementioned properties. I am trying to make it so that when a user clicks on the heart of a song, the number of likes goes up by one, but none of the functions I've tried seem to work. Below are my attempts at this addLike function, as well as the resulting error, and below that is the full code of my html template, and component, and data structure. Any help would be appreciated. Thank you!
addLike(index){
this.songs.update(index, { likes: this.songs[index] + 1 });

}

//(23,1): Supplied parameters do not match any signature of call target.

addLike(index){
this.songs[index].update({likes: this.songs[index] + 1 });
}
//ERROR TypeError: Cannot read property 'update' of undefined

Here is the full code

//COMPONENT HTML

 TEST

        Title
        Artist
        Likes

{{ song.title }}
{{ song.artist }}
{{ song.likes }}

            <i class="fa fa-heart-o" aria-hidden="true"  *ngIf="song.likes < 1">
         = 1">

//COMPONENT TS

import { Component } from '@angular/core';
import { AngularFireDatabase, FirebaseListObservable, FirebaseObjectObservable } from 'angularfire2/database';
import { AngularFireAuthModule,AngularFireAuth} from 'angularfire2/auth';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})

export class AppComponent {
    title = 'Oxcord';

  songs: FirebaseObjectObservable<any>;
   constructor(db: AngularFireDatabase) {
    this.songs = db.object('/songs');
  }

  addLike(index){
this.songs[index].update({likes: this.songs[index] + 1 });

}

}

{
  "songs" : [ {
    "artist" : "J Cole",
    "likes" : 3,
    "title" : "No Role Modelz"
  }, {
    "artist" : "Michael Jackson",
    "likes" : 8,
    "title" : "Thriller"
  }, {
    "artist" : "Meek Mill",
    "likes" : 0,
    "title" : "Trash"
  }, {
    "artist" : "Kendrick",
    "likes" : 6,
    "title" : "Humble"
  }, {
    "artist" : "Missy",
    "likes" : 4,
    "title" : "Work It"
  } ]
}

A: You're updating your local songs property. You should update your database instead:
addLike(id: string, likes: number): void {
  this.db.object(`/songs/${id}`).update({ likes: likes + 1 });
}

That way, you can call the addLike method in your songs list passing the song key and the current amount of likes:

Then, in your method, you can update the number of likes at that song location in your database.
See the documentation for more details.


text:
Q: Blueshift in a rotating frame The edge of a spinning disc with sufficiently low mass to exclude gravity effects emits a light signal received in the center of the disc. Does the acceleration towards the center imply that the signal is blueshifted, alternatively is a signal from the center blueshifted as seen from the edge?

*

*And does relativity enter the calculation?

A: There is no kinematic blueshift because the edge is not moving toward (or away from) the center, but there is a frequency shift that arises entirely due to relativity. Since the edge of the disc is moving, its clocks run slower (in the center's frame), so the signal received by the center is slowed, i.e. redshifted. Another perspective is that within the frame of a section of the disk, there is a gravitational field pointing away from the center (which is responsible for the centrifugal force), so light climbing toward the center is redshifted.


text:
Q: Reloading JSP page I have an authorization frame displayed on every page and I want to keep that page displaying even if the user will choose to log in (using jstl tags i will simply put instead of this frame user info and link to shopping cart). How can i achieve that ? I have some ideas, but they all breaking out my controller design.
public class FrontController extends HttpServlet {

private ActionContainer actionContainer = ActionContainer.getInstance();

public FrontController() {
    super();
}
/**
 * Processes requests for both HTTP GET and POST methods.
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@SuppressWarnings("unchecked")
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String page = null;

    try {
        Action action = actionContainer.getAction(request);
        page = action.execute(request, response);
        RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(page);
        dispatcher.forward(request, response);

    } catch (ActionNotFoundException e) {
        RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(PageNames.ERR_PAGE);
        request.setAttribute(AttributeNames.ERR_MESSAGE_ATTRIBUTE, "Unknown Action command: " + e.getMessage());
        dispatcher.forward(request, response);
    } catch (Exception e) {
        RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(PageNames.ERR_PAGE);
        request.setAttribute(AttributeNames.ERR_MESSAGE_ATTRIBUTE, "Exception:\n" + e.getMessage());
        dispatcher.forward(request, response);
    }
}

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    processRequest(request, response);
}

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    processRequest(request, response);
}

/**
 * Returns a short description of the servlet.
 * @return a String containing servlet description
 */
@Override
public String getServletInfo() {
    return "Front Controller";
}

@Override
public void init() throws ServletException {
    super.init();
    Locale.setDefault(new Locale("ru","RU"));
}

}
I was thinking about of redirecting to especially written for this case page, which will redirect to the original page, or to check page string for null and reloading from controller the original page, but i cannot clearly understand how to do this.

A: Your question isn't clear enough. But I think you're asking how you can replace a certain component on a page (Login button) with an other (username, welcome message and shopping cart details) after the user logs in.
If I understand your requirements, then what I would do after the user logs in is set a cookie (or a value in localStorage). The cookie is added to the Set-Cookie response header by means of the addCookie method of HttpServletResponse. Here's an example:
  Cookie userCookie = new Cookie("user", "uid1234");
  response.addCookie(userCookie);

Then in your controller simply check if the "user" value is set or not and take the appropriate action. A tutorial on servlets with cookies.
If you need to handle the front-end component, and change values on the form without reloading the page, I would recommend using javascript to do this, you can find and remove the old DOM elements with new ones (User's name, Welcome message, shopping cart, whatever).
If your iFrame is doing the login, then on successful login, have it call a function in your top window that does the update after reading the updated values from the cookie.
If you want to handle this completely at the front-end, i.e. Javascript, then I would skip using cookies and use localStorage instead. There is plenty of help on Stackover and on the internet about what localStorage is, but I will suggest the YUI Storage Lite library which makes storing and loading data from localStorage very simple.
Regards,

A: Include the current URL as a hidden field of your authentication form. In the action handling the authentication, once the user is authenticated, redirect to this URL.
In the JSPs, test if the user is authenticated and include the authentication form or the shopping cart. This test can be done by just putting a boolean value in the HTTP session once the user is authenticated.


text:
Q: Wordpress Homepage Overflow and Creating Blank Space I am using BeTheme. I tried following: Removed Slider and Tried Removing Content but still problem is same. Whereas other page works fine

A: Add this css and check
@media(max-width:767px){
    body.mobile-side-slide {
       margin: 0px;
       overflow: auto !important;
    }
}


text:
Q: Derivation of $a_{j}$ coefficients in the quantum harmonic oscillator In Griffiths' book page 53, when we derive the solution of the quantum harmonic oscillator by using the power series way, we have: $$a_{j+2} = \frac{2j+1-K}{(j+1)(j+2)}\, a_{j} .$$ And for large $j$, we have: $$a_{j+2}\approx\frac{2}{j}\,a_j.$$ Up to this point I totally agree (one just takes the limit).
However, the subsequent derivation of solution $a_{j}$ and $h(\xi)$ I attached from the Griffiths' textbook are very confusing.

*

*How did it go from $a_{j+2}\approx\frac{2}{j}a_j$ to the solution of $a_{j}$?

*Also, how do the second and third approximations work in $h(\xi)$?

My questions are mainly mathematical. I very much hope someone can provide a derivation or refer a link where these questions may already be answered.

A: Looking at even indices, from $a_{2j_0+2} \approx \frac{1}{j} a_{2j_0}$, we get :
$$a_{2j_0+2k} \approx \frac{(j_0-1)!}{(j_0+k-1)!}a_{2j_0} = \frac{1}{(j_0+k)!} C \tag{1}$$, with $C=(j_0+k)\,(j_0-1)! \,\,a_{2j_0}$
So, taking $n= 2(j_0+k)$, we have finally $a_{n} \approx \frac{1}{(n/2!)} \, C$
Finally, $h_{even}(\xi) \approx \sum\limits_{n= j_0 + 1}^{+\infty}a_{2n} \xi^{2n}= C\sum\limits_{n= j_0 + 1}^{+\infty}\frac{1}{n!} (\xi^2)^n $
The  behaviour of $h_{even}(\xi)$ for high $\xi$, is then the same as the behaviour of $C\sum\limits_{n= 0}^{+\infty}\frac{1}{n!} (\xi^2)^n = C e^{\xi^2}$
You have the same demonstration for $h_{odd}(\xi)$, so finally, the behaviour of $h(\xi)$ for high $\xi$ is $C e^{\xi^2}$, too.
UPDATE
(to answer to the OP's comments)
a) You have : $a_{2j_0+2} \approx \frac{1}{j} a_{2j_0}$, then you apply the formula to $(j_0+k)$ : $a_{2j_0+2k} \approx \frac{1}{j_0+k-1} a_{2j_0+2k-2}$, so finally, you have : $a_{2j_0+2k} = \frac{1}{(j_0+k-1)(j_0+k-2)...(j_0)}a_{2j_0}$. You multiply numerator and denominator by $(j_0+k)(j_0-1)!$, and you get the formula $(1)$
b) The identity is $e^y = \sum\limits_{i=0}^{+\infty}\dfrac{y^n}{n!}$
c) You have to choose some particular $j_0$ as a departure point for the recurrence relation described in a). I used this notation to show that $j_0$ is not a variable, it is fixed.
d) The identity described in b) is true for all $y$, because the serie is convergent for all $y$


text:
Q: Java 8+ API desugaring support for pure kotlin modules I'm trying new Java 8+ API desugaring support (Android Gradle Plugin 4.0.0+)
Everything is fine with android app and android library modules but in pure kotlin modules desugared API's get highlighted red with errors similar to:

Call requires API level 26 (current min is 21):
  java.time.LocalTime#parse

Everything compiles and works well.
Is there something in .gradle file that needs to be specified or is it a bug in IDE?

A: This seems to be a known bug on the google issue tracker


text:
Q: Import bootstrap error: Unexpected token, test-utils, working in one test but not another I'm new to unit testing with jest in vue.
I have added the plugin unit test from here: https://www.npmjs.com/package/@vue/cli-plugin-unit-jest
It have created a test folder with another folder called unit where I have placed 2 files: Footer.spec.js and Main.spec.js. It also created a jest.config.js file.
Footer.spec.js
import '../../src/plugins/fontawesome'
import { mount } from '@vue/test-utils'
import Footer from '../../src/components/Footer/Footer.vue'
import BootstrapVue from 'bootstrap-vue'
import { createLocalVue } from '@vue/test-utils'

describe('Footer', () => {
  const localVue = createLocalVue()
  localVue.use(BootstrapVue)
  const wrapper = mount(Footer, {localVue})

  it('has a FooterPhoneNumber', () => {
    expect(wrapper.html()).toContain('some HTML')
  })

  it('has a FooterEmail', () => {
    expect(wrapper.html()).toContain('some HTML')
  })
})

Main.spec.js
import '../../src/plugins/fontawesome'
import { mount } from '@vue/test-utils'
import Main from '../../src/components/Main.vue'
import BootstrapVueMain from 'bootstrap-vue'
import { createLocalVueMain } from '@vue/test-utils'

describe('Main', () => {
  const localVueMain = createLocalVueMain()
  localVueMain.use(BootstrapVueMain)
  const wrapper = mount(Main, {localVueMain})

  it('the modal for browser not compatible', () => {
    expect(wrapper.html()).toContain('some HTML')
  })
})

From the jest.config.js
 transformIgnorePatterns: [
   '/node_modules/(?!(bootstrap|bootstrap-vue)/)',
   '/node_modules/',
 ],

I'm getting an error because of 2 imports:
     import 'bootstrap/dist/css/bootstrap.css'
     | ^
  18 | import 'bootstrap-vue/dist/bootstrap-vue.css'

The Footer.spec.js pass the test but the Main.spec.js dosen't.
Any suggestions on how to fix it?

A: In the Main.spec.js you are importing and using createLocalVueMain(), instead of createLocalVue(). Because of that, BootstrapVue is not registered to localVue instance - because it was not created.


text:
Q: Using functions as input I've written a program (A) that takes, as input, the names of functions I wrote in a separate program (B). I want to use these functions in program (A), so I am trying to run (A) by doing this: A(f1, f2, f3, f4)
At the top of (A), I imported program (B) using import B. In (A) there is just one function (excluding main) that accepts four inputs (f1, f2, f3, f4), and then uses them, like this:
    for i in range(x, y):
       z = B.f1(i)
       u = B.f2(i)
       ...
    ...

The trouble is, when I try to run A(f1, f2, f3, f4), I get the error
Traceback (most recent call last):
   File "<pyshell#0>", line 1, in <module>
      A(f1, f2, f3, f4)
NameError: name 'f1' is not defined

I see that python is not recognizing the functions in (B) as input in (A), but I don't know why or how else I can connect the two programs.
Update: Program A
def A(f1, f2, f3, f4) :

   x = 0
   y = 10

   for i in range(x, y):
       x = B.f1(i) //returns float
       plt.plot(i, x)
   ...

A: Based on a literal reading of your question, if you imported B via
import B

then every reference to functions, variables, classes etc defined in B must be done in the form B.func1 etc.
Your error message clearly says that you're trying to do A(f1, f2, f3, f4).  This should be A(B.f1, B.f2, B.f3, B.f4)
EDIT Judging from your updated question, I'm guessing you want something like:
import B

def A(input_function1, input_function2, input_function3, input_function4) :
    x = 0
    y = 10

    for i in range(x, y): #btw, you don't need the x value here if it's 0
        x = input_function1(i) //returns float #I removed the 'B.'
        plt.plot(i, x)
    # Other stuff here

if __name__=='__main__':
    A(B.f1, B.f2, B.f3, B.f4)
    # or alternatively A(B.f78, B.f21, B.f1, B.f90) or whatever

Or alternatively:
from B import f1, f2, f3, f4

def A(f1, f2, f3, f4) :
    # Stuff here

if __name__=='__main__':
    A(f1, f2, f3, f4) # Explicit imports mean that the 'B.' prefix is unnecessary

A: To extend what @zehnpaard has already suggested, if you want to call the B function in A() using f1...f4 as arguments, you can alternatively use getattr(), like this:
...
def A(f1, f2, f3, f4) :

   x = 0
   y = 10

   for i in range(x, y):
       x = getattr(B, f1)(i)
       plt.plot(i, x)
   ...

getattr(B, f1) will return the function as in B.f1, and you call the function and pass the argument i with (i), just like: getattr(module, function)(*args).
For example: getattr(plt, 'plot')(i, x) = plt.plot(i, x)
Pay attention that you pass plot as string 'plot', so when you're trying to call function A(), you will do:
if __name__=='__main__':
    A('f62', 'f22', 'f2323', 'f100')

As a side note: if the function you pass is not in B, it will raise AttributeError.
Hope this helps.

A: Sounds like you have the following defined in your interactive session
import B

def A(f1, f2, f3, f4):

    for i in range(10):
        plt.plot(i, f1(i))

And the user should call it by doing:
>>> A(B.f1, B.f49, B.f100, B.f42)