text:
Q: Indesign conditional text styling using ExtendScript Does anyone know if it's possible to style text a certain way using ExtendScript, only when a certain condition is met for the paragraph in question?
I've cobbled together an ExtendScript script that I use in InDesign to fix text styles when they aren't fixed properly by the Paragraph Style tool, and it works well so far - changing Courier and Arial Unicode text to Times New Roman and fixing the font size - but i would really like to include a function that changes Times New Roman Italic to Times New Roman Bold Italic - but ONLY when the paragraph it appears in has a first letter that is set in Univers. Is there a way I can include an 'if' statement that will only trigger this style change in those circumstances?
Here's my existing code:
  var mydoc = app.activeDocument;

var theFontSize = [
  'Courier New','16','Courier New','8.75',
  'Times New Roman','16','Times New Roman','8.75',
];

for (i = 0; i < (theFontSize.length/4); i++) {

  app.findTextPreferences = NothingEnum.nothing;
  app.changeTextPreferences = NothingEnum.nothing;
  app.findTextPreferences.appliedFont = theFontSize[i*4];
  if (theFontSize[(i*4)+1] != ''){
    app.findTextPreferences.pointSize = theFontSize[(i*4)+1];
  };
  app.changeTextPreferences.appliedFont  = theFontSize[(i*4)+2];
  if (theFontSize[(i*4)+3] != ''){
    app.changeTextPreferences.pointSize  = theFontSize[(i*4)+3];
    };
    mydoc.changeText();
  };

var theFontReplacements = [
  'Courier New','Regular','Times New Roman','Regular',
  'Courier New','Italic','Times New Roman','Italic',
  'Courier New','Bold','Times New Roman','Bold',
  'Courier New','Bold Italic','Times New Roman','Bold Italic',
  'Courier New','75 Black','Univers','75 Black',
  'Arial Unicode MS','Regular','Times New Roman','Regular',
];

for (i = 0; i < (theFontReplacements.length/4); i++) {

  app.findTextPreferences = NothingEnum.nothing;
  app.changeTextPreferences = NothingEnum.nothing;
  app.findTextPreferences.appliedFont = theFontReplacements[i*4];
  if (theFontReplacements[(i*4)+1] != ''){
    app.findTextPreferences.fontStyle = theFontReplacements[(i*4)+1];
  };
  app.changeTextPreferences.appliedFont  = theFontReplacements[(i*4)+2];
  if (theFontReplacements[(i*4)+3] != ''){
    app.changeTextPreferences.fontStyle  = theFontReplacements[(i*4)+3];
  };
  mydoc.changeText();

};

app.findTextPreferences = NothingEnum.nothing;
app.changeTextPreferences = NothingEnum.nothing;

A: This should get you started. It will be slower than using changeText, but I don't think you can do what you're asking with changeText.
// Change applied font of text set in Times New Roman Italic in paragraphs whose first character is set in Univers to Times New Roman Bold Italic

app.findTextPreferences.appliedFont = 'Times New Roman';
app.findTextPreferences.fontStyle = 'Italic';

var foundItems = app.activeDocument.findText(); // Set foundItems to all results of search according to app.findTextPreferences
for (var i = 0; i < foundItems.length; i++) { // For each result found
    var item = foundItems[i];
    if (item.paragraphs[0].characters[0].appliedFont.name.indexOf('Univers') == 0) { // If item's first enclosing paragraph's first character's font name starts with "Univers"
        item.appliedFont = 'Times New Roman\tBold Italic'; // Set item's font to Times New Roman italic
    }
};


text:
Q: Debian-Jessie: How do you check iptables status? In old sysvinit I would just do service iptables status and see if it was running or not.
But in newer Debian-Jessie I grep for iptables in the list of services and don't see iptables listed anywhere. And when I try to query the status via systemctl status iptables I get an error.
Debian-Jessie: How do you check iptables status?

A: Iptables in Linux is implemented as a number of kernel modules. Normally it is configured by some init script - but you can add and remove rules on the fly from the command line. So basically, there are (at least) thee relevant questions:

*

*Are the kernel modules loaded?

*Are any rules applied?

*Is my firewall script/program "running"?

The old iptables "service" was obsoleted by systemd. I think this project attempts to make a similar "service" available for Debian.
To see if the kernel modules are loaded:
# lsmod | grep ip_tables

To see the effective rules:
# iptables -L

or, if you want to see the NAT rules:
# iptables -t nat -L

In Debian there are a number of firewall packages that can set up the iptables rules for you. (I have not tried any of them, I usually roll out my own when I need it).
apt-cache search firewall | grep firewall | less

redpajama_set_name: RedPajamaStackExchange


text:
Q: View "Variables" and "Frames" tabs for IntelliJ at the same time? Currently, I have two separate tabs: variables and frames, and can only have one open at a time. i like to be able to view the stack trace (frame) and the variables (and possibly even the console) at the same time when I am in debug mode. How do I do this?

A: Try to restore the layout on the debugger tab (option is under the setting button to the left)


text:
Q: Grid View Autogenerated Column Data Type I am using asp.net grid view which has is populated dynamically that means it has auto generated columns at run time.
I just want to know db type of these columns whether a column is text , date or int type.
Please write back to me if any body has done this.
Regards
SYED

A: When the database contents are re-bound to the grid view from the database, they are always Strings. Even if you have a numeric or date column, the data is rebound as a String.
This method isn't suitable for discovering the datatypes of your database table(s).


text:
Q: Convolver node in AudioGraph (UWP) I'm trying to implement several types of reverberation effect (Hall, Room, Chamber). But I can not find a convolver node in UWP AudioGraph. Is there any analogue of it or maybe there is other way to apply impulse response to the audio buffer?

A: To implement reverberation effect in UWP, we can take advantage of ReverbEffectDefinition class.
This class represents a reverberation effect definition supported by the audio graph. You can demonstrate different types of reverberation effect by setting different values of ReverbEffectDefinition's properties. For more info about these properties' explanations, please refer to the MSDN page.
Once the effects are initialized, we can add them to the EffectDefinitions list of an audio graph node such as adding to the EffectDefinitions property of AudioFileInputNode class and then apply the reverberation effect by calling EnableEffectsByDefinition method. For more info, please refer to the AudioGraph sample especially Scenario 5: In-box Effects. And the article Custom audio effects also might be helpful.


text:
Q: Question about the encyclopedia of triangle centers The Encyclopedia of Triangle Centers has developed a neat approximate way to check whether an entry about a particular point already exists. It involves checking the first coordinate of the normalized trilinears of the "new" point against a list of all points.
All entries in the ETC however also list interesting properties of points, e.g. "X(44004) lies on these lines: {2, 35311}, {20, 10620}, {3448, 9033}, {5965, 43768}, {15319, 15801}"
My question is where do people get the data about tens of thousands of points to determine this, presumable in an automated way? I cannot imagine that this comes out of random checks, and also it is difficult to imagine that hundreds of contributors have typed all known points' barycentric coordinates in their own code to facilitate automatic checks.

A: The founders of "Encyclopedia of Triangle Centers" have mainly conducted an intelligent compilation and structuration of thousands of results found, considering the most important ones, a century ago...
This does not mean that, in particular with computers' help, a big number of new centers and/or properties haven't been discovered in the meanwhile.
I am going to explain it with a historical perspective.
In mid-18th century, only 5 remarkable triangle centers had been identified, the first four having 2 thousand years of "existence" (incenter, centroid, circumcenter, orthocenter), a fifth one having been added by Euler, the nine points circle center. In the ETC, these points are listed as the first ones (X(1)...X(5)).
In the first three quarters of the 19th century, some others were gradually obtained : Gergonne point (X(7)) Feuerbach point (X(11)), around 1820, Lemoine (or symmedian) point (X(6)) and Brocard points later, around 1880, etc. Please note that the ranking in ETC doesn't follow in the 19th century the "date of birth" of the points... It looks based on an estimated relative importance of these centers.
Then, a triangle-mania arose in the last quarter of the 19th century, with a first peak around 1890-1910, a second even more important peak between 1920 and 1950 with an incidence on secondary school syllabus, followed by a significant decrease. At that time, thousands of more or less amateur mathematicians have been hunting  properties of triangles (some of them rather remote, not to say sterile), and in particular have found this myriad of centers with, for many of them, barycentric or trilinear coordinates, alignment properties as you mention one, concyclicities, etc.
The "new maths" wave around 1960-1970 with a largely exaggered ban of figure geometry, left few people working on triangle geometry. It must be said that the "game" had become scarcer... most triangle properties had been found... with some exception, for example "Conway circle".
A regain of interest came in the 1990s, in particular due to possibilities offered by the computer.
Remark: Historicaly, remarkable points were defined using "pure geometry" also known as the "synthetic method". It is only gradually, through the slow adoption of barycentric (or areal) coordinates (introduced by Möbius in 1827) and/or trilinear coordinates (born some decades later in particular with their use in physics ; a first reference being by Gibbs in 1873) that algebraic approaches have proven their efficiency. Please note that classical cartesian coordinates are unable to render the ternary symmetry existing between the vertices/sides/angles of a triangle. One must not forget as well that the distinction made between metric, affine, projective invariance of the different points/lines, etc... wasn't familiar to the mind of these "amateur geometers" (although some of them were very smart !) at the eve of 20th century.
I end this part by showing (Fig. 1) a partial statistics of use of the words incenter and orthocenter (partial because the corpus is limited to books in the "Google books corpus" written in English). Many biases are to be taken into account, in particular the fact that the share of mathematical books has been shrinking during that time.

Fig. 1: Statistics of relative use of the word "incenter" and "orthocenter" from 1860 till now, obtained using  Google Books Ngram Viewer. One can note the "new math" impact in the 1970s followed by a considerable renewal of interest at the end of 20th century (due in part to ETC site !). Please note that the keyword "triangle" displays similar trends though some of its uses are outside mathematics. Another remark: The names "orthocenter" and "incenter" where created in the 1860s.
Edit:

*

*An interesting document about certification of ETC site using Coq.

*For recent works (since year 2000) on triangle geometry in particular, see the interesting "Forum Geometricum" journal.

*About the new trend at the end of 19th century, see the PhD thesis of Pauline Romera-Lebret "La nouvelle géométrie du triangle : passage d'une mathématique d'amateurs à une mathématique d'enseignants (1873-1929)"
(Univ. of Nantes, France, 2009).

*Another thesis (by E. Cook, Univ. of Florida, 1937) compiles the works of a certain J. Mackey. It gives an idea of the extreme meticulosity of some of the "founding fathers" (here, a little more than an amateur !) of what I have called triangle-mania.

*Another interesting article by Ph.J. Davis, "The rise, fall, and possible transfiguration of triangle geometry: A mini-history" Amer. Math. Monthly , 102 (1995) pp. 204–214

*About Conway's "elementary" accomplishments, see this answer https://mathoverflow.net/questions/357197/conways-lesser-known-results/357406#357406) and the surrounding ones.

*Don't miss Douillet's glossary dealing with barycentric coordinates of remarkable "centers".

*About the "new maths" episode, see the controversial paper of a famous geometer, Dan Pedoe here.


text:
Q: Получить все, а не только первое совпадение как ВПР(VLOOKUP) Дана таблица имён и фамилий, вот ссылка:
https://docs.google.com/spreadsheets/d/13IyzK_Wa-AuIUG4iiXh2hD8g4orikKB-eo-vEz6qIss/edit?usp=sharing
Нужно по фамилии найти имена всех людей с такой фамилией. Найти хотя бы одного легко с помощью VLOOKUP [C1] или формулой из [B1]. Формулы из [B2], [B3], [B4] и [B5] ищут как-раз то, что нужно - они ищут 1е 2е 3е и 4ое имена соответственно. Формула почерпнута из источника.
Помогите понять почему и как формула работает, а её составные части в столбце C не работают.

