text:
Q: Adjusting figure quality in matplotlib I've written some code to produce a multi-panelled figure in matplotlib. To make the figure look sharper for use in a document, I tried increasing the dpi. I found, though, that this also changed the sizes of the figure, font, lines etc., as illustrated in the following simpler example:
#First normal figure
fig, axarr = plt.subplots(2,2, figsize=(6,6))
for i,ax in enumerate(axarr.flatten()):
    ax.plot(range(10))
    ax.set_title('title'+str(i), fontsize=10)
    ax.set_xlabel('x'+str(i), fontsize=10)
    ax.set_ylabel('y'+str(i), fontsize=10)
plt.tight_layout()

#Again, with higher dpi
fig, axarr = plt.subplots(2,2, figsize=(6,6), dpi=200)
for i,ax in enumerate(axarr.flatten()):
    ax.plot(range(10))
    ax.set_title('title'+str(i), fontsize=10)
    ax.set_xlabel('x'+str(i), fontsize=10)
    ax.set_ylabel('y'+str(i), fontsize=10)

plt.tight_layout()
plt.show()

On my computer (using matplotlib 1.4.3), the second figure is larger in size and the text is larger, so that the y-axis labels overlap. Without the use of plt.tight_layout(), the overlap of the subplot axes is also worse. Obviously, this is not helpful when just trying to make a higher quality figure. What is going on here, and how can I change the figure quality and keep the appearance of the figure constant? Is there a solution that will also work when I've adjusted subplot parameters, added colour bars and legends etc. i.e. in general? Thanks in advance for any help you can give.

A: Your problem is that you show it and then you save it on the GUI window. You have to save image from command savefig defining there the dpi.
Something like this:
import matplotlib.pyplot as plt

#First normal figure
fig, axarr = plt.subplots(2,2, figsize=(6,6))
for i,ax in enumerate(axarr.flatten()):
    ax.plot(range(10))
    ax.set_title('title'+str(i), fontsize=10)
    ax.set_xlabel('x'+str(i), fontsize=10)
    ax.set_ylabel('y'+str(i), fontsize=10)
plt.tight_layout()
plt.savefig('myfigure_100.png', dpi=100)
plt.savefig('myfigure_200.png', dpi=200)

If you want to show it, you can at the end of the scrpit add plt.show()
EDIT
The relation of the dpi of figure size and the font size can be shown on the following example:
import matplotlib.pyplot as plt

#First normal figure
fig1, axarr1 = plt.subplots(2,2, figsize=(6,6), dpi=100)
for i,ax in enumerate(axarr1.flatten()):
    ax.plot(range(10))
    ax.set_title('title'+str(i), fontsize=10)
    ax.set_xlabel('x'+str(i), fontsize=10)
    ax.set_ylabel('y'+str(i), fontsize=10)
plt.tight_layout()

fig2, axarr2 = plt.subplots(2,2, figsize=(12,12), dpi=50)
for i,ax in enumerate(axarr2.flatten()):
    ax.plot(range(10))
    ax.set_title('title'+str(i), fontsize=20)
    ax.set_xlabel('x'+str(i), fontsize=20)
    ax.set_ylabel('y'+str(i), fontsize=20)
plt.tight_layout()

plt.show()


text:
Q: I am getting this in sfmc Errors: Old style JOIN (ANSI JOINs) syntax is not allowed. Please use standard syntax i am getting below error in sql.
Select Journey_Duration,
CASE
WHEN (Journey_Duration='CompleteYourQuote') THEN
(Select (C.Count+E.Count) as Conversion, 1 as Flag
FROM (Select COUNT(A.EmailAddress) as Count,'J' as JoinCriteria
FROM TEST_Three_Complete_Quote2_Archive_20190918 A
INNER JOIN TEST_Three_Contact_20190201 B ON A.EmailAddress=B.EmailAddress
Where A.Emailaddress in (Select Emailaddress From TEST_Three_Purchase_Policy_Archive_20190910)
OR A.Emailaddress in (Select Emailaddress From TEST_Three_Purchase_Policy_Archive_20190311)) C
INNER JOIN
(Select COUNT(D.EmailAddress) as Count,'J' as JoinCriteria
FROM TEST_Three_Complete_Quote_Archive_20190307 D
INNER JOIN TEST_Three_Contact_20190201 B ON D.EmailAddress=B.EmailAddress
WHERE D.Emailaddress in (Select Emailaddress From TEST_Three_Purchase_Policy_Archive_20190910)
OR D.Emailaddress in (Select Emailaddress From TEST_Three_Purchase_Policy_Archive_20190311)) E
ON C.JoinCriteria= E.JoinCriteria)
END AS CompleteYourQuote,
CASE
WHEN (Journey_Duration='PurchaseYourPolicy') THEN
(Select (G.Count+L.Count) as Conversion, 1 as Flag
FROM (Select COUNT(T.EmailAddress) as Count,'J' as JoinCriteria FROM TEST_Three_Contact_20190201 B
INNER JOIN TEST_Three_Purchase_Policy_Archive_20190910 T ON B.EmailAddress=T.EmailAddress
INNER JOIN TEST_Three_Policy_20190201 F ON T.QuoteNumber = F.QuoteNumber     where B.PartyID is not null)
 G
INNER JOIN
(Select COUNT(H.EmailAddress) as Count,'J' as JoinCriteria
FROM TEST_Three_Contact_20190201 B
INNER JOIN TEST_Three_Purchase_Policy_Archive_20190311 H ON B.EmailAddress=H.EmailAddress
INNER JOIN TEST_Three_Policy_20190201 F ON H.QuoteNumber=F.QuoteNumber where B.PartyID is not null) L
ON G.JoinCriteria= L.JoinCriteria)
END AS PurchaseYourPolicy,
CASE
WHEN (Journey_Duration='StartYourQuote') THEN
(Select COUNT(M.EmailAddress) as Conversion,1 as Flag
from TEST_Three_StartYourQuote_Archive_20190412 M
INNER JOIN TEST_Three_Contact_20190201 B ON M.EmailAddress=B.EmailAddress
INNER JOIN TEST_Three_Quote_20190201 N ON B.PartyID = N.PartyID Where N.QuoteNumber is not null)
END AS StartYourQuote
from
TEST_Three_Conversion_20200611

redpajama_set_name: RedPajamaStackExchange


text:
Q: Dual Boot - Windows does not show tldr:

*

*have SSD + 2 HDD

*tried to install Ubuntu (on HDD) next to Win 7 (installed on SSD)

*couldn't install or 'try'; computer freezed everytime I chose one of those options

*managed to install Ubuntu by turning of ASMedia Controler in UEFI and adding nomodeset (instead of 'quiet splash')

*while booting having problems with "hard resetting link"

*wasted hours; just wanted to go back to 'win-only'

*opened windows partioning manager; looked for the 'linux' partition (which is not recognized by windows).

*deleted it; booted; 'grub rescue', 'no such device'

*noticed I made big mistake (never use windows to delete linux....)

*Re-Installed Ubuntu with this guide: "http://linuxbsdos.com/2012/05/17/how-to-dual-boot-ubuntu-12-04-and-windows-7/"

*used 'boot-repair-disk' to install new 'grub'

*still no Windows 7 on startup boot manager

*BUT I can use Ubuntu now (but I still have to use 'nomodeset' + turning off ASMedia Controler in the UEFI)

*I can open every harddrive (ssd, too) when I am in Ubuntu. There's still a windows folder and everything else in my SSD.

QUESTION: How do I bring back my Windows 7?
(also: whats the difference between turning asmedia controller 'on' or 'off'?)
this is what fidsk -l gives me:
Disk /dev/sda: 59,6 GiB, 64023257088 bytes, 125045424 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disklabel type: dos
Disk identifier: 0x07c27c6f
Device     Boot  Start       End   Sectors  Size Id Type
/dev/sda1  *      2048    206847    204800  100M  7 HPFS/NTFS/exFAT
/dev/sda2       206848 125042687 124835840 59,5G  7 HPFS/NTFS/exFAT
Disk /dev/sdc: 931,5 GiB, 1000204886016 bytes, 1953525168 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 4096 bytes
I/O size (minimum/optimal): 4096 bytes / 4096 bytes
Disklabel type: dos
Disk identifier: 0xefaf9078
Device     Boot      Start        End    Sectors   Size Id Type
/dev/sdc1             2048 1465141247 1465139200 698,6G  7 HPFS/NTFS/exFAT
/dev/sdc2  *    1465141248 1466118143     976896   477M 83 Linux
/dev/sdc3       1466118144 1943758847  477640704 227,8G 83 Linux
/dev/sdc4       1943758848 1953523711    9764864   4,7G 82 Linux swap / Solaris
Disk /dev/sdb: 298,1 GiB, 320072933376 bytes, 625142448 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 4096 bytes
I/O size (minimum/optimal): 4096 bytes / 4096 bytes
Disklabel type: dos
Disk identifier: 0x4596a0fe
Device     Boot Start       End   Sectors   Size Id Type
/dev/sdb1  *     2048 625139711 625137664 298,1G  7 HPFS/NTFS/exFAT
Disk /dev/sdd: 14,5 GiB, 15518924800 bytes, 30310400 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disklabel type: dos
Disk identifier: 0x00000000
Device     Boot Start      End  Sectors  Size Id Type
/dev/sdd1  *     2048 30310399 30308352 14,5G  c W95 FAT32 (LBA)
PLEASE, let me know if you need any more logs or something else. I am pretty new to Linux.
thank you very much!

A: Why you are still trying to install Ubuntu 12.04 , install 15.04 its really easy they even show install alongside windows option . and do you have windows 7 bootloader in another partition ? it should be a 100 MB partition check it. and install ubuntu 15.04 with custom partitioning create /boot and / in different partitions use ext4 it should work fine after installing ubuntu just to be sure it detected the windows type sudo update grub2 see if it shows "windows loader found" if not then do a sudo fdisk -l and post the output :)


text:
Q: How to delete all files of a database in sqlite3? How to delete all files of a database in sqlite3?
I try to delete the filename I created, but there is some strange files left.

A: If you sqlite3 database filename is "/xxx/test.db", you need try to delete follow four files:

*

*"/xxx/test.db"

*"/xxx/test.db-shm"

*"/xxx/test.db-wal"

*"/xxx/test.db-journal"

These four files may exist, may not exist , so you should ignore the error of "file not exist" during the unlinkat/unlink syscall.

A: From https://www.sqlite.org/tempfiles.html:
SQLite currently uses nine distinct types of temporary files:

Rollback journals
Master journals
Write-ahead Log (WAL) files
Shared-memory files
Statement journals
TEMP databases
Materializations of views and subqueries
Transient indices
Transient databases used by VACUUM

The following are always written in the same directory as the database file:

*

*rollback journal (with the same name as the database file but with the 8 characters "-journal" appended)

*WAL ("-wal" appended)

*shared-memory file ("-shm" appended)

*Master Journal File (randomized suffix)
Other temporary files can be located in the same directory, depending on a variety of factors.
See the above link for further details.
By request
If DBNAME is a pathname of the SQLite database, you might like to consider these options for removing all the related files in the directory in which the database file lives:
rm -i ${DBNAME} ${DBNAME}-*

or:
rm -i ${DBNAME}*

or if you're quite sure, either of the above but without -i


