text:
Q: jQuery keyup event is activated multiple times, doubling every time it's triggered I added an auto-completing search bar to my website. It queries the database for elements that start with the entered string every time the user types a new character.
It works fine, however every time the user adds another character or does any keyboard event like backspace it doubles the event activation. 1,2,4,8,16, etc.. times.
How could I make it so that it doesn't accumulate event triggers and only triggers .keyup() one time per keyboard event?
Here's the HTML code:
<form>

    <input class="search-query form-control" placeholder="Items"
       type="text"  name="items" value="" id="id1" />

</form>

And here's the jQuery code:
$(document).ready(function() {
  $('#id1').keyup(function(){
    var query = $(this).val();
    $.get('/url/', {items: query}, function(data){
      $('#id2').html(data);
    });
  });
});

A: I finally figured out how to fix it.
For anyone interested, here's how I did it:
(Obviously more experienced user please feel free to correct me if I am wrong!)
Basically, adding a .one() method solved it. As it detaches the event from the "#id1" element by only executing it once.
Here's the functional code:
$(document).ready(function() {
  $('#id1').one("keyup", function(){
    var query = $(this).val();
    $.get('/url/', {items: query}, function(data){
      $('#id2').html(data);
    });
  });
});

For comparison here's the old one as posted above again:
$(document).ready(function() {
  $('#id1').keyup(function(){
    var query = $(this).val();
    $.get('/url/', {items: query}, function(data){
      $('#id2').html(data);
    });
  });
});

A: Add these lines:
$(document).ready(function() {
var lastTime = Date.now(), milisecondsToWait = 2000;//Here we will wait 2 seconds
  $('#id1').keyup(function(){
    if(Date.now() - lastTime >= milisecondsToWait){//And here
      var query = $(this).val();
      $.get('/url/', {items: query}, function(data){
        $('#id2').html(data);
        lastTime = Date.now(); //And finally here
      });
    }
  });
});


text:
Q: Having same NavigationDrawer in all acitivies I have followed a bunch of examples for implementing the same NavigationDrawer in all activities so far no success.
I have 2 issues:
1.
I Have defined a BaseActivity and Override its setContentView.
BUT in setContentView I don't seem to be able to access the ListView containing my NavDrawer items.
(drawerListView returns null)

*
How am I supposed to reuse the code for my NavDrawer? I could not find a good example here.
I don't like to add a DrawerLayout, FrameLayout and ListView to all my Fragment layout xmls.
Right now the only solution to have NavigationDrawer in all my pages that comes to my mind is like this:

I change my fragment layouts so that the whole xml is embedded in a frame layout like this:
so that all my fragments layouts have THEIR own NavDrawer. This is what I DO'NT like and I know is
a bad solution. (I'm not even sure if this will work and in my BaseActivity I won't face difficulties having many ListViews with the same id ("drawerList") and many FrameLayouts with the same id....
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<android.support.v4.widget.DrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

<FrameLayout
    android:id="@+id/mainContent"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    all my xml content to form a fragment

</FrameLayout>

<!-- Use any Views you like -->
<ListView
    android:id="@+id/drawerList"
    android:layout_width="240dp"
    android:layout_height="match_parent"
    android:divider="@android:color/transparent"
    android:dividerHeight="0dp"
    android:background="#ffffff"
    android:layout_gravity="left"
    />
</android.support.v4.widget.DrawerLayout>

What am I supposed to do? any good and clear example is highly appreciated.
The code for my BaseActivity
public class BaseActivity extends ActionBarActivity implements OnItemClickListener
{
private DrawerLayout drawerLayout;
private String[] properties;
private ListView drawerListView;

protected DrawerLayout fullLayout;
protected FrameLayout actContent;

@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
        long id) {
    Intent intent2=new Intent(BaseActivity.this, ActivitySearchForSale.class);
    startActivity(intent2);

}
@Override
public void setContentView(int layoutResID) {
    fullLayout= (DrawerLayout) getLayoutInflater().inflate(layoutResID, null); // Your base layout here
    actContent= (FrameLayout) fullLayout.findViewById(R.id.drawer_layout);
    drawerListView = (ListView) findViewById(R.id.drawerList);
    properties = getResources().getStringArray(R.array.propertyTypeArray);
    drawerListView.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, properties));
    drawerListView.setOnItemClickListener((OnItemClickListener) this);

    getLayoutInflater().inflate(layoutResID, actContent, true); // Setting the content of layout your provided to the act_content frame

    super.setContentView(fullLayout);
}

The code for my activity_main.xml i which I have defined the DrawerLayout and I don't know how to include this in my other fragment layouts.
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">

<FrameLayout
android:id="@+id/mainContent"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
    style="@style/StyleForSimpleTextView"
    android:text="zzzzz"
    />
</FrameLayout>

<!-- Use any Views you like -->
<ListView
    android:id="@+id/drawerList"
    android:layout_width="240dp"
    android:layout_height="match_parent"
    android:divider="@android:color/transparent"
    android:dividerHeight="0dp"
    android:background="#ffffff"
    android:layout_gravity="left"
    />
</android.support.v4.widget.DrawerLayout>

My activity_search_for_sale.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/container"
android:layout_width="fill_parent"
android:layout_height="match_parent"
tools:context="com.*.*.ActivitySearchForSale"
tools:ignore="MergeRootFrame" />

My fragment_search_for_sale
<?xml version="1.0" encoding="utf-8" standalone="no"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    >

<LinearLayout android:id="@+id/llSearchForSale"
style="@style/StyleForParentVerticalLinearLayouts">
.

.

.

   </LinearLayout>
   </ScrollView>

Java class for activity:
public class ActivitySearchForSale extends BaseActivity{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search_for_sale);
        if (savedInstanceState == null) {
            getSupportFragmentManager().beginTransaction().add(R.id.container, FragmentSearchForSale.newInstance(3)).commit();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        return super.onOptionsItemSelected(item);
    }

}

And I have a java class for my fragment which onCreateView is as follows:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View rootView;
        rootView = inflater.inflate(R.layout.fragment_search_for_sale, container, false);
    return rootView;
}

A: Seems like you forgot to find the drawerList view in the layout you just inflated.
Instead you tried to findViewById on the activity's content which was not yet set.
Furthermore it looks like your trying to cast the DrawerLayout to a FrameLayout which is probably not what you wanted.
Create a layout that holds your Drawer (e.g. drawer_layout.xml):
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<android.support.v4.widget.DrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

<ListView
    android:id="@+id/drawerList"
    android:layout_width="240dp"
    android:layout_height="match_parent"
    android:divider="@android:color/transparent"
    android:dividerHeight="0dp"
    android:background="#ffffff"
    android:layout_gravity="left"/>
</android.support.v4.widget.DrawerLayout>

Override the setContentView in your BaseActivity like this:
@Override
public void setContentView(int layoutResID) {
    // All activities share the drawer
    drawer = (DrawerLayout) getLayoutInflater().inflate(R.layout.drawer_layout, null);
    drawerListView = (ListView) fullLayout.findViewById(R.id.drawerList);
    properties = getResources().getStringArray(R.array.propertyTypeArray);
    drawerListView.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, properties));
    drawerListView.setOnItemClickListener((OnItemClickListener) this);

    // After creating the drawer add the activity's layout as the first child
    ViewGroup layout = getLayoutInflater().inflate(layoutResID, null);
    drawer.addView(layout, 0);

    super.setContentView(fullLayout);
}

Now your activity_main.xml will look like:
<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/mainContent"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
    <TextView
        style="@style/StyleForSimpleTextView"
        android:text="zzzzz"/>
</FrameLayout>

And you set it with:
setContentView(R.layout.activity_main);

This will work for all of your activities as long as they extend BaseActivity.

redpajama_set_name: RedPajamaStackExchange


text:
Q: sort words in text by number of times cited in same line look for most frequent words in text, sorted by numbers printed in same line for each number
    grep -oE '[[:alpha:]]' file.txt | sort | uniq -c | sort -nr

it gives
3 linux
3 fedora
2 ubuntu
2 mandriva

i look for
3 linux fedora
2 ubuntu mandriva

    grep -oE '[[:alpha:]]' file.txt | sort | uniq -c | sort -nr

the result
 3 linux
 3 fedora
 2 ubuntu
 2 mandriva

I look for
 3 linux fedora
 2 ubuntu mandriva

A: I wasn't able to do it in a bash oneliner, but I have it here in short python script if that works for you.
import os

preMergedList = os.popen("grep -o -E '\w+' file.txt | sort | uniq -c | sort -nr").readlines()

countDict = {}
for line in preMergedList:
    count, word = line.split(None)
    count = int( count.strip() )
    word = word.strip()
    if not countDict.has_key( count ):
        countDict[count] = ""
    countDict[count] += word + " "

for count, wordString in sorted( countDict.iteritems(), reverse=True ):
    print count, wordString


text:
Q: can i split my Stored procedure into two like this? Since i got error  error when I try to run a stored procedure from mvc project which return multiple result sets i decided to split my Sp like this :
I am using Entity Framework database-first approach.
This was my original stored procedure :
  Create PROCEDURE [dbo].[uspMarket_test]
@UserID INT OUTPUT,
@Session VARCHAR(36)
  AS
  BEGIN
SET NOCOUNT ON;

    SELECT TOP 1
        FirstName, LastName, grant
    FROM dbo.test_Users AS U
    WHERE
       U.userID = @UserID
       AND CAST (U.userHashKey as varchar(36)) = @Session;

    select
       GS.Account, GSA.Permissions
    from user_name GS
    Inner join user_name_Apps GSA on GS.ID = GSA.ID
    where GS.UserID = @UserID

    UPDATE dbo.test_Users
    SET grant = 0
    WHERE
     userID = @UserID
     ;

    END

Now i split this into two like this :
   USE [Tracker]
   GO
  SET ANSI_NULLS ON
   GO

   SET QUOTED_IDENTIFIER ON
  GO

   Create PROCEDURE [dbo].[Market_Scope]
@UserID INT OUTPUT
  AS
    BEGIN
SET NOCOUNT ON;

SELECT TOP 1

       GS.Account, GSA.Permissions
     from user_name GS
     Inner join user_name_Apps GSA on GS.ID = GSA.ID
       where GS.UserID = @UserID
 ;
          END
           GO

2nd SP is :
    USE [Tracker]
   GO
   SET ANSI_NULLS ON
   GO

   SET QUOTED_IDENTIFIER ON
   GO

   Create PROCEDURE [dbo].[Market_Users]
          @UserID INT OUTPUT,
        @Session VARCHAR(36)
        SELECT TOP 1
       FirstName, LastName, grant
        FROM dbo.test_Users AS U
     WHERE
      U.userID = @UserID
     AND CAST (U.userHashKey as varchar(36)) = @Session;
    UPDATE dbo.test_Users
     SET grant = 0
    WHERE
    userID = @UserID
     ;

    END
     Go

Now i am calling these two SP like this in my class :
     public void permissions(string sess)
    {
        using (var ctx2 = new Tracker_Entities())
        {
       ctx2.uspMarket_Users(new ObjectParameter("UserID", typeof(int)), sess);
       ctx2.uspMarket_list(new ObjectParameter("UserID",typeof(int)));
       ctx2.SaveChanges();
        }
      }