A:
Нужно по фамилии найти имена всех людей с такой фамилией.

Это задача фильтрации, а не поиска. И решается одной формулой:
=filter(B:B, A:A = "Ivanova")


text:
Q: How to use inline svg's in Blazor wasm .NET 5 My Blazor wasm project is targeting the .NET 5.0 runtime. I've got .NET SDK 5.0.200 and .NET Runtime 5.0.2 installed.
According to Zaneris on this Github issue, inline svg's can be used like this in Blazor:

   <svg> <use xlink:href="images/test.svg#test-logo" /> </svg>

However, I can only get it to work like this:

            <svg>
                <symbol id="test-logo" viewBox="0 0 255.905 185.056">
                    <g id="Group_284" data-name="Group 284" transform="translate(-65.569 -74.438)">
                        ...
                    </g>
                </symbol>
                <use xlink:href="#test-logo" />
            </svg>

What am I doing wrong? Do I need to link the svg file in the head tag? If so, what do I set the "rel" to?
I would love to be able to reference the symbol ID straight from the svg file in wwwroot.

A: I'd like to sell you on the idea of treating .svg code like any other markup and putting it into Razor components.  This way, you can put it inline anywhere you want, and control variables like you would with any other razor control:
Here's an .svg saved from illustrator: (sample.svg)

<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
     viewBox="0 0 100 100" enable-background="new 0 0 100 100" xml:space="preserve">
    <text transform="matrix(1 0 0 1 16.2917 24.9155)"><tspan x="0" y="0" font-family="'MyriadPro-Bold'" font-size="12px">Lorem ipsum</tspan></text>
    <circle fill="#EC008C" stroke="#000000" stroke-miterlimit="10" cx="50" cy="58.8" r="15.3" />
</svg>

Here's a razor page I made from it, (SampleSVG.razor).  Note the variables @Text and @fill.  I can put it anywhere I want like any other component: <SampleSVG />
@page "/svgsample"

Change Text: <input @bind="@Text" /><button @onclick="DoCoolStuff">Go Crazy!</button>

    <svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
            viewBox="0 0 100 100" enable-background="new 0 0 100 100" style="stroke-width: 0px; background-color: #000000;" xml:space="preserve">
        <text transform="matrix(1 0 0 1 16.2917 24.9155)">
            <tspan x="0" y="0" fill="orange" font-family="'MyriadPro-Bold'" font-size="12px">@Text</tspan>
        </text>
        <circle fill="@fill" stroke="#000000" stroke-miterlimit="10" cx="50" cy="58.8" r="15.3" />
    </svg>

@code {
    string Text = "Start Text";
    string fill = "#EC008C";
    Random random = new Random();

    async Task DoCoolStuff()
    {
        for (int i=0; i< 5; i++)
        {
            fill = String.Format("#{0:X6}", random.Next(0x1000000));
            StateHasChanged();
            await Task.Delay(200);
        }
    }
}

Pro-tip: since the button handler is async, if you click it over and over really fast, you can change the circle's color more than 5x / second.  DISCO! (and possible seizure warning. . . )

A: Okay, I made a sample file and tested the technique you mentioned in your OP, and was able to display two symbols from a single file by #referencing them.  So the technique seems not to be the problem.
However, they were upside down from the original.  My understanding was that you could just use a symbol and it would work, but maybe it needs a little more tinkering somehow, with regard to setting the viewboxes properly?
--edit--
According to Mozilla, "xlink:href" is now obsolete.  So there's a possibility that at some point in the future, client sites will break.  I doubt it will be soon because it seems to be a VERY new update, but something to consider.


text:
Q: DateTime strange error DateTime? billDateFrom = string.IsNullOrWhiteSpace(txtBillDateFrom.Text) ? null : (DateTime?)DateTime.Parse(txtBillDateFrom.Text);

txtBillDateFrom.Text equals "05/26/2011". (26 may 2011)
This code throws an error "String was not recognized as a valid DateTime" only in a web application. In a console application it works good.
Why? Does it depend on locale?

A: Yes, the behavior of Parse() depends on the current thread's culture. You can use ParseExact() to make that behavior consistent, regardless of that culture:
DateTime.ParseExact(txtBillDateFrom.Text, "d", CultureInfo.InvariantCulture)

A: Yes it does. You can change thread's culture, or get a CultureInfo for a desired locale and pass its DateTimeFormat to DateTime.Parse
// Setting in thread
Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.GetCultureInfo("en-US");
DateTime dt1 = DateTime.Parse("05/26/2011");
// Only for 1 parse
DateTime dt2 = DateTime.Parse("05/26/2011", System.Globalization.CultureInfo.GetCultureInfo("en-US").DateTimeFormat);

Also I beleive you can set the culture in asp.net application's settings.
<system.web>
    <globalization culture="en-US"/>
</system.web>

A: Yes, it depends on locale.
You can specify the locale that you want to use in the web.config file, or you can specify it in the call to Parse:`
DateTime.Parse(txtBillDateFrom.Text, CultureInfo.GetCultureInfo("en-GB"))

A: It depends on current culture. In web.config you can set needed culture:
<globalization uiCulture="it" culture="it-IT" />

A: Try Below
 DateTime dt;
        DateTime.TryParse("05/26/2011", out dt);


text:
Q: Why the requirement for custom allocators to be copyconstructible? The C++11 standard (or at least, this working draft) requires that classes which implement the Allocator concept provide copy constructors.
This made sense back when all allocators had to be stateless, but when state is allowed in an allocator class, providing a copy constructor might not be desirable.  For example, if the allocator implements some kind of slab allocation system or memory pool, where it maintains an internal freelist.  It seems to me that such an allocator should always be moved, never copied.  Actually copying it would require allocating new storage and then completely reproducing the internal state of the original allocator, including all free memory blocks, free-lists, etc.  (Or does "copying" an Allocator simply imply returning Allocator(), i.e. returning a new default-constructed allocator?)
Actually copying a state-ful allocator seems to be totally unnecessary because as far as I can see, in practice there's no real common use-case for copy-constructing an allocator.  No Container actually copies an allocator - C++11 containers will call Allocator::select_on_container_copy_construction within the container copy constructor instead, which usually just returns Allocator().  Then the container will usually just copy element by element from the other container, probably by just calling Container::insert.
Of course an optimized container implementation might do something more complex using internal knowledge about the container structure, but still nobody is going to copy-construct other.get_allocator() - the Container will just call other.get_allocator().select_on_container_copy_construction() to get a default-constructed allocator.
So why do we have the requirement that an Allocator itself must be copy-constructible?  Shouldn't move construction be sufficient?

Note: To be clear, this question is not a duplicate of why does allocator in c++ need a copy constructor?.  That question is asking specifically about std::allocator (which is stateless), whereas I am asking about custom allocators that implement the Allocator concept.

A: Re the claim

"  No Container actually copies an allocator

that may be so (I haven't tested), and std::string may be regarded as a non-Container, but still:
#include <string>
#include <iostream>
#include <memory>       // std::allocator

template< class Type >
struct Alloc
    : std::allocator<Type>
{
    using Base = std::allocator<Type>;

    template< class Other >
    struct rebind
    {
        using other = Alloc<Other>;
    };

    Alloc() {}

    Alloc( Alloc<Type> const& other )
        : Base( other )
    { std::clog << "Alloc::<copy>\n"; }

    template<class Other>
    Alloc( Alloc<Other> const& other )
        : Base( other )
    { std::clog << "Alloc::<generic-copy>\n"; }
};

auto main() -> int
{
    using namespace std;
    basic_string< char, char_traits<char>, Alloc<char> > a = "A", b = "B";
    a = b;
}

Output with Visual C++:

Alloc::<copy>
Alloc::<copy>

With g++ the number of allocator copy operations is higher.

A: The standard library Containers typically have constructors that take a reference-to-const of an existing allocator object; e.g. vector has since C++20
constexpr explicit vector( const Allocator& alloc ) noexcept;

Move construction would not be appropriate semantics because no resources can be removed from alloc, as it is const. Copy construction is necessary for this purpose because the lifetime of alloc is unspecified and alloc cannot be used for state-modifying allocations. See also Why is allocator const in vector?.
You can have an Allocator with a reference to an underlying allocating class to avoid copying memory management data, or to share it across multiple Allocators. But you could safely use state in an Allocator to provide per-Container memory as long as you provide an appropriate copy constructor or select_on_container_copy_construction member function (which could be a call to the default constructor).
Given an Allocator A,
std::allocator_traits<A>::select_on_container_copy_construction

returns a copy of A if A does not provide the member function select_on_container_copy_construction.


text:
Q: If statement inside a for loop to find a function? I am trying to find the value of two functions with two variables by using for loop. Then I want them to satisfy a condition and if that holds then I want to write only those sets of the variables for which the rate just becomes less than exp and then go to the next value. I have tried like this but didn't work. It is printing all those sets for which rate < exp. How can I do that?
rate= 0.5 (T^5/rt^4);
exp=10^(-18) T^2;
For[rt=10^3,rt <= 10^5,rt=rt+10
For[T=1,T <= 10^3,T=T+10
Evaluate[exp];
Evaluate[rate];
If[rate < exp, Print[{rt, T}]]
]
]

A: Something like this?
rate = 1/2 (T^5/rt^4);
exp = 10^(-18) T^2;

Assuming[T > 0 && rt > 0,
  Reduce[rate < exp, {T, rt}] // FullSimplify]
(*    rt > 10000 2^(1/4) Sqrt[5] T^(3/4)    *)

% // N
(*    rt > 26591.5 T^(3/4)    *)

A: Using the numbers you gave, it will take forever to finish. (it is also using For loop, which is slow).
I fixed few things to make it run, and changed couple of numbers to make it finish quickly.
It is not recommended to use For in Mathematica. But here is your For version which now works. Using a functional approach will make it faster. May be someone can make a functional version of this if they like.
ClearAll[rate, exp, T, rt];
rate[T_, rt_] := 0.5 (T^5/rt^4);
exp[T_] := 10^(-1) T^2;  (*10^(-18) T^2; makes it grow too slow*)
First@Last@Reap@For[rt = 10^3, rt <= 10^4, rt = rt + 10;
    For[T = 1, T <=10, (*10^3, makes it take very long time*)
     T = T + 10 exp[T];
     If[rate[T, rt] < exp[T],
      Sow[{rt, T}]
      ]
     ]
    ]


text:
Q: `security unlock-keychain` from a bash script On MacOSX, if I ssh in and run the command:
security -v unlock-keychain -p <password> <keychain_path>

The keychain unlocks and all is well with the world.
If I put that same command into a bash script and run
bash test.sh

I get prompted for the password.
How can I get around this?

A: You need to explicitly let your script test.sh access your keychain.

*

*Open the Keychain Access

*Right click on the private key

*Select "Get Info"

*Select "Access Control" tab

*Click "Allow all applications to access this item"

*Click "Save Changes"

*Enter your password

*Enjoy

Credits: Running xcodebuild from a forked terminal


text:
Q: Connecting WSO2 Identity Server to an External LDAP source using startTLS We have recently migrated our internal ApacheDS embedded LDAP service over to an external OpenLDAP server in our WSO2 Identity Server (4.6.0). That has been working well for last month.
In an effort to secure the environment further, I have created a new OpenLDAP cluster which enforces the use of TLS (startTLS). Below is my user-mgt.xml file. I have also imported the cacert.pem from the OpenLDAP server into the ./resources/security/client-truststore.jks on both of our IS nodes.
At startup I receive the follow errors:
Cannot create connection to LDAP server. Error message Error obtaining connection. [LDAP: error code 13 - TLS confidentiality required]
Below is my user-mgt.xml
            <UserManager>
            <Realm>
                <Configuration>
                        <AddAdmin>true</AddAdmin>
                        <AdminRole>admin</AdminRole>
                        <AdminUser>
                             <UserName>admin</UserName>
                             <Password>SECRET</Password>
                        </AdminUser>
                    <EveryOneRoleName>everyone</EveryOneRoleName> <!-- By default users in this role sees the registry root -->
                    <Property name="dataSource">jdbc/bpsdbq</Property>
                </Configuration>

                <!-- If product is using an external LDAP as the user store in read/write mode, use following user manager
                        In case if user core cache domain is needed to identify uniquely set property <Property name="UserCoreCacheIdentifier">domain</Property>
                -->
                <UserStoreManager class="org.wso2.carbon.user.core.ldap.ReadWriteLDAPUserStoreManager">
                    <Property name="TenantManager">org.wso2.carbon.user.core.tenant.CommonHybridLDAPTenantManager</Property>
                    <Property name="ConnectionURL">ldap://ourldap.server.com</Property>
                    <Property name="Disabled">false</Property>
                    <Property name="ConnectionName">cn=admin,dc=wso2,dc=org</Property>
                    <Property name="ConnectionPassword">SECRET</Property>
                    <Property name="passwordHashMethod">SHA</Property>
                    <Property name="UserNameListFilter">(objectClass=person)</Property>
                    <Property name="UserEntryObjectClass">inetOrgPerson</Property>
                    <Property name="UserSearchBase">ou=users,dc=wso2,dc=org</Property>
                    <Property name="UserNameSearchFilter">(&(objectClass=person)(cn=?))</Property>
                    <Property name="UserNameAttribute">cn</Property>
                    <Property name="UsernameJavaRegEx">[a-zA-Z0-9._-|//]{3,30}$</Property>
                    <Property name="UsernameJavaScriptRegEx">^[\S]{3,30}$</Property>
                    <Property name="RolenameJavaScriptRegEx">^[\S]{3,30}$</Property>
                    <Property name="RolenameJavaRegEx">[a-zA-Z0-9._-|//]{3,30}$</Property>
                    <Property name="PasswordJavaScriptRegEx">^[\S]{5,30}$</Property>
                    <Property name="ReadGroups">true</Property>
                    <Property name="WriteGroups">true</Property>
                    <Property name="EmptyRolesAllowed">false</Property>
                    <Property name="GroupSearchBase">ou=groups,dc=wso2,dc=org</Property>
                    <Property name="GroupNameListFilter">(objectClass=groupOfNames)</Property>
                    <Property name="GroupEntryObjectClass">groupOfNames</Property>
                    <Property name="GroupNameSearchFilter">(&(objectClass=groupOfNames)(cn=?))</Property>
                    <Property name="GroupNameAttribute">cn</Property>
                    <Property name="SharedGroupNameAttribute">cn</Property>
                    <Property name="SharedGroupSearchBase">ou=SharedGroups,dc=wso2,dc=org</Property>
                    <Property name="SharedGroupEntryObjectClass">groupOfNames</Property>
                    <Property name="SharedGroupNameListFilter">(objectClass=groupOfNames)</Property>
                    <Property name="SharedGroupNameSearchFilter">(&(objectClass=groupOfNames)(cn=?))</Property>
                    <Property name="SharedTenantNameListFilter">(objectClass=organizationalUnit)</Property>
                    <Property name="SharedTenantNameAttribute">ou</Property>
                    <Property name="SharedTenantObjectClass">organizationalUnit</Property>
                    <Property name="MembershipAttribute">member</Property>
                    <Property name="UserRolesCacheEnabled">true</Property>
                    <Property name="ReplaceEscapeCharactersAtUserLogin">true</Property>
                    <Property name="MaxRoleNameListLength">100</Property>
                    <Property name="MaxUserNameListLength">100</Property>
                    <Property name="SCIMEnabled">false</Property>
                </UserStoreManager>

                <AuthorizationManager
                    class="org.wso2.carbon.user.core.authorization.JDBCAuthorizationManager">
                    <Property name="AdminRoleManagementPermissions">/permission</Property>
                    <Property name="AuthorizationCacheEnabled">true</Property>
                </AuthorizationManager>
            </Realm>
        </UserManager>

Any help would be appreciated!
Thanks!

A: WSO2IS does not support to connect with startTLS. You can find an open jira for this. However, you can connect with normal SSL/TLS. Yes..then you need to import the openLDAP certificate in to resources/security/client-truststore.jks  and connect to the SSL LDAPS port of the openLDAP


text:
Q: What is the property of object in fabricjs similar to css's overflow : hidden I am trying to make fixed size text object using fabric js.
So I tried to set the text object's left, top, width and height but that width and height is changed after entering text.
I want to hide all the overflow part.
  var canvas = new fabric.Canvas('c');
    canvas.setHeight(300);
        canvas.setWidth(500);

canvas.add(new fabric.Text('Tap and Type', {
      left: 50,
      top: 100,
      width: 300,
      height: 200,
      fontFamily: 'arial black',
      fill: '#333',
      fontSize: 50
}));

Is there anyone who have built text object similar to html textarea using fabric js?
I tried to find on google but not found.
Can it be done easily using fabric text object attribute?
Jsfiddle : https://jsfiddle.net/Lvfpq57h/117/

A: I think your problem is not solved as simple attribute of text object. Please see reference issue. https://github.com/kangax/fabric.js/issues/187
And here's something helpful. http://jsfiddle.net/3j352toh/19/
Here redefined fabric.Textbox.prototype._wrapLine to format the text as you want.
CODE:
fabric.Textbox.prototype._wrapLine = function(ctx, text, lineIndex) {
    var lineWidth        = 0,
        lines            = [],
        line             = '',
        words            = text.split(' '),
        word             = '',
        letter           = '',
        offset           = 0,
        infix            = ' ',
        wordWidth        = 0,
        infixWidth       = 0,
        letterWidth      = 0,
        largestWordWidth = 0;

    for (var i = 0; i < words.length; i++) {
        word = words[i];
        wordWidth = this._measureText(ctx, word, lineIndex, offset);
        lineWidth += infixWidth;

        // Break Words if wordWidth is greater than textbox width
        if (this.breakWords && wordWidth > this.width) {
            line += infix;
            var wordLetters = word.split('');
            while (wordLetters.length) {
                letterWidth = this._getWidthOfChar(ctx, wordLetters[0], lineIndex, offset);
                if (lineWidth + letterWidth > this.width) {
                    lines.push(line);
                    line = '';
                    lineWidth = 0;
                }
                line += wordLetters.shift();
                offset++;
                lineWidth += letterWidth;
            }
            word = '';
        } else {
            lineWidth += wordWidth;
        }

        if (lineWidth >= this.width && line !== '') {
            lines.push(line);
            line = '';
            lineWidth = wordWidth;
        }

        if (line !== '' || i === 1) {
            line += infix;
        }
        line += word;
        offset += word.length;
        infixWidth = this._measureText(ctx, infix, lineIndex, offset);
        offset++;

        // keep track of largest word
        if (wordWidth > largestWordWidth && !this.breakWords) {
            largestWordWidth = wordWidth;
        }
    }

    i && lines.push(line);

    if (largestWordWidth > this.dynamicMinWidth) {
        this.dynamicMinWidth = largestWordWidth;
    }

    return lines.slice(0,this.cHeight/this.lineHeight/this.fontSize);
};

var _fabric = new fabric.Canvas('breaker');
_fabric.setBackgroundColor('#eee', _fabric.renderAll.bind(_fabric));

var curWidth = document.getElementById('breaker').width;
var curHeight = document.getElementById('breaker').height;
var longText="ABCDEFEFABCDEFEFABCDEFEFABCDEFEFABCDEFEFABCDEFEFABCDEFEFABCDEFEFABCDEFEFABCDEFEFABCDEFEF";
var breakingTextbox = new fabric.Textbox(longText,
    {
        width: curWidth / 2,
        cHeight: curHeight/2,
        left: curWidth / 2,
        top: 180,
        fill: '#333',
        cursorWidth: 0.5,
        originX: 'center',
        originY: 'top',
        textAlign: 'center',
        breakWords: true
});
_fabric.add(breakingTextbox).setActiveObject(breakingTextbox);
breakingTextbox.enterEditing();

A: Just use the Textbox class instead of the Text.
It is editable by default and will wrap the text when not fitting the width. (it will not hide it as overflow:hidden but will work as a textarea where the text wraps)
canvas.add(new fabric.Text('Tap and Type', {

https://jsfiddle.net/gaby/Lvfpq57h/118/


text:
Q: VisualSVN - set up repository and set access to use Basic Windows Authentication - login results in 403? I've set up my repository using VisualSVN Server, imported an existing repostiory, and set the user access rights to use Windows Authentication (Basic). I then try to access the URL of the created repository; after entering my username and password, I am immediately greeted with a 403 Forbidden notice (even though I have specified both Read / Write privileges to myself using VisualSVN Server Manager console).
I've tried using VisualSVN's own username/password combo, and this works successfully. It's only when authenticating via Active Directory, and entering the username and password correctly, that I get this 403 (of course, if I enter it incorrectly, I am prompted for a username and password once more).
Can anyone point me in the right direction?
Cheers

A: I guess that when you installed VisualSVN Server you selected Subversion authentication and authorization type and then later switched to Basic Windows authentication. In such case VisualSVN Server does not automatically create a file required to be in each repository's /conf directory "VisualSVN-WinAuthz.ini". This is currently by design for security reasons but the behavior is going to be improved in future releases.

So I suggest you to check VisualSVN Server's eventlog:
Start eventvwr.msc |  Applications and Services Logs | VisualSVN Server log.
What error event do you see there?
If the error is
 Failed to load the AuthzVisualSVNReposRelativeAccessFile: Can't open
 file 'C:\Repositories\MyRepo\conf\VisualSVN-WinAuthz.ini': The system
 cannot find the file specified. (OS 2)

Then you have to create the file which contains the list of authorization rules. To do this you can go to Security properties of a repository in VisualSVN Server Manager console and add / remove any account from the list. This will force VisualSVN Server to create an empty authorization file and global permissions will start working properly.

A: I face the same issue but i resolved, kindly find the my below error.

Failed to load the AuthzVisualSVNSubversionReposRelativeAccessFile: An
  authz rule refers to group '@ReleaseTeam', which is undefined
  (220003) APR does not understand this error code
     192.168.10.131

Error Meaning:
This error shows there is no groups like ReleaseTeam, while we taking backups from existing server  that backups refers some users and groups which we created earlier.
So I suggest you to check VisualSVN Server's eventlog:
Start eventvwr.msc | Applications and Services Logs | VisualSVN Server log.
What error event do you see there?
If the error is:

Failed to load the AuthzVisualSVNSubversionReposRelativeAccessFile: An
  authz rule refers to group '@ReleaseTeam (Username or Groups from
  existing Visual SVN Server)', which is undefined

Steps to follow:
Find the user or group name and Create the same groupname or users in new Visual SVN Server. Try this it will work definitely


text:
Q: Sort NSMutableArray is same order as another NSMutableArray I'm using a NSMutableArray *allObjectsArray; with dictionaries to fill a Table View with content.
Now I want to use a second NSMutableArray *userDataArray; (also with dictionaries) to display some user defined data in the same TableView.
To make a way for the dictionaries from the different arrays to recognize each other, they both have a string with key: "Name" with matching values.
So how can I write a code so that the userDataArray objects are in the same order as the allObjectsArray objects using the matching values from the "Name" key?
So when the cells are created, the [allObjectsArray objectAtIndex: indexPath.row] should now reprecent the same object as [userDataArray objectAtIndex: indexPath.row]

A: Why don't you just associate the objects in userDataArray to the objects in allObjectsArray directly? For example, each object in allObjectsArray can have a userData field that points to the associated object in userDataArray
In any case, if you really want to sort them you can do this:
NSArray * descriptors = @[ [ NSSortDescriptor sortDescriptorWithKey:@"Name" ascending:YES ] ] ;
allObjectsArray = [ allObjectsArray sortedArrayUsingDescriptors:descriptors ] ;
userDataArray = [ allObjectsArray sortedArrayUsingDescriptors:descriptors ] ;

EDIT: To directly associate the dictionaries from userDataArray with those in allObjectsArray
For each object in allObjectsArray, since they're dictionaries, you can just do this
NSDictionary * dictionaryFromAllObjectsArray = ...
[ dictionaryFromAllObjectsArray setObject:associatedUserObject forKey:@"userObject" ]

Now they're associated...
Later:
NSDictionary * dictionaryAtIndex = [ allObjectsArray objectAtIndex:indexPath.row ] ;
NSDictionary * userDictionaryAtIndex = [ dictionaryAtIndex objectForKey:@"userObject" ] ;

A: The best way is to restructure your data so that you only have a single dictionary for any name and it combines the objects and keys that you currently have in your pair of dictionaries.  That would mean only needing one array and once it's sorted you have the rows you need.


text:
Q: handling events in java swing How can I assign two buttons to share the same class for handling events in Java/swing?
For example, I have this:
private class BtnEvtHandler implements ActionListener {

        private int counter=10;

        public void actionPerformed(ActionEvent e) {
            gs.setX(counter);
            gs.repaint();
            counter=counter+10;
        }

        public void actionPerformed(ActionEvent e) {

                //action for move button
        }

    }

        JButton jumpBtn= new JButton("JUMP");
        BtnEvtHandler okButtonHandler= new BtnEvtHandler();
        (jumpBtn).addActionListener(okButtonHandler);
        menuPanel.add(jumpBtn);

Now I want to add another button as below which can have the same class as event handler but dispatches to different actionPerformed as mentioned in above code.
        JButton moveBtn= new JButton("MOVE");
        menuPanel.add(moveBtn);
        (moveBtn).addActionListener(okButtonHandler);

A: You can't reuse one ActionListener and expect it to call a different method depending on the button you attach it to.  The contract of ActionListener has one method that gets called.  But you can check the source of the event and have flow control based on that.  Here's an example:
package com.sandbox;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.WindowConstants;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;

public class SwingSandbox {

    public static void main(String[] args) throws IOException {
        JFrame frame = buildFrame();

        JPanel pane = new JPanel();

        MyActionListener myActionListener = new MyActionListener();

        JButton button1 = new JButton("Button1");
        button1.addActionListener(myActionListener);
        pane.add(button1);
        JButton button2 = new JButton("Button2");
        button2.addActionListener(myActionListener);
        pane.add(button2);

        frame.add(pane);
    }

    private static JFrame buildFrame() {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.setSize(200, 200);
        frame.setVisible(true);
        return frame;
    }

    private static class MyActionListener implements ActionListener {

        @Override
        public void actionPerformed(ActionEvent e) {
            JButton source = (JButton) e.getSource();
            if ("Button1".equals(source.getText())) {
                System.out.println("You clicked button 1");
            } else {
                System.out.println("You clicked button 2");
            }
        }
    }

}


text:
Q: Number of ways to choose tuples I have six numbers: 1,2,3,4,5,6
I need to count in how many ways (I expect every way will have 5 tuples).  Difference of two tuple members must not be bigger than 1.
For example:
(1,2) (2,3) (3,4) (4,5) (5,6) // this is one way
Is there any way to count this?
I need algorithm to write all possible ways.
Many tnx!

A: 1) Unordered tuples of the form $(a, a+1)$, where $a$ and $a+1$ belong to the list of $n$ consecutive integers, $\{m_1, m_1+1, m_1+2, ..., m_1+n-1\}$: You can select $a$ in $n-1$ ways; $a$ has to come from $\{m_1, m_1+1, m_1+2, ..., m_1+n-2\}$. Therefore, you get $n-1$ unordered tuples.
2) Unordered tuples of the form $(a, a)$, where $a$ belongs to the list of $n$ consecutive integers, $\{m_1, m_1+1, m_1+2, ..., m_1+n-1\}$: You can select $a$ in $n$ ways. Therefore, you get $n$ tuples.
The total number of unordered tuples is $n+n-1=2n-1$. Note that if the tuples are ordered, we can reverse each tuple of case (1) to get another admissible tuple. This process doesn't generate new tuples for any tuple of case (2). The total tuples will then be $n+2(n-1)=3n-2$.


text:
Q: How to adapt the size of multiple plots? How can I adapt the size of the following plots with regard to their length of the x-axis?

The width of the plots should refer to the length of their respective section of the x-axis. The height should be the same for all plots.

A: The function you want is base graphics function help("layout").
First I will make up a dataset, since you have not posted one. I will not draw the regression lines, just the points.
Data creation code.
fun <- function(X, A) {
  apply(X, 1, function(.x){
    xx <- seq(.x[1], .x[2], length.out = 100)
    y <- A[1]*xx + A[2] + rnorm(100, 0, 25)
    list(xx, y)
  })}

Coef <- matrix(c(0.24, 0.54,
                 0.75, 0.54,
                 0.33, 2.17,
                 0.29, 3.3,
                 0.29, 4.41), byrow = TRUE, ncol = 2)

X <- matrix(c(0.1, 0.49,
              0.5, 2.49,
              2.5, 3.9,
              4.0, 5.9,
              6.0, 12.0), byrow = TRUE, ncol = 2)

set.seed(1234)
res <- fun(X, Coef)

The problem.
Define a layout matrix with each plot in a sequence from first to 5th. And the widths given by the X ranges.
layout_mat <- matrix(c(1, 2, 3, 4, 5), 1, 5, byrow = TRUE)
w <- apply(X, 1, diff)
l <- layout(layout_mat, widths = w)
layout.show(l)

Now make some room for the axis annotation, saving the default graphics parameters, and plot the 5 graphs.
om <- par(mar = c(3, 0.1, 0.1, 0.1),
          oma = c(3, 2, 0.1, 0.1))
for(i in 1:5) plot(res[[i]][[1]], res[[i]][[2]])
par(om)


text:
Q: Dynamic int value int[] numbers = { 1, 2, 3, 4, 5 };
12 rows in my ListView,
I want the first item to have the lowest index in the array and the last item to have the highest index of the array.
The reason is because there is going to be a fade between the first item and the last and I want it to be with these 5 colors no matter how many list items I have.
But what happens when,
if items = 12,
1 has number 1,
2 has number 1,
3 has number 2,
4 has number 2
etc...
What if I have more numbers or more items? Am I completely stupid? Yelp!
Edit:
First item: 0%,
Last item: 100%,
No matter how many items!

A: I noticed this from your comments: item.setColorFilter( Color.parseColor( allColors[ ( position / itemCount ) ] ), Mode.SRC_ATOP);
You are using position / itemCount. I assume that both of those are integers, which means that since position is smaller than itemCount, this division will always return 0. What you want to do is to find a relative position for an item in your item list. This position can then be used to find a corresponding position in the number list.
double pos = (double)position/(double)itemCount; // item 5 has 5/12 = 0.42
int colorPos = pos*allColors.length(); // Find position based on number of colors
// item 5: 0.42*5 = 2.1, cast to int ->2. 5 gets color at index 2

item.setColorFilter( Color.parseColor( allColors[ (colorPos) ] ), Mode.SRC_ATOP);

Hope this helps!


text:
Q: Formula for memory alignment While browsing through some kernel code, I found a formula for memory alignment as

aligned = ((operand + (alignment - 1)) & ~(alignment - 1))

So then I even write a program for this:
#include <stdio.h>

int main(int argc, char** argv) {
    long long operand;
    long long alignment;
    if(argv[1]) {
        operand = atol(argv[1]);
    } else {
        printf("Enter value to be aligned!\n");
        return -1;
    }
    if(argv[2]) {
        alignment = strtol(argv[2],NULL,16);
    } else {
        printf("\nDefaulting to 1MB alignment\n");
        alignment = 0x100000;
    }
    long long aligned = ((operand + (alignment - 1)) & ~(alignment - 1));
    printf("Aligned memory is: 0x%.8llx [Hex] <--> %lld\n",aligned,aligned);
    return 0;
}

But I don't get this logic at all. How does this work?

A: Basically, the formula increase an integer operand (address) to a next address aligned to the alignment.
The expression
aligned = ((operand + (alignment - 1)) & ~(alignment - 1))

is basically the same as a bit easier to understand formula:
aligned = int((operand + (alignment - 1)) / alignment) * alignment

For example, having operand (address) 102 and alignment 10 we get:
aligned = int((102 + 9) / 10) * 10
aligned = int(111 / 10) * 10
aligned = 11 * 10
aligned = 110

First we add to the address 9 and get 111. Then, since our alignment is 10, basically we zero out the last digit, i.e. 111 / 10 * 10 = 110
Please note, that for each power of 10 alignment (i.e. 10, 100, 1000 etc) we basically zeroing out last digits.
On most CPUs, division and multiplication operations take much more time than bitwise operations, so let us get back to the original formula:
aligned = ((operand + (alignment - 1)) & ~(alignment - 1))

The second part of the formula makes sense only when alignment is a power of 2. For example:
... & ~(2 - 1) will zero last bit of address.
... & ~(64 - 1) will zero last 5 bits of address.
etc

Just like with zeroing out last few digits  of an address for power of 10 alignments, we zeroing out last few bits for power of 2 alignments.
Hope it does make sense for you now.


text:
Q: Find pair values MySQL Query between min and max in two tables I have two table:

Can't run query, to display "Result" table, pls help.

A: Consider:
SELECT
    t1.id,
    t2.id1,
    t2.col
FROM table1 t1
INNER JOIN table2 t2
    ON  t1.nr1 BETWEEN t2.MinNr1 AND t2.MaxNr1
    AND t1.nr2 BETWEEN t2.MinNr2 AND t2.MaxNr2

A: Work only with:
INNER JOIN table2 t2
On t1.nr1 >= t2.MinNr1 And t1.<= t2.MaxNr1
And t1.nr2 >= t2.MinNr2 And t2.MinNr2 <= t2.MaxNr2


text:
Q: Using SUMIF and having a function in sum_range I have a column like:
156
2105 Kb
15 Kb
163
14 secs
65 Kb

etc

What I want to do is to put a function at the bottom of that column, and have it sum the numbers where the unit is Kb (so 2105 + 15 + 65 = answer). I got as far as:
=sumif(right(C200:C201,2),"Kb",LEFT(C200:C201,FIND(" ",C200:C201)-1))

Which fails for numerous reasons I think. I am guessing the sum_range in the SUMIF can not be a function. Happy to move away from SUM and IF if there is another solution.

A: The problem is that SUMIF cannot take processed ranges as the 'sum_column'. You could use SUM and IF separately in an array function:
=SUM(IF(RIGHT(C200:C201,3)=" Kb",LEFT(C200:C201,FIND(" ",C200:C201)-1)*1,0))

Array function means that after typing the formula in, you will need to press Ctrl+Shift+Enter for it to work.


text:
Q: How to install packages with pip in Windows PowerShell I am using Python 2.7.9 on a Windows 8 computer.
I tried to install lxml by typing pip install lxmlin Windows PowerShell after typing python, but I get the following error: SyntaxError: invalid syntax
I tried installing pip by using the following tutorial http://www.tylerbutler.com/2012/05/how-to-install-python-pip-and-virtualenv-on-windows-with-powershell/ only to later realize that I already had pip.exe, pip2.7.exe and pip2.exe installed when I first installed Python. They are located in the C:\Python27\Scripts directory.
Yet, if I try something like pip help I will get an invalid syntax error.
Do I have to reinstall pip or how do I get it to work in order to install the lxml library.
Thank you for any help you can provide.

A: Starting from Python versions 2.7.9 and 3.4.0, 'pip' is already included in the regular install. Check if the path to the 'Scripts' directory inside your Python installation directory is contained in your system's 'PATH' environment variable, so 'pip' can be found.
Look here for more information:
How do I install pip on Windows?
Edit: Sounds like you are trying to run pip inside python, You shouldn't get an 'invalid syntax' error through the command prompt. More like "'pip' is not recognized". Try simply just opening command prompt and typing 'pip help'

A: I had the same problem. You need to set the PATH environment variable, so that the system recognizes the command "pip".
If typing easy_install or pip [in PowerShell] doesn't work, it means the Scripts folder is not in your path. Run the next command in that case (Note that this command must be run only once or your PATH will get longer and longer). Make sure to replace c:\Python33\Scripts with the correct location of your Python installation:
setx PATH "%PATH%;C:\Python33\Scripts"

Close and reopen PowerShell after running this command.
Source: http://arunrocks.com/guide-to-install-python-or-pip-on-windows/


text:
Q: Page displaying only 1 of 2 charts In this codepen I am trying to create 2 treemaps with D3.js but only the second treemap gets displayed. When I check the elements in the console I can see the 2 different svg's are created and written to the DOM but only the second "g" tag is populated with the SVG rect elements. There are 2 distinct div tags with distinct id's. How can I draw 2 D3.sj treemaps on side by side? Thank you.
D3.js code

var margin = {top: 10, right: 10, bottom: 10, left: 10},
  width = 445 - margin.left - margin.right,
  height = 445 - margin.top - margin.bottom;

// append the svg object to the body of the page
var svg = d3.select("#my_dataviz1")
.append("svg")
  .attr("width", width + margin.left + margin.right)
  .attr("height", height + margin.top + margin.bottom)
.append("g")
  .attr("transform",
        "translate(" + margin.left + "," + margin.top + ")");

// read json data
d3.json("https://raw.githubusercontent.com/holtzy/D3-graph-gallery/master/DATA/data_dendrogram_full.json", function(data) {

  // Give the data to this cluster layout:
  var root = d3.hierarchy(data).sum(function(d){ return d.value}) // Here the size of each leave is given in the 'value' field in input data

  // Then d3.treemap computes the position of each element of the hierarchy
  d3.treemap()
    .size([width, height])
    .paddingTop(28)
    .paddingRight(7)
    .paddingInner(3)      // Padding between each rectangle
    //.paddingOuter(6)
    //.padding(20)
    (root)

  // prepare a color scale
  var color = d3.scaleOrdinal()
    .domain(["source1", "source2", "source3"])
    .range([ "#402D54", "#D18975", "#8FD175"])

  // And a opacity scale
  var opacity = d3.scaleLinear()
    .domain([10, 30])
    .range([.5,1])

  // use this information to add rectangles:
  svg
    .selectAll("rect")
    .data(root.leaves())
    .enter()
    .append("rect")
      .attr('x', function (d) { return d.x0; })
      .attr('y', function (d) { return d.y0; })
      .attr('width', function (d) { return d.x1 - d.x0; })
      .attr('height', function (d) { return d.y1 - d.y0; })
      .style("stroke", "black")
      .style("fill", function(d){ return color(d.parent.data.name)} )
      .style("opacity", function(d){ return opacity(d.data.value)})

  // and to add the text labels
  svg
    .selectAll("text")
    .data(root.leaves())
    .enter()
    .append("text")
      .attr("x", function(d){ return d.x0+5})    // +10 to adjust position (more right)
      .attr("y", function(d){ return d.y0+20})    // +20 to adjust position (lower)
      .text(function(d){ return d.data.name.replace('mister_','') })
      .attr("font-size", "19px")
      .attr("fill", "white")

  // and to add the text labels
  svg
    .selectAll("vals")
    .data(root.leaves())
    .enter()
    .append("text")
      .attr("x", function(d){ return d.x0+5})    // +10 to adjust position (more right)
      .attr("y", function(d){ return d.y0+35})    // +20 to adjust position (lower)
      .text(function(d){ return d.data.value })
      .attr("font-size", "11px")
      .attr("fill", "white")

  // Add title for the 3 groups
  svg
    .selectAll("titles")
    .data(root.descendants().filter(function(d){return d.depth==1}))
    .enter()
    .append("text")
      .attr("x", function(d){ return d.x0})
      .attr("y", function(d){ return d.y0+21})
      .text(function(d){ return d.data.name })
      .attr("font-size", "19px")
      .attr("fill",  function(d){ return color(d.data.name)} )

  // Add title for the 3 groups
  svg
    .append("text")
      .attr("x", 0)
      .attr("y", 14)    // +20 to adjust position (lower)
      .text("Three group sources")
      .attr("font-size", "19px")
      .attr("fill",  "grey" )

})

var margin = {top: 10, right: 10, bottom: 10, left: 10},
  width = 445 - margin.left - margin.right,
  height = 445 - margin.top - margin.bottom;

// append the svg object to the body of the page
var svg = d3.select("#my_dataviz2")
.append("svg")
  .attr("width", width + margin.left + margin.right)
  .attr("height", height + margin.top + margin.bottom)
.append("g")
  .attr("transform",
        "translate(" + margin.left + "," + margin.top + ")");

// read json data
d3.json("https://raw.githubusercontent.com/holtzy/D3-graph-gallery/master/DATA/data_dendrogram_full.json", function(data) {

  // Give the data to this cluster layout:
  var root = d3.hierarchy(data).sum(function(d){ return d.value}) // Here the size of each leave is given in the 'value' field in input data

  // Then d3.treemap computes the position of each element of the hierarchy
  d3.treemap()
    .size([width, height])
    .paddingTop(28)
    .paddingRight(7)
    .paddingInner(3)      // Padding between each rectangle
    //.paddingOuter(6)
    //.padding(20)
    (root)

  // prepare a color scale
  var color = d3.scaleOrdinal()
    .domain(["source1", "source2", "source3"])
    .range([ "#402D54", "#D18975", "#8FD175"])

  // And a opacity scale
  var opacity = d3.scaleLinear()
    .domain([10, 30])
    .range([.5,1])

  // use this information to add rectangles:
  svg
    .selectAll("rect")
    .data(root.leaves())
    .enter()
    .append("rect")
      .attr('x', function (d) { return d.x0; })
      .attr('y', function (d) { return d.y0; })
      .attr('width', function (d) { return d.x1 - d.x0; })
      .attr('height', function (d) { return d.y1 - d.y0; })
      .style("stroke", "black")
      .style("fill", function(d){ return color(d.parent.data.name)} )
      .style("opacity", function(d){ return opacity(d.data.value)})

  // and to add the text labels
  svg
    .selectAll("text")
    .data(root.leaves())
    .enter()
    .append("text")
      .attr("x", function(d){ return d.x0+5})    // +10 to adjust position (more right)
      .attr("y", function(d){ return d.y0+20})    // +20 to adjust position (lower)
      .text(function(d){ return d.data.name.replace('mister_','') })
      .attr("font-size", "19px")
      .attr("fill", "white")

  // and to add the text labels
  svg
    .selectAll("vals")
    .data(root.leaves())
    .enter()
    .append("text")
      .attr("x", function(d){ return d.x0+5})    // +10 to adjust position (more right)
      .attr("y", function(d){ return d.y0+35})    // +20 to adjust position (lower)
      .text(function(d){ return d.data.value })
      .attr("font-size", "11px")
      .attr("fill", "white")

  // Add title for the 3 groups
  svg
    .selectAll("titles")
    .data(root.descendants().filter(function(d){return d.depth==1}))
    .enter()
    .append("text")
      .attr("x", function(d){ return d.x0})
      .attr("y", function(d){ return d.y0+21})
      .text(function(d){ return d.data.name })
      .attr("font-size", "19px")
      .attr("fill",  function(d){ return color(d.data.name)} )

  // Add title for the 3 groups
  svg
    .append("text")
      .attr("x", 0)
      .attr("y", 14)    // +20 to adjust position (lower)
      .text("Three group sources")
      .attr("font-size", "19px")
      .attr("fill",  "grey" )

})
.dataviz {
  display: inline-block;
}

A: You have the same name for the two SVG selections:
var svg = d3.select("#my_dataviz1")//etc...
var svg = d3.select("#my_dataviz2")//etc..

The solution is quite simple, give them different names:
var svg = d3.select("#my_dataviz1")//etc...
var svg2 = d3.select("#my_dataviz2")//etc...

Finally, considering that both drawing functions do the same, consider creating a single function to which you pass the SVG selection and the data. That way, you can substantially reduce the size of your code.
Here is your code with the changes:

var margin = {top: 10, right: 10, bottom: 10, left: 10},
  width = 445 - margin.left - margin.right,
  height = 445 - margin.top - margin.bottom;

// append the svg object to the body of the page
var svg = d3.select("#my_dataviz1")
.append("svg")
  .attr("width", width + margin.left + margin.right)
  .attr("height", height + margin.top + margin.bottom)
.append("g")
  .attr("transform",
        "translate(" + margin.left + "," + margin.top + ")");

// read json data
d3.json("https://raw.githubusercontent.com/holtzy/D3-graph-gallery/master/DATA/data_dendrogram_full.json", function(data) {

  // Give the data to this cluster layout:
  var root = d3.hierarchy(data).sum(function(d){ return d.value}) // Here the size of each leave is given in the 'value' field in input data

  // Then d3.treemap computes the position of each element of the hierarchy
  d3.treemap()
    .size([width, height])
    .paddingTop(28)
    .paddingRight(7)
    .paddingInner(3)      // Padding between each rectangle
    //.paddingOuter(6)
    //.padding(20)
    (root)

  // prepare a color scale
  var color = d3.scaleOrdinal()
    .domain(["source1", "source2", "source3"])
    .range([ "#402D54", "#D18975", "#8FD175"])

  // And a opacity scale
  var opacity = d3.scaleLinear()
    .domain([10, 30])
    .range([.5,1])

  // use this information to add rectangles:
  svg
    .selectAll("rect")
    .data(root.leaves())
    .enter()
    .append("rect")
      .attr('x', function (d) { return d.x0; })
      .attr('y', function (d) { return d.y0; })
      .attr('width', function (d) { return d.x1 - d.x0; })
      .attr('height', function (d) { return d.y1 - d.y0; })
      .style("stroke", "black")
      .style("fill", function(d){ return color(d.parent.data.name)} )
      .style("opacity", function(d){ return opacity(d.data.value)})

  // and to add the text labels
  svg
    .selectAll("text")
    .data(root.leaves())
    .enter()
    .append("text")
      .attr("x", function(d){ return d.x0+5})    // +10 to adjust position (more right)
      .attr("y", function(d){ return d.y0+20})    // +20 to adjust position (lower)
      .text(function(d){ return d.data.name.replace('mister_','') })
      .attr("font-size", "19px")
      .attr("fill", "white")

  // and to add the text labels
  svg
    .selectAll("vals")
    .data(root.leaves())
    .enter()
    .append("text")
      .attr("x", function(d){ return d.x0+5})    // +10 to adjust position (more right)
      .attr("y", function(d){ return d.y0+35})    // +20 to adjust position (lower)
      .text(function(d){ return d.data.value })
      .attr("font-size", "11px")
      .attr("fill", "white")

  // Add title for the 3 groups
  svg
    .selectAll("titles")
    .data(root.descendants().filter(function(d){return d.depth==1}))
    .enter()
    .append("text")
      .attr("x", function(d){ return d.x0})
      .attr("y", function(d){ return d.y0+21})
      .text(function(d){ return d.data.name })
      .attr("font-size", "19px")
      .attr("fill",  function(d){ return color(d.data.name)} )

  // Add title for the 3 groups
  svg
    .append("text")
      .attr("x", 0)
      .attr("y", 14)    // +20 to adjust position (lower)
      .text("Three group sources")
      .attr("font-size", "19px")
      .attr("fill",  "grey" )

})

var margin = {top: 10, right: 10, bottom: 10, left: 10},
  width = 445 - margin.left - margin.right,
  height = 445 - margin.top - margin.bottom;

// append the svg object to the body of the page
var svg2 = d3.select("#my_dataviz2")
.append("svg")
  .attr("width", width + margin.left + margin.right)
  .attr("height", height + margin.top + margin.bottom)
.append("g")
  .attr("transform",
        "translate(" + margin.left + "," + margin.top + ")");

// read json data
d3.json("https://raw.githubusercontent.com/holtzy/D3-graph-gallery/master/DATA/data_dendrogram_full.json", function(data) {

  // Give the data to this cluster layout:
  var root = d3.hierarchy(data).sum(function(d){ return d.value}) // Here the size of each leave is given in the 'value' field in input data

  // Then d3.treemap computes the position of each element of the hierarchy
  d3.treemap()
    .size([width, height])
    .paddingTop(28)
    .paddingRight(7)
    .paddingInner(3)      // Padding between each rectangle
    //.paddingOuter(6)
    //.padding(20)
    (root)

  // prepare a color scale
  var color = d3.scaleOrdinal()
    .domain(["source1", "source2", "source3"])
    .range([ "#402D54", "#D18975", "#8FD175"])

  // And a opacity scale
  var opacity = d3.scaleLinear()
    .domain([10, 30])
    .range([.5,1])

  // use this information to add rectangles:
  svg2
    .selectAll("rect")
    .data(root.leaves())
    .enter()
    .append("rect")
      .attr('x', function (d) { return d.x0; })
      .attr('y', function (d) { return d.y0; })
      .attr('width', function (d) { return d.x1 - d.x0; })
      .attr('height', function (d) { return d.y1 - d.y0; })
      .style("stroke", "black")
      .style("fill", function(d){ return color(d.parent.data.name)} )
      .style("opacity", function(d){ return opacity(d.data.value)})

  // and to add the text labels
  svg2
    .selectAll("text")
    .data(root.leaves())
    .enter()
    .append("text")
      .attr("x", function(d){ return d.x0+5})    // +10 to adjust position (more right)
      .attr("y", function(d){ return d.y0+20})    // +20 to adjust position (lower)
      .text(function(d){ return d.data.name.replace('mister_','') })
      .attr("font-size", "19px")
      .attr("fill", "white")

  // and to add the text labels
  svg2
    .selectAll("vals")
    .data(root.leaves())
    .enter()
    .append("text")
      .attr("x", function(d){ return d.x0+5})    // +10 to adjust position (more right)
      .attr("y", function(d){ return d.y0+35})    // +20 to adjust position (lower)
      .text(function(d){ return d.data.value })
      .attr("font-size", "11px")
      .attr("fill", "white")

  // Add title for the 3 groups
  svg2
    .selectAll("titles")
    .data(root.descendants().filter(function(d){return d.depth==1}))
    .enter()
    .append("text")
      .attr("x", function(d){ return d.x0})
      .attr("y", function(d){ return d.y0+21})
      .text(function(d){ return d.data.name })
      .attr("font-size", "19px")
      .attr("fill",  function(d){ return color(d.data.name)} )

  // Add title for the 3 groups
  svg2
    .append("text")
      .attr("x", 0)
      .attr("y", 14)    // +20 to adjust position (lower)
      .text("Three group sources")
      .attr("font-size", "19px")
      .attr("fill",  "grey" )

})
.dataviz {
  display: inline-block;
}


text:
Q: maven in 5 min not working I have downloaded latest

maven 3.0.3, java version "1.6.0_18".
mvn –version

Apache Maven 3.0.3 (r1075438; 2011-02-28 18:31:09+0100)
    Maven home: C:\software\apache-maven-3.0.3
    Java version: 1.5.0_05, vendor: Sun Microsystems Inc.
    Java home: C:\software\jdk1.5.0.15\jre
    Default locale: en_GB, platform encoding: Cp1252
    OS name: "windows xp", version: "5.1", arch: "x86", family: "windows"

My application located at: C:\Temp\ecm_esv\app\ENT_APP\ESV>. I am getting following error message:
C:\Temp\ecm_esv\app\ENT_APP\ESV>mvn archetype:generate -DgroupId=com.mycompany.app -DartifactId=my-app -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false
[INFO] Scanning for projects...
Downloading: http://repo1.maven.org/maven2/org/apache/maven/plugins/maven-clean-plugin/2.4.1/maven-clean-plugin-2.4.1.pom
[WARNING] Failed to retrieve plugin descriptor for org.apache.maven.plugins:maven-clean-plugin:2.4.1: Plugin org.apache.maven.plugins:maven-clean-plugin:2.4.1 or one of its dependencies could not be resolved: Failed to read artifact descriptor for org.apache.maven.plugins:maven-clean-plugin:jar:2.4.1
Downloading: http://repo1.maven.org/maven2/org/apache/maven/plugins/maven-install-plugin/2.3.1/maven-install-plugin-2.3.1.pom
[WARNING] Failed to retrieve plugin descriptor for org.apache.maven.plugins:maven-install-plugin:2.3.1: Plugin org.apache.maven.plugins:maven-install-plugin:2.3.1 or one of its dependencies could not be resolved: Failed to read artifact descriptor for org.apache.maven.plugins:maven-install-plugin:jar:2.3.1
Downloading: http://repo1.maven.org/maven2/org/apache/maven/plugins/maven-deploy-plugin/2.5/maven-deploy-plugin-2.5.pom
[WARNING] Failed to retrieve plugin descriptor for org.apache.maven.plugins:maven-deploy-plugin:2.5: Plugin org.apache.maven.plugins:maven-deploy-plugin:2.5 or one of its dependencies could not be resolved: Failed to read artifact descriptor for org.apache.maven.plugins:maven-deploy-plugin:jar:2.5
Downloading: http://repo1.maven.org/maven2/org/apache/maven/plugins/maven-site-plugin/2.0.1/maven-site-plugin-2.0.1.pom
[WARNING] Failed to retrieve plugin descriptor for org.apache.maven.plugins:maven-site-plugin:2.0.1: Plugin org.apache.maven.plugins:maven-site-plugin:2.0.1 or one of its dependencies could not be resolved: Failed to read artifact descriptor for org.apache.maven.plugins:maven-site-plugin:jar:2.0.1
Downloading: http://repo1.maven.org/maven2/org/apache/maven/plugins/maven-antrun-plugin/1.3/maven-antrun-plugin-1.3.pom
[WARNING] Failed to retrieve plugin descriptor for org.apache.maven.plugins:maven-antrun-plugin:1.3: Plugin org.apache.maven.plugins:maven-antrun-plugin:1.3 or one of its dependencies could not be resolved: Failed to read artifact descriptor for org.apache.maven.plugins:maven-antrun-plugin:jar:1.3
Downloading: http://repo1.maven.org/maven2/org/apache/maven/plugins/maven-assembly-plugin/2.2-beta-5/maven-assembly-plugin-2.2-beta-5.pom
[WARNING] Failed to retrieve plugin descriptor for org.apache.maven.plugins:maven-assembly-plugin:2.2-beta-5: Plugin org.apache.maven.plugins:maven-assembly-plugin:2.2-beta-5 or one of its dependencies could not be resolved: Failed to read artifact descriptor for org.apache.maven.plugins:maven-assembly-plugin:jar:2.2-beta-5
Downloading: http://repo1.maven.org/maven2/org/apache/maven/plugins/maven-dependency-plugin/2.1/maven-dependency-plugin-2.1.pom
[WARNING] Failed to retrieve plugin descriptor for org.apache.maven.plugins:maven-dependency-plugin:2.1: Plugin org.apache.maven.plugins:maven-dependency-plugin:2.1 or one of its dependencies could not be resolved: Failed to read artifact descriptor for org.apache.maven.plugins:maven-dependency-plugin:jar:2.1
Downloading: http://repo1.maven.org/maven2/org/apache/maven/plugins/maven-release-plugin/2.0/maven-release-plugin-2.0.pom
[WARNING] Failed to retrieve plugin descriptor for org.apache.maven.plugins:maven-release-plugin:2.0: Plugin org.apache.maven.plugins:maven-release-plugin:2.0 or one of its dependencies could not be resolved: Failed to read artifact descriptor for org.apache.maven.plugins:maven-release-plugin:jar:2.0
Downloading: http://repo1.maven.org/maven2/org/apache/maven/plugins/maven-metadata.xml
Downloading: http://repo1.maven.org/maven2/org/codehaus/mojo/maven-metadata.xml
[WARNING] Could not transfer metadata org.apache.maven.plugins/maven-metadata.xml from/to central (http://repo1.maven.org/maven2): Error transferring file: repo1.maven.org
[WARNING] Could not transfer metadata org.codehaus.mojo/maven-metadata.xml from/to central (http://repo1.maven.org/maven2): Error transferring file: repo1.maven.org
Downloading: http://repo1.maven.org/maven2/org/apache/maven/plugins/maven-metadata.xml
Downloading: http://repo1.maven.org/maven2/org/codehaus/mojo/maven-metadata.xml
[WARNING] Could not transfer metadata org.apache.maven.plugins/maven-metadata.xml from/to central (http://repo1.maven.org/maven2): Error transferring file: repo1.maven.org
[WARNING] Could not transfer metadata org.codehaus.mojo/maven-metadata.xml from/to central (http://repo1.maven.org/maven2): Error transferring file: repo1.maven.org
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 0.406s
[INFO] Finished at: Mon Apr 18 15:51:05 CEST 2011
[INFO] Final Memory: 1M/3M
[INFO] ------------------------------------------------------------------------
[ERROR] No plugin found for prefix 'archetype' in the current project and in the plugin groups [org.apache.maven.plugins, org.codehaus.mojo] available from the repositories [local (C:\Temp\ecm_esv\app\ENT_APP\ESV), central (http://repo1.maven.org/maven2)] -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/NoPluginFoundForPrefixException
C:\Temp\ecm_esv\app\ENT_APP\ESV>

C:\software\apache-maven-3.0.3\conf\settings.xml
I have enabled proxies here as:
….

<proxies>
    <!-- proxy
     | Specification for one proxy, to be used in connecting to the network.
     |-->
    <proxy>
      <id>optional</id>
      <active>true</active>
      <protocol>http</protocol>
      <host>www.BT.co.uk</host>
      <port>80</port>
      <nonProxyHosts>localhost|google.com</nonProxyHosts>
    </proxy>

  </proxies>

What is the problem I am facing here? Why it is not downloading?

A: Found solution:
Solution #1:
issue was with proxy in settings.xml file:
<host>webproxy</host>

to get host goto IE->tools->connection->LAN settings->advanced->http.
=====
Solution #2:
if auto configured proxy is given: then
1> open IE(or any browser)
2> get the url address from your browser through IE->Tools->internet option->connections->LAN Settings-> get address and give in url eg: as http://autocache.abc.com/ and enter, a file will be downloaded with .pac format, save to desktop
3> open .pac file in textpad, identify PROXY:
In your editor, it will come something like:
   return "PROXY web-proxy.ind.abc.com:8080; PROXY proxy.sgp.abc.com:8080";

4> go to Maven settings.xml and enter as:
<proxy>
      <id>optional</id>
      <active>true</active>
      <protocol>http</protocol>
      <host>web-proxy.ind.abc.com</host>
      <port>8080</port>
</proxy>

5> run mvn:install through command prompt or run through eclipse.
=====
Solution #3:
For any other issues delete maven local repository and run mvn:install again.

A: Clearly this is an issue of proxy. Either use VPN or edit procy setting in setting.xml.
I searched lot about this error. Finally, I used VPN(Virtual private network ) to disable the proxy and was able to use cemtral repository of Maven.

A: Window-Preferences-Maven-User Settings. Check, does settings.xml exists? if eclipse says no, get settings.xml from you friend or set the path to it.

A: Try checking proxy settings in settings.xml file located under following directory:
C:\Users\UserName\.m2

A: I just copied setting.xml which comes under "\apache-maven-3.1.1\conf" directory, to the directory "${user.home}/.m2/)" of windows machine and change the required proxy setting according to my network as below and it worked for me.
<proxy>
  <id>optional</id>
  <active>true</active>
  <protocol>http</protocol>
  <host>www-proxy.xxxx</host>
  <port>8080</port>
</proxy>

Thanks --
Kamran Shahzad

A: We have observed that the maven project creation fails when it tries to download the archtype from this URL: Maven Repository which falls under "https" protocol.
So solution #2 mentioned above worked only after a little change to the settings.xml. Instead of using "http" protocol I have to use "https"
<proxy>
  <id>optional</id>
  <active>true</active>
  <protocol>https</protocol>
  <host>web-proxy.ind.abc.com</host>
  <port>8080</port>

Hope it helps someone.
Note: Make sure that you check  the following internet settings.
Internet Explorer > Internet Options > Connections [TAB] > LAN Settings > Under Proxy server check Use proxy server for LAN > Advanced > Check "same proxy server for all protocols" and Click OK.

A: Adding below under proxy tag in settings.xml worked for me
<proxy>
  <id>optional</id>
  <active>true</active>
  <protocol>https</protocol>
  <host>web-proxy.ind.abc.com</host>
  <port>8080</port>
</proxy>


text:
Q: Julia API Call to Alpaca trading receives HTTP/1.1 401 Unauthorized First time asking a question here. Hoping I do this right!
I've recently heard of Alpaca for algorithmic trading, and thought it would be a cool opportunity to learn Julia and try to get an algo working! Super excited, but running into some trouble getting the initial API call to work.
I'm hung up on the initial API HTTP request for authorization. My account is set up and approved. I've been able to get it to work with the Python library: alpaca-trade-api, but have not had luck with a simple Julia HTTP GET request. Same keys, same domain, but Julia gives an "unauthorized" error.
Link to API documentation:
https://docs.alpaca.markets/web-api/
Here's the code I'm using:
using HTTP
using JSON

key = Dict("APCA-API-KEY-ID" => "my_key")
secret_key = Dict("APCA-API-SECRET-KEY" => "my_secret_key")
params = merge(key,secret_key)

base_url = "https://paper-api.alpaca.markets"
endpoint = "/v1/account"
url = base_url * endpoint

api = HTTP.request(
    "GET",
    url,
    ["Content-Type" => "application/json"],
    JSON.json(params)
    )

And I get the error:
"code":40110000,"message":"access key verification failed : access key not found (Code = 40110000)
Unsure if it has to do with the format in which I'm submitting my keys, but I've tried just using the dictionary as the argument, or defining "headers=params" and that didn't work either. Same error.
Curious if anyone else has experience with getting Alpaca working with Julia, or has insight into why this wouldn't be working.

A: I just resolved a similar issue using PyLiveTrader, although that uses a config.yaml for the API keys. I was able to solve it by using the proper syntax for yaml (four spaces after colon), as well as making sure that I was using the paper key when using the paper base_url (originally I had the regular base_url). Best of luck! (I'm very new to this, so sorry if this isn't helpful).

A: From the linked documentation, you see the corresponding curl command:
curl -X GET \
   -H "APCA-API-KEY-ID: {YOUR_API_KEY_ID}" \
   -H "APCA-API-SECRET-KEY: {YOUR_API_SECRET_KEY}"\
   https://{apiserver_domain}/v1/account

The option -H, means header. So the keys must go in the header, i.e. the 3rd parameter of HTTP.request (https://juliaweb.github.io/HTTP.jl/stable/index.html#Requests-1):
api = HTTP.request(
   "GET",
   url,
   ["Content-Type" => "application/json",
    "APCA-API-KEY-ID => "YOUR_API_KEY_ID",
    "APCA-API-SECRET-KEY => "YOUR_API_SECRET_KEY" ]
)

You should replace YOUR_API_KEY_ID and YOUR_API_SECRET_KEY by your credientials.


text:
Q: Android TabLayout and Fragments I have been learning Android for a few months but I have several questions I can't find solution.
Recently, I follow a few tutorials where there explain about TabLayout, Fragments and RecyclerView but that is not worth for me.
I need an Android interface which a few tabs, with diferent content, but what I need is to enable scroll.
This is my code:
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/coordinator_main_content"
android:layout_width="match_parent"
android:layout_height="match_parent">

<android.support.design.widget.AppBarLayout
    android:id="@+id/appbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <android.support.design.widget.TabLayout
        android:id="@+id/tabs"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        app:layout_scrollFlags="scroll|enterAlways" />

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

<android.support.v4.view.ViewPager
    android:id="@+id/pager"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior" />

A: SOLUTION: To fix this, we have to use NestedScrollView


text:
Q: Is using async componentDidMount() good? Is using componentDidMount() as an async function good practice in React Native or should I avoid it?
I need to get some info from AsyncStorage when the component mounts, but the only way I know to make that possible is to make the componentDidMount() function async.
async componentDidMount() {
    let auth = await this.getAuth();
    if (auth)
        this.checkAuth(auth);
}

Is there any problem with that and are there any other solutions to this problem?

A: When you use componentDidMount without async keyword, the doc say this:

You may call setState() immediately in componentDidMount(). It will trigger an extra rendering, but it will happen before the browser updates the screen.

If you use async componentDidMount you will loose this ability: another render will happen AFTER the browser update the screen. But imo, if you are thinking about using async, such as fetching data, you can not avoid the browser will update the screen twice. In another world, it is not possible to PAUSE componentDidMount before browser update the screen

A: I think it's fine as long as you know what you're doing. But it can be confusing because async componentDidMount() can still be running after componentWillUnmount has run and the component has unmounted.
You may also want to start both synchronous and asynchronous tasks inside componentDidMount. If componentDidMount was async, you would have to put all the synchronous code before the first await. It might not be obvious to someone that the code before the first await runs synchronously. In this case, I would probably keep componentDidMount synchronous but have it call sync and async methods.
Whether you choose async componentDidMount() vs sync componentDidMount() calling async methods, you have to make sure you clean up any listeners or async methods that may still be running when the component unmounts.

A: Update April 2020:
The issue seems to be fixed in latest React 16.13.1, see this sandbox example. Thanks to @abernier for pointing this out.

I have made some research, and I have found one important difference:
React does not process errors from async lifecycle methods.
So, if you write something like this:
componentDidMount()
{
    throw new Error('I crashed!');
}

then your error will be caught by the error boundary, and you can process it and display a graceful message.
If we change the code like this:
async componentDidMount()
{
    throw new Error('I crashed!');
}

which is equivalent to this:
componentDidMount()
{
    return Promise.reject(new Error('I crashed!'));
}

then your error will be silently swallowed. Shame on you, React...
So, how do we process errors than? The only way seems to be explicit catch like this:
async componentDidMount()
{
    try
    {
         await myAsyncFunction();
    }
    catch(error)
    {
        //...
    }
}

or like this:
componentDidMount()
{
    myAsyncFunction()
    .catch(()=>
    {
        //...
    });
}

If we still want our error to reach the error boundary, I can think about the following trick:

*

*Catch the error, make the error handler change the component state

*If the state indicates an error, throw it from the render method

Example:
class BuggyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = { error: null };
  }

  buggyAsyncfunction() { return Promise.reject(new Error('I crashed async!'));}

  async componentDidMount() {
    try
    {
      await this.buggyAsyncfunction();
    }
    catch(error)
    {
        this.setState({error: error});
    }
  }

  render() {
    if(this.state.error)
        throw this.state.error;

    return
I am OK
;
  }
}

A: Update:
(My build: React 16, Webpack 4, Babel 7):
When using Babel 7 you'll discover:
Using this pattern...
async componentDidMount() {
    try {
        const res = await fetch(config.discover.url);
        const data = await res.json();
        console.log(data);
    } catch(e) {
        console.error(e);
    }
}

you will run into the following error...
Uncaught ReferenceError: regeneratorRuntime is not defined
In this case you will need to install babel-plugin-transform-runtime
https://babeljs.io/docs/en/babel-plugin-transform-runtime.html
If for some reason you do not wish to install the above package (babel-plugin-transform-runtime) then you will want to stick to the Promise pattern...
componentDidMount() {
    fetch(config.discover.url)
    .then(res => res.json())
    .then(data => {
        console.log(data);
    })
    .catch(err => console.error(err));
}

A: Let's start by pointing out the differences and determining how it could cause troubles.
Here is the code of async and "sync" componentDidMount() life-cycle method:
// This is typescript code
componentDidMount(): void { /* do something */ }

async componentDidMount(): Promise<void> {
    /* do something */
    /* You can use "await" here */
}

By looking at the code, I can point out the following differences:

*

*The async keywords: In typescript, this is merely a code marker. It does 2 things:

*

*Force the return type to be Promise<void> instead of void. If you explicitly specify the return type to be non-promise (ex: void), typescript will spit an error at you.

*Allow you to use await keywords inside the method.

*The return type is changed from void to Promise<void>

*

*It means you can now do this:
async someMethod(): Promise<void> { await componentDidMount(); }

*You can now use await keyword inside the method and temporarily pause its execution. Like this:
async componentDidMount(): Promise<void> {
    const users = await axios.get<string>("http://localhost:9001/users");
    const questions = await axios.get<string>("http://localhost:9001/questions");

    // Sleep for 10 seconds
    await new Promise(resolve => { setTimeout(resolve, 10000); });

    // This line of code will be executed after 10+ seconds
    this.setState({users, questions});
    return Promise.resolve();
}

Now, how could they cause troubles?

*

*The async keyword is absolutely harmless.

*I cannot imagine any situation in which you need to make a call to the componentDidMount() method so the return type Promise<void> is harmless too.
Calling to a method having return type of Promise<void> without await keyword will make no difference from calling one having return type of void.

*Since there is no life-cycle methods after componentDidMount() delaying its execution seems pretty safe. But there is a gotcha.
Let's say, the above this.setState({users, questions}); would be executed after 10 seconds. In the middle of the delaying time, another ...
this.setState({users: newerUsers, questions: newerQuestions});
... were successfully executed and the DOM were updated. The result were visible to users. The clock continued ticking and 10 seconds elapsed. The delayed this.setState(...) would then execute and the DOM would be updated again, that time with old users and old questions. The result would also be visible to users.
=> It is pretty safe (I'm not sure about 100%) to use async with componentDidMount() method. I'm a big fan of it and so far I haven't encountered any issues which give me too much headache.

A: I like to use something like this
componentDidMount(){
   const result = makeResquest()
}
async makeRequest(){
   const res = await fetch(url);
   const data = await res.json();
   return data
}

A: Your code is fine and very readable to me. See this Dale Jefferson's article where he shows an async componentDidMount example and looks really good as well.
But some people would say that a person reading the code may assume that React does something with the returned promise.
So the interpretation of this code and if it is a good practice or not is very personal.
If you want another solution, you could use promises. For example:
componentDidMount() {
    fetch(this.getAuth())
      .then(auth => {
          if (auth) this.checkAuth(auth)
      })
}

A: Actually, async loading in ComponentDidMount is a recommended design pattern as React moves away from legacy lifecycle methods (componentWillMount, componentWillReceiveProps, componentWillUpdate) and on to Async Rendering.
This blog post is very helpful in explaining why this is safe and providing examples for async loading in ComponentDidMount:
https://reactjs.org/blog/2018/03/27/update-on-async-rendering.html

A: To Tag on to @C-F's answer, I added a typescript decorateor
(AsyncMethodErrorHandler) to handle errors in async componentDidMount() and other async methods that fail to bubble up errors to
the application state.
I found this easier than wrapping dozens of async methods in a try/catch block in an app
whose maintainince I inherited.
class BuggyComponent extends React.Component<{error_message?:string}> {

  @AsyncMethodErrorHandler("error_message")
  async componentDidMount() {
      await things_that_might_fail();
  }

  render(){
      if(this.state.error_message){
          return
Something went wrong: {this.state.error_message}

      }
  }
}

function AsyncMethodErrorHandler(
  /* Key in the this.state to store error messages*/
  key: string,
  /* function for transforming the error into the value stored in this.state[key] */
  error_handler: string | { (e: Error): string } = (e: Error) => e.message
) {

  return function (
    cls: React.Component,
    propertyKey: string,
    descriptor: PropertyDescriptor
  ) {
    const f: { (...args: any[]): Promise<any> } = descriptor.value;
    return {
      ...descriptor,
      value: function (...args: any[]) {
        return f.apply(this, args).catch((e: Error) => {
          console.log(`an error occured in the ${propertyKey} Method:`, e);
          (this as any as React.Component).setState({
            [key]:
              typeof error_handler === "string"
                ? error_handler
                : error_handler(e),
          });
        });
      },
    };
  };
}

Note that as of this writing, this solution does not work for async function properites because:

property decorator[s] can only be used to observe that a property of a
specific name has been declared for a class


text:
Q: Can a corollary follow a conjecture? It is typical to find a corollary that following theorems, but is it right to use the word corollary for a statement following a conjecture, where the statement is true only if the unproven conjecture is true?

A: I would write "Proposition Z: If X holds, then Y is true." Even if the deduction of
Y from X were trivial, I think labelling this a corollary would be confusing. (After all,
what is the statement "X implies Y" a corollary of?) However, I wouldn't have a
problem writing something like "as we saw above, Y would be a corollary of X" later on. (The subjunctive voice is important here!)

A: Making a new Theorem environment that let you have the bolded part say "Corollary to Conjecture X" seems to me a good compromise of concise and unlikely to confuse anyone.

A: The correct term for such an item is CONJOLLARY.
;)

A: I think it's generally bad form to have a corollary dependent on an earlier conjecture.  I recommend one of the following:
Theorem:  Assuming Conjecture A, properties X, Y and Z are true.
or
Theorem:  Conjecture A implies X, Y and Z.
Most importantly, it should be crystal clear that the result is dependent on the conjecture.

A: I'm reminded of the following story that I posted on my personal web journal a couple years ago:

At the Topology seminar yesterday, the speaker presented a theorem, which he immediately followed with a refinement: a statement that directly and obviously implies the theorem. He labeled his refinement a "corollary". I turned to Noah Snyder, and said that it was more an "uncorollary, or an anticorollary", but as soon as I said as much, the two of us simultaneously correctly labeled the refinement as a "rollary".
There should be more rollaries in mathematical writing.


text:
Q: How to pass function as parameters I have a function that receives a vector and sum all the elements.
(def rec
  (fn [numbers acc]
    (if (empty? numbers)
      acc
      (recur (rest numbers) (+ acc (first numbers))))))
(prn (rec [1 2 3] 0))

But instead of calling the function "+" I want to pass the operation as parameter, it means, I want to pass a function as parameter and then call the function.
I tried:
(def rec
  (fn [f numbers acc]
    (if (empty? numbers)
      acc
      (recur (rest numbers) (f acc (first numbers))))))
(prn (rec + [4 2 1] 0))

But it does not work, I know there are better ways to sum numbers in a vector, but I'm starting with functional, so it is important to do this kind of exercise.
Thanks in advance.

A: You need to recur with the same arguments as the parameter vector, in this case:
(recur f (rest numbers) (f acc (first numbers))))))

(btw, it's standard to use defn for defining functions, (defn f[x] ... ) is more concise than (def f (fn [x] ...)))

A: More ideomatic Clojure would be using reduce here, I think
(defn rec [f numbers acc]
  (reduce f acc numbers))

(rec + [1 2 3] 0)
# 6

A: Factoring
In your
(def rec
  (fn [numbers acc]
    (if (empty? numbers)
      acc
      (recur (rest numbers) (+ acc (first numbers))))))

... you can push the accumulator acc beneath the surface of rec:
(defn rec [numbers]
  (loop [ns numbers, acc 0]
    (if (empty? ns)
      acc
      (recur (rest ns) (+ acc (first ns))))))

For example,
(rec + [1 3])
; 4

If you want to pass the operation as a parameter, the convention is that calling it with no arguments gives its identity: the value which returns the other argument when it is applied to two.
Thus
(+) ; => 0
(*) ; => 1

So we can write your parameterized rec as
(defn rec [op numbers]
  (loop [ns numbers, acc (op)]
    (if (empty? ns)
      acc
      (recur (rest ns) (op acc (first ns))))))

This is almost how reduce works, though not quite as elegantly, IMO.


text:
Q: Return Object From Webservice How can I retuen a Object from a web service:
[WebMethod]
        public DataSet GetVendors(string Database)
        {
            SqlConnection sqlConn = new SqlConnection();
        sqlConn.ConnectionString = GetConnString(Database);

        // build query
        string strSQL = @"  SELECT      [No_] AS [VendorNo],
                                        LTRIM([Name]) AS [VendorName]

                            FROM        [********_$Vendor]

                            WHERE       LEN(RTRIM([Name])) > 0 /* avoid blank names */

                            AND         [Vendor Posting Group] = 'VEND'

                            ORDER BY    LTRIM([Name]) ASC; /* LTRIM fixes spaces before name */ ";

        SqlDataAdapter da = new SqlDataAdapter(strSQL, sqlConn);

        DataSet ds = new DataSet();

        da.Fill(ds, "Vendors");

        return (ds);
    }

A: If I'm interpreting your question properly, populate an object on your end with your information in the DataSet and set your return type to object.  Or just return the object you populate as that object.

A: An alternative would be to return the dataset xml as a string and create a dataset from it on the client side.
Although I'm sure encrypting the object would be fairly straightforward, this approach helped me out when my web services needed encryption (serialize everything, encrypt that string, return string, decrypt, deserialize).

A: If you're asking how to return any kind of object, not an Object, then you're going to need to serialize that object. If you're trying to serialize a DataSet, I would suggest making it into a List or other data structure first.

A: Seems brittle to me.  It presumes that the client will know how to deserialize that object, which locks the client into a particular platform (e.g. Java EE or .NET).
XML serialization is less brittle because it's platform-agnostic and leaves unmarshalling quirks to be resolved by the client.  I'd recommend that over returning an object.

A: Another reason not to return DataSet is "leaky abstraction": why expose the client to anything having to do with the persistence tier?   Rethink it.

A: IMO returning datasets from your web services is not such a great idea. It assumes that the clients understand the Dataset, DataTable etc data structures and classes. Instead I recommend you use plain CLR object i.e. Data Transfer Objects or if you want you may use XmlNode as your datatype.You can secure your web service using WSE.


text:
Q: postgresql - find Discontinuous id and get read_time I have a table like this, and there are three cases,
## case a
| rec_no |      read_time      | id
+--------+---------------------+----
|  45139 | 2023-02-07 17:00:00 | a
|  45140 | 2023-02-07 17:15:00 | a
|  45141 | 2023-02-07 17:30:00 | a
|  45142 | 2023-02-07 18:15:00 | a
|  45143 | 2023-02-07 18:30:00 | a
|  45144 | 2023-02-07 18:45:00 | a

## case b
| rec_no |      read_time      | id
+--------+---------------------+----
|  21735 | 2023-02-01 19:15:00 | b
|  21736 | 2023-02-01 19:30:00 | b
|  21742 | 2023-02-01 21:00:00 | b
|  21743 | 2023-02-01 21:15:00 | b
|  21744 | 2023-02-01 21:30:00 | b
|  21745 | 2023-02-01 21:45:00 | b

## case c
| rec_no |      read_time      | id
+--------+---------------------+----
|  12345 | 2023-02-02 12:15:00 | c
|  12346 | 2023-02-02 12:30:00 | c
|  12347 | 2023-02-02 12:45:00 | c
|  12348 | 2023-02-02 13:15:00 | c
|  12352 | 2023-02-02 14:00:00 | c
|  12353 | 2023-02-02 14:15:00 | c

I'd like to find out the missing readtime field when the rec is not continuous.

*

*read_time is '15 min' interval

*in different 'id', rec_no are independent
I'd like something like this,
## case a
## nothing because rec_no is continous
|      read_time      | id
+---------------------+----

## case b
## get six rows
|      read_time      | id
+--------+-----------------
| 2023-02-01 19:45:00 | b
| 2023-02-01 20:00:00 | b
| 2023-02-01 20:15:00 | b
| 2023-02-01 20:30:00 | b
| 2023-02-01 20:45:00 | b
| 2023-02-01 21:00:00 | b

## case c
## get two rows (13:00:00 is missing but rec_no is continous)
|      read_time      | id
+--------+-----------------
| 2023-02-02 13:30:00 | c
| 2023-02-02 13:45:00 | c

Is there a way to do this ? The output format is not too important as long as I can get the result correctly.

A: step-by-step demo: db<>fiddle
SELECT
    rec_no,
    id,
    gs
FROM (
    SELECT
        *,
        lead(rec_no) OVER (PARTITION BY id ORDER BY rec_no) - rec_no > 1 AS is_gap,  -- 1
        lead(read_time) OVER (PARTITION BY id ORDER BY rec_no) as next_read_time
    FROM mytable
)s, generate_series(                                                                 -- 3
      read_time + interval '15 minutes',                                             -- 4
      next_read_time - interval '15 minutes',
      interval '15 minutes'
  ) as gs
WHERE is_gap                                                                         -- 2

*

*Use lead() window function to move the next rec_no value and the next read_time value to the current row. With this you can check if the difference between the current and next rec_no values are greater than 1.

*Filter all records with greater differences

*Generate a time series with 15 minutes interval

*Because the series includes start and end, you need a start at the next 15 minutes points (+ interval) and end one "slot" before the next recorded value (- interval).