text:
Q: C++ SQLite query works just once. What's wrong with my code? I have a function witch contains this code, when I call this function in first time, it will give the results, but after that every time I call it no result returns. I need to fix this.
char query[150];
sprintf(query, "SELECT building, inner, level, position, village FROM Builds WHERE village=%d AND inner=%d", villageId, side);
std::string path=FileUtils::getInstance()->getWritablePath() + "data.db3";
sqlite3 *pDB;
int result = sqlite3_open(path.c_str(), &pDB);

sqlite3_stmt *selectStmt;
sqlite3_prepare(pDB, query, -1, &selectStmt, NULL);

std::list<Build> buildings;
// get data
while (1) {
    int s;
    s = sqlite3_step(selectStmt);
    if (s == SQLITE_ROW) {
        Build building;
        building.building = sqlite3_column_int(selectStmt, 0);
        building.inner = sqlite3_column_int(selectStmt, 1);
        building.level = sqlite3_column_int(selectStmt, 2);
        building.position = sqlite3_column_int(selectStmt, 3);
        building.village = sqlite3_column_int(selectStmt, 4);
        buildings.push_back(building);
    }
    else {
        break;
    }
}
// clode database
sqlite3_finalize(selectStmt);
sqlite3_close(pDB);

// return data
return buildings;

Thank you in advance!

A: Fixed by reducing closing and reopening the database. I also used
sqlite3_open_v2(path.c_str(), pDB, SQLITE_OPEN_READWRITE, NULL);

for opening and
sqlite3_open_v2(path.c_str(), pDB, SQLITE_OPEN_CREATE, NULL);

in the beginning of the execution


text:
Q: How to access  from XSD File for an XML element (eg Country Code,State Code) Problem DeFinition:
I have an XML file and its XSD file
Many Elements in XML have values like :
RES
instead of "RES" I need to display  values from The documentation.
<xs:element name="ResidentialStatus">
                <xs:annotation>
                    <xs:documentation>
                        RES - Resident
                        NRI - Non Resident
                        NOR - Resident but not Ordinarily resident
                    </xs:documentation>
                </xs:annotation>
                <xs:simpleType>
                    <xs:restriction base="nonEmptyString">
                        <xs:enumeration value="RES" />
                        <xs:enumeration value="NRI" />
                        <xs:enumeration value="NOR" />
                    </xs:restriction>
                </xs:simpleType>
            </xs:element>

One option is to maintain this  Key Value collection somewhere within XSL and use it. But if its directly accessible from XSD, that will be the best option as there are many such elements and maintaining dictionary will be tedious.
Thanks


text:
Q: HTML email, remove spacing between tr tags? I have tried adding cellspacing="0" cellpadding="0" . Does not fix the issue in email clients.
Here is a image of the spacing in gmail:

HTML:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

    <title>Openx Webinar</title>

Any advice on how I can fix this? NOTE: this is for HTML email.
UPDATED HEADER CODE:
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

    <title>Openx Webinar</title>

A: Fixed the issue by adding a style="display:block" to images.

A: Change your code to this:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

  <title>Openx Webinar</title>

A: To remove the space between the tr tags simply add border-collapse: collapse; to your table tag. Like for a table within an email you can add it as:

A: You can change display option for 	 that contains the first image:
thead tr:first-child td
{
  display: block;
  height:65px;
}

or for the img itself
thead tr:first-child td img
{
display: block;
}

A: *

*Start by putting your table in another table that has the width set to 100%.

*interior table set to 600 and is center holds all contents

*no longer will you need to put width or align on every td. That is bloating your email.

*block works. As does valign top.

*Get better results!

*Sorry, Get rid of Div. Tables are just that. s

*Don't use classes.

*Cellpadding and Cellspacing are Dynamite and a torch. You're going to blow stuff up.


text:
Q: Does more granular partition key play a role in RU cost, other things being equal? For example, let's say we have a total of 10Gb of data, and there is 1Gb of data for each partition key.
Now, lets consider a query:
SELECT * FROM c WHERE c.Amount > 100
AND c.partitionKey = "someKey"

Assumptions:

*

*This query always returns the same number of results.

*All partition keys fall into the same physical partition.

Question:
Are there any cost implications in setting partitionKey more granular? In other words, if they are within the same physical partition, is there a difference if there are 1000s or 10000s or 100000s of documents with the same partitonKey value?

A: If all of your data resides on a single physical partition nothing you do with your partition key will have any impact on performance.
Your partition key only impacts your ability to scale out. In write-heavy scenarios you want to distribute your writes across as wide an array of partition keys as possible to best saturate or utilize available throughput. In read-heavy scenarios (generally), you want to focus your queries on one or a bounded set of partition key values to avoid fanning out across partitions which do not contain your data.
I say generally because in some cases, where the data you want resides on all partitions, cross-partition queries can be of use as they can run across multiple partitions in parallel. However this is often an edge case and only for queries without high concurrency.
In scenarios where you have both write and read heavy workloads you will need to decide whether to optimize for reads or writes or whether to optimize for writes and use Change Feed and duplicate the data into a second container to serve queries. However, this requires carefully measuring the cost of all operations and comparing it to the cost of not doing this.


text:
Q: Pass an instance of a generic type as a parameter on a dynamic instance of a generic class I am trying to build a list of dynamic types that is actually of type ExceptionLogCondition which is a class that defines the type of exception that needs to be dismissed and an optional condition predicate for the specific exception type.
The problem is with passing the exception to the IsConditionValid(T e) method. I always get this exception:

The best overloaded method match for
  'MvcApplication.ErrorLogCondition.IsConditionValid(Exceptions.AjaxOnlyViolationException)'
  has some invalid arguments

Stacktrace:

at CallSite.Target(Closure , CallSite , Object , Exception )    at
  System.Dynamic.UpdateDelegates.UpdateAndExecute2[T0,T1,TRet](CallSite
  site, T0 arg0, T1 arg1)    at
  CONCENTRA.MOS.MvcApplication.ErrorLog_Filtering(Object sender,
  ExceptionFilterEventArgs e) in C:_teamprojects\Main\Source\Global.asax.cs:line
  213    at Elmah.ErrorLogModule.OnFiltering(ExceptionFilterEventArgs
  args)    at Elmah.ErrorLogModule.LogException(Exception e, HttpContext
  context)    at Elmah.ErrorLogModule.OnError(Object sender, EventArgs
  args)    at System.EventHandler.Invoke(Object sender, EventArgs e)
  at System.Web.HttpApplication.RaiseOnError()

Here's the code:
public class MvcApplication : System.Web.HttpApplication
{
    protected void ErrorLog_Filtering(object sender, ExceptionFilterEventArgs e)
    {
        var exceptionsToDismiss = new List<dynamic>() {
            new ErrorLogCondition<Exceptions.AjaxOnlyViolationException>(),
            new ErrorLogCondition<WebsiteException>(c => c.LogError == true)
        };

        foreach (var exd in exceptionsToDismiss)
        {
            if(((Type)exd.ExceptionType).Equals(e.Exception.GetBaseException().GetType()) &&
                exd.IsConditionValid(e.Exception.GetBaseException()))
                // The second condition fails even though the type is correct (see first if condition).
                e.Dismiss();
        }
    }
}

public class ErrorLogCondition<T> where T : Exception, new() {
    public Type ExceptionType {get;set;}
    public Predicate<T> ExceptionTypeCondition { get; set; }

    public ErrorLogCondition() {
        ExceptionType = typeof(T);
    }

    public ErrorLogCondition(Predicate<T> c)
    {
        ExceptionType = typeof(T);
        ExceptionTypeCondition = c;
    }

    public bool IsConditionValid(T e)
    {
        return ExceptionTypeCondition == null || ExceptionTypeCondition.Invoke(e);
    }
}

My gut feeling says I might be overdoing it a bit. So I am open to other suggestions. Nevertheless I would also like to know why this doesn't work.

A: GetBaseException() returns an Exception, which is not what IsConditionValid can accept.  You have the moral equivalent of this code:
Exception baseExp = e.Exception.GetBaseException() //which is a AjaxOnlyViolation
IsConditionValid( baseExp);

//where isconditionvalid is:
bool IsConditionValid(AjaxOnlyViolation e) { }

It doesn't matter that the instance at runtime is an AjaxOnlyViolation at runtime - the compiler doesn't know that.  What matters is that it is declared as possible that it is any exception, and there is no implicit cast from Exception to AjaxOnlyViolation.  Therefore, error.
You need to tell the compiler;  You can either change IsConditionValid to accept an Exception, then cast it to a T inside that method, or cast it before calling the method.

A: From the code provided I deduct that  e.Exception.GetBaseException() returns an instance of the type which is not castable to AjaxOnlyViolationException type.

A: As GetBaseException() return type is Exception, no method public bool IsConditionValid(Exception e) can be found. You should provide a method with the Exception type in the signature.
Nevertheless, this might not be the better approach for performance concerns (see MSDN about dynamics).
But you could use a List<Predicate<Exception>> which would do the same kind of job while reducing the required lines of code to do it, IMHO.


text:
Q: How to append from one csv file to another? Tried different ways. The closest way that may fit my need is the following code:
   with open('list.csv', 'r') as reader, open('list-history.csv', 'a') as writer:
         for row in reader:
             writer.writerow(row)

I'm using 'a' and tried 'w' as well but no luck.
The result is no output at all.
Any suggestion, please? Thanks.

A: I think there should be a error with a stacktrace.
Here: writer.writerow(row)
Normally open() returns file object which doesn't have .writerow() method, normally, you should use .write(buffer) method.
Example
with open('list.csv', 'r') as reader, open('list-history.csv', 'a') as writer:
    for row in reader:
        writer.write(row)

For me it works well with test csv files. But it doesn't merge them, just appends content of one file to another one.

A: If both the csv columns have same name. Python's pandas module can help.
Example Code snippet.
import pandas as pd

df1 = pd.read_csv("csv1.csv")
df2 = pd.read_csv("csv2.csv")

df1.append(df2, ignore_index=True)
df1.to_csv("new.csv",index=False)


text:
Q: Using GDB to read MSRs Is there some way to read the x86-64 model-specific registers, specifically IA32_FS_BASE and IA32_GS_BASE, while debugging a program using GDB?
Less preferable would be a solution using a dynamic instrumentation package like Intel's Pintool, but it would be appreciated all the same.

A: Since gdb 8 the registers $fs_base and $gs_base are also available. These work in code dumps too, not just live programs.

A: The x86 MSRs can be read with the RDMSR instruction, which is privileged (Ring 0).  In Linux there are system calls that a user thread can invoke to read FS_BASE and GS_BASE.  There are no library wrappers for them, so you have to write code to invoke them yourself.
Here's one way to do it in C++, you add these global function definitions to your program:
#include <cstdint>
#include <asm/prctl.h>
#include <sys/syscall.h>
namespace x86 {
    uint64_t fs_base() {
        uint64_t fs_base;
        syscall(SYS_arch_prctl,ARCH_GET_FS,&fs_base);
        return fs_base;
    }
    uint64_t gs_base() {
        uint64_t gs_base;
        syscall(SYS_arch_prctl,ARCH_GET_GS,&gs_base);
        return gs_base;
    }
}

Now you can call these functions from gdb and print their return value in hex, like this:
(gdb) p/x x86::fs_base()
$1 = 0x7ffff5e01780
(gdb) p/x x86::gs_base()
$2 = 0x0
(gdb)