This is how i calling in controller :
  public ActionResult Index(string sess)
    {

        var permissions = new Accept();
        permissions.permissions(sess);

        return View();
     }

since both SP just selecting records what i did is i populated dummy data into my user_name_apps table. So how do i  check in front end whether this SP executing properly or not? I can execute in my sql server and it is working fine there.But i want to make sure i am calling my SP correctly. So how can i do this ?


text:
Q: Dual monitor, permission issue I had a dual monitor configuration going on for quite some time. One day, after moving the computer to another location and reconnecting everything, it changed such that I saw everything in double (being very much sober), I think it's called the 'mirrors' config. Anyway, from there on, there was nothing to be done through the system settings gui to change it back, as it wouldn't allow me to save any modification. The error I get when clicking 'save' is :
"Failed to create file /home/me/monitors.xml.xxxxxx. Permission denied", xxxx being a random code, changing everytime.
However, I can save all the configurations I want just fine by using the terminal, in my case:
 xrandr --output DVI-I-1 --right-of VGA-1

So I do have a workaround and this is therefore a question more out of curiosity. What could possibly have changed to make it impossible to do it through the gui and still letting me change the config using xrandr without being root? I'm having a hard time believing it could have anything to do with disconnecting/reconnecting the monitors... Any idea? Thanks !

A: I don't know what happened, but try to add the command to a startup script. This will take care of it after you login.
As for why this happened, perhaps an update of some sort. Connection/Deconnection has probably nothing to do with it (although ya never know)

A: The monitors.xml file goes under /home/me/.config/monitors.xml.  You may try to remove it, if it's there and check the .config directory permissions.


text:
Q: Display custom UI Component in modal I have created a UI Component based on the code from Alan Storm's excellent tutorial. This UI Component displays as expected in pages with dedicated routes.
However, the UI Component will not display in a modal on the Product page in adminhtml. Here is a Modifier for a modal to display the UI Component from the fine tutorial:
<?php
namespace Dotancohen\Foo\Ui\DataProvider\Product\Form\Modifier;

use Magento\Catalog\Model\Locator\LocatorInterface;
use Magento\Catalog\Ui\DataProvider\Product\Form\Modifier\AbstractModifier;

class Features extends AbstractModifier {

    protected $_product;

    /**
     * @param LocatorInterface $locator
     */
    public function __construct(LocatorInterface $locator)
    {
        $this->_product = $locator->getProduct();
    }

    public function modifyMeta(array $meta) : array
    {
        if ( !$this->_product ) {
            return $meta;
        }
        $product_id = $this->_product->getId();

        $meta['exclude_modal'] = array (
            'arguments' => array (
                'data' => array (
                    'config' => array (
                        'componentType' => 'modal',
                        'dataScope' => '',
                        'provider' => 'product_form.product_form_data_source',
                        'ns' => 'product_form',
                        'options' => array (
                            'title' => 'Configure Particular Foo or Bar', /* How to Display the Foo ID or Bar ID here? */
                            'buttons' => array (
                                0 => array (
                                    'text' => 'Save',
                                    'class' => 'action-primary',
                                    'actions' => array (
                                        0 => array (
                                            'targetName' => 'index = product_form',
                                            'actionName' => 'save',
                                        ),
                                        1 => 'closeModal',
                                    ),
                                ),
                            ),
                        ),
                    ),
                ),
            ),
            'children' => array (
                'modal_content' => array (
                    'arguments' => array (
                        'data' => array (
                            'config' => array (
                                'autoRender' => false,
                                'componentType' => 'container',
                                'dataScope' => 'data.product',
                                'externalProvider' => 'data.product_data_source',
                                'ns' => 'product_form',
                                'render_url' => 'https://example.com/admin/mui/index/render/key/123abc/',
                                'realTimeLink' => true,
                                'behaviourType' => 'edit',
                                'externalFilterMode' => true,
                                'currentProductId' => $product_id,
                            ),
                        ),
                    ),
                    'children' => array (
                        'modal-fieldset' => array (
                            'arguments' => array (
                                'data' => array (
                                    'config' => array (
                                        'label' => 'Fieldset',
                                        'componentType' => 'fieldset',
                                        'dataScope' => 'foos_features',
                                        'collapsible' => true,
                                        'sortOrder' => 10,
                                        'opened' => true,
                                    ),
                                ),
                            ),
                            'children' => array (
                                /* These "Features" will be different for each Foo and Bar! How to get the Foo or Bar ID to invoke a method which will return the proper data? */
                                'first_feature' => array (
                                    'arguments' => array (
                                        'data' => array (
                                            'config' => array (
                                                'label' => 'Feature the first',
                                                'dataScope' => 'first_feature',
                                                'componentType' => 'pulsestorm_simple',
                                                'sortOrder' => 10,
                                            ),
                                        ),
                                    ),
                                ),
                                'second_feature' => array (
                                    'arguments' => array (
                                        'data' => array (
                                            'config' => array (
                                                'label' => 'Feature the second',
                                                'dataScope' => 'second_feature',
                                                'componentType' => 'field',
                                                'dataType' => 'text',
                                                'formElement' => 'checkbox',
                                                'valueMap' => array (
                                                    'true' => '1',
                                                    'false' => '0',
                                                ),
                                                'sortOrder' => 20,
                                            ),
                                        ),
                                    ),
                                ),
                            ),
                        ),
                    ),
                ),
            ),
        );

        return $meta;
    }

}

I suspect that the problem is that I do not know what values to use for the component's dataType or formElement in the config array, so I do not have these values configured.
Where are the dataType, formElement, and other config array keys documented? I see no mention of them in the fine manual. Furthermore, is this in fact the problem? What else might be?


text:
Q: Bash/Sed - multiline sed operation printing lines out of order I am having some trouble with using sed to edit a log file.  I have built it into a function which is supposed to replace the text between two search strings with the output from another function.  It is almost working correctly, but is printing the lines to the log file out of order.  For the life of me I can't figure out why, and most adjustments I have made while trying to fix it have actually had less desirable results.
My sed function:
log_edit(){
"$3" > temp.txt
sed -i -n "/$1/{
:loop
n
/$2/!b loop
x
r temp.txt
G
s/$2/\n\n&/
}
p" "$FILE"
rm temp.txt
}

I am using the "=== text ===" dividers as my start and stop strings to pass along to the function, and using the same functions that built the log in the first place to fill the temporary text file.
The problem is occurring somewhere near/related to the 'G' command.  Rather than appending the hold pattern line to the end of the string, it appears to be attaching it to the beginning of the string.
Original log sample/Desired output:
=== Metech ITAMS Log ===

Metech Recycling
ITAMS Hardware Report
Date: Thu Mar  2 08:01:38 PST 2017
Tech: SP

=== Manufacturer Information ===

# dmidecode 2.12
...

Unfortunately, the output I am getting looks like this:
=== Manufacturer Information ===

=== Metech ITAMS Log ===

Metech Recycling
ITAMS Hardware Report
Date: Fri Mar  3 09:39:02 PST 2017
Tech: SS

# dmidecode 2.12
...

Would someone be able to help me understand what I'm doing wrong, or propose a fix?  This is my first question ever to SO, if more information is necessary I am happy to provide it.  Thanks in advance.
Edit #1: As requested a snippet of the code that calls the function:
        2)
            printf "\n"
            text_prompt "Please enter Tech initials: "
            set_tech_id
            text_prompt "Please enter Traveler ID: "
            set_travel_id
            mv "$FILE" "$TRAVEL_ID $TECH_INITIALS"
            FILE="$TRAVEL_ID $TECH_INITIALS"
            log_edit "=== Metech ITAMS Log ===" \
"=== Manufacturer Information ===" "print_header"
            unset TECH_INITIALS
            unset TRAVEL_ID
        ;;

This is part of a menu function, and it would be overkill to include the whole thing, just be aware that there will be several calls to log_edit with different start/stop strings (though all follow the === === pattern), but usually calling different functions to fill the temp.txt with.
Edit 2: For added clarity, I thought I should add the function being called with $3:
print_header(){ #Prints log header.
print_div "Metech ITAMS Log"
printf "Metech Recycling\nITAMS Hardware Report\nDate: $(date)\nTech: %s\n" \
"$TECH_INITIALS"
}

and print_header calls print_div:
print_div(){ #Prints a divider.  Required parameter: $1=Text for divider.
printf "\n=== %s ===\n\n" "$1"
}

Edit 3:  For question clarity, my issue is that the $2 string is being written to the log before the contents of temp.txt, rather then after.
Final Edit: A solution was found.  I thought I would post the working code below just in case it's helpful to others.  A big portion of my problem was a misunderstanding with how sed uses the 'r' command.  There's another part to this solution that came from the accepted answer that I still don't understand, and that is the substitute commands that add backslashes, this was key to making it work.  I don't know why it works, but it does.
log_edit() { #Works!!
"$3" > temp.txt
sed -i -n '/^'"$1"'$/ {
:loop
n
/^'"$2"'$/!b loop
i\
'"$(sed 's/\\/\\&/g;s/$/\\/' -- "temp.txt")"'

#Blank line terminates i command.
}
p' "$FILE"
rm temp.txt
}

A: The r command copies out the file before the next read, not when it is evaluated, and does not modify pattern-space.  However the file can be inserted into the script as part of an i command:
log_edit() {
    sed -n '/^'"$1"'$/ {
        p
        :loop
        n
        /^'"$2"'$/!bloop
        i\
'"$("$3" | sed 's/^[[:space:]]/\\&/;s/\\/\\&/g;s/$/\\/')"'

        # The blank line above is part of the `i' command,
        # and appends a newline to the inserted text.
    }
    p' "$FILE" > "$FILE.mod" && mv -f -- "$FILE.mod" "$FILE"
}

The command-substitution "$("$3" | sed '...')" filters the output
of $3 for use with sed's i command.  The i command prints
a series of lines will all but the last ending with a \.
$ echo three | sed 'i\
> one\
> two
> '
one
two
three

A: Looks like just a few things out of order there. Try this:
log_edit(){
"$3" > text.tmp
sed -i -n "/$1/{
r text.tmp
:loop
N
/$2/!b loop
s/.*\n/\n\n/g
}
p
" "$FILE"
rm text.tmp
}

print_header(){ #Prints log header.
    print_div "Metech ITAMS Log"
    printf "Metech Recycling\nITAMS Hardware Report\nDate: $(date)\nTech:%s" "$TECH_INITIALS"
}

print_div(){ #Prints a divider.  Required parameter: $1=Text for divider.
    printf "\n=== %s ===\n\n" "$1"
}

log_edit "=== Metech ITAMS Log ===" "=== Manufacturer Information ===" "print_header"

A: Try the csplit program, which can divide a file up into sections according to a pattern:
csplit $3 "/\($1\|$2\)/" "{*}"

This means take file $3, and break it into files xxNN (where NN starts at 00 and goes up) according to sections demarcated by an unlimited number ({*}) of patterns $1 OR $2 (two alternate patterns, separated by \| and grouped by escaped parentheses). The demarcation lines will remain in the output.  You can then write ancillary code to delete the files you don't want.  You can also change the name of the output filename and pattern.
# cat foo
a
b
@
c
d
%
e
f
@
g
h
%
i
j
# csplit foo '/\(@\|%\)/' '{*}'
4
6
6
6
6
# more xx0*
::::::::::::::
xx00
::::::::::::::
a
b
::::::::::::::
xx01
::::::::::::::
@
c
d
::::::::::::::
xx02
::::::::::::::
%
e
f
::::::::::::::
xx03
::::::::::::::
@
g
h
::::::::::::::
xx04
::::::::::::::
%
i
j

