text:
Q: How to save textarea data to session with jquery ajax post method [Codeigniter]? I want to save textarea to Controller session using jquery ajax post method in Codeigniter smarty. I can't save data to session. How can I do this? Please guide me with full description coding example please.

$this->session->set_userdata()

Here is my view

    <form method="post" id="programmingQ1" name="programmingQ1" action="{base_url('home/question2')}" enctype="multipart/form-data">

        {foreach $question_data as $qdata}

                {$qdata->Question|nl2br}

        {/foreach}

            Fill in the answer :

            <textarea name="answer1"  id="text" maxlength="2000" class="form-control" rows="20">{if isset($value)}{$value['answer1']}{/if}</textarea>
          <input type="button" id="mybutton" name="next" class="btn btn-default nextbutton" id="btn_submit" value="Next">

    </form>

Here is my ajax

Here is my controller
public function saveq1()
{
    $data=array();

    if($_SERVER['REQUEST_METHOD']=='POST')
    {
        $this->load->library('session');
        $this->session->set_userdata('answer1',$this->input->post());
        print_r($this->session->userdata('answer1'));
    }
    $data['value']=$this->session->userdata('question1');
    $this->smarty->view('question1.tpl',$data);
}

A: <?php session_start();?>

    <form method="post" id="programmingQ1" name="programmingQ1" action="{base_url('home/question2')}" enctype="multipart/form-data">

        {foreach $question_data as $qdata}

                {$qdata->Question|nl2br}

        {/foreach}

            Fill in the answer :

            <textarea name="answer1"  id="text" maxlength="2000" class="form-control" rows="20">{if isset($value)}{$value['answer1']}{/if}</textarea>
          <input type="button" id="mybutton" onclick="setTxtAreaDataToSession();" name="next" class="btn btn-default nextbutton" id="btn_submit" value="Next">

    </form>


text:
Q: Having problems installing a GHCI in Debian 11 GNU/Linux I'm trying to install GHCI in Debian 11 GNU/Linux but the system won't allow me, It says that I'm not an admin.
If you post here some help I will surely could build a better question.
Thanks,
F.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to periodically clear unfinished cron jobs I have scheduled a cron job (which runs a php script) which runs every 15 minutes. This cron job is in dependence of another separate system and code and one day this system crashed so after the weekend I found the server flooded with numerous scheduled jobs.
Can you give me some advice how to avoid such problems? Maybe, to clean similar old cron jobs automatically or something else?
Thank you!


text:
Q: Extract column of matrices from a 3D indexes I try to extract columns of matrices(in 2D) from a set of given indices(in 3D), without converting the 2D matrix into 3D so as to efficiently use memory (I'm dealing with very huge data), can I achieve this? I'll reuse the 2D matrix for each slice of the 3D matrix, but I just don't know how to do it. Example code:
A=rand(9,100); %The matrix that will be reused
B=randi([1 100],[1 100 30]); %the indices
Extracted=A(:,B); %this part I can't seem to solve it yet

Expected output of Extracted would be 9x100x30. Any idea guys? Thanks in advance!

A: A solution can be using inline function and arrayfun:
A=rand(9,100); %The matrix that will be reused
B=randi([1 100],[1 100 30]); %the indices
func = @(x) A(x);
Extracted = arrayfun(func, B);

Another solution is convert 3D matrix B to a vector.
Then using your method to retrieve Extracted:
A=rand(9,100); %The matrix that will be reused
B=randi([1 100],[1 100 30]); %the indices
idx = reshape(B,1,numel(B));
Extracted = A(idx);


text: Q: I have uploaded an app for iTunes, the build is there but the details is not visible. I have uploaded an app for iTunes, the build is there but the details (whether rejected, under review or available for testing) is not visible. This is unlike my previous apps which show said details.


text:
Q: Search Keyword Query to list all team sites on SharePoint Online Highlighted Content WebPart I want to display all private Team-Sites on a Page in SharePoint Online
Can somebody help me to get the right custom query?
Kind regards from austria,
Helmut

A: You could try to use the below query to list all team sites in Highlighted Content Web part:
(contentclass:"STS_Site")(SiteTemplate:"GROUP" OR SiteTemplate:"STS")


text:
Q: How to write OSX/Finder tags as metadata into PDF? I have added tags to all of my PDF documents, but the problem is, that these kind of tags are only supported by OSX (Mavericks), that means they are gone if I want to use the PDF on a e.g. windows or linux machine.
I'am looking for a solution to automatically write all my tags into the PDF as keyword metadata.

A: Here's a start: Tag is a command line tool to manipulate tags in Mavericks.
ExifTool is a command line tool for writing metadata into images.
So you need to do something like this to glue them together in a command line function:
function tags2metadata(){
   tags=$(tag -N "$1");
   exiftool -Keywords="${tags//,/, }" "$1";
   tag --add "$tags" "$1";
}

tags=$(tag -N "$1"); harvests the tags as a comma separated list (the -N option is to avoid it displaying the file name in its output), eg good,bad,ugly
exiftool -Keywords="${tags//,/, }" "$1"; adds the tags to the "Keyword" metadata field in the pdf metadata (the expression ${tags//,/, } replaces every comma in $tags with comma+space, so that they become separate keywords).
Now exiftool creates a new file with the name of the original file and renames the original; eg. foo.pdf is renamed to foo.pdf_original and a new file foo.pdf is created with the modified metadata. You can change this by adding -overwrite_original to the exiftool command like this:
exiftool -overwrite_original -Keywords="${tags//,/, }" "$1";

but I chose to just re-write the mavericks Finder tags to the new file using tag --add "$tags" "$1"; ($1 in a function stands for the input it is given).
So to use it, you could then open a terminal, type in the script above, cd to the directory with your pdfs in it and do:
for i in *.pdf
   do tags2metadata "$i"
done

If you open the new file and check for keywords, you should find all your Finder tags in there.
To install tags and exiftool I recommend Homebrew. Once you've installed it you just need to type brew install exiftool tag and it will do the necessary magic for you.
Please test this on files that you don't mind screwing up before you let it loose on your good stuff.


text:
Q: Buttons are not appearing in a basic Activity As shown in image no text of "Hello world" and floating action button appear.

I changed my styles.xml
<style name="AppTheme" parent="Base.Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>

content_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_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"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="io.sentry.sentry_android_example.MainActivity"
    tools:showIn="@layout/activity_main">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!" />
</RelativeLayout>

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context="io.sentry.sentry_android_example.MainActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

    </android.support.design.widget.AppBarLayout>

    <include layout="@layout/content_main" />

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="@dimen/fab_margin"
        android:src="@android:drawable/ic_dialog_email" />

</android.support.design.widget.CoordinatorLayout>

As per many comments, I have updated my activity_main.xml, content_main.xml styles.xml
But in design layout, I am still not able to see the buttons and text

And now I am getting errors
  1)Render problem Failed to find style 'coordinatorLayoutStyle' in the current theme
  2)Render problem Couldn't resolve resource @dimen/activity_horizontal_margin
  3)Missing Styles
  4)Failed to instantiate one or more class

A: In the right corner of the screen shot it shows read mark that means you have an error should have to be fixed so please click the read mark and check the error or please post your xml so that i can help you more.

A: This is my style and it works fine please check it out
 <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>

Here is my screenshot :

A: There are something wrong in styles.xml. Use this instead, which is default
<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>
    <style name="AppTheme.NoActionBar">
        <item name="windowActionBar">false</item>
        <item name="windowNoTitle">true</item>
    </style>
    <style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar"/>
    <style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light"/>

</resources>

You must be accidentally deleted the resources tag.
And for below issue

Render problem Couldn't resolve resource
  @dimen/activity_horizontal_margin

Go to values --> dimens.xml, and add below line in resources tag
 <dimen name="activity_vertical_margin">15dp</dimen>

Hope this helped.


text:
Q: SQL query with join, sum, group by, etc I'm trying to build a report that will look like this:
      jan feb mar apr may jun jul ago sep oct nov dec
food   0   1   1   2   0   0   3   1   0   0   1   1
car    1   0   0   0   1   2   1   0   1   2   3   4
home   0   0   1   2   2   2   5   1   2   4   0   0
other  0   0   0   0   0   0   0   0   0   0   0   0

I have two tables: t_item and t_value. t_item has 2 columns: itemID and itemName. t_value has 3 columns: itemID, value, date.
With the following query I can generate a list with all the itens, even with the empty ones.
SELECT t_item.itemID, ISNULL(SUM(t_value.value), 0) AS value
FROM t_value RIGHT OUTER JOIN t_item ON t_value.itemID = t_item.itemID
GROUP BY t_item.itemID

But, if I try to include a MONTH column (as follows) the result will show only the items with values...
SELECT t_item.itemID, ISNULL(SUM(t_value.value), 0) AS value, MONTH(date) AS date
FROM t_value RIGHT OUTER JOIN t_item ON t_value.itemID = t_item.itemID
GROUP BY t_item.itemID, MONTH(date)

Is it possible to do it? How do I include into the results the itens with no values and group then by month?
TIA,
Bob

A: For the "holes" in your data you need a filler table.  Join this table with a full outer join to the fact table on month.
month
------
month --values jan through dec

For the formating you have a couple options.

*

*In your reporting tool use the cross tab or matrix function.

*In SQL use the CASE function.

*In SQL use the Pivot function.

A: Are you using a reporting tool with crosstab like ability?
If not, you can create a sum column for each month. so your resultset would actually look like that report sample.
SELECT t_item.itemID,

--ISNULL(SUM(t_value.value), 0) AS value,

sum(case when MONTH(date) = 1 then t_value.value else 0 end) AS m1_sum,
sum(case when MONTH(date) = 2 then t_value.value else 0 end) AS m2_sum,
sum(case when MONTH(date) = 3 then t_value.value else 0 end) AS m3_sum,
--etc

FROM t_value RIGHT OUTER JOIN t_item ON t_value.itemID = t_item.itemID
GROUP BY t_item.itemID

A: Here's an example:
create table #months (value int, name varchar(12))
create table #items (value int, name varchar(24))
create table #sales (month int, item int, sales int)

insert into #months values (1, 'jan')
insert into #months values (2, 'feb')
insert into #months values (3, 'mar')

insert into #items values (1, 'apple')
insert into #items values (2, 'pear')
insert into #items values (3, 'nut')

insert into #sales values (1,1,12)
insert into #sales values (2,2,3)
insert into #sales values (2,2,5)
insert into #sales values (3,3,7)

You can query it using a PIVOT table, like:
select *
from (
    select
        item = #items.name
    ,   month = #months.name
    ,   sales = isnull(sum(#sales.sales),0)
    from #months
    cross join #items
    left join #sales on #months.value = #sales.month
         and #items.value = #sales.item
    group by #months.name, #items.name
) vw
pivot (sum(sales) for month in ([jan],[feb],[mar])) as PivotTable

Or as an alternative, a regular query:
select
    item = #items.name
,   jan = sum(case when #sales.month = 1 then sales else 0 end)
,   feb = sum(case when #sales.month = 2 then sales else 0 end)
,   mar = sum(case when #sales.month = 3 then sales else 0 end)
from #items
left join #sales on #items.value = #sales.item
group by #items.name

Both result in:
item        jan     feb     mar
apple       12      0       0
nut         0       0       7
pear        0       8       0

In the first example, the "cross join" ensures all months and values are present. They're then "left joined", so even the rows with no values are displayed.
The IsNull() is just so that it displays 0 instead of NULL for a month in which that particular item was not sold.

A: WITH    calendar(mon) AS
        (
        SELECT  1
        UNION ALL
        SELECT  mon + 1
        FROM    calendar
        WHERE   mon < 12
        )
SELECT  itemID, mon, SUM(value)
FROM    calendar c, t_item i
LEFT OUTER JOIN
        t_value v
ON      v.itemID = i.itemID
        AND MONTH(date) = mon
GROUP BY
        i.itemID, mon


text:
Q: SQL subquery / join I am trying to use a subquery / join to compare a set of rows in a table to other rows in the same table.
Excerpt data set:
Guid                        MonitorsetID    groupName
26464009405210800000000000  2162            ~templates.root
26464009405210800000000000  2161            ~templates.root
26464009405210800000000000  1464            ~templates.root
26464009405210800000000000  1224            ~templates.root
321794737607583             2162            lab.root.abc
321794737607583             2161            lab.root.abc
321794737607583             1464            lab.root.abc
321794737607583             1224            lab.root.abc
500311571061532             2196            lab.root.abc
500311571061532             2195            lab.root.abc
500311571061532             1464            lab.root.abc
500311571061532             1224            lab.root.abc
129478194721498             1464            lab.root.def
129478194721498             1224            lab.root.def

I need to result on which MonitorsetID(s) exist on one particular Guid '26464009405210800000000000'  but are "missing" for a select group of other Guid records, for this example all Guids with groupName 'lab.root.abc'. In the exerpt above, there are currently 4 MonitorsetIDs matching this Guid: 2162, 2161, 1464, 1224. 2162 and 2161 are "missing" from the Guid '500311571061532'.
The result set I would like is:
Guid                        MonitorsetID    groupName
500311571061532             2162            lab.root.abc
500311571061532             2161            lab.root.abc

Or, the following would also work:
Guid                        MonitorsetID    groupName           Guid                MonitorsetID    groupName
26464009405210800000000000  2162            ~templates.root     500311571061532     NULL            lab.root.abc
26464009405210800000000000  2161            ~templates.root     500311571061532     NULL            lab.root.abc

I'm able to get the inverse of the result I want with the following:
SELECT VMAA.agentguid, VMAA.MonitorsetID
FROM [vMonitorsetAgentAssignment] VMAA
LEFT JOIN [vMonitorsetAgentAssignment] VMAA2
ON VMAA.MonitorsetID = VMAA2.MonitorsetID

WHERE
    VMAA.agentguid in
    (
    SELECT AgentGuid FROM vMonitorsetAgentAssignment VMAA
    WHERE VMAA.groupName = 'lab.root.abc'
    )
    AND
    VMAA2.agentguid = '26464009405210876452365122'

ORDER BY agentGuid, MonitorsetID

My attempts at getting the needed results by adding a condition to the JOIN ON clause with "IS NULL", etc. just return blank results.

A: Get all possible combinations of the GUIDs in the groupName you are filtering over along with the MonitorsetID's of the GUID you are filtering on (by cross-joining from the base table to a distinct set of MonitorsetIDs for the GUID you are filtering on).
Once you have that data-set, it becomes a simple left-join from that derived data set over to your base table again on guid/monitersetIds that don't exist:
with root_data as
(
    select  distinct a.agentguid, b.MonitorsetID, a.groupName
    from    vMonitorsetAgentAssignment a
    cross join (
            select  distinct MonitorsetID
            from    vMonitorsetAgentAssignment d
            where   d.agentguid = '26464009405210800000000000'
        ) b
    where   a.groupName = 'lab.root.abc'
)
select  *
from    root_data d
left join vMonitorsetAgentAssignment a
on      a.agentguid = d.agentguid
and     a.MonitorsetID = d.MonitorsetID
where   a.agentguid is null;

A: If I understand correctly:
select '500311571061532' as agentguid, a.MonitorsetID
from vMonitorsetAgentAssignment a left join
     vMonitorsetAgentAssignment a2
     on a2.agentguid = '500311571061532' and
        a.MonitorsetID = a2.MonitorsetID
where a.agentguid = '321794737607583' and
      a2.agentguid is null;

I'm not sure where the group comes from.

A: This query will extract missing ids for both guids 129478194721498 and 500311571061532.
with createddata as (
  select *
  from
  (
     select distinct guid, groupname from vMonitorsetAgentAssignment
     where guid <> '26464009405210800000000000'
  ) a
  cross join
  (
     select monitorsetid from vMonitorsetAgentAssignment
     where guid = '26464009405210800000000000'
  ) b
)
select x.*
from createddata x
left join vMonitorsetAgentAssignment y
  on x.guid = y.guid
  and x.monitorsetid = y.monitorsetid
  and x.groupname = y.groupname
  and y.guid <> '26464009405210800000000000'
where y.guid is null

Results
|            guid |    groupname | monitorsetid |
|-----------------|--------------|--------------|
| 129478194721498 | lab.root.def |         2162 |
| 129478194721498 | lab.root.def |         2161 |
| 500311571061532 | lab.root.abc |         2162 |
| 500311571061532 | lab.root.abc |         2161 |

Example: http://sqlfiddle.com/#!3/80719/33
Ignore the answer below
Take a look at this query for the results you described as desired:
  select a.* from
  vMonitorsetAgentAssignment a
  left join (
      select monitorsetid as masterids from vMonitorsetAgentAssignment
      where guid = '26464009405210800000000000'
  ) b on a.monitorsetid = b.masterids
  where not guid = '26464009405210800000000000'
        and masterids is null

Result:
|            Guid | MonitorsetID |    groupName |
|-----------------|--------------|--------------|
| 500311571061532 |         2196 | lab.root.abc |
| 500311571061532 |         2195 | lab.root.abc |

A: This is basically what you need.
WITH monitor_sets AS (
    SELECT MonitorsetID, agentguid
    FROM vMonitorsetAgentAssignment
    WHERE agentguid = '26464009405210876452365122'
)

SELECT DISTINCT vmaa.agentguid AS guid_with_missing, ms.agentguid, ms.MonitorsetID
FROM vMonitorsetAgentAssignment vmaa
CROSS JOIN monitor_sets ms
WHERE vmaa.groupName = 'lab.root.abc'
    AND vmaa.MonitorsetID NOT IN (SELECT MonitorsetID FROM monitor_sets)
    AND vmaa.agentguid NOT IN (SELECT agentguid FROM vMonitorsetAgentAssignment WHERE MonitorsetID = ms.MonitorsetID)


text:
Q: How can I find the n-th item in a sorted array, but that array is represented using two AVL trees? I have two AVL trees filled with numbers from a set. The information stored in every node is both the value of the node itself and the size of the corresponding subtree. The question is how can I (in an optimal time complexity) find the nth value of the sorted array containing all the items in the AVL trees (basically, the nth smallest number).
My approach would be to do some kind of binary search regarding the sizes of the subtrees, but the fact that there are two makes it a little bit more difficult. Would it be inefficient to firstly combine the two AVL trees? What would be your approach?


text:
Q: How do I get the id's of children of siblings using jquery I am using this code and it outputs the correct objects, but I am unable to get only the id from these objects. Here is the code:
console.log($(this).parent().parent().siblings().children());

Output is:
[div#first-example.box-prop.top-widget, div#second-example.box-prop.top-widget, div#third-example.box-prop.top-widget, prevObject: init[3], context: i.fa.fa-times.close-x]

A: You can use .map:
var ids = $(this).parent().parent().siblings().children().map(function(e){
    return this.id;
}).get();


text:
Q: After server is restarted, the database and the backups are destroyed by the system crash. What ACID properties are broken in this situation? I am currently studying ACID properties and stumbled upon a question for which I can't find the answer.
Let's assume that two transactions execute on a database, both reading, and writing. At some time, the system crashes. After the server is restarted, the database and the backups were destroyed by the crash and the database does no longer exists. Which ACID properties would this break?
My first guess is that it breaks only Durability since we can assume that transactions did nothing to the database ensuring Atomicity, the database is definitely consistent, and I am not sure about isolation, but I don't see how would this break isolation.

A:
After the server is restarted, the database and the backups were destroyed by the crash and the database does no longer exists.

If a server failure has destroyed both the database and its backups, then whoever set up the backups is, frankly, incompetent.
The whole point of Backups - indeed, the only reason that we expend so much time, effort and money on them at all - is so that they can be Recovered even if you lose your entire machine estate and have to rebuild everything using new servers driven onto your site on the back of great, big lorries (Ye Olde Schoole of Recovery).
OK, everything's "Virtual" these days, but the same principle applies.
If you take your backups on a VM on the same Hypervisor as the database server, do you really have any protection of the hypervisor blows up?

Which ACID properties would this break?

ACID describes behaviours inside a properly working database, in much the same way that an operating manual might describe the proper working of, say, a carriage clock.
If you drop the clock off a tall building, it's not likely to tell the time reliably, or at all, afterwards.
Same goes for your "broken" database.
But at least, with proper Backups, you can reconstruct your database (no-one's figured out an equivalent for the clock, yet).

A: It wouldn't break any ACID properties regarding the single database, because neither the database nor the backups exist after the incident.
ACID are are a set of properties regarding transactions:

In computer science, ACID (atomicity, consistency, isolation, durability) is a set of properties of database transactions intended to guarantee data validity despite errors, power failures, and other mishaps. In the context of databases, a sequence of database operations that satisfies the ACID properties (which can be perceived as a single logical operation on the data) is called a transaction. For example, a transfer of funds from one bank account to another, even involving multiple changes such as debiting one account and crediting another, is a single transaction.

Reference: ACID (Wikipedia)
You wouldn't know the state of the ACID properties until you restored the database, which you can't.
Atomicity

Transactions are often composed of multiple statements. Atomicity guarantees that each transaction is treated as a single "unit", which either succeeds completely, or fails completely: if any of the statements constituting a transaction fails to complete, the entire transaction fails and the database is left unchanged.

Answer: We don't know
Consistency

Consistency ensures that a transaction can only bring the database from one valid state to another, maintaining database invariants: any data written to the database must be valid according to all defined rules, including constraints, cascades, triggers, and any combination thereof. This prevents database corruption by an illegal transaction, but does not guarantee that a transaction is correct.

Answer: We don't know
Isolation

Transactions are often executed concurrently (e.g., multiple transactions reading and writing to a table at the same time). Isolation ensures that concurrent execution of transactions leaves the database in the same state that would have been obtained if the transactions were executed sequentially. Isolation is the main goal of concurrency control; depending on the method used, the effects of an incomplete transaction might not even be visible to other transactions

Answer: We don't know
Durability

Durability guarantees that once a transaction has been committed, it will remain committed even in the case of a system failure (e.g., power outage or crash). This usually means that completed transactions (or their effects) are recorded in non-volatile memory.

Answer: We don't know
However
...you could start making well guessed hypothetical assumptions:
Durability probably went out the window, because the transaction never ended and probably didn't roll back.
Consistency probably failed, because the state became unknown.
Atomicity possibly failed, because it's not guaranteed that the data was correcty written to the database.
Isolation probably won, because transactions are mostly conducted in some sequential order as defined by the database settings and session settings. But that is highly speculative. It depends on the order of the total system failure and how it unfolded internally.


text:
Q: Rearrange array values to "root level" Given the following array
array(
  0 => array(
    'id' => '54'),
  1 => array(
    'id' => '11'),
  2 => array(
    'id' => '2')
);

Is there a (preferrably built-in) function that re-arranges it to
array(
  0 => '54',
  1 => '11',
  2 => '2'
);

in PHP?
My current way is to iterate over the array and save it to another one, which seems awfully redundant, slow, and inefficient.
$newArray = array();
foreach ($oldArray as $innerArray {
    $newArray[] = $innerArray['id'];
}

A: How about using array_walk
function array_flatten( &$item ){
    $item = $item['id'];
}

array_walk( $array, 'array_flatten' );

A: How about this?
$arr = array(
  0 => array(
    'id' => '54'),
  1 => array(
    'id' => '11'),
  2 => array(
    'id' => '2')
);
$newArr = call_user_func_array('array_merge_recursive',$arr);
print_r($newArr['id']);


text:
Q: How to use Linkedin-iphone current_user in an other view I'm using this LinkinClientLibrary https://github.com/ResultsDirect/LinkedIn-iPhone
I'm little confused, it's a single view app the DEMO, it working, I've managed to make it work in my own app.. But now after the successful login of the user, I want to show a tableview with all his/her connections and maybe a detail screen of a connection...
So I have now a login screen and after successful authenticate the user I perform a segue to a tableview and how can I use the current users connections in that tableview or even if its simpler to explain the current users data in a view (and check that the user is still connected)
Thnx Fred

A: There's another iPhone sample client here:
    https://github.com/synedra/LinkedIn-OAuth-Sample-Client
In that there is a profile view that uses the authentication information from LinkedIn to make calls to LinkedIn - it demonstrates both read and write functionality.  Check out the code to see if it answers your questions.


text:
Q: sklearn linear regression for 2D array I have a Numpy 2D array in which the rows are individual time series and the columns correspond to the time points.  I would like to fit a regression line to each of the rows to measure the trends of each time series, which I guess I could do (inefficiently) with a loop like:
array2D = ...
for row in array2D:
    coeffs = sklearn.metrics.LinearRegression().fit( row, range( len( row ) ).coef_
    ...

Is there a way to do this without a loop?  What is the resulting shape of coeffs?

A: The coefficients that minimize the linear regression error are

You can solve for all rows in one go using numpy.
import numpy as np
from sklearn.linear_model import LinearRegression

def solve(timeseries):

    n_samples = timeseries.shape[1]
    # slope and offset/bias
    n_features = 2
    n_series = timeseries.shape[0]

    # For a single time series, X would be of shape
    # (n_samples, n_features) however in this case
    # it will be (n_samples. n_features, n_series)
    # The bias is added by having features being all 1's
    X = np.ones((n_samples, n_features, n_series))
    X[:, 1, :] = timeseries.T

    y = np.arange(n_samples)

    # A is the matrix to be inverted and will
    # be of shape (n_series, n_features, n_features)
    A = X.T @ X.transpose(2, 0, 1)
    A_inv = np.linalg.inv(A)

    # Do the other multiplications step by step
    B = A_inv @ X.T
    C = B @ y

    # Return only the slopes (which is what .coef_ does in sklearn)
    return C[:,1]

array2D = np.random.random((3,10))
coeffs_loop = np.empty(array2D.shape[0])
for i, row in enumerate(array2D):
    coeffs = LinearRegression().fit( row[:,None], range( len( row ) )).coef_
    coeffs_loop[i] = coeffs

coeffs_vectorized = solve(array2D)

print(np.allclose(coeffs_loop, coeffs_vectorized))

A: For those like me who prefer the range as X and the timeserie data as y.

def linear_fit(periods, timeseries):
    # just format and add one column initialized at 1
    X_mat=np.vstack((np.ones(len(periods)), periods)).T

    # cf formula : linear-regression-using-matrix-multiplication
    tmp = np.linalg.inv(X_mat.T.dot(X_mat)).dot(X_mat.T)
    return tmp.dot(timeseries.T)[1] # 1 => coef_, 0 => intercept_

X = np.arange(8) # the periods, or the common range for all time series

y = np.array([ # time series
    [0., 0., 0., 0., 0., 73.92, 0., 114.32],
    [0., 0., 0., 0., 0., 73.92, 0., 114.32],
    [0., 10., 20., 30., 40., 50., 60., 70.]
])

linear_fit(X, y)
[1]: array([12.16666667, 12.16666667, 10.        ])

PS:This approach (linear regression with matrix multiplication) is a gold mine for large dataset


text:
Q: how to compare array.include(arrayData) in vue i have two array data
checked: [
'orange', 'apple', 'juice'
]

and 2nd
products: [
 '0': {
    title: 'this is product title',
    categories: [
     'apple', 'juice'
    ]
  }
]

i want to to filter data with computed property with checkbox
i tried this
computed: {
   filterProducts(){
       return this.products.filter(product => this.checked.includes(product.categories));
   }
}

but its not working how can i do this

A: You're trying to check if an array of strings includes an array (which won't work even if your initial array contained arrays). Instead of using .includes(), use .every() on product.categories to check if all items within this array are contained within checked:

const checked = ['orange', 'apple', 'juice'];

const products = [
  {
    title: 'this is product title',
    categories: ['apple', 'juice']
  }
];

const computed = products.filter(product => product.categories.every(item => checked.includes(item) || !checked.length));

console.log(computed);

A: You can use .every() for that.
Here is an example:

checked = [
  'orange', 'apple', 'juice'
]

products = [{
  title: 'this is product title',
  categories: [
    'apple', 'juice'
  ]
}];

const filteredProducts = products.filter(({ categories }) => categories.every(cat => checked.includes(cat)));

console.log(filteredProducts);

This will return an array of products that have a categories array with all its values included in the checked array.
I'm not sure if this is exactly what you're trying to do, if you instead want to get all the products with a categories array that has at least one of its values in the checked array, use .some() instead of .every().


text:
Q: Cannot load phoenix js library with SystemJS in angular2 I followed the Angular2 quickstart typescript tutorial (here).
Now I am trying to include the phoenix.js package so that I can connect to my Elixir Phoenix channels.
I've added phoenix from this package to my package.json and installed it.
I've added a line to systemjs.config.js like this:
'phoenix': 'node_modules/phoenix/web/static/js/phoenix.js'

I'm trying to import it into my Angular2 service like this (I'm using ES6 and have read through this issue):
import { Socket } from 'phoenix';

I get the error
app/app.phoenix_channels.service.ts(2,24): error TS2307: Cannot find module 'phoenix'.

I'm not actually 100% sure how the SystemJS config file is included and run.  It's included in the HTML prior to the application, but I can't see it being included or parsed when I'm compiling typescript.
I've been through this question on Stack but I can't work out how to get the dependency loaded using the framework that the Angular tutorial provides.
I tried adding additional_deps as a key to the systemjs.config.js like this:
additional_deps: {
  src: 'node_modules/phoenix/priv/static/phoenix.js',
  inject: 'libs'
},

But that doesn't seem to work.
How can I get this dependency to load so that I can import from this library?

A: You have the JS file, which is for runtime, but the error is a compilation error because it's looking for a typescript file. For libraries, TypeScript definition files are used but some libraries don't have TypeScript support so we need to install external modules with the type definitions.
Some JS projects you may not find a definition file out there, and you need to write your own. Or you can just do what the poster in the answer you linked to did. Just declare random any type variables (don't import)
declare var Socket: any;

Now you can use Socket. The problem with this though is that you don't have any strong typing or intellisense.
Luckily it looks like someone wrote a definition file for phoenix
npm install --save-dev @types/phoenix

That should get it to work. As far as runtime, your SystemJS configuration looks like it should be good.


text:
Q: $2^n=na_n+na_{n-1}-a_{n-1}$ by range transformation I want to range transform $2^n=na_n+na_{n-1}-a_{n-1}$ to get rid of the $2^n$ term and then solve it with any other method (seems like telescoping will work once it's reduced).
I've tried transforming it by $b_n=a_n/2^n$ which yields:
$1=\frac{n}{2^n}*b_n+\frac{n}{2^n}*b_{n-1}-b_{n-1}$
But now the $b_n$ terms have $2^n$ in their coefficient, which is no better than I started with.

A: Hint First simplify the equation, you get $2^n=na_n+(n-1)a_{n-1}$ and let $u_n=(-1)^nna_n$  then $2^n(-1)^n=u_n-u_{n-1}$ so that you have:
$$u_{n}=\sum_{i=1}^n(-1)^i2^i+u_0=\frac{2}{3}\left((-2)^n-1\right)$$
so that $$a_n=\frac{2}{3n}\left((2)^n-(-1)^n\right)$$


text:
Q: unable to to poll the message from the kafka server by using the consumer while I run the java code use the kafka comsumer to poll the message from the kafka server, it always show 0 message,
the kafka server log shows the group error:
[2022-09-08 05:03:03,785] INFO [GroupCoordinator 1]: Dynamic Member with unknown member id joins group KafkaStudy in Empty state. Created a new member id consumer-1-e99d5a30-346b-4e26-8ff5-7f0e5fac3e9b for this member and add to the group. (kafka.coordinator.group.GroupCoordinator)

[2022-09-08 05:03:03,785] INFO [GroupCoordinator 1]: Preparing to rebalance group KafkaStudy in state PreparingRebalance with old generation 27 (__consumer_offsets-15) (reason: Adding new member consumer-1-e99d5a30-346b-4e26-8ff5-7f0e5fac3e9b with group instance id None; client reason: not provided) (kafka.coordinator.group.GroupCoordinator)

[2022-09-08 05:03:03,788] INFO [GroupCoordinator 1]: Stabilized group KafkaStudy generation 28 (__consumer_offsets-15) with 1 members (kafka.coordinator.group.GroupCoordinator)

[2022-09-08 05:03:03,809] INFO [GroupCoordinator 1]: Assignment received from leader consumer-1-e99d5a30-346b-4e26-8ff5-7f0e5fac3e9b for group KafkaStudy for generation 28. The group has 1 members, 0 of which are static. (kafka.coordinator.group.GroupCoordinator)

[2022-09-08 05:03:13,819] INFO [GroupCoordinator 1]: Member consumer-1-e99d5a30-346b-4e26-8ff5-7f0e5fac3e9b in group KafkaStudy has failed, removing it from the group (kafka.coordinator.group.GroupCoordinator)

[2022-09-08 05:03:13,820] INFO [GroupCoordinator 1]: Preparing to rebalance group KafkaStudy in state PreparingRebalance with old generation 28 (__consumer_offsets-15) (reason: removing member consumer-1-e99d5a30-346b-4e26-8ff5-7f0e5fac3e9b on heartbeat expiration) (kafka.coordinator.group.GroupCoordinator)

[2022-09-08 05:03:13,821] INFO [GroupCoordinator 1]: Group KafkaStudy with generation 29 is now empty (__consumer_offsets-15) (kafka.coordinator.group.GroupCoordinator)

the below are code:
 Properties properties = new Properties();
        properties.put("bootstrap.servers","192.168.226.133:9092");
        properties.put("key.deserializer","org.apache.kafka.common.serialization.StringDeserializer");
        properties.put("value.deserializer","org.apache.kafka.common.serialization.StringDeserializer");
        properties.put("enable.auto.commit", true);
        properties.put("group.id","KafkaStudy");
        properties.put("group.instance.id","1");
        consumer = new KafkaConsumer<String, String>(properties);
        consumer.subscribe(Collections.singleton("quickstart-events"));

        try{
               ConsumerRecords<String,String> records = consumer.poll(100);
                for (ConsumerRecord<String, String> record : records) {System.out.println(record.value());}

            } finally{
            consumer.close();
        }

A: By default, the consumer starts at the end of the topic. You need a new group id with
properties.put("auto.offset.reset","earliest");

Or produce data while consumer is running.


text:
Q: Is this virtual member function template? Why does the following code work if virtual is not allowed on class template member functions?
template <typename T>
class Test {

public:

    virtual ~Test() {}
    virtual void Func(const T&) {}
};

A:
...if virtual is not allowed on class template member functions?

I think the issue here is terminological ambiguity:

*

*It is perfectly permissible to have virtual functions inside class templates. In fact, it could be a requirement that Test<T>'s destructor is virtual if you were to subclass Test<T> and delete instances of the subclass through pointers to Test<T>. See When to use virtual destructors? for an extended discussion.

*What you can't do is make function templates virtual. See Can a C++ class member function template be virtual?

A: You have some answers already that explain what's valid and what isn't, but let me try to word it differently to explain the confusion:
"class template member functions" is ambiguous. It could mean member functions of a class template, or it could mean template member functions of a class. The former can be virtual (as long as they themselves are not template member functions), the latter cannot.
It seems as if someone claimed virtual is not allowed on class template member functions, and meant template member functions of a class, but you interpreted it differently.

A: You cannot have templated virtual member functions(more here). What you have is a template class with a virtual member function which is completely fine.

A: the code will not not compile if you use this syntax:
template <typename T> virtual Func(const T&){}

This has not a meaning as virtual function are bounded at runtime to allow dynamic polymorphism but if a function is a template one it's meant to be instantiated at compile time (static polymorphism).
In your case your function is not a template one so it can be declared virtual inside your template class.


text:
Q: How to use passed arguments as default parameter values in Python? Given a function with multiple arguments, where all but the first one are variable.
E.g.:
def f(a, b = .., ...)
I am looking for minimalist python-code that realizes the intuitive code below:
def f(a, b = a, ...)
Hence, I could not find any satisfying answers I am asking here although I am without doubts that the answers to this question have been given already somewhere - in that case i apologize.
Cheers!
I specify by another example my desired functionality again intuitively by wrong code:
def f(a,b,c, d = 0, e = [], f = b, g = c, h = a):
...

Thank you in advance!

A: According to the Python docs:

the expression [used as default parameter value] is evaluated once, when the function is defined, and that the same "pre-computed" value is used for each call.

So what you are trying to achieve would not work so simply because default parameter values are computed only once at the function definition, not at every call.
Instead, you can set all default parameter values to None and test for this value in the body of the function:
def func(a, b, c, d = 0, e = [], f = None, g = None, h = None):
    f = b if f == None else f
    g = c if g == None else g
    h = a if h == None else h


text:
Q: The security context contains no authentication token ESI and Symfony2 I'm using ESI (Edge Side Includes) to speed up my page but every time that I want to check if the user is loged in or not I get this error:

AuthenticationCredentialsNotFoundException: The security context contains no authentication token. One possible reason may be that
  there is no firewall configured for this URL.

In my config.yml file I have this:
  **esi:             true

  fragments:       { path: /_proxy }

  trusted_proxies: [127.0.0.1]**

Does someone knows how to solve it? I already tried to set a firewall for the /_proxy urls but I think that this is not the solution.
These are my firewalls:
main:
   pattern:    ^/
   form_login:
      check_path: /user/login_check
      login_path: /user/login
      provider: chain_provider
      failure_path:   null
   logout:
      path:   /user/logout
      target: /
      success_handler: logout_success_handler
      invalidate_session: true
   anonymous: ~
   security: true
dev:
   pattern:  ^/(_(profiler|wdt)|css|images|js)/
   security: false

Thanks


text:
Q: Need a detail understanding about the slicing based on the below example x = boston_housing.iloc[:,0:3]
Please explain why we need the , and how it slices the dataframe.

A: I just looked at the pandas documentation for iloc and am surprised that this is not directly explained there. However, there are a few examples where you can see the output of your input.
Basically, in your example, you have two arguments (divided by the ,) for the function iloc. The second one is 0:3, which means that you want to select columns 0 to 3 (exclusive). The first argument is only :, which means you want to select all rows. How slicing works in detail can be seen in this answer.
So, why do we need the first argument if it is simply selecting all rows? It is only a placeholder that we need to write the second argument. It is simply necessary if we only want to specify the columns.
To show you what it does here is an example from the docs. Assuming this dataframe:
      a     b     c     d
0     1     2     3     4
1   100   200   300   400
2  1000  2000  3000  4000

if we use df.iloc[:,0:3] the result is:
      a     b     c
0     1     2     3
1   100   200   300
2  1000  2000  3000

As you can see all rows are still there, but only the first, second, and third column are returned.


text:
Q: Salesforce Scheduled flow bulkification best practice/ clarity I have a question about bulkifying scheduled flows. When you create one you have two options. Use a get element to grab the records you want or set an object & conditions. I've found the documentation confusing around which is the preferred method.
My understanding is that when you specify an object the flow will create an individual flow interview for each record. There is a limit of 250,000 flow interviews/24HRs along with all the normal limits. But if you have a sufficiently complex flow and expect it to pull in a large volume of records this is preferable as it prevents you from hitting nodes visited/DML limits.
In the case of using a Get statement, you don't have to worry about the flow interview limit, but you do need to worry about nodes visited/DML limits. Oh! And you get to work with collections!
This makes me think that specifying an object is better for bulkification, I know there are other limits around date/time fields you can use in the criteria that might lead to one or the other, but from a pure bulkification best practices perspective specifying an object is correct?
Can anyone confirm my understanding or explain to me the correct way of thinking?
Additionally - in this help doc. There is the follow:

The maximum number of schedule-triggered flow interviews per 24 hours is 250,000, or the number of user licenses in your org multiplied by 200, whichever is greater. One interview is created for each record retrieved by the schedule-triggered flow's query.If you specify an object so that the flow runs for a batch of records, then set the time, frequency, and record conditions to avoid reaching this limit. You can use debug logs to check how many records a schedule-triggered flow runs on. Track the number of records with the FLOW_START_SCHEDULED_RECORDS event. If your org reaches the limit, Salesforce sends a flow error email.

This seems to indicate that specifying an object is the preferred method, but it's really confusing to me.  Also I'm not sure what it means by the "schedule-triggered flow's query"
Thanks in advance!

A: I got an answer to this from Mikey Brown on the Salesforce community. See Below:

Hey Thomas, I agree with your understanding. As a best practice, I agree that specifying the object up front in the entry conditions of the scheduled flow is the way to go, especially for bulkfication. I know there can be some confusion where admins will set a very generic entry criteria for the scheduled flow, and then use a get records inside the scheduled flow to drilldown to the records they want, but in my opinion, this can degrade performance as it's executing this get records for every iteration of the initial collection of records that met the criteria. It's usually more effective to have your entry criteria essentially be your Get Records element so that everything you need to gather upfront is already collected.  I liken using a Get Records inside a Scheduled Flow similar to using a Get Records inside a Flow Loop. It's not recommended because you can easily hit governor limits (although sometimes it is needed for complex scenarios)


text:
Q: Trouble using percent sign operator (%) (PHP) I'm attempting to convert 7500 seconds to minutes, and then the minutes to hours. If it comes out to 2 hours and 5 minutes, as in this example, I'd like to display it as "2 hours and 5 minutes". If its 2 hours even, I just want it to display "2 hours".
7500 divided by 60 divided by 60 comes out to 2.083 (3 repeated). Why does the % return 0? How can I determine if its hours exactly, or if there are minutes to display?
die("Test: " . ((7500 / 60) / 60) % 1);

A: For conversion, you can use:
function secondsToWords($seconds)
{
    /*** return value ***/
    $ret = "";

    /*** get the hours ***/
    $hours = intval(intval($seconds) / 3600);
    if($hours > 0)
    {
        $ret .= "$hours hours ";
    }
    /*** get the minutes ***/
    $minutes = bcmod((intval($seconds) / 60),60);
    if($hours > 0 || $minutes > 0)
    {
        $ret .= "$minutes minutes ";
    }

    /*** get the seconds ***/
    $seconds = bcmod(intval($seconds),60);
    $ret .= "$seconds seconds";

    return $ret;
}
echo secondsToWords(7500);

A: Because that is the modulus operator, which gives the remainder of the division.
You want to use /, the division operator, that returns a float. See here

A: I've created a nice function for that a while ago. It also does years and months (and anything you'd like) if you want.
Source + examples: http://hotblocks.nl/tests/time_ago.php
Function:
<?php
function time_ago( $f_seconds, $f_size = 2, $f_factor = 1.6 ) {
    $units = array(
        86400*365.25 => array(' year', ' years'),
        86400*30 => array(' month', ' months'),
        86400*7 => array(' week', ' weeks'),
        86400 => array(' day', ' days'),
        3600 => array(' hour', ' hours'),
        60 => array(' minute', ' minutes'),
        1 => array(' second', ' seconds'),
    );

    if ( isset($GLOBALS['g_units']) && is_array($GLOBALS['g_units']) ) {
        $units = $GLOBALS['g_units'];
    }

    $timeAgo = array();

    $seconds = (int)$f_seconds;
    foreach ( $units AS $range => $unit ) {
        if ( 1 == $range || $seconds >= $range * $f_factor ) {
            is_array($unit) || $unit = array($unit, $unit);

            $last = count($timeAgo) == $f_size-1;
            $round = $last ? 'round' : 'floor';

            $num = $round($seconds / $range);
            $timeAgo[] = $num . $unit[(int)(1 != $num)];

            if ( $last ) {
                break;
            }

            $seconds -= $num * $range;
        }
    }

    $separator = isset($GLOBALS['g_separator']) ? $GLOBALS['g_separator'] : ', ';
    return implode($separator, $timeAgo);
}
?>

A: That's the way the mod (%) operator works. Every integer is divisible by 1, so
    n % 1 = 0
for all integral n.
What are you trying to do with the % operator?
Whatever it is, you probably want to apply it on an integral value, like the number of seconds. It doesn't work for non-integral values; they are promoted to int values before the operator is applied.


text:
Q: how to begin learning oracle forms and reports? i have complete sql and plsql course and , i want to begin learn oracle forms and reports
so i want to know how to begin and what i need (books , websites ..)
thanks

A: First get yourself an install of Oracle Forms that you can use for testing and experimenting.  Forms is part of the Oracle Fusion Middleware product now and requires WebLogic Server to be installed.
Take a look at the Oracle Forms page to get info on how to get a development copy downloaded and installed:
http://www.oracle.com/technetwork/developer-tools/forms/overview/index-098877.html
The Oracle Fusion Middleware documentation library is a great resource for tutorials and installation guides.  Use it to learn how to install the product and then start working the tutorials:
https://docs.oracle.com/en/middleware/middleware.html


text:
Q: Read from Blob using Php/Ajax Oracle I am a newbie to PHP development. I want to fetch pdf documents stored in a blob column and display them in href on different pages of my website. But the problem is it shows adobe reader error that says:
"The PDF Document cannot be displayed correctly"
So far (for the sake of simplicity) I have this:

Click here!

PHP code:
<?php
session_start();

$id = $_GET[id];
$conn = OCILogon("abc","abc","abcserver");

$qry = "select blob_file,doc_name from doc_data where ID =".$id;

$stmt = ociparse ($conn,$qry);

OCIDefineByName($stmt,"BLOB_FILE",$blobFile);
OCIDefineByName($stmt,"DOC_NAME",$blobFileName);
OCIExecute($stmt);

while ($rowResult = OCIFetch($stmt))
{
if($rowResult != null){

$a = $rowResult[0];

}
}
header('Content-type: application/pdf');
header('Content-disposition: inline;filename='.$blobFileName.'.pdf');
echo $a;

?>

Please tell me where I am going wrong?

A: Don't know why it makes sense, but I replaced the code from:
while ($rowResult = OCIFetch($stmt))
{
if($rowResult != null){
$a = $rowResult[0];
}

to this:
while ( $row = OCI_Fetch_Array($stmt, OCI_ASSOC+OCI_RETURN_LOBS) )
{
$a = $row['BLOB_FILE'];
}

Keeping the rest of the code same and now it displays all pdf's in the browser beautifully. Chow :)


text:
Q: retrieve table from a web service to wp7 page Is there any way to retrieve a table from  a web service to a wp7 app page as its?
 i just wanna sth easy to use than making a table each time getting data

A: Have look on MSDN for System.Xml namespace. It contains lot of usable classes. You should use XmlReader or something similair to load it to array or generic collection. Hope this helps, 'cause bit unclear question.
EDIT:
This is the code what have I done for loading sample data to generic collection:
Sample data:
<?xml version="1.0" encoding="utf-8" ?>
 <studentPunishmentsTables>
  <studentPunishmentsTable>
    <fromSemester/>
    <fromSemesterDesc/>
    <issueDate>01/04/2012</issueDate>
    <note/>
    <penalty>Course Failure</penalty>
    <semester>311</semester>
    <semesterDesc>First Semester 31/32</semesterDesc>
    <toSemester/>
    <toSemesterDesc/>
  </studentPunishmentsTable>
  <studentPunishmentsTable>
    <fromSemester/>
    <fromSemesterDesc/>
    <issueDate>01/04/2012</issueDate>
    <note/>
    <penalty>Semester Failure</penalty>
    <semester>311</semester>
    <semesterDesc>First Semester 31/32</semesterDesc>
    <toSemester/>
    <toSemesterDesc/>
  </studentPunishmentsTable>
</studentPunishmentsTables>

Code:
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.IO;

namespace XMLStudent
{
    class Program
    {
        static void Main(string[] args)
        {
            XmlDocument doc = new XmlDocument();
            doc.Load("st.xml");
            List<StudentPunishment> sp = new List<StudentPunishment>();
            foreach (XmlNode nod in doc.SelectNodes(@"studentPunishmentsTables/studentPunishmentsTable"))
            {
                StudentPunishment s = new StudentPunishment();
                s.FromSemester = nod.ChildNodes[0].InnerText;
                s.FromSemesterDesc = nod.ChildNodes[1].InnerText;
                s.IssueDate = nod.ChildNodes[2].InnerText;
                s.Note = nod.ChildNodes[3].InnerText;
                s.Penalty = nod.ChildNodes[4].InnerText;
                s.Semester = nod.ChildNodes[5].InnerText;
                s.SemesterDesc = nod.ChildNodes[6].InnerText;
                s.ToSemester = nod.ChildNodes[7].InnerText;
                s.ToSemesterDesc = nod.ChildNodes[8].InnerText;
                sp.Add(s);
            }
            Console.WriteLine(sp[0].IssueDate);
            Console.Read();
        }
    }
    class StudentPunishment
    {
        public string FromSemester { get; set; }
        public string FromSemesterDesc { get; set; }
        public string IssueDate { get; set; }
        public string Note { get; set; }
        public string Penalty { get; set; }
        public string Semester { get; set; }
        public string SemesterDesc { get; set; }
        public string ToSemester { get; set; }
        public string ToSemesterDesc { get; set; }
    }
}

So. This code is loading XMLDocument with sample data and it's selecting data of each studentPunishmentsTable into new object of StudentPunishment class. There're properties for holding that data. After everything is done and object of student's punishment is added into generic collection ('List'), code is trying to show date of first object in collection. You can test is yourself, it's working for me.


text:
Q: Adding Text input to BootStrap 3 Tab I have a bs3 tab panel with 3 tabs. The third tab I'm using as a search button. When the user clicks on the tab it displays the textbox for input.
I'm trying to get the textbox aligned to the left side of the tab. What would be the best way to do that.

Live example at http://jsfiddle.net/xnmktc54/3/
Here is a sample of my html:

Friends

Invite

            <input id="xx" type="text" style="display: none; position: absolute;" />

test 1

test 2

test 3

test 4

A: Remove the inline css and never use any of that again if you can.
input#xx{position:absolute};

override bootstrap.min.css:5
.nav-tabs>li>a {display:inline-block};

A: One way is to add "right:Amount of Pixels You want" to the css code.  See the code below.
<input id="xx" type="text" style="display: none; position: absolute; right:80px;" />

Check it out in this jsfiddle.
http://jsfiddle.net/xnmktc54/11/


text:
Q: Aspect long running - returning object without blocking I have an aspect that does some validation checks before the service API (REST) is executed. This should generally be quick but can be long running (if cache is invalidated) so it's important this code does not block or slow down overall app performance. Does this look fine, or is it recommended (possible?) to have the aspect return a CompletableFuture instead of an Object?
@Around("@within(com.someCustomAnnotation)")
public Object validateUserBeforeServiceCall(ProceedingJoinPoint joinPoint) {
    return longOperation().thenApply(result -> {
       // Some basic quick checks on result here

       return joinPoint.proceed(joinPoint.getArgs());
    }).handle(result, exception) -> {
       // Handle error and log
       return null;
    }
}

private CompletableFuture<String> longOperation() { ... }


text:
Q: Android IBeacon - using a wildcard for proximityUUID in Region with RadiusNetworks API I am using radiusnetworks Android API for my IBeacon service. According to their docs, "When constructing a range, any or all of these fields may be set to null, which indicates that they are a wildcard and will match any value." However, when I create a region with null proximityUUID, I get a null pointer exception. Here is the stack:
Thread [<1> main] (Suspended (exception NullPointerException))
<VM does not provide monitor information>
RegionData(Region).hashCode() line: 140
HashMap.containsKey(Object) line: 332
IBeaconService.startRangingBeaconsInRegion(Region, Callback) line: 262
IBeaconService$IncomingHandler.handleMessage(Message) line: 151
IBeaconService$IncomingHandler(Handler).dispatchMessage(Message) line: 99

This does not happen when I set the proximityUUID to a value. Have anybody used this library and tried to set proximity uuid to null?

A: While the ProximityUuid, major and minor in a Region may be null, you must provide some value for the "uniqueId" which is the first parameter to the constructor:
new Region("com.myappname.myregiondescriptor", null, null, null);

This works, but the following will give you the error you describe:
new Region(null, null, null, null);

That first parameter has nothing to do with the iBeacon identifiers.  It is just used as a unique reference string for your app, so you can cancel ranging/monitoring at a later time by passing the IBeaconManager a region with the same uniqueId string.  You can give it any value you want, but if you start monitoring or ranging on a second Region that has the same uniqueId value, it will replace that Region currently being monitored.


text:
Q: Invalid Control flag, JAVA.IO.FILEPERRMISSION As I am working in a project which uses jaas authorisation after adding policy file I am getting an error as follows:
java.lang.SecurityException: java.io.IOException: Configuration Error:
    Invalid control flag, JAVA.IO.FILEPERMISSION
    at java.base/sun.security.provider.ConfigFile$Spi.<init>(ConfigFile.java:139)
    at java.base/sun.security.provider.ConfigFile.<init>(ConfigFile.java:104)
    at java.base/jdk.internal.reflect.DirectConstructorHandleAccessor.newInstance(DirectConstructorHandleAccessor.java:67)
    at java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:499)
    at java.base/java.lang.reflect.ReflectAccess.newInstance(ReflectAccess.java:128)
    at java.base/jdk.internal.reflect.ReflectionFactory.newInstance(ReflectionFactory.java:341)
    at java.base/java.lang.Class.newInstance(Class.java:677)
    at java.base/javax.security.auth.login.Configuration$2.run(Configuration.java:258)
    at java.base/javax.security.auth.login.Configuration$2.run(Configuration.java:249)
    at java.base/java.security.AccessController.doPrivileged(AccessController.java:569)
    at java.base/javax.security.auth.login.Configuration.getConfiguration(Configuration.java:248)
    at java.base/javax.security.auth.login.LoginContext$1.run(LoginContext.java:250)
    at java.base/javax.security.auth.login.LoginContext$1.run(LoginContext.java:248)
    at java.base/java.security.AccessController.doPrivileged(AccessController.java:318)
    at java.base/javax.security.auth.login.LoginContext.init(LoginContext.java:248)
    at java.base/javax.security.auth.login.LoginContext.<init>(LoginContext.java:423)
    at Authenticate.doPost(Authenticate.java:21)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:681)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:764)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:227)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:197)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:135)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:687)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:360)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:399)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:890)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1789)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191)
    at org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.base/java.lang.Thread.run(Thread.java:833)

Caused by: java.io.IOException: Configuration Error:
Invalid control flag, JAVA.IO.FILEPERMISSION
at java.base/sun.security.provider.ConfigFile$Spi.ioException(ConfigFile.java:669)
at java.base/sun.security.provider.ConfigFile$Spi.parseLoginEntry(ConfigFile.java:472)
at java.base/sun.security.provider.ConfigFile$Spi.readConfig(ConfigFile.java:430)
at java.base/sun.security.provider.ConfigFile$Spi.init(ConfigFile.java:332)
at java.base/sun.security.provider.ConfigFile$Spi.init(ConfigFile.java:296)
at java.base/sun.security.provider.ConfigFile$Spi.(ConfigFile.java:137)
//My policy file contains the following code
    ```grant {"file:C:/Program Files/Apache Software Foundation/Tomcat 9.0/webapps/doctor/admin.html" required Principal="C/Program Files/Apache Software Foundation/Tomcat 9.0/webapps/doctor/WEB-INF/classes/java-files/DaPrincipal.java" ;}; "Admin" {  Permission java.io.FilePermission "read,write";};```


text:
Q: Two Column Div Layout in Wrapper - Why is one getting pushed down? url: http://www.5vforest.net/#portfolio
#portfolio .projectWrapper{
width: 100%;
float: left;
}

.projectLeft{
font-size: 10pt;
padding-top: 10px;
margin-right: 500px;
}

.projectRight{
width: 500px;
text-align: right;
float: right;
}

No idea why this isn't working.... I'm totally stumped. Any advice? Thanks.

A: You can make it work by moving
..
 to before
..
 in the HTML.

A: Because there is no space for it. Project left has a 500px margin right which is pushing it down.
.projectLeft {
    font-size: 10pt;
    padding-top: 10px;
    width: 500px; // other div must have fluid space, thanks thirtydot
    float: left;
}

A: both columns should float:
.projectLeft{
font-size: 10pt;
padding-top: 10px;
float:left;
//the width you need
width: 500px

}

.projectRight{
width: 500px;
text-align: right;
float: right;
}


text:
Q: What does it mean if macros in a Lisp are monadic? In the Lux Language introduction we read:

Unlike in most other lisps, Lux macros are monadic. The (Lux a) type is the one responsibly for the magic by threading Compiler instances through macros. Macros must have the Macro type and then be declared as macros.

Now I assume that this means that additional type checking information is available at compile time giving you some feedback on the correctness of your code.
But what could be incorrect about a macro that you could find out at compile-time?
My question is: What does it mean if macros in a Lisp are monadic?

A: From a cursory glance, it seems both "normal" macros and reader macros are monadic in Lux.
For normal macros, they are threading a state of type Compiler through. Various macro operations (I imagine gensyming would be an obvious example) require changing this internal state, since they rely on stateful effects like maintaining the next available fresh atom. Threading state (i.e. functions that look like s -> (a, s), getting the initial state as the argument and returning the updated state and the result) exhibits an obviously monadic structure, i.e. given some first step s -> (a, s), choosing the next step s -> (b, s) can depend on looking at the intermediate result a.
For reader macros, it is a similar story, except the effect in question is the consumption of input. A monadic parser is one that allows previously consumed input to affect the way subsequent input is parsed.


text:
Q: XSLT 2: Add an element with an incremented value to a list I am new to XSLT and have spent hours trying to figure out a solution to a problem that seems to look kind of trivial.
I have a xml document which contains a list like that:
  <Header>
    <URLList>
      <URLItem type="type1">
        <URL></URL>
      </URLItem>
      <URLItem type="type2">
        <URL>2</URL>
      </URLItem>
    </URLList>
  </Header>

If it doesn't exist, I now need to add an "ID" Element to each URLItem. The value of the ID Element has to be an incremented value.
The xml should look like this in the end:
  <Header>
    <URLList>
      <URLItem type="type1">
        <ID>1</ID>
        <URL></URL>
      </URLItem>
      <URLItem type="type2">
        <ID>2</ID>
        <URL>2</URL>
      </URLItem>
    </URLList>
  </Header>

I have been trying various things, but could not get it working correctly.
For instance, if I try to use a template to match the List, I am not able to get the correct incremented value. The ID value is [2,4], but not [1,2] as it should... This is the xslt:
  <xsl:template match="/Header/URLList/URLItem[not(child::ID)]">
    <xsl:copy>
      <ID> <xsl:value-of select="position()"/></ID>
      <xsl:apply-templates select="@* | node()"/>
    </xsl:copy>
  </xsl:template>

I have been also trying to use a for-each loop like this:
  <xsl:template match="/Header/URLList">
    <xsl:copy>
      <xsl:apply-templates select="@* | node()"/>
    </xsl:copy>
    <xsl:for-each select="/Header/URLList/URLItem">
        <xsl:if test="not(ID)">
          <xsl:element name="ID"><xsl:value-of select="position()" /></xsl:element>
        </xsl:if>
    </xsl:for-each>
  </xsl:template>

This way I seem to get the increment right, but the new ID Elements appear at the parent node. I haven't been able to find a way to attach them as a child of the URLItem element.
Any help greatly appreciated.

A: Instead of
  <xsl:template match="/Header/URLList/URLItem[not(child::ID)]">
    <xsl:copy>
      <ID> <xsl:value-of select="position()"/></ID>
      <xsl:apply-templates select="@* | node()"/>
    </xsl:copy>
  </xsl:template>

use
  <xsl:template match="/Header/URLList/URLItem[not(child::ID)]">
    <xsl:copy>
      <xsl:apply-templates select="@*"/>
      <ID><xsl:number/></ID>
      <xsl:apply-templates/>
    </xsl:copy>
  </xsl:template>

A: <?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml"/>
<xsl:template match="/">
<Header>
<xsl:apply-templates select="//URLList"/>
</Header>
</xsl:template>
<xsl:template match="URLList">
<URLList>
<xsl:for-each select="URLItem[not(child::ID)]">
<xsl:copy>
    <xsl:apply-templates select="@*"/>
      <ID> <xsl:value-of select="position()"/></ID>
      <xsl:copy-of select="URL"/>
    </xsl:copy>
  </xsl:for-each>
  </URLList>
  </xsl:template>
  <xsl:template match="@*">
<xsl:copy-of select="."/>
  </xsl:template>
</xsl:stylesheet>


text:
Q: Would it be possible to use a Socket IO connection on multiple pages with PersistJS? If I would store the Socket IO connection variable using something like PersistJS, would the connection and its events still work if navigating to another page and loading the Socket IO connection variable from PersistJS?
For example

*

*Connect using Socket IO (or WebSockets)

*Store the connection var to JS session, e.g. PersistJS

*Navigate to another page

*Load the Socket IO var from PersistJS, if it exists

*Are the socket IO connection + events restored?
The purpose would be to keep the Socket IO connection active between the browsing of pages. A delay to load it again is acceptable.
I'm guessing the events attached to Socket IO messages will be removed, or something might be wrong with the connection.


text:
Q: Regarding element-wise derivative of matrices
Let $X=(x_{ij})$ be a real n-by-n matrix where $x_{ij}$ are in a range such that $X$ is insvertible. Let $Y=X^{-1}=(y_{pq})$, and regard  $y_{pq}=y_{pq} (x_{11},x_{12},\ldots,x_{nn})$ as a function of $x_{ij}$. Prove that $\frac{\partial y_{pq}}{\partial . x_{ij}}=-y_{pi}y_{jq}.$.

Any solution to prove this in a right way would be appreciated. And is there any name for this type of derivative? How can I handle it?
And the followings are some non-sense scribbles I've made
$XY=I$
${d(XY)\over dx}=IY+X{dY\over dx}=O$
${\partial Y\over \partial x_{ij}}=-X^{-1}Y=-Y^2$
$\frac{\partial y_{pq}}{\partial x_{ij}}=-y_{pi}y_{jq}.$.
Is there any why this can be justified?

A: I guess the argument is cleaner if you use:
$$
0=\frac{\partial (XY)}{\partial x_{ij}} =\frac{\partial X}{\partial x_{ij}}Y+ X\frac{\partial Y}{\partial x_{ij}}
$$
So
$$
\frac{\partial Y}{\partial x_{ij}}=-X^{-1}\frac{\partial X}{\partial x_{ij}}Y=-Y\frac{\partial X}{\partial x_{ij}}Y
$$
So taking the $(l,k)$ matrix entry in the previous equation we get:
$$
\frac{\partial y_{lk}}{\partial x_{ij}}=-\sum_{m,n} y_{ln}\left(\frac{\partial X}{\partial x_{ij}}\right)_{nm}y_{mk}
$$
And $\left(\frac{\partial X}{\partial x_{ij}}\right)_{nm}=\delta_{in}\delta_{jm}$ so:
$$
\frac{\partial y_{lk}}{\partial x_{ij}}=-\sum_{m,n} y_{ln}\delta_{in}\delta_{jm}y_{mk}=-y_{li}y_{jk}
$$

A: $\frac{\partial X}{\partial x_{ij}} = \frac{\partial x_{pq}}{\partial x_{ij}} = \delta_{pi}\delta_{jq}$ is a 4th order tensor.
$I = \delta_{pq}$ is a 2nd order tensor (or a matrix).
So be careful, $\frac{\partial X}{\partial x_{ij}} \neq I$
$XY=I \Leftrightarrow x_{pk}y_{kq} = \delta_{pq}$
$\frac{\partial (x_{pk}y_{kq})}{\partial x_{ij}} = O_{pqij}$, where O is the null 4th order tensor.
$\frac{\partial x_{pk}}{\partial x_{ij}}y_{kq} + x_{pk}\frac{\partial y_{kq}}{\partial x_{ij}} = O_{pqij}$
$x_{pk}\frac{\partial y_{kq}}{\partial x_{ij}} = -\frac{\partial x_{pk}}{\partial x_{ij}}y_{kq} = -\delta_{pi}\delta_{jk}y_{kq} = -\delta_{pi}y_{jq}$
$y_{pt}x_{tk}\frac{\partial y_{kq}}{\partial x_{ij}} = -y_{pt}\delta_{ti}y_{jq}$
$\delta_{pk}\frac{\partial y_{kq}}{\partial x_{ij}} = -y_{pi}y_{jq}$

$\frac{\partial y_{pq}}{\partial x_{ij}} = -y_{pi}y_{jq}$


text:
Q: How would a hacker be able to spoof their IP when logging into a private FTP server? If, somehow, someone gains access to one of the users on my FTP server, I would still be able to see their IP address and trace it to them. However, I fear that it might be possible for them to spoof their IP address when logging in. Is this possible, and how would they do it?

A: Yes, They can spoof their IP.
The obvious one - as mentioned in the comments is to use a VPN, however there are more other ways, which boil down to the same thing - use an intermediary server.  These include -

*

*Virtual Machines set up with SSH.

*Proxy servers which support FTP.

*Hacked websites with scripts to run FTP from those boxes.

*Use a jump box / Bastion / SSH gateway.

*Hacked systems the ftp user has compromised.


text:
Q: Why my python package doesn't install in my virtualenv? I made my own package, I succesfully installed it in my global pip with the command python setup.py install (from the directory where the code is) but when I tried the same command in a virtualenv everything seems to work but when I look at my pip list package of this virtualenv I can't see my package and I can't import it in my interpreter.
The same result happen when I use pip install .
Output of the python setup.py install
(fig_local_analysis_virginia) ➜  parser_cvat git:(main) python setup.py install
running install
/home/r2p2/Documents/virginia_project/fig_local_analysis/fig_local_analysis_virginia/lib/python3.8/site-packages/setuptools/command/install.py:34: SetuptoolsDeprecationWarning: setup.py install is deprecated. Use build and pip and other standards-based tools.
  warnings.warn(
/home/r2p2/Documents/virginia_project/fig_local_analysis/fig_local_analysis_virginia/lib/python3.8/site-packages/setuptools/command/easy_install.py:144: EasyInstallDeprecationWarning: easy_install command is deprecated. Use build and pip and other standards-based tools.
  warnings.warn(
running bdist_egg
running egg_info
writing cvat_parser.egg-info/PKG-INFO
writing dependency_links to cvat_parser.egg-info/dependency_links.txt
writing top-level names to cvat_parser.egg-info/top_level.txt
reading manifest file 'cvat_parser.egg-info/SOURCES.txt'
adding license file 'LICENSE.md'
writing manifest file 'cvat_parser.egg-info/SOURCES.txt'
installing library code to build/bdist.linux-x86_64/egg
running install_lib
running build_py
creating build/bdist.linux-x86_64/egg
creating build/bdist.linux-x86_64/egg/cvat_parser
copying build/lib/cvat_parser/parsing_cvat_file.py -> build/bdist.linux-x86_64/egg/cvat_parser
copying build/lib/cvat_parser/cvat_annotation_on_image.py -> build/bdist.linux-x86_64/egg/cvat_parser
copying build/lib/cvat_parser/type_cvat_parser.py -> build/bdist.linux-x86_64/egg/cvat_parser
copying build/lib/cvat_parser/__init__.py -> build/bdist.linux-x86_64/egg/cvat_parser
byte-compiling build/bdist.linux-x86_64/egg/cvat_parser/parsing_cvat_file.py to parsing_cvat_file.cpython-38.pyc
byte-compiling build/bdist.linux-x86_64/egg/cvat_parser/cvat_annotation_on_image.py to cvat_annotation_on_image.cpython-38.pyc
byte-compiling build/bdist.linux-x86_64/egg/cvat_parser/type_cvat_parser.py to type_cvat_parser.cpython-38.pyc
byte-compiling build/bdist.linux-x86_64/egg/cvat_parser/__init__.py to __init__.cpython-38.pyc
creating build/bdist.linux-x86_64/egg/EGG-INFO
copying cvat_parser.egg-info/PKG-INFO -> build/bdist.linux-x86_64/egg/EGG-INFO
copying cvat_parser.egg-info/SOURCES.txt -> build/bdist.linux-x86_64/egg/EGG-INFO
copying cvat_parser.egg-info/dependency_links.txt -> build/bdist.linux-x86_64/egg/EGG-INFO
copying cvat_parser.egg-info/top_level.txt -> build/bdist.linux-x86_64/egg/EGG-INFO
zip_safe flag not set; analyzing archive contents...
creating 'dist/cvat_parser-0.0.1-py3.8.egg' and adding 'build/bdist.linux-x86_64/egg' to it
removing 'build/bdist.linux-x86_64/egg' (and everything under it)
Processing cvat_parser-0.0.1-py3.8.egg
Removing /home/r2p2/Documents/virginia_project/fig_local_analysis/fig_local_analysis_virginia/lib/python3.8/site-packages/cvat_parser-0.0.1-py3.8.egg
Copying cvat_parser-0.0.1-py3.8.egg to /home/r2p2/Documents/virginia_project/fig_local_analysis/fig_local_analysis_virginia/lib/python3.8/site-packages
cvat-parser 0.0.1 is already the active version in easy-install.pth

Installed /home/r2p2/Documents/virginia_project/fig_local_analysis/fig_local_analysis_virginia/lib/python3.8/site-packages/cvat_parser-0.0.1-py3.8.egg
Processing dependencies for cvat-parser==0.0.1
Finished processing dependencies for cvat-parser==0.0.1
(fig_local_analysis_virginia) ➜  parser_cvat git:(main)

Output of the pip install .
(fig_local_analysis_virginia) ➜  parser_cvat git:(main) pip install .
Processing /home/r2p2/Documents/virginia_project/parser_cvat
Building wheels for collected packages: cvat-parser
  Building wheel for cvat-parser (setup.py) ... done
  Created wheel for cvat-parser: filename=cvat_parser-0.0.1-py3-none-any.whl size=4347 sha256=fa0071a7de37749cb311cf366e265d602a6b790e9a95a26f9ece7b949d34b626
  Stored in directory: /tmp/pip-ephem-wheel-cache-zod4lic_/wheels/8a/db/73/568b5ff251d9fbb587cce00359c1099410982cce7baca6b78e
Successfully built cvat-parser
Installing collected packages: cvat-parser
  Attempting uninstall: cvat-parser
    Found existing installation: cvat-parser 0.0.1
    Uninstalling cvat-parser-0.0.1:
      Successfully uninstalled cvat-parser-0.0.1
Successfully installed cvat-parser-0.0.1
(fig_local_analysis_virginia) ➜  parser_cvat git:(main)

I use the which python command to be sure to use the good version of python
fig_local_analysis_virginia) ➜  parser_cvat git:(main) which python
/home/r2p2/Documents/virginia_project/fig_local_analysis/fig_local_analysis_virginia/bin/python
(fig_local_analysis_virginia) ➜  parser_cvat git:(main)

my version of pip is 22.2.2
my version of python is 3.8.10

A: There was 2 problems the first one was that my pip in virtualenv was not updated (I always have to update it manually) and the second problem was a typo in the name of the package.


text:
Q: password checking function with preg_match i have this function:
public static function encPasswordCheckFailed($password)
    {
        if (!preg_match('/[A-Z]+/', $password)){
            return true;
        }
        if (!preg_match('/[a-z]+/', $password)){
            return true;
        }
        if (!preg_match('/[0-9]+/', $password)){
            return true;
        }
        if (!preg_match('/[!@#$%^&*()-+<>]+/', $password)) {
            return true;
        }

        return false;
    }

and now i want to force the user to have at least 1 Uppercased Letter, 1 Lowercased Letter, 1 Number and 1 Specialcharacter.
I'm having the problem with this:
if (!preg_match('/[!@#$%^&*()-+<>]+/', $password)) {
    return true;
}

All other requirements work. I have only a problem with the specialcharacters.
Can someone tell me the correct pattern for these specialcharacters: !@#$%^&*()-+<>
i've read some of the answers from here, here and here but they didn't help me further...

A:
You may need to escape some special characters used by the Regex Engine. And by the way, you could as well do that in one Go as shown below. Quick-Test Here.

<?php

    /*public static*/ function encPasswordCheckFailed($password) {
        // THIS READS:
        // IF THE PASSWORD DOES CONTAIN AN UPPER-CASE CHARACTER
        // AND ALSO DOES CONTAIN A LOWER-CASE CHARACTER
        // AND STILL DOES CONTAIN A NUMERIC CHARACTER
        // AND EVEN MORE, DOES CONTAIN ANY  OF THE SPECIFIED SPECIAL CHARACTERS
        // RETURN FALSE OTHERWISE RETURN TRUE
        if (preg_match('/[A-Z]+/', $password) &&                    // CHECK FOR UPPERCASE CHARACTER
            preg_match('/[a-z]+/', $password) &&                    // AND CHECK FOR LOWERCASE CHARACTER
            preg_match('/[0-9]+/', $password)&&                     // AND CHECK FOR NUMERIC CHARACTER
            preg_match('/[\!@#$%\^&\*\(\)\-\+<>]+/', $password)     // AND CHECK FOR SPECIAL CHARACTER
        ) {
            return false;
        }

        return true;
    }

    var_dump( encPasswordCheckFailed("abcd123") );    //<== boolean true
    var_dump( encPasswordCheckFailed("abcD123") );    //<== boolean true
    var_dump( encPasswordCheckFailed("abcD1@23-") );  //<== boolean false

A: The dash/minus character is your issue, as when inside a character group, it denotes a character range.
You need to either:

*

*Escape it with a backslash, so that it isn't treated as a special character:
/[!@#$%^&*()\-+<>]+/

*Or put it at the end of the pattern, so the PCRE engine knows it can't possibly denote a range:
/[!@#$%^&*()+<>-]+/
Similarly, the caret (^) is also a special character, denoting negation when inside a character group, but because you didn't put it at the very first position inside the character group, the PCRE engine knows it has no special meaning in your case.

A: This will gonna work for special characters:
preg_match('/\[!@#$%^&*\(\)\-+<>\]+/', $password);

If it's not working, look down:

OTHER ANSWERS:

*

*preg_match php special characters (pmm's answer)


text:
Q: Battery indicator stuck at 98% percentage Ubuntu 13.10 64-bit, used to work fine but lately battery applet with percentage says 98% at boot but doesn't drain (though obviously battery is draining).
How can I reboot the applet/make it work normally? Tried to end session, suspend, reboot...
didn't work. It, for some weeks, works fine, and for some others like this. I'm upset (being an average user without any special knowledge, just type in the console what others more capable say).
I'm on an ACER Aspire Timeline U Intel® Core™ i3-2367M CPU @ 1.40GHz × 4, Intel® Sandybridge Mobile graphics.
Thanks for the help!


text:
Q: mv cdable_vars - where has my .bashrc gone? I thought it would be clever to have an alias to my dotfiles repo, where I keep my dotfiles such as .bashrc.
Following a recommendation, I added this to my .bashrc:
shopt -s cdable_vars
export dotfiles=$HOME/dotfiles/

Then I wanted to test, by moving my bashrc to dotfiles with:
mv .bashrc dotfiles

However, the bashrc never appeared in $HOME/dotfiles/ - it's also not in my home folder anymore.
Anyone knows where it could be gone?

A: How to stop it happening again
Use the -t or -T options of mv and cp
SYNOPSIS
       mv [OPTION]... [-T] SOURCE DEST
       mv [OPTION]... SOURCE... DIRECTORY
       mv [OPTION]... -t DIRECTORY SOURCE...

so for your example
mv -t dotfiles/ .bashrc
If your cp and mv dose not have option -t, then you can do
mv .bashrc dotfiles/
There is no alternative to -T.

A: Found it:
cd ~
nano dotfiles

I renamed .bashrc to dotfiles...
:embarrassing:


text:
Q: How calculate variance-covariance matrix of coefficients for multivariate (multiple) linear regression? How to calculate a variance-covariance matrix of coefficients for multivariate (multiple)  linear regression?
Something like (equation below), but for the multivariate case.
Being more specific I'm interested in equations for diagonal terms.

The question is different from:
How to derive variance-covariance matrix of coefficients in linear regression
Because of the MULTIVARIATE regression case.

A: The general equation is the same for both the univariate and multivariate cases,
$$
V[\hat{\beta}] = V[(X^{T}X)^{-1}X^{T}Y]\\
= (X^{T}X)^{-1}X^{T}V[Y]X(X^{T}X)^{-1}\\ = \sigma^2(X^{T}X)^{-1}
$$
This is unfortunately challenging to calculate. Examining $X^{T}X$ we see (assuming an intercept is included in the model),
$$X^{T}X = \begin{bmatrix}
n & \sum_{i=1}^{n}x_{i1} & \sum_{i=1}^{n}x_{i2} & \ldots& \sum_{i=1}^{n}x_{ik}\\
\sum_{i=1}^{n} x_{i1} & \sum_{i=1}^{n} x_{i1}^2 & \sum_{i=1}^{n} x_{i1}x_{i2} & \ldots & \sum_{i=1}^{n}x_{i1}x_{ik} \\
\vdots & \vdots & \vdots & & \vdots\\
\sum_{i=1}^{n}x_{ik} & \sum_{i=1}^{n} x_{ik}x_{i1} & \sum_{i=1}^{n} x_{ik}x_{i2} & \ldots & \sum_{i=1}^{n} x_{ik}^2
\end{bmatrix}$$
which is symmetric, but does not have a clean expression for the inverse. Therefore the simple formulas for the univariate case are not available for the multivariate case.


text:
Q: PHP: Upload Video File via Youtube API v3 that logins automatically without user interaction I would like to upload a video-file with PHP and the YouTube Data Api v3.
The PHP file should

*

*automatically log in to the YouTube Data API

*upload a video file

so that the user does not have to login manually.
The goal is to allow a user to be able to upload a video to YouTube via app or website without needing to login to google first.
This is the code I am using:
<?php

if (!file_exists(__DIR__ . '/youtubeapi/vendor/autoload.php')) {
    throw new Exception(sprintf('Please run "composer require google/apiclient:~2.0" in "%s"', __DIR__));
    }

require_once __DIR__ . '/youtubeapi/vendor/autoload.php';

putenv('GOOGLE_APPLICATION_CREDENTIALS=service_credentials.json');
$client = new Google_Client();
$client->setScopes([
    'https://www.googleapis.com/auth/youtube',
    'https://www.googleapis.com/auth/youtube.force-ssl',
    'https://www.googleapis.com/auth/youtube.upload',
    'https://www.googleapis.com/auth/youtubepartner-channel-audit',
    'https://www.googleapis.com/auth/youtubepartner'
]);
$client->useApplicationDefaultCredentials();

// Define service object for making API requests.
$service = new Google_Service_YouTube($client);

// Define the $video object, which will be uploaded as the request body.
$video = new Google_Service_YouTube_Video($client);

// Add 'snippet' object to the $video object.
$videoSnippet = new Google_Service_YouTube_VideoSnippet($client);
$videoSnippet->setCategoryId('22');
$videoSnippet->setDescription('Description of uploaded video.');
$videoSnippet->setTitle('Test video upload.');
$video->setSnippet($videoSnippet);

// Add 'status' object to the $video object.
$videoStatus = new Google_Service_YouTube_VideoStatus($client);
$videoStatus->setPrivacyStatus('private');
$video->setStatus($videoStatus);

// TODO: For this request to work, you must replace "YOUR_FILE"
//       with a pointer to the actual file you are uploading.
//       The maximum file size for this operation is 128GB.
$response = $service->videos->insert(
  'snippet,status',
  $video,
  array(
    'data' => file_get_contents("big_buck_bunny.mp4"),
    'mimeType' => 'video/*',
    'uploadType' => 'multipart'
  )
);
print_r($response);

?>

And this is the error I get:
> Fatal error: Uncaught Google_Service_Exception: { "error": { "errors":
> [ { "domain": "youtube.header", "reason": "youtubeSignupRequired",
> "message": "Unauthorized", "locationType": "header", "location":
> "Authorization" } ], "code": 401, "message": "Unauthorized" } } in
> /homepages/37/d797893845/htdocs/development/sitesmedia/youtube/youtubeapi/src/Google/Http/REST.php:118
> Stack trace: #0
> /homepages/37/d797893845/htdocs/development/sitesmedia/youtube/youtubeapi/src/Google/Http/REST.php(94):
> Google_Http_REST::decodeHttpResponse(Object(GuzzleHttp\Psr7\Response),
> Object(GuzzleHttp\Psr7\Request), 'Google_Service_...') #1
> /homepages/37/d797893845/htdocs/development/sitesmedia/youtube/youtubeapi/src/Google/Task/Runner.php(176):
> Google_Http_REST::doExecute(Object(GuzzleHttp\Client),
> Object(GuzzleHttp\Psr7\Request), 'Google_Service_...') #2
> /homepages/37/d797893845/htdocs/development/sitesmedia/youtube/youtubeapi/src/Google/Http/REST.php(58):
> Google_Task_Runner->run() #3 /homepages/37/d797893845/ in
> /homepages/37/d797893845/htdocs/development/sitesmedia/youtube/youtubeapi/src/Google/Http/REST.php
> on line 118

A: It looks like YouTube does not support service accounts.
https://developers.google.com/youtube/v3/docs/errors

unauthorized (401)  youtubeSignupRequired This error indicates that the user has an unlinked Google Account, which means that the user has
  a Google Account but does not have a YouTube channel. Such users can
  access many features that are dependent on user authorization, such as
  rating videos or adding videos to a watch_later playlist. However, as
  an example, the user would need a YouTube channel to be able to upload
  a video. A user who has a Gmail account or an Android device is
  certain to have a Google Account but may not have already linked that
  Google Account to a YouTube channel.
This error is commonly seen if you try to use the OAuth 2.0 Service Account flow. YouTube does not support Service Accounts, and if you
  attempt to authenticate using a Service Account, you will get this
  error.
The YouTube API blog post introducing Google Account support also
  discusses the youtubeSignupRequired error in more detail. Although the
  blog post explains the error for API version 2.1, the meaning of the
  error is still applicable.

Sounds like you're going to have to create a YouTube channel and then authenticate the requests that way.
https://developers.google.com/youtube/registering_an_application


text:
Q: tailwindcss hidden class in table header / row I'm trying to create a responsive table layout in tailwindcss where certain columns will be hidden if the display size is mobile.
I'm adding hidden sm:inline-block to the th and td values that I want hidden, but the inline-block display breaks the normal flow of the table. I've tried block, flex, inline-flex, etc. but they all mess with the layout of the header and columns when viewed at the larger screen sizes.
What is the "normal" display for these elements that should be used in the breakpoint directive instead of inline-flex?
Here's a look at the code, by removing the hidden sm:inline-block you can see what should be displayed vs. what is displayed.
https://play.tailwindcss.com/jyMaE0MVWx

A: The default is display: table-cell so setting sm:table-cell should do the trick. Here is a remix of your play https://play.tailwindcss.com/g7PJ6ETsX5
Edit: You can always find the default display property for an element in the inspector inside the computed properties tab.


text:
Q: How can I add new colors to SCSS map $theme-colors to generate new classes? This is in my SCSS file
@import "../node_modules/bootstrap/scss/bootstrap.scss";

$custom-colors: (
  "custom-color": #900
);

// Merge the maps
$theme-colors: map-merge($theme-colors, $custom-colors);

This is what should work then:

Text

I read bootstrap will generate new classes if I add variables to $theme-colors map (text-custom-color, bg-custom-color etc. when I add custom-color to the map). How else would I customize the $theme-colors map than like this? Why doesnt the customization work on the code below:


text:
Q: How to calculate values according to the a value's nth occurances in pandas? For example, I have a data frame as follows:
df = pd.DataFrame()
df['Name'] = ['Ankita', 'Ankita', 'Ankita', 'Ankita', 'Ankita', 'Yashvardhan', 'Yashvardhan', 'Yashvardhan', 'Yashvardhan', 'Yashvardhan']
df['Date'] = ['2014-10-07', '2015-03-30', '2015-12-07', '2015-12-09', '2017-01-30', '2017-01-30', '2018-02-19', '2018-02-23', '2018-11-19', '2020-01-23']
df['Value'] = [2200, 75, 100, 22, 98, 0.36, 57, 29, 1026, 1296]
df['Date'] = pd.to_datetime(df['Date'])

    Name    Date    Value
0   Ankita  2014-10-07  2200.00
1   Ankita  2015-03-30  75.00
2   Ankita  2015-12-07  100.00
3   Ankita  2015-12-09  22.00
4   Ankita  2017-01-30  98.00
5   Yashvardhan 2017-01-30  0.36
6   Yashvardhan 2018-02-19  57.00
7   Yashvardhan 2018-02-23  29.00
8   Yashvardhan 2018-11-19  1026.00
9   Yashvardhan 2020-01-23  1296.00

How can I calculate the average Value of only the earliest 3 entries of Ankita (expecting to be 791.67) and Yashvardhan (expecting to be 28.79)? And how can I calculate the average value of only the 4th and 5th earliest entries for Ankita (expecting to be 60) and Yashvardhan (expecting to be 1161)?
I tried some manipulations with value_counts(), but I couldn't figure it out. Does anyone know the answer to such a problem? Thanks in advance!

A: You can manage this with boolean indexing and the groupby/transform function: .rank()
For your first case, the mean of the earliest 3 entries per person:
To get the rows you want:
In [23]: dfg = df[df.groupby('Name')['Date'].rank(ascending=True) <= 3]

In [24]: dfg
Out[24]:
          Name       Date    Value
0       Ankita 2014-10-07  2200.00
1       Ankita 2015-03-30    75.00
2       Ankita 2015-12-07   100.00
5  Yashvardhan 2017-01-30     0.36
6  Yashvardhan 2018-02-19    57.00
7  Yashvardhan 2018-02-23    29.00

To then get the means of the 'Value' column per person:
In [28]: dfg.groupby('Name')['Value'].mean()
Out[28]:
Name
Ankita         791.666667
Yashvardhan     28.786667
Name: Value, dtype: float64

The rank values could be given as a list for specific values rather than the comparison, and these could be chained together in a one-liner as well:
In [29]: df[df.groupby('Name')['Date'].rank() <= 3].groupby('Name')['Value'].mean()
Out[29]:
Name
Ankita         791.666667
Yashvardhan     28.786667
Name: Value, dtype: float64

In [30]: df[df.groupby('Name')['Date'].rank().isin([4,5])].groupby('Name')['Value'].mean()
Out[30]:
Name
Ankita           60.0
Yashvardhan    1161.0
Name: Value, dtype: float64


text:
Q: Do line level circuits need shielded enclosures? I made a quick volume pedal, just a button, 50k pot, input and output jacks
I used a plastic enclosure for it since it was convenient, but I realized almost all guitar pedals and other stomp boxes are metal. Not only does this help with durability, but it acts as a Faraday cage. Connected to ground, it reduces noise, just like a shielded cable. Is this necessary? I can line the inside with aluminum foil, but it would be annoying to do so, and not sure if it's necessary.
Moreover, I am curious about what is the best practice here.
Does a line level circuit like a volume pedal need a shielded enclosure? (I don't plan on ever using this for something pickup level also.)

A:
Does a line level circuit like a volume pedal need a shielded enclosure?

No, But if you put your cell phone right next to a plastic box with a high impedance signal loop, poorly designed on the high impedance input, you might be able to pickup the tower re-sync transmissions. dah-dit-da-dit...  This RF often comes from input diode carrier demodulation to baseband and can be suppressed with an RF shunt cap.
Most poor SNR situations come in from radiated noise induced into conducted noise on the signal cables and from poor HF ripple on floating DC supplies.
This current transfers into a voltage from unbalanced impedances for signal and return.
A range of supply capacitors for DC ought to be included from 0.01uF to 10uF to suppress AC hum to RF induced noise currents.

A: I'm just a hobbyist at best, but you mentioned lining the inside with aluminum foil, and I have done this before.  It wasn't a volume pedal, but it was cheap little stereo.   It was about as cheap as they come: it probably came from a drug store and sold for about US $20 (about 15 years ago). And this thing wasn't just inexpensive (which doesn't necessarily mean low quality), but this thing was CHEAP! It had an FM radio that sported a digital readout of the station it was tuned to, which was purely for looks, After opening it, I saw that it was just and old style mechanical tuner! I can't say if that technology was bad in general, but this thing was. Anyway, it's not surprising that it had an annoying hum coming out of the speakers. So I decided to shield the enclosure from the inside like you mentioned. I didn't use aluminum foil, but I used adhesive backed foil tape which is fairly common (used for duct work maybe?)  You're right, that can be a tedious task, I think I spent a good week or two on the project. The metal can't be soldered, which meant mechanical connections throughout! The CD player was broken, so I had line inputs free, so I gave it 1/4" jacks for guitar/musical gear. It turned out that a soup can was the exact height for the enclosure so that was what the jacks were mounted on! Anyway when I finished the project, I was totally AMAZED at how drastic the reduction in hum was! I really thought I had killed the thing when I first powered it up because at Vol=10 I couldn't hear anything. There of course, was some, but by comparison it was silent.  I wouldn't spend so much time doing that again, but it was an extremely helpful learning experience.  I would say that if you're not noticing any hum, don't bother with shielding it.

A: Yes, it is a high impedance single ended input, which is extremely susceptible to noise. This noise will typically appear as hum.  The wire and or case is actually an antenna which in its own right is very good at low frequencies. Watch out for ground loops they are hard to find and can be very nasty.
This is one of the major reasons the professionals went to balanced inputs typically 600 ohm instead of approximately 10K on a line input. The balanced mode puts the noise in common mode and basically eliminates it.
Consider when doing your design keeping it at the signal source using as little signal line as possible and use a remote to change it. This can be wired or wireless both will work.
In a home environment you may not notice it but it will be there.
For more information look on the Rane web site they post a lot of great information. Start Here: https://www.rane.com/library.html#gpm1_2
I have been playing with this stuff both as a hobby and as a professional for over 60 years.