A: If you prefer not changing your code (or if the code is not available) you could do something similar to amdn's answer in the following way. The call to arch_prctl requires a pointer to a uint64_t, for which I use the address to an empty portion of the stack (8 bytes below the current stack pointer). After the call returns, read the 8 byte value stored at the location.
Constants used: ARCH_GET_FS = 0x1003, ARCH_GET_GS = 0x1004
(gdb) p $rsp
$1 = (void *)0x7fffffffe6f0

(gdb) call arch_prctl(0x1003, $rsp - 0x8)
$2 = 0
(gdb) x /gx $rsp - 0x8
0x7fffffffe6e8: 0x00007ffff7fe0700   => IA32_FS_BASE

(gdb) call arch_prctl(0x1004, $rsp - 0x8)
$3 = 0
(gdb) x /gx $rsp - 0x8
0x7fffffffe6e8: 0x0000000000000000   => IA32_GS_BASE


text:
Q: cakephp model class not found error while upgrading I am trying to upgrade my CakePHP application from 1.3.6 to 2.2.4
I did all the upgrade steps based on official CakePHP upgrade documentation.
But i am struggling with this error:

Class 'Content' not found in
  C:\wamp\www\cakephp-2.2.4\app\Controller\Component\OrderBaseComponent.php
  on line 20
Argument 1 passed to Component::__construct() must be an instance of
  ComponentCollection, none given, called in
  C:\wamp\www\cakephp-2.2.4\app\Controller\Component\OrderBaseComponent.php
  on line 17 and defined [CORE\Cake\Controller\Component.php, line 77]

A: For the first error make sure you always App::uses() every single class you use in your code.
So your Content (whatever class it is) must also be included before you can actually use it.
Only if it is a model you can just use ClassRegistry::init(), otherwise put sth like
App::uses('Content', '[TYPE]'); at the top of the file.
This second error is pretty self-explanatory!
Look into the outlined "CORE\Cake\Controller\Component.php" file and make sure your function does have the exact same arguments in your custom component:
public function __construct(ComponentCollection $collection, $settings = array()) {
    //...
}

A: We don't have any relevant source code but generally you might add this at the top or your component file:
First:
 App::uses('Content', 'Model');

And you might have to add something like in your init or construct method:
$this->Content = ClassRegistry::init('Content');

That should solve the first issue or give a clear explanation about what goes wrong. Actually this code was likely already not correctly independent functional.
I suspect it depends on the Model to be loaded already in another piece of code that's why it worked likely. A component should work not dependent on other pieces of code so adding the App::uses, App::import etc statements makes the code work always. For example when you re-use it in your other projects.
Second:
The second issue comes really with migration issues. Check that the model extends the Component class first.
Then make sure that if you implement a custom method __construct() but also init() for example that you check whether you should add a call to the parent. For example this applies to beforeFilter controller method.
public function beforeFilter() {
    parent::beforeFilter();
}

Documentation and code example from: http://book.cakephp.org/2.0/en/controllers.html#the-app-controller
Relevant piece of documentation: http://book.cakephp.org/2.0/en/appendices/2-0-migration-guide.html#components


text:
Q: Active record callbacks running before creation of associated records in create and update methods In my update and create method for my game controller, I am creating some game_events. There are then after_save callbacks on my game model that should run. These callbacks generate data that I need, and are saved in their respective columns. However, the issue I'm having is that the game_events are being created it seems, after the callbacks are being called. So that my "set_events_user" callback doesn't seem to acknowledge that there are any game_events. However, if from the console I save the game a second time, the callbacks acknowledge these game_events, and the events_user data is generated fine.
Essentially the reason my controller methods for update and create look so weird is because I've tried different ways of rearrangthe order of events so that when the callbacks run, the game_events are acknowledged. I've tried extracting the bit of code where it iterates over the events_user array from the params into a seperate method, then calling save a second time in one method to get it to acknowledge the events.
def create
    @game = Game.create(game_params)
    authorize @game
    @game.organization_id = current_user.organization_id
    params[:events_user].each do |e|
      @game.game_events.create({
        event_type: e["event_type"],
        event_id: e["event_id"],
      })
    end
    @game.save
    render json: @game, status: :ok
  rescue StandardError => e
    render json: @game.errors, status: :unprocessable_entity
  end

  def update
    authorize @game
    @game.game_events.destroy_all
    params[:events_user].each do |e|
      @game.game_events.create({
        event_type: e["event_type"],
        event_id: e["event_id"],
      })
    end
    @game.update(game_params)
    render json: @game, status: :ok
  rescue StandardError => e
    render json: @game.errors, status: :unprocessable_entity
  end

after_save :set_events_user

def set_events_user
        @sequence = []
        self.game_events.by_sequence.each do |e|
            @e = {}
            @e[:id] = e.id
            @e[:event_id] = e.event_id
            @e[:event_type] = e.event_type
            @e[:question_text] = e.event.question_text
            @e[:a1] = {es: e.event.a1, en: e.event.a1 }
            @e[:a2] = {es: e.event.a2, en: e.event.a2 }
            @e[:a3] = {es: e.event.a3, en: e.event.a3 }
            @e[:correct_answer] = e.event.correct_answer if e.event_type == 'Question'
            @sequence << @e
        end

        @sequence.to_json
        self.events_user = @sequence
    end

No error message, but I expect that the gme_events are created, the callback runs upon being saved, and the game is saved with the generated data. However, unless I save it manually from the console a second time, the first time the data is empty because it won't acknowledge game events.


text:
Q: Pyinstaller: path or glob "/usr/include/python3.4m/pyconfig.h" not found or matches no files." I am trying to build my project on a Oracle virtualbox ubuntu 14.04.2 LTS.
My project is in Python 34. I installed pyinstaller via:
pip install https://github.com/pyinstaller/pyinstaller/archive/python3.zip

When I run pyinstaller run.py I get the following error:
FileNotFoundError: Path or glob "/usr/include/python3.4m/pyconfig.h" not found or matches no files.

I indeed don't have a directory '/usr/include/python3.4m', only 'usr/include/python2.7'. Python 34 is installed (by default in Ubuntu).
How can I get it to work?

A: Apparently installing libpython3.4-dev package solved the problem.
http://packages.ubuntu.com/utopic/amd64/libpython3.4-dev/filelist
So do sudo apt-get install libpython3.4-dev if you encounter the problem.


text:
Q: Prometheus metrics are not coming when it takes more time than scrap interval Overview
I am new to Prometheus. My Custom Exporter takes IP addresses as input. Does some stream processing and then registers new metrics to Prometheus registry. Below is the code,
#!/usr/bin/env python3

from prometheus_client import start_http_server, Gauge, Counter
from prometheus_client import REGISTRY
from prometheus_client.metrics_core import GaugeMetricFamily
import time

count = 0

class TestExporter:

    def collect(self):
        global count
        count += 5

        for i in range(3):
            yield self.check_stream(count, i)

    def check_stream(self, count, host):
        # some processing time
        # lets assume 5 seconds
        time.sleep(5)
        metric = GaugeMetricFamily('aa_stream_test', 'testing stream delete', labels=['stream'])
        if count > 100:
            metric.add_metric(['B', str(host)], count)
        else:
            metric.add_metric(['A', str(host)], count)
        print (count, 'registering . . .')
        return metric

if __name__ == '__main__':

    REGISTRY.register(TestExporter())

    # Start up the server to expose the metrics.
    start_http_server(8000)
    print("started server...")

    while True:
        time.sleep(1)

Issue
In check_stream function, I have defined estimated time that It can take to process the request. As of now, I have put as 5 seconds. (But it can vary)
The check_stream function gets executed for 3 times, so if I use function time.sleep(3), I can see metrics in prometheus graph. because total time is 3 * 3 = 9 which is less than 10sec prometheus scrap time. But if I use time.sleep(5), It takes total 5*3=15, which is >= scrap interval time. Here I don't see any prometheus values in graph. It is empty.
Please help.
Thanks.

A: Prometheus configuration has a scrape_timeout that defaults to 10 seconds.
Prometheus attempts to scrape your target and, if the target takes longer than the scrape_timeout to respond, then it will timeout (and not scrape the metrics).
You should increase the scrape_timeout in your Prometheus server config so that server does not timeout when attempting to scrape your target.


text:
Q: Python3 - Urllib & BeautifulSoup4 to Extract Specific Text I am new to python and I am trying to get a script working alongside with urllib and BeautifulSoup4 to collect the tweets which are streamable via the emojitracker API. It outputs the tweets of a specific emoji as .json files. An example is this link (opens in chrome):
http://emojitracker.com/api/details/1F52B
I can get all the text from the .json, but I only want to get the tweet (which is after "text:"). I had a look around and there was an example to get all the links on the page, using soup.findAll("a",class_="classname").
I used inspect element and found that the tweet i need is stored as: (span class="type-string")tweet goes here(/span). So I tried the following:
from bs4 import BeautifulSoup
import urllib.request

url = "http://emojitracker.com/api/details/1F52B"
page = urllib.request.urlopen(url)
soup = BeautifulSoup(page.read(),"html.parser")
tweets = soup.findAll("span", class_"type-string")

for tweet in tweets:
    print (tweet.string)

Running, this it did not print anything. How can I make it so that it only prints out the tweets?

A: The page you provide is not an html page. In fact it's formatted as a json file, so you won't be able to treat it as an HTML page.
As I understand, what you want is to retrieve all of the recent tweets.
In order to do this, we get the response, as already do, and parse the response string and convert it to a Python dictionary using the json library (which does not require installation as it's part of the standard library).
If you want to do this, we can write the following code:
import json
import urllib.request

url = "http://emojitracker.com/api/details/1F52B"
page = urllib.request.urlopen(url)
json = json.loads(str(page.read(), 'latin'))

for tweet in json['recent_tweets']:
    print(tweet['text'])

Hope it helps,


text:
Q: Using moment.js timezone to get day extremes in another timezone (but the answer in UTC) I want to work out the day extremes (midnight to midnight) for a particular day, where that day is a whole number of days relative to now (i.e. relative to Date.now())... but for a different timezone to UTC.  But I want the answer (midnight times) back in UTC time (in milliseconds, similar to what you get with Date.now()), so that I can feed those to an API that expects UTC times, to get the exact right time range of data.  I have tried to use moment.js timezone but am getting horribly stuck... I found this answer but it doesn't work in a different timezone.

A: I suggest you consider using Luxon, which is essentially the replacement for moment.js.
The algorithm is create a date for now in the required representative location, subtract the required number of days, then set to the start of day, then get the time value, e.g.

let DateTime = luxon.DateTime;

// Create date for 00:00:00 3 days ago in Denver
let d = DateTime.local()                   // Create a date
                .setZone('America/Denver') // Set to Denver
                .minus({days:3})           // Subtract 3 days
                .startOf('day');           // Set to start of day
// Create date for end of day
let e = d.endOf('day');

// Denver 3 days ago at start and end of day
console.log('Start of day: ' + d.toISO() + '\nTime value  : ' + d.ts);
console.log('End   of day: ' + e.toISO() + '\ntime value  : ' + e.ts);
<script src="https://cdn.jsdelivr.net/npm/luxon@1.24.1/build/global/luxon.min.js"></script>

Note that 3 days ago in Denver might be a different date to 3 days ago in the host system because of the offset differences. E.g in Sydney, Australia at 9 am on 20 July it's 5 pm on 19 July in Denver, so subtracting 3 days in Sydney is 17 July but 16 July in Denver.

A: Moment will allow you to do this fairly easily:
function getUTCMidnightMillis(timezone, days_ago) {
  return moment()               // Current time.
    .tz(timezone)               // Convert to desired timezone.
    .subtract(days_ago, 'days') // Go back x days.
    .startOf('day')             // Get start of day, aka Midnight!
    .utc()                      // Convert value into UTC.
    .valueOf()                  // Return milliseconds since unix epoch.
}

console.log("Midnight in Denver:", getUTCMidnightMillis("America/Denver", 0))
console.log("Midnight in New York:", getUTCMidnightMillis("America/New_York", 0))

Which produces the output:
Midnight in Denver: 1594274400000
Midnight in New York: 1594267200000

And indeed, you can verify that is correct:
new Date(1594274400000).toISOString()
// Produces: "2020-07-09T06:00:00.000Z"

For the 9th of July, 2020, we observe daylight savings in Denver, making our UTC offset -6 hours. So the above timestamp (6:00am UTC) is the same moment at which it is midnight in Denver.


text:
Q: How can I take a picture from my app and use that to display using UIImageView I am fairly new to Xcode and I want to take a picture from my app and display that picture on a UIImageView. Please help thank you!

A: First add <UIImagePickerControllerDelegate> protocol in header filer,after this on button action put  code-

 self.pickerImageView = [[UIImagePickerController alloc] init];
 self.pickerImageView.delegate = self;
self.pickerImageView.sourceType = UIImagePickerControllerSourceTypeCamera;
[self.navigationController presentViewController:self.pickerImageView animated:YES completion:nil];

-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    [self.pickerImageView dismissViewControllerAnimated:YES completion:nil];
    yourimageview.iamge=[info objectForKey:@"UIImagePickerControllerOriginalImage"];
    self.pickerImageView=nil;
}