Note: You'll need to tweak it if your demarcation lines can repeat/occur out of order.  This is very simple; the breaks occur at any point that one pattern OR the other is seen, regardless of order.


text:
Q: Extension of cocountable sigma algebra with the counting measure.
Let $(X,v,S_0)$ a measure space and define $$\mu^*(E)=\inf\{\sum_nv(A_n):A_n \in S_0,E \subseteq \bigcup_nA_n\}$$
It is easy to see that $\mu^*$ is an outer measure and is called $\textbf{the outer measure induced by}$ $v$.
Also again it is not difficult to prove that $\mu^*(E)=\min\{v(A):A \supseteq E\}$
We denote $\Sigma_{\mu^*}$ the Caratheodory sigma algebra of $\mu^*-$measurable sets.
Now with some work it is proved that if $\mu$ (the restriction of $\mu^*$ to $\Sigma_{\mu^*}$) is sigma finite then $(X,\Sigma_{\mu^*},\mu)$ is the completion of $(X,v,S_0)$

Now assume that $X$ is an uncountable set and  $S_0=\{A \subseteq X: \text{$A$ is countable or $A^c$ is countable}\}$ and $v=$counting measure $|A|$
$X$ is not sigma finite with respect to this measure since it is uncountable.
I want to prove that $\Sigma_{\mu^*}=P(X)$ where $m^*$ is the outer measure induced by the counting measure.
Here is my work:
Clearly $(X,|\cdot|,S_0)$ is a measure space.
Now let $A \subseteq X$ and $E \subseteq X$
We always have the inequality $\mu^*(E)\leq \mu^*(E \cap A)+\mu^*(E \cap A^c)$
So if $E$ is infinite exists $B \in S_0$ such that $B \supset E$ and  $+\infty=|B|=\mu^*(E) \leq\mu^*(E)\leq \mu^*(E \cap A)+\mu^*(E \cap A^c)$
Thus the equality is satisfied with like this: $+\infty=+\infty$
Now assume that $E$ is finite.
Then  $$\mu^*(E)=|E|=|E\cap A|+|E \cap A^c| = \mu(A \cap E)+\mu(E \cap A^c)=\mu^*(A \cap E)+\mu^*(E \cap A^c)$$
since $E,A \cap E,A^c \cap E$ are finite sets so belong to $S_0$.
In every case the desired equality is satisfied,thus $\Sigma_{\mu^*}=P(X)$
Is this correct,or am i missing something?
Thank you in advance.

A: If $X$ is uncountable then the counting measure $\nu$ on the collection of countable and cocountable sets is not $\sigma$-finite so that identification with completion is not okay here.
Anyway, a counting measure is always complete (already). This because its only null-set is the empty set (which belongs to every $\sigma$-algebra).

edit:
Any outer measure $\mu^*$ on a set $X$ is a function on $\wp(X)$ with special properties and induces a complete measure on a $\sigma$-algebra $\Sigma_{\mu^*}$.
This complete measure is then $\mu^*$ itself but restricted to this $\sigma$-algebra and $A$ is an element of $\Sigma_{\mu^*}$ iff:$$\forall E\in\wp(X)\;[\mu^*(E)=\mu^*(E\cap A)+\mu^*(E\cap A^{\complement})]\tag1$$
If we observe that $\mu^*$ is already a measure itself on $\sigma$-algebra $\wp(X)$ then from that we can draw the immediate conclusion that $(1)$ is satisfied for all $A\in\wp(X)$ so that  $\Sigma_{\mu^*}=\wp(X)$ and the complete measure induced by $\mu^*$ is just $\mu^*$ itself.
You are in that situation here because it is easy to verify that the map that sends finite sets to their cardinality and sends infinite sets to $+\infty$ is indeed a measure on $\wp(X)$.
So your proof (which is okay) is a bit redundant.


text:
Q: Find the intersection between a linear equation and a quadratic equation, where the linear equation is x, not y What the title says essentially. Where one is x=0.6(y-4)^2+4 and another is x=15
The confusing part for me is that it is x=15, there is no y. There are a lot of help for y=?, but x=?
NEVERMIND, I figured out how to do it. Sorry guys ;)
I am guessing I need to sub in 15 into the equation, then solve for y

A: You would need to sub in 15 to the equation x=0.6(y-4)^2+4
That will give you the two y values in which the line intersects with the quadratic.


text:
Q: Регулярные выражения Python вернуть true если слово не начинается на цифру, и в слове встречается больше 5 цифр подряд Регулярные выражения Python вернуть false если слово не начинается на цифру, и в слове встречается больше 5 цифр подряд
примеры слов:
19181920flupandemic
covid19
blackdeath
coronavirus
italy
covid1920
pandemic
sarscov2
2009flupandemic
2020coronaviruspandemicinitaly
Из списка должны остаться:
covid19
blackdeath
coronavirus
italy
pandemic
sarscov2
Нашла (^\d\w.*$)
Но как применить не знаю
text = ['19181920flupandemic','covid19','blackdeath','coronavirus','italy','covid1920','pandemic','sarscov2','2009flupandemic','2020coronaviruspandemicinitaly']
text2 = []
for i in range(len(text)):

    if len(str(text[i])) <= 15:#слово короче 15 символов

        if str(text[i]) and #здесь хочу вставить условия регулярных выражений
             text2.append(str(text[i]))

A: Попробуйте так:
import re

text = ['19181920flupandemic','covid19','blackdeath','coronavirus','italy','covid1920','pandemic','sarscov2','2009flupandemic','2020coronaviruspandemicinitaly']

r = re.findall(r'^\D+\d{0,5}', text[1]) #Вместо text[1] подставляете любую строку

print(r)

A: Мой вариант (за образец взят предыдущий ответ от Alioshca Z)
text = ['19181920flupandemic','covid19','blackdeath','coronavirus','italy','covid1920','pandemic','sarscov2','2009flupandemic','2020coronaviruspandemicinitaly']

text2 = []

for items in text:
    if (re.findall(r'^\D', items)) and not (re.findall(r'\d{6,}', items)):
        text2.append(items)

print(text2)

Результат:
['covid19', 'blackdeath', 'coronavirus', 'italy', 'covid1920', 'pandemic', 'sarscov2']
Примечание: в представленном вами входящем списке нет строки, которая отвечает обоим условиям из заголовка (т.е. не начинается с цифры и содержит больше 5 цифр подряд). В вашем примере выходных данных цифр как раз должно быть от 0 до 5.
Вторая часть регулярного выражения может выглядеть как-то так – not (re.findall(r'\d{6,}', items)
т.е. не 6 и более цифр подряд.
Предложенный ранее вариант пропускает строки, где число цифр подряд больше 6 (тестовый пример 'sarscov23456789').
r = re.findall(r'^\D+\d{0,5}', "sarscov23456789")
print(r)

вывод ['sarscov23456']
Примите это во внимание, если к вам в список попадают не только указанные ранее строки.

A: Вроде вот такое должно подойти:
^(?!(?!\d).*\d{5})

Если надо всё-таки true, то внешние отрицание удалить.


text:
Q: What are the useful utility classes in java? There are some utility classes which can be useful in day to day development.
I know couple of such utility classes as below.

*

*Word Utils

*StringUtils
Both of these are basically from Apache commons library. Are there any other libraries or any such utility classes?

A: I think FileUtils & NumberUtils useful.Hope helps.


text:
Q: set_model() missing 1 required positional argument: 'model' I'm have created a Keras Sequential Model and am using Adam optimizer. I wished to get the learning rate after every epoch. This stackoverflow question seem to answer my question. However, when I followed the solution mentioned, I get the following error
set_model() missing 1 required positional argument: 'model'

Here's my code to create a model:
model = Sequential()

model.add(Conv2D(64, (5, 5), input_shape=(IMG_HEIGHT, IMG_WIDTH, 3), activation='relu'))

model.add(Conv2D(64, (5, 5), activation='relu'))
model.add(MaxPooling2D((2, 2)))
model.add(Dropout(0.2))

model.add(Conv2D(128, (5, 5), activation='relu'))
model.add(Conv2D(128, (5, 5), activation='relu'))
model.add(MaxPooling2D((2, 2)))
model.add(Dropout(0.2))

model.add(Conv2D(256, (5, 5), activation='relu'))
model.add(Conv2D(256, (5, 5), activation='relu'))
model.add(MaxPooling2D((2, 2)))
model.add(BatchNormalization(axis=3))
model.add(Dropout(0.2))

model.add(Flatten())
model.add(Dense(256, activation='relu'))

model.add(Dropout(0.5))

model.add(Dense(256, activation='relu'))

model.add(Dropout(0.5))
model.add(Dense(10, activation='softmax'))

model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])

learning_rate_reduction = ReduceLROnPlateau(monitor='val_acc',
                                            patience=3,
                                            verbose=1,
                                            factor=0.4,
                                            min_lr=0.0001)
csvlogger = CSVLogger("solution.csv", separator='\t')
checkpoint = ModelCheckpoint("models/best_model5.h5", monitor="val_acc", save_best_only=True, mode='max')
learning_rate_reduction = ReduceLROnPlateau(monitor='val_acc',
                                            patience=3,
                                            verbose=1,
                                            factor=0.4,
                                            min_lr=0.00001)

class MyCallback(keras.callbacks.Callback):
    def on_epoch_end(self, epoch, logs=None):
        lr = self.model.optimizer.lr
        decay = self.model.optimizer.decay
        iterations = self.model.optimizer.iterations
        lr_with_decay = lr / (1. + decay * K.cast(iterations, K.dtype(decay)))
        print(K.eval(lr_with_decay))

model.fit_generator(datagen.flow(x_train, y_train, batch_size=75),
                           epochs=10, validation_data=(x_validation, y_test),verbose=1,
                           steps_per_epoch=x_train.shape[0], callbacks=[csvlogger, checkpoint, MyCallback])

How do I get past this error "set_model() missing 1 required positional argument: 'model'
"
Below is the stack trace
TypeError                                 Traceback (most recent call last)
<ipython-input-12-1826a19039cd> in <module>()
    128 model.fit_generator(datagen.flow(x_train, y_train, batch_size=75),
    129                            epochs=10, validation_data=(x_validation, y_test),verbose=1,
--> 130                            steps_per_epoch=x_train.shape[0], callbacks=[csvlogger, checkpoint, MyCallback])
    131 model.save('trained_model5.h5')
    132

/usr/local/lib/python3.6/dist-packages/keras/legacy/interfaces.py in wrapper(*args, **kwargs)
     89                 warnings.warn('Update your `' + object_name +
     90                               '` call to the Keras 2 API: ' + signature, stacklevel=2)
---> 91             return func(*args, **kwargs)
     92         wrapper._original_function = func
     93         return wrapper

/usr/local/lib/python3.6/dist-packages/keras/models.py in fit_generator(self, generator, steps_per_epoch, epochs, verbose, callbacks, validation_data, validation_steps, class_weight, max_queue_size, workers, use_multiprocessing, shuffle, initial_epoch)
   1274                                         use_multiprocessing=use_multiprocessing,
   1275                                         shuffle=shuffle,
-> 1276                                         initial_epoch=initial_epoch)
   1277
   1278     @interfaces.legacy_generator_methods_support

/usr/local/lib/python3.6/dist-packages/keras/legacy/interfaces.py in wrapper(*args, **kwargs)
     89                 warnings.warn('Update your `' + object_name +
     90                               '` call to the Keras 2 API: ' + signature, stacklevel=2)
---> 91             return func(*args, **kwargs)
     92         wrapper._original_function = func
     93         return wrapper

/usr/local/lib/python3.6/dist-packages/keras/engine/training.py in fit_generator(self, generator, steps_per_epoch, epochs, verbose, callbacks, validation_data, validation_steps, class_weight, max_queue_size, workers, use_multiprocessing, shuffle, initial_epoch)
   2131         else:
   2132             callback_model = self
-> 2133         callbacks.set_model(callback_model)
   2134         callbacks.set_params({
   2135             'epochs': epochs,

/usr/local/lib/python3.6/dist-packages/keras/callbacks.py in set_model(self, model)
     50     def set_model(self, model):
     51         for callback in self.callbacks:
---> 52             callback.set_model(model)
     53
     54     def on_epoch_begin(self, epoch, logs=None):

TypeError: set_model() missing 1 required positional argument: 'model'

Also, another question that I have is, whether the above solution is correct.This tensorflow link about Adam Optimizer suggests learning rate to be calculated as:

lr_t <- learning_rate * sqrt(1 - beta2^t) / (1 - beta1^t)

This seems quite different from the solution that is mentioned in the other link. Did I miss something?

A: The error means you are not providing a value for the argument at position 1 (starting at 0) which is called "model". The caller is Tensorflow itself, so the fault is most likely not there.
This error suggests that you are calling the static method rather than the method on the object, thus passing only 1 argument instead of 2. That is because when you call a method on an object, the object as passed as the first argument and "model" will be passed as the second argument.
In short, your mistake is that your callback is a "class" and not an "object". Make sure you are providing an instance of your callback class and not the class itself.
Like this (notice the brackets after "MyCallback"):
model.fit_generator(datagen.flow(x_train, y_train, batch_size=75),
                           epochs=10, validation_data=(x_validation, y_test),verbose=1,
                           steps_per_epoch=x_train.shape[0], callbacks=[csvlogger,
                           checkpoint, MyCallback()])

A: Actually, in the model.fit_generator method's callbacks parameter, you are passing the class instead of an object of that class.
It should be
my_calback_object = MyCallback() # create an object of the MyCallback class

model.fit_generator(datagen.flow(x_train, y_train, batch_size=75),
                    epochs=10, validation_data=(x_validation, y_test),
                    verbose=1, steps_per_epoch=x_train.shape[0],
                    callbacks=[csvlogger, checkpoint, my_callback_object])

A: This is more of a comment, it just did not fit.
It is quite strange. The default implementation of set_model that MyCallback inherits is:
def set_model(self, model):
    self.model = model

and this is exactly how it is being called by according to the stack trace:
/usr/local/lib/python3.6/dist-packages/keras/callbacks.py in set_model(self, model)
     50     def set_model(self, model):
     51         for callback in self.callbacks:
---> 52             callback.set_model(model)

My only guess at this point is that there is some version mismatch on your system. You might have some old .pyc lying around as well. I would try to debug this by editing /usr/local/lib/python3.6/dist-packages/keras/callbacks.py directly. For example, add a print statement before line 52 to make sure this code really runs. Then, drop into pdb (add import pdb; pdb.set_trace) and check why it is complaining. It is a basic python question at this point.


text:
Q: Reassigning Colour from Integer Value (args) Hi I have managed to store the colour into a database table as an arg type integer. But now I am not sure how I turn that back into a colour so I can use it.
mCatButList[i].BackColour = Color.FromArgb((int)CatRow[8]);

Tried this and I am just getting grey. When the value in CatRow[8] is 8421631.

A: BackColor = Color.FromArgb(147, 230, 203); // which is  the teal color

and then you convert it to  int
int backColor = BackColor.ToArgb();

you will  get a signed value like this -7084341  // which is a negative number
last try to be sure that your database accept a signed integer


text:
Q: JavaFX: Anchor Pane constraints inside a tab I have a JavaFX application with multiple fxml files, with a MainPanel set up like this:
 <?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.control.Tab?>
<?import javafx.scene.control.TabPane?>
<?import javafx.scene.layout.AnchorPane?>
<?import java.net.URL?>

<AnchorPane xmlns="http://javafx.com/javafx/8.0.111" xmlns:fx="http://javafx.com/fxml/1" fx:controller="MainPanelController">
   <children>
      <TabPane fx:id="mainTabPane" prefHeight="570.0" prefWidth="880.0" tabClosingPolicy="UNAVAILABLE" tabMaxHeight="20.0" tabMaxWidth="3520.0" tabMinHeight="20.0" tabMinWidth="50.0" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0">
            <tabs>
                <Tab fx:id="tab1" text="Tab 1" />
                <Tab fx:id="tab2" text="Tab 2" />
                <Tab fx:id="tab3" text="Tab 3" />
                <Tab fx:id="tab4" text="Tab 4" />
                <Tab fx:id="tab5" text="Tab 5" />
                <Tab fx:id="tab6" text="Tab 6" />
                <Tab fx:id="tab7" text="Tab 7" />
            </tabs>
        </TabPane>
   </children>
</AnchorPane>

The process goes like this:

*

*The application is launched by:
Parent root = FXMLLoader.load(getClass().getResource("Login.fxml"));
primaryStage.setScene(new Scene(root, 880, 570));
primaryStage.setTitle("Login");
primaryStage.show();

With the Login fxml being:
 <?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.control.Button?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.control.PasswordField?>
<?import javafx.scene.control.TextField?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.layout.VBox?>
<?import javafx.scene.text.Font?>

<AnchorPane fx:id="mainAnchorPane" prefHeight="550.0" prefWidth="880.0" xmlns="http://javafx.com/javafx/8.0.111" xmlns:fx="http://javafx.com/fxml/1" fx:controller="LoginController">
   <children>
      <VBox layoutX="340.0" layoutY="186.0" spacing="5.0" AnchorPane.bottomAnchor="186.0" AnchorPane.leftAnchor="340.0" AnchorPane.rightAnchor="340.0" AnchorPane.topAnchor="186.0">
         <children>

              <TextField fx:id="userField" prefHeight="30.0" prefWidth="200.0" />
              <PasswordField fx:id="passwordField" prefHeight="30.0" prefWidth="200.0" />
              <Button fx:id="loginButton" mnemonicParsing="false" onAction="#login" prefHeight="30.0" prefWidth="200.0" text="Login">

              </Button>
         </children>
      </VBox>

   </children>
</AnchorPane>

*The user clicks the login button, the MainPanel is loaded like this:
Node mainNode = FXMLLoader.load(Login.class.getResource(fxmlPath));
mainAnchorPane.getChildren().setAll(mainNode);

*The MainPanel Controller then loads each individual fxml into each tab in a similar way. I've tried something like this:
tab1.setContent(loadedNode);

And this:
tab1AnchorPane.getChildren().setAll(tab1Node);

I've tried having the Tab with no children and just loading into it. I've tried having an AnchorPane inside the tab. I've tried a combination of HBoxes/VBoxes with AnchorPanes, with no success.
The AnchorPane constraints work if I load the fxml file individually. However, when I try to load it into a tab, it doesn't work.
Here's an fxml which works if loaded separately, and doesn't when loaded into a tab:
<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.geometry.Insets?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.TableColumn?>
<?import javafx.scene.control.TableView?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.layout.HBox?>
<?import javafx.scene.layout.VBox?>

<AnchorPane fx:id="tab1AnchorPane" prefHeight="550.0" prefWidth="880.0" xmlns="http://javafx.com/javafx/8.0.111" xmlns:fx="http://javafx.com/fxml/1" fx:controller="Tab1Controller">
    <children>
        <VBox prefHeight="550.0" prefWidth="880.0" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0">
            <children>
                <TableView fx:id="table" editable="true" prefHeight="450.0" prefWidth="474.0" VBox.vgrow="ALWAYS">
                    <columns>
                        <TableColumn fx:id="column1" prefWidth="75.0" text="Column 1" />
                        <TableColumn fx:id="column2" prefWidth="75.0" text="Column 2" />
                    </columns>
                    <VBox.margin>
                        <Insets bottom="10.0" left="10.0" right="10.0" top="10.0" />
                    </VBox.margin>
                </TableView>
                <HBox alignment="CENTER" prefHeight="30.0" prefWidth="880.0" spacing="50.0" VBox.vgrow="ALWAYS">
                    <children>
                        <VBox spacing="50.0">
                            <children>
                                <Button fx:id="button1" mnemonicParsing="false" onAction="#action1" prefHeight="30.0" prefWidth="150.0" text="Button 1" />
                                <Button fx:id="button2" mnemonicParsing="false" onAction="#action2" prefHeight="30.0" prefWidth="150.0" text="Button 2" />
                            </children>
                        </VBox>
                        <VBox spacing="10.0">
                            <children>
                                <Button fx:id="button3" mnemonicParsing="false" onAction="#action3" prefHeight="30.0" prefWidth="150.0" text="Button 3" />
                                <Button fx:id="button4" mnemonicParsing="false" onAction="#action4" prefHeight="30.0" prefWidth="150.0" text="Button 4" />
                                <Button fx:id="button5" mnemonicParsing="false" onAction="#action5" prefHeight="30.0" prefWidth="150.0" text="Button 5" />
                            </children>
                        </VBox>
                        <VBox spacing="10.0">
                            <children>
                                <Button fx:id="button6" mnemonicParsing="false" onAction="#action6" prefHeight="30.0" prefWidth="150.0" text="Button 6" />
                                <Button fx:id="button7" mnemonicParsing="false" onAction="#action7" prefHeight="30.0" prefWidth="150.0" text="Button 7" />
                                <Button fx:id="button8" mnemonicParsing="false" onAction="#action8" prefHeight="30.0" prefWidth="150.0" text="Button 8" />
                            </children>
                        </VBox>
                        <VBox spacing="50.0">
                            <children>
                                <Button fx:id="button9" maxWidth="150.0" mnemonicParsing="false" onAction="#" prefHeight="30.0" text="Button 9" />
                                <Button fx:id="button10" mnemonicParsing="false" onAction="#action9" prefHeight="30.0" prefWidth="150.0" text="Button 10" />
                            </children>
                        </VBox>
                    </children>
                    <VBox.margin>
                        <Insets bottom="20.0" left="10.0" right="10.0" top="10.0" />
                    </VBox.margin>
                </HBox>
            </children>
        </VBox>
    </children>
</AnchorPane>

Not even the TabPane inside the MainPanel resizes properly. What am I doing wrong here? I'm feeling a bit lost.

A: I got also similar situation you mentioned.
When some node is added on root pane loaded by fxml, root pane dosen't resized corresponding with stage at all. (I suspect it may bug on JavaFx.)
So I add listener on stage's widthProperty (or heightProperty) to resize stage's root pane simultaneously.
    Scene      scene = stage.getScene();
    AnchorPane root  = (AnchorPane) scene.getRoot();
    scene.widthProperty().addListener( ( observable, oldValue, newValue ) -> root.setPrefWidth( newValue.doubleValue() ) );
    scene.heightProperty().addListener( ( observable, oldValue, newValue ) -> root.setPrefHeight( newValue.doubleValue() ) );


text:
Q: How to find sum of other categories in the data in R? I have a panel data, sampled monthly for various product types.
type year month cost
 A   2020  01     3
 A   2020  02     6
 B   2020  01     7
 B   2020  02     9
 C   2020  01     10
 C   2020  02     15

I need to calculate an additional variable stating: "For a given period, what is the sum of costs from other product types?"
For example,

*

*For 2020-01, Total Cost = 3 + 7 + 10 = 20. Costs of non-A types are 20 - 3 = 17.

*For 2020-02, Total Cost = 6 + 9 + 15 = 30. Costs of non-B types are 30 - 9 = 21.

So the final data frame should look like this:
type year month cost other_costs
 A   2020  01     3      17
 A   2020  02     6      24
 B   2020  01     7      13
 B   2020  02     9      21
 C   2020  01     10     10
 C   2020  02     15     15

I have tried group_by() + mutate() functions from dplyr, but I get NA with the following code:
df %>%
 group_by(year, month) %>%
 mutate(other_costs = sum(cost) - cost)

What are your suggestions?


text:
Q: PL SQL Inserting Parameters into String I am trying to insert a new row into a table in my database. I am having issues with the MODPLSQL_PROCEDURE_NAME field below.
DECLARE
    lId VARCHAR2(20);
BEGIN
    lId := 'XLRP' || SEQ.NEXTVAL;
END;

INSERT INTO REPORTS(CATEGORY_ID,
                             DESCRIPTION,
                             ID,
                             MODPLSQL_PACKAGE_NAME,
                             MODPLSQL_PROCEDURE_NAME,
                             NOTES)
            VALUES          ('XLRC0',
                             'Training Task XL Report',
                             'XLRP' || WORKFLOW_REPORTS_SEQ.NEXTVAL,
                             '!MODPLSQL_XL_REPORTS_PKG',
                             'XL_REPORT?pReportId=' || lId || '&' || 'pReportName=Training Task XL Report' || '&' || 'pPackageName=TRAINING_PKG' || '&' || 'pProcedureName=RUN_NOW',
                             NULL);

My desired output for the field is shown below (Example lId = XLRP100):
XL_REPORT?pReportId=XLRP100&pReportName=Training Task XL Report&pPackageName=TRAINING_PKG&pProcedureName=RUN_NOW

In the MODPLSQL_PROCEDURE_NAME I need to import a seq generated ID lId from the statement above. Can anyone advise me on the correct syntax to do this?
Additionally, I have broken up my string with &'s in order to avoid a box popping up requesting me to input paramters, 'set define off' does not change this. Is there a better way of writing this?

A: If you want to use the value of lId in your INSERT statement, the easiest way is to move it into your PL/SQL block, for example:
DECLARE
    lId VARCHAR2(20);
BEGIN
    lId := 'XLRP' || SEQ.NEXTVAL;

    INSERT INTO REPORTS(CATEGORY_ID,
                             DESCRIPTION,
                             ID,
                             MODPLSQL_PACKAGE_NAME,
                             MODPLSQL_PROCEDURE_NAME,
                             NOTES)
            VALUES          ('XLRC0',
                             'Training Task XL Report',
                             lId,
                             '!MODPLSQL_XL_REPORTS_PKG',
                             'XL_REPORT?pReportId=' || lId || '&' || 'pReportName=Training Task XL Report' || '&' || 'pPackageName=TRAINING_PKG' || '&' || 'pProcedureName=RUN_NOW',
                             NULL);

END;

Secondly, if you want to avoid any problems with the & character, you can use CHR(38) instead.
                             'XL_REPORT?pReportId=' || lId || CHR(38) || 'pReportName=Training Task XL Report' || CHR(38) || 'pPackageName=TRAINING_PKG' || CHR(38) || 'pProcedureName=RUN_NOW',


text:
Q: Error using Tikz matrix inside of subfloat
Possible Duplicate:
Problem with defining shortcuts for TikZ matrices.

I'm getting a the following error using subfloat and tikz matrix together:
ERROR: Package pgfbasematrix Error: Single ampersand used with wrong catcode.
Commenting out the subfloat lines results in no errors. Thanks in advance for any suggestions.
\documentclass{article}
%% For drawing
\usepackage{tikz}
\usetikzlibrary{arrows,positioning}

%% For subfloat
\usepackage{subfig}

%% Drawing
\def\linkaba{stealth'-stealth'}
\def\linkab{-stealth'}
\def\linkba{stealth'-}
\newcommand{\directedtriangle}[4]{
  \node (A) at (0,0) [nd] {}; % Lower Left
  \node (B) at +(1,0) [nd] {}; % Lower Right
  \node (C) at +(0.5,0.75) [nd] {}; % Top
  \draw[#1] (A)--(B);
  \draw[#2] (A)--(C);
  \draw[#3] (B)--(C);
  \node [below] at +(0.5,-0.1) {\footnotesize (#4)};
}
\newcommand{\directedwedge}[3]{
  \node (A) at (0,0) [nd] {}; % Lower Left
  \node (B) at +(1,0) [nd] {}; % Lower Right
  \node (C) at +(0.5,0.75) [nd] {}; % Top
  \draw[#1] (A)--(C);
  \draw[#2] (B)--(C);
  \node [below] at +(0.5,-0.1) {\footnotesize (#3)};
}

\begin{document}
\begin{figure}[t]
\subfloat[Wedges]{
  \begin{tikzpicture}[nd/.style={circle,draw,fill=black!50,inner sep=2pt}]
    \matrix[column sep=0.4cm, row sep=0cm]
    {
      \directedwedge{\linkba}{\linkba}{i} &
      \directedwedge{\linkab}{\linkba}{ii} &
      \directedwedge{\linkab}{\linkab}{iii} \\
      \directedwedge{\linkaba}{\linkab}{iv} &
      \directedwedge{\linkaba}{\linkba}{v} &
      \directedwedge{\linkaba}{\linkaba}{vi} \\
    };
  \end{tikzpicture}}

\subfloat[Triangles]{
  \begin{tikzpicture}[nd/.style={circle,draw,fill=black!50,inner sep=2pt}]
    \matrix[column sep=0.4cm, row sep=0cm]
    {
      \directedtriangle{\linkab}{\linkba}{\linkba}{a} &
      \directedtriangle{\linkab}{\linkba}{\linkab}{b} &
      \directedtriangle{\linkaba}{\linkba}{\linkba}{c} &
      \directedtriangle{\linkaba}{\linkab}{\linkba}{d} \\
      \directedtriangle{\linkaba}{\linkab}{\linkab}{e} &
      \directedtriangle{\linkaba}{\linkaba}{\linkba}{f} &
      \directedtriangle{\linkaba}{\linkaba}{\linkaba}{g}\\
    };
  \end{tikzpicture}}
  \vspace{-0.5cm}
  \caption{All different directed wedges and triangles}
  \label{fig:dwedge}
\end{figure}

\end{document}


text:
Q: Traverse graph and return class instances created by recursively calling node with children for arguments Have a graph mapping class types to a list of their arguments. How do I return the roots instantiated with their ancestors for arguments? (Apologies for what is probably a terrible description of my problem). Consider the following:
graph = {Foo: [42], Baz: [None], Bar: [Baz], FooBar: [Foo, Bar], Qux: [True]}

For roots returned by set(graph).difference(chain.from_iterable(graph.values())), I expect two values, qux and foobar, created like the following:
qux = Qux(True)
foobar = FooBar(Foo(42), Bar(Baz(None)))

Here is additional code to reproduce the example:
from itertools import chain

class Node:
    name = None
    def __init__(self, *args):
        self.args = args

class FooBar(Node):
    name = 'foobar'

class Foo(Node):
    name = 'foo'
    parent = FooBar

class Bar(Node):
    name = 'bar'
    parent = FooBar

class Baz(Node):
    name = 'baz'
    parent = Bar

class Qux(Node):
    name = 'qux'

Thank you in advance.

A: You could use this recursive function:
def get_inst (graph, arg):
    val = graph[arg]

    return arg(*(el if type(el) != type else get_inst (graph, el) for el in val))

Sample usage of this function:
roots = set(graph).difference(chain.from_iterable(graph.values()))

for root in roots:
    val = get_inst(graph, root)


text:
Q: Projection in JPQL with property of type list How I can made a select of a property of type list on JPQL?
example:
@Entity
public class Person {

    @id
    private Long id;
    private String name;
    private String lastname;
    private String birthdate;
    @OneToMany
    private List<Phone> getPhones();

    ...
}

@Entity
public class Phone {

    @id
    private Long id;
    private String number;

    ...
}

And on repository I want a projection, so:
public interface IPersonProjection {

    Long getId();
    String getName();
    List<Phone> phones();
}

@Repository
public interface IAtendimentoRepository extends JpaRepository<Atendimento, Long> {

    @Query("SELECT P.id, P.name, P.phones FROM Person P ")
    List<IPersonProjection> findAllProjected();
}

But when I try this (SELECT P.id, P.name, P.phones FROM Person P) occur an error on syntax of SQL.

A: As specified in Spring Data Docs, you should have accessors of your properties in your Projection Interface. So i think you should change the name of phones method of IPersonProjection to getPhones.


text:
Q: Produce repeated left to right movement on sprite without going off screen Recently, a friend sent a basketball game through FB Messenger and I thought it was a pretty cool game. I wanted to recreate it just for fun.
You swipe to "shoot" the ball into the goal. Simple. The goal is stationary from scores 1-10. Moves left to right from scores 11-20. Moves left to right a little faster from scores 21-30. Another friend says that the goal zig zags across the screen at score 31. My highest is 22. The ball also moves along the x-axis at the bottom of the screen in five different positions, randomly.
I was able to get the goal to move either left or right but not a repeated action.
I'm using Xcode 7.3 and Swift 2.2. Any help would be appreciated. Just want to make sure I'm going in the right direction.
GameScene.swift
let ball = SKSpriteNode(imageNamed: "basketball")
var gameScore: SKLabelNode!
var score: Int = 0 {

    didSet {
        gameScore.text = "Score: \(score)"
    }
}

override func didMoveToView(view: SKView) {
    /* Setup your scene here */

    self.backgroundColor = SKColor.whiteColor()

    // Sets the game score BUT it is not displaying on the screen.
    gameScore = SKLabelNode(fontNamed: "Chalkduster")
    gameScore.text = "Score: 0"
    gameScore.position = CGPoint(x: 250, y: 500)
    gameScore.horizontalAlignmentMode = .Left
    gameScore.fontSize = 20

    addChild(gameScore)

    score = 0

    // Create Physics Body that borders the bottom of the screen
    let borderBody = SKPhysicsBody(edgeLoopFromRect: self.frame)

    // Set friction to 0
    borderBody.friction = 0

    // Set physicsBody to borderBody
    self.physicsBody = borderBody

    // Add the ball to the scene

    ball.physicsBody = SKPhysicsBody(circleOfRadius: ball.size.width / 2.0)

    ball.physicsBody!.restitution = 0.4
    ball.xScale = 0.2
    ball.yScale = 0.2
    ball.position = CGPoint(x: CGRectGetMidX(self.frame), y: 0)
    ball.name = "ball"
    addChild(ball)

    // Commented out so the goal can be stationary
    // moveGoal()

}

override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?)
{

}

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?)
{
   /* Called when a touch begins */

}

func moveGoal()
{
    let movingGoal = SKSpriteNode(imageNamed: "Goal")

    movingGoal.position = CGPoint(x: CGRectGetMidX(self.frame), y: 525)
    movingGoal.xScale = 0.7
    movingGoal.yScale = 0.7

    movingGoal.runAction(SKAction.moveByX(size.width, y: 0.0, duration: 5.0))

    addChild(movingGoal)

}

func moveBallAlongXAxis()
{

    ball.physicsBody = SKPhysicsBody(circleOfRadius: ball.size.width / 2.0)

    ball.physicsBody!.restitution = 0.4
    ball.xScale = 0.2
    ball.yScale = 0.2
    ball.position = CGPoint(x: CGRectGetMidX(self.frame), y: 25)
    ball.name = "ball"
    addChild(ball)

}

override func update(currentTime: CFTimeInterval)
{

}


text:
Q: SQL Server Database connection Error : "No statement handle available" Error: " I am trying to connect SQL Server database. Here is my code:
from PyQt5.QtSql import QSqlDatabase, QSqlQuery, QSqlQueryModel
from PyQt5.QtWidgets import QTableView, QApplication
import sys

SERVER = '192.19.45.11:1433'
DATABASE = 'insightAccounts'
USERNAME = 'Admin'
PASSWORD = '******'

db = QSqlDatabase.addDatabase('QODBC')
db.setDatabaseName(f'Driver={{SQL SERVER}}; Server={SERVER}; Database={DATABASE}; UID={USERNAME}; PWD={PASSWORD}')
db.open()

def displayData(sqlStatement):
    print('processing query...')
    qry = QSqlQuery(db)
    qry.prepare(sqlStatement)
    qry.exec()

    model = QSqlQueryModel()
    model.setQuery(qry)

    view = QTableView()
    view.setModel(model)
    return view

if __name__ =='__main__':
    app = QApplication(sys.argv)
    SQL_STATEMENT = 'SELECT top 5 * FROM insightAccounts.dbo.insightAccount'
    dataView = displayData(SQL_STATEMENT)
    dataView.show()
    app.exit()
    sys.exit(app.exec_())

Here is the output:
processing query...
QSqlQuery::prepare: database not open
"QODBCResult::exec: No statement handle available"      Error: ""


text:
Q: How is n = 4q + r here?
If it says to divide quotient by 4 , then it should q/4 = r .

A: I don't really like calling it "division". Instead, I would say that every $n\in \Bbb N$ can be represented as one (and only one) of the following: $$\begin{cases} 4q \\ 4q+1 \\ 4q+2 \\ 4q+3\end{cases}$$
that is, there is a $q\in \Bbb N$ and an $r\in\{0,1,2,3\}$ such that $n=4q+r$ for every $n\in\Bbb N$. That is what the question is driving at.
So, instead of calculating $i^n$, it calculates $i^{4q+r}=i^r$ because $i^4=1$, and so because $i^0=1, i^1=i, i^2=-1, i^3=-i$, we can construct that: $$i^n=\begin{cases} 1 &n= 4q \\ i &n=4q+1 \\ -1 &n=4q+2 \\-i & n= 4q+3\end{cases}$$ which is the aim of this question, to generalise $i^n$

A:
When n is divided by 4 , the quotient is q.
Now the value n will be equal to 4q + r.It is easily understandable from the photo now I guess.
Example is :
$i^{135}$ = Here n is divided by 4 .
We are left with 3 as remainder.
Notice , 4q + 3 = 135 where q = 33
I hope it it clear now


text:
Q: How do I center an image vertically within a div that is position:fixed? I've looked through a lot of various vertical centering techniques, but none are working for me - mainly because I'm using a fixed positioned div.

#lightbox {
position:fixed;
top:0;
left:0;
width:100%;
height:100%;
background:#ffffff;
text-align:center;
z-index:4;
display:none;
}

#lightboxImgContainer
{
display:table-cell;
vertical-align:middle;
max-height:100%;
max-width:100%;
text-align:center;
}

#lightbox img {
max-height: 100%;
max-width: 100%;
}

Also, am I the only person that thinks its a joke that vertical alignment isn't as simple as horizontal alignment? I've spent far too much time on this to achieve what should be a simple task.

A: The easiest way is to set it as a background image:
#lightbox {
  background:url(myimage.jpg) no-repeat center center
}

Alternatively, you could use flexbox if you don't need to support IE <= 9
#lightbox {
  display: flex;
}
#lightbox img {
  align-items:  center;
}


text:
Q: Bulma align button at the bottom of a column So I'm having a hard time aligning a button at the bottom of my Bulma's column.

I want the button "Buy" to be at the bottom of the right column (side by side with the button "Hello"). I'm in this situation because my other column content is longer.
So far I tried thoses CSS styles on my button (and none of them helped me):
vertical-align: bottom;

margin-bottom: auto;

position: absolute;
bottom: 0;

Here is my HTML:

I'm a big column

            I'm taller than the column next to me so my column will be bigger, lorem ipsum lorem ipsum lorem ipsum lorem ipsum

"lorem ipsum"

            <button class="button is-fullwidth">Hello</button>

I'm a small column

            I'm a small column, and my button missplaced

"lorem ipsum"

            <button class="button is-fullwidth">BUY</button>

Could you guys help me?
Thanks.

A: Alright, foud the answer : The Bulma column needs to have a few properties (suggested by @ahsan-ullah). Then the button needs to have an auto margin to top.

I'm a big column

            I'm taller than the column next to me so my button will be higher,lorem ipsum lorem ipsum lorem ipsum lorem ipsum

"lorem ipsum"

            <button class="button is-fullwidth">Hello</button>

I'm a small column

            I'm a small column, and my button is well placed

"lorem ipsum"

            <button class="button is-fullwidth">BUY</button>

.item{
    display:flex;
    flex-direction:column;
    justify-content:space-between
  }

.columns button{
    margin-top: auto;
  }

Result :

A: hope it is the answer for you work.

.maindiv{
  width:200px;
  height:180px;
  border:1px solid red;
  display:flex;
  flex-direction:column;
  align-items:center;
  justify-content:space-between
}

.innerdiv{
  display:flex;
  flex-direction:column;
}

button{
  width:150px;
  height:30px;
  color:white;
  background-color:blue;
  border-radius:4px
}

Mana Foutan

  lorem ipsum lorem ispum

    Make it rain!
    <button>Buy</button>

A: You can use inline style margin-top:auto on the column div like this:

I'm a small column

        I'm a small column, and my button missplaced

"lorem ipsum"

        <button class="button is-fullwidth">BUY</button>

Alternately, probably preferably, add it as a custom style to your .css and use it as a class inline.
.css:
.valignbottom{
    margin-top: auto;
}

html:

I'm a small column

        I'm a small column, and my button missplaced

"lorem ipsum"

        <button class="button is-fullwidth">BUY</button>


text:
Q: Trouble with pointer arrays and attempting to resize Before anything, let me say this is for an assignment and I am not allowed to use Vectors.
What I'm attempting to do is resize 2 pointer arrays that contain objects. Array custArray has 3 elements and array gArray has 1. I need to move one specific object from custArray to gArray and remove it from custArray (so they both have 2 elements), so I have created 2 temporary arrays to change, then eventually set to equal custArray and gArray.
void setPreferred(string id, int cSize, int pSize, Customer *custArray, Gold *gArray)
{
   int count = 0;
   Customer *temp1 = new Customer[cSize - 1];
   Gold *temp2 = new Gold[pSize + 1];
   *temp2 = *gArray;
   for(int i = 0; i < cSize; i++)
      {
         if(custArray[i].getID() == id)
            {
               temp2[pSize].setName(custArray[i].getFirstName(), custArray[i].getLastName());
               temp2[pSize].setID(custArray[i].getID());
               temp2[pSize].setTotal(custArray[i].getTotal());
               temp2[pSize].setDiscount(0.5);
               //cout << temp2[1].getName() << " " << temp2[1].getID() << " " << temp2[1].getTotal() << " " << temp2[1].getDiscount() << endl;
            }

         if (custArray[i].getID() != id)
            {
               temp1[count].setName(custArray[i].getFirstName(), custArray[i].getLastName());
               temp1[count].setID(custArray[i].getID());
               temp1[count].setTotal(custArray[i].getTotal());
               count++;
            }
      }
   //cout << temp1[0].getName() << " " << temp1[0].getID() << " " << temp1[0].getTotal() << endl;
   //cout << temp1[1].getName() << " " << temp1[1].getID() << " " << temp1[1].getTotal() << endl;

   delete [] custArray;
   delete [] gArray;

   *custArray = *temp1;
   *gArray = *temp2;
}

The 2 original arrays are defined down in main as
Customer *customerArray = new Customer[customerSize];
Gold *goldArray = new Gold[preferredSize];

Arrays temp1 and temp2 work fine in the function, the cout statements print all the correct information. However, when I try to print in main any members of customerArray[1], it displays the incorrect information and members of goldArray[1] throw a bad_alloc error. I suppose that means there's something wrong with how I delete or reassign the arrays. Any help would be appreciated.

A: You cannot dereference a pointer after it has been deleted.  If you do that, unexpected things may happen.

A: Firstly, *custArray = *temp1 just copies single value, pointed by temp1 and not  the rest (temp1+1, temp1+2, and so on). You have to do assignment in loop to copy array, but semantically you should NOT do this here.
You also delete storage that was pointed by custArray before you try to write to it, which is an UB.
You have on-off error by iterating through array of cSize - 1 objects. Your Customer class is either obviously uncopyable, or you for some reason use getters\setters to copy individual fields instead of copy assignment. Makes me wonder if you even know how struct\class assignment works.
Secondly, custArray is local variable in way how you defined function parameters and you didn't change value outside of function. Passing pointer by reference  Customer *& (or C-style Customer**) would solve this, but it's ugly and makes code complex and error-prone. Reallocation changes memory storage and you have to return pointer to the new storage
I implore you to create class, specialized to work with array of Customer or Gold, or which is better, some generic Array template to work with any element class and implement basic assignment\move\allocation\deallocation logic inside of it. You writing C++ code, not C code, so ban on particular standard language component means you have to learn how implement your own, not just throw away it and pretend that it is an impossibility.

A: In outline this is how your code should look
// note custArray and gArray passed by reference
void setPreferred(string id, int cSize, int pSize, Customer*& custArray, Gold&* gArray)
{
    // allocate the new arrays
    Customer *temp1 = new Customer[cSize - 1];
    Gold *temp2 = new Gold[pSize + 1];

    // code to do the copying from custArray and gArray to temp1 and temp2
    // (you still need to write this)
    ...

    // delete the old arrays
    delete[] custArray;
    delete[] gArray;

    // return the new arrays to the caller
    custArray = temp1;
    gArray = temp2;
}


text:
Q: How can I tell when text is being typed into my Android SearchView on the ActionBar I want to disable certain features of my app while the user is entering text for a search.  The xml for the relevant item in my ActionBar is
<item android:id="@+id/actionbar_search"
    android:orderInCategory="1"
    android:showAsAction="always|withText|collapseActionView"
    android:actionViewClass="android.widget.SearchView"
    android:icon="@drawable/earth_2508858_search_en"
    android:inputType="textPostalAddress" />

and in the corresponding code that I have at present to cater for the search is
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    super.onCreateOptionsMenu(menu);
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.action_menu, menu);

    MenuItem DestinationTxt = menu.findItem(R.id.actionbar_search);
    final SearchView mySearchView = (SearchView)DestinationTxt.getActionView();

    mySearchView.setOnQueryTextListener(new OnQueryTextListener() {
        @Override
        public boolean onQueryTextChange(String newText) { return false; }

        @Override
        public boolean onQueryTextSubmit(String query) {
            //Hide the Keyboard
            imm.hideSoftInputFromWindow(mySearchView.getWindowToken(), 0);
            // CODE TO DO THE SEARCH
            return true;
        }
    });
}

I've browsed the methods on SearchView, but I didn't see anything that would tell me whether it's active or not.  I'm also worried about putting in a boolean state variable to indicate when the text is being typed into the SearchView, in case some behaviour that I haven't catered for occurs (e.g. back button pressed, activity gets suspended), and somehow the state variable gets stale so that the disabled features stay disabled.  So I'm looking for a robust way of doing this, all help appreciated :-).
Update.  An answer below suggests using the interface OnFocusChangeListener which is implemented by the mySearchView object, and/or the mySearchView.isFocussed() method.  Both sounded promising, however I've now tested and neither seem to work.  Perhaps their failure has got something to do with the fact that this SearchView is in the ActionBar?  In any case, I'm still after a robust solution.

A: It's right there.
mySearchView.setOnQueryTextListener(new OnQueryTextListener() {
    @Override
    public boolean onQueryTextChange(String newText) { return false; }

That's where you'll get updates to text changes in the SearchView.
The return value should be as such (documentation):

Returns
  false if the SearchView should perform the default action of showing any suggestions if available, true if the action was handled by the listener.

If you want to know if the SearchView has been activated or deactivated, use View.setOnFocusChangeListener(View.OnFocusChangeListener);
public interface OnFocusChangeListener{

    public void onFocusChange (View v, boolean hasFocus);
    // The boolean will tell you if it's focused or not.

}

A: Since monitoring the focus didn't work, I looked at the SearchView documentation again. It's a bit convoluted, but it seems like the intended solution to this problem.
If your SearchView is inflated from a menu XML in onCreateOptionsMenu(), then you can add this line:
menu.findItem(/* your SearchView's ID here */).setOnActionExpandListener(
    new OnActionExpandListener(){

        @Override
        public boolean onMenuItemActionCollapse (MenuItem item){
            enableInteraction();
            return true; // Allow the SearchView to collapse.
        }

        @Override
        public boolean onMenuItemActionExpand(MenuItem item){
            disableInteraction();
            return true; // Allow the SearchView to expand.
        }
    }
);

Then enable and disable your Activity's views in enableInteraction() and disableInteraction(), respectively. You should retain the MenuItem in your Activity so you can query it in onResume() like so:
@Override
public void onResume(){
    super.onResume();

    searchViewMenuItem.isActionViewExpanded() ?
    disableInteraction() : enableInteraction();
}

This part might not be needed. The SearchView might automatically get collapsed when the Activity is hidden and stay that way, so you can simply call enableInteraction() in onResume() so your user isn't locked out.
If you just need to reference the state of the SearchView, use
searchViewMenuItem.isActionViewExpanded();


text:
Q: Firebase RecyclerView infinite scroll I'm looking for a way to implement infinite scrolling in my Firebase app.
I'm retrieving my data the following way :
I have a list of keys (items a user created, items a user liked and stuff like this) that I am sending to an adapter which gets the data like this :
 public void onBindViewHolder(final BaseViewHolder viewHolder, final int position) {

    DatabaseReference ref = getAllItemsRef().child(itemIDs.get(position));

    ValueEventListener itemListener = new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            Item item = dataSnapshot.getValue(Item.class);
            viewHolder.bindItem(item);
        }

        @Override
        public void onCancelled(DatabaseError firebaseError) {
        }
    };
    ref.addValueEventListener(itemListener);

}

I would like to add infinite scrolling to gain performance but I have no idea how I should do that with Firebase.
I've seen that FirebaseUI would like to implement it but haven't done it yet.

A: It is very simply achievable with a combination of startAt, limitToLast and orderByKey/orderByChild


text:
Q: Can one see the progress of an application in % for Spark using its REST API I am running a Spark application on a Stand alone Spark cluster. If I check the status of the applications using the Spark REST API, I get something like the following.
curl localhost:4040/api/v1/applications

[ {
  "id" : "app-20191107150648-0000",
  "name" : "MyAppName",
  "attempts" : [ {
    "startTime" : "2019-11-07T14:06:47.372GMT",
    "endTime" : "1969-12-31T23:59:59.999GMT",
    "lastUpdated" : "2019-11-07T14:06:47.372GMT",
    "duration" : 0,
    "sparkUser" : "Username",
    "completed" : false,
    "appSparkVersion" : "2.4.4",
    "startTimeEpoch" : 1573135607372,
    "lastUpdatedEpoch" : 1573135607372,
    "endTimeEpoch" : -1
  } ]
}

My question is, is there any API which also shows how much the application has progressed in %. For example, if its half done, it shoud show 50%. I know its impossible to get an exact figure, but even an estimate would be fine.

A: You could get a list of all stages for a given app from .../applications/[app_id]/stages, and then see how many have been finished via .../applications/[app_id]/stages?status=complete (see https://spark.apache.org/docs/latest/monitoring.html#rest-api). After making a daring assumption that all stages are created equal, you can divide the size of list #2 by #1, and get a percentage.


text:
Q: Java new file creation works on local but not on websphere application server The following code creates a new file in C:\tmp\JSON\Input when I run the application in my local:
ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(new File("\tmp\JSON\Input" ,  "file.json"), request);

But when the ear is deployed to the server, I'm not sure where the file is created. I looked for it under /<root>/tmp/JSON/Input in the server and it is not there.
Am I doing it right or is there another way to do this? Please help. Thanks.

A: Quite possibly, WAS is not running on Windows on the servers, and there is no c:. If *nix and allowed, the /tmp directory would be created on the root, but I doubt that is allowed.
There is no simple solution. Talk to the server admins and find out if they provide a directory for temporary files.


text:
Q: How to access S3 bucket name and end point from instance metadata? I created S3 bucket using Cloud formation template script.
Now i want to access S3 bucket name and end point from instance metadata.
Any help?

A: To enable applications running on an Amazon EC2 instance to access Amazon S3 (or any AWS service), you can create an IAM Role for the EC2 instance and assign it to the instance.
Applications on that instance that use the AWS SDK to make API calls to AWS will automatically have access to credentials with permissions described in the assigned role.
Your particular situation is slightly difficult because the CloudFormation template will create a bucket with a unique name, while your IAM Role will want to know the exact name of the Amazon S3 bucket. This can be accomplished by referring to the S3 bucket that was created within the CloudFormation template.
The template would need to create these resources:

*

*AWS::S3::Bucket

*AWS::IAM::Role to define the permissions

*AWS::IAM::InstanceProfile to link the role to the EC2 instance

*AWS::EC2::Instance that refers to the IAM Role

Within the definition of the IAM Role, the ARN for the S3 bucket would need to refer to the bucket created elsewhere in the template. This would require a bit of string manipulation to insert the correct value into the policy.
If you run into difficulty, feel free to create another StackOverflow question showing the template that you have been working on, highlighting the part that is causing difficulty.


text:
Q: How can i delete _id properties? My problem is im trying to delete ._id when i show the contacts with all properties but for some reason if doesnt work.
app.get("/contacts", (req,res)=>{
var id = res.params._id;
contacts.find({}).toArray((err,contactsArray)=>{

    if(err){
         console.log("Error: "+err);
    }else{
        var arraySinId = contactsArray.map((t)=>{
           t.delete(id);
        });
        res.send(arraySinId);
    }
});

A: You can remap array into a new one with properties that you need. Check out code below.

const contactsArray = [
  { id: 1, foo: 'foo'},
  { id: 2, foo: 'bar'},
  { id: 3, foo: 'baz'},
  { id: 4, foo: 'foobar'}
]

const arraySinId = contactsArray.map((t) => ({
  foo: t.foo,
}));

console.log(arraySinId)

UPDATE
In case the prop that has to be removed is dynamic you can use utility function omit that you can find in libraries such as Ramda or Lodash OR wite by your own.

const dynamicPropToRemove = 'id'

const contactsArray = [
  { id: 1, foo: 'foo'},
  { id: 2, foo: 'bar'},
  { id: 3, foo: 'baz'},
  { id: 4, foo: 'foobar'}
]

const arraySinId = contactsArray.map(R.omit([ dynamicPropToRemove ]));

console.log(arraySinId)
<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.min.js"></script>


text:
Q: Using MVC5, How can I databind a collection to a DropDownListFor I am developing an MVC5 application. I have a controller/view to Create new AccountDtos. An AccountDto has a collection (List<KeyValuePair<string, string>>) of AssociatedVendors. My AccountDto is a simple POCO and looks like this
public class AccountDto
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Reference { get; set; }
    public List<KeyValuePair<string, string>> AssociatedVendors { get; set; }
    . . .
}

In my view, I have two multi-select controls (see image below). One lists all Vendors, the other lists the vendors I select. The goal is to allow me to select a sub-set of vendors to associate with my AccountDto upon creation.

I add items from either select control using javascript

    $("#vendor-add").on("click", function(e) {
        e.preventDefault();
        $("#vendor-source-select").find(':selected').appendTo($("#vendor-dest-select"));
    });

    $("#vendor-addall").on("click", function (e) {
        e.preventDefault();
        $("#vendor-source-select").children().appendTo($("#vendor-dest-select"));
    });

    $("#vendor-remove").on("click", function (e) {
        e.preventDefault();
        $("#vendor-dest-select").find(':selected').appendTo($("#vendor-source-select"));
    });

    $("#vendor-removeall").on("click", function (e) {
        e.preventDefault();
        $("#vendor-dest-select").children().appendTo($("#vendor-source-select"));
    });

The problem is databinding. I am trying to databind the select control on the right to the AssociatedVendors that I select. I have tried various flavours of ListBoxFor and DropdownListFor such as
@Html.DropDownListFor(m => m.AssociatedVendors,
new SelectList(Model.AssociatedVendors.Select(s => new SelectListItem{Text = s.Value, Value = s.Key})),
htmlAttributes: new { id = "vendor-dest-select", @class = "vendor-select", multiple = "multiple" })

@Html.DropDownListFor(x => x.AssociatedVendors, new SelectList(Model.AssociatedVendors, "Key", "Value"))

@Html.ListBoxFor(x => x.AssociatedVendors, new SelectList(Model.AssociatedVendors, "Key", "Value"))

When I submit my view back to the controller, the AssociatedVendors property is always 0 length. I'd appreciate any help or pointers in the right direction.  Thank you.

A: I've come up with a kind of fix. I realise that I cannot data bind to the same list that's being edited, so I added a new collection of AssocVendorIds to my AccountDto.  Then I can data bind to that collection using
@Html.DropDownListFor(M => M.AssocVendorIds,
new MultiSelectList(Model.Vendors.Select(s => new SelectListItem{Value = s.Id.ToString(), Text = s.Name}),
"Value", "Text"), htmlAttributes: new { id = "vendor-dest-select", @class = "vendor-select", multiple = "multiple" })


text:
Q: custom usercontrol content in UpdatePanel disappears on button click postback I have the following function that updates the UpdatePanel content by adding/loading an ascx custom usercontrol in the placeholder that is in default.aspx:
 protected void NavigationTab_Click(string ascxpath)
                {
                        Control ctrl = LoadControl(ascxpath);
                        //cphmaincontent is my asp ContenPlaceHoderId in masterpage
                        PlaceHolder phmaincontent = (PlaceHolder)cphmaincontent.FindControl("phmaincontent");
                        phmaincontent.Controls.Clear();
                        phmaincontent.Controls.Add(ctrl);
                        upmaincontent.Update();
                }

Masterpage UpdatePanel:
<asp:UpdatePanel ID="upmaincontent" runat="server" UpdateMode="Conditional">
                    <ContentTemplate>
                        <asp:Label ID="lbmsg" runat="server" Text=""></asp:Label>
                        <asp:ContentPlaceHolder ID="cphmaincontent" runat="server">
                        </asp:ContentPlaceHolder>
                    </ContentTemplate>
                </asp:UpdatePanel>

I am calling NavigationTab_Click from my navigation control that is another custom ascx control, my ctrl Control object that is loading dynamically on each has button and label when I click the button it simply reassigns some text to the label.
and I have this following code on my masterpage just to get the ascx control path:
protected override void OnInit(EventArgs e)
        {
               //raising an event to set ascx path
                mainmenu.NavigatePath += new usercontrols.mainmenu.NavigationHandler(NavigationTab_Click);

                base.OnInit(e);
        }

so far everything works good, after loading my ctrl object by calling NavigationTab_Click  function I see my ctrl in the placeholder and has the button and the label but the issue is this if I click this button it should reassign the label to some text but instead the whole ctrl control content disappears, please help.

A: When you're adding controls dynamically you must ensure that it gets recreated on every postback. You also have to ensure that you assign the same ID as before, otherwise events will not be triggered correctly and values cannot be reloaded from ViewState. This must be done it Page_Load at the latest(better in Page_Init).
That's the reason why you should avoid dynamical controls whenever possible.
So you can add controls in event-handlers like you've done. But they must be recreated on the next Postback. So you need to store somewhere what(f.e. IDs) or how many controls are already created. That can be done for example in ViewState or Session. Then you can assign appropriate IDs to the controls(for example with the index or ID suffixed).
Here are some additional informations on this subject:

*

*View State and Dynamically Added Controls *

*ASP.NET Page Life Cycle Overview


text:
Q: What is " let a=new Error("Error") console.log(a) " and what does it actually do? I am a beginner and getting started with JavaScript, so recently I came across this code and I am really confused as the keyword 'new' in JavaScript is used alongside a constructor function to create a new empty object.
Error("Error") isn't a function, still I am successfully able to run this lines of code
let a=new Error("Error")
console.log(a)

I tried researching from my end and look everywhere where I can, but I cant seem to find a satisfactory answer to resolve my doubt


text:
Q: Find the sum of the series 1 + 1/2 + 1/3 ....+ 1/n, using while loop This is my homework problem. We were asked to find the sum of the series -> 1 + 1/2 + 1/3 + 1/4 ... + 1/n (here n = 20)
The code I tried is provided below.
denominator=1
num=float(1/denominator)
sum=0
while denominator<=20:
    print(num)
    sum+=num
    denominator+=1
print(f'the sum of the above series is {sum}.')

The output is coming out to be 20. But that is not the required result.

A: 1 / denominator is already a float, so no need for float(...), and assigning 1 / denominator to num once doesn't mean num will change as denominator changes, so, you should calculate 1 / denominator for each denominator in the loop, and avoid using built-in function sum (which you could have used to solve this) as a variable name:
denominator = 1
s = 0
while denominator <= 20:
    num = 1 / denominator
    print(num)
    s += num
    denominator += 1
print(f'the sum of the above series is {s}.')

Output:
1.0
0.5
0.3333333333333333
0.25
0.2
0.16666666666666666
0.14285714285714285
0.125
0.1111111111111111
0.1
0.09090909090909091
0.08333333333333333
0.07692307692307693
0.07142857142857142
0.06666666666666667
0.0625
0.058823529411764705
0.05555555555555555
0.05263157894736842
0.05
the sum of the above series is 3.597739657143682.

Using built-in sum with a generator expression:
s = sum(1 / d for d in range(1, 21))

A: sum = 0
for i in range(1, 21):
    sum += 1.0 / i

print(sum)

Output:
3.59773965714

A: The float(1/denominator) is not a function definition but it returns a value.
When you call this code it evaluate to the current value of 1/denominator = 1/1 = 1.
So in the while loop you add 1 for 20 iterations that's the reason you get 20.
Either create a function or move the logic to the loop.
def get_num(denominator):
    return float(1/denominator)

denominator=1
sum=0
while denominator<=20:
    sum+=get_num(denominator)
    denominator+=1
print(f'the sum of the above series is {sum}.')

denominator=1
sum=0
while denominator<=20:
    sum+=float(1/denominator)
    denominator+=1
print(f'the sum of the above series is {sum}.')

A: You can use Fractions module of python for this calculation. Fractions
#!/usr/bin/python

import fractions

denominator = 1
sum = 0
while denominator<=20:
    num = fractions.Fraction(1, denominator)
    sum += num
    denominator += 1

print('the sum of the above series is :', sum)
print('the sum of the above series is :', float(sum))

Output:
the sum of the above series is : 55835135/15519504
the sum of the above series is : 3.597739657143682

Above code is tested on python2.7 and python3.
It prints two lines. First one prints the value as fraction and second one prints the value as float.


text:
Q: String parsing with RegExp in Actionscript I have a string that is similar to a path, but I have tried some regex patterns that are supposed to parse paths and they don't quite work.
Here's the string

f|MyApparel/Templates/Events/

I need the "name parts" between the slashes.
I tried (\w+) but the array came back [0] = "f" and [1] = "f".
I tested the pattern on http://www.gskinner.com/RegExr/ and it seems to work correctly.
Here's the AS code:
var pattern : RegExp = /(\w+)/g;
var hierarchy : Array = pattern.exec(params.category_id);
params.name = hierarchy.pop() as String;

A: pattern.exec() works like in JavaScript. It resets the lastIndex property every time it finds a match for a global regex, and next time you run it it starts from there.
So it does not return an array of all matches, but only the very next match in the string. Hence you must run it in a loop until it returns null:
var myPattern:RegExp = /(\w+)/g;
var str:String = "f|MyApparel/Templates/Events/";

var result:Object = myPattern.exec(str);
while (result != null) {
  trace( result.index, "\t", result);
  result = myPattern.exec(str);
}

A: I don't know between which two slashes you want but try
var hierarchy : Array = params.category_id.split(/[\/|]/);

[\/|] means a slash or a vertical bar.


text:
Q: How to calculate pvalue for the Spearman correlation test I'm trying to code up the spearman correlation coefficient test of R in C++.
> x = runif(100)
> y = runif(100)
> cor.test(x,y, method="spearman")
Spearman's rank correlation rho

data:  x and y
S = 165182, p-value = 0.9306
alternative hypothesis: true rho is not equal to 0
sample estimates:
    rho
    0.008808881

I manage to get S and rho, but I cannot find any documentation to go from S to the pvalue. Is there any GSL distribution I can use for this? BTW, I don't want to test significance using Student's t distribution or permutations.
Thanks!


text:
Q: How to select a kMean cluster as new Dataframe in Spark I have a dataframe with a few million entries, I used k-Means clustering and found that a specific cluster has very different centers from the rest. That is very interesting.
How can I select the entries that belong to this cluster to investigate them further? Can we select clusters as each being a Dataframe of its own?

A: Are you using Spark ML or Spark MLLib?
See the example from https://spark.apache.org/docs/latest/ml-clustering.html#k-means -- predictions object contains what you are looking for.


text:
Q: VFP. Trapping COM errors Trapping Excel COM errors from a VFP program.
A program is writing out an extract from several large tables to Excel using Automation.
Typical instructions include :
lCell = "I1234"
.sSheet1.Range(lCell).value = cCust.Name

This generally works fine, but if cCust.name has a value such as '=' (which Excel does not like), this causes an OLE COM error.
Had tried using TRY  .. . CATCH . . . ENDTRY to trap this error, but the OLE COM error still reports.
I suppose that I could find out all the possible errors in the data and clean them up, but is there any way of getting Automation to ignore the error and carry on (leaving the field unpopulated)?
Thank you.

A: I am adding this as an answer, since it contains some code that would otherwise cause a mess. With ON error it is working perfectly fine for me. ie:
*** Constant Group: XlSaveAction
#Define xlDoNotSaveChanges                                2
#Define xlSaveChanges                                     1

Local loExcel As Excel.Application
Local lcValue
loExcel = Createobject('Excel.Application')
loExcel.Workbooks.Add()
loExcel.ActiveWorkbook.SaveAs('c:\temp\ExcelReadTest.xlsx')
loExcel.DisplayAlerts = .F.
*loExcel.Visible = .T.
On Error lcValue = .Null.
With loExcel.ActiveWorkbook.ActiveSheet
    .Range('A5').Value = '=Like me'
    lcValue = .Range('A5').Value
    ? m.lcValue
Endwith
On Error
loExcel.ActiveWorkbook.Close(xlSaveChanges)
loExcel.Quit()


text:
Q: Laravel delete is just not working I tried bunch of methods to delete images but laravel just ignores the deleting part for some reason. I tried to see if it gets the link with dd($filename) and it get the link right. I tried php unlink too but I'm having issue to pass the path right with it
Storage::delete('storage/images/'.$filename);

This is what I try and laravel acts like it de

A: It's probably a path issue or file permission issue:
 $exists = Storage::exists('storage/images/'.$filename);

 if($exists){
    Storage::delete('storage/images/'.$filename);
    //file should be deleted here.... if not check permissions in storage path
    //webserver sys user should have +r+w on storage path
 }else{
    echo "file not found in ".storage_path('storage/images/').$filename;
 }

A: You should provide more information. Check if you are doing
use Illuminate\Support\Facades\Storage;

before
Storage::delete('storage/images/'.$filename);

Maybe you have some errors or another debug info?

A: Add this code to use storage :
use Illuminate\Support\Facades\Storage;

then find the file by this code:
$file = Storage::exists('storage/images/'.$filename);

then delete file if exist:
if ($file) {Storage::delete('storage/images/'.$filename)}
else {
 return "File Not exist";
}

N:B make sure that the file that you want to delete have proper permission

A: Firstly find the data on particular id
For example
$post = \App\Post::find($id);
unlink(public_path().'/uploads/post/'.$post->image);
$post->delete();

A: I ended up using the raw PHP way to do that.
unlink('storage/images/'.$filename);

unlink is working well, and there is no setup required to accomplish it.