Q: what are the attributes in Cals table mean I've working on CALS tables and was stuck in a step. I've the below table.
<?xml version="1.0" encoding="UTF-8"?>

<tgroup cols="2">
<colspec colnum="1" colname="col1" colwidth="2*"/>
<colspec colnum="2" colname="col2" colwidth="16*"/>

<row>
<entry align="center" valign="top" colname="col1" colsep="1" rowsep="1"><para><content-style font-style="bold">A</content-style></para></entry>
<entry align="left" valign="top" colname="col2" colsep="1" rowsep="1"><para><content-style font-style="bold">Board Matters</content-style></para></entry>
</row>
<row>
<entry align="center" valign="top" colname="col1" colsep="1" rowsep="1"><para></para></entry>
<entry align="left" valign="top" colname="col2" colsep="1" rowsep="1"><para></para></entry>
</row>
<row>
<entry align="center" valign="top" colname="col1" colsep="1" rowsep="1"><para><content-style font-style="bold">2</content-style></para></entry>
<entry align="left" valign="top" colname="col2" colsep="1" rowsep="1"><para><content-style font-style="bold">Board composition and balance</content-style> <content-style font-style="bolditalic">(strong and independent board with no dominant</content-style><content-style font-style="bolditalic" format="strikethrough">e</content-style> <content-style font-style="bolditalic">individual(s))</content-style></para></entry>
</row>

</tgroup>

and the below XSLT.
    <xsl:template name="table" match="table">

<xsl:if test="./title/page">
        <xsl:apply-templates select="./title/page"/>
    </xsl:if>

<xsl:value-of select="./title"/>

            <xsl:apply-templates select="child::node()[not(self::title)]"/>

    </xsl:template>

    <xsl:template match="tgroup">
        <xsl:if test="not(preceding-sibling::tgroup)">
            <xsl:if test="@colsep|@rowsep|@align|cols">

            </xsl:if>
        </xsl:if>
        <colgroup>
            <xsl:apply-templates select=".//colspec" />
        </colgroup>
        <xsl:apply-templates select="child::node()[not(self::colspec|self::tfoot/*)]" />
    </xsl:template>
    <xsl:template name="tbody" match="tgroup/tbody">

            <xsl:for-each select="current()/row">
                <xsl:call-template name="row" />
            </xsl:for-each>

        <xsl:if test="preceding-sibling::tfoot">

            <xsl:apply-templates select="preceding-sibling::tfoot"/>

        </xsl:if>

    </xsl:template>
    <xsl:template name="thead" match="tgroup/thead">

            <xsl:for-each select="current()/row">

                    <xsl:for-each select="current()/entry">
                        <xsl:call-template name="headentry" />
                    </xsl:for-each>

            </xsl:for-each>

    </xsl:template>

<xsl:template match="box">

<xsl:value-of select="./title"/>

<xsl:apply-templates select="child::node()[not(self::title)]"/>

</xsl:template>

    <xsl:template name="colspec" match="colspec">

        <xsl:variable name="b">
            <xsl:value-of select="sum(../colspec/number(substring-before(@colwidth,'*')))"/>
        </xsl:variable>
        <col class="colname-{current()/@colname} colwidth-{concat(format-number( number(substring-before(@colwidth,'*')) div $b * 100,'##'),'%')}" />
    <xsl:text disable-output-escaping="yes"><![CDATA[</col>]]></xsl:text>
    </xsl:template>

    <xsl:template name="row" match="row">
    <xsl:if test="./entry/*/page">
    <xsl:apply-templates select="./entry/*/page"/>
    </xsl:if>
    <xsl:choose>
                    <xsl:when test="parent::tfoot">

            <xsl:for-each select="current()/entry">
                <xsl:call-template name="entry" />
            </xsl:for-each>

                    </xsl:when>
                    <xsl:otherwise>

            <xsl:for-each select="current()/entry">
                <xsl:call-template name="entry" />
            </xsl:for-each>

                    </xsl:otherwise>
                </xsl:choose>

    </xsl:template>

    <xsl:template match="entry" name="entry">

        <xsl:choose>
            <xsl:when test="./@namest">
                <xsl:variable name="namest" select="@namest"/>
                <xsl:variable name="nameend" select="@nameend"/>
                <xsl:variable name="namestPos" select="count(ancestor::tgroup/colspec[@colname=$namest]/preceding-sibling::colspec)"/>
                <xsl:variable name="nameendPos" select="count(ancestor::tgroup/colspec[@colname=$nameend]/preceding-sibling::colspec)"/>

                                                <xsl:apply-templates select="child::node()[not(self::page)]"/>

            </xsl:when>
            <xsl:when test="@align and ./@morerows">

                    <xsl:for-each select="para">

                                                       <xsl:apply-templates select="child::node()[not(self::page)]"/>

                    </xsl:for-each>

            </xsl:when>
            <xsl:when test="./@morerows and not(./@align)">

                    <xsl:for-each select="para">

                                                        <xsl:apply-templates select="child::node()[not(self::page)]"/>

                    </xsl:for-each>

            </xsl:when>
            <xsl:when test="not(./@morerows) and ./@align">

                    <xsl:for-each select="para">

                            <xsl:apply-templates select="child::node()[not(self::page)]"/>

                    </xsl:for-each>

            </xsl:when>
            <xsl:otherwise>

                    <xsl:for-each select="para">

                                                        <xsl:apply-templates select="child::node()[not(self::page)]"/>

                    </xsl:for-each>

            </xsl:otherwise>
        </xsl:choose>

    </xsl:template>

    <xsl:template name="headentry">
        <xsl:choose>
            <xsl:when test="@align">

                    <xsl:if test="translate(current()/@namest,'col','') != translate(current()/@nameend,'col','')">
                        <xsl:variable name="colspan">
                            <xsl:value-of select="xs:integer(translate(current()/@nameend,'col','')) - xs:integer(translate(current()/@namest,'col','')) + 1" />
                        </xsl:variable>
                        <xsl:attribute name="colspan">
                            <xsl:value-of select="$colspan">
                            </xsl:value-of>
                        </xsl:attribute>
                    </xsl:if>
                    <xsl:for-each select="para">

                            <xsl:apply-templates></xsl:apply-templates>

                    </xsl:for-each>

            </xsl:when>
            <xsl:otherwise>

                    <xsl:if test="translate(current()/@namest,'col','') != translate(current()/@nameend,'col','')">
                        <xsl:variable name="colspan">

                        </xsl:variable>
                        <xsl:attribute name="colspan">
                            <xsl:value-of select="$colspan">
                            </xsl:value-of>
                        </xsl:attribute>
                    </xsl:if>
                    <xsl:for-each select="para">

                            <xsl:apply-templates></xsl:apply-templates>

                    </xsl:for-each>

            </xsl:otherwise>
        </xsl:choose>
    </xsl:template>

here when i run the XSLT everything is fine but i was having a problem with the below XML part.
<row>
    <entry align="center" valign="top" colname="col1" colsep="1" rowsep="1"><para></para></entry>
    <entry align="left" valign="top" colname="col2" colsep="1" rowsep="1"><para></para></entry>
    </row>

In the output i need a blank row, and it is getting generated, but it looks more like two lines on one another with no gap. as shown below.

But i actually i need some gap between these lines like below.
please let me know how can i get this done, I want to know how i can make use of the colsep and rowsep in my XSLT.
Thanks

A: Add a non-breaking space as a content in your empty para. More like
<row>
    <entry align="center" valign="top" colname="col1" colsep="1" rowsep="1"><para> </para></entry>
    <entry align="left" valign="top" colname="col2" colsep="1" rowsep="1"><para> </para></entry>
</row>


Q: NULL not being counted in aggregate SQL Could use a little help with this SQL query.
Let's say I have a table, called StudentGrades, containing a list of students and a flag indicating whether they have passed a class or not. Assuming there are a large portion of students who have not yet been given a grade, how do I calculate the current percentage of those students that have passed/failed or have not been given a grade.
ID     LastName         GradeGiven
-------------------------------
1      Bueller          PASS
2      Smith            FAIL
3      Carter           FAIL
4      Howell           NULL
5      Clinton          PASS
6      Brown            FAIL
.
.
.
48     Jones            NULL
49     Frank            NULL
50     Jenkins          NULL