-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [self.pickerImageView dismissViewControllerAnimated:YES completion:nil];
    self.pickerImageView=nil;
}

A: Here are few of the tutorial links for Camera usage:
http://www.techotopia.com/index.php/An_Example_iOS_4_iPhone_Camera_Application
http://www.appcoda.com/ios-programming-camera-iphone-app/
Hope this helps you.

A: Below is the code to achieve your desired task :
#pragma mark - Change Profile picture

- (IBAction)profileImageButtonAction:(id)sender {
    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle: nil
                                                             delegate: self
                                                    cancelButtonTitle: @"Cancel"
                                               destructiveButtonTitle: nil
                                                    otherButtonTitles: @"Take a new photo", @"Choose from existing", nil];

    [actionSheet showInView:self.appDelegate.window];

}

#pragma mark - UIActionSheet Delegate

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    fromPhotoLibaryOrCamera = YES;
    switch (buttonIndex) {
        case 0:
            [self takeNewPhotoFromCamera];
            break;
        case 1:
            [self choosePhotoFromExistingImages];
            break;
        default:
            break;
    }
}

#pragma mark - UIImagePicker Delegates

- (void)takeNewPhotoFromCamera
{
    if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera])
    {
        UIImagePickerController *controller = [[UIImagePickerController alloc] init];
        controller.sourceType = UIImagePickerControllerSourceTypeCamera;
        controller.allowsEditing = NO;
        controller.mediaTypes = [UIImagePickerController availableMediaTypesForSourceType: UIImagePickerControllerSourceTypeCamera];
        controller.delegate = self;
        [self.navigationController presentViewController: controller animated: YES completion: nil];

    }else{

        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error!"
                                                        message:@"Camera not available"
                                                       delegate:self
                                              cancelButtonTitle:@"Try Again"
                                              otherButtonTitles: nil];
        [alert show];

    }

}
//Method to upload image from image library
-(void)choosePhotoFromExistingImages
{
    if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypePhotoLibrary])
    {
        UIImagePickerController *controller = [[UIImagePickerController alloc] init];
        controller.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        controller.allowsEditing = NO;
        controller.mediaTypes = [UIImagePickerController availableMediaTypesForSourceType: UIImagePickerControllerSourceTypePhotoLibrary];
        controller.delegate = self;
        controller.isAccessibilityElement = YES;
        [self.navigationController presentViewController: controller animated: YES completion: nil];
    }
}

-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info

{

    UIImage *image=[info valueForKey: UIImagePickerControllerOriginalImage];

    NSLog(@"Image Size = %@",NSStringFromCGSize(image.size));

    //image = [image resizedImage:imgProfile.bounds.size interpolationQuality:kCGInterpolationDefault];

    image = [image resizedImageWithContentMode:UIViewContentModeScaleAspectFill bounds:imgProfile.bounds.size interpolationQuality:kCGInterpolationDefault];

    NSLog(@"Image Size = %@",NSStringFromCGSize(image.size));

    imgData = UIImageJPEGRepresentation(image, 0.1);

    imgProfile.image=image;
    [imgProfile addBorder:3.0 andColor:[UIColor lightGrayColor]];
    [self.navigationController dismissViewControllerAnimated:YES completion:nil];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker;
{

    [self.navigationController dismissViewControllerAnimated: YES completion: nil];

}

Keep a button behind the image view and connect the IBAction of the button with
- (IBAction)profileImageButtonAction:(id)sender
and the rest of the job will be done. Hope this helps. Thanks and Cheers. :)


text:
Q: Kivy Update TextInput Field with Entry from Another Screen Hi I have a question about passing variables in Kivy. So what my app is trying to do is:
Have a TextInput field that for a name of an item. However, I have a button where when I click, I can scan the QR, QR is translated into a text and the TextInput field is filled with updated with the QR translation.
I also Screen Manager and Sockets.
How can I achieve this?
The main problem I am struggling is when the QR is translated, it is saved as self.codename in the QrScreen. Since I want to update the TextField in the MainScreen, the MainScreen needs to update the self.codename from "" to the translated QR. This is the process that I don't understand.
here is the code:
import kivy
from kivy.app import App

from kivy.uix.label import Label
from kivy.uix.gridlayout import GridLayout
from kivy.uix.textinput import TextInput
from kivy.uix.button import Button
from kivy.uix.widget import Widget
from kivy.properties import ObjectProperty
from kivy.uix.screenmanager import ScreenManager, Screen

# Import Package that deals with socket
import socket_client

# Import QR Reader
import qr_reader

# from android.permissions import request_permissions, Permission
# request_permissions([
#     Permission.CAMERA,
#     Permission.WRITE_EXTERNAL_STORAGE,
#     Permission.READ_EXTERNAL_STORAGE
# ])

class MainScreen(Screen):
    def update_name(self, new_qr):
        print(' Iam updating this name ' + new_qr)

    def turn_camera_on(self):
        print("turning camera on...")

    def send_message(self, _):
        message = _
        print(message)

        if message:
            socket_client.send(message)

class QrScreen(Screen):
    camera = ObjectProperty(None)

    def capture_image(self):

        texture = self.camera.texture
        size = texture.size
        pixels = texture.pixels
        self.codename = qr_reader.convert_qr(size, pixels)
        print(self.codename)
        # update the text in the main page

        # switch screen to main page

    def send_message(self, _):
        message = _
        print(message)

        if message:
            socket_client.send(message)

class SettingsScreen(Screen):
    ipadd = ObjectProperty(None)
    port = ObjectProperty(None)
    username = ObjectProperty(None)
    def connect(self):
        print(f"joining {self.ipadd.text} | {self.port.text} AS {self.username.text}")

        # Get information for sockets client
        port = int(self.port.text)
        ip = self.ipadd.text
        username = self.username.text

        if not socket_client.connect(ip, port, username, show_error):
            return

class MyApp(App):

    # Initiate the variable for codename

    codename = ObjectProperty(None)
    def build(self):
        self.codename = ""

        # Create the screen manager
        sm = ScreenManager()
        sm.add_widget(MainScreen(name='mainpage'))
        sm.add_widget(QrScreen(name='qrpage'))
        sm.add_widget(SettingsScreen(name='settings'))

        return sm

def show_error(message):
    pass

if __name__ == '__main__':
    theapp = MyApp()
    theapp.run()

my.kv:
<MainScreen>:
    GridLayout:
        cols: 1

        GridLayout:
            cols: 2
            codename: codename
            Label:
                text: "Code Name"
            TextInput:
                id: codename
                multiline: False
            Button:
                text: 'Scan QR'
                on_press: root.manager.current = 'qrpage'
                on_press: root.turn_camera_on()
            Button:
                text: 'Go'
                on_press: root.send_message("Go")
            Button:
                text: 'Stop'
                on_press: root.send_message("Stop")
            Button:
                text: 'Setting'
                on_press: root.manager.current = 'settings'

<QrScreen>:
    camera: camera
    GridLayout:

        cols: 1
        Camera:
            id: camera
            resolution: (640,480)
            play: False
        GridLayout:
            cols: 2
            ToggleButton:
                text: 'Play'
                on_press: camera.play = not camera.play

            Button:
                text: 'Capture'
                on_press: root.capture_image()

            Button:
                text: 'Back'
                on_press: root.manager.current = 'mainpage'

<SettingsScreen>:
    ipadd: ipadd
    port: port
    username: username

    GridLayout:
        cols: 1
        GridLayout:
            cols:2

            Label:
                text: "IP Address: "
            TextInput:
                id: ipadd
                text: "192.168.1.65"
                multiline: False

            Label:
                text: "Port: "
            TextInput:
                id: port
                text: "1234"
                multiline: False

            Label:
                text: "Username: "
            TextInput:
                id: username
                text: "User"
                multiline: False

            Button:
                text: 'Join'
                on_press: root.connect()

            Button:
                text: 'Back'
                on_press: root.manager.current = 'mainpage'

A: Haven't tested this code, but using ids and the get_screen() method of ScreenManager should allow you to update the Textinput:
def capture_image(self):

    texture = self.camera.texture
    size = texture.size
    pixels = texture.pixels
    self.codename = qr_reader.convert_qr(size, pixels)
    print(self.codename)

    # update the text in the main page
    main_screen = self.manager.get_screen('mainpage')
    main_screen.ids.codename.text = self.codename

    # switch screen to main page
    self.manager.current = `mainpage`


text:
Q: Challenging Path Integral Let $c$ be the curve of intersection of the plane defined by $x+y+z = a$ and the cylinder $x^{2} + y^{2} = a^{2}$ ($a > 0$). Evaluate the path integral:
$\displaystyle\oint_{c} \sqrt{a^2 + xy}   \mathrm{d}s$

I have first tried to parametrize the curve of intersection with the followng (let $0 \leq t \leq 2\pi$):
$x = a\cos(t)$
$y = a\sin(t)$
$z = a - x -y = a - a\cos(t) - a\sin(t)$
Then, we can find that $|c'(t)| = \sqrt{(-a\sin(t))^2 + (a\cos(t))^2 + (a\sin(t) - a\cos(t))^2}$, to then have that:
$\displaystyle\oint_{c} \sqrt{a^{2} + xy} \mathrm{d}s = \int_{0}^{2\pi} \sqrt{a^{2}+a^{2}\cos(t)\sin(t)} |c'(t)|\mathrm{d}t = \int_{0}^{2\pi} \sqrt{a^{2}+a^{2}\cos(t)\sin(t)} \sqrt{2a^{2}-2a^{2}\cos(t)\sin(t)} \mathrm{d}t = \sqrt{2}a^{2} \int_{0}^{2\pi} \sqrt{1-\cos^{2}(t)\sin^{2}(t)} \mathrm{d}t$
I've been trying to solve the last integral, but apparently I checked if it could be solved with Wolfram Alpha, and it gives the solution in terms of the elliptic integral of the second kind. On the other hand, Stokes' Theorem cannot be used that easily as we would not have a line integral in this case.
What would be the best way to solve this problem to obtain a closed form solution? Perhaps I made a mistake in my calculations. Thank you for the help.


text:
Q: Running rails console with .env config I've got a Rails 4 app that is deployed to Heroku and talks to S3. Access credentials for S3 are stored in ENV variables on Heroku and locally I have a .env file.
When I run the server locally via heroku local -p 3000, everything works as it should - files upload to S3 just fine.
When I try to run rails console via heroku local:run rails console, I can't find the magic sauce to avoid a key not found error.
What am I missing?
.env
S3_BUCKET_NAME=BUCKETNAME
AWS_ACCESS_KEY_ID=KEYID
AWS_SECRET_ACCESS_KEY=SECRETKEY
AWS_REGION=REGION

Procfile
web: bundle exec rails server -p $PORT

config/environments/development.rb
...
config.paperclip_defaults = {
  storage: :s3,
  s3_credentials: {
    bucket: ENV.fetch('S3_BUCKET_NAME'),
    access_key_id: ENV.fetch('AWS_ACCESS_KEY_ID'),
    secret_access_key: ENV.fetch('AWS_SECRET_ACCESS_KEY'),
    s3_region: ENV.fetch('AWS_REGION'),
  }
}

the error stack:
heroku local:run rails console
[OKAY] Loaded ENV .env File as KEY=VALUE Format
/Users/username/Development/rails_application/config/environments/development.rb:48:in `fetch': key not found: "S3_BUCKET_NAME" (KeyError)
  from /Users/username/Development/rails_application/config/environments/development.rb:48:in `block in <top (required)>'
  from /Users/username/.rvm/gems/ruby-2.2.1/gems/railties-4.2.5.1/lib/rails/railtie.rb:210:in `instance_eval'
  from /Users/username/.rvm/gems/ruby-2.2.1/gems/railties-4.2.5.1/lib/rails/railtie.rb:210:in `configure'
  from /Users/username/Development/rails_application/config/environments/development.rb:1:in `<top (required)>'
  from /Users/username/.rvm/gems/ruby-2.2.1/gems/activesupport-4.2.5.1/lib/active_support/dependencies.rb:274:in `require'
  from /Users/username/.rvm/gems/ruby-2.2.1/gems/activesupport-4.2.5.1/lib/active_support/dependencies.rb:274:in `block in require'
  from /Users/username/.rvm/gems/ruby-2.2.1/gems/activesupport-4.2.5.1/lib/active_support/dependencies.rb:240:in `load_dependency'
  from /Users/username/.rvm/gems/ruby-2.2.1/gems/activesupport-4.2.5.1/lib/active_support/dependencies.rb:274:in `require'
  from /Users/username/.rvm/gems/ruby-2.2.1/gems/railties-4.2.5.1/lib/rails/engine.rb:598:in `block (2 levels) in <class:Engine>'
  from /Users/username/.rvm/gems/ruby-2.2.1/gems/railties-4.2.5.1/lib/rails/engine.rb:597:in `each'
  from /Users/username/.rvm/gems/ruby-2.2.1/gems/railties-4.2.5.1/lib/rails/engine.rb:597:in `block in <class:Engine>'
  from /Users/username/.rvm/gems/ruby-2.2.1/gems/railties-4.2.5.1/lib/rails/initializable.rb:30:in `instance_exec'
  from /Users/username/.rvm/gems/ruby-2.2.1/gems/railties-4.2.5.1/lib/rails/initializable.rb:30:in `run'
  from /Users/username/.rvm/gems/ruby-2.2.1/gems/railties-4.2.5.1/lib/rails/initializable.rb:55:in `block in run_initializers'
  from /Users/username/.rvm/rubies/ruby-2.2.1/lib/ruby/2.2.0/tsort.rb:226:in `block in tsort_each'
  from /Users/username/.rvm/rubies/ruby-2.2.1/lib/ruby/2.2.0/tsort.rb:348:in `block (2 levels) in each_strongly_connected_component'
  from /Users/username/.rvm/rubies/ruby-2.2.1/lib/ruby/2.2.0/tsort.rb:420:in `block (2 levels) in each_strongly_connected_component_from'
  from /Users/username/.rvm/rubies/ruby-2.2.1/lib/ruby/2.2.0/tsort.rb:429:in `each_strongly_connected_component_from'
  from /Users/username/.rvm/rubies/ruby-2.2.1/lib/ruby/2.2.0/tsort.rb:419:in `block in each_strongly_connected_component_from'
  from /Users/username/.rvm/gems/ruby-2.2.1/gems/railties-4.2.5.1/lib/rails/initializable.rb:44:in `each'
  from /Users/username/.rvm/gems/ruby-2.2.1/gems/railties-4.2.5.1/lib/rails/initializable.rb:44:in `tsort_each_child'
  from /Users/username/.rvm/rubies/ruby-2.2.1/lib/ruby/2.2.0/tsort.rb:413:in `call'
  from /Users/username/.rvm/rubies/ruby-2.2.1/lib/ruby/2.2.0/tsort.rb:413:in `each_strongly_connected_component_from'
  from /Users/username/.rvm/rubies/ruby-2.2.1/lib/ruby/2.2.0/tsort.rb:347:in `block in each_strongly_connected_component'
  from /Users/username/.rvm/rubies/ruby-2.2.1/lib/ruby/2.2.0/tsort.rb:345:in `each'
  from /Users/username/.rvm/rubies/ruby-2.2.1/lib/ruby/2.2.0/tsort.rb:345:in `call'
  from /Users/username/.rvm/rubies/ruby-2.2.1/lib/ruby/2.2.0/tsort.rb:345:in `each_strongly_connected_component'
  from /Users/username/.rvm/rubies/ruby-2.2.1/lib/ruby/2.2.0/tsort.rb:224:in `tsort_each'
  from /Users/username/.rvm/rubies/ruby-2.2.1/lib/ruby/2.2.0/tsort.rb:203:in `tsort_each'
  from /Users/username/.rvm/gems/ruby-2.2.1/gems/railties-4.2.5.1/lib/rails/initializable.rb:54:in `run_initializers'
  from /Users/username/.rvm/gems/ruby-2.2.1/gems/railties-4.2.5.1/lib/rails/application.rb:352:in `initialize!'
  from /Users/username/Development/rails_application/config/environment.rb:5:in `<top (required)>'
  from /Users/username/.rvm/gems/ruby-2.2.1/gems/spring-2.0.1/lib/spring/application.rb:92:in `require'
  from /Users/username/.rvm/gems/ruby-2.2.1/gems/spring-2.0.1/lib/spring/application.rb:92:in `preload'
  from /Users/username/.rvm/gems/ruby-2.2.1/gems/spring-2.0.1/lib/spring/application.rb:143:in `serve'
  from /Users/username/.rvm/gems/ruby-2.2.1/gems/spring-2.0.1/lib/spring/application.rb:131:in `block in run'
  from /Users/username/.rvm/gems/ruby-2.2.1/gems/spring-2.0.1/lib/spring/application.rb:125:in `loop'
  from /Users/username/.rvm/gems/ruby-2.2.1/gems/spring-2.0.1/lib/spring/application.rb:125:in `run'
  from /Users/username/.rvm/gems/ruby-2.2.1/gems/spring-2.0.1/lib/spring/application/boot.rb:19:in `<top (required)>'
  from /Users/username/.rvm/rubies/ruby-2.2.1/lib/ruby/site_ruby/2.2.0/rubygems/core_ext/kernel_require.rb:54:in `require'
  from /Users/username/.rvm/rubies/ruby-2.2.1/lib/ruby/site_ruby/2.2.0/rubygems/core_ext/kernel_require.rb:54:in `require'
  from -e:1:in `<main>'

A: From dotenv README
# config/application.rb
Bundler.require(*Rails.groups)

Dotenv::Railtie.load

HOSTNAME = ENV['HOSTNAME']

see here too .env not being loaded in test environment in Rails with rspec

A: *

*Acces your enviroment variables like this: ENV["AWS_KEY"]

*Make sure you have the enviroment variables set in the heroku admin panel(the last tab,reveal enviroment varibales), do not push the .env file to the respository as that is a dangerous practive.


text:
Q: Does a POD cache the files read in a container in POD's memory? I am running an application in K8S POD.
Event though the applications memory usage is limited the PODs memory usage is growing till a certain limit and then remaining constant.
The application reads lot of input files are closes them.
Why us POD memory usage so high? Do PODs caches files inside POD memory, like OS.?
I am using Linux containers.

A: I don't think so because pods are ephemeral in nature. and as far as my point of view pod does not cause memory issue because of files. If it's java application then you have to limit the Heap usage by setting JAVA_OPTS as env and set the maximum memory limit in your deployment file. like this
env:
- name: JVM_OPTS
  value: "-Xms1048M -Xmx2048M"   # here xms value means starting memory for jvm and it can use upto 2048

Here is the very nice article https://banzaicloud.com/blog/java-resource-limits/

A:
Even though the applications memory usage is limited

That is only the half of the story. In case of Java you need to consider JVM as well.

the PODs memory usage is growing till a certain limit and then remaining constant.

There are limits for pods. You can get these limits with the help of kubectl get pod <pod_name> -o yaml (you are interested in the "requests" section).

Why us POD memory usage so high?

You can check what exactly is going on with the help of kubectl exec -it <pod_name> -- top -o RES -n1 | head command. In this very example I'm sorting the output of top by the RES field. You can use any other fields ( for example VIRT, SHR, etc).
Here is the example from my machine:
$ kubectl get pod jenkins -o yaml | grep -A2 requests
      requests:
        cpu: 300m
        memory: 512Mi

$ kubectl top pod jenkins
NAME                           CPU(cores)   MEMORY(bytes)
jenkins                        3m           508Mi

$ kubectl exec -it jenkins -- top -o RES -n1
...

PID USER      PR  NI    VIRT    RES    SHR S  %CPU %MEM     TIME+ COMMAND
  6 root      20   0 4478216 449952   8000 S   0.0  5.9  39:11.70 java

From the above output you can see that my jenkins pod has limit at 512Mi and consumes ~508Mi. You can get more insight on how exactly RAM is "wasted" by java app if you ran pmap -x <pid> , ps -La -p <pid> on pod.
It is worth checking java -XX:+PrintFlagsFinal -version | grep Heap and adjusting it with the Dashrath Mundkar's suggestion (if you would like to reduce the memory allocated by JVM inside your pod.
The following resources 1, 2, 3 might be useful here.


text:
Q: Marker label is never shown I am trying to add a marker with label specified in MarkerOptions, but i never see a label inside the icon. I know there is a class MarkerWithLabel, but for my purposes standard label will be enough, and this is how documentation describes it...
  vGeocoder.geocode( { 'address': vStart}, function(results, status) {
     if (status == google.maps.GeocoderStatus.OK) {
        vStartMarker = new google.maps.Marker({
            map: vMap,
            position: results[0].geometry.location,
            label: 'A',
            icon: "http://maps.google.com/mapfiles/ms/icons/yellow-dot.png"
        });

        vMap.setCenter(results[0].geometry.location);
        vMap.setZoom(8);
     } else { alert('Geocode was not successful for the following reason: ' + status); }
  });


text:
Q: HTML Special Characters converted to question mark in Chrome & Mozilla HTML Special Characters like á, Á are getting converted to ? in Chrome & Mozilla. It works fine in IE.
When I use special character á in the search box of the site, there is a difference in url for both Chrome/Mozilla and IE. Special Character in the search query is converted as:
%E1 - in URL of Chrome/Mozilla, but in text field it is displayed as ?.
%26aacute%3B - in URL of IE, textfield correctly show the special character á. This is correct.
Can somebody help to fix this issue.
Site uses encoding:
<meta http-equiv="content-type" content="text/html; charset=UTF-8">

Thanks for your help.


text:
Q: Can't get HTTPS working in Spring Boot (PKCS12 not found) I've been attempting to follow the following tutorials regarding setting up HTTPS in Spring Boot:

*

*https://www.drissamri.be/blog/java/enable-https-in-spring-boot/

*https://www.thomasvitale.com/https-spring-boot-ssl-certificate/
But when I start up my app in Eclipse it throws an exception:

Caused by: java.io.IOException: Failed to load keystore type [PKCS12 ]
  with path
  [file:/C:/Users/dbush/workspace/my_app/target/classes/keystore.p12]
  due to [PKCS12  not found]

I checked the filename given and the file exists.  I also ran keytool -list -keystore keystore.p12 and was able to read it after giving the password used to create it, which is the same password in application.properties.
Any idea what could be causing this?
I also tried using a JKS file instead of a PKCS12 file and got the same error with "JKS not found".
My pom.xml contains:
...
  <dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
        <version>1.5.3.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.data</groupId>
        <artifactId>spring-data-mongodb</artifactId>
        <version>1.10.3.RELEASE</version>
    </dependency>
    <dependency>
        <groupId> org.springframework.security</groupId>
        <artifactId>spring-security-core</artifactId>
        <version>4.2.3.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.mongodb</groupId>
        <artifactId>mongodb-driver</artifactId>
        <version>3.4.2</version>
    </dependency>
    <dependency>
        <groupId>org.json</groupId>
        <artifactId>json</artifactId>
        <version>20160810</version>
    </dependency>
    <dependency>
        <groupId>org.jvnet.jaxb2_commons</groupId>
        <artifactId>jaxb2-basics</artifactId>
        <version>0.6.3</version>
    </dependency>
  </dependencies>
..

My main App.java:
package dbush;

import org.apache.catalina.Context;
import org.apache.catalina.connector.Connector;
import org.apache.tomcat.util.descriptor.web.SecurityCollection;
import org.apache.tomcat.util.descriptor.web.SecurityConstraint;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.context.embedded.EmbeddedServletContainerFactory;
import org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;

@Configuration
@EnableAutoConfiguration
@ComponentScan
@EnableMongoRepositories(basePackages = "dbush.repository")
public class App {

    public static void main(String[] args) {
        SpringApplication.run(App.class, args);
    }

    @Bean
    public EmbeddedServletContainerFactory servletContainer() {
      TomcatEmbeddedServletContainerFactory tomcat = new TomcatEmbeddedServletContainerFactory() {
          @Override
          protected void postProcessContext(Context context) {
            SecurityConstraint securityConstraint = new SecurityConstraint();
            securityConstraint.setUserConstraint("CONFIDENTIAL");
            SecurityCollection collection = new SecurityCollection();
            collection.addPattern("/*");
            securityConstraint.addCollection(collection);
            context.addConstraint(securityConstraint);
          }
        };

      tomcat.addAdditionalTomcatConnectors(redirectConnector());
      return tomcat;
    }

    private Connector redirectConnector() {
      Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
      connector.setScheme("http");
      connector.setPort(8080);
      connector.setSecure(false);
      connector.setRedirectPort(8443);

      return connector;
    }

}

My application.properties:
security.require_ssl=true

server.port=8443
server.ssl.key-alias=tomcat
server.ssl.key-password=changeit
server.ssl.key-store=classpath:keystore.p12
server.ssl.key-store-type=PKCS12

Full stack trace:
2017-11-22 16:38:09.554 ERROR 8556 --- [           main] org.apache.tomcat.util.net.SSLUtilBase   : Failed to load keystore type [PKCS12 ] with path [file:/C:/Users/dbush/workspace/my_app/target/classes/keystore.p12] due to [PKCS12  not found]

java.security.KeyStoreException: PKCS12  not found
    at java.security.KeyStore.getInstance(KeyStore.java:851) ~[na:1.8.0_131]
    at org.apache.tomcat.util.net.SSLUtilBase.getStore(SSLUtilBase.java:122) ~[tomcat-embed-core-8.5.14.jar:8.5.14]
    at org.apache.tomcat.util.net.SSLHostConfigCertificate.getCertificateKeystore(SSLHostConfigCertificate.java:187) [tomcat-embed-core-8.5.14.jar:8.5.14]
    at org.apache.tomcat.util.net.jsse.JSSEUtil.getKeyManagers(JSSEUtil.java:185) [tomcat-embed-core-8.5.14.jar:8.5.14]
    at org.apache.tomcat.util.net.AbstractJsseEndpoint.createSSLContext(AbstractJsseEndpoint.java:112) [tomcat-embed-core-8.5.14.jar:8.5.14]
    at org.apache.tomcat.util.net.AbstractJsseEndpoint.initialiseSsl(AbstractJsseEndpoint.java:85) [tomcat-embed-core-8.5.14.jar:8.5.14]
    at org.apache.tomcat.util.net.NioEndpoint.bind(NioEndpoint.java:225) [tomcat-embed-core-8.5.14.jar:8.5.14]
    at org.apache.tomcat.util.net.AbstractEndpoint.start(AbstractEndpoint.java:978) [tomcat-embed-core-8.5.14.jar:8.5.14]
    at org.apache.coyote.AbstractProtocol.start(AbstractProtocol.java:628) [tomcat-embed-core-8.5.14.jar:8.5.14]
    at org.apache.catalina.connector.Connector.startInternal(Connector.java:993) [tomcat-embed-core-8.5.14.jar:8.5.14]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150) [tomcat-embed-core-8.5.14.jar:8.5.14]
    at org.apache.catalina.core.StandardService.addConnector(StandardService.java:225) [tomcat-embed-core-8.5.14.jar:8.5.14]
    at org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainer.addPreviouslyRemovedConnectors(TomcatEmbeddedServletContainer.java:247) [spring-boot-1.5.3.RELEASE.jar:1.5.3.RELEASE]
    at org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainer.start(TomcatEmbeddedServletContainer.java:190) [spring-boot-1.5.3.RELEASE.jar:1.5.3.RELEASE]
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.startEmbeddedServletContainer(EmbeddedWebApplicationContext.java:297) [spring-boot-1.5.3.RELEASE.jar:1.5.3.RELEASE]
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.finishRefresh(EmbeddedWebApplicationContext.java:145) [spring-boot-1.5.3.RELEASE.jar:1.5.3.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:545) [spring-context-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122) [spring-boot-1.5.3.RELEASE.jar:1.5.3.RELEASE]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:737) [spring-boot-1.5.3.RELEASE.jar:1.5.3.RELEASE]
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:370) [spring-boot-1.5.3.RELEASE.jar:1.5.3.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:314) [spring-boot-1.5.3.RELEASE.jar:1.5.3.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1162) [spring-boot-1.5.3.RELEASE.jar:1.5.3.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1151) [spring-boot-1.5.3.RELEASE.jar:1.5.3.RELEASE]
    at dbush.App.main(App.java:23) [classes/:na]
Caused by: java.security.NoSuchAlgorithmException: PKCS12  KeyStore not available
    at sun.security.jca.GetInstance.getInstance(GetInstance.java:159) ~[na:1.8.0_131]
    at java.security.Security.getImpl(Security.java:695) ~[na:1.8.0_131]
    at java.security.KeyStore.getInstance(KeyStore.java:848) ~[na:1.8.0_131]
    ... 23 common frames omitted

2017-11-22 16:38:09.554 ERROR 8556 --- [           main] o.a.coyote.http11.Http11NioProtocol      : Failed to start end point associated with ProtocolHandler ["https-jsse-nio-8443"]

java.lang.IllegalArgumentException: java.io.IOException: Failed to load keystore type [PKCS12 ] with path [file:/C:/Users/dbush/workspace/myapp/target/classes/keystore.p12] due to [PKCS12  not found]
    at org.apache.tomcat.util.net.AbstractJsseEndpoint.createSSLContext(AbstractJsseEndpoint.java:114) ~[tomcat-embed-core-8.5.14.jar:8.5.14]
    at org.apache.tomcat.util.net.AbstractJsseEndpoint.initialiseSsl(AbstractJsseEndpoint.java:85) ~[tomcat-embed-core-8.5.14.jar:8.5.14]
    at org.apache.tomcat.util.net.NioEndpoint.bind(NioEndpoint.java:225) ~[tomcat-embed-core-8.5.14.jar:8.5.14]
    at org.apache.tomcat.util.net.AbstractEndpoint.start(AbstractEndpoint.java:978) ~[tomcat-embed-core-8.5.14.jar:8.5.14]
    at org.apache.coyote.AbstractProtocol.start(AbstractProtocol.java:628) ~[tomcat-embed-core-8.5.14.jar:8.5.14]
    at org.apache.catalina.connector.Connector.startInternal(Connector.java:993) [tomcat-embed-core-8.5.14.jar:8.5.14]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150) [tomcat-embed-core-8.5.14.jar:8.5.14]
    at org.apache.catalina.core.StandardService.addConnector(StandardService.java:225) [tomcat-embed-core-8.5.14.jar:8.5.14]
    at org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainer.addPreviouslyRemovedConnectors(TomcatEmbeddedServletContainer.java:247) [spring-boot-1.5.3.RELEASE.jar:1.5.3.RELEASE]
    at org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainer.start(TomcatEmbeddedServletContainer.java:190) [spring-boot-1.5.3.RELEASE.jar:1.5.3.RELEASE]
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.startEmbeddedServletContainer(EmbeddedWebApplicationContext.java:297) [spring-boot-1.5.3.RELEASE.jar:1.5.3.RELEASE]
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.finishRefresh(EmbeddedWebApplicationContext.java:145) [spring-boot-1.5.3.RELEASE.jar:1.5.3.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:545) [spring-context-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122) [spring-boot-1.5.3.RELEASE.jar:1.5.3.RELEASE]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:737) [spring-boot-1.5.3.RELEASE.jar:1.5.3.RELEASE]
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:370) [spring-boot-1.5.3.RELEASE.jar:1.5.3.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:314) [spring-boot-1.5.3.RELEASE.jar:1.5.3.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1162) [spring-boot-1.5.3.RELEASE.jar:1.5.3.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1151) [spring-boot-1.5.3.RELEASE.jar:1.5.3.RELEASE]
    at dbush.App.main(App.java:23) [classes/:na]
Caused by: java.io.IOException: Failed to load keystore type [PKCS12 ] with path [file:/C:/Users/dbush/workspace/myapp/target/classes/keystore.p12] due to [PKCS12  not found]
    at org.apache.tomcat.util.net.SSLUtilBase.getStore(SSLUtilBase.java:149) ~[tomcat-embed-core-8.5.14.jar:8.5.14]
    at org.apache.tomcat.util.net.SSLHostConfigCertificate.getCertificateKeystore(SSLHostConfigCertificate.java:187) ~[tomcat-embed-core-8.5.14.jar:8.5.14]
    at org.apache.tomcat.util.net.jsse.JSSEUtil.getKeyManagers(JSSEUtil.java:185) ~[tomcat-embed-core-8.5.14.jar:8.5.14]
    at org.apache.tomcat.util.net.AbstractJsseEndpoint.createSSLContext(AbstractJsseEndpoint.java:112) ~[tomcat-embed-core-8.5.14.jar:8.5.14]
    ... 19 common frames omitted

2017-11-22 16:38:09.555 ERROR 8556 --- [           main] o.apache.catalina.core.StandardService   : Failed to start connector [Connector[HTTP/1.1-8443]]

org.apache.catalina.LifecycleException: Failed to start component [Connector[HTTP/1.1-8443]]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:167) ~[tomcat-embed-core-8.5.14.jar:8.5.14]
    at org.apache.catalina.core.StandardService.addConnector(StandardService.java:225) ~[tomcat-embed-core-8.5.14.jar:8.5.14]
    at org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainer.addPreviouslyRemovedConnectors(TomcatEmbeddedServletContainer.java:247) [spring-boot-1.5.3.RELEASE.jar:1.5.3.RELEASE]
    at org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainer.start(TomcatEmbeddedServletContainer.java:190) [spring-boot-1.5.3.RELEASE.jar:1.5.3.RELEASE]
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.startEmbeddedServletContainer(EmbeddedWebApplicationContext.java:297) [spring-boot-1.5.3.RELEASE.jar:1.5.3.RELEASE]
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.finishRefresh(EmbeddedWebApplicationContext.java:145) [spring-boot-1.5.3.RELEASE.jar:1.5.3.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:545) [spring-context-4.3.8.RELEASE.jar:4.3.8.RELEASE]
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122) [spring-boot-1.5.3.RELEASE.jar:1.5.3.RELEASE]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:737) [spring-boot-1.5.3.RELEASE.jar:1.5.3.RELEASE]
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:370) [spring-boot-1.5.3.RELEASE.jar:1.5.3.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:314) [spring-boot-1.5.3.RELEASE.jar:1.5.3.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1162) [spring-boot-1.5.3.RELEASE.jar:1.5.3.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1151) [spring-boot-1.5.3.RELEASE.jar:1.5.3.RELEASE]
    at dbush.App.main(App.java:23) [classes/:na]
Caused by: org.apache.catalina.LifecycleException: service.getName(): "Tomcat";  Protocol handler start failed
    at org.apache.catalina.connector.Connector.startInternal(Connector.java:1000) ~[tomcat-embed-core-8.5.14.jar:8.5.14]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150) ~[tomcat-embed-core-8.5.14.jar:8.5.14]
    ... 13 common frames omitted
Caused by: java.lang.IllegalArgumentException: java.io.IOException: Failed to load keystore type [PKCS12 ] with path [file:/C:/Users/dbush/workspace/myapp/target/classes/keystore.p12] due to [PKCS12  not found]
    at org.apache.tomcat.util.net.AbstractJsseEndpoint.createSSLContext(AbstractJsseEndpoint.java:114) ~[tomcat-embed-core-8.5.14.jar:8.5.14]
    at org.apache.tomcat.util.net.AbstractJsseEndpoint.initialiseSsl(AbstractJsseEndpoint.java:85) ~[tomcat-embed-core-8.5.14.jar:8.5.14]
    at org.apache.tomcat.util.net.NioEndpoint.bind(NioEndpoint.java:225) ~[tomcat-embed-core-8.5.14.jar:8.5.14]
    at org.apache.tomcat.util.net.AbstractEndpoint.start(AbstractEndpoint.java:978) ~[tomcat-embed-core-8.5.14.jar:8.5.14]
    at org.apache.coyote.AbstractProtocol.start(AbstractProtocol.java:628) ~[tomcat-embed-core-8.5.14.jar:8.5.14]
    at org.apache.catalina.connector.Connector.startInternal(Connector.java:993) ~[tomcat-embed-core-8.5.14.jar:8.5.14]
    ... 14 common frames omitted
Caused by: java.io.IOException: Failed to load keystore type [PKCS12 ] with path [file:/C:/Users/dbush/workspace/myapp/target/classes/keystore.p12] due to [PKCS12  not found]
    at org.apache.tomcat.util.net.SSLUtilBase.getStore(SSLUtilBase.java:149) ~[tomcat-embed-core-8.5.14.jar:8.5.14]
    at org.apache.tomcat.util.net.SSLHostConfigCertificate.getCertificateKeystore(SSLHostConfigCertificate.java:187) ~[tomcat-embed-core-8.5.14.jar:8.5.14]
    at org.apache.tomcat.util.net.jsse.JSSEUtil.getKeyManagers(JSSEUtil.java:185) ~[tomcat-embed-core-8.5.14.jar:8.5.14]
    at org.apache.tomcat.util.net.AbstractJsseEndpoint.createSSLContext(AbstractJsseEndpoint.java:112) ~[tomcat-embed-core-8.5.14.jar:8.5.14]
    ... 19 common frames omitted

A: You need to add the following properties in application.yml for enabling https
server:
  ssl:
    enabled: ${SSL_ENABLED:true}
    key-store: classpath:certificate.p12
    key-store-password: edgepay123
    key-store-type: PKCS12
    key-alias: 1

It seems you are missing the server.ssl.key-store-type property
Also use the following dependency of spring boot security
   <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>

instead of the spring security dependency you are using

A: You added location to you keystore with this properties:server.ssl.key-store=classpath:keystore.p12
In spring boot classpath is src/main/resources folder. So put your keys in that folder like in the picture below.


text:
Q: How many compositions of n are there with same parity Let n be a non-negative integer. How many compositions of n are there where the i-th part has the same parity as i? For example, compositions of 7 that satisfy this condition are (7), (5,2), (3,4), (1,6), (1,2,1,2,1). Express your answer as the coefficient of a simplified rational expression.
can someone help me please :(

A: Hint: The number of solutions where there is exactly 1 part is the coefficient of $x^n$ in $x + x^3 + x^5 + \ldots  = \frac{x}{1-x^2}$.
Hint: The number of solutions where there are exactly 2 parts is the coefficients of $x^n$ in $(x+x^3+x^5 + \ldots ) \times (x^2 + x^4 + x^6 + \ldots )  = \frac{ x } { 1-x^2} \times \frac{x^2} { 1-x^2} $.
Hence, the number of solutions is (summing over all possible number of parts) is the coefficient of $x^n$ in
$$ \sum_{i=1}^\infty \left(\frac{x}{1-x^2} + \frac{ x } { 1-x^2} \times \frac{x^2} { 1-x^2} \right) \left(\frac{ x } { 1-x^2} \times \frac{x^2} { 1-x^2} \right)^i $$
Simplify this further.


text:
Q: Cannot make TextView's text to be vertically aligned center In this screenshot :

The text of the TextView "Vidy" is not centered vertically, I think it is at the top, here is code :
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:stretchColumns="*"
    android:shrinkColumns="*"
    style="@style/BazarStyle" >
    <TableRow
        android:id="@+id/tableRow1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        style="@style/BazarTitleStyle"
        android:layout_span="5"
        android:gravity="center"
        android:layout_marginBottom="5dp">
            <TextView
                android:id="@+id/title_tv"
                android:layout_width="wrap_content"
                android:layout_height="fill_parent"
                android:singleLine="true"
                android:scrollHorizontally="true"
                android:ellipsize="marquee"
                android:marqueeRepeatLimit="marquee_forever"
                android:textColor="#fff"
                android:gravity="center"
                style="@style/BazarStyleTransparent"/>
    </TableRow>
    <TableRow
        android:id="@+id/tableRow2"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" >
        <TextView
            android:id="@+id/tvtype"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/od_type"
            style="@style/BazarStyleLabel"
            />
        <Spinner
            android:id="@+id/type"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content">
            <requestFocus />
        </Spinner>
    </TableRow>
    <TableRow
        android:id="@+id/tableRow3"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" >
        <TextView
            android:id="@+id/tvproduit"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/od_product"
            style="@style/BazarStyleLabel" />
        <Spinner
            android:id="@+id/produit"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"/>
    </TableRow>
    <TableRow
        android:id="@+id/tableRow4"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" >
        <TextView
            android:id="@+id/tvtsena"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/od_market"
            style="@style/BazarStyleLabel" />
        <Spinner
            android:id="@+id/tsena"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"/>
    </TableRow>
    <TableRow
        android:id="@+id/tableRow5"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content">
        <TextView
            android:id="@+id/tvqte"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/od_quantity"
            style="@style/BazarStyleLabel" />
        <EditText
            android:id="@+id/qte"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:inputType="number"/>
        <EditText
            android:id="@+id/fatra_qte"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginRight="20dp"/>
    </TableRow>
    <TableRow
        android:id="@+id/tableRow6"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content">
        <TextView
            android:id="@+id/tvnorme"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/od_norm"
            style="@style/BazarStyleLabel" />
        <EditText
            android:id="@+id/norme"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"/>
    </TableRow>
    <TableRow
        android:id="@+id/tableRow7"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <TextView
            android:id="@+id/tvprix"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/od_price"
            style="@style/BazarStyleLabel" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="2"
            android:orientation="horizontal" >

        <EditText
            android:id="@+id/prix"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:inputType="number" />

        <TextView
            android:id="@+id/monnaie"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            style="@style/BazarStyleTransparent" />

        <TextView
            android:id="@+id/barre"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text=" / "
            style="@style/BazarStyleTransparent" />

        <EditText
            android:id="@+id/vidy_fatra"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:layout_marginRight="20dp"
            android:inputType="text" />

        </LinearLayout>

    </TableRow>
    <TableRow
        android:id="@+id/tableRow5"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center">
        <Button
            android:id="@+id/ok"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/button_ok" />
    </TableRow>

</TableLayout>

Code of styles :
<resources xmlns:android="http://schemas.android.com/apk/res/android">
    <style name="BazarStyle">
       <item name="android:background">@color/bg_color</item>
       <item name="android:textColor">@color/txt_color</item>
    </style>
    <style name="BazarTitleStyle">
       <item name="android:background">@color/bg_topbar_color</item>
       <item name="android:textColor">@color/txt_color</item>
    </style>
    <style name="BazarStyleTransparent">
       <item name="android:background">@null</item>
       <item name="android:textColor">@color/txt_color</item>
    </style>
    <style name="BazarStyleLabel">
       <item name="android:background">@null</item>
       <item name="android:textColor">@color/txt_color</item>
       <item name="android:layout_marginLeft">20dp</item>
    </style>
</resources>

<color name="bg_color">#6cb650</color>
    <color name="bg_topbar_color">#4d7e3a</color>
    <color name="txt_color">#FFF</color>

So how to make the text centered vertically ?

A: Put android:gravity="center_vertical" in TableRow with id tableRow7.......

<TableRow
        android:id="@+id/tableRow7"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_vertical" >

        <TextView
            android:id="@+id/tvprix"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="od_price"
            style="@style/BazarStyleLabel" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="2"
            android:orientation="horizontal" >

        <EditText
            android:id="@+id/prix"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:inputType="number" />

        <TextView
            android:id="@+id/monnaie"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            style="@style/BazarStyleTransparent" />

        <TextView
            android:id="@+id/barre"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text=" / "
            style="@style/BazarStyleTransparent" />

        <EditText
            android:id="@+id/vidy_fatra"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:layout_marginRight="20dp"
            android:inputType="text" />

        </LinearLayout>

    </TableRow>

A: use below property on your textview
                android:gravity="center_vertical"

or
    <TextView
        android:id="@+id/textView1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center_vertical"
        android:text="Check Vertical center"
        android:textSize="21sp"
        android:textStyle="bold" />

http://developer.android.com/reference/android/widget/TextView.html


text:
Q: In magento how do you limit the amount of items in the new product xml? Hi I've set up the new product xml and can access it via
http:/xxxxxxxx.com/index.php/rss/catalog/new/store_id/1/
But I'm having trouble because it is trying to get all the products and is causing (at times some memory problems)
Any help would be great!
Thanks
Richard

A: I believe this has been previously discussed: Magento limit the number of products shown with in the new products block
Hope this helps.
Regards,
Dan


text:
Q: why C++ Initialization list is before brace? I want to know what's difference in the following two class.
example 1:
class A
{
string name;
public:
  A(const char* _name):name(_name){}
  void print(){cout<<"A's name:"<<name<<endl;}
};

example 2:
class A
{
string name;
public:
  A(const char* _name){name(_name);}
  void print(){cout<<"A's name:"<<name<<endl;}}

why the example 1 is passed and the last one is wrong?
Thanks

A: The first example is an actual initialization.  It has a number of advantages, including being the only way to set up const members, and having proper exception-safety.
The second example is not valid C++, AFAIK.  If you had instead written name = name_, then this would just be normal assignment.  Of course, this isn't always possible; the object might be const, or not have an assignment operator defined.  This approach could also be less efficient that the first example, because the object is both default-initialized and assigned.
As for why the initializer list is before the constructor body; well, that's just the way the language has been defined.

A: In example 1 you initialize the string with the given value right away.
In example 2 you create an empty string first and assign it later on.
Despite some performance differences and ignoring possible differences due to copy constructor handling etc. it's essentially the same result.
However once you use a const member you'll have to use example 1's way to do it, e.g. I usually create unique IDs the following way:
class SomeObject
{
    static unsigned int nextID = 0;
    const unsigned int ID;
    SomeObject() : ID(nextID++)
    {
        // you can't change ID here anymore due to it being const
    }
}

A: That's just how the language is defined. The member initializers should be placed before the body of the constructor.

A: In the first example the member name is initialized with a ctr getting char * as parameter.
In the second case it is initialized with a default ctr at first and it gets value by the assignment operator (operator=) later. That's why it is wrong with your case that it is already constructed there so you can not use the ctr once again you could just use the assignment operator.

A: The reason is that name lookup works different in initializer lists and function bodies:
class A
{
  std::string foo; // member name
public:
  A(const char* foo) // argument name
    : foo(foo) // member foo, followed by argument foo.
  {
    std::cout << foo; // argument foo.
  }
};

If the initializer list was inside the function body, there would be an ambiguity between member foo and argument foo.

A: The motivation behind the initialization list is due to const field holding a object by value (as opposed to reference/pointer field).
Such fields must be initialized exactly once (due to their const-ness). If C++ didn't have initialization list then a ctor would look something like:
class A {
public:
  const string s;
  const string t;

  A() {
    // Access to either s or t is not allowed - they weren't initialized
    s = "some-string";
    // now you can access s but you can't access t
    f(*this);

    t = "some other string";
    // From now you can access both ...
  }
}

void f(A& a) {
  // Can you access a.s or a.t?
  cout << a.s << a.t;
}

Without an initialization list a ctor can pass a partially-initialized object of type A to a function, and that function will have no way of knowing which fields are initialized yet. Too risky and very difficult for the compiler/linker to check.


text:
Q: How to create an automated when tag is pushed to Github via github actions When some one pushes a tag to github an automated PR is to be created between main and this tag. i am very new to github actions and below code is not working for me. Although the action is executed but PR is not created. i checked the logs and found that action creates a  branch from latest main and compares with it  and since no changes are found nothing is done by the action.
How to compare the main with the tag and create a pr ?? Thanks in advance
name: Auto PR Generator

on:
  push:
    tags:
    - '*-release-v[0-9]+.[0-9]+.[0-9]+'

jobs:
  autopr:
    runs-on: ubuntu-latest
    steps:
    - name: checkout the code
      uses: actions/checkout@v2

    - name: extract the git commit
      uses: rlespinasse/git-commit-data-action@v1

    - name: Author information
      run: echo "Changes authored by ${{ env.GIT_COMMIT_AUTHOR_NAME }}"

    - name: raise a new pr
      uses: peter-evans/create-pull-request@v3
      with:
        base: main
        title: "This PR is created automatically"
        committer: ${{ env.GIT_COMMIT_AUTHOR_NAME }} <${{ env.GIT_COMMIT_AUTHOR_EMAIL }}">
        author: ${{ env.GIT_COMMIT_AUTHOR_NAME }} <${{ env.GIT_COMMIT_AUTHOR_EMAIL }}">
        body:
          PR Creation testing as a part of CI
        token: ${{ secrets.PAT }}


text:
Q: Disable "Response receipt" in a google form using google apps script? I'm using Google Apps Script to generate a form, however when I setCollectEmail(true) the Response receipt option is toggled automatically. I would like to disable it, but I can't seem to find a way by looking at the documentation.
How can I achieve that ?


text:
Q: Document with ability to change only certain words? I am creating an contract template. Instead of highlighting words which needs to be changes each time new contract is created, I'd like to have a fixed and changeable text.
How can I create a Word document where all text will be uneditable except certain words?
Will I be able to jump from word to word via tab or similar button?
I was actually searching for this solution on Google, but I was not sure which keywords to use against this search.

A: I think what you miss is the word "Form" :-)
See if this here helps:
http://office.microsoft.com/en-001/word-help/create-forms-that-users-complete-or-print-in-word-HA010030746.aspx

A: You can use words Developer tab. If this isn't on the ribbon go to:

*

*File,

*Options,

*Customize Ribbon,

*In the right hand box tick the developer checkbox.

In this tab you can create Active X controls such as text entries, Scroll bars and tick boxes.
once your document is created you then need to restrict editing.


text:
Q: ADO.NET - What is best practice for getting datareader values? Just wondering what is best practice for getting the values of a datareader. For example:
I have been doing this:
MyValue = Dr("ColumnName")

But have noticed other people doing:
MyValue = Dr.GetString("ColumnName")

I am intested to know the benifits of the 2nd method

A: The DbDataReader.GetString(int) method can only be used if you know the index of the column.  Using DbDataReader.GetString("ColumnName") is not possible as there is no such overload.  I.e. you have the following two options:
 string myValue1 = (string) Dr["ColumnName"];
 string myValue2 = Dr.GetString(columIndex);

The first line internally calls DbDataReader.GetOrdinal("ColumnName").

A: I've been using a wrapper that does a similar thing for a while that does the trick nicely.

     RowHelper helper = new RowHelper(Dr);
     MyValue = helper.IntColumn("ColumnName");

The nice thing about this is the helper will return pre-defined defaults for NULL columns (this is configurable).  I've got methods for all the main SQL data types.
To answer your question, the second method has some boxing / unboxing overhead but it would probably be a waste of your time to optimise this for a typical business application.

A: I made a couple of generic extension methods for that:
public static class DataReaderExtensions
{
    public static T GetValueOrNull<T>(this IDataRecord reader, string fieldName)
        where T : class
    {
        int index = reader.GetOrdinal(fieldName);
        return reader.IsDBNull(index) ? null : (T)reader.GetValue(index);
    }
}

You get the picture... I also have a GetValueOrDefault for value types.

A: DataReader returns type object so you need to cast the value from the DataReader to whatever type MyValue is so in the case of int
MyValue = (int)Dr("ColumnName");

or
MyValue = Convert.ToInt(Dr("ColumnName"));

or
MyValue = Dr("ColumnName").ToInt();

I'm not sure of performance differences but I think that could be construed as micro-optimizing unless working on extremely large data sets

A: Using AutoMapper:
var dataReader = ... // Execute a data reader
var views = Mapper.Map<IDataReader, IEnumerable<SomeView>>(_dataReader);


text:
Q: Solve this system of polynomial equations. Question
Solve
$\begin{cases}
6x-y-z=51\\
x^2+y^2+z^2=2010
\end{cases}$
for positive integers $x,y,z$.
Answer
$(x,y,z)=(17,40,11)$ or $(17,11,40)$.
My problem
Obviously $y+z=6x-51$ and $y^2+z^2=2010-x^2$, and then I got stuck here. I don't know how to continue.
You don't have to show me the complete solution. Just a hint will be fine.

A: Hint:
Replace the value of $z$
$$x^2+y^2+(6x-y-51)^2=2010$$ which is a quadratic equation in $x$
As $x$ is integer, the discriminant must be perfect square

A: Refer to the equation $y+z=6x-51$ as $(1)$ and $y^2+z^2=2010-x^2$ as $(2)$. Then $(1)^2 - (2)$ gives:
$$y^2+2yz+z^2 - (y^2+z^2) = (6x-51)^2 - 2010 + x^2$$
$$\Rightarrow 2yz = 36x^2-612x+2601 - 2010 +x^2$$
$$\Rightarrow 2yz = 37x^2-612x+591$$
$$\Rightarrow 37x^2-612x+(591 - 2yz)=0$$
Since $yz$ are positive, then the value of $x$ must lie between the roots of $37x^2-612x+(591 - 2(1)(1)) = 0$ or $37x^2-612x+589 = 0$.  Dividing by $37$ and rounding up gives $x^2-17x-16$, and since $x$ is positive, $0 < x < 17$.
The discriminant $(-612)^2 - 4(37)(591-2yz) = 296yz+287076 = 4(74yz + 71769)$ also must be a perfect square.
$71769 \equiv 26 \pmod {37}$. $26$ is a quadratic residue modulo $37$ so there is a solution.

A: Your observation is correct.
The inequality $$2y^2+2z^2\geq (y+z)^2$$
gives $$-38x^2+612x+1419\geq 0$$ which simplifies to
$$-x^2+16x+38>0$$ where $16$ and $38$ comes from rounding up $612\over38$ and $1419\over 38$
Complete the square and you get $(x-8)^2<102$ and therefore $x<18$.
From the first equation we know $x\geq9$ and from the second equation mod $4$ we two one of $x,y,z$ are odd, one is even. If $x$ is the even one then the first equation won't hold so $x$ is odd and can only be $11,13,15,17$.
Four cases shouldn't be hard to check manually.


text:
Q: Using the android backbutton with Dojomobile and phonegap in worklight Im creating an app (rather big one) with Worklight. When im testing the app in an android phone and press the backbutton it closes the app.. now i want it to go back one page. Right now the page navigation is with dojox mobile implemented system. this way:
<button data-dojo-type="dojox.mobile.ToolBarButton" data-dojo-props="transition:'fade',dir:'1',moveTo:'Contact'" class="buttonHem" style="color:black; font-size:1em;">Kontakta Oss</button>

is there a way to use the android backbutton without having to redo everything?
we have deadline in 2 weeks so there is really no time to redo the app with jquery mobile..
Answers will be appreciated.

A: The back button functionality should work in Dojo Mobile. Looking at the documentation for ToolBarButton I think what you need to do is use a # in front of your next view for the moveTo attribute. In your example it would be moveTo:'#Contact' Take a look at the moveTo attribute in the doc below for more info.
http://dojotoolkit.org/reference-guide/1.8/dojox/mobile/ToolBarButton.html

A: If you're talking about a hardware Android back button you have a WL API to override it's behaviour.
WL.App.overrideBackButton(function() { doSomething });
and WL.App.resetBackButton();