text:
Q: What is the exact meaning of 'leverage' in this sentence? "Developers like Google, Airbus and Huawei are racing to leverage these materials and others into transistors that could make conventional microchips obsolete and deliver "quantum computing" -- massive new levels processing power with far less energy consumption."
I looked up the leverage in the dictionary which gives

*

*(formal) the ability to influence what people do.

*(technical) the act of using a ↑lever to open or lift sth; the force used to do this.

*(finance) the relationship between the amount of money that a company owes and the value of its shares

I think all the explanations do not fit the meaning of the sentence here. What is the exact meaning and how to use this word?

A: It is a figurative usage of leverage that suggests the improvement of something:
To leverage:

*To improve or enhance: "It makes more sense to be able to leverage what we [public radio stations] do in a more effective way to our listeners" (Delano Lewis).

(AHD)
The sense is that the developers are racing to improve, make more effective, these materials that could outperform conventional microchips.


text:
Q: Selection of a group of dropdown box values using each statement in jquery I want to write a simple code in Velocity Template Language (VTL). I have a group of dropdowns, I want iterate through all the dropdowns and get the values of each dropdown and count the number of selected values under each distinct category. The code is listed below:
#macro( macroYesNoSelect $fieldId $section )
<select  name='${fieldId}' id='${fieldId}' section='${section}' ischanged="">
    <option value="Yes"
        #if ($Form.getFieldValue("${fieldId}") == "Yes")
            selected
        #end
    score="1">Yes</option>
    <option value="No"
        #if ($Form.getFieldValue("${fieldId}") == "No")
            selected
        #end
    score="0">No</option>
    <option value="N/A"
        #if ($Form.getFieldValue("${fieldId}") == "N/A")
            selected
        #end
    score="0">N/A</option>
</select>
#end

Javascript:

HTML code:

        Question1 ?

            #macroYesNoSelect ( "id1" "Questions" )

         Question2 ?

            #macroYesNoSelect ( "id2" "Questions" )

         Question3 ?

            #macroYesNoSelect ( "id3" "Questions" )

I want to select the number of YES, NO and NA as per my selection. But when I call the function calcYesNO(), I am unable to calculate them...
Can someone help me on resolving this?
Thanks
Kishore

A: jQuery is smart about retrieving <select> values; you can call .val() directly. I also recommend being more explicit with the each() iterator, since the "this" keyword can have unexpected values in certain circumstances.
$("select[section='"+ sectionName +"']").each(function(n, element){

     if($(element).val() == 'Yes')
     {
      optionYes=optionYes+1;
     }
     else if($(element).val() == 'No')
     {
      optionNo=optionNo+1;
     }
     else
     {
      optionNA=optionNA+1;
     }
    }

That said, your existing code looks like it should work. Have you verified that $("select[section='"+ sectionName +"']") is actually retrieving the select menu?

redpajama_set_name: RedPajamaStackExchange


text: Q: Retrieve values from AmCharts 5 Axis I would like to retrieve only the values which are rendered, I found _minReal and _maxReal but they are the absolute ends of the value range(so even when I zoom in, they remain constant). I need this to be able to refetch data when zooming in.


text:
Q: Color Schemes don't look right in CLI vim I was having a bit of trouble reading the dark red strings of Vim's default color scheme, so I decided to switch to a different one.
http://code.google.com/p/vimcolorschemetest/source/browse/colors/blackboard.vim?r=2
http://files.werx.dk/wombat.vim
However, when I set my color schemes to these, not only do they not come out correctly (for example, comments are bright blue), but these 2 somehow come out looking exactly the same!
Am I doing something wrong, or are these colors restricted in the terminal so default colors are being chosen?

A: Couldn't load the first link.  The second link changes the colors for the gui (i.e., for gVim) only, not the colors for vim in a terminal
Look up the docs for the 'highlight' command, which will show you that guifg and guibg are options that set the color for text foreground and background in gVim, and ctermfg and ctermbg are the corresponding options to set colors in terminal vim.
So if you wanted to make Comments in both terminal and gui versions have the same colors you might issue a command like this:
  :hi Comment ctermfg=Cyan guifg=Cyan ctermbg=black guibg=black


text:
Q: Why plot to a handle erase the previous object even with `hold on`? Why does the line
plot(handle, 3, 3, 'ro')

clears the figure in handle even I set hold on?
Full Code
hold on
figure(1);
hdl.r = subplot(121);
hdl.t = subplot(122);
plot(hdl.r, 1, 1, 'ro');
plot(hdl.r, 1, 2, 'ro');

There's always only one dot in my figure.

A: Hold applies to axis, when having multiple axis I would always use the "long" version of hold (hold(axis_handle,'on'))
figure(1);
hdl.r = subplot(121);
hdl.t = subplot(122);
hold(hdl.r,'on');
hold(hdl.t,'on');
plot(hdl.r, 1, 1, 'ro');
plot(hdl.r, 1, 2, 'ro');


text:
Q: mysql fetch data from multiple table with one to many foreign key reference Hi i have to write a mysql query i will explain the query how i want to work.
I have two table
A
CREATE TABLE IF NOT EXISTS `A` (
  `field1` int(10) NOT NULL AUTO_INCREMENT,
  `field2` int(10) NOT NULL,
  `field3` int(10) NOT NULL,
  `field4` varchar(255) DEFAULT NULL,
  `fields5` int(10) NOT NULL,
  `field6` varchar(255) NOT NULL,
  `field7` varchar(255) NOT NULL,
  `field8` int(10) NOT NULL,
  `field9` tinyint(1) NOT NULL COMMENT '1=for enabled resource 0= for
disabled resource',
  PRIMARY KEY (`field1`);

table B
CREATE TABLE IF NOT EXISTS `estimate_resource_mth` (
  `field1` int(10) NOT NULL AUTO_INCREMENT,
  `field2` int(10) NOT NULL,
  `field3` int(10) NOT NULL,
  `field4` int(10) NOT NULL,
  PRIMARY KEY (`field1`) ;

There is one to many reference from tableA to tableB that is A.field1 multiple reference to B.table2. Now i will explain what i need to get, i have an id which fetch the data from table A using where condition i need to return this list with the sum of filed4 in tableB(field2 in tableB reference to tableA and it may be a multple row one to many relatio ). How could i got a this data in a single query.

A: Your description is poor and your generic column names are not very helpful, but if I understand, tableB.field2 references tableA.field1.  In that case, a LEFT JOIN with an aggregate SUM() on tableB.field4 will do the job.
SELECT
  tableA.field1,
  SUM(tableB.field4) AS the_sum
FROM
  tableA
  LEFT JOIN tableB ON tableA.field1 = tableB.field2
WHERE
  /* IN() for multiple possible vals. Use = if only 1 val needed
     and then the GROUP BY is unnecessary */
  tableA.field1 IN ('val1','val2',val3')
GROUP BY tableA.field1


text:
Q: Do not collapse AppBarLayout when scrolling down I have a fragment with such a layout
    <?xml version="1.0" encoding="utf-8"?>
    <android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.v7.widget.RecyclerView
        app:layout_behavior="@string/appbar_scrolling_view_behavior"
        android:id="@+id/list"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

    <android.support.design.widget.AppBarLayout
        android:background="?attr/cropperBckColor"
        android:id="@+id/appBarLayout"
        android:layout_width="match_parent"
        android:layout_height="@dimen/cropper_height"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

        <android.support.design.widget.CollapsingToolbarLayout
            android:id="@+id/collapsingToolBarLayout"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:layout_scrollFlags="scroll|exitUntilCollapsed"
            app:statusBarScrim="@android:color/transparent"
            app:contentScrim="@color/transparent">

            <com.paralect.mediapicker.custom_views.cropper.ImageCropperView
                android:id="@+id/image"
                app:layout_collapseMode="parallax"
                app:layout_collapseParallaxMultiplier="0.0"
                android:layout_width="match_parent"
                android:layout_height="match_parent"/>

            <android.support.v7.widget.Toolbar
                app:layout_collapseMode="pin"
                app:contentInsetLeft="0dp"
                app:contentInsetStart="0dp"
                android:layout_gravity="bottom"
                android:layout_width="match_parent"
                android:layout_height="@dimen/my_tab_height">
                <RelativeLayout
                    android:layout_width="match_parent"
                    android:layout_height="match_parent">
                    <android.support.v7.widget.AppCompatImageView
                        android:layout_alignParentBottom="true"
                        style="@style/Icon"
                        android:src="@drawable/ic_rezoom"
                        android:id="@+id/rezoom"
                        android:layout_alignParentLeft="true"
                        android:layout_alignParentStart="true" />

                    <android.support.v7.widget.AppCompatImageView
                        android:layout_alignParentBottom="true"
                        style="@style/Icon"
                        android:src="@drawable/ic_multiple_disabled"
                        android:id="@+id/multiSelect"
                        android:layout_alignParentEnd="true"
                        android:layout_alignParentRight="true" />
                </RelativeLayout>
            </android.support.v7.widget.Toolbar>
        </android.support.design.widget.CollapsingToolbarLayout>
    </android.support.design.widget.AppBarLayout>
</android.support.design.widget.CoordinatorLayout>

The coordinator layout is working as expected but I want to change the behaviour of the AppBarLayout namely make it NOT collapse when scrolling down the recycler view but collapse when scrolling the AppBarLayout.
How can I do that?
Thanks in advance

A: According to android documentation for RecyclerView implementing the RecyclerView.OnScrollListener contains the method OnScroll(...) which contains delta_x and delta_y. Using the delta_y value can be used to detect change in the displacement of y direction. therefore,
if( dy > 0 ) { you're scrolling in the positive vertical direction }
else if( dy < 0 ) { you're scrolling in the negative vertical direction }
else { dy == 0, you're not scrolling or the visible item changed }
knowing this logic, if(dy<0) { do not collapse the AppBarLayout }, and you can make this happen by using setScrollFlags( int ) according to the android documentation for AppBarLayout.

A: In your Activity class make the following changes
toolbar.setCollapsible(false);

In your XML file  set
app:layout_scrollFlags="snap"

for CollapsingToolbarLayout
This change would avoid AppBarLayout to Collapse while scrolling down.
Hope this works.


text:
Q: 20.10: Unable to setup either EFI or legacy boot System specs (after everything described below): https://pastebin.ubuntu.com/p/87pyy86mZq/
I'm trying to install Kubuntu 20.10 from LiveUSB to replace an existing Ubuntu installation. The drive (sda) has an MBR table with two existing ext4 partitions, sda1 (/) and sda2 (/home). I choose to format sda1 and keep sda2, with the same mount points. I also resize sda1 down by a few GB and use the free space to create a swap partition (sda5).
The installer appears to run fine, but eventually terminates with unable to install GRUB on dev/sda1. executing grub-install /dev/sda failed. This is a fatal error. When I try to boot the drive, I enter grub rescue mode:
error: file '/boot/grub/i386-pc/normal.mod' not found.
Entering rescue mode...
grub rescue>

Running the LiveUSB, I see that /boot/grub is missing all but a few files, so I can't do much in grub rescue. I attempt to run boot-repair instead: https://help.ubuntu.com/community/Boot-Repair
The repair tells me: The boot of your PC is in EFI mode, but no EFI partition was detected. You may want to retry after creating a EFI partition(FAT32, 100MB~250MB, start of the disk,boot flag).
Presumably, this is why the installer failed in the first place. Realizing I don't know enough about different boot modes, I quit the boot-repair and start reading up. Afterwards, my understanding is that I should either

*

*boot the LiveUSB in legacy mode, then repair/reinstall, if I want legacy boot (which I probably had before), or

*create an EFI System Partition (ESP), then repair/reinstall, if I want EFI boot, in which case I would boot from the ESP.

I attempt option 1 first. On machine startup I enter Asus UEFI Bios Utility, which displays the USB drive twice in the boot menu: one of them is prefixed with "UEFI:" and the other one should be legacy mode. However, selecting the legacy mode apparently fails to boot the USB and falls back to default boot order. There is no error message, just a black screen for a while and then I end up in grub rescue. I try fiddling with advanced settings but to no avail.
I attempt option 2 next. I run the Kubuntu installer again, taking 512 MB from swap to make an EFI System Partition (sda3). This time the installer finishes without errors. I reboot, but the EFI partition apparently fails to boot and I still end up in grub rescue. I try running boot-repair from LiveUSB again. I no longer get the message from before and the repair seems to run without problems. Log: https://pastebin.ubuntu.com/p/tsqjr9SX9f/
At the end the repair says Please do not forget to make your UEFI firmware boot on the Ubuntu 20.10 entry (sda3/EFI/ubuntu/shimx64.efi file) !. Looking at the log, it seems this is already done (am I wrong?). "UEFI: ubuntu" shows up as the first boot option in the UEFI Utility but still fails to boot. I just end up in whatever's next in the boot order, either the LiveUSB or sda (which launches grub rescue). To be certain, I remove the USB and disable CSM so that "UEFI: ubuntu" is the only remaining option but it still won't boot. Instead, the UEFI Utility launches automatically on startup.
Any ideas on how to proceed? Is there any way to tell why the boot fails? I've found conflicting information on whether an MBR table is compatible with EFI boot and if I should use GPT instead. Switching to GPT would completely format the drive though, right? Is there any way to setup legacy boot even if the LiveUSB is booted in EFI mode? I usually install Ubuntu first on my machines and then KDE on top of it, but I don't think that would make much difference here?
Possibly relevant: My previous installation always (seemingly) booted directly into Ubuntu, without a bootloader menu. I'm not sure how it worked, but I don't recall having any trouble with installation back then. I do see grub in the backup of my old root.

A: I eventually managed to get legacy boot to work as follows. I'd read in multiple places that as long as the LiveUSB itself was booted in legacy mode, it would also install Linux with legacy boot. Using Rufus (https://rufus.ie/) I was able to create a LiveUSB that successfully boots in legacy mode on my machine. I verified the boot mode with inxi, which now said BIOS instead of UEFI, and with efibootmngr, which said EFI variables are not supported on this system.
The installer itself also seemed to acknowledge the legacy mode at first. However, after I'd erased the now needless ESP and confirmed my new partition table, the installer said: No EFI System Partition was found. This system will likely not be able to boot successfully, and the installation process may fail. Please go back and add an EFI System Partition, or continue at your own risk.
This seemed strange since if I'm installing with legacy boot, I shouldn't need an ESP anymore? Moreover, I did not get this warning during my very first attempt despite the fact that back then I also had no ESP and the LiveUSB was booted in EFI mode. I decided to continue anyway, and the installer again failed to install grub, same as the first time.
This time, however, the boot-repair tool correctly recognized the legacy mode. Following the instructions (pasting a bunch of lines in a shell), the tool successfully installed grub and my machine now boots into Kubuntu just fine.
My only concern is that the installer terminated when it failed to install grub. Was installing grub the final step, or was there perhaps something more to be done afterwards? Everything seems to work fine so far, at least.

A: I ran into this when installing Kubuntu on my legacy bios machine.  I always install to the root partition and left /home alone.  The installation needed to (without saying so) make a /boot/efi partition but there was no room due to my other partitions.  The installation failed as mentioned above.
Not knowing what to do, I did an install and let it repartition the entire drive.  I then split the main partition into / and /home and restored my /home from backup.  Not ideal, but a simple way to recover that others may find useful.
The big questions is: why is /boot/efi needed on a old legacty Bios machine starting with Kubuntu 20.10?


text:
Q: run Nodejs module in phonegap Is it possible to run an an nodejs module inside an phonegap/dordavo or sencha touch on Android ?
I want to use an nodejs module to read my email through imap protocol.

A: You should take a look at http://browserify.org
It allows you to bundle up node modules to run client side (in the browser) - in your case, the PhoneGap/Cordova webview.


text:
Q: Powershell / VSTS Build - Store Credentials Independent/ Agnostic of User Running Script I'm trying to create a script for a build that checks out a file, edits it and checks it back in.
I want it to work when running as a developer, or as a build agent.
I have a solution similar to this, whereby the password is stored in a file and retrieved for the build.
i.e.
File creation:
read-host -prompt Password -assecurestring | convertfrom-securestring | out-file .\ps-password.pwd -ErrorAction Stop

File use:
# *VSTS Login*
$Username = $tfsUserName
$Password = Get-Content $tfsUserPasswordPath | ConvertTo-SecureString

$creds = New-Object -typename System.Management.Automation.PSCredential -ArgumentList $Username,$Password
$tfsServer = New-Object System.Uri("https://myaccount.visualstudio.com")
$tfsCollection = New-Object Microsoft.TeamFoundation.Client.TfsTeamProjectCollection($tfsServer,$creds)
$tfsCollection.Authenticate()
"***************** Authenticated *****************"

" *VSTS Check Out file* from $fileToUpdate"
Add-TfsPendingChange -Edit -Item $fileToUpdate -Verbose -ErrorAction Stop -wa 0

# read the file, update the number and save it back
$stuff = Get-Content $fileToUpdate
# modify stuff
Set-Content -Value $stuff -Path $fileToUpdate

# *VSTS Check In* Check in the file after changes.
" *VSTS Check In"
New-TfsChangeset -Item $fileToUpdate -Verbose -Comment "***NO_CI***" -Override true -ErrorAction Stop

SecureStrings are based on the machine/users account, so the build works fine when I run from Powershell ISE as my account, but not when triggered from the build server (it runs as NetworkService for now).
I have tried following this post to create the password file as 'Network Service' as well as trying a key for the secure string, but can't get anything to work under both my user and Network Service.
How can I simply store credentials that will work idependently of the user running the script?
Or is this just the wrong way to do it, and I should be using a PAT somehow?

A: Builds allow you to access PAT token via a settings in build definition. These are on the fly generated PAT tokens, so you won't need to store any secret anywhere.
For running the script at a developer's machine, you can ask a developer to enter PAT or have an if else logic where you can ask him for username password.
More info at
https://www.visualstudio.com/en-us/docs/build/scripts/#use-the-oauth-token-to-access-the-rest-api
Update (full solution):
In your build, you must go to 'Options' and turn on 'Allow scripts to access OAuth token'.
Your final script will look something like the following.
Add-PSSnapin Microsoft.TeamFoundation.PowerShell
# This file requires the TFS Power Tools (2015+). When installing, you must select Custom Installation and select PowerShell Cmdlets

# *VSTS Login*
$url = "$($env:SYSTEM_TEAMFOUNDATIONCOLLECTIONURI)$env:SYSTEM_TEAMPROJECTID/_apis/build/definitions/$($env:SYSTEM_DEFINITIONID)?api-version=2.0"
Write-Host "URL: $url"
$definition = Invoke-RestMethod -Uri $url -Headers @{
    Authorization = "Bearer $env:SYSTEM_ACCESSTOKEN"
}
Write-Host "Definition = $($definition | ConvertTo-Json -Depth 100)"
"***************** Authenticated *****************"

" *VSTS Check Out file* from $fileToUpdate"
Add-TfsPendingChange -Edit -Item $fileToUpdate -Verbose -ErrorAction Stop -wa 0

# read the file, update the number and save it back
$stuff = Get-Content $fileToUpdate
# modify stuff - make sure you actually make a change!
Set-Content -Value $stuff -Path $fileToUpdate

# *VSTS Check In* Check in the file after changes.
" *VSTS Check In"
New-TfsChangeset -Item $fileToUpdate -Verbose -Comment "***NO_CI***" -Override true -ErrorAction Stop


text:
Q: How do I workout the Poisson equation? I have trouble with working out the Poisson equation. I don't know how to go from step $1$ to step $2$.  Why is in $(2.)$ the $k$ in front of the nabla sign? How did the nabla sign come in front of the $k$ (in the bracketed part.)
$$\begin{array}{l}
 (1.) -\nabla \cdot(k \nabla u)=f \\
 (2.) -k \nabla \cdot \nabla u-(\nabla k) \cdot(\nabla u)=f
\end{array}$$
It would be great if someone can give me a hint.
Ter

A: It is a matter of notation. For three variables, we write

*

*$\nabla u = (u_x,u_y,u_z)$

*$\nabla = (\partial_x, \partial_y,\partial_z)$
Then,
$$\begin{aligned}\nabla\cdot(k\nabla u)&= (\partial_x, \partial_y,\partial_z)\cdot(ku_x,ku_y,ku_z)\\
&=\partial_x(k u_x)+\partial_y(ku_y)+\partial_z(ku_z)
\end{aligned}$$


text:
Q: Kubernetes Rest API to change existing secret/configmap in Pod I have deployed Pod using kubernetes Rest API POST /api/v1/namespaces/{namespace}/pods
The request body has the podspec with volumes something as below:
{
 "kind": "Pod",
  "apiVersion": "v1",
  "metadata": {
    "name": "test",
    "namespace": "default"
  },
  "spec": {
    "volumes": [
            {
                "name": "test-secrets",
                "secret": {
                    "secretName": "test-secret-one"
                }
            }
        ],
"containers":[
<<container json>>.........
]
  }
}

*

*Now I want to change the secret name test-secret-one to test-secret-two for the Pod?

*How can I achieve this? And what Rest API I need to use?

*Patch rest API - I can use the change container image but cant be used for Volumes. If this can be used Can you give me an example or reference?

*Is there any Kubernetes Rest API to restart the Pod. Note that we are not using a deployment object model. It is directly deployed as Pod, not as deployment.
Can anyone help here?

A: I'm posting the answer as Community Wiki as solution came from @Matt in the comments.

Volumes aren't updatable fields, you will need to recreate the pod
  with the new spec.
The answer to most of your questions is use a deployment and patch it.
  The deployment will manage the updates and restarts for you.

A different approach is also possible and was suggested by @Kitt:

If you only update the content of Secrets and Configmap instead of
  renaming them, the mounted volumes will be refreshed by kubelet in
  the duration --sync-frequency(1m as default).


text:
Q: How to run @RunWith(RobolectricTestRunner::class) and @RunWith(Parameterized::class) together in Junit4 I have to test android application written in Kotlin. I tried
@RunWith(RobolectricTestRunner::class)
    public class GeoWindowTest {

    @RunWith(Parameterized::class)
    class TestParameterizedGeoWindow {}

}

but it doesnt work. Im looking if there is another solutions to use these two runners. Also I could have used Junit5 but then Roboelectric is not compatible yet with Junit5

A: Robolectric has support for this, as described in this blog post.
@RunWith(ParameterizedRobolectricTestRunner::class)
class GeoWindowTest(private val param1: String, private val param2: Int) {
    companion object {
        @JvmStatic
        @ParameterizedRobolectricTestRunner.Parameters
        fun data() = listOf(
            arrayOf("Input 1", 4),
            arrayOf("Input 2", 7)
        )
    }
}


text:
Q: Difference between Entity Type Standard and Managed in Common Data Service? In PowerApps entity list page, we have default five fields Entity, Name, Type, Customizable & Tags
What does the Type field mean, I couldn't find any article related to this! Even Microsoft docs is a no go!!
I do know that Custom is the Type assigned to the tables created by us, whereas the default tables are grouped into two - Managed & Standard (refer screenshot).
But under what criteria do they get separated into the two groups?

A: This Standard type is part of Common Data Model (CDM) and PowerApps nomenclature:

CDM provides standard entities common across most industry domains – Sales, Purchase, Customer Service, Productivity among others. Leveraging the years of experience with Dynamics business applications and Office 365 and working with thousands of enterprise customers we have defined and implemented these standard entities that will connect to Microsoft's first party business applications and support a broad ecosystem of ISV and customer solution development.

Learn more about CDM.
Managed is something like First party integration apps like LinkedIn, AI, Teams, etc. You will see publish prefix like msdyn_, li_, etc to see some identities. (maybe some third party Managed entities will follow this route, I'm not sure though).
I see some ADX portal like legacy entities marked as Standard rather than Managed, and some vice versa. I would say some sausage is being made, too early to look into that & that why documentation is missing.


text:
Q: To get Numeric value from a alphanumeric String in PHP? i want a function or a code to get numeric value from the string whose value is "2008 Revenue $5,700,390,000". the output that i want is $5,700,390,000.

A: If you're absolutely certain the string will always be formatted as YEAR TYPE VALUE with spacings between the values you could:
$str = "2008 Revenue $5,700,390,000";

$exploded = explode(" ", $str);

$my_value = $exploded[2];

A: This may be a good use of regular expressions (how to with PHP).
The expression \$[\d,]+ seems to work.

A: This is a hybrid using the built-in "floatval()" function and a regular expression - this deals with more complex strings.
function floatvalue($value) {
     return floatval(preg_replace('#^([-]*[0-9\.,\' ]+?)((\.|,){1}([0-9-]{1,2}))*$#e', "str_replace(array('.', ',', \"'\", ' '), '', '\\1') . '.\\4'", $value));
}

If you have more simple situations "32121.54BLAH" for example, floatval() will handle these without assistance.

A: I only know C#, but I would use a Regex, like [\$.0-9]+ in its simplest form. If you need culture awareness (e.g. different currency symbols) you need to add more logic. Hope this helps.


text:
Q: force restart postgresql docker I have a script trying to restart postgresql docker container:
DOCKER_CONTAINER_NAME="timescaledb"
docker restart -t 1 $DOCKER_CONTAINER_NAME
timeout 9000000s bash -c "until docker exec $DOCKER_CONTAINER_NAME pg_isready ; do sleep 1 ; done"

However, this line (with any -t number)
docker restart -t 1 $DOCKER_CONTAINER_NAME

Takes extremely large amount of time to shutdown postgresql. Generally I have to go to the screen container postgresql (I used screens to manage my orchestration). and press Ctrl-C to force it shutdown and enter
docker run -ti --user 1000:1000  -p 5432:5432 --name timescaledb  --volume=/home/ubuntu/pgdata3:/home/postgresql/pgdata --rm -e POSTGRES_PASSWORD=dashdhwqehqwhhkshajdkh -e PGDATA=/home/postgresql/pgdata timescale/timescaledb-ha:pg13-latest;

Is it possible to complete this process of force restart without me entering into the "screen" and press Ctrl-C and restart manually?
A related question is posted here:
postgresql docker ctrl C seems to be better than docker kill
I wanted to find a way to mimic Ctrl-C shut down of postgresql.

A: You can use docker-compose up to start your docker and add restart: always to restart the docker when it shuts down for any reason.
Example of docker-compose.yml
services:
   db:
       image: postgres:14
       restart: always

EDIT. Replying to your comment, maybe you could prepare a bash script, forcing the docker to restart every x minutes:
while true
do
   docker restart posgresql
   sleep 15m
done

Or, probably better, you could program a task in crontab:
crontab -e
15 * * * * docker restart posgresql

I'm assuming you're working with Linux

A: ok, it seems this is sequence of command served my purpose. Thanks, everyone!
docker stop -t 120 $DOCKER_CONTAINER_NAME
docker kill $DOCKER_CONTAINER_NAME
screen -S i2 -X stuff 'docker run -ti --user 1000:1000  -p 5432:5432 --name timescaledb  --volume=/home/ubuntu/pgdata3:/home/postgresql/pgdata --rm -e POSTGRES_PASSWORD=sahisahikqhwwkejkqwjehjhwqjh -e PGDATA=/home/postgresql/pgdata timescale/timescaledb-ha:pg13-latest;\n'


text:
Q: How can I join two lines with different patterns in file in linux? I want to join lines in a file which have been written on two lines. for example, as shown below, I want to join first and second line which have a proverb and name of author respectively. All similar occurrences I want to join in a file.
I can join them manually, by using Shift+J but there are almost 10000 lines and It has become very difficult to do it.

*,119., 120., are the original source line numbers that are also present in line.

So I want to search and join all lines which have got a number at starting of the line and then a dot and then a space and then text.. ^[0-9]*. (118. ) and next line having no number at the starting of line. So join them.
I have searched everywhere and tried to implement it but of no use.
118. People don't care how much you know until they know how much they care.
John C. Maxwell
119. A life lived in fear is a life half lived. - Proverb
120. Nothing great was ever achieved without enthusiasm.
Ralph Waldo Emerson
121. Damn the torpedoes, full speed ahead. - David Farragut
122. Our lives begin to end the day we become silent about things that matter. -
Martin Luther King, Jr.

A: This should do it:
awk '/^[0-9]+\./ { if (last) print last; last = $0; next }
                 { print last, $0; last = "" }'

Given data file:
118. People don't care how much you know until they know how much they care.
John C. Maxwell
119. A life lived in fear is a life half lived. - Proverb
120. Nothing great was ever achieved without enthusiasm.
Ralph Waldo Emerson
121. Damn the torpedoes, full speed ahead. - David Farragut
122. Our lives begin to end the day we become silent about things that matter. -
Martin Luther King, Jr.

That produces the output:
118. People don't care how much you know until they know how much they care.  John C. Maxwell
119. A life lived in fear is a life half lived. - Proverb
120. Nothing great was ever achieved without enthusiasm.  Ralph Waldo Emerson
121. Damn the torpedoes, full speed ahead. - David Farragut
122. Our lives begin to end the day we become silent about things that matter. -  Martin Luther King, Jr.

The code does assume there's only ever one continuation line.  If you can have multiple continuation lines, then you need a more complex script.
$ cat new.data
118. People don't care how much you know until they know how much they care.
John C. Maxwell
119. A life lived in fear is a life half lived. - Proverb
120. Nothing great was ever achieved without enthusiasm.
Ralph Waldo Emerson
121. Damn the torpedoes, full speed ahead. - David Farragut
122. Our lives begin to end the day we become silent about things that matter. -
Martin Luther King, Jr.
123. More than one line of data causes trouble for the basic script.
A more complex script can deal with those too. -
Jonathan Leffler
$ awk '/^[0-9]+\./ { if (last) print last; last = $0; next }
>                  { last = last " " $0 }
>      END         { if (last) print last }' new.data
118. People don't care how much you know until they know how much they care.  John C. Maxwell
119. A life lived in fear is a life half lived. - Proverb
120. Nothing great was ever achieved without enthusiasm.  Ralph Waldo Emerson
121. Damn the torpedoes, full speed ahead. - David Farragut
122. Our lives begin to end the day we become silent about things that matter. -  Martin Luther King, Jr.
123. More than one line of data causes trouble for the basic script. A more complex script can deal with those too. - Jonathan Leffler
$

A: :%s/\n\%(\d\+\. \)\@! should do it in vim. This command works with multiple continuation lines but only removes newlines; it doesn't insert spaces or anything.

A: In awk, "no empty lines and **first line** is present in file", leading space also expected:
$ awk '{printf "%s%s", ($1 ~ /^ *\*\*/? (NR>1?ORS:"") : OFS), $0} END {printf ORS}' file

.
{   # finish previous with ORS if current starts with a number and output it
    printf "%s%s", ($1 ~ /^ *\*\*/? (NR>1?ORS:"") : OFS), $0
}
END {printf ORS} # closing ORS

A: This might work for you (GNU sed):
sed 'N;/\n[0-9]/!s/\n//;P;D' file

Read two lines and if the second line does not start with a number, remove the newline.
Another way:
sed 'N;s/\n\([^0-9]\)/\1/;P;D' file


text:
Q: Multiple Document Roots based on directory? My server's structure is like this:
|- var
   |-- www
       |--- website1
       |--- website2
       |--- website3

I'm currently working on website1, but I found that when I submit one of my Ajax forms, it returns the following error:
http://www.website.com/signup: The requested URL /signup was not found on this server.

When it should be looking under http://www.website.com/website1/signup instead.
Here's what I currently have added in my apache2.conf:
Alias /website1 "/var/www/website1/public"
<Directory /var/www/website1>
    Options Indexes FollowSymLinks
    AllowOverride All
    Require all granted
</Directory>

And my DocumentRoot is set to /var/www in my VirtualHosts. How can I fix this?

A: This can't work. You confuse the Alias directive with a Virtual Host.
What you call www.website1.com is a hostname, not a directory part of the url. Therefore the Alias directive will not catch. An Alias directive allows you to map something like http://www.website.com/folder1 to an arbitrary location inside your local file system by means of a directive like Alias /folder1 .... Not more. It does not see the requested host, since it is located inside a host configuration.
Instead you need a Virtual Host for each hostname / domain name you want to serve content for. If you have no virtual hosts setup yet, then the http server will fall back to the default host, which is what you call www.website.com.
All options of the apache http server are documented in excellent quality. I suggest you take a look into that documentation: http://httpd.apache.org/docs/2.2/vhosts/

To be precise here: what you describe can actually be done by means of url rewriting. But it would be a pain and very intransparent. Virtual hosts are the way to go.

A: You have to use Apache's Virtual Hosts.
In your Apache config:
# Ensure that Apache listens on port 80
Listen 80

# Listen for virtual host requests on all IP addresses
NameVirtualHost *:80

<VirtualHost *:80>
DocumentRoot /www/example1
ServerName www.example.com

# Other directives here

</VirtualHost>

<VirtualHost *:80>
DocumentRoot /www/example2
ServerName www.example.org

# Other directives here

</VirtualHost>


text:
Q: Pax-Web Jetty-Bundle publishing Jersey App I'm trying to deploy a Jersey app on Apache Felix. I have these bundles installed:
    ID|State      |Level|Name
    0|Active     |    0|System Bundle (4.4.1)
    1|Active     |    1|Apache Felix Bundle Repository (2.0.2)
    2|Active     |    1|Apache Felix Gogo Command (0.14.0)
    4|Active     |    1|Apache Felix Gogo Shell (0.10.0)
   10|Active     |    1|Apache Felix Configuration Admin Service (1.2.8)
   11|Active     |    1|Apache Felix EventAdmin (1.2.10)
   35|Active     |    1|Apache Felix Gogo Runtime (0.12.1)
   90|Installed  |    1|Apache Felix Log Service (1.0.0)
   91|Resolved   |    1|OSGi R4 Compendium Bundle (4.0.0)
   92|Installed  |    1|Apache Felix Declarative Services (1.6.0)
   94|Installed  |    1|Apache Felix Web Management Console (3.1.2)
   95|Installed  |    1|Apache Felix iPOJO WebConsole Plugins (1.6.0)
   96|Resolved   |    1|Apache Felix Shell Service (1.4.2)
  119|Installed  |    1|Servlet 2.1 API (1.0.0)
  144|Active     |    1|OSGi JAX-RS Connector (4.1.0.201407081443)
  147|Active     |    1|jersey-all (2.10.1)
  157|Active     |    1|OPS4J Pax Web - Jetty Bundle (4.0.0)
  158|Active     |    1|OPS4J Pax Web - Runtime (4.0.0)
  163|Active     |    1|http://repo1.maven.org/maven2/org/slf4j/slf4j-api/1.7.7/slf4j-api-1.7.7-sources.jar (0.0.0)
  165|Active     |    1|Java Servlet API (3.0.1)
  167|Active     |    1|OPS4J Pax Logging - API (1.8.1)
  170|Active     |    1|Apache Felix Dependency Manager (3.2.0)
  171|Active     |    1|OPS4J Pax Web - Extender - WAR (4.0.0)
  174|Active     |    1|Apache Felix Dependency Manager Runtime (3.2.0)
  177|Active     |    1|ASM (5.0.3)
  178|Active     |    1|ASM commons classes (5.0.3)
  179|Active     |    1|ASM Tree class visitor (5.0.3)
  182|Active     |    1|Apache XBean OSGI Bundle Utilities (3.18.0)
  183|Active     |    1|Apache XBean :: Classpath Resource Finder (3.18.0)
  216|Active     |    1|Auth Test (2.0.0.SNAPSHOT)

The last one, Auth Test is the Jersey app that I want to publish. I can install the bundle and start it. When I start it I get these logs:
g! start 216
Started Activator
org.ops4j.pax.web.pax-web-extender-war[org.ops4j.pax.web.extender.war.internal.WebEventDispatcher] : Sending web event WebEvent [replay=false, type=DEPLOYING, bundle=platform-component-web-rest-service-authentication [216], extenderBundle=org.ops4j.pax.web.pax-web-extender-war [171], cause=null, timestamp=1416226629360, contextPath=/authentication, collisionIds=null, httpService=null, httpContext=null] for bundle platform-component-web-rest-service-authentication
org.ops4j.pax.web.pax-web-extender-war[org.ops4j.pax.web.extender.war.internal.WebEventDispatcher] : org/osgi/service/web/DEPLOYING
org.ops4j.pax.web.pax-web-extender-war[org.ops4j.pax.web.extender.war.internal.parser.WebAppParser] : version found in web.xml - 3.0
org.ops4j.pax.web.pax-web-extender-war[org.ops4j.pax.web.extender.war.internal.parser.WebAppParser] : metadata-complete is: false
org.ops4j.pax.web.pax-web-extender-war[org.ops4j.pax.web.extender.war.internal.parser.WebAppParser] : scanning for ServletContainerInitializers
org.ops4j.pax.web.pax-web-extender-war[org.ops4j.pax.web.extender.war.internal.parser.WebAppParser] : found container initializers by SafeServiceLoader ... skip the old impl.
org.ops4j.pax.web.pax-web-extender-war[org.ops4j.pax.web.extender.war.internal.Activator] : Scheduling start of extension for bundle platform-component-web-rest-service-authentication asynchronously
org.ops4j.pax.web.pax-web-extender-war[org.ops4j.pax.web.extender.war.internal.WebAppPublisher] : Publishing web application [WebApp{displayName=Authentication Manager,contextName=authentication,m_httpContext=null}]

I guess the whole problem is behind the web.xml which looks like this:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    id="platform-component-web-rest-manager-authentication" version="3.0">

    <display-name>Authentication Manager</display-name>

    <!-- ****************************************************************** -->
    <!-- SERVLETS -->
    <!-- ****************************************************************** -->
    <servlet>
        <servlet-name>wd-platform-product-web</servlet-name>
        <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
        <init-param>
            <param-name>jersey.config.server.provider.packages</param-name>
            <param-value>
                com.mycompany.platform.component.web.rest;
                com.mycompany.wd.platform.component.web.rest,
            </param-value>
        </init-param>
        <init-param>
            <param-name>jersey.config.server.provider.scanning.recursive</param-name>
            <param-value>true</param-value>
        </init-param>
        <init-param>
            <param-name>jersey.config.server.provider.classnames</param-name>
            <param-value>
                com.wordnik.swagger.jersey.listing.ApiListingResourceJSON;
                com.wordnik.swagger.jersey.listing.JerseyApiDeclarationProvider;
                com.wordnik.swagger.jersey.listing.JerseyResourceListingProvider
            </param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>wd-platform-product-web</servlet-name>
        <url-pattern>/rest/2.0.0/*</url-pattern>
    </servlet-mapping>

    <servlet>
        <servlet-name>swagger-default-jaxrs-config</servlet-name>
        <servlet-class>com.wordnik.swagger.jaxrs.config.DefaultJaxrsConfig</servlet-class>
        <init-param>
            <param-name>api.version</param-name>
            <param-value>2.0.0</param-value>
        </init-param>
        <init-param>
            <param-name>swagger.api.basepath</param-name>
            <param-value>/rest/2.0.0/</param-value>
        </init-param>
        <load-on-startup>2</load-on-startup>
    </servlet>

</web-app>

My activator class is the standard model:
import java.util.HashMap;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import org.osgi.service.event.Event;
import org.osgi.service.event.EventAdmin;

/**
 * This is to make sure we signal the application has been deployed/un-deployed
 * via the OSGi EventAdmin service.
 *
 * @author Jakub Podlesak (jakub.podlesak at oracle.com)
 */
public class WebAppContextListener implements BundleActivator, ServletContextListener {

    static EventAdmin ea;

    BundleContext bc;
    ServiceReference eaRef;

    synchronized static EventAdmin getEa() {
        return ea;
    }

    synchronized static void setEa(EventAdmin ea) {
        WebAppContextListener.ea = ea;
    }

    @Override
    public void contextInitialized(final ServletContextEvent sce) {
        if (getEa() != null) {
            final String contextPath = sce.getServletContext().getContextPath();
            getEa().sendEvent(new Event("jersey/test/DEPLOYED",new HashMap<String, String>(){{
                put("context-path", contextPath);}}));
        }
    }

    @Override
    public void contextDestroyed(final ServletContextEvent sce) {
        if (getEa() != null) {
            getEa().sendEvent(new Event("jersey/test/UNDEPLOYED",new HashMap<String, String>(){{put("context-path", sce.getServletContext().getContextPath());}}));
        }
    }

    @Override
    public void start(BundleContext context) throws Exception {
        System.out.println("Started Activator");
        bc = context;
        eaRef = bc.getServiceReference(EventAdmin.class.getName());
        if (eaRef != null) {
            setEa((EventAdmin)bc.getService(eaRef));
        }
    }

    @Override
    public void stop(BundleContext context) throws Exception {
        if (eaRef != null) {
            setEa(null);
            bc.ungetService(eaRef);
        }
    }
}

And my main REST service looks like this:
@Path("/service/authentication")
@Api(value = "/service/authentication", description = "Authentication Service")
public class AuthenticationServiceRestService extends RestService
{

    ServiceLayer<Request<?>> serviceLayer;
    AuthenticationLayer<Request<?>> authenticationLayer;
    ExceptionLayer<Request<?>> exceptionLayer;

    public AuthenticationServiceRestService() throws AuthenticationServiceRestServiceException
    {
        this.serviceLayer = new ServiceLayer<Request<?>>();

        try
        {
            this.authenticationLayer = new AuthenticationLayer<Request<?>>(this.serviceLayer);
        }
        catch (AuthenticationServiceException exception)
        {
            throw new AuthenticationServiceRestServiceException(exception.getMessage(), exception);
        }

        this.exceptionLayer = new ExceptionLayer<Request<?>>(this.authenticationLayer);
    }

    @POST
    @Path("/auth")
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    @ApiOperation(value = "Get authentication token.", response = AuthenticationTokenFacade.class)
    public Response getAuthenticationToken(@ApiParam(value = "Authentication Data", required = true) AuthenticationRequestFacade authenticationRequestFacade)
    {
        System.out.println("auth request");
        GetAuthenticationTokenJsonRequest getAuthenticationTokenJsonRequest = new GetAuthenticationTokenJsonRequest(authenticationRequestFacade);

        return exceptionLayer.execute(getAuthenticationTokenJsonRequest);
    }

When I make a POST request to http://localhost:8080/authentication/rest/2.0.0/service/authentication/auth I get 404. I don't even know if my whole service is published on jetty. How can I do that? Jetty displays this in the middle of a massive log when I make that request:
org.ops4j.pax.logging.pax-logging-api[org.ops4j.pax.web.service.spi.model.ServerModel] : Matching [/authentication/rest/2.0.0/service/authentication/auth]...
org.ops4j.pax.logging.pax-logging-api[org.ops4j.pax.web.service.spi.model.ServerModel] : Path [/authentication/rest/2.0.0/service/authentication/auth] does not match any context

Any help to make this work would be great.
Thanks in advance and sorry about the long question but I had to make sure that all the information is provided.

A: First, thanks for the detailed question this is much better this way, only thing missing is the version of Pax Web you're using ;-)
Second, you might be interested in using Karaf with Pax Web. It's easy to install Pax-Web in Karaf by issuing the
feature:install war

command to have Pax Web installed inside Karaf. Now why am I suggesting this at first, because you said you don't know if the application is actually available. For this there are two commands available in the Karaf shell that will tell you if it is or not.
One would be
web:list

the other one is
http:list

either one will give you a list of a) the web application bundles deployed or b) the servlets registered.
This to give you a better feeling about the deployed application.
Now, what I don't get is, why you have an Activator in your WebApplicationBundle (WAB), cause for WABs you just use a "regular" war with OSGi Manifest including the Web-ContextPath. From there on the WebExtender will do the work for you, as in your case it has been done.
If you want to have a ServletContextListener used, register it in the regular way in the web.xml or since you're using Servlet3 web.xml with the standard annotations.
Now the last part, the log message tells you already when issuing the request to the server, there hasn't been found a httpContext for the Request. The reason for this will most likely be somewhere in the long logs you had before that. It could be something got wrong registering the servlet. Again the
web:list command might be of help to get a even better picture.
As Pax Web hasn't been explicitly tested for this :-) it could be of interest to provide a simple Sample to the Pax Web community to add it to the samples and to have Integration tests. It's also always good to ask at the ops4j mailinglist.


text:
Q: SQL left join - limit number of rows returned I have a working SQL statement, but there is one issue within it I can't solve.
When I left join my table sites_photos there can be multiple matches on sp.sites_id = s.id, but I want the table to only return 1. Is this possible.
SELECT s.*, sp.photo
FROM sites s
LEFT JOIN sites_photos sp
ON sp.sites_id = s.id

My output: 2 times id 30, but with different photo paths, I only want 1 returned for that id, or both bundled in one array.
Array
(
[0] => Array
    (
        [id] => 30
        [url] => www.test.nl
        [name] => Aleve
        [date] => 2014-08-16
        [cms_active] => Y
        [archive] => N
        [photo] => 2014080812365920120214103601number_1.jpg
    )
[1] => Array
    (
        [id] => 30
        [url] => www.test.nl
        [name] => Aleve
        [date] => 2014-08-16
        [cms_active] => Y
        [archive] => N
        [photo] => 20140811021102news.jpg
    )
)

A: You can do so,by using GROUP_CONCAT which will concatenate all the photos per site by and produces comma separated list of photos then you can use SUBSTRING_INDEX over result of GROUP_CONCAT to pick one photo,you can also add the criteria of order by in GROUP_CONCAT as GROUP_CONCAT(sp.photo ORDER BY sp.id DESC)
SELECT s.*, SUBSTRING_INDEX(GROUP_CONCAT(sp.photo),',',1) photo
FROM sites s
LEFT JOIN sites_photos sp
ON sp.sites_id = s.id
GROUP BY s.id


text:
Q: How to Load custom Service Provider in Laravel I would like to load a serviceprovider from my vendor folder. I actually added this vendor into my project
Learning Laravel PayPal SDK
Now under the folder structure
vendor/
   - paypal/
        - rest-api-sdk-php/
            - config/
                 - paypal.php
            - docs/
            - lib/
                - PayPal/
                - PayPalConfigServiceProvider.php
            - sample/
            - test/
            - composer.json

As you can see I added some items on the vendor. I added config folder and a config file under it namely paypal.php and also under lib folder I added PayPalConfigServiceProvider.php
Full path of service provider is
my_project/vendor/paypal/rest-api-sdk-php/lib/PayPalConfigServiceProvider.php
Now I would like to add that PayPalConfigServiceProvider so that when I run composer update or something the PayPalConfigServiceProvider will copy a config file to myproject\config folder. So I added
'providers' => [
      Illuminate\Validation\ValidationServiceProvider::class,
      Illuminate\View\ViewServiceProvider::class,
      Illuminate\Html\HtmlServiceProvider::class,

      PayPal\PayPalServiceProvider::class,
]

on config/app.php under the providers array. But now when I try to run php artisan I get this error
PHP Fatal error:  Class 'PayPal\PayPalServiceProvider' not found in myproject/vendor/laravel/framework/src/Illuminate/Foundation/ProviderRepository.php

So I assumed that this has something to do with my composer.json on my root directory and this is the content of it
{
"name": "laravel/laravel",
"description": "The Laravel Framework.",
"keywords": ["framework", "laravel"],
"license": "MIT",
"type": "project",
"require": {
    "php": ">=5.5.9",
    "laravel/framework": "5.1.*",
    "illuminate/html": "^5.0",
    "doctrine/dbal": "^2.5",
    "paypal/rest-api-sdk-php": "*"
},
"require-dev": {
    "fzaninotto/faker": "~1.4",
    "mockery/mockery": "0.9.*",
    "phpunit/phpunit": "~4.0",
    "phpspec/phpspec": "~2.1"
},
"autoload": {
    "classmap": [
        "database"
    ],
    "psr-4": {
        "App\\": "app/"
    }
},
"autoload-dev": {
    "classmap": [
        "tests/TestCase.php"
    ]
}
}

It seems the paypal is already included now I'm not sure what I need to add for it to be recognized. I just need my PayPalServiceProvider to be initialized so that this code will be run
PayPalServiceProvider.php
namespace PayPal;
use Illuminate\Support\ServiceProvider;

class PayPalServiceProvider extends ServiceProvider {

/**
 * Register the service provider.
 *
 * @return void
 */
public function register()
{
    // TODO: Implement register() method.

}

public function boot()
{
    $this->mergeConfigFrom(__DIR__ . '../config/paypal.php', 'paypal');
}
}

I also checked the paypal vendor folder and checked its composer.json and here's the content
{
"name": "paypal/rest-api-sdk-php",
"description": "PayPal's PHP SDK for REST APIs",
"keywords": ["paypal", "payments", "rest", "sdk"],
"type": "library",
"license": "Apache2",
"homepage": "http://paypal.github.io/PayPal-PHP-SDK/",
"authors": [
    {
        "name": "PayPal",
        "homepage": "https://github.com/paypal/rest-api-sdk-php/contributors"
    }
],
"require": {
    "php": ">=5.3.0",
    "ext-curl": "*",
    "ext-json": "*"
},
"require-dev": {
    "phpunit/phpunit": "3.7.*"
},
"autoload": {
    "psr-0": {
        "PayPal": "lib/"
    }
}
}

I know I can always add something like this on the composer.json on my root directory
"autoload": {
    "classmap": [
        "database"
    ],
    "psr-4": {
        "App\\": "app/",
        "PayPal\\": "vendor/paypal/rest-api-sdk-php/lib",
    }
}

And this will work when I run composer dumpautoload. But I don't want this kind of approach I see many libraries but non of them did something like this. Is there any approach where I can load my serviceprovider without adding an entry on my autoload under my composer.json on root directory? Its ok if I'll add something on the composer.json of the vendor folder. But how will I accomplish this? please help on this. Thanks

A: You should not add files into the package folder.
You can move your config files into the config folder and move your Paypal service provider (I think you write it by yourself) to the app/Providers folder and use your application namespace for that class.
However, if you still want to load your created class from the lib folder (again, I do not recommend to do that), put your service provider class into the lib/Paypal instead of lib. The reason is this class use PSR-0 class loading standard, you can see a clear explanation about the different between PSR-0 and PSR-4 in this answer on Stack Overflow.

A: If you place your service provider inside your vendor folder you have to tell laravel where it is, and, as you said, putting this line in your composer.json:
"psr-4": {
        "App\\": "app/",
        "PayPal\\": "vendor/paypal/rest-api-sdk-php/lib",
    }

will do that.
Anyhow, Beware of putting your code in the vendor folder: this is a very bad practice, as the vendor folder is reserved for the external packages of the progect. You can, and should, consider putting your service provider inside your App Folder, i.e: App\Providers\PayPalServiceProvider.php
And set the namespace this way:
namespace App\Providers;

use Illuminate\Support\ServiceProvider;

class PayPalServiceProvider extends ServiceProvider {

//...

}

This way in your app.php you could set:
App\Providers\PayPalServiceProvider::class,

without adding anything in your composer.json file

A: First, please don't try to modify things under package folder (vendor) unless you know what you are doing, it's generated and should not be included into VCS like git.
So put your service provider under app/Providers and define it under App\Provider namespace.
As for your PaypalServiceProvider, it should be given a full class name as App\Providers\PaypalServiceProvider and put in my_project/app/Providers.

If you want to create a package, you should learn something about Composer (getcomposer.org) and Packagist (packagist.org)

Secondary, about why your PaypalServiceProvider could not be found, you should learn something about PSR-4 (www.php-fig.org/psr/psr-4/).


text:
Q: NPM Build issue Trying to run this command: npm run build.
Here is the scripts definition of the package.json file
"scripts": {
"start": "npm run build",
"build": "webpack -d, --devtool && cp src/index.html dist/index.html && webpack-dev-server --content-base src/ --inline --hot",
"build:prod": "webpack -p && cp src/index.html dist/index.html"
},
"keys": [
"reactjs"
],
This is the error been produced regardless I also tried for build in scripts webpack -d, wepack -d --devtool as well webpack -d, --devtool nothing helped. The error shows as
[webpack-cli] Error: Option '-d, --devtool ' argument missing
[webpack-cli] Run 'webpack --help' to see available commands and options
npm ERR! code 2
npm ERR! path /Users/naveed.hasan/Projects/demo/react/fileuplod
npm ERR! command failed
npm ERR! command sh -c webpack -d && cp src/index.html dist/index.html && webpack-dev-server --content-base src/ --inline --hot

A: You have a comma after your -d in your script:
"build": "webpack -d, --devtool
-----------------------------^ there
I'm not a webpack user, but it doesn't look voluntary

A: you should configure the devtool option, either in the command line -d eval or in your webpack.config.js file :
module.exports = {
    ...
    devtool: 'eval',
    ...
};


text:
Q: Symmetry factor in $\phi^4$ theory I'm having trouble while trying to understand what the symmetry factor of a Feynman diagram really is. From books I get that it is a geometrical factor that you get by the number of ways in which you can deform the internal lines of diagram such that it looks the same. That is, as I understand, it has nothing to do with the number of contractions that lead to the same topology (Wick's theorem), nor with the $4!$ factor of the Lagrangian, nor with the $n!$ factor from the Dyson series expansion, and so on.
However, when I see some discussions here, they seem not to consider this geometrical factor. I will give you a summary of this discussion:
Summary
Consider the lagrangian of the real scalar field given by $$\mathcal L = \frac{1}{2} (\partial \phi)^2 - \frac{1}{2} m^2 \phi^2 - \frac{\lambda}{4!} \phi^4$$
Disregarding snail contributions, the only diagram contributing to $ \langle p_4 p_3 | T (\phi(y)^4 \phi(x)^4) | p_1 p_2 \rangle$ at one loop order is the so called dinosaur:

Let's start with the external legs on the left. There are eight possible places for the first upper-left external leg to attach: it can attach to one of the four possible $\phi_x$ fields, or to one of the four possible $\phi_y$ fields. The lower-left external leg then only has three choices, since if the first leg attached to the $\phi_x$ field, this leg must also attach to a $\phi_x$ field, and similarly for $\phi_y$. So attaching these legs gives a factor of $2\times 4\times 3$.
Now, let's do the legs on the right. If the legs on the left attached to $\phi_x$, the legs on the right must attach to $\phi_y$, and vice-versa. So there are only four choices for the upper-right external leg, and three choices for the upper-left external leg. Thus, attaching these legs gives a factor of $4\times 3$.
Finally, let's attach the internal legs. The first leg has two places to attach, and the second only has one. So we get a factor of $2$.
Overall, the Dyson series gives us a $\frac{1}{2!}$, and the vertices give us a $\frac{1}{4!4!}$, so the symmetry factor is
$$
\frac{2\times 4 \times 3\times 4\times 3\times 2}{2!4!4!}=\frac{1}{2}
$$
End of summary
What Jahan Claes does here is to take into account the $\frac{1}{(4!)^2}$ factor from the two vertices; the $\frac{1}{2!}$ factor from the Dyson expansion of the exponential, which cancels out with the $2!$ from the interchange of the roles of the two vertices; the $4\times 3 \times 4 \times 3$ from the contractions of the external legs with the fields; and an additional $2$ from the contractions of the internal fields.
Should we also divide this by 2 to consider the permutation of the internal lines leading to the same diagram?
If that is the case, why do we have to cast out one of those repeated diagrams? Wouldn't it mean that this kind of diagrams just contributes more than other diagrams which don't have that geometrical factor?

A:
I'm having trouble trying to understand what the symmetry factor of a Feynman diagram really is. [...] I understand it has nothing to do with the number of contractions that lead to the same topology (Wick's theorem), nor with the $4!$ factor of the Lagrangian, nor with the $n!$ factor from the Dyson series expansion.

This seems to be a rather deep confusion over what a symmetry factor is. We don't put in symmetry factors just because we feel like it; they arise naturally and automatically. To summarize:

*

*When performing perturbation theory to $n^{\text{th}}$ order with $\phi^4$ vertices, we get a factor of $1/n!$ from the Dyson series and a factor of $1/4!$ from each vertex, due to the coefficient in the Lagrangian.

*These factors mean that every Wick contraction comes with a factor of $1/N$.

*There are multiple Wick contractions that lead to the exact same Feynman diagram; say there are $M$. Then the Feynman diagram, which counts contributions from all Wick contractions that lead to it, comes with a factor of $M/N$.

*The factors in $N$ are conventionally chosen so that most of the time, $M = N$ and the Feynman diagrams don't come with any factors. However, if the Feynman diagram is symmetric, then two purportedly distinct Wick contractions that produce the Feynman diagram could in fact be the exact same Wick contraction. Hence $M$ will be less than $N$, so $M/N$ is less than $1$.

*In general, $M/N = 1/S$, where $S$ is an integer called the symmetry factor. But you can then prove that $S$ is the size of the symmetry group of the Feynman diagram. So if you can compute $S$, you can skip the steps above.

In his answer, Jahan Claes has gone through this procedure explicitly to show that the Feynman diagram you drew comes with a factor of $1/2$. You could also get this factor by noting that $S = 2$. But you don't multiply by $1/2$ twice, because they're counting the exact same thing.


text:
Q: Nginx Relative URL to Absolute Rewrite Rule? Given the following config:
server {

    listen 80;
    server_name site.com;

    location /proxy {
            proxy_pass   http://newsite.com/;
   }
 }

The page hosted on site.com uses relative path (/main.css) for all it statics files, so when i receive the proxied page, the browser is querying static files with the wrong path:
i.e. : http://site.com/main.css
How would i go to have these static files requested follow to their original location (http://newsite.com/main.css)?

A: You should be able to use a rewrite rule in your server section, something like the following (untested):
server_name site.com;
rewrite ^/([^/]+\.css)$ http://newsite.com/$1;

That should redirect all requests for .css files in the top-level directory of site.com to http://newsite.com/. Adjust the regex or add rewrite rules as necessary if you need to include other static files (images, scripts, etc.).


text:
Q: Indicar datos en grafico de barras con matplotlib Estoy trabajando con una tabla que indica el Número del día, la hora del día y un número de visitas

Y quiero crear un gráfico de barras que indique el número de visitas por cada hora (como el de la imagen)

Pero, ¿cómo puedo indicar también las horas en cada barra? Algo similar a esto que he hecho con el paint, pero en todas las horas, claro.

A: Puedes usar matplotlib.pyplot.text o también matplotlib.pyplot.annotate para añadir el texto que quieras sobre cada columna.
Supongo que tus datos están en un DataFrame de Pandas, por lo que puedes usar pandas.DataFrame.plot.bar para facilitar la creación del gráfico a partir del mismo, aunque la idea es la misma si se usa matplotlib.pyplot.bar directamente.
import pandas as pd
import matplotlib.pyplot as plt

data = {"Dia": (14, 14, 14, 12, 12, 12, 12, 12),
        "Hora": (16, 14, 13, 12, 23, 22, 21, 20),
        "Visita": (5, 2, 6, 19, 8, 47, 13, 51)}

visitsPerDay = pd.DataFrame(data)
ax = visitsPerDay.plot.bar("Dia", "Visita")

for i, bar in enumerate(ax.patches):
    ax.text(bar.get_x() + bar.get_width() / 2, bar.get_height() + 1.5,
            f"{visitsPerDay['Hora'][i]}:00",
            horizontalalignment= 'center', verticalalignment='bottom',
            fontsize=10, rotation=90, color='dimgrey')

ax.set_xlabel("Número del dia")
ax.set_ylabel("Visitas")
ax.margins(x=0, y=0.3)

plt.show()

Dado que aparentemente la hora la representas como un entero, he usado simplemente formateo de literales de cadena f"{visitsPerDay['Hora'][i]}:00" para asignar la cadena correspondiente a cada barra , si usas Python < 3.6 puedes usar "{}:00".format(visitsPerDay['Hora'][i]).


text:
Q: Rails number_to_currency precision doesn't work - is it a bug? I'm trying to use number_to_currency to get two digits after the decimal dot in Rails 3, but I can get only one. My DB field is defined like this:
t.decimal  "amount",              :precision => 5, :scale => 2

In my template I have:
#{number_to_currency(@purch.amount)}

And yet as the result I get: PLN 34,7
In the DB I can clearly see: 34.70
I would like to see my second zero - is it a feature or am I missing something?
Thanks!

A: The answer is to check the following setting in one's locale configuration file:
  currency:
      format:
        strip_insignificant_zeros: false

A: Since you seem to be using a custom locale, try forcing the behavior you want by explicitly setting the options of number_to_currency:
number_to_currency(@purch.amount, :precision => 2)

You can also set these options in the locale file for your language. Take a look at http://guides.rubyonrails.org/i18n.html


text:
Q: Rspec - Module inside class I have tried several way to rspec the 'to_type' function. The fact that it is inside the class means that only the class should be able to call it right? I've tried to include the Class in my rspec but the module "Format" is still not recognized. Any ideas how I can rspec this method 'to_type' from the module?
class Loom::Lma < Loom::Base
  module Format
    STANDARD_FORMATS = {
      1 => '0',
      2 => '13.4',
    }
    def to_type(format)
      # type is calculated here then return type
      # for instance
      return :date
    end
    module_function :to_type
  end
  def initialize()
    #init stuff
  end
  def otherstuff()
        #another function
  end
end

RSPEC
it 'type should not be :date' do
   include Loom::Lma
   Format.to_type('some string format').should_not eq(:date)
end

Any ideas?

A: Are you sure you want to put that module into a class not the other way around?
Anyway, you can access to_type like this:
Loom::Lma::Format.to_type()


text:
Q: Is it possible to add methods to the Iterable interface in TypeScript? I have read about and successfully added a member to the Array interface using code like this:
interface Array<T> {
    first(): T | undefined;
}

Array.prototype.first = function<T>(this: T[]): T | undefined {
    return this.length > 0 ? this[0] : undefined;
};

However, if I try to do the same to the Iterable interface, it does not work:
interface Iterable<T> {
    first(): T | undefined;
}

Iterable.prototype.first = function <T>(this: Iterable<T>): T | undefined {
    return undefined;
}

The TS compiler returns an error about the line where I am trying to modify the Iterable prototype:
'Iterable' only refers to a type, but is being used as a value here.

Is it possible to add methods to Iterable? Thanks!

A: Iterable is an interface. All it means is "this thing that implements this interface is guaranteed to have the things the interface says it does". But an interface itself is not a thing.
If you modify an interface, the only thing it will do is show you in your code, at compile time, where things that implement the interface are not doing it correctly.
Here's some things you could do, just to put you in the mind set:
Declare a new interface, and make all of you code conform to it. Declare a new class and give it all the behavior you need. Or Create a static helper class that works by passing it instances of existing Iterables.
interface Iterable {
  propA: string;
  propB: string;
}

interface MyIterable<T> extends Iterable {
  propC: string;
  first: T;
  forEach: () => void;
}

class MyClassIterable<T> implements Iterable<T> {
  propA: string;
  propB: string;

  [Symbol.iterator] (): Iterator<T> {
    //
  }

}

class MyClassForMyIterable<T> implements MyIterable<T> {
  propC: string;
  first: T;
  propA: string;
  propB: string;

  [Symbol.iterator] (): Iterator<T> {
    //
  }

  forEach (): void {
    //
  }

  get first(): T | null {
    //
  }

}

abstract class IterationHelper {
  static first<T> (iterable: Iterable): T {
    return (some value from iterable)
  }
}


text:
Q: How to close eventSource with redux action in saga? I want to start and stop eventSource by buttons. Start button with CONSTANTS.FETCHING_STARTED action and stop button with CONSTANTS.FETCHING_STOPPED action.
https://github.com/redux-saga/redux-saga/issues/940 - not works for me.
I've tried stop and start in one function, but it didn't work.
This is my saga.
import {
  call,
  take,
  takeLatest,
  put,
  race,
  cancelled
} from "redux-saga/effects";
import { eventChannel, END } from "redux-saga";

import * as CONSTANTS from "../constants";

export function* innerSSE(eventSrc) {
  const eCh = eventChannel(emitter => {
    eventSrc.onmessage = msg => {
      emitter(msg);
    };

    eventSrc.onerror = () => {
      emitter(END);
    };

    return () => {
      eventSrc.close();
    };
  });

  try {
    yield takeLatest(eCh);
  } finally {
    if (yield cancelled()) eCh.close();
  }
}

function* start() {
  const eventSrc = new EventSource(CONSTANTS.STREAM_URL);
  const chan = yield call(innerSSE, eventSrc);

  while (true) {
    const msg = yield take(chan);

    yield put({
      type: CONSTANTS.FETCHING_IN_PROGRESS,
      payload: JSON.parse(msg.data)
    });
  }
}

function* stop(eventSrc) {
  // innerSSE.close()
}

export function* sseSaga() {
  while (true) {
    try {
      const started = yield take(CONSTANTS.FETCHING_STARTED);

      yield call(start, started);
    } catch (error) {
      console.log(error);
    }
  }
}

A: componentWillUnMount() => dispatch aciton => saga trigger

A: Try this
function* main(){
  yield takeLatest(CONSTANTS.FETCHING_STARTED, function*(){
    // create event channel
    const chan = eventChannel(()=>{ /* ... */})

    yield takeEvery(chan, function*(){
        // process event
    })

    try{
        // waiting for FETCHING_STOPPED
        yield take(CONSTANTS.FETCHING_STOPPED)
    }finally{
        // or close by another FETCHING_STARTED
        chan.close()
    }
  })
}

A:     function eventSource(eventSource, events = []) {
    const subs = emitter => {

        eventSource.onmessage = (msg) => {
            //return emitter(msg);
        };

        eventSource.onerror = () => {
            return emitter(END)
        };
        console.log(events);

        eventSource.addEventListener('disconnect', (event) => emitter({type: 'DISCONNECT', payload: JSON.parse(event.data)}), false);

        events.map((eventType, index) => {
            console.log(eventType);
            return eventSource.addEventListener(eventType, (event) => emitter({type: eventType, payload: JSON.parse(event.data)}), false)
        });

        return () => {
            return eventSource.close();
        }
    };
    return eventChannel(subs);
}

   function* itemsEventSource(formData){
    let result;
    try {

        const params = new URLSearchParams();

        params.append('clientId', formData.clientID);
        params.append('access_token', formData.token);

        result = new EventSource([SOCKET, 'notify'].join("/") + "?" + params.toString());

        const channel = yield call(eventSource, result, [CONNECTED, DISCONNECTED, FETCH_SUCCESS, 'NOTIFY']);

        while (true) {

            const action = yield take(channel);

            yield put(action);

        }

    } catch (error) {
        yield put({type: CONNECT_FAILED, error: error.message});
    }
    return result;}

    function* watchItemsEventSource() {
    while (true) {
        try {
            const {payload} = yield take(CONNECT);

            const [connect, cancel] = yield race(
                [
                    call(itemsEventSource, payload),
                    take(CONNECT_FAILED)
                ]);

            console.log(connect, cancel, payload);

        } catch (error) {
            yield put({type: ERROR, error: error.message});
        }
    }}

    export function *moduleASaga(){
       yield all({[ fork(watchItemsEventSource)]})   }


text:
Q: Send keyboard input to a specific app on Android? Java I want to send keyboard inputs to a specific app, mostly it will be tab presses.
Do you think this is possible? If so, how?
Note that Root Access is no problem.
I just need to make it press tab presses.
That's all.
It would send it to another Android app, that is not mine.


text:
Q: In Yii, why use CActiveDataProvider instead of Post::model()->findAll()? I see CActiveDataProvider used in the controller actionIndex() function.
Is there any difference between using this instead of simply Post::model()->findAll()?

A: CActiveDataProvider is a wrapper for CActiveRecord with extended capabilities of sorting, pagination and filtering. Typically CActiveDataProvider is being used in conjunction with zii widgets like CListView or CGridView which are utilizing its sort and search capabilities. So if you want to display data in terms of list or table with (optional) sorting/filtering/pagination - most convenient way of doing it in Yii is using described zii widgets or their extensions.
If you just need to fetch data and use it in any other way, but without smart rendering mechanisms provided by CListView or CGridView - use CActiveRecord, because it doesn't perform anything else except of fetching of data.
reference


text:
Q: Java - JSON to YAML (Dynamic) I want to convert JSON to YAML. And I want to this in Java dynamically. Based on the componentId, properties will change. This JSON can vary and supports multiple componentIds and this comes from HTTP request.
Example JSON:
[
    {
        "id": "timer",
        "attributes": {
            "type": "tick"
            "period": "5000"
        },
        "output": "transform"
    },
    {
        "id": "transform",
        "attributes": {
            "expression": "${body.toUpperCase()}",
            "type": "simple"
        },
        "output": "log"
    },
    {
        "id": "log",
        "attributes": {
            "message": "hello world",
            "type": "info"
        }
    }
]

Expected YAML:
- from:
    uri: "timer:tick"
    parameters:
      period: "5000"
    steps:
      - set-body:
          constant: "Hello Yaml!!!"
      - transform:
          simple: "${body.toUpperCase()}"
      - to: "log:info"

A: I think you should be able to convert any kind of JSON to YAML using Jackson. Add the following dependencies to your project:
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>${jackson.version}</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.dataformat</groupId>
            <artifactId>jackson-dataformat-yaml</artifactId>
            <version>${jackson.version}</version>
        </dependency>

If you have an input Kamelet JSON string like this:
{
  "apiVersion": "camel.apache.org/v1alpha1",
  "kind": "Kamelet",
  "metadata": {
    "name": "echo-sink",
    "labels": {
      "camel.apache.org/kamelet.type": "sink"
    }
  },
  "spec": {
    "definition": {
      "title": "Echo",
      "description": "Replies with an echo message to each incoming event",
      "properties": {
        "prefix": {
          "title": "Prefix",
          "description": "The prefix to prepend to the incoming event",
          "type": "string",
          "default": "echo: "
        }
      }
    },
    "types": {
      "in": {
        "mediaType": "text/plain"
      },
      "out": {
        "mediaType": "text/plain"
      }
    },
    "flow": {
      "from": {
        "uri": "kamelet:source",
        "steps": [
          {
            "set-body": {
              "simple": "{{prefix}}${body}"
            }
          }
        ]
      }
    }
  }
}

You can easily convert it into YAML using Jackson like this:
File jsonFile = new File(JsonToYaml.class.getResource("/kamelet.json").getFile());

ObjectMapper jsonMapper = new ObjectMapper();
YAMLMapper yamlMapper = new YAMLMapper();

// Read file as JsonNode
JsonNode jsonNode = jsonMapper.readTree(jsonFile);
// Convert it into YAML String
String yamlOutput = yamlMapper.writeValueAsString(jsonNode);

System.out.println(yamlOutput);


text:
Q: How to pass in a variable from middleware to controller in laravel I made a input with type time and when i select 12 pm it shows me 12:00 but when i try to use carbon and get time for 12:00 like this -> Carbon::now()->addMinute(30)->format('H:i') It shows me 00:00 so what can i do about that? how can i make them both the same way?
My html code ->

<input type="time">

My php code ->

return Carbon::now()->addMinute(30)->format('H:i'); // Added 30 because 30 minutes was left for 12:00 pm


text:
Q: Running maven command remotely using ssh Trying to execute a script on the remote aws centos machine using the command mentioned below
ssh root@hostname script

Everything works fine until the script comes to a maven command. For example "mvn package" in the script. Getting the error below.
    bash: mvn: command not found


text:
Q: What is the correct way to calculate percentage increase/decrease between two numbers using Decimal.js? Desired Behaviour
Show percentage increase/decrease of new_value in comparison to old_value, showing negative indicator when there has been a decrease, and 4 decimal places (with trailing zeros if necessary).
Actual Behaviour
Good
If old_value is 38.1200 and new_value is 19.0600 result is -50.0000
Not so good
If old_value is 0.0000 and new_value is 1.0000 result is Infinity (I expect the result to be 100.0000.  Edit: I now realise that there is no such thing as a percentage increase from 0 to anything, per posts like this).
What I've Tried

var old_value = new Decimal(0.0000);
var new_value = new Decimal(1.0000);
var difference = new_value.sub(old_value).dividedBy(old_value).times(100).toFixed(4, 7);

// without using Decimal.js, the equation above would be:
// (new_value - old_value) / old_value * 100

$(".result").text(difference.toString());

A: I am assuming the equation is correct, it was just the Infinity result that threw me, so here is solution to "handle" the issue:

var old_value = "38.1200";

if (old_value === "0.0000") {
  // show an infinity sign or something
  $(".result").text("HI!!");
} else {
  old_value = new Decimal(old_value);
  var new_value = new Decimal(19.0600);
  var difference = new_value.sub(old_value).dividedBy(old_value).times(100).toFixed(4, 7);

  $(".result").text(difference.toString());
}


text:
Q: Reading date with numbers such as "27.10.82" Can you please say how to read if the date is written like this: 27.10.82
Should it be pronounced - 27th October, 1982 or can we say just the numbers? If only numbers are enough, should we say point or dot?

A: As FumbleFingers says in a comment, in ordinary speech, I'd say it in full. In some contexts where it was already established that this was a date - for example, when reading out a list of dates, or when going through a number of files in a drawer, reading out the date on each one - i might say "twenty-seven ten eighty-two". I wouldn't say "dot" or "point" or anything else between them (and in writing, I would more likely use / or - than .)


text:
Q: PHP seems to disregard function & array in foreach I've been trying to make a simple video list system for my website, and I can't get this working.
    $buffer = explode("|", $playlist['videos']);
    $id = 0;

    foreach($buffer as $key) {
        if(!empty($key)) {
            $id++;
            $video = getVideoFromId($key, $conn);
            print_r($video);

getVideoFromId
function getVideoFromId($id, $connection) {
    $stmt = $connection->prepare("SELECT * FROM videos WHERE rid = ?");
    $stmt->bind_param("s", $id);
    $stmt->execute();
$result = $stmt->get_result();
$video = $result->fetch_assoc();
$stmt->close();

return $video;
}

It seems to completely ignore it, buffer is not empty because when I print_r'd it, it outputted the stuff that I needed. $playlist is a function named getPlaylistFromID.
getPlaylistFromId
function getPlaylistFromID($id, $connection) {
    $stmt = $connection->prepare("SELECT * FROM playlists WHERE rid = ?");
    $stmt->bind_param("s", $id);
    $stmt->execute();
$result = $stmt->get_result();
$playlist = $result->fetch_assoc();
$stmt->close();

return $playlist;
}

$key is the video ID, and $video is an array of the video containing all the data like the title, description, and whatnot.
$buffer is usually a video id seperated by |, for example: |MTYxMTUxNzE2MzQ=47|MTYxMTUxNzE2MzQ=47|MTYxMTUxNzE2MzQ=47|MTYxMTUxNzE2MzQ=47|MTYxMTUxNzE2MzQ=47|MTYxMTUxNzE2MzQ=47 is the format it is in.


text:
Q: Javascript memorise HTML tag contents and replace after duration I have the following code that copies a Server IP to the client's clipboard via a .swf solution. As you can see it replaces the Copy IP button with a success 'Copied' message. How would I go about having that Copy IP button return after 5 seconds of displaying the success message, so the user can copy and paste multiple IP addresses from that page, copying the same one more than once.

A: Just add a setTimeout inside the client.on function. Because of how JS closures work it will have access to the event object even though setTimeout is asynchronous and will execute 5 seconds later:
    function addCopyHandler(id) {
      var client = new ZeroClipboard( document.getElementById(id) );
      client.on( "ready", function( readyEvent ) {
      // alert( "ZeroClipboard SWF is ready!" );
          client.on( "aftercopy", function( event ) {
              // `this` === `client`
              // `event.target` === the element that was clicked
              event.target.innerHTML = " Copied";
              event.target.style.textDecoration = "none";
              event.target.style.color = "#3c763d";
              event.target.style.cursor = "default";
              setTimeout(function(){
                  event.target.innerHTML = "Copy IP";
                  event.target.removeAttribute("style");
              },5000);
          });
      });
    }

A: You can use setTimeout() function. It's used to execute a command after the specified delay (in milliseconds).
client.on( "aftercopy", function( event ) {
                  // `this` === `client`
                  // `event.target` === the element that was clicked
                  event.target.innerHTML = " Copied";
                  event.target.style.textDecoration = "none";
                  event.target.style.color = "#3c763d";
                  event.target.style.cursor = "default";
                  setTimeout(function(){
                      event.target.innerHTML = " Copy";
                  },5000);

          });


text:
Q: Why doesn't it work? A simple SQL query I'm new to SQL, I have 3 tables in my database:

*

*One named notifications,

*the other notifications_log,

*and the third one is control.

Both notification and notification_log have notification_id with pk-fk relation.
There is also another column named control_id in notifications and I have this column in control table too.
Now  what I want to do is to get rows under description column of notification_log table by connecting notification table and control table with their control_id field. Can you help me with that?
Here's something I've tried:
select c.control_name
  from notifications note, notifications_log note_log, control c
 where note_log.ALARM_ID = note.ALARM_ID
   and note.CONTROL_ID = C.CONTROL_ID
  order by control_name desc

A: Use JOIN:
SELECT c.control_name, note_log.description FROM notifications note
INNER JOIN notifications_log note_log
    ON note.notification_id = note_log.notification_id
INNER JOIN control c
    ON note.control_id = c.control_id
ORDER BY c.control_name DESC

What you have to understand is if every record in control table has a corresponding record in other tables, otherwise it will not be showed with INNER JOIN.

A: select description from notification_log where notification_id in (select notification_id from notification)
if you want to get only the description..
hope it helps :D

A: From your description, it sounds as though you are selecting the wrong field in your query. Try:
select distinct note_log.description
  from notifications note, notifications_log note_log, control c
 where note_log.notification_id = note.notification_id
   and note.CONTROL_ID = C.CONTROL_ID
order by 1


text:
Q: Google pubsub listener not receiving all the messages I'm using Google Cloud Storage for storing objects, with the bucket associated to a topic and subscription id. The flow is such that a Java application requests for the upload link(s), and upload object(s) using those upload link(s). I also have a pubsub listener implemented in Java, which receives the upload notification message, and does something on every successful upload. This is the snippet that handles the event listening.
public void eventListener() {
    MessageReceiver messageReceiver = (message, consumer) -> {
        final Map<String, Object> uploadMetaDataMap = getUploadDataMap(message);
        LOGGER.info("Upload event detected => {} ", uploadMetaDataMap);
        // do something
        consumer.ack();
    };
    Subscriber subscriber = null;
    Subscriber finalSubscriber = subscriber;
    /* To ensure that any messages already being handled by receiveMessage run to completion */
    Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override
        public void run() {
            finalSubscriber.stopAsync().awaitTerminated();
        }
    });
    try {
        subscriber = Subscriber.newBuilder(subscription, messageReceiver)
                .setCredentialsProvider(FixedCredentialsProvider.create(creds)).build();
        subscriber.addListener(new Subscriber.Listener() {
            @Override
            public void failed(Subscriber.State from, Throwable failure) {
                // Handle failure. This is called when the Subscriber encountered a fatal error and is shutting down.
                LOGGER.error(String.valueOf(failure));
            }
        }, MoreExecutors.directExecutor());
        subscriber.startAsync().awaitRunning();
        subscriber.awaitTerminated();
    } finally {
        if (subscriber != null) {
            subscriber.stopAsync().awaitTerminated();
        }
    }
}

I'm storing the objects in this format => bucket/uuid/objectName.extension and on every successful upload, LOGGER.info("Upload event detected => {} ", uploadMetaDataMap); logs messages like this
2020-08-03 16:12:14,686 [Gax-1] INFO  listener.AsynchronousPull - Upload event detected => {size=85, uuid=6dff9a20-3995-4f28-93e9-79e6c3cf613d, bucket=bucketName}

The issue I'm facing now is, not all the successful upload events send out notification message. I can see the folder structure created in the GCS with the respective object inside it, but notification related to that upload is nowhere to be found in the logs printed by pubsub listener. It's been bothering me for a while now, and could really use some help with this.


text:
Q: iterate through non-consecutive enum elements in c++ There are many ways to iterate through consecutive enums like
enum Animal {Cat, Dog, Dolphin}

But is there a convenient and easy way to iterate through non-consecutive enum elements like
enum Animal {Cat = 0, Dog = 5, Dolphin = 8}

A: The short answer to this is "no".
You could make a table animals, and then use a range loop on animals.
Here's a complete "demo":
#include <iostream>

using namespace std;

enum Animal {Cat = 0, Dog = 5, Dolphin = 8};

int main()
{
    Animal animals[] = { Cat, Dog, Dolphin };

    for(Animal a : animals) cout << a << endl;
}

The output will be:
0
5
8

A: You could also provide the necessary operator(s) for the enumeration:
enum Animal
{
  Cat = 0
  , Dog = 5
  , Dolphin = 8
};

inline Animal& operator++ (Animal &x)
{
  switch (x) {
    case Cat:
      x = Dog;
      break;
    case Dog:
      x = Dolphin;
      break;
    case Dolphin:
    default:
      x = static_cast<Animal>(static_cast<int>(x) + 1);
      break;
  }
  return x;
}

DTTO for postfix ++, < and anything else you need. Of course, you have to keep them in sync with the definition of the enumeration. Not really straightforward, but it is an option.

A: I'm not sure that the question even makes sense.  It is at any
rate fundamentally impossible.  Consider:
enum Animal
{
    cat = 0,
    dog = 5,
    dolphin = 8,
    canine = 5,
    bear = 20
};

When the underlying value is 5, you have no way of determining
whether it was set by dog or by canine, and so no way of
knowing whether the next value should be dolphin or bear.
You could put the values in an array, and iterate over that, but
I don't see any other solution.
In general, of course, most of the time you're explicitly
affecting values like this this, you're defining a bitmask (e.g.
like std::ios_base::fmtflags), and in that case, it makes no
sense to iterate.  Other use cases I can think of would be
special sentinal values (e.g. something like unset), which you
would probably want to skip when iterating, or synonyms (like my
dog/canine example above), in which case, you'd probably
only want to visit one of the synonyms, and realistically, you'd
write something like:
enum Animal
{
    cat,
    dog,
    canine = dog,
    dolphin,
    bear
};

, and the usual iteration tricks would result in exactly what
you want.


text:
Q: Compact operator on a hilbert space.
Possible Duplicate:
A compact operator is completely continuous.

I came across this question in a book, it is an exercise, I can't prove it. Can someone please help me.
If $X$ and $Y$ are Banach spaces, we have to prove that a compact linear operator is completely continuous.
 A mapping $T \colon X \to Y$ is called completely continuous, if it maps a weakly convergent sequence in $X$ to a strongly convergent sequence in
$Y$ , i.e., $x_n\underset{n\to +\infty}\rightharpoonup x$  implies $\lVert Tx_n-
Tx\rVert_Y\to 0$.

A: Suppose not. Then there is some sequence $(x_n)$ in $X$ with $x_n \rightharpoonup x$ but $Tx_n \not\to Tx$. That is, there is some $\epsilon > 0$ such that $\|Tx_{n_j} - Tx\| \ge \epsilon$ for some subsequence $(x_{n_j})$. As $(x_{n_j})$ is bounded and $T$ is compact, some subsequence converges in $Y$, say $Tx_{n_{j_k}} \to y$. As $T$ is norm-to-norm continuous, it is weak-to-weak continuous, hence $Tx_{n_{j_k}} \rightharpoonup Tx$. Weak limits are unique, so $Tx = y$, that is $Tx_{n_{j_k}} \to Tx$, contradicting the choice of $(x_{n_j})$.
Hence $T$ is completely continuous.


text:
Q: In Jupyter Notebook, what is the best way to execute a function from another notebook? I am new to Jupyter Notebooks and using the Anaconda install for Python 3.7. What is the best way to execute a function from another notebook? I found this 2-year-old answer here, but I don't know if there is a new/better way to do it with the Anaconda install (nbimporter has to be installed separately, it's not in Anaconda).
Here is the code/info in the notebooks:
Try #1 (fail)
# working directory files:
# mytest.ipynb # this contains the function I am trying to call
# Untitled.ipynb # this is the Notebook I am working in

# mytest.ipynb contents:
def testfcn(x):
    return print("input is", str(x))

# Untitled.ipynb contents:
from mytest import testfcn
testfcn(4)

ModuleNotFoundError: No module named 'mytest'

Try #2 (okay, not ideal)
# Untitled.ipynb contents:

%run mytest.ipynb
testfcn(4)

# returns this, extra stuff:
0.019999999999999997
<class 'float'>
input is 4

A: The discussion here includes a comment by MEdwin on how to run another notebook from within yours and then you'll be able to call the functions of the other notebook in the noteboook where you ran the %run other_notebook.ipynb step.
Update: I just came across the subnotebook project that let's you run a notebook as you would call a Python function, pass parameters and get results back, including output contents. Might be useful in this context. END OF UPDATE.
Additionally, for Python functions, you don't want to do return print. You'd either remove the return and leave the print part or return the string that you could then print.


text:
Q: Google Chrome Extension Cross domain AJAX and Content-Security-Policy I am developing a Google Chrome Extensions which fetches title and description from each site and send to the server using jQuery AJAX. I am using manifest version 2 and added permissions for all http and https sites. The Ajax call was working fine with all sites.
Last day I found an error which prevented the code from sending ajax to server. To be accurate facebook.com was not allowing me to send cross domain request as they are using the HTTP header Content-Security-Policy(CSP). I think this is not related to the CSP of extension.
I am using Google Chrome version 25.0.1364.160.
Is this CSP Header breaking the cross-domain request capability of the Chrome extensions ?
Is there any workaround ?
Thanks in Advance!


text:
Q: Angular ng-repeat, Gridster, and Web Components are conflicting I am using angular-gridster to show a grid in my application, but I am seeing some strange behavior, of which my search efforts have yielded nothing.
Here is my code for showing a simple grid in gridster::

{{item.sizeX}}

standardItems is just the example from the gridster-angular GitHub:
$scope.standardItems = [
  { sizeX: 2, sizeY: 1, row: 0, col: 0 },
  { sizeX: 2, sizeY: 2, row: 0, col: 2 },
  ...
  { sizeX: 1, sizeY: 1, row: 2, col: 3 },
  { sizeX: 1, sizeY: 1, row: 2, col: 4 }
];

In addition to this grid, other parts of my application use web components, and therefore the webcomponents.js polyfill.
In Chrome (a browser that natively implements web components), the page works fine.  But in FireFox and IE (browsers that either do not natively support web components or require user settings to be changed) have an issue processing the ng-repeat.  In fact, it doesn't seem process the ng-repeat at all, and the containing div that gridster generates is completely empty.
The following is the HTML generated by gridster in FireFox (note the empty .gridster-content):

                                                /\
                         Why is this empty? ----||

If I remove the webcomponents.js polyfill from being loaded on my page, then gridster and the ng-repeat works perfectly in all browsers.  This leads me to believe that out of these three items, something is conflicting with the others.
Has anyone encountered this sort of problem?  Any help is very appreciated.
Links:
angular-gridster
webcomponents.js

A: its a problem with webcomponents library here you can find a reference to it https://github.com/webcomponents/webcomponentsjs/pull/393


text:
Q: Change condition of replaced member function operator bool() I have this struct called Status which have this member function bool():
struct Status {
public:
    Status();
    operator bool() const;
private:
    bool ok_; //!< true if successful and false otherwise
    ErrorMessage message_; //!< Message with "Ok" or error
};

Status::Status():
ok_(true),
message_("Ok") {
}

Status::operator bool() const {
    return ok_;
}

So I replaced operator bool() with function isOk():
bool Status::isOk() const {
    return ok_;
}

Now, I have some code which used this bool() construction before:
if (!(status = CheckLength(currentIndexFrom, currentIndex, currentLexemStartLineNum))) {
    return status;
}

CheckLength returns status object:
Status CheckLength(Uint32 indexFrom, Uint32 indexTo, Uint32 lineNum) {
    Status status;
    if (indexTo - indexFrom + 1 > limits::xml::tokenValueLength) {
        Char8 message[limits::xml::errorMesLength] = {};
        snprintf(message, sizeof(message),
        "Unexpected expression in string %u, or is larger than %u characters",
        lineNum,
        limits::xml::tokenValueLength);
        status.setError(message);
    }
    return status;
}

How to change if (condition) right?

A: You can change it like this:
if (!(status = CheckLength(currentIndexFrom, currentIndex, currentLexemStartLineNum)).isOk())

but why would you do this? AFAIK the operator makes the code more readable so I would keep it as it is, and only use isOK where it makes sense.


text:
Q: Number of ways to make n digit number? Given M digits which are between 1 to 9,
Find the number of ways to form N digit number, by repeating one or more given digits such that each of M digits are present in N digit number at least once.
Example if M = 3 and N = 4
Answer is 36.
Explanation -  let the three digits be 1 2 3
our N = 4, digit number can be 1123, 3211, 1132, ..... repeating 1
similarly repeating 2 and three we will get the total ans.
Since answer is large find the ans % 10000000007.
1 ≤ M ≤ N ≤ 100.

A: If I understand this correctly it is a familiar problem, equivalent to the problem
of counting the number of $N$-letter words from an alphabet of size $M$,
with the restriction that each letter is used at least once.
The well-known answer is $M!S(N,M)$, where $S(N,M)$ is the Stirling number of the second kind,
counting the number of ways to partition $[N]$ in $M$ parts.
You can find references about these Stirling numbers like recursive formulas
and generating functions all over the place if you actually need to write a program
that produces the answer for concrete values of $M$ and $N$.
Btw, a Java implementation using a simple summation for these Stirling numbers calculates
e.g. $S(200,100)$ in a fraction of a second (although it has over 200 digits), so performance cannot be a problem for the values you mention.