I would like to be able create a query that would display the number of students who passed, failed, and don't have a grade assigned yet. To do this I create this query ...
SELECT
  COUNT(GradeGiven) AS "Count of each Grade",
  GradeGiven,
  COUNT(GradeGiven * 100.0/(SELECT COUNT(*) from StudentGrades) AS "Percentage"
FROM
  StudentGrades
GROUP BY
  GradeGiven

My question is that NULL shows up as having a count of 0, even though it is present. Shouldn't it have a count even if it represents no value? I would have expected it to have a count of 45 and a large percentage if most of the grades has not been filled out. Yet it is 0.000
Count        GradeGiven         Percentage
------------------------------------------
0            NULL                 0.000
2            PASS                 4.000
3            FAIL                 6.000

A: Use count(*) or count(1):
SELECT COUNT(*) AS "Count of each Grade",
       GradeGiven,
       COUNT(*) * 100.0/(SELECT COUNT(*) from StudentGrades) AS "Percentage"
FROM StudentGrades
GROUP BY GradeGiven;

Confusion over count(<column name>) is why I don't think it should be used, at least by beginners in SQL.  You can read more about my opinion in this matter here.


Q: Entity framework update change I have an entity model with a self relation (parent/child). My entity named Article has a property called parent. This parent is in fact the relation, and ParentID which is the field in the relation. In ef 4 i did this:
using (var dbContext= new DataBaseModel())
{
    ArticleTable newEntity= new ArticleTable();
   newEntity.name="childArt";
   newEntity.ParentID = 1;
   dbContext.ArticleTable.Add(newEntity);
   dbContext.SaveChanges();

  //after calling save I can do this
   var parentName = newEntity.Parent.Name;
}

With entity framework 6, this doesn't work any more, I have get the entity from the database again in order to get the related parent entity. Is this because of changes to lazyloading? what should i do different.

A: The difference is that in EF 4 entities were generated with piles of code that took care of change notification and lazy loading. Since then, the DbContext API with POCOs has become the standard.
If you want the same behavior as with the old 'enriched' entities you must make sure that lazy loading can occur by a number of conditions:

*

*The context must allow lazy loading. It does this by default, but you can turn it off.

*The navigation properties you want to lazy load must have the virtual modifier, because

*EF must create dynamic proxies. These proxies somewhat resemble the old generated entities in that they are able to execute lazy loading, because they override virtual members of the original classes.

The last (and maybe second) point is probably the only thing for you to pay attention to. If you create a new object by new, it's just a POCO object that can't do lazy loading. However, if you'd create a proxy instead, lazy loading would occur. Fortunately, there is an easy way to create a proxy:
ArticleTable newEntity= dbContext.ArticleTables.Create();

DbSet<T>.Create() creates dynamic proxies -

if the underlying context is configured to create proxies and the entity type meets the requirements for creating a proxy.


Q: .htaccess redirect to subdirectory for Ruby application deployed by passenger My Ruby on Rails project is on justhost server. When I am creating there ruby project, it is creating this in folder rails_apps by default.
For my project, I have created symlinks.
ln -s ~/rails_apps/webworth/public ~/public_html/webworth
And
ln -s ~/rails_apps/webworth ~/public_html/webworth_app [Purpose of this symlink just for browsing files by ftp client]
I created .htaccess file in ~/rails_apps/webworth/public directory. Below is the .htaccess code
Options -MultiViews
PassengerResolveSymlinksInDocumentRoot on
RailsEnv development
RailsBaseURI /webworth
SetEnv GEM_HOME /home5/worthgur/ruby/gems

and one .htaccess file in ~/public_html. Below is the code:
# Use PHP5 Single php.ini as default
AddHandler application/x-httpd-php5s .php

RewriteEngine on
Options +SymLinksIfOwnerMatch
RewriteBase /

RewriteCond %{HTTP_HOST} ^(www\.)?webworth.com [NC]
RewriteCond %{REQUEST_URI} !webworth/ [NC]
RewriteRule ^(.*)$ "webworth\/$1" [L]

Everything is working proper with these structure of .htaccess files except one problem. Extra text is appending to all urls in my project i.e "webworth" for all links generated by routes.rb file. And I want to remove this extra text "webworth" from all URL's.
Now urls are generating for example in this manner.
http://webworth.com/webworth/tags/smartphones
while it should be http://webworth.com/tags/smartphones.

This extra text i.e "webworth" was added previously for the folder that has to be accessed since it was not in the document root for the site and because of this extra text, extra text is appending to all URL's generated by routes.rb file thru ~/rails_apps/webworth/public/.htaccess file [Reason: RailsBaseURI /webworth]
I guess this can be fixed by changing RailsBaseURI /webworth to RailsBaseURI / in ~/rails_apps/webworth/public/.htaccess file.
I did that and I am sure I could not write proper commands in ~/public_html/.htaccess file so that I can redirect the traffic from the public_html to the symlink (webworth) for my site. I used many options but couldn't figure out how it will work. Please help to write ~/public_html/.htaccess file properly to redirect the traffic from public_html folder to my symlink(webworth).
Justhost suggested this link: How to host the Primary Domain from a subfolder. But still I could not figure out the issue. Thanks

A: I had the same problem with justhost and I solved it without adding any redirect.
I set my rails app public folder to be the main site public folder.

*

*I renamed the original "public_html" to "public_html_backup", just in case.

*Added a symlink ln -s ~/myRailsApp/public ~/public_html

*in my htaccess I changed RailsBaseURI /myRailsApp to RailsBaseURI /, resulting in:
<IfModule mod_passenger.c>
      Options -MultiViews
      PassengerResolveSymlinksInDocumentRoot on
      RailsEnv production
      RackBaseURI /
      SetEnv GEM_HOME /yourUserPath.../ruby/gems
</IfModule>
I hope this can help you.
Cheers


Q: Is there a USB B to Ethernet Adapter for an External 3.5 Hard Drive? I have a 3.5" 4TB HHD in a cheap NexStar enclosure connected to my GS63VR laptop via usb 3.0 and it's 90% full. The data is/was in the process of being backed up to back blaze but it will take months, already on month 2. I just moved to France were voltage is now 240. I had the TV connected to the HDMI port. I touched the laptop one day and saw a spark more than once, it was stronger than your average static spark. I've since ruled out everything but the HDMI cable, I disconnected that and no more shocks. However, I think the shocks screwed up my USB ports. I've tried replacing the HD enclosure and power supplies. The laptop seems to connect to it when I turn it on most of the time but it disappears from This PC shortly after and doesn't come back, but the laptop still sees a USB unknown device connected. It's possible the HD was affected but my instinct says it is the ports... so I want to know if I can put this singular HD on the network like a NAS but without wiping the data obviously. Any help is appreciated.

A: This is a bit of an XY problem.
For starters I would first check to see if the USB ports of your laptop aren't fried. Any other USB device, like a USB stick, printer, mouse, keyboard will do for that.
If you are sure the laptop is fine you just need a USB to SATA converter, or an empty enclosure, both which can be had for as little as 30 euro.
You just use that to hook up the disk itself to the laptop.
If the laptop is fried you've got a bigger problem. It will probably degrade further over time, become unreliable and will have to be replaced eventually.
As you already said so yourself a NAS is usually the solution to put a disk "on the network" but EVERY NAS I have ever seen wipes the disk(s) first.
The only way around that is to find a cheap NAS with USB port. Put another disk in that NAS to get the NAS working/configured. Then attach your 4TB disk to that USB port as additional device. That won't wipe it and you can share the disk via the NAS.
There is an alternative though. Many SOHO routers have a USB port to which you can attach a USB stick or USB disk and share it where the router acts as the NAS. If your router has that functionality that is your cheap way out.
In fact. Buying a router just for that will actually be CHEAPER than buying a NAS+extra disk.
(P.S. Some fancy printer/scanner multifunctional machines may have this functionality too.)
Bear in mind that your laptops USB AND the USB of the disk-enclosure may BOTH be fried. Actually it wouldn't surprise me at all if that is the case. In that case you still need a new enclosure or USB-SATA converter to hook up the disk to the NAS or router.


Q: No mole class for NativeMethods.cs? I have a class named NativeMethods.cs which contains all extern methods:
internal static class NativeMethods
{
    [DllImport("kernel32.dll", SetLastError = true, CallingConvention = CallingConvention.Winapi)]
    [return: MarshalAs(UnmanagedType.Bool)]
    internal static extern bool IsWow64Process([In] IntPtr hProcess, [Out] out bool wow64Process);

    [DllImport("advapi32.dll", CharSet = CharSet.Auto)]
    internal static extern int RegOpenKeyEx(
        IntPtr hKey,
        string subKey,
        int ulOptions,
        int samDesired,
        out int hkResult);
}

The assembly containing this class has a corresponding .Moles file. All other classes included in the assembly can be moled and stubbed properly, except this one.
There is no MNativeMethods that we can use for detouring. Is there a special case against the class name "NativeMethods" (Highly unlikely)? Or a special case against extern methods?

A: Moles is capable of detouring calls to managed code. This class is clearly not dealing with managed code. Try creating a stub for this class, manually.  This means crating an INativeMethods interface, have NativeMethods implement INativeMethods, and then use the interface as the stub, as usual.  Moles will then generate stub type SINativeMethods from the interface, for use in test projects.

A: "Thus, if a method has no body (such as an abstract method), we cannot detour it." - Moles Dev


Q: adb I/O Error, possible corruption I am struggling to fix an issue I have. Basically my Galaxy S3 has just up and decided that Google Calendar will now crash whenever I open it. After examining the system log, stack trace, etc... it appears to be stemming from the app trying to access /data/data/com.google.android.calendar/databases/<database>.db, of course with a specific database name.
When I cd into the folder by using adb in root mode I find the folder lib, cache and a file named databases. The other two folders perform normally but databases is weird, it does not auto-complete with tab and using any form of file operation on it (such as less, rm, etc...) results in an I/O Error.
I think this is an oddly corrupted file that is causing the problem, particularly as it appears to stay even when I uninstall Google Calendar. Any help would be most appreciated in getting this sorted as I could really do with getting my calendar back.
Long display of results:
root@m0:/data/data/com.google.android.calendar # ls
databases
root@m0:/data/data/com.google.android.calendar # rm databases
rm failed for databases, I/O error
255|root@m0:/data/data/com.google.android.calendar # rm -rf databases
rm failed for databases, I/O error
1|root@m0:/data/data/com.google.android.calendar # cd databases
/system/bin/sh: cd: /data/data/com.google.android.calendar/databases: I/O error
2|root@m0:/data/data/com.google.android.calendar #
2|root@m0:/data/data/com.google.android.calendar # sqlite3 databases
SQLite version 3.7.11 2012-03-20 11:35:50
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite> .databases
Error: unable to open database "databases": unable to open database file
1|root@m0:/data/data/com.google.android.calendar #

Regards,
Ybrad

A: It happened to a friend on his Moto X Force, Instagram kept crashing. He was using LineageOS 7.1, we wiped everything and installed the original firmware (through TRWP) and when we was installing the package, it returned IO Error on "data/data/com.instagram.android/analytics/xxxxxxxx.pending". We formatted the /data partition but the problem persisted.
We installed the original firmware along with Magisk, installed Root Explorer and renamed the "com.instagram.android" folder to "insta.broken", uninstalled and reinstalled the app and voilá, working again.

A: Huh,
Turns out that if you uninstall the app, rename the folder containing the corrupted file and then re-install everything goes swimmingly.
No idea what caused it or even what is wrong but hey, I have my calendar back.


Q: geting maximu value in a table column I am trying to get maximum value of id column
$taskid = (new Query())->select('MAX(id)')->from('member');

echo $taskid;

unfortunate I got the below text
O:12:"yii\db\Query":20:{s:6:"select";a:1:{i:0;s:7:"MAX(id)";}s:12:"selectOption";N;s:8:"distinct";N;s:4:"from";a:1:{i:0;s:21:"member";}s:7:"groupBy";N;s:4:"join";N;s:6:"having";N;s:5:"union";N;s:6:"params";a:0:{}s:18:"queryCacheDuration";N;s:20:"queryCacheDependency";N;s:27:"yii\base\Component_events";a:0:{}s:35:"yii\base\Component_eventWildcards";a:0:{}s:30:"yii\base\Component_behaviors";N;s:5:"where";N;s:5:"limit";N;s:6:"offset";N;s:7:"orderBy";N;s:7:"indexBy";N;s:16:"emulateExecution";b:0;}

please help me out

A: Maximum id value of Member model:
use app\models\Member;
// ...
echo Member::find()->max('id');


Q: Determine a joint probablity density function Random variables X & Y's joint distribution is uniformly distributed over the region 2>y>x>0, determine joint pdf.
I just don't get it. It should be simple.

A: To declare that $(X,Y)$ is uniformly distributed over some region $D$ is to ask that their joint density is
$$
f_{X,Y}=\frac{\mathbf 1_D}{|D|}.
$$
Can you compute $|D|$ in your case?

A: Draw the region on which the joint density "lives." Make a $2\times 2$ square, with corners $(0,0)$, $(0,2)$, $(2,2)$, and $(0,2)$.  Your density function lives in the part of the square which is above the line $y=x$. Draw that line.
So the joint density lives on a certain triangle. Find the area of the triangle, and the joint density will drop out.


Q: Testing RegEx against Null When calling RegEx.prototype.test() on null, JS runtimes appear to convert null into its string form ("null") and then test the regex against that. A few examples:
/[a-z]+/.test(null)
    true

/null/.test(null)
    true

/[0-9]+/.test(null)
    false

/nnull/.test(null)
    false

My questions are:

*

*Why?

*Is this correct behavior according to current specifications?

This behavior is horribly unintuitive. Since null conceptually represents the absence of any object, it conceptually makes sense that a RegEx test against it would fail, because there should be nothing to test against. It doesn't help that a lot of basic RegEx will succeed on testing against "null".
I have confirmed this behavior in Node.js and Firefox Nightly.

A: 21.2.5.13 RegExp.prototype.test( S )

The following steps are taken:

*

*Let R be the this value.

*If Type(R) is not Object, throw a TypeError exception.

*Let string be ToString(S).

*ReturnIfAbrupt(string).

*Let match be RegExpExec(R, string).

*ReturnIfAbrupt(match).

*If match is not null, return true; else return false.

And look at the ToString(S) you will see null = "null" and you get what you see.

A: Yes, this is as specified.
Per §21.2.5.13 "RegExp.prototype.test( S )" in the 2015 version (6th Edition), one of the first few steps is to apply the "ToString" operation to the argument S, and use its result. The "ToString" operation converts various non-string values to string values; null, in particular, is converted to "null".


Q: How can I use matcaffe in Windows? To use caffe in MATLAB, i need matcaffe.
The manual tells me to run "make all matcaffe"
But it does not tell where to command.
I command "run make all" matcaffe by running cmd from the cafe root folder where caffe.exe exists.
But there is an error saying "There is nothing to do for matcaffe"
Is there a clear, specific, and accurate description of how matcaffe can be run?
Thank you.

A: There is an official branch for caffe on Windows. BVLC/caffe
Follow the steps in that repository, like the below
C:\Projects> git clone https://github.com/BVLC/caffe.git
C:\Projects> cd caffe
C:\Projects\caffe> git checkout windows
:: Edit any of the options inside build_win.cmd to suit your needs
C:\Projects\caffe> scripts\build_win.cmd

If you got all the tools successfully installed, you will be able to build it successfully. Then you could find a .mex64 file under the caffe/matlab folder.
Simply add that directory into matlab, you can use matcaffe then.


Q: Issues with macros and formulas in Excel I'm having problems when inserting a formula from a macro in Excel. I managed to insert exactly the same value that I have on another cell where the formula is working perfectly. It always says #¿NAME? unless I press F2 and Enter. I checked and rechecked the calculation mode and is not Manual, is set to automatic but this formulas doesn't work at all. The method SendKeys "{f2}" SendKeys "{enter}" seems to work but it's horrible and not "seamless".
I've tried with different formulas (from simpler to more complex) and every time a tried any function inside my formula just doesn't work. The only way I insert a working formula is just using numbers (ex. "=1+1" and stuff like that) but when using any function for ex. "=SUM(A1:A5)" just don't work (unless pressing F2 and Enter).
I don't understand why having exactly the same "text" inserted as Formula it just don't work.
What can I do to solve this???
Thanx in advance

A: Thanks for your replies!!!
Using FormulaLocal works great!!! What I did was to "translate" the functions names and done!
Cells(LastRow + 1, 3).Formula = "=IFERROR(VLOOKUP(" & "B" & laststr & " , Datos!A2:E52, 3), """")"

A: Please refer to the answer by Monster for the correct solution to the problem.
I have to leave this answer here until it is "unaccepted", and then I will be able to delete it.

To enter locale-dependent formulas, you need to use FormulaLocal:
Cells(LastRow + 1, 3).FormulaLocal = "=SI.ERROR(BUSCARV(B" & laststr & " , Datos!A2:E52, 3), """")"


Q: Eclipse not recognizing my "Main" method I'm trying to write a "Hello, World" variant program in Eclipse, and I can't seem to be able to run my program.
Here's the code:
/**
 *
 */
package GreeterPackage;

/**
 * @author Raven Dreamer
 * Prints out "Hello, World" in three languages:
 * English, French, and Spanish.
 */
public class GreeterProg {

    /**
     * returns "Hello, World" three times, once
     * in English, once in French, and once in
     * Spanish.
     */
    public static void Main(String[] args){
    /** instances of the three greeter
     * classes so the non-static methods
     * can be called.
     */
    EnglishGreeter eng = new EnglishGreeter();
    FrenchGreeter fre = new FrenchGreeter();
    SpanishGreeter spa = new SpanishGreeter();
    System.out.println(eng.greet());
    System.out.println(fre.greet());
    System.out.println(spa.greet());

}
}

And here's my code for SpanishGreeter (French and English greeter are identical, currently)
/**
 *
 */
package GreeterPackage;

    /**
     * @author Raven Dreamer
     * Returns "Hello, World!" but in Spanish!
     */
    public class SpanishGreeter extends greeter {

        /**Spanish string of "Hello, World!"
         */
        private String GREET = "¡Hola, World!";

        /**
         * returns "Hello, World" in Spanish
         */
        public String greet() {
            return GREET;
        }

    }

The code compiles fine with no errors, but when I try to run the program as a java application, I get the following error:

So I am left baffled as to what, exactly, the problem is. Am I missing something salient in terms of how I set the project up in the first place?

A: The problem is that you have Main with a capital letter. Java is case-sensitive.
The full method signature is: public static void main(String [] args)

A: Your main method needs to be a lowercase "main".

A: "main" must be in lowercase only. Java method names are case-sensitive.


Q: Infinite scrolling I am trying to add some "Infinite Scrolling" to my product pages. However, i can't get it working at all, so i have nothing.
The page currently works, but it just outputs all of the products. I can't get the infinite scrolling scripts i found working, as my query is not always the same.
This is the code that builds my query, using GETs:
$kategori_q = "";
if ($kategori !== "") {
    if ($hkat !== "") {
        $ukator = "";
        $underkategorier = sqlSelect("SELECT * FROM underkategorier WHERE fk_hkategori = '$kategori'");
        while ($row = sqlFetch($underkategorier)) {
            $ukator .= " fk_ukategori = '".$row['underkategori_id']."' OR";
        }
        $kategori_q = rtrim($ukator, "OR");
        $kategori_q = "WHERE ($kategori_q)";
    }
    else {
        $kategori_q = "WHERE fk_ukategori = '$kategori'";
    }
}

$query = "SELECT * FROM annoncer $kategori_q ORDER BY annonce_id DESC";

$soeg = "";
if (isset($_GET['soeg'])) {
    $soeg = $_GET['soeg'];
    if (substr_count($query, "WHERE") == 1) {
        $soeg = " AND (overskrift LIKE '%$soeg%' OR beskrivelse LIKE '%$soeg%')";
    }
    else {
        $soeg = " WHERE (overskrift LIKE '%$soeg%' OR beskrivelse LIKE '%$soeg%')";
    }
}

$query = "SELECT * FROM annoncer $kategori_q $soeg ORDER BY annonce_id DESC";
$q = sqlSelect($query);


Q: Magento 2 Developer Toolbars When developing themes and modules for Magento 2 I came across a barrier, how can I debug better?
So I come here to ask, what are the best developer toolbars for Magento 2?

A: I tested the best developer toolbars, I'll put down the more I liked it.

*

*ADM/QuickDevBar
Info : Information about controller, route, action and store. A dedicated tab output a phpinfo.
Design : List handles called and display layout structure of nested blocks and containers
Profile : View current observers, all events dispatched and collections, models loaded
Queries : Statistics about executed queries and detailed query listing
with syntax highlighting of main SQL keywords
Logs : Display log files with ability to reset these files
Actions : Easily toggle template hints and inline translation and flush cache

*Mirasvit/Module-profiler

*Balloz/Magento2-developer-toolbar

A: The best developer toolbar I came accross is the one developed by Alan Storm called Commerce Bug ($99.95)
It handles:

*

*Details of the request

*List of CRUD Models calls

*List of collections calls

*List of blocks

*Details of the layout

*List of other classes calls

*List of events dispatched

*List of observers called

*An alias lookup tool

*System tasks actions such as cache clearing, template hints toggling, Magento logging toggling, inline translation toggling.


Q: JavaScript function not retrieving string from HTML textarea I am learning JavaScript and I am not understanding why my message is not being retrieved by a word count function. When I click the button with a message of multiple words, I am receiving '1' as the word count, which is incorrect. I have tested the calWords function which works correctly when using console.log(calWords(some message));.
This code is written using requirements and I cannot use .split() or regex. Here is a link to the code:
https://jsbin.com/rucicol/edit?html,js,console,output
<form class="userform">
  Enter a Message to Display Statistics

  <textarea type="text" name="message" id='userInput'></textarea>

  <button type="button" onclick="showStats()">Submit</button>
</form>

// global variables
var numWords = 0;
var displayStats = document.getElementById('userInput').value;

// display stats
function showStats() {

   alert(calWords(displayStats));
}

// calculate words
function calWords(str) {

   for(var i = 0; i < str.length; i++) {
     if (str[i] === ' ') {
      numWords ++;
     }
   }
   return numWords + 1;
}

A: This is because, when you create displayStats you take the value of the textarea at the moment of the creation (e.g. nothing).
To make your script working, you can "store" the reference to the textarea in displayStatsand access his value when needed.
This is the corrected script:
// global variables
var numWords = 0;
var displayStats = document.getElementById('userInput');

// display stats
function showStats()
   alert(calWords(displayStats.value));
}

// calculate words
function calWords(str) {
   for(var i = 0; i < str.length; i++) {
     if (str[i] === ' ') {
      numWords ++;
     }
   }
   return numWords + 1;
}

A: Add the code to get the text area content inside the function.
// global variables
var numWords = 0;

// display stats
function showStats() {
  var displayStats = document.getElementById('userInput').value;
  alert(calWords(displayStats));
}

// calculate words
function calWords(str) {

  for(var i = 0; i < str.length; i++) {
    if (str[i] === ' ') {
      numWords ++;
    }
  }
  return numWords + 1;
}

A: The reason being you have initialised the displayStats globally which will be initialised once the page when load will happen. It would be better if you move displayStats inside click handler.
Also, if you are interested in knowing the number of words in the textarea, you should move your numWords inside the calWords, that way you will get the number of words which is present in the textarea.

// display stats
function showStats() {
  var displayStats = document.getElementById('userInput').value;
  alert(calWords(displayStats));
}

// calculate words
function calWords(str) {
  var numWords = 0;
   for(var i = 0; i < str.length; i++) {
     if (str[i] === ' ') {
        numWords ++;
     }
   }
   return numWords + 1;
}
<form class="userform">
  Enter a Message to Display Statistics

  <textarea type="text" name="message" id='userInput'></textarea>

  <button type="button" onclick="showStats()">Submit</button>
</form>


Q: Wordpress: register_my_menus / creating a new menu does not work I have prepared a positioning of my own menus. So far the menu only reacts to the styling. Wordpress simply selects any menu. For example, if I create a new footer menu, the actual top menu is replaced. The current solution without further menus:
<?php wp_nav_menu( [ 'container_id' => 'main-nav','menu_id' => 'menu-top-menu', 'menu_class' => 'dropdown'] ); ?>

The code in the function.php I have used so far:
function register_my_menus() {

  register_nav_menus(

   array( 'top_menu' => __( 'Top Menu', 'test' ),

          'footer_menu' => __( 'Footer Menu', 'test' ))

          'blog_menu' => __( 'Blog Menu', 'test' ))

  );

}

add_action ('init', 'register_my_menus');

The code in the header.php that I have tried so far for positioning:
<?php wp_nav_menu( array( 'theme_location' => 'top_menu', 'container_id' => 'main-nav','menu_id' => 'menu-top-menu', 'menu_class' => 'dropdown' ) ); ?>

A: I love the object-oriented approach:
class Menu_init {

    public function __construct() {
        add_action( 'init', array($this, 'register_menus'));
    }

    public function register_menus() {

        register_nav_menus(

            array(
                'top_menu' => __( 'Top Menu', 'test' ),
                'footer_menu' => __( 'Footer Menu', 'test' )
                'blog_menu' => __( 'Blog Menu', 'test' )
            )

        );

    }

}

new Menu_init();

and for your header of course:
<?php
wp_nav_menu( [
    'theme_location' => 'primary',
    'container_id' => 'main-nav',
    'menu_id' => 'menu-top-menu',
    'menu_class' => 'dropdown'
] );
?>

It is true, you have an extra bracket ( ) ).

A: function register_my_menus() {

    $locations = array(
        'primary'  => __( 'Top Menu', 'test' ),
        'blog' => __( 'Blog Menu', 'test' ),
        'footer'   => __( 'Footer Menu', 'test' ),
    );

    register_nav_menus( $locations );
}

add_action( 'init', 'register_my_menus' );

<?php wp_nav_menu( [ 'theme_location' => 'primary', 'container_id' => 'main-nav','menu_id' => 'menu-top-menu', 'menu_class' => 'dropdown'] ); ?>


Q: Matlab: Creating contour maps/images similiar to SigmaPlot If a = columns, b = rows and c = intensity. How can I create an image of dimensions a by b and for each pixel to have intensity c:
In SigmaPlot, to create a 29x4 image, a , b and c are formatted as follows, how can the data be formatted in Matlab to achieve similar results:
[a, b, c] =

1   1   0
2   1   0
3   1   0
4   1   0
5   1   0
6   1   360.389854270598
7   1   524.553377941978
8   1   587.550618428821
9   1   535.164504523392
10  1   494.350943153525
11  1   509.366595359498
12  1   541.550829317582
13  1   714.122144025010
14  1   807.904727901154
15  1   634.059149684754
16  1   406.202488197581
17  1   338.349519959103
18  1   348.757723417053
19  1   334.118680593247
20  1   375.846361889047
21  1   507.518116274100
22  1   422.583478997748
23  1   0
24  1   0
25  1   0
26  1   0
27  1   0
28  1   0
29  1   0
1   2   0
2   2   0
3   2   0
4   2   0
5   2   0
6   2   222.769016959765
7   2   426.141970064050
8   2   481.453912764027
9   2   517.069153954465
10  2   487.414455654141
11  2   506.604099604784
12  2   514.770604062499
13  2   460.590220686965
14  2   376.241099616609
15  2   337.728227490832
16  2   394.310238250583
17  2   644.982641646965
18  2   856.664806333676
19  2   1040.69617779231
20  2   1128.07830809176
21  2   1070.24104109274
22  2   850.891638429000
23  2   489.144965506451
24  2   0
25  2   0
26  2   0
27  2   0
28  2   0
29  2   0
1   3   0
2   3   0
3   3   0
4   3   0
5   3   0
6   3   0
7   3   337.875341290982
8   3   446.387817855576
9   3   505.667919278579
10  3   474.666874694826
11  3   404.395323496310
12  3   345.514890319901
13  3   367.942209080407
14  3   450.883569030291
15  3   507.808892555292
16  3   498.203471996257
17  3   501.711478584646
18  3   518.354642382383
19  3   596.694216569632
20  3   591.347390565249
21  3   622.610680837716
22  3   667.944336239558
23  3   445.858691175108
24  3   0
25  3   0
26  3   0
27  3   0
28  3   0
29  3   0
1   4   0
2   4   0
3   4   0
4   4   0
5   4   0
6   4   0
7   4   216.608353008468
8   4   375.475770667960
9   4   425.565743597413
10  4   380.722854551759
11  4   317.194831801482
12  4   337.830175882681
13  4   352.530658493000
14  4   352.286503054898
15  4   323.117595263304
16  4   289.104540650745
17  4   259.229945714487
18  4   233.527214821773
19  4   137.305656551259
20  4   1418.69232849777
21  4   1055.72415597513
22  4   818.007236956091
23  4   595.146860875435
24  4   363.440841935283
25  4   0
26  4   0
27  4   0
28  4   0
29  4   0

A: It seems there is an inconsistency in the data definition: you define

*

*a as the columns (ranging from 1 to 29)

*b as the rows (ranging from 1 to 4)

*nevertheless, then you refer to a 29 x 4 matrix, while it should be 4 x 29
A part from that, you have to first re-arrange the definition of the input data as follow:
abc=[
1   1   0
2   1   0
3   1   0
4   1   0
5   1   0
6   1   360.389854270598
7   1   524.553377941978
8   1   587.550618428821
...
all the other data
...
]

that is to include them into [].
Then you can:

*

*extract the intensity data (which are in the third column of the abc matrix

*use the reshape function to convert the intensity array into a matrix

*"automatically" the x and y data by using the unique function

*get the number of row and column using the length function

*use the meshgrid function to generate the XY grid over which to plot the surface

At this point you can:

*

*use the surf function to plot a 3D surface (the z values will be the intensity data)

*create flat surface and use the intensity data as "colour"

*use the contour function to plot a 2D contour plot

*use the contour3 function to plot a 3D contour plot

This solution can be implemented as follows (where abc is your complete data set):
% Get the intensity data
intensity=abc(:,3);
% Get the x and y data
row_data=unique(abc(:,1));
col_data=unique(abc(:,2));
n_row=length(row_data);
n_col=length(col_data);

% Reshape the intensity data to get a 29x4 matrix
z=reshape(intensity,n_row,n_col);
% Create the grid to plot the surface
[X,Y]=meshgrid([1:n_col],[1:n_row])

% Plot a 3D surface
figure
surf(X,Y,z)
shading interp
colorbar

% Plot a flat surface with
figure
% Create a "dummy" zeros matrix to plot a flat surface
Z=zeros(size(X));
surf(X,Y,Z,z)
shading interp
colorbar

% Plot a 2D contour
figure
[c,h] = contour(z);
clabel(c,h)
colorbar

% Plot a 3D contour
figure
[c,h] = contour3(z);
clabel(c,h)
colorbar

Hope this helps.
Qapla'


Q: When do I see "404" in the page? I'm a rookie in nodejs, and I'm learning Koa. I got some problem about this code.
const Koa = require('koa');
const app = new Koa();

app.use(async function(ctx, next) {
  await next();
  if (ctx.body || !ctx.idempotent) return ;
  ctx.status = 404;
});

What is the meaning of await next() and if statement after that ?

A: This works like a "catch all" statement, reading in plain English:

*

*wait for the request to be processed by other parts of the app
(await next())

*when done, check if the app responded with a body or the request does not require a response body

*if none is true, return HTTP code 404 "Not Found"


Q: How to make clipping geometry scale with the target? In the following example whenever Grid size is changed, the clipping region size remains as it is expressed in absolute coordinates.
<Grid Clip="M10,10 L10,150 L150,150 L150,10 Z">
    <Rectangle Fill="Red"/>
</Grid>

Is is possible somehow to clip the region such that the clipping geometry is scaled along with the clipped object?
Code behind solutions are not accepted, because this is to be used in the control template. Also, the region in the example is a simple shape for clarity sake. The actual used region is a complex and asymmetric shape.
EDIT:
It looks like I have to be more specific. This is the snipped that is part of custom control template for ProgressBar. When scaling the outer grid, the PART_Indicator rectangle does not scale its clipping region. The correct composition is when grid is sized 200x200.
<Grid>
    <Path Name="PART_Track"
          Data="M100,0 A100,100 0 1 0 100,200 A100,100 0 1 0 100,0 Z"
          Fill="AliceBlue" Stretch="Fill"/>

    <Rectangle Clip="M100,0 A100,100 0 1 0 100,200 A100,100 0 1 0 100,0 Z"
               Stretch="Fill"
               Name="PART_Indicator" Fill="Red"
               Height="100" VerticalAlignment="Top"/>

    <Path Name="Border" Data="M100,0 A100,100 0 1 0 100,200 A100,100 0 1 0 100,0 Z"
          Stretch="Fill" StrokeThickness="3" Stroke="Black"/>
</Grid>

UPDATE:
Rick provided excellent suggestion, though it took time for me to understand how to use it.
Here is the final code.
<Viewbox StretchDirection="Both" Stretch="Fill" >
    <Grid>
        <Path Name="PART_Track"
              Data="M100,0 A100,100 0 1 0 100,200 A100,100 0 1 0 100,0 Z"
              Fill="AliceBlue" Stretch="Fill"/>

        <Border Clip="M100,0 A100,100 0 1 0 100,200 A100,100 0 1 0 100,0 Z"
                Height="200" VerticalAlignment="Bottom">
            <Rectangle Name="PART_Indicator" Fill="Red" VerticalAlignment="Bottom"
                       Height="40"/>
        </Border>

        <Path Name="Border"
              Data="M100,0 A100,100 0 1 0 100,200 A100,100 0 1 0 100,0 Z"
              StrokeThickness="3"
              Stretch="Fill" Stroke="Black"/>
    </Grid>
</Viewbox>

A: Put the Grid inside of a Viewbox and change the size of the Viewbox instead of the Grid.
<Viewbox>
    <Grid Clip="M10,10 L10,150 L150,150 L150,10 Z" Width="200" Height="200">
        <Rectangle Fill="Red"/>
    </Grid>
</Viewbox>

A: An alternative approach to this is to define the clipping path using element rather than attribute syntax, and then use the same transformation on the clip as you apply to the element as a whole, e.g.:
<Grid.Clip>
    <PathGeometry FillRule="Nonzero" Transform="{Binding Path=MatrixTransform, RelativeSource={RelativeSource TemplatedParent}, Mode=OneWay}">
        <PathFigure StartPoint="715, 96.3333" IsClosed="True" IsFilled="True">
            <PolyLineSegment IsStroked="False">
                <PolyLineSegment.Points>
                    <Point X="1255.2526" Y="540" />
                    <Point X="426.3333" Y="1342.3333" />
                     <Point X="64.66666" Y="7356.6666" />
                </PolyLineSegment.Points>
            </PolyLineSegment>
       </PathFigure>
   </PathGeometry>
</Grid.Clip>


Q: Which version of angular-notify is compatible with angular version 15? I use angular version 15.0.0 and tried to install angular-notify version 12, but I got an error while installing process. How can I fix the error and install notify successfully?
Best regards.


Q: How can I return the sum of things counted in xpath for $b in doc ("courses.xml") //Course_Catalog/Department/Course
where count($b/Instructors/Lecturer)=0
return count($b)

This code returns the result: 1 1 1 1 1 1 1 1 1 1.  What I acutally want is all the ones to be added up to return the figure 10.
I would be grateful if somebody can tell me how to achieve this. Thank you in advance for any help offered.

A: Use sum:
sum(
  for $b in doc ("courses.xml") //Course_Catalog/Department/Course
  where count($b/Instructors/Lecturer)=0
  return count($b)
)

A: You actually need the count of all such elements.
Use:
count(doc ("courses.xml")//Course_Catalog/Department/Course[not(Instructors/Lecturer)])


Q: Динамическая группировка данных в CollectionViewSource В коде XAML в ресурсах прописан CollectionViewSource
<CollectionViewSource x:Key="viewCollection"  Source="{Binding Path=MyCollecthion,Mode=OneWay}">
            <CollectionViewSource.GroupDescriptions>
                <PropertyGroupDescription PropertyName="MyEnum"/>
            </CollectionViewSource.GroupDescriptions>
        </CollectionViewSource>

Как сделать так, чтоб при изменении свойства MyEnum автоматически элемент перемещался в соответствующую группу
Свойство MyCollection вернет ObservebleCollecthion<MyType>
Свойство MyEnum класса MyType имеет одно из заранее известных значений.
A: 1) Тебе нужен доступ к CollectionViewSource через ключ в самом коде формы - это так
viewCollection=(CollectionViewSource)элемент_где_храниться_CVS.Resources["viewCollection"];
2) Тебе нужно при изменении свойства вызвать следующее из этого объекта
    viewCollection.View.Refresh();


Q: Exit protractor spec without failure Is there a way I can stop protractor from executing more tests in a spec even if there was no failure in the previous tests?
> describe('tests', function () {
>         it('should exit', function () {
>           protractor.stop(); <---- is there a way to prevent executing more tests?
>         });
>         it('should not run', function () {
>           expect(something).toBeTruthy();
>         });
>       });


Q: Rbenv permission denied issue I have trouble getting my Rails app running after I deployed this to my DO droplet.
I deployed (and installed everything including rbenv) following this guide. Rbenv seems to be installed properly but app is not running and nginx error log says "cannot execute /root/.rbenv/shims/ruby permission denied (13)"
I can not get the sense of this error, hope anyone can help with that.

A: Looks like rbenv's installed under root. It should probably be installed under your (or your app user's) home directory, in this case for the user named 'deploy.'
This Passenger configuration line from nginx.conf shows where it's expected to live:
/home/deploy/.rbenv/shims/ruby

So you should probably (re)install rbenv as/under 'deploy.'


Q: A bound using Cauchy formula Let $0<t_0<1$  fixed number , $ n_0$ integer $ \geq 2$ fixed  and let  $\forall 0<u<1, f(u)= \displaystyle \frac{(1-u)^{n_0} \log(1-u)}{(1-ut_0)^{n_0+1}} $.
Let $0<u_0<1 $ be given.  I'm looking a good upper bound (which is an explicit  function in $u_0,t_0, n_0$) to $ |f^{(n_0)}(u_0)|$ ($n_0$-th derivative).
I suppose that by Cauchy formula, and choosing the good radius one can have a good upper bound, but I don't know how to do it. Any help?


Q: How to catch mouse moves outside of screen boundaries My application catpures mouse on down event and relies on mouse movements not directly related to current mouse pointer position (visible pointer). So the math is based on initial point and the relative point of the mouse and has the visual feedback visually not linked to the visible mouse pointer so the pointer might as well be hidden completely. But when I reach the screen boundaries, the incoming coordinates are clipped. It looks reasonable since the pointer don't move either, but I would like to continue getting information about relative mouse movements even if the visible pointer reached the screen boundary. Is this possible? Maybe with access to raw mouse information from the driver?

A: Basically Raw Input Api serves my goal. One needs to register the window with RegisterRawInputDevices and get WM_INPUT message. The incoming data passes relative mouse movements not limited by the screen boundaries.


Q: Bus Fault Handler when writing to a memory provided by a linker script I have to work with code written by someone else for the Cortex M3-based board. I know that this code is supposed to work and it used to pass its integration test: the code is flashed to the board using openocd and then a Python script asserts that certain breakpoints are hit in the code using pygdbmi.
Now in my environment, the integration test is failing and manually flashing the board and running the executable I am hitting a BusFault_Handler every time the code is writing to RAM memory, a specific part of it allocated by the linker script.
This is a minimal C code that reproduces the hard fault. I have derived this minimal code from the real code that does memcpy to that specific part of RAM (in the real program the writes to destination address by the memcpy trigger the hard fault). My simplified code starts at the beginning of main:
extern uint8_t __dedicated_ram_start;
int main(void) {
  /// As suggested in the comments:
  /// Try enabling Usage, Bus & Memory faults in the SCB->SHCSR register.
  /// With those bits set to disabled (the default setting), everything
  /// vectors to the HardFault handler instead of to the individual
  /// handlers for each one.
  SCB->SHCSR |= SCB_SHCSR_USGFAULTENA_Msk
             |  SCB_SHCSR_BUSFAULTENA_Msk
             |  SCB_SHCSR_MEMFAULTENA_Msk;

  uint8_t *ptr = (uint8_t *)&__dedicated_ram_start;
  for (uint32_t i = 0; i < 2000; i++) {
    ptr[i] = i; // BusFault_Handler here, i is rather random in the range of [0..40]
  }
  ...

These are parts that I see relevant in the linker script:
RAM_START_ADDRESS   = 0x20000000;
RAM_SIZE            = 64k;
DEDICATED_RAM_SIZE  = 36k;

MEMORY
{
    rom (rx)  : ORIGIN = 0x60000000, LENGTH = 256k

    /* Area of RAM usable for heap and stack */
    ram (rwx) : ORIGIN = RAM_START_ADDRESS + DEDICATED_RAM_SIZE, LENGTH = RAM_SIZE - DEDICATED_RAM_SIZE
}

PROVIDE (__dedicated_ram_start = RAM_START_ADDRESS);

The bus fault handler:
(gdb) c
Continuing.
^C
Program received signal SIGINT, Interrupt.
BusFault_Handler () at ../.../startup-cortex-m3-minimal.S:328
312     B .
(gdb) bt
+bt
#0  HardFault_Handler () at ../.../startup-cortex-m3-minimal.S:312
#1  <signal handler called>
#2  0x6000036c in main () at ../.../main.cpp:155
(gdb) up
+up
#1  <signal handler called>
(gdb) up
+up
#2  0x6000036c in main () at ../.../main.cpp:155
155     ptr[i] = i;
(gdb) p i
+p i
$4 = 20

The value of i in the above example is a different number with every run and
varies from 0 to 40.
I know this is very limited information that I am providing and I am happy to provide more if needed.
To the best of my knowledge, I am using the same board and the same toolchain to build the code as my predecessors because I was literally following their tutorial documents.
Here's the compiler version:
$ arm-none-eabi-gcc --version
arm-none-eabi-gcc (GNU MCU Eclipse ARM Embedded GCC, 64-bit) 8.2.1 20181213 (release) [gcc-8-branch revision 267074]
Copyright (C) 2018 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

Update 1
One comment suggested to enable Bus/Usage/Mem Fault handlers and inspect corresponding registers. I am set the SCB->SHCSR register and that transformed my original Hard Fault into a Bus Fault.
To turn imprecise errors into precise errors I am using
set *(uint32_t*)0xE000E008=(*(uint32_t*)0xE000E008 | 1<<1)

as recommended in How to debug a HardFault on an ARM Cortex-M MCU.
Using the debugging hard/bus fault handlers described here I am getting the following results:
Continuing.

Program received signal SIGTRAP, Trace/breakpoint trap.
HardFault_Handler () at .../main.cpp:149
149     bkpt();
(gdb) i loc
+i loc
faultType = BusFault
faultAddress = 536870940
isFaultPrecise = true
isFaultImprecise = false
isFaultOnUnstacking = false
isFaultOnStacking = false
isFaultAddressValid = true
(gdb) up
+up
#1  <signal handler called>
(gdb) up
+up
#2  0x6000036c in main () at ../.../main.cpp:155
155     ptr[i] = i;
(gdb) p i
+p i
$4 = 28

(gdb) p /x 28
+p /x 28
$6 = 0x1c
(gdb) p /x 536870940
+p /x 536870940
$8 = 0x2000001c

so the address fault seems to be exactly the one that corresponds to the last i before the Bus Fault occurs.
Update 2
Another comment suggested trying reads as well. I tried the same for loop as above but this time doing reading from the ptr memory and it crashes with the same BusFault_Handler.


Q: Why java.util.Optional is not Serializable, how to serialize the object with such fields The Enum class is Serializable so there is no problem to serialize object with enums. The other case is where class has fields of java.util.Optional class. In this case the following exception is thrown: java.io.NotSerializableException: java.util.Optional
How to deal with such classes, how to serialize them? Is it possible to send such objects to Remote EJB or through RMI?
This is the example:
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.Optional;

import org.junit.Test;

public class SerializationTest {

    static class My implements Serializable {

        private static final long serialVersionUID = 1L;
        Optional<Integer> value = Optional.empty();

        public void setValue(Integer i) {
            this.i = Optional.of(i);
        }

        public Optional<Integer> getValue() {
            return value;
        }
    }

    //java.io.NotSerializableException is thrown

    @Test
    public void serialize() {
        My my = new My();
        byte[] bytes = toBytes(my);
    }

    public static <T extends Serializable> byte[] toBytes(T reportInfo) {
        try (ByteArrayOutputStream bstream = new ByteArrayOutputStream()) {
            try (ObjectOutputStream ostream = new ObjectOutputStream(bstream)) {
                ostream.writeObject(reportInfo);
            }
            return bstream.toByteArray();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

A: The Vavr.io library (former Javaslang) also have the Option class which is serializable:
public interface Option<T> extends Value<T>, Serializable { ... }

A: It's a curious omission.
You would have to mark the field as transient and provide your own custom writeObject() method that wrote the get() result itself, and a readObject() method that restored the Optional by reading that result from the stream. Not forgetting to call defaultWriteObject() and defaultReadObject() respectively.

A: This answer is in response to the question in the title, "Shouldn't Optional be Serializable?" The short answer is that the Java Lambda (JSR-335) expert group considered and rejected it. That note, and this one and this one indicate that the primary design goal for Optional is to be used as the return value of functions when a return value might be absent. The intent is that the caller immediately check the Optional and extract the actual value if it's present. If the value is absent, the caller can substitute a default value, throw an exception, or apply some other policy. This is typically done by chaining fluent method calls off the end of a stream pipeline (or other methods) that return Optional values.
It was never intended for Optional to be used other ways, such as for optional method arguments or to be stored as a field in an object. And by extension, making Optional serializable would enable it to be stored persistently or transmitted across a network, both of which encourage uses far beyond its original design goal.
Usually there are better ways to organize the data than to store an Optional in a field. If a getter (such as the getValue method in the question) returns the actual Optional from the field, it forces every caller to implement some policy for dealing with an empty value. This will likely lead to inconsisent behavior across callers. It's often better to have whatever code sets that field apply some policy at the time it's set.
Sometimes people want to put Optional into collections, like List<Optional<X>> or Map<Key,Optional<Value>>. This too is usually a bad idea. It's often better to replace these usages of Optional with Null-Object values (not actual null references), or simply to omit these entries from the collection entirely.

A: A lot of Serialization related problems can be solved by decoupling the persistent serialized form from the actual runtime implementation you operate on.
/** The class you work with in your runtime */
public class My implements Serializable {
    private static final long serialVersionUID = 1L;

    Optional<Integer> value = Optional.empty();

    public void setValue(Integer i) {
        this.value = Optional.ofNullable(i);
    }

    public Optional<Integer> getValue() {
        return value;
    }
    private Object writeReplace() throws ObjectStreamException
    {
        return new MySerialized(this);
    }
}
/** The persistent representation which exists in bytestreams only */
final class MySerialized implements Serializable {
    private final Integer value;

    MySerialized(My my) {
        value=my.getValue().orElse(null);
    }
    private Object readResolve() throws ObjectStreamException {
        My my=new My();
        my.setValue(value);
        return my;
    }
}

The class Optional implements behavior which allows to write good code when dealing with possibly absent values (compared to the use of null). But it does not add any benefit to a persistent representation of your data. It would just make your serialized data bigger…
The sketch above might look complicated but that’s because it demonstrates the pattern with one property only. The more properties your class has the more its simplicity should be revealed.
And not to forget, the possibility to change the implementation of My completely without any need to adapt the persistent form…

A: If you would like a serializable optional, consider instead using guava's optional which is serializable.

A: If you want to maintain a more consistent type list and avoid using null there's one kooky alternative.
You can store the value using an intersection of types. Coupled with a lambda, this allows something like:
private final Supplier<Optional<Integer>> suppValue;
....
List<Integer> temp = value
        .map(v -> v.map(Arrays::asList).orElseGet(ArrayList::new))
        .orElse(null);
this.suppValue = (Supplier<Optional<Integer>> & Serializable)() -> temp==null ? Optional.empty() : temp.stream().findFirst();

Having the temp variable separate avoids closing over the owner of the value member and thus serialising too much.

A: Just copy Optional class to your project and create your own custom Optional that implements Serializable. I am doing it because I just realized this sh*t too late.

A: the problem is you have used variables with optional. the basic solution to avoid this, provide the variable without optional and get them as optional when you call the getter like below. Optional<Integer> value = Optional.empty(); to  Integer value = null;
public class My implements Serializable {

        private static final long serialVersionUID = 1L;
        //Optional<Integer> value = Optional.empty(); //old code
        Integer value = null; //solution code without optional.

        public void setValue(Integer value ) {
           //this.value  = Optional.of(value); //old code with Optional
           this.value  = value ; //solution code without optional.
        }

        public Optional<Integer> getValue() {
            //solution code - return the value by using Optional.
            return Optional.ofNullable(value);
        }
}


Q: Как передать IP адрес сервера, а не мой личный, на обработчик на другом сайте через веб форму? Задача передать POST переменные на другой сайт. На другом сайте должны прочитать IP адрес сервера на котором лежит форма с которой осуществляется POST запрос. То есть в какой бы точке мира я не находился бы, обработчик должен считывать IP адрес сервера, а не мой личный IP.
Подскажите пожалуйста как реализовать или в каком направлении думать. Спасибо.
Пример формы:
<form action="https://paymentgateway.com/payment/" method="post">
  <input type="hidden" name="action" value="<?=$params['action']?>" />
  <input type="hidden" name="client_key" value="<?=$params['client_key']?>" />
  <input type="hidden" name="order_id" value="<?=$params['order_id']?>" />
  <input type="hidden" name="order_amount" value="<?=$params['order_amount']?>" />
  <input type="hidden" name="order_currency" value="<?=$params['order_currency']?>" />
  <input type="hidden" name="order_description" value="<?=$params['order_description']?>" />
  <input type="hidden" name="card_token" value="<?=$card_token?>" />
</form>

A:
Как передать IP адрес сервера, а не мой личный, на обработчик на другом сайте через веб форму?

Никак.

в каком направлении думать.

Думать в направлении того, где форма, а где сервер.


Q: Coldfusion Parse URLs in text Can anyone help with a function that will parse all urls into valid html links in a text string?
For example:
"Welcome to www.nerds4life.com. View our articles at nerds4life.com or at http://nerds4life.com or also http://www.nerds4life.com"
would become:
"Welcome to www.nerds4life.com. View our articles at nerds4life.com or at http://nerds4life.com or also http://www.nerds4life.com"
What would be the best way to approach this. Regex (and if so, how?) or loop through each word in the text (would think that's less efficient)
Thanks

A: Again... there may be a more elegant regex...
Certainly feel free to google for "good" regex's for finding URLs if this one falls short.
<cfset myText = "Welcome to www.nerds4life.com. View our articles at nerds4life.com or at http://nerds4life.com or also http://www.nerds4life.com or at https://foo.com or http://123.com" />

<cfset myNewText = rereplaceNoCase( myText, '((http(s)?://)?((www\.)?\w+\.\w{2,6}))', '\1', 'all' ) />

A: This will parse URL in string that starts with http or www and terminated by a space
<cfset myString = "Welcome to www.nerds4life.com. View our articles at nerds4life.com or at http://nerds4life.com or also http://www.nerds4life.com">
<cfset URLinString = rereplaceNoCase(myString, '(((http(s)?://)|(www))\.?(\S+))', '\1', 'all')>


Q: TypeError: userAgent.toLowerCase is not a function While running Angular-unit test, using chrome browser, ended up with the error as
TypeError: userAgent.toLowerCase is not a function
    at _isAndroid (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/forms/fesm2015/forms.mjs:176:43)
    at new DefaultValueAccessor (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/forms/fesm2015/forms.mjs:227:38)
    at NodeInjectorFactory.factory (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/forms/fesm2015/forms.mjs:254:1)
    at getNodeInjectable (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/core/fesm2015/core.mjs:3565:44)
    at instantiateAllDirectives (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/core/fesm2015/core.mjs:10318:27)
    at createDirectivesInstances (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/core/fesm2015/core.mjs:9647:5)
    at ɵɵelementStart (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/core/fesm2015/core.mjs:14561:9)
    at templateFn (ng:///TodaysMarketMoversComponent.js:397:66)
    at executeTemplate (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/core/fesm2015/core.mjs:9618:9)
    at renderView (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/core/fesm2015/core.mjs:9421:13)

Most wondering/confusing part to me- toLowerCase function has never been used through out the component/spec file.

A: It looks like the userAgent is being checked by the @angular/forms lib and has been deleted or not provided at all for some reason.
If it's not your code that's changing the userAgent then it's probably some third-party script.
If I were you I'd start with the latest additions in terms of libraries and dependencies and peel them back until I get a unit test running. That will give the clue.


Q: How can I change the CheckBox focus color on Android? I want to change the checkbox "outline" color, which is visible when focusing the checkbox in order to improve the visibility of the currently focused item when using the app with a keyboard or directional pad. How can I do that?
Image of what I mean:
Focused CheckBox on Android
Edit: After finding the correct wording ("ripple color") for what I mean, I managed to change it with:
<item name="colorControlHighlight">#00f</item>

But this only applies to unchecked checkboxes. Does anybody know how to apply it to all (also checked) checkboxes?
Image of colorControlHighlight effect on checked and unchecked checkboxes

A: Thanks to @special N9NE
This works: define an own ripple ripple_bg.xml:
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
        android:color="@color/accent_26" />

And set it as background (globally):
<resources>
    <style name="AppTheme" parent="Theme.AppCompat.DayNight">
        <!-- ... -->

        <!-- custom checkbox style to improve visibility on special (TV) devices -->
        <item name="android:checkboxStyle">@style/MyCheckBoxStyle</item>
    </style>

    <style name="MyCheckBoxStyle" parent="Widget.AppCompat.CompoundButton.CheckBox">
        <item name="android:background">@drawable/ripple_bg</item>
    </style>
</resources>

A: You can check this blog: AppCompat themes
colorControlHighlight is for ripple color

So try to create a ThemeOverlay.AppCompat theme where you will set the value of the color that you want and that will allow you to change the ripple color for that view and its children.
To target ripple in theme use this attribute:

android:colorControlHighlight

A: you can use the theme attribute:
app:theme="@style/MyCheckboxStyle"

then add this in your style.xml file :
<style name="MyCheckboxStyle" parent="AppTheme">
    <item name="colorAccent">@color/colorAccent</item>  // color when checkbox is checked
    <item name="android:textColorSecondary">@color/colorSecondary</item>  // when it is unchecked
</style>


Q: Does the Trophy Shop always sell unique trophies? In "Games & More" > "Vault" > "Trophies" > "Shop" Smash for Wii U contains a shop where you can select from one of eight trophies to buy. This selection of eight is different almost every time you load up the shop.
However, what I'm worried about is buying a duplicate trophy. Does the Shop only ever stock trophies you don't already have? I don't want to accidentally spend a whole ton of money on a trophy I already have, and I also don't want to have to go all the way to my Trophy list in the Vault and check every time before I buy a trophy from the shop. Thanks!

A: Eventually, the trophy shop will start selling duplicate trophies. But you don't have to go and check to avoid buying them - they'll have a blue "Unlocked" tag on them.

*

*Information Source

*Image Source


Q: Go: How can I "unpack" a struct? I have a struct:
type mystruct struct {
    Foo string
    Bar int
}

I'd like to create SQL insert statements from the struct which have the following form:
m := mystruct{ "Hello" , 1 }
query := "INSERT INTO mytbl ( foo, bar ) VALUES ( ?,? )"
res,err := db.Exec(query, m.Foo, m.Bar)

Now my question is: how can I make the last line dynamically from the struct (or m) itself? I am able to get the struct names using reflect, but I don't know how to create the []interface{} slice for the db.Exec() call. This is what I have tried: (http://play.golang.org/p/GR1Bb61NFH)
package main

import (
    "fmt"
    "reflect"
)

type mystruct struct {
    Foo string
    Bar int
}

func main() {
    m := mystruct{"Foo", 1}
    fmt.Println(readNames(m))
    x := unpackStruct(m)
    fmt.Printf("%#v\n", x)
}

func unpackStruct(a interface{}) []interface{} {

    // "convert" a to m t

    // doesn't work, from 'laws of reflection'
    s := reflect.ValueOf(&t).Elem()
    typeOfT := s.Type()
    for i := 0; i < s.NumField(); i++ {
        f := s.Field(i)
        fmt.Printf("%d: %s %s = %v\n", i,
            typeOfT.Field(i).Name, f.Type(), f.Interface())
    }

    // this is in principle what I want:
    m := mystruct{"Hello", 2}
    var ret []interface{}
    ret = make([]interface{}, s.NumField())
    ret[0] = m.Foo
    ret[1] = m.Bar
    return ret
}

// works fine:
func readNames(a interface{}) []string {
    s := reflect.TypeOf(a)
    lenStruct := s.NumField()
    ret := make([]string, lenStruct)

    for i := 0; i < lenStruct; i++ {
        ret[i] = s.Field(i).Name
    }
    return ret
}

A: If getting the values of the fields is your issue, this code snippet should help:
s := reflect.ValueOf(a)
ret := make([]interface{}, s.NumField())
for i := 0; i < s.NumField(); i++ {
    ret[i] = s.Field(i).Interface()
}

A: If creating the []interface{} value is your problem, using reflect's slice creation mechanisms should work nicely:
slc := reflect.MakeSlice(InterfaceType, len, cap) // See the link below for creating InterfaceType
slc.Index(0).Set(TargetValue)
return slc.Interface()

(Here's the above-mentioned link).
Modifying the above code to loop over the values in the struct instead of just the 0th index shouldn't be too bad.


Q: Python mysql.connector select without locked rows from transactions I'm currently working on a Project with MySQL-based Jobworkers. In order for them to fetch a new Job i ran into a problem with row locking:
On Native MySQL (ran 2 terminals and executed following):
SELECT id FROM `data` WHERE `status`=0 ORDER BY `created_at` LIMIT 20 FOR UPDATE SKIP LOCKED;

The Select does not lock the rows what so ever (intended to be this way & what I want)
But running the exact same in Python:
import mysql.connector

class DB:
    def __init__(self):
        self.conn = mysql.connector.MySQLConnection(
            host     = "localhost",
            database = "test"
        )

-------------------------

db = DB()
cursor = db.conn.cursor()
cursor.execute("SELECT id FROM `data` WHERE `status`=0 ORDER BY `created_at` LIMIT 20 FOR UPDATE SKIP LOCKED")

Locks all selected Rows even tho no Transaction was ever started for all other Python connections + Native selects in Terminal.
What am I missing here?
Basically all I want is a select to skip locked rows from Python.
Cheers.
Tried enabling autocommit with:
db = DB()
db.autocommit = True

Also tried:
mysql.connector.MySQLConnection
mysql.connector.connect


Q: How to call static func by passing $_GET params? i have got a static function> which is called
regenerateThumbnailsCron()
And I would like to execute this function by GET params, for example>
if($_GET["pass"]=="password")
self::regenerateThumbnailsCron();

But if I tryied to call this function in constructor>
class AdminImages extends AdminTab
...
 public function __construct()
 {
    if($_GET["pass"]=="password")
    self::regenerateThumbnailsCron();
}

I cannot execute this function.
Is any way, how to call this function before __construct to correctly execute?
Thanks very much for any advice.
EDIT>
I tried also with public function>
<?php
include 'AdminImages.php';

$images = new AdminImages();
$images->regenerateThumbnailsCron();

?>

But i got error>
Fatal error: Class 'AdminTab' not found

A: You need to do a include 'AdminTab.php'; as well, since your class extends that

A: Not completely sure I understand your question, are you saying that you have static class "B" which extends class "A", "A" having your regenerateThumbnailsCron() method which you want to call before anything else?
If so then try this:
<?php
class A {
  private function regenerate() {
  .... do something ....
  }
}

class B extends A {
  function __construct() {
    if ($_GET["pass"] == "password") {
      parent::regenerate();
    }
  }

  function regenerateThunbnailsCron() {
  .... do somethinig ....
  }

}

$images = new B();
$images->regenerateThumbnailsCron();
?>

This way, your parent's "regenerate()" function would get called during the constructor.  You can switch this around to be a static class if you want, which if your goal is to compartmentalise any variables and functions away from the global scope would be a better way.


Q: SetProperty of "SelectedItem is not supported on control type: Window while trying to select an item from combo box in windows application error message showing

"SetProperty of "SelectedItem" is not supported on control type: Window"

A: The problem is that you are calling an instance of class Window but not ComboBox. I see to possible reasons why this happens. Either you are referring to the wrong ui property from UIMap or Coded UI Test Builder recorded wrong element or not the whole hierarchy of your wanted test control.
Moreover, if you are trying to select an item in combobox, then just use
comboBox.SelectedIndex = 3; // to select an item by its zero-based index
comboBox.SelectedItem = "Item Text"; // to select an item by its text

If it does not help, provide additional information on the problem, particularly on the technology of your Windows Application (UIA/WPF or MSAA/WinForms).


Q: Java 8 how to check null values and get List of object? I've a below code written in Java and I wanted to use in Java 8. How can I do that?
Below code is within method:
Query query = new Query();
query.fields().include("address");
query.fields().exclude("_id");

List<User> users = mongoTemplate.find(query, User.class);

List<Address> addresses = new ArrayList<>();
if(!users.isEmpty()) {
    for (Address address : addresses) {
        addresses.addAll(country.getSubaddress());
    }
}
return address;

in Java 8
List<List<Address>> values = countries.stream().filter(Objects::nonNull).map(x -> x.getAddresses()).collect(Collectors.toList());

I only want List of Address. How can I do that ?

A: This is one way of solving the problem:
List<Address> addresses = Optional.ofNullable(users)
            .orElseGet(Collections::emptyList)
            .stream()
            .filter(Objects::nonNull)
            .flatMap(x -> x.getAddress().stream())
            .collect(Collectors.toList());


Q: How to continously deploy a feature to karaf? I want to continously deploy a feature to ServiceMix 6.0, which is based on Karaf 3.0.4.
I first tried this using the karaf console. However there are some problems. It is for a standard karaf installation not possible to determine on the karaf console if a feature is already installed (see my other question on this). The other problem with the karaf console is that it doesn't support exit codes. So it is not possible to determine reliably if a feature installation was successfully finished.
I then installed hawtio and tried to use the exposed JMX beans via jolokia/REST that is bundled with hawtio. The problem here is that karaf 3.0.x is unable to update a feature. Therefore features must be uninstalled first. However the FeatureService only offers the possibility to uninstall an explicitly specified feature. But when a previous version of the feature was installed, subfeatures were installed with it. They also need an upgrade and therefore be uninstalled first. So I would need a way to iterate over the subfeatures of a feature, which I do not have.
So how can continous deployment of features to karaf 3.0.x be done?

A: The first try we have implemented is a bash script. The biggest problem is uninstalling the old version. Therefore we have set up a convention for the names of the feature and it's subfeatures. So we can use the following to find already installed features:
features=$(echo "feature:list" | ssh -p $smx_ssh_port $smx_user@$smx_host | grep -h "<feature-name-convention-regex>.*|.*x.*|" | cut -f1 -d" " | tr '\n' ' ')

This can then be passed to feature:uninstall and can also be used for detecting if features were installed after the call to feature:repo-add -i.
The remaining problem is that we are unable to reference 3rd-party subfeatures because they won't be uninstalled when an updated version needs to be installed and we can't be sure if all of the subfeatures have been successfully installed.

A: For karaf 3 there is no good way to update features.
This is already a little better for karaf 4. It allows to update a feature repo and you can then simply install the feature again. It will detect that the feature has changed and do the necessary changes in bundles.


Q: Using cuda thrust::max_element to find max element in array returns incorrect sometimes I have a 2^20 element array being filled on the device; these numbers should be the same every time.
I then move that array over to the host and then search for the max element in the array, this technique works with 2^10 element array but once I begin to get any larger than that I begin to get random answers not sure if thrust is messing up or the device calculations.
The answer max_element should return is 0.094479 usually the first time the program is run the code will output the correct answer then the answer will randomly show up every few times
GPU is tesla k20 running 5.0 also tested on 780GTX; same issue both times
//Host Code
int main( void ) {
    float h_c[TOTAL];
    float *d_c;

    cudaMalloc((void**)&d_c, sizeof(float)*TOTAL);

    cudaEvent_t start, stop;
    cudaEventCreate(&start);
    cudaEventCreate(&stop);
    cudaEventRecord(start);

    //Number of threads
    kernel<<<BLOCKS,THREADS>>>(d_c);

    cudaEventRecord(stop);
    cudaEventSynchronize(stop);
    float mil = 0;
    cudaEventElapsedTime(&mil, start, stop);

    cudaMemcpy(h_c, d_c, sizeof(float)*TOTAL, cudaMemcpyDeviceToHost);

    for(int y = 0; y < TOTAL; y++){
        printf(" %d: Host C: %f \n",y, h_c[y]);
    }
    float *result = thrust::max_element(h_c, h_c + TOTAL);
    printf("Max is: %f \n", *result);
    printf("Time:  %f \n", mil/1000);
    printf("THREADS:  %d \n", THREADS);
    printf("BLOCKS:  %d \n", BLOCKS);
    printf("TOTAL:  %d \n", TOTAL);
    cudaFree(d_c);
    cudaDeviceReset() ;
    return 0;
}

Device Code
#include <thrust/extrema.h>
#include <math.h>
#include <stdio.h>

#define ARRAYSIZE 15
#define THREADS 1024
#define BLOCKS 32
#define TOTAL THREADS * BLOCKS

__global__ void kernel(float *cc){

//Get thread for summing all elements
int threadId = threadIdx.x + blockDim.x * blockIdx.x;

int decimalNumber,quotient;
//Size of the array
//const int size = 10;
//Holds the binary number in an array
int binaryNumber[ARRAYSIZE];
int i = 0;

int a[ARRAYSIZE] = {1192, 1315, 1462, 1484, 1476, 1443, 1508, 1489, 1470, 1573, 1633, 1539, 1600, 1707, 1701};//, 1682, 1688, 1681, 1694, 1728};
int b[ARRAYSIZE] = {1162, 1337, 1282, 1491, 1508, 1517, 1488, 1513, 1539, 1576, 1626 ,1634, 1573,    1786, 1741};//, 1782, 1755, 1669, 1700, 1826};

//Holds Product from the dot product
int c[ARRAYSIZE];
//Arrays to hold integers to be summed
int aSumArr[ARRAYSIZE];
int bSumArr[ARRAYSIZE];

for(int i = 0; i < ARRAYSIZE; i++){
    c[i] = 0;
    aSumArr[i] = 0;
    bSumArr[i] = 0;
}

//Holds the value for the dot product
int dotSum = 0;
//Holds sum of valid array positions for array a
int aSum = 0;
//Holds sum of valid array positions for array b
int bSum = 0;

//Holds the Value of the arcCos of the dot product / sqrt(array a) * sqrt(array b)
float finalValue = 0;
//printf("ThreadID: %d \n", threadId);
//ALL 1's 1048575 = Threads
decimalNumber = threadId;
//printf("decimal number:  %d \n", decimalNumber);

quotient = decimalNumber;
//Loop to convert decimal into binary and store in array
while(quotient!=0){

    binaryNumber[i++]= quotient % 2;

    quotient = quotient / 2;

}

//Test if conversion from decimal to binary is complete and correct
//printf("Equivalent binary value of decimal number %d: \n",decimalNumber);

//for(int in = size-1; in >= 0;in--){
  //printf("Index: %d | binary number:  %d ----  a:%d || b: %d\n",in,binaryNumber[in],a[in],b[in]);
//}
//printf(" \n ");

//Loop through binaryNumber array
for(int x = ARRAYSIZE-1 ; x >= 0; x--){
    //If index is == 1 Perform calculation
    if(binaryNumber[x] == 1){
        //Multiply numbers at good index
        c[x] = a[x] * b[x];
        //Fill sum arrays at correct index
        aSumArr[x] = a[x];
        bSumArr[x] = b[x];

        //Checks if the loop is executing correctly
        //sumArray[x] = 1;
        //printf("Multiplied - %d * %d = %f\n", a[x], b[x], c[x]);
        //printf("--This should not be run --\n");
    }else{
//          printf("SKIPPED - %d * %d = %f\n", a[x], b[x], c[x]);
    }

}

//Sums up the product array to complete dot product
for(int j = 0; j < ARRAYSIZE; ++j){
    dotSum += c[j];
    //printf("aSumArr %d \n", aSumArr[j]);
    //printf("bSumArr %d \n", bSumArr[j]);
    aSum += powf( aSumArr[j], 2 );
    bSum += powf( bSumArr[j], 2 );
//      printf("aSum: %d +  aSumArr %d \n", aSum, aSumArr[j]);
//      printf("bSum: %d +  bSumArr %d \n", bSum, bSumArr[j]);
}

//printf("\n");
//Print out the dot prudct
//printf("Dot product is: %d \n", dotSum);
//printf("aSum is: %d \n", aSum);
//printf("bSum is: %d \n", bSum);

float sqSum1 = sqrtf(aSum);
float sqSum2 = sqrtf(bSum);
// printf("sqSum1: %f \n", sqSum1);
// printf("sqSum2: %f \n", sqSum2);
float sqSum = sqSum1 * sqSum2;
// printf("sqSum %f \n", sqSum);
float div = dotSum / sqSum ;
// printf("div: %f \n", div);
finalValue = acosf( div ) ;

//Stores the threads final value in array cc, in the respected index
if(finalValue == finalValue){
    cc[threadId] = finalValue;
}else{
    cc[threadId] = -2;
}
//printf("final value is: %f for number %d \n", finalValue, threadId);
}

A: It seems to be a case of using improperly initiialized/uninitialized variables.
After I added the following line:
for(int i = 0; i < ARRAYSIZE; i++){
    c[i] = 0;
    aSumArr[i] = 0;
    bSumArr[i] = 0;
    binaryNumber[i] = 0; // add this line
}

I was no longer able to reproduce the issue.


Q: Wifi adaptor not working even with ubuntu driver I have found a lot of questions here with the same issue as mine, but so far none have solved it.

My wifi adapter is not recognized, my wifi screen simply says  "No Wifi adapter found"
In some other answers I've been told to run this command and post the results
dylan@dylan-HP-Desktop-M01-F1xxx:~$ lspci -nnk | grep 0280 -A3
09:00.0 Network controller [0280]: Realtek Semiconductor Co., Ltd. RTL8821CE 802.11ac PCIe Wireless Network Adapter [10ec:c821]
    Subsystem: Hewlett-Packard Company RTL8821CE 802.11ac PCIe Wireless Network Adapter [103c:831a]
    Kernel modules: rtl8821ce
0a:00.0 Ethernet controller [0200]: Realtek Semiconductor Co., Ltd. RTL8111/8168/8411 PCI Express Gigabit Ethernet Controller [10ec:8168] (rev 15)

I also ran some other commands I found in this answer Link, but still I am having the same issue.
 I'm sorry if this has already been solved, i genuinely couldn't figure it out myself.
Results from comment:
sudo dmesg | grep 8821
[    8.614458] Bluetooth: hci0: RTL: examining hci_ver=08 hci_rev=000c lmp_ver=08 lmp_subver=8821
[    8.617444] Bluetooth: hci0: RTL: loading rtl_bt/rtl8821c_fw.bin
[    8.617763] Bluetooth: hci0: RTL: loading rtl_bt/rtl8821c_config.bin

A: In our chat, in an attempt to find the reason that the driver would not start as expected, we examined the make.log created by the dkms install. It is riddled with warnings: https://paste.ubuntu.com/p/smwRJsWQtW/
I suggested that, instead, we install this driver: https://github.com/lwfinger/rtw88.git When we examined the result of ‘make’, we saw that it proceeded perfectly, with no errors or warnings at all. I recommended that you keep this driver and remove the previous dkms install.
This driver must be reinstalled every time that Update Manager offers a newer kernel version. After the requested reboot, with a temporary internet connection by ethernet, tethering or whatever means possible, do:
cd rtw88
make clean
git pull
make
sudo make install
sudo modprobe rtw_8821ce

Your wireless should be working again. Please retain the rtw88 file and these instructions for that time.
Finally, after disabling Secure Boot, your wireless is working as expected.

A: I had some problems with wifi driver (I have the same driver as yours) on Xubuntu 21.04. I had to change system to Ubuntu 20.04. Here wifi works much better, but after sleep it sometimes do not see the adaptor. I type in terminal
sudo modprobe -r rtl8821ce && sleep 10 && sudo modprobe rtl8821ce

Then sleep, then type it again. An empty wifi-triangle appears. It is empty, but connection works! To check if there still is "no adapter found" try to go to Settings > Wifi.


Q: Set background color of NSWindow with appearance set I am using the following code on my NSWindow so that all my buttons, pop ups, etc. are in a dark mode tint:
[self.window setAppearance:[NSAppearance appearanceNamed:NSAppearanceNameVibrantDark]];

But I want to set a custom window background color instead of the black color which is set as default for the Vibrant Dark Appearance. Calling this line without the appearance works otherwise fails to set:
self.window.backgroundColor = [NSColor colorWithPatternImage:[NSImage imageNamed:@"backgroundColor"]];

Any ideas?

A: Just add a view with a background color and use It as your window's background.
Take a look at this sample app.


Q: How to run angular test using Cloud Build? I use out-of-the-box Angular testing framework: Jasmine and karma for Unit Test and GCP Cloud Build to deploy the app. However, there is a problem in testing because there is no Chrome installed for the node Docker image.
What is the best way to handle that? Create a customized docker image? Or is there any well-known docker image I can leverage for build and test Angular app in Cloud Build?
cloudbuild.yaml
steps:
  # Install
  - name: node:14
    entrypoint: npm
    args: ["install"]
  #Build
  - name: node:14
    entrypoint: npm
    args: ["run", "build", "--", "--aot"]

  # Test <- This step fails. See the error message below
  - name: node:14
    entrypoint: npm
    args: ["run", "test", "--", "--watch=false"]

  # Deploy to Firebase
  - name: gcr.io/$PROJECT_ID/firebase
    args: ["deploy", "--project=$PROJECT_ID", "--only=hosting"]

Error
Already have image: node:14

> carealth@0.0.0 test /workspace
> ng test "--watch=false"

- Generating browser application bundles (phase: setup)...
18 01 2022 19:22:45.740:INFO [karma-server]: Karma v6.3.11 server started at http://localhost:9876/
18 01 2022 19:22:45.744:INFO [launcher]: Launching browsers Chrome with concurrency unlimited
18 01 2022 19:22:45.749:INFO [launcher]: Starting browser Chrome
18 01 2022 19:22:45.756:ERROR [launcher]: No binary for Chrome browser on your platform.
  Please, set "CHROME_BIN" env variable.
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! carealth@0.0.0 test: `ng test "--watch=false"`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the carealth@0.0.0 test script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /builder/home/.npm/_logs/2022-01-18T19_22_45_880Z-debug.log

A: If you need headless chrome in your container, choose a container with node14 and headless chrome installed. I found this one with Chrome 89 and released 10 months ago. You could find better source I guess
Else, you can use your node:14 container and, if it's possible, install headless Google Chrome on it (something like that, install work, but I haven't node file to test on it to validate completely that example)
  - name: node:14
    entrypoint: bash
    args:
      - -c
      - |
        wget https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb
        apt update && apt install -y libappindicator1 fonts-liberation ./google-chrome-stable_current_amd64.deb
        npm run test -- --watch=false


Q: My keyboard doesn't have Super button. Can I do anything to fix this? I am using a Lenovo PC which doesn't have a Super button.
Using Ubuntu 18.04.5 LTS.
What can I do to fix this?

A: The super key and the Windows logo key are the same.


Q: What is on my heap? C linux So I called malloc(1024) today to just play around with the heap. I for the most part understand the structure of the heap, so when I printed out what was in memory, I wasn't surprised to see "00000000 00000409 00000000 00000000 ...."
however 1032 bytes later, I expected to find the top chunk of the heap. Instead I found another chunk as if another call of malloc(1024) had happened after my initial one.
In this chunk is the following:
00000000 00000409 30387830 65336234
30203a30 30303030 20303030 30303030
30303030 30303020 30303030 30302030
34303030 33203930 33303330 20303330
30333033 30333032 33343320 33303330
33332030 39333032 000a3233 00000000

which translates to:
08x0e3b40 :00000 00000000000000 000000 040003 903030 03003030302343 303033#09302
23

Does anyone know why this exists? I am sure I am only calling malloc once. And it always seems to be there no matter what size I malloc.

A: malloc reservers a particular amount of memory on the heap and gives back a pointer to this memory block (or NULL, if it was not able to allocate the desired memory block). Note, however, that malloc will not initialise the memory block in any way. It will not fill it with 0 or any other value; it will simply keep it's content as is.
So the question is actually "what is the initial content of the heap when a program starts?". And the answer is: it depends on the operating system, which portion of memory it assigns to a program when executed, and the content of this memory block is very likely to be just "something undefined", not even random. This can be some recurring patterns of values, it can be zeros, it can be everything.
When you look into different portions of a program's heap, you will probably see this "something undefined" content, regardless of whether you have used malloc before or not. You may see recurring patterns as in your case. Note, however, that "looking into" portions of the heap that have not been allocated before is actually undefined behaviour.


Q: Recursively update a State Monad this question is related to this question
I have a state monad. An object provides an update function as in the OOD strategy pattern.

*

*The choice of having a object is that in real, production code, the
class provides an array of operations, all sharing state through the
monad. Inheritance helped me extend the basic functionality and
further customizing the class providing the operations.

*The choice of having a monad instead of a mutable property within the class is that the monad, through proper use of generics, is helping me abstracting and being more flexible on what variables/information must be carried along the computation as "state".

I have a simple toy example:
/////////////////////////////////////////////////////////////////////////////////////
// Definition of the state
/////////////////////////////////////////////////////////////////////////////////////
type StateFunc<'State, 'T> = 'State -> 'T * 'State

/////////////////////////////////////////////////////////////////////////////////////
// Definition of the State monad type
/////////////////////////////////////////////////////////////////////////////////////
type StateMonadBuilder<'State>() =

    // M<'T> -> M<'T>
    member b.ReturnFrom a : StateFunc<'State, 'T> = a

    // 'T -> M<'T>
    member b.Return a : StateFunc<'State, 'T> = ( fun s ->  a, s)

    // M<'T> * ('T -> M<'U>) -> M<'U>
    member b.Bind(p : StateFunc<_, 'T>, rest : 'T -> StateFunc<_,_>) : StateFunc<'State, 'U>  =
        (fun s ->
            let a, s' = p s
            rest a s')

    // Getter for the whole state, this type signature is because it passes along the state & returns the state
    member b.getState : StateFunc<'State, _> = (fun s -> s, s)

    // Setter for the state
    member b.putState (s:'State) : StateFunc<'State, _> = (fun _ -> (), s)

let runState f init = f init

/////////////////////////////////////////////////////////////////////////////////////
// STRATEGY PATTERN
/////////////////////////////////////////////////////////////////////////////////////

let state = StateMonadBuilder<int> ()

// DoubleFunctOne defines standard operations that remain always the same
type Strategy (aFunction) =
    member this.Update (x: int) = state {
        let! currState = state.getState
        let processedx = aFunction x
        do! state.putState (currState + x) }

// Create a function that customizes the strategy
let myFunction x =
    2 * x

// Customize the strategy with the desired function:
let strategy = Strategy (myFunction)

/////////////////////////////////////////////////////////////////////////////////////////////////////////
// Update recursively
/////////////////////////////////////////////////////////////////////////////////////////////////////////

// ?? How to run update recursively ??
let result initialCondition =
    initialCondition
    |> (for i = 10 to 100 do
            yield state { do! strategy.Update i } )

My goal is to apply the initial conditions, fetch data and launch recursively (within a for or a while loop or even some functional operation) the functions provided by strategy. Working with the monad, I am not sure how to do this.
Thank you.
Computational Expression For
Inspired by @kvb answer, I have added a for method to the computational expression.
// Loops through seqnc of numbers that constitute an input to func
member b.For (seqnc:_ List, func) =
    seqnc
    |> List.map (fun item -> func item)
    |> List.reduce (fun acc item ->
            (fun s ->
                let _, s' = acc s
                item s' ) )

I run a few tests and I have the impression that this one works.
Thanks.

A: Something like this?
let result initialCondition =
    let rec loop = function
    | 101 -> state { return () }
    | i ->
        state {
            do! strategy.Update i
            do! loop (i+1)
        }
    initialCondition
    |> runState (loop 10)

Alternatively, define a For member on your builder and write it the more imperative way:
let result initialCondition =
    let f = state {
        for i in 10 to 100 do
            do! strategy.Update i
    }
    initialCondition
    |> runState f

Also, note that there is likely a bug in your definition of Strategy.Update: processedx is bound but unused.


Q: Linq to sql Distinct after join I have a join query and i want to filter the result of this query by using distinct. I want to get only one of the shoes which has same brand, model, primary color and secondary color. How can i make this ? Here is my join query.
var query = from b in db.BrandTbls.AsQueryable()
            join m in db.ShoeModelTbls on b.BrandID equals m.BrandID
            join s in db.ShoeTbls on m.ModelID equals s.ModelID
            join i in db.ShoeImageTbls on s.ShoeID equals i.ShoeID
            where s.Quantity > 0
            orderby m.ModelName
            select new
            {
                s.ShoeID,
                m.ModelName,
                m.Price,
                b.BrandName,
                i.ImagePath
            };

A: I found the solution. This query does approximately what i want to do
            var query = from b in db.BrandTbls.AsQueryable()
                    join m in db.ShoeModelTbls on b.BrandID equals m.BrandID
                    join s in db.ShoeTbls on m.ModelID equals s.ModelID
                    join i in db.ShoeImageTbls on s.ShoeID equals i.ShoeID
                    group new {b,m,s,i} by new {b.BrandName,m.ModelName,m.Price,s.ShoeID,s.PrimaryColor,s.SecondaryColor,i.ImagePath} into g
                    select new {g.Key.ShoeID,g.Key.BrandName,g.Key.ModelName,g.Key.ImagePath,g.Key.Price};

A: Remove price from the output and use Distinct() like this:
var query = (from b in db.BrandTbls.AsQueryable()
            join m in db.ShoeModelTbls on b.BrandID equals m.BrandID
            join s in db.ShoeTbls on m.ModelID equals s.ModelID
            join i in db.ShoeImageTbls on s.ShoeID equals i.ShoeID
            where s.Quantity > 0
            orderby m.ModelName
            select new
            {
                s.ShoeID,
                m.ModelName,
                b.BrandName,
                i.ImagePath
            }).Distinct();