text:
Q: How to Read Json Collection From File Using Json.Net in C# I have this json file :
{
   "transactions":[
      {
         "type":"deposit",
         "account_id":123456789012345,
         "amount":20000.0
      },
      {
         "type":"deposit",
         "account_id":555456789012345,
         "amount":20000.0
      },
      {
         "type":"payment",
         "account_id":123456789012345,
         "amount":20000.0
      },
      {
         "type":"transfer",
         "from":555456789012345,
         "to":123456789012345,
         "amount":20000.0
      }
   ]
}

and I want to read this file with JSON.net.
I tried this code but it has some unhandeld errors :
var records = JsonConvert.DeserializeObject<List<Type>>(File.ReadAllText(FileAddress));
using (StreamReader SrFile = File.OpenText(FileAddress))
{
    JsonSerializer Serializer = new JsonSerializer();
    JsonAccount newJsonAccount = (JsonAccount)Serializer.Deserialize(SrFile, typeof(JsonAccount));
}

the error is :

An unhandled exception of type 'Newtonsoft.Json.JsonReaderException' occurred in Newtonsoft.Json.dll
Additional information: Unexpected character encountered while parsing
  value: �. Path '', line 0, position 0

now it has this error :
Additional information: Error converting value "transactions" to type 'ImportAndExport.MainForm+JsonAccount'. Path '', line 1, position 14.
UPDATE 2 :
now the error is :
    An unhandled exception of type 'Newtonsoft.Json.JsonReaderException' occurred in Newtonsoft.Json.dll

Additional information: Invalid character after parsing property name. Expected ':' but got: t. Path '', line 2, position 7.

A: Your error:

Additional information: Unexpected character encountered while parsing value: �. Path '', line 0, position 0.

Is probably caused by your using curly quotes instead of straight quotes. Replace it with standard straight quotes.
EDIT:
In case you get more issues with JSON parsing, this is how I would parse that JSON:
         string jsonString = @"{
    ""transactions"": [
        {
            ""type"": ""deposit"",
            ""account_id"": 123456789012345,
            ""amount"": 20000
        },
        {
            ""type"": ""deposit"",
            ""account_id"": 555456789012345,
            ""amount"": 20000
        },
        {
            ""type"": ""payment"",
            ""account_id"": 123456789012345,
            ""amount"": 20000
        },
        {
            ""type"": ""transfer"",
            ""from"": 555456789012345,
            ""to"": 123456789012345,
            ""amount"": 20000
        }
    ]
}";

        var recordObject = JObject.Parse(jsonString);

If I wanted to get the last transaction
        var lastRecord = JObject.Parse(jsonString)["transactions"].Last()

If I wanted the deposit records
        var deposits = from transactions in JObject.Parse(jsonString)["transactions"]
                       where transactions["type"].ToString().Equals("deposit")
                       select transactions;


text:
Q: Seperate the jars using maven assembly plugin I need to separate the jars into different folders.
Inside my project, I have several modules, i.e: module1, module2, and assembly.
By using maven assembly plugin, I would like to put generated jar from modules1 and module2 into target/modules and all the dependencies into target/dependencies.
How can I achieve this requirement?
Thanks

A: Based on the fact that your project is structured like :
project
    |- module1
    |- module2
    |- assembly
        |- pom.xml
        |- src
            |- assembly
                |- bin.xml

assembly should depend on module1 and module2; set these dependencies in assembly/pom.xml :
<dependencies>
    <dependency>
        <groupId>${project.groupId}</groupId>
        <artifactId>module1</artifactId>
        <version>${project.version}</version>
    </dependency>
    <dependency>
        <groupId>${project.groupId}</groupId>
        <artifactId>module2</artifactId>
        <version>${project.version}</version>
    </dependency>
</dependencies>

You must also add maven-assembly-plugin in assembly/pom.xml :
<plugin>
    <artifactId>maven-assembly-plugin</artifactId>
    <version>3.1.0</version>
    <configuration>
        <descriptors>
            <descriptor>src/assembly/bin.xml</descriptor>
        </descriptors>
    </configuration>
    <executions>
        <execution>
            <id>make-assembly</id>
            <phase>package</phase>
            <goals>
                <goal>single</goal>
            </goals>
        </execution>
    </executions>
</plugin>

assembly:single is bound on package phase, to create the assembly when running mvn package.
Finally, define assembly/src/assembly/bin.xml as follows :
<assembly   xmlns="http://maven.apache.org/ASSEMBLY/2.0.0"
            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
            xsi:schemaLocation="http://maven.apache.org/ASSEMBLY/2.0.0 http://maven.apache.org/xsd/assembly-2.0.0.xsd">
    <id>bin</id>
    <formats>
        <format>dir</format>
    </formats>
    <includeBaseDirectory>false</includeBaseDirectory>
    <dependencySets>
        <dependencySet>
            <outputDirectory>modules</outputDirectory>
            <includes>
                <include>${project.groupId}:*:*</include>
            </includes>
            <excludes>
                <exclude>${project.groupId}:${project.artifactId}:*</exclude>
            </excludes>
        </dependencySet>
        <dependencySet>
            <useTransitiveDependencies>true</useTransitiveDependencies>
            <outputDirectory>dependencies</outputDirectory>
            <excludes>
                <exclude>${project.groupId}:*:*</exclude>
            </excludes>
        </dependencySet>
    </dependencySets>
</assembly>

*

*format defines the format you want for the assembly (here a directory, but could be tar.gz, zip, ...)

*first dependencySet defines a folder modules/ where all artifacts from the same groupId will be put. Here you can also control if you want only some of the artifacts (for example if you want only module1). assembly JAR is excluded from this folder, as this module is only used to create the assembly

*second dependencySet defines a folder dependencies/ where all dependencies (and transitive dependencies) will be put. Dependency here means artifact with a different groupId, as states the excludes clause

mvn package will then generate the assembly (in assembly/target/ folder), named assembly-${project.version}-bin, with the structure you want.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Using CMAKE_DEBUG_POSTFIX with exported targets When I use set(CMAKE_DEBUG_POSTFIX "d"), the build and install targets work as expected. But in the libfooTargets-debug.cmake file with the exported targets, there is a path to libfoo and not libfood.
I exported the targets like this:
install(TARGETS libfoo EXPORT libfoo-targets LIBRARY DESTINATION lib ARCHIVE DESTINATION lib RUNTIME DESTINATION bin)
install(EXPORT libfoo-targets FILE libfooTargets.cmake DESTINATION ${CMAKE_INSTALL_PREFIX})

which creates and installs libfooTargets.cmake and libfooTargets-debug.cmake when building in debug mode, and libfooTargets.cmake and libfooTargets-release.cmake when building in release mode.
Both libfooTargets-release.cmake and libfooTargets-debug.cmake reference the name without a postfix as:
list(APPEND _IMPORT_CHECK_FILES_FOR_libfoo "${_IMPORT_PREFIX}/lib/libfoo.lib" )

and thus a program linking against the debug target still uses the release-build library and I would need to install release and debug versions into different folders to be able to link against the debug target.
How can I get the exported targets to work with a debug postfix?

I could of course try to change the library name depending on CMAKE_RELEASE_TYPE or a CONFIGURATION generator expression, but this will probably break the multi-configuration features in MSVC and other IDEs supporting different targets and seems not to work in the sense of how the exported targets feature is meant to simplify and unify the build.
I suspect that the install(EXPORT ...) command somehow drops the CMAKE_DEBUG_POSTFIX or does not implement it for generating the libfooTargets-{release,debug}.cmake files, but possibly I overlooked how to make this variable visible to the generator of the exported targets or something like this.

All target code
cmake_minimum_required(VERSION 3.11.1)
project(foo)
include(CMakePackageConfigHelpers)
set(CMAKE_WINDOWS_EXPORT_ALL_SYMBOLS ON)
set(CMAKE_DEBUG_POSTFIX "d")

# ...

add_library(libfoo STATIC somesource.cpp someheader.h)
target_include_directories(libfoo PUBLIC
         $<INSTALL_INTERFACE:include>
        $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
)
target_link_libraries(libfoo
        somelibrary
)
target_include_directories (libfoo PUBLIC
        somelibrary_header_dirs
)
install(TARGETS libfoo EXPORT libfoo-targets LIBRARY DESTINATION lib ARCHIVE DESTINATION lib RUNTIME DESTINATION bin)
install(EXPORT libfoo-targets FILE libfooTargets.cmake DESTINATION ${CMAKE_INSTALL_PREFIX})

configure_package_config_file(libfooConfig.cmake.in ${CMAKE_CURRENT_BINARY_DIR}/libfooConfig.cmake INSTALL_DESTINATION ${CMAKE_INSTALL_PREFIX})
install(FILES ${CMAKE_CURRENT_BINARY_DIR}/libfooConfig.cmake DESTINATION ${CMAKE_INSTALL_PREFIX})
install(DIRECTORY include/ DESTINATION include FILES_MATCHING PATTERN "*.h")

The platform is a Windows 10 with cmake 3.11.1 and MSVC 2015. Of course the most general solution is probably the best one.

A: According to the documentation of the install command, you need to reference the configuration that you are interested in:

[...] If a CONFIGURATIONS option is given then the file will only be installed when one of the named configurations is installed. Additionally, the generated import file will reference only the matching target configurations. [...]

So, you need to add the CONFIGURATIONS option in both install commands and duplicate the commands for each configuration you want to install and export.


text:
Q: Insert video into InDesign in a not fitting box How can I put af video into InDesign in a frame/box that not has the normel video proportions?
When I place a video into a box that is square I get a message saying that some elements are cropped in a way that PDF cannot display, or something like that.
Is video in square boxes or maybe circles not possible?

A: If you want the PDF document to include a play area with feathering or other effects that may not export well when applied to a poster, consider using a placed image for the play area, and then place a movie (without a poster) on top of the placed image.


text:
Q: Load different JS based on users location I'm trying to make my website load different js files based on users languages. Possible?
I got this javascript application: test.js <- inside this i can define the language (default eng)
So that, i would like to recreate test.js and name it like test-it.js test-es.js ecc.
In my index the script is loaded as usual:
<script type="text/javascript" src="http://mysite.com/test.js"></script>

Is it possible to setup an if/else condition that detect browser language and load the right js app?
Thanks, Gio

A: Browsers will typically send an Accept-Language HTTP header indicating the user's preferred language.
In php you can read this header and use it to return the appropriate file.
test.php
<?php
$locale = locale_accept_from_http($_SERVER['HTTP_ACCEPT_LANGUAGE']);
list($language, $country) = explode('_', $locale);
include 'test-'.$language'.js';
?>

This however is not the best approach, because you may want to give the user the ability to override the language and not use the browser's language. Also, the browser may not send a language at all, or it may specify a language you do not support. Also, using server side selection like this may hurt your ability to cache the file. Also, if the JavaScript file has code in it besides language you do not want to duplicate the code in multiple files.
I would recommend using a library for this like: http://i18next.com/


text:
Q: Electric potential for a continuous charge distribution First consider a small element on a planar object with charge $dq$. Taking $V=0$ at $r=\infty$, the potential $dV$ due to $dq$ at a point $P$ outside of the object is:
$$dV = \frac{1}{4\pi\epsilon_0} \frac{dq}{r}$$
where $r$ is the distance between $P$ and $dq$.
To find the total potential $V$ due to all the charges in the object at $r$, we simply integrate:
$$
\begin{aligned}
V &= \frac{1}{4\pi\epsilon_0} \int \frac{dq}{r} \\
&= \frac{1}{4\pi\epsilon_0} \frac{Q}{r}
\end{aligned}
$$
However, the distance $r$ to $P$ varies for each element $dq$. So is the equation saying that we can take the total charge Q of the object to be at a point? If so, where would the point be?

A: You did not evaluate the integral over all $dq$ for your total potential correctly. r is different for each  $dq$ element of the planar object. So you have to consider a volume integral over the object with $dq=\rho dxdydz$ in the numerator and $r=\sqrt{x^2+y^2+z^2}$ in the denominator, $\rho$ is the charge density. If the object has only surface charge you can use a surface integral with the surface charge density. r is the distance between the point in space where you are determining the potential and the location of the infinitesimal charge element.

A: I think your last equality should be interpreted more as an aproximation than as an equality if you're dealing with a macroscopic object but its quite accurate if the distance from the object where you're measuring the potential is very big in comparison with any dimension of your object.  As you get closer to the object you should also take into account higher multipolar contributions. But as I said, if you're far enough you can consider the distribution as a point charge.
For you're last question I think the coordinates of the point should be calculated as a weighted average. If I'm not mistaken it would be the analogous as the center of mass of a "distribution of mass", so it would be the "center of charge" of the distribution of charge and you compute it in the same way.

A: In fact, the correct interpretation of this equation is the following:
$$ dV=\frac{1}{4\pi \epsilon_0}\frac{dq}{r}=\frac{1}{4\pi \epsilon_0} \rho(\vec{r}) \frac{d\Omega}{r}$$
where I have used $\vec{r}$ for the vector from the point where I will be integrating to point $P$, $\rho(\vec{r})$ for the charge density (as it has been already pointed, is analougous to the mass density: it is the charge per unit of volume at a given point in the space. I use $d\Omega$ for the element of volume since you have already used $dV$
The second expression you pointed is only valid for a point charge :) (You can extend it using Gauss theorem to other distributions with spherical symmetry). The charge density of a point charge is $Q$ where it is and 0 everywhere else (there is a mathematical object to describe this, known as  Dirac delta).
As a counter example to your derivation when the charge is not point-like, I leave you the potential an infinite charged plane creates. The electric field can be obtained using Gauss law, yielding:
 $$ E=2\pi\sigma$$
where $\sigma$ is the surface charge density. As you may know, $E=-\frac{dV}{dx}$ with $x$ the direction normal to the plane. Then:
$$ V=-2\pi\sigma x$$
for every point P at a distance $x$ of the plane (if I have not made any mistake). This does nothing to do with what you obtained :).

A: Let $\vec r_s=x_s\hat x+y_s\hat y$ be a point on your object, and $\vec r_P=x_P\hat x+y_P\hat y+z_P\hat z$ the location of your point $P$.  The small amount $dq_s$ of charge located at $\vec r_s$ will contribute
$$
dV=\frac{dq_s}{4\pi\epsilon_0}\frac{1}{\vert \vec r_p-\vec r_s\vert}=
\frac{dq_s}{4\pi\epsilon_0}\frac{1}{\sqrt{(x_P-x_s)^2+(y_P-y_s)^2+z_P^2}}
$$
to the potential at $P$.  You then need to integrate over the location of the source charges, using $dq=\sigma_s(\vec r_s)dS$ where $\sigma_s(\vec r_s)$ is the surface charge density at $\vec r_s$ and $dS$ is the small area around $\vec r_s$ containing the charge $dq_s$.
In Cartesian coordinates you would thus get
$$
V=\frac{1}{4\pi\epsilon_0}\int\int
\frac{dx_s\,dy_s \sigma_s(\vec r_s)}{\sqrt{(x_P-x_s)^2+(y_P-y_s)^2+z_P^2}}
$$
with the limits of integration determined by the boundary of your planar object.


text:
Q: Javascript + Regex = Breaks function call somehow html code:

  <input type="button" value="button" onclick="doValidateForm();" />

javascript:

The problem is the {5}.  With it in I get "JavaScript runtime error: 'doValidateForm' is undefined."  I've moved the {5} around in the expression.  With it not there, the code executes fine.
I've tried:
/^[0-9]{5}+$/.test(zip)

and
/^{5}[0-9]+$/.test(zip)

But it still breaks.  Any help would be greatly appreciated.
edit fixed code.

A: You are probably looking for this regex:
/^[0-9]{5}$/

It matches 5-digit numbers (with leading zeroes counting as digits)
Use it like this:
if (!/^[0-9]{5}$/.test(zip)) { ...

Quick explanation:
+ means "once or more"
{5} means "exactly 5 times"
So is doesn't make sense to have + and {5} one after the other in any regex. It's kinda like asking javascript to calculate what 3+*5 is. It's just a rough comparison - the similarity lies in operators being used without operands)

A: This condition:
if (!/^[0-9]+${5}/.test(zip) && zip != "")

should be rewritten as:
if (/^\d{5}$/.test(zip) == false) {


text:
Q: Android Studio can't record screen at 1080p I am trying to record my Nexus 7 2013 (1080p) with Android Studio 1.5.1 (stable).
In the settings, I put :
Bitrate : 10Mbps
WxH : 1200 1900
I cannot use 1080 * 1900 because 1080 is not a multiple of 16.
As soon as I click on start with the aforementioned settings, the record stops and produces a file with a previous recording performed with default settings (720p, 4Mbps).
Why ?
I once successfully made a 1080p video with the same device but I cannot remember how I did it.
Thanks in advance !

A: Use adb directly to record 1080p video
abd shell
screenrecord --size 1080x1920 /sdcard/demo.mp4

If the device you are recording on is a 1080p device, then adb by default records in 1080p.
Detaild tutorial : http://www.androidauthority.com/android-customization-screen-recording-adb-599331/


text:
Q: How to give permission to share folder in Ubuntu? I have made a folder share, when I shared this folder and access it from window 7 it gives an alert box that you have no permission only folder show "share" when go inside this folder then it alert appear.

A: EDIT -> This is probably the easiest:
http://www.7tutorials.com/how-access-ubuntu-shared-folders-windows-7
Turn on guest access before playing with permissions to check it works

EDIT-> If you wanted to configure Samba:
Are you using Samba?  I imagine you are, have you edited the Samba configuration file?
Where your share equals "testshare" you will need something like:
[testshare]
comment = Public Share
path = /path/to/share/point
read only = no
browseable = yes
guest only = yes
guest ok = yes

Note that is a public share at a very basic level.  Here is a useful link I just borrowed:
https://help.ubuntu.com/community/Samba/SambaServerGuide


text:
Q: Catching exceptions when using  I am pulling data from queue and then validating the input payload using int-xml:validating-filter.  I have set throw-exception-on-rejection="true" so that exception is thrown.
I need to get hold of the exception message(validation errors) as well as the input payload.  Could you please suggest the options available to capture this data?
<int-jms:message-driven-channel-adapter   id="jmsIn"
destination="requestQueue" channel="orderChannel"/>

<int-xml:validating-filter id="validatingFilter"
    input-channel="orderChannel"
    output-channel="validOutputChannel"
    discard-channel="errOutputChannel"
    schema-type="xml-schema"
    throw-exception-on-rejection="true"
    schema-location="OrderProcessing/order.xsd"/>

A: You concern isn't clear, if you can catch that exception.
The code in the XmlValidatingMessageSelector looks like:
if (this.throwExceptionOnRejection) {
    throw new MessageRejectedException(message, "Message was rejected due to XML Validation errors",
            new AggregatedXmlMessageValidationException(
                Arrays.<Throwable>asList(validationExceptions)));
}

So, that MessageRejectedException has the desired message as a cause for validation failure. And all the validation errors are represent in the AggregatedXmlMessageValidationException cause of that MessageRejectedException.


text:
Q: Find the value of $\frac{ x_1^2}{1-x_1}+\frac{x_2^2}{1-x_2}+...+\frac{x_n^2}{1-x_n}.$ Suppose, $x_1+x_2+...+x_n=1\space (x_i\in \mathbb{R}, x_i ≠1)$ and
$\frac{ x_1}{1-x_1}+\frac{x_2}{1-x_2}+...+\frac{x_n}{1-x_n}=1.$$\\$
Find the value of $\frac{ x_1^2}{1-x_1}+\frac{x_2^2}{1-x_2}+...+\frac{x_n^2}{1-x_n}.$

A: $\frac{ x_1^2}{1-x_1}+\frac{x_2^2}{1-x_2}+...+\frac{x_n^2}{1-x_n}=\frac{ x_1^2}{1-x_1}+\frac{x_2^2}{1-x_2}+...+\frac{x_n^2}{1-x_n} - 1 +1\\=\frac{ x_1^2 -x_1}{1-x_1}+\frac{x_2^2 - x_2}{1-x_2}+...+\frac{x_n^2-x_n}{1-x_n} + 1=-(x_1 + x_2 + .. +x_n) + 1 = 0$

A: Let $S$ be the sum of the series ${x_1^2 \over 1 - x_1} + {x_2^2 \over 1 - x_2} + \cdots + {x_n^2 \over 1 - x_n}$ , represented by $S = \sum_{i=1}^n {x_i^2 \over 1-x_i}$
First, let's do some algebra.
$$\begin{align*}
{x_i^2 \over 1-x_i} & = {x_i^2 - 2x_i + 2x_i - 1 + 1  \over 1-x_i} \\
& = {(x_i^2 - 2x_i + 1) + (x_i - 1) + x_i   \over 1-x_i} \\
& = {(x_i - 1)^2 \over 1-x_i} + {x_i - 1 \over 1-x_i} + {x_i \over 1-x_i} \\
& = (1 - x_i) - 1 + {x_i \over 1 -x_i} \\
& = {x_i \over 1-x_i} - x_i \\
\end{align*}$$
Now we can simplify our sum.
$$S = \sum_{i=1}^n {x_i^2 \over 1-x_i} = \sum_{i=1}^n ({x_i \over 1-x_i} - x_i)=\sum_{i=1}^n {x_i \over 1-x_i} - \sum_{i=1}^n x_i = 1 - 1 = 0$$

A: HINT:
$$a-\dfrac a{1-a}=\dfrac{a(1-a)-a}{1-a}=?$$


text:
Q: How to update a form value and submit the updated form using JS I have this form:
<form name = "myform" method='POST' >{% csrf_token %}

 {{form.GenerateDate.as_hidden}}

 {{form.Product.as_hidden}}

 {{form.Link.as_hidden}}

      <textarea id="textarea1" class="materialize-textarea" id="usercontent"></textarea>

 {{form.Status.as_hidden}}

<input type='submit' value='add' class="waves-effect waves-light btn" ></input>

</form>

I am loading the value in textarea using this script:

The value is displayed as it is in the DB. But now I want to update this {{form.UserContent.Value}} in the form and using JS then POST it again using the submit button and let django save the new value.
But it stores "None" instead!
I am using materialize css and django 1.11 Textarea is a must for my use.
For HTML advisers here is the code :
<form name = "myform" method='POST' >

      <textarea id="textarea1" class="materialize-textarea" id="usercontent"></textarea>

<input type='submit' value='add' class="waves-effect waves-light btn" ></input>

</form>

I want to update abcdef to qwerty in the form after hitting submit button using JS here.


text:
Q: Using different classes to map JSON data with GSON My application is receiving JSON messages from a WebSocket connection.
There are different types of answers, which are formatted like that:
{
    "type": "snapshot",
    "product_id": "BTC-EUR",
    "bids": [["1", "2"]],
    "asks": [["2", "3"]]
}

or
{
    "type": "l2update",
    "product_id": "BTC-EUR",
    "changes": [
        ["buy", "1", "3"],
        ["sell", "3", "1"],
        ["sell", "2", "2"],
        ["sell", "4", "0"]
    ]
}

... for example (see full API here).
Depending on the "type", I would like GSON to map a different class (e.g. Snapshot.class and l2update.class).
I have message handlers that subscribe to the WebSocket connection and I want the message to be processed by the relevant handler. For instance:

*

*ErrorMessageHandler would manage the errors

*SnapshotMessageHandler would create the initial order book

*L2UpdateMessageHandler would update the order book

*and so on

My problem is to dispatch the messages depending on their type.
I was thinking to convert them to the appropriate class and then call the relevant handler using a factory. I'm currently stuck at the first step, converting the JSON in Error.class or Snapshot.class depending on the "type".
How can I do that?

A: For Gson you could use com.google.gson.typeadapters.RuntimeTypeAdapterFactory.
Assuming you have - for example - following classes:
public class BaseResponse {
    private String type, product_id;
    // rest of the common fields
}

public class Snapshot extends BaseResponse {
    // rest of the fields
}

public class L2Update extends BaseResponse {
    // rest of the fields
}

then you would build following RuntimeTypeAdapterFactory:
RuntimeTypeAdapterFactory<BaseResponse> runtimeTypeAdapterFactory =
    RuntimeTypeAdapterFactory
        .of(BaseResponse.class, "type") // set the field where to look for value
        .registerSubtype(L2Update.class, "l2update") // values map to 'type'
        .registerSubtype(Snapshot.class, "snapshot");// value in json

Registering this with Gson will then enable automativcal instantiation of each type of responses:
Gson gson = new GsonBuilder()
        .registerTypeAdapterFactory(runtimeTypeAdapterFactory).create();

and provide BaseResponse for fromJson(..) if using it , like:
gson.fromJson( json , BaseResponse.class);

NOTE: that  Gson omits de- & serializing the type field. However it needs to be set in Json. Just as it is now in responses you get.

A: You may want to consider using a library that requires a bit less of a solid object model, at least at first.  I use JsonPath for this type of thing.  You could use it to at least find out the type you're dealing with:
String type = JsonPath.read(yourIncomingJson, "$.type");

and then, based on the string, do a switch statement as @ShafinMahmud suggests.
However, you could use JsonPath for the whole thing too.  You could read all of the values using the path notation and know how to parse based on the type.
Adding another library to read a single value may or may not work for you but if you use it to read other values it might end up being worthwhile.


text:
Q: How can I give a plugin's default settings access to the final settings? I'm working on a jQuery plugin. When the plugin runs, the first thing it does is determine its settings. It does this by taking some default settings and overriding some or all of them with whatever the user passed in.
Here's a simplified version:
(function( $ ) {
  $.fn.somePlugin = function(userOptions) {
    // Short name for internal use - exposed below for external modification
    var defaults = $.fn.somePlugin.defaults;

    // Decide settings
    // User settings overrule defaults, but merge both into an empty
    // hash so that original defaults hash isn't modified
    var settings = $.extend(true, {}, defaults, userOptions);

    settings.alerter.call();

    // More code, etc.
  }

  $.fn.somePlugin.defaults = {
    name: 'Captain Slappy von Martinez, Esquire, DDS',
    favoriteColor: 'red',
    alerter: function(){alert("I got bones!");}
  }

})( jQuery );

So, if you call the plugin like this:
    $('div').somePlugin({alerter: function(){alert('No bones here!');}});

... you override the default alerter function, but use the default favoriteColor.
I'm defining the defaults outside the plugin itself so that they are publicly accessible. So if you want to change the default value for favoriteColor, you can just do this:
$.fn.somePlugin.defaults.favoriteColor = 'blue';

... and that will change it for every instance on the page after that.
All of this works fine.
Here's my problem: in one of the default functions, I need to refer to settings. Something like this:
  $.fn.somePlugin.defaults = {
    name: 'Captain Slappy von Martinez, Esquire, DDS',
    favoriteColor: 'red',
    alerter: function(){alert("Paint me " + settings.favoriteColor);}
  }

But when I try this, I get a Javascript error on the line where the default alerter function is declared: "settings is not defined." True enough: it's not defined yet when the parser hits that line. It WILL be defined by the time the function runs, but that doesn't seem to matter.
So my question is: How can I import my default function into the plugin in such a way that it has access to settings?

*

*Is there a way to delay evaluation of settings until the function is actually called?

*If so, is there a way to make sure it has access to the local scope of the plugin, even though I assume that, as an object, this function is being passed by reference? I know that I can alter the value of this inside a function by using someFunction.call(valueToUseForThis), but I don't know whether I can alter its scope after the fact.

Some Stuff that Doesn't Work

*

*Initially, it seemed that if I declared settings in the outer, self-executing function, that would make it available to the defaults. But declaring it there causes problems: if I use my plugin multiple times on a page, the instances get their settings mixed up.

A: Any attempts to change scope after the fact are doomed. There's no dynamic scoping in JavaScript.
Workaround 1.
Pass settings to the alerter explicitly:
$.fn.somePlugin = function(userOptions) {
  var settings = $.extend(...);
  settings.alerter(settings)
}

$.fn.somePlugin.defaults = {
  favoriteColor: 'red',
  alerter: function(settings) { alert("Paint me " + settings.favoriteColor) }
}

Workaround 2. Pass settings to the alerter implicitly:
$.fn.somePlugin = function(userOptions) {
  var settings = $.extend(...);
  settings.alerter()
}

$.fn.somePlugin.defaults = {
  favoriteColor: 'red',
  alerter: function() { alert("Paint me " + this.favoriteColor) }
}

Both solutions tested and work well with multiple uses of the plugin. If you have no plans for using this keyword in your alerter, you can use it for referencing settings.
The third valid solution, which you and fudgey mentioned, is to attach settings object to the DOM element itself:
$.fn.somePlugin = function(userOptions) {
  var settings = $.extend(...);
  $(this).data('somePlugin', {settings: settings})
  settings.alerter.call(this)
}

$.fn.somePlugin.defaults = {
  favoriteColor: 'red',
  alerter: function() {
      alert("Paint me " + $(this).data('somePlugin').settings.favoriteColor)
  }
}

Extra fun. Emulating dynamic scope, a.k.a don't do this
function dynamic(fn) {
  var parts = fn.toString().split('{')
  fn = parts.shift() + '{ with (args) { ' + parts.join('{') + '}'
  return {bind: function(args) { return eval('(' + fn + ')') }}
}

a = b = c = 0

function adder(c) {
  alert(a + b + c)
}

dynamic(adder).bind({a: 1, b: 2})(3) // alert(6)

Usage in a plugin:
$.fn.somePlugin = function(userOptions) {
  var settings = $.extend(...);
  dynamic(settings.alerter).bind({settings: settings})()
}

$.fn.somePlugin.defaults = {
  favoriteColor: 'red',
  alerter: function() { alert("Paint me " + settings.favoriteColor) }
}

A: The settings variable is scoped to the $.fn.somePlugin function so it is not available outside of this, which is where you're trying to reference it in $.fn.somePlugin.defaults. Can you not simply move the default object inside $.fn.somePlugin and declare it in there?
Try this (code untested):
(function( $ ) {
  $.fn.somePlugin = function(userOptions) {
    // Short name for internal use - exposed below for external modification
    var settings = {},
        defaults = {
            name: 'Captain Slappy von Martinez, Esquire, DDS',
            favoriteColor: 'red',
            alerter: function(){alert("Paint me " + settings.favoriteColor);}
        };

    // Decide settings
    // User settings overrule defaults, but merge both into an empty
    // hash so that original defaults hash isn't modified
    settings = $.extend(true, {}, defaults, userOptions);

    settings.alerter.call();

    // More code, etc.
  }

})( jQuery );

Edit: In light of your comment below, the simplest approach is probably to just move the declaration of settings up a level into the outer function - being locally scoped to this function, it will still be private to external callers. Revised code below:
(function( $ ) {

  var settings = {}

  $.fn.somePlugin = function(userOptions) {
    // Decide settings
    // User settings overrule defaults, but merge both into an empty
    // hash so that original defaults hash isn't modified
    settings = $.extend(true, {}, $.fn.somePlugin.defaults, userOptions);

    settings.alerter.call();

    // More code, etc.
  }

  $.fn.somePlugin.defaults = {
      name: 'Captain Slappy von Martinez, Esquire, DDS',
      favoriteColor: 'red',
      alerter: function(){alert("Paint me " + settings.favoriteColor);}
  }

})( jQuery );

$.fn.somePlugin.defaults.favoriteColor = 'blue';

$.fn.somePlugin(); // Should alert 'Paint me blue'

alert(settings.favoriteColour) // Will not work here;

A: Simply change settings to this:
$.fn.somePlugin.defaults = {
    name: 'Captain Slappy von Martinez, Esquire, DDS',
    favoriteColor: 'red',
    alerter: function () { alert("Paint me " + this.favoriteColor); }
}

That's it!
EDIT: Oh!  I just noticed something in your code!  Don't use .call() to call settings.alerter.  That changes the meaning of this.  Just call the method directly.  If you must use .call(), pass in settings as the parameter for this.
settings.alerter.call();         // this won't work.
settings.alerter();              // but this will!
settings.alerter.call(settings); // this works too

Here's a complete working example based on your code: http://jsfiddle.net/gilly3/k2Eep/2/


text:
Q: How to populate table from JSON with two objects inside? I have got the below JSON as result from database through calll of json_encode

[
   {
        "id":1,"FullName":"Duce",
        "subjects": [
                {
                  "id":1,
                 "SubjectName":"Phy",

          "pivot":{
                "student_id":1,
                "subject_id":1
              }
            }
          ],

      "topics": [

               {
                 "id":1,
                 "TopicName":"Meas",
                 "Subject_id":"1",

                     "pivot":{
                         "student_id":1,
                         "topic_id":1,
                         "Price":15000,

                 }
              }
         ]
   }
]

I need to achive something like this

  ------------------------------------------------------------------------------------------------------------------
  ID        Subject Name             Topics Name                   Price                Action
--------------------------------------------------------------------------------------------------------------------
  1            Phy                     Meas                          15000                X

  2            -----                   ----                          -----

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

i tried on using Jquery Ajax each methods to pass through every object within a data responses as below but got an intended results

 let rows = '';

            $.get(URL_GET_STUDENT,
                 function (data ,status) {
                  console.log(data);
                   $.each(data ,function (key ,value) {

                         $("#FullName").val(value.FullName);

                         $.each(value.subjects ,function (key1 ,value1 ) {
                              rows += "
" +
                                          "" +
                                            "<select class='form-control subject_selected' name='subject[]' id='subject' data-id='0' required>" +
                                             "<option>"+ value1.SubjectName +"</option>" +
                                           "</select>" +
                                       "	" +
                                       "";
                         });

                       $.each(value.topics ,function (key2 ,value2 ) {

                           rows += "<select class='form-control topic_selected' name='topic[]' id='topic' data-id='0' required>" +
                               "<option>" + value2.TopicName + "</option>" +
                               "</select>" +
                               "	" +
                               "td>" +
                               "<input type='text' class='form-control Amount' name='Amount[]' id='Amount' value='"+ value2.TopicName +"'/>" +
                               "	" +
                               "" +
                               "X" +
                               "	"+
                               "
";
                       });

                     });
                     $("#table_tuition_fee").append(rows);
            });

Which is like below

Anyone who can help me to achieve the above result? I real appreaciate your help?


text:
Q: Unix command ls -lrt giving unexpected results So I was doing my work and I needed to list some particular files in a folder.
I typed
ls -lrt *ABCD*201604*
and it returned
*ABCD*201604* not found.
Then to see if such files actually were there or not I did ls -lrt and found that there were such files.
So next I copied ABCD and 201604 from listed files while typing command ls -lrt *ABCD*201604* and that worked!
I compared both of my commands to see if I did any mistake but found that both were exactly same. Any explanation for such behavior?
One which I wrote:
$ ls -lrt *RFPTDW*20160425*
*RFPTDW*20160425* not found

One which I copied:
$ ls -lrt *RFPTDW*20160425*
RFPTDW107_01_01_20160425_1526.txt
RFPTDW059_01_01_20160425_1527.txt

In second output I have omitted other details but filename.

A: The shell is responsible for expanding the globs on the command line. The command executed doesn't see those wildcard characters: it sees the expanded arguments.
When you want to see how those are expanded, try prepending the command you want with echo. Like such:
$ touch ABCD
$ touch 201604
$ touch foo_ABCD_bar_201604_baz
$ echo ls -lrt *ABCD*
ls -lrt ABCD foo_ABCD_bar_201604_baz
$ echo ls -lrt *201604*
ls -lrt 201604 foo_ABCD_bar_201604_baz
$ echo ls -lrt *ABCD*201604*
ls -lrt foo_ABCD_bar_201604_baz
$ rm foo_ABCD_bar_201604_baz
$ echo ls -lrt *ABCD*201604*
ls -lrt *ABCD*201604*

Notice that on the last line, the glob no longer expands to a filename, so the ls command would be handed the argument *ABCD*201604*, which names a file that does not exist.
Edit:
If you prepend echo to your actual commands, I expect that your result will be
$ echo ls -lrt *RFPTDW*20160425*
ls -lrt *RFPTDW*20160425*

in the first case, and
$ echo ls -lrt *RFPTDW*20160425*
ls -lrt RFPTDW107_01_01_20160425_1526.txt RFPTDW059_01_01_20160425_1527.txt

in the second case. In the first case, the files do not exist, so the glob does not expand to anything. In the second case, some files match the glob, and so the shell can expand it.

A: Sometimes character encoding is the problem. There are characters in Unicode which are looking quite the same as the ASCII ones (so called homoglyphs). So maybe there are "special" characters which only work when you copy paste them.
Also ASCII characters are sometimes hard to distinguish like 0-O (Zero, Letter O), or 1-l (One and Letter L)


text:
Q: How to link www sub-domain to specific vhost DocumentRoot? Server Environment: Ubuntu 12.04 | Apache 2.2
I have disabled the default vhost configuration using a2dissite default and deleted the default file from sites-available and sites-enabled. I have 3 domains pointed at the VPS at DigitalOcean and I've added CNAME records for www linked to domain.com. (with the trailing dot).
Theis is the current setup:

*

*domain1.com : http://pastie.org/9457734

*domain2.com : http://pastie.org/9457732

*domain3.com : No vhost defined, but pointed at VPS

Navigating to domain1.com serves the intended DocumentRoot, so does domain2.com. However, navigating to www.domain1.com serves the DocumentRoot of domain2.com (this is the problem). This doesn't seem to happen with www.domain2.com which serves the correct path. domain3.com which has no vhost created also mysteriously serves the content from domain2.com
If I delete the www CNAME records, the links with www do not work after DNS propagation. I have seen suggestions to add a ServerAlias directive in the vhost files. When I add such directives, Apache errors out with the following:

"ScriptAlias takes two arguments, a fakename and a realname"

How can I solve this problem?

A: Not sure why you get this error when using ServerAlias, however this should be the way to go.
From the docmuentation :

The ServerAlias directive sets the alternate names for a host, for
  use with name-based virtual hosts

This is actually what you are doing, as you have defined www.hrsys.com.ng as an alias (CNAME) in your DNS for hrsys.com.ng.


text:
Q: Adding Access Control Origin to Kubernetes I am trying to allow Access Control Origin due to the following error in an Android Cordova app:
http://localhost:8080/#/: Line 0 : Access to XMLHttpRequest at 'https://api.v2.domain.com/api/v1/users/me/favorites?lat=42.5467&lng=-83.2113&radius=10.0&limit=5&search=' from origin 'http://localhost:8080' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

I am trying to figure out where in Kubernetes to add it - I assume it's somewhere in the Service or the Deployment.
Here's both:
apiVersion: v1
kind: Service
metadata:
  name: domain-server
  annotations:
    dns.alpha.kubernetes.io/external: "api.v2.domain.com"
    service.beta.kubernetes.io/aws-load-balancer-ssl-cert: arn:aws:acm:us-east-2:152660121739:certificate/8efe41c4-9a53-4cf6-b056-5279df82bc5e
    service.beta.kubernetes.io/aws-load-balancer-backend-protocol: http
spec:
  type: LoadBalancer
  selector:
    app: domain-server
  ports:
    - port: 443
      targetPort: 8080
---
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: domain-server
spec:
  replicas: 2
  strategy:
    type: RollingUpdate
    rollingUpdate:
      maxSurge: 3
  revisionHistoryLimit: 10
  template:
    metadata:
      labels:
        app: domain-server
    spec:
      containers:
        - name: domain-server
          image: "152660121739.dkr.ecr.us-east-2.amazonaws.com/domain-server"
          imagePullPolicy: Always
          resources:
            limits:
              memory: "1200Mi"
            requests:
              memory: "900Mi"
              cpu: "200m"
          ports:
            - name: http
              containerPort: 8080
     ...

Is this the correct place to put the header? If so, how would one add CORS to Kubernetes here? I am noticing some suggestions like Nginx ingresses, but the application I am using does not use Nginx.

A: This problem is not about Kubernetes. Browsers enforce CORS, check reference here: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS . You can also use curl or postman and see content without CORS error.
Normally nginx servers can fix that and kubernetes-nginx is not really different. It basically uses reverse proxy to control services. Check this reference to get started to fix CORS error by ingress: https://kubernetes.github.io/ingress-nginx/user-guide/nginx-configuration/annotations/#enable-cors

A: It would be much more easier if you use Nginx, that you will have to add just these annotations in service configuration file:
nginx.ingress.kubernetes.io/enable-cors: "true"
nginx.ingress.kubernetes.io/cors-allow-methods: "PUT, GET, POST, OPTIONS"
nginx.ingress.kubernetes.io/cors-allow-credentials: "true"
nginx.ingress.kubernetes.io/configuration-snippet: |
   more_set_headers "Access-Control-Allow-Origin: $http_origin";

But in your case it seems that problem is connected more with CORS that straight with Kubernetes cors-article. You have to enable CORS.
You can edit kubernetes API server yaml file, to get CORS working.
Add line --cors-allowed-origins=["http://*"] argument to /etc/default/kube-apiserver or /etc/kubernetes/manifests/kube-apiserver.yaml file, it depends where your kube-apiserver configuration file is located.
spec:
containers:
- command:
  - kube-apiserver
  - --cors-allowed-origins=["http://*"]

Then restart to kube-apiserver.
Then change annotation dns.alpha.kubernetes.io/external: "api.v2.domain.com" to dns.alpha.kubernetes.io/external: "http://api.v2.domain.com" in your service configuration file and apply changes.


text:
Q: Estimation of a sum involving Dirichlet character I want to show that :
$$\sum_{p\le x\\p^a \le x}\sum_{a=2}^{\infty}\frac{\chi(p^a)\log p}{p^a}=O(1)$$where , $\chi$ denotes the Dirichlet's character $\mod k$.

We have, $\displaystyle \left | \sum_{p\le x\\p^a \le x}\sum_{a=2}^{\infty}\frac{\chi(p^a)\log p}{p^a}\right |\le \sum_{p \le x}\log p \sum_{a=2}^{\infty}\frac{1}{p^a}=\sum_{p\le x}\frac{\log p}{p(p-1)}<\sum_{n=2}^{\infty}\frac{\log n}{n(n-1)}=O(1)$.

Is it correct ?


text:
Q: Fatal error: Call to undefined function navigator_web() in I just uploaded my website to hostinger(hosting provider)
.It works on localhost.
I get this error
Fatal error: Call to undefined function navigator_web() in /home/u664439336/public_html/index.php on line 45
localhost php version : 5.3.1
hostinger php version : 5.3
this my index.php
<?php
session_start();
unset($_SESSION['SESS_USERNAME']);
?>

    <title>Sistem Pakar Diagnosa Bipolar Disorder</title>
    <meta http-equiv="content-type" content="text/html; charset=utf-8" />
    <meta name="description" content="" />
    <meta name="keywords" content="" />
    <link href='http://fonts.googleapis.com/css?family=Questrial' rel='stylesheet' type='text/css'>

        <link rel="stylesheet" href="css/skel-noscript.css" />
        <link rel="stylesheet" href="css/style.css" />
        <link rel="stylesheet" href="css/style-desktop.css" />

<?php  include("library.php"); include("koneksi_db.php");?>

<marquee scrollamount="10">Sistem Pakar Diagnosa Gangguan Bipolar Disorder 1</marquee>

                        <?php navigator_web();?>

    <?php
  $page = $_GET['page'];
    if ($page==1)
        include ('halaman_utama.php');

    else if ($page==2)
        include ('bantuan.php');
    else if ($page==3)
        include ('informasi.php');
    else if ($page==4)
        include ('registrasi.php');
    else if ($page==5)
        include ('lupa_password.php');
    else if ($page==7)
        include ('user_diagnosa.php');

else if ($page=="daftar")
        include ('pasienaddfm.php');

    else if ($page=="daftarsim")
        include ('pasienaddsim.php');

    else if ($page=="konsul")
        include ('konsultasifm.php');

        else if ($page=="konsul2")
        include ('konsultasifm_gejala.php');

    else if ($page=="konsulcek")
        include ('konsultasiperiksa.php');

    else if ($page=="konsulcek2")
        include ('konsulperiksa2.php');

    else if ($page=="hasil")
        include ('analisahasil.php');

        else if ($page=="mania")
        include ('episodemania.php');
    else if ($page=="hipomania")
        include ('episodehipomania.php');
    else if ($page=="depresi")
        include ('episodedepresi.php');

    else if ($page=="berhasil")
        include ('berhasil_registrasi.php');
    else if ($page=="gagal")
        include ('gagal_registrasi.php');
    else if ($page=="gagal2")
        include ('gagal_registrasi2.php');
    else if ($page=="gagal_login")
        include ('gagal_login.php');
    else if ($page=="gagal_login2")
        include ('gagal_login2.php');
    else if ($page=="haruslogin")
        include ('harus_login.php');

    else if ($page=="about")
        include ('about.php');
    else
        include ('halaman_utama.php');
?>

Beri Komentar

                         <form align="center">

 <input type="text" name="nama" placeholder="Nama" />

 <input type="text" name="email" placeholder="Email" />

 <textarea name="komentar" rows="5" placeholder="Komentar"></textarea>

  <input type="submit" value="Tambahkan Komentar"/>

 </form>

Line 45
        <?php navigator_web();?>

Thank you

A: Yes the problem is that you are calling the function navigator_web() but didnt defined in the coding.You need to first define the function and then call it

A: Please add this file inclusion code at php as navigator_nav() is at library.php
 Include('library.php');


text:
Q: Data Access from Entity framework works during debugging but not on live I got unique situation in my Entityframework web application, I'm trying to load the fields in page through list but its keep saying
"The objectContext insteance has been disposed and can no longer be used for operations that require a connection."
But when I set the debugging point and step into to see what is the error it works fine??
Here is my codes: This is Under my Page Load Event...
private void loadGPYouth()
{
  List<GPYouth> leader = GPYouthLoader.getGPYouth(ViewState["LeaderID"].ToString());
   foreach (var item in leader)
   {
   ddlConstituency.SelectedValue = item.Grampanchayat.ConstituencyID.ToString();
   ddlMandal.SelectedValue = item.Grampanchayat.MandalID.ToString();
   //filling remaing fields.....
   }
}

This is under GPYouthLoader class :
public static List<GPYouth> getGPYouth(string LeaderID)
{
  List<GPYouth> list = new List<GPYouth>();
  using (var db = new TDPMADANEntities())
  {
   int _id = Convert.ToInt32(LeaderID);
   var query = (from b in db.GPYouths where b.YouthID == _id select b).ToList();
   list = query.ToList();
  }
  return list;
}

And This is my GPYouth class :
public partial class GPYouth
{
    public long YouthID { get; set; }
    public Nullable<long> GPID { get; set; }
    //Remaining Fields....
    public virtual Grampanchayat Grampanchayat { get; set; }
}

A: You're disposing your entity context (thanks to the using), so you can't lazy-load your Grampanchayat property after.
Remember lazy-loading requires to execute a new SQL request against the database, so if your connection to the DB is closed (which is, because you disposed the context) you can't lazy-load anything anymore.
It probably works in debug because the Visual Studio debugger itself tries to access to your Grampanchayat property before disposing the context (for example, to display it in the Watch window).
A proper correction to your issue would be to eager load (see this link for example ) navigation properties you're interested in, then dispose the context. All your GPYouth instances as well as all your Grampanchayat navigation properties will be fetched in one query from the DB. You won't need to execute SQL requests later using lazy-loading.
Don't let an entity context not disposed, try to shorten its lifetime as much as possible. Once you're done with it, dispose it. If anything goes wrong after, you'll know you've forgot to eager load a navigation property.
As a side note, I personally think using lazy-loading is a bad practice. Main points IMHO are: terrible performances if not used correctly (which is often the case), broken exception management (as you might fail to execute SQL on your DB anywhere is your code, not just in the DAL). I would disable it to avoid similar issues in the future.

A: In my GPYouthLoader class I have taken out the using statement and it starts working fine.
public static List<GPYouth> getGPYouth(string LeaderID)
{
  List<GPYouth> list = new List<GPYouth>();
  int _id = Convert.ToInt32(LeaderID);
  var db = new TDPMADANEntities();
  var query = (from b in db.GPYouths where b.YouthID == _id select b).ToList();
  list = query.ToList();
  // You could directly set list = (from b....).ToList(); instead of list=query.ToList();
  return list;
}


text:
Q: Complex Cron Scheduler Is it possible to start a Cron Scheduler every 30 days before the last day of each month?
I know how to trigger it every last days (not 30 days before that) using this expression for example:

0 0 9 L /1 *

Thanks for you help.
Best,
Ramzi


text:
Q: Run event on hovering on drawn line on canvas in python's tkinter gui Is there any way to have an event for hovering/clicking on a drawn line on the Canvas widget (not the widget itself)?

A: You can put a tag on the line and then bind Enter or Button-1 to the tag with the tag_bind method of the canvas widget.


text:
Q: PayPalEnvironmentProduction and PayPalEnvironmentSandbox failed I am trying to use paypal iOS SDK in out app. I finished registration and create app, then i got two client ID, sandbox and live.
When i use sandbox client ID, live client ID, i got an error.
iOS Alert Tip:
We're Sorry. There was a problem communicating with the PayPal servers. Please tey again.

(I tried many times, but still failed.)
Error Log:
PAYMENT_CREATION_ERROR - System error (PAYMENT_CREATION_ERROR). Please try again later. (422) | PayPal Debug-ID: fd805f5f6239a [live, PayPal iOS SDK 2.5.0]

Please help me.
Thank you~

A: Use only sandbox client id for testing purpose your application
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:    (NSDictionary *)launchOptions
{
// Override point for customization after application launch.
[PayPalMobile initializeWithClientIdsForEnvironments:@{PayPalEnvironmentProduction : @"YOUR_CLIENT_ID_FOR_PRODUCTION",
                                                       PayPalEnvironmentSandbox : @"AYRzOxBmlQ6vUoUn2O8UHjdYvq9hDdTQ8fE9lfA-glkMJAMYCAaZ"}];

}

I use this and its working fine for me..


text:
Q: How to enable multi touch gesture in phonegap android? I have come across a strange problem. I am showing an image within my android application.
And I want to enable multi-touch gesture but it is not working. I have found that in
samsung galaxy it works but not on other devices. Do you have any ideas guys how can I
make the thing work for all devices.
Thanks so much

A: Multitouch inside the android browser is only working for version from android 3.x
But you need to cancel a touch move to get another one. Take a look here:
http://www.html5rocks.com/en/mobile/touch.html

A: For Android devices with 2.x there is a solution about upgrading your phonegap project for multitouch using. Try this library: https://github.com/Philzen/webview-multitouch-polyfill
I use it on Android 2.3.3 with cordova-2.2.0 in Eclipse and i get a second touchevent:
    document.getElementById("yourDOMelement").addEventListener("touchstart", function(event) {
            if(event.touches.length >1){
                // more than one touch event
            }
    },false);


text:
Q: Acknowledgement Behaviour of GCP Pub/sub messages I'm working on micro-service that contains subscriptions to a topic in GCP Pub/Sub. As multiple instances of a Microservices run on more than one host (multiple clusters on cloud), I wanted to know acknowledging behaviour of messages from subscriptions. When a subscription on one instance receives, process and acknowledges the message, does the same subscription on other hosts receive the message?
I expect that once the subscriber acknowledges, pub/sub doesn't further send the message, but what if two subscribers on same subscription on different hosts receives message at the same time, does it cause duplication?

A:
Pub/Sub delivers each published message at least once for every subscription.

https://cloud.google.com/pubsub/docs/subscriber#at-least-once-delivery
If you want multiple "workers" to not receive message clones, you need to use a single subscription for all of them.
This is because for events you can have multiple systems listening on the same topic, on different subscriptions so that all the systems receive the event that something has happened.
For commands, you usually want a single system to handle them (even if split between multiple workers) so you would need a single subscription that is shared among all the workers.
By the way, your system should be idempotent in processing events/commands from a topic. The general rule of thumb is that each message is guaranteed to be received by a subscriber at least one time. Meaning the same system could potentially receive the same command two times.


text:
Q: AWS Cognito: Test triggers using postman I am very new to AWS and I am trying to implement passwordless authentication. I have created an user pool and has implemented triggers for phone & OTP authentication in AWS Cognito by following this tutorial: https://youtu.be/m8DE5ZV4FG4
I created an user using the Hosted UI in the App Client Settings in AWS Cognito. But unfortunately I didn't receive any OTP in the number which was used to sign up. Is this the right way to test it? Is there a way to test the triggers without using AWS Amplify, for eg: by using another software like Postman?

A: Just calling those lambdas will not trigger user creation, or confirmation.  User creation happens if a user calls the Cognito signup apis and:

*

*the username isn't taken

*the pre-signup trigger succeeds ( or you don't have one ) they define "succeeds" by saying the event they passed into the lambda was returned to them with only the "response" object modified.

All you could do with postman was expose your lambda trigger(s) through something like API Gateway, and pass in various payloads to see if it responds correctly. that is one way to do it..
Personally what i do to validate triggers is write unit tests that run when the trigger deploys that tests out various payloads to the triggers against an expected response.
I'm not sure what language you're writing the lambda in, but any would have SDK's available to call Cognito directly to sign up a user. That would in turn call your trigger. await Cognito.signUp({ ... }) for me in node.


text:
Q: grails service inside a package
I'm pretty new to grails and spring
Me created a service like this
services\com.mypackage\MyService

where
class MyService {
    static transactional = true

    def serviceMethod(params) {
         println "params:"+params
    }
}

Then when in my controller
controller\com.mypackage\mycontroller

Then in its action I tried to access like this
def myaction= {
        com.mypackag.MyService myService //also used def myService
        myService.serviceMethod(params)
        render(view: "otherpage")
    }

But it show the following error :(
java.lang.NullPointerException: Cannot invoke method serviceMethod() on null object

it cannot make the object of myservice.
myService shows null

What mistake i have done?
It will be very helpful if anyone provide me some good simple links and tutorials for using service with grails
Thank you

A: One mistake you have done.
You are declaring that myService inside your myaction closures. Where it should be done in the controller outside any of your methods or closures.
You can access your service methods using your service object (here myService) inside any of your methods or closures
So change like this
In your controller\com.mypackage\mycontroller  declare your service first
def myService

Then you can access it in any closures
 def myaction= {
        myService.serviceMethod(params)
        render(view: "otherpage")
    }

A: Your directory hierarchy does not correspond to you packages. You should change the directory hierarchy for your service to:
services\com\mypackage\MyService.groovy

and make sure you add the following at the top of MyService.groovy
package com.mypackage

class MyService {
  // .....
}

Similarly, change the directory hierarchy for your controller to
controller\com\mypackage\MyController.groovy

Then to get a reference to your service inside your controller
// add the correct package statement
package com.mypackage

// rename the controller and the mycontroller.groovy file to MyController
class MyController {

  // this will be injected by Spring (it must be named with a lower-case 'm')
  def myService

  def myaction= {
    // use the service inside your action
    myService.serviceMethod(params)
    render(view: "otherpage")
  }
}

A: 1) I'd read the Grails User guide on Services
2) I'd make your services using the command line tools grails provides as it will save you putting things in invalid directories (com.mypackage as a folder name is going to give you nothing but trouble), and it will make sure you have the correct package declarations at the top of your groovy files


text:
Q: How to calculate what date a particular day of the year is in excel? I've found plenty of functions to determine what day of the year a particular date is:
Function Yearday(dat As Date) As Integer
    'Purpose: does the same as day for month
    'Use to access an array where the index corresponds to days

    Yearday = DateDiff("d", CDate("1/1/" & Year(dat)), dat) + 1
End Function

But I haven't found any functions to determine the date, based on the day of a particular year.
The function signature would look like this:
Function getDateBasedOnYearAndDayOfYear(year As Integer, dayOfYear As Integer) AS Date

A: Maybe something like this,
Function getDateBasedOnYearAndDayOfYear(year As Integer, dayOfYear As Integer) AS Date
    getDateBasedOnYearAndDayOfYear = dateserial(year, 1, 0) + dayofyear
end function

A: Just create a new date with January first of the passed year, then add the number of days.  This is really easy in VBA, because Dates are just doubles with the integer portion representing the number of days since 12/31/1899.
Start with this:
Function getDateBasedOnYearAndDayOfYear(year As Integer, dayOfYear As Integer) As Date

    Dim result As Date

    result = DateSerial(year, 1, 1)
    getDateBasedOnYearAndDayOfYear = result + dayOfYear - 1

End Function

I'd probably add bounds checking and so forth, i.e. the -634th day of the year doesn't make much sense.
Edit:
Just tested against DateSerial - you don't even need to do the math:
Function getDateBasedOnYearAndDayOfYear(year As Integer, dayOfYear As Integer) As Date

    getDateBasedOnYearAndDayOfYear = DateSerial(year, 1, dayOfYear)

End Function


text:
Q: Both Production and Beta versions in Google Play I have published an app in Google Play in Production mode. Now, I have a new version which I want to be release in Beta mode for my limited number of private beta users. Is it possible to have them both? i.e. version 1.0 in production mode and version 1.1 in beta mode? Or should I maintain a different app for beta (which is not convenient, as I need to change package names).

A: you can have both, technically you can have 4 apks available to users and depending on other requirements can have even more than that.
Alpha - alpha testers who opt in can test it
Beta  - beta testers who opt in can test, can be different from alpha
Staged Rollout - percentage of users can download
Production - all users, or latest version
https://support.google.com/googleplay/android-developer/answer/3131213?hl=en

A:
Is it possible to have them both?

Yes. It is possible to have them both.
However,

i.e. version 1.0 in production mode and version 1.1 in beta mode?

It prioritizes the larger version code. So if your version code in Production is 1.0 and 1.1 in Beta, what you will see in Play Store is the one in Beta. Regardless whether it is Open Beta Testing or Communities. Haven't tried the Closed Beta Testing

Or should I maintain a different app for beta (which is not
  convenient, as I need to change package names)

In my case, I already have an app in Production until I decided to add in-app products, so I uploaded the in-app version in Beta. It turns out that it has the same package name appearing in Play Store. What I did was to deactivate first the product and disable Beta. When the app is ready, then upload it to Production and have the product activated.
As an additional thought on versionCode, let me share this answer

A: Yes, you can have both. Google play do not restrict


text:
Q: Error after Altering (Dropping columns and Change many-to-many membership) the SQLite in FLASK migrate I had a User and channel class in my model.py. They had many-to-many relationships. I decided to remove the many-to-many relationships between User and channel and add the many-to-many relationship between Usertemp class and channel class.
After this, I issue:
flask db migrate
flask db upgrade

However I received the error message that SQLite cannot perform this operation consider batch migration. I looked at other familiar topics such as https://github.com/miguelgrinberg/Flask-Migrate/issues/61#issuecomment-208131722
or Why Flask-migrate cannot upgrade when drop column
I have come across this code in both of the above links:
with app.app_context():
    if db.engine.url.drivername == 'sqlite':
        migrate.init_app(app, db, render_as_batch=True)
    else:
        migrate.init_app(app, db)

However maybe there is more do to since I still receive the SQLite error.
More Info: After looking at my version files in migration folder I had none as the name of some tables:
This is the first version of my migration file that I use batch migration to drop the column I guess the None is creating the problems:
def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.add_column('enroll', sa.Column('usertemp_id', sa.Integer(), nullable=True))
    op.drop_constraint(None, 'enroll', type_='foreignkey')
    op.create_foreign_key(None, 'enroll', 'usertemp', ['usertemp_id'], ['id'])
    with op.batch_alter_table('enroll') as batch_op:
        batch_op.drop_column('user_id')

Then I added the following to my code:
convention = {
    "ix": 'ix_%(column_0_label)s',
    "uq": "uq_%(table_name)s_%(column_0_name)s",
    "ck": "ck_%(table_name)s_%(constraint_name)s",
    "fk": "fk_%(table_name)s_%(column_0_name)s_%(referred_table_name)s",
    "pk": "pk_%(table_name)s"
}

metadata = MetaData(naming_convention=convention)
db = SQLAlchemy(app, metadata=metadata)

And the run the flask db upgrade but again I receive error:
Following is my updated migration version:
def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_constraint(None, 'enroll', type_='foreignkey')
    op.create_foreign_key(op.f('fk_enroll_usertemp_id_usertemp'), 'enroll', 'usertemp', ['usertemp_id'], ['id'])
    op.drop_column('enroll', 'user_id')
    op.create_unique_constraint(op.f('uq_user_name'), 'user', ['name'])

I suspect the solution given for render_as_batch=true can fix the issue since some people have posted it is working for them. However can anyone explain how to add it to my files, where I should add it?
I suspect it should be added env.py file. However then what else I should change after?
Is adding the above code including render_as_batch fix the problem by itself.
I would appreciate it if anyone can help since right now anytime I make a mistake I issuedb.drop_all() and create the tables again, which is very inefficient.


text:
Q: Adjusting CSV Datetime/Timestamp Formats in AWS or SQL Server I imported the contents of a SQL Server table into an S3 CSV file.
A year_month column was formatted as datetime in SQL Server, and appeared as 2020-01-01 00:00:00.000. That same record appears as 1/1/2020 12:00:00 AM in the S3 csv file.
I am using this dataset in AWS Forecast, which requires 2020-01-01 00:00:00.000 formatting.
What is the best tool within AWS to adjust the format?
Or conversely, can I tackle the problem in SQL Server?


text:
Q: Highlight selected menu item not working I am trying to get this snippet from JSFiddle working on my site. I copied the HTML directly, used the CSS inline and put the Javascript in an external file. Sadly, the functionality isn't working. You can view what I've done on my test page. I'm not experienced so any advice as to what I'm doing wrong would be very helpful.
Code from my test page
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Javascript test</title>

Aberdeen

Ada

Adamsville

Addyston

 Delphi

Ada

Saarland

Salzburg

Saarland

 Salzburg

 Delphi

Ada

Saarland

Salzburg

 Delphi

Ada

Saarland

Salzburg

Perch

Amesville

A: Make sure to include all exnternal JS libraries from JS fiddle, you can find list as shown below.
For the specific case you can include it like this:

UPD:
Move your  to the end, just before . Your code should be executed after loading of the page. So it's even better to put in to corresponsing event like this:
$(document).ready(function() {
    $( "#menu" ).menu({

        select: function( e, ui ) {

            // Remove the highlight class from any existing items.
            $( this ).find( "a.ui-state-highlight" )
                     .removeClass( "ui-state-highlight" );

            // Adds the "ui-state-highlight" class to the selected item.
            ui.item.find( "> a" )
                   .addClass( "ui-state-highlight ui-corner-all" );

        }

    });

});

UPD2:
And finally, include JQueryUI CSS file:
<link rel="stylesheet" type="text/css" href="https://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css">

I recommend you to read some Getting Started tutorial for JQueryUI to sort out such issues: https://learn.jquery.com/jquery-ui/getting-started/

A: You included jQuery, but you also need to include jQuery UI. Since you're using the google CDN for jQuery, you can use that same CDN for jQuery UI. Add this after your jQuery script tag.

You can also use the CDN on jquery.com here https://code.jquery.com/ui/


text:
Q: SQL many to many select category_product
---------------
id_category
id_product

product
---------------
id_product
id_manufacturer

manufacturer
---------------
id_manufacturer
name

How would I create an SQL query so that it selects all the names from manufacturer when id_category is equal to something?

A: It's a straightforward inner join of the tables:
SELECT m.name, cp.id_category
FROM manufacturer as m
INNER JOIN product as p
    ON m.id_manufacturer = p.id_manufacturer
INNER JOIN category_product as cp
    ON p.id_product = cp.id_product
WHERE cp.id_category = 'some value'

A: Select M.name
From   manufacturer M
Where  M.id_manufacturer in ( Select P.id_manufacturer
                              From   product P
                              Where  P.id_product in ( Select C.id_product
                                                       From   category_product C
                                                       Where  C.id_category = ?))

A: Query without joins will look like following :
SELECT m.name
FROM manufacturer as m, product as p, category_product as cp
WHERE cp.id_category = <your value>
      AND cp.id_product = p.id_product
      AND p.id_manufacturer = m.id_manufacturer

A: Try something like
SELECT  m.*
FROM      category_product cp INNER JOIN
           product p ON cp.id_product = p.id_product INNER JOIN
           manufacturer m ON p.id_manufacturer = m.id_manufacturer
WHERE      cp.id_category = <your_value>

A: SELECT m.name, cp.id_category
FROM manufacturer AS M INNER JOIN product AS P
    ON M.id_manufacturer = M.id_manufacturer
 INNER JOIN category_product AS CP
    ON P.id_product = CP.id_product
WHERE cp.id_category = 'add value'


text:
Q: Javascript using datejs to parse RFC3339 datetime I'm having trouble using datajs with a date format from Google Calendar API. The datetime format I believe is RFC3339 and this is a sample datetime returned from the calendar api
2012-01-05T08:45:00Z

This is from the datejs documentation here
Date.parse('1985-04-12T23:20:50Z')          // RFC 3339 Formats

But this just returns null.
I'm assuming I have datejs working correctly as
Date.today().next().friday()

returns Fri May 11 2012 00:00:00 GMT+0100 (BST)

A: SOLVED: Use Date.parseExact OR this version according to this Bug report
DEMO using date.js
DEMO using date-en-US.js

Using the first version I get
null
http://datejs.googlecode.com/files/date.js
Line 13

when I take the assertions out of the testsuite:
// null
console.log('Date.parse("1985-04-12T23:20:50Z")',
  Date.parse('1985-04-12T23:20:50Z'));

// my previous answer works
console.log('Date.parse("1985-04-12T23:20:50Z".replace(...))',
     Date.parse('1985-04-12T23:20:50Z'
           .replace(/\-/g,'\/')
           .replace(/[T|Z]/g,' ')
     )
  );

// the test suite without the Z works
console.log('1985-04-12T23:20:50',
  new Date(1985,3,12,23,20,50).equals( Date.parse('1985-04-12T23:20:50')));

// but this one fails when not in the test suite
try {
  console.log('1985-04-12T23:20:50Z',
    new Date(1985,3,12,23,20,50).equals( Date.parse('1985-04-12T23:20:50Z')));
}
catch(e) {
     console.log('1985-04-12T23:20:50Z',e.message);
}

Here is an older answer for this issue when not using date.js


text:
Q: Why does easy_install work with some Windows binaries? Background
Windows does not include a compiler by default, and installing a compiler (and perhaps configuring Python to use it) is a complicated enough task that many developers avoid doing so. To this end, many packages that have binary dependencies are available as a precompiled Windows executable that contains binary files. As an example, there is psycopg.
The executable file is an installer. When executed, it provides a graphical interface that locates an installed version of Python via the registry, and it installs the Python library and the included binary dependencies in the global Python installation.
However, this is not always desirable. Particularly when using virtualenv, developers don't want to install the library globally. They want the library installed in the virtual environment. Since this environment is not represented in the registry, the graphical installer cannot locate it. Luckily, a command similar to the following can be used to install the library to the virtual environment:
C:\> C:\virtualenv\Scripts\activate.bat
(virtualenv) C:\> easy_install psycopg2-2.5.win32-py2.7-pg9.2.4-release.exe

Note that this works regardless of whether easy_install comes from setuptools or distribute.
The actual question
Why does this command work? What is it about the exe that allows easy_install to process it?
I have noticed that the exe seems to be some kind of zip file. 7-Zip is able to open it for browsing, and these exe files that easy_install can process seem to have a common file structure. They have a top directory named PLATLIB which contains an egg-info file or folder and another (possibly more than 1?) folder. Are these exes just Python eggs with some kind of executable wrapped around them? How might I produce one myself? (Or to word it differently, is there some standard way of producing exes like this?)
Edit
Bonus question: Why doesn't pip work with these files?


text:
Q: Let $G$ be the set of all $2 \times 2$ symmetric invertible matrices with real entries Let $G$ be the set of all $2 \times 2$ symmetric invertible matrices with real entries then with matrix multiplication, $G$ is not from a group. Help me to find a counter examples.

A: Take $A=\begin{bmatrix} 1 & 2 \\ 2 & 1 \end{bmatrix}$,
$B=\begin{bmatrix} 1 & 0 \\ 0 & 2 \end{bmatrix}$. Clearly, $A,B$ are symmetric and they are elements of $G$.
Then $AB=\begin{bmatrix} 1 & 4 \\ 2 & 2 \end{bmatrix}$.
Since $AB$ is not symmetric, the set is not closed under multiplication and hence does not form a group.


text:
Q: iOS 6 - Keyboard does not show even the UIView is still first responder I have an UIView work like a textEditor with can become first responder to show keyboard. When my UIView with keyboard is showing, I press home button to put app to background and open other app, open a file to my app. The problem is the keyboard is not automatically shown after the modal viewController is dismissed.
I have a check and see: the isFirstResponder of my UIView is YES. But the keyboard is still not available. At that time my application have 2 windows, but the second window does not contains keyboard as usual.
It's weird. Anyone have this problem like me ?
Note that this issue is only on iOS 6.0.


text:
Q: Automatically Set Alerts on List Is it possible to create a workflow or jquery function within the list's page that would allow a user to automatically be signed up for the built-in sharepoint alerts on any item they themselves create in the list?  This can be remedied with a workflow to create our own custom alert emails, but would like to try to implement the built-ins. Is this doable?

A: In SharePoint Designer, create a workflow that sends an email to the creator of the item on creation and on item change.  This is out of the box functionality.

but would like to try to implement the built-ins

Not sure what you mean by that.. unless you mean out of the box.


text:
Q: How does $\sqrt {\frac{{4 + \sqrt {15} }}{8}} = \frac{{\sqrt {8 + 2\sqrt {15} } }}{4}$ I have the follow answering to a question from my textbook:
$\sqrt {\frac{{4 + \sqrt {15} }}{8}}$
However my textbook simplifies it to:
$\frac{{\sqrt {8 + 2\sqrt {15} } }}{4}$
I've checked and my answer seems to be the same value as the one in the textbook but How do I go about getting the textbooks answer?

A: $$\frac{4+\sqrt{15}}8=\frac{8+2\sqrt{15}}{16}$$
which in fact can be further simplified as
$$\frac{(\sqrt3)^2+(\sqrt5)^2+2\sqrt3\sqrt5}{16}=\left(\frac{\sqrt5+\sqrt3}4\right)^2$$

A: Multiply as follows:
$$\sqrt{\frac{4+\sqrt{15}}{8}\frac{2}{2}}=\sqrt{\frac{8+2\sqrt{15}}{16}}=\frac{\sqrt{8+2\sqrt{15}}}{4}$$


text:
Q: Probability in game of bridge In a game of bridge, find the probability that the North, East, South, and West hands will get respectively $a,b,c,d$ spades.
I tried like this. First I choose $a$ spades from the $52$ cards; then, from the remaining $39$ I choose $b$ spades; then, from the remaining $26$ cards I choose $c$ spades, and the rest can be done in $1$ way only. But am not sure about my solution. Please help.

A: Imagine dealing in an unusual way, $13$ cards to South, then $13$ to East, and so on.
There are $\binom{52}{13}$ equally likely ways to choose the cards South gets. There are $\binom{13}{a}\binom{39}{13}$ ways to choose $a$ spades and $13-a$ non-spades. So the probability that South gets the right kind of hand can be computed. For the record (we will not do it again) it is $\frac{\binom{13}{a}\binom{39}{13-a}}{\binom{52}{13}}$
Now there are $39$ cards left, of which $13-a$ are spades, and $26+a$ non-spades.
There are $\binom{39}{13}$ equally likely ways to choose the cards East gets.There are $\binom{13-a}{b}\binom{26+a}{13-b}$ ways to give East the right kind of hand.
Now there are $26$ cards left, $13-a-b$ spades and $13+a+b$ non-spades. There are $\binom{26}{13}$ ways to choose North's cards. There are $\binom{13-a-b}{c}\binom{13+a+b}{13-c}$ ways to give North the right kind of hand.
And now it's over.  When we multiply the probabilities and compute the binomial coefficients, there is a pleasant amount of cancellation.
Remark: We should really give a symmetrical solution. The numbers $a$, $b$, $c$ appear quite asymmetrically in the argument, and poor $d$ did not get mentioned at all. Symmetry reappears when we simplify, and may suggest a much nicer argument.
Out of tiredness, I just gave a solution that's ugly, but works. Maybe tomorrow.


text:
Q: Leaky Stack Function I need to create a LeakyStack where the stack size is 5 and the capacity is 10. Following should be the end result -

Some notes are :
If at a point, the stack (i.e. the inner array of the stack) is as follows:   [4, 1, 3, 2, 5, None, None, None, None, None], where "4" is the bottom of the stack and "5" is the top of the stack, and a new number "8" is pushed in the stack, the stack should be as follows:  [None, 1, 3, 2, 5, 8, None, None, None, None, None].  This means "4" is ignored (leaked).
If at a point the stack is as follows: [2, 3, None, None, None, None, None, 8, 9, 1], where "8" is the bottom of the stack and "3" is the top of the stack, and a new number "5" is pushed in the stack, the stack will become: [2, 3, 5, None, None, None, None, None, 9, 1]. This means "8" is ignored (leaked).
Other special situations should be considered such as performing a pop operation when the stack is empty.
This is my code. Right now I need to fix something at the __init__ and at the end I think.
class Full(Exception):
pass

class Empty(Exception):
pass

class MyLeakyStack:

def __init__(self, maxlen, capacity, len):
    # note: this function is partially completed
    self.data = []
    self._maxlen = maxlen
    self._capacity = capacity  # size of the circular array
    self._storage = [None] * capacity  # initialise storage room, this is treated as a circular array

def __len__(self):
    return self.len

def push(self,x):
    if self.len == maxsize:
        del self.data[0]
        self.data.append(x)
    else:
        self.data.append(x)
        self.len += 1

def pop(self):
    self.len = -1
    self.data.pop()

def is_empty(selfs):
   return len(self.data)==0

def __str__(self):
    return ' '.join(str(self.data[i]) for i in range(len(self.data)))

if __name__ == '__main__':

 S = MyLeakyStack(5, 10)   # stack size should be 5 and the capacity of the array should be 10

 for i in range(12):
    try:
        S.push(i)
        print("after push "+str(i), S._storage)
    except Exception as e:
        print(e)

 for i in range(6):
    try:
        a=S.pop()
        print("after pop "+str(a), S._storage)
    except Exception as e:
        print(e, S._storage)

 for i in range(5):
    try:
        S.push(i+100)
        print("after push " + str(i+100), S._storage)
    except Exception as e:
        print(e, S._storage)

a = MyLeakyStack()
a.push(1)
a.push(2)
a.push(3)
a.push(4)
a.push(5)
a.push(6)
a.push(8)
a.push(0)
a.pop(1)
print(len(a))

A: First of all, I don't understand why are you passing "len" to the __init__ function, Since you are not using that parameter.
Secondly, even if you were doing something with it (i can see you are calling self.len in the other object functions), you can't use the word "len" to name a variable, because its reserved for the len() function.
So, I would say you don't need that when you initialise your object, because as soon as it is created it's length is always going to be 0.
I changed a your code to match the required output.
class Full(Exception):
    pass

class Empty(Exception):
    pass

class MyLeakyStack:

    def __init__(self, maxlen, capacity):
        # note: this function is partially completed
        self._maxlen = maxlen
        self._capacity = capacity  # size of the circular array
        self._storage = [None] * capacity  # initialise storage room, this is treated as a circular array
        self.f = 0
        self.r = 0

    def __len__(self):
        return (self._capacity - self.r + self.f) % self._capacity

    def push(self,x):
        self._storage[self.f] = x
        self.f = (self.f + 1) % self._capacity
        if len(self) > self._maxlen:
            l = self._storage[self.r]
            self._storage[self.r] = None
            self.r = (self.r + 1) % self._capacity
            raise Full("Reach stack limit, forget element " + str(l))

    def pop(self):
        if self.is_empty():
            raise Empty("Stack is empty")

        pop = self._storage[self.f - 1]
        self._storage[self.f - 1] = None
        self.f = (self.f - 1) % self._capacity
        return pop

    def is_empty(self):
        return self.f == self.r

    def __str__(self):
        return " " + str(self._storage)

if __name__ == '__main__':

    S = MyLeakyStack(5, 10)   # stack size should be 5 and the capacity of the array should be 10

    for i in range(12):
        try:
            S.push(i)
            print("after push "+str(i), S._storage)
        except Exception as e:
            print(e)
            print("after push "+str(i), S._storage)

    for i in range(6):
        try:
            a=S.pop()
            print("after pop "+str(a), S._storage)
        except Exception as e:
            print(e, S._storage)

    for i in range(5):
        try:
            S.push(i+100)
            print("after push " + str(i+100), S._storage)
        except Exception as e:
            print(e, S._storage)

a = MyLeakyStack(5, 10)
a.push(1)
a.push(2)
a.push(3)
a.push(4)
a.push(5)
a.push(6)
a.push(8)
a.push(0)
a.pop()
print(str(len(a)))

Here's the output I get, that is kind of the same of what you're asked to have.
after push 0 [0, None, None, None, None, None, None, None, None, None]
after push 1 [0, 1, None, None, None, None, None, None, None, None]
after push 2 [0, 1, 2, None, None, None, None, None, None, None]
after push 3 [0, 1, 2, 3, None, None, None, None, None, None]
after push 4 [0, 1, 2, 3, 4, None, None, None, None, None]
Reach stack limit, forget element 0
after push 5 [None, 1, 2, 3, 4, 5, None, None, None, None]
Reach stack limit, forget element 1
after push 6 [None, None, 2, 3, 4, 5, 6, None, None, None]
Reach stack limit, forget element 2
after push 7 [None, None, None, 3, 4, 5, 6, 7, None, None]
Reach stack limit, forget element 3
after push 8 [None, None, None, None, 4, 5, 6, 7, 8, None]
Reach stack limit, forget element 4
after push 9 [None, None, None, None, None, 5, 6, 7, 8, 9]
Reach stack limit, forget element 5
after push 10 [10, None, None, None, None, None, 6, 7, 8, 9]
Reach stack limit, forget element 6
after push 11 [10, 11, None, None, None, None, None, 7, 8, 9]
after pop 11 [10, None, None, None, None, None, None, 7, 8, 9]
after pop 10 [None, None, None, None, None, None, None, 7, 8, 9]
after pop 9 [None, None, None, None, None, None, None, 7, 8, None]
after pop 8 [None, None, None, None, None, None, None, 7, None, None]
after pop 7 [None, None, None, None, None, None, None, None, None, None]
Stack is empty [None, None, None, None, None, None, None, None, None, None]
after push 100 [None, None, None, None, None, None, None, 100, None, None]
after push 101 [None, None, None, None, None, None, None, 100, 101, None]
after push 102 [None, None, None, None, None, None, None, 100, 101, 102]
after push 103 [103, None, None, None, None, None, None, 100, 101, 102]
after push 104 [103, 104, None, None, None, None, None, 100, 101, 102]
Traceback (most recent call last):
  File "so.py", line 77, in <module>
    a.push(6)
  File "so.py", line 27, in push
    raise Full("Reach stack limit, forget element " + str(l))
__main__.Full: Reach stack limit, forget element 1

Consider that it ends with an error because that's an Exception you raised. If you want the script not to stop, you need to use a try-except block.


text:
Q: Como descobrir o negativo de uma cor em hexadecimal? Gostaria de saber qual é o cálculo que posso utilizar em linguagem como javascript, php ou python para descobrir o negativo de uma cor hexadecimal.
Exemplo: Se negativo de branco é preto, então eu pressuponho:
`#FFFFFF => #000000`

Ou
 0xFFFFFF => 0x000000

A: A cor inversa pode ser calculada via OU exclusivo (XOR) versus o valor máximo (#FFFFFF).
O formato de cores em hexadecimal já é uma dica de como realizar esta operação: cada um dos duplos octetos em #RRGGBB representa uma cor primária, cuja intensidade pode variar de #00 a #FF (255 em decimal).
Em outras palavras, cada cor primária é representada por 8 bits.
Para inverter uma cor, inverta os bits:
Cor     Valor HEX valor BIN                     BIN invertido                 HEX invertido
Preto   #000000   B00000000 00000000 00000000   B11111111 11111111 11111111   #FFFFFF
Branco  #FFFFFF   B11111111 11111111 11111111   B00000000 00000000 00000000   #000000
Azul    #0000FF   B00000000 00000000 11111111   B11111111 11111111 00000000   #FFFF00

Um exemplo de código em Angular/javaScript que realiza esta operação segue abaixo:

function SampleController($scope) {
  $scope.sourceValue = 0;
  $scope.inverseColor = function(){
    var srcVal = $scope.sourceValue;
    var valNumerico = parseInt(srcVal, 16);
    var mascara = parseInt('FFFFFF', 16);
    var dest = valNumerico ^ mascara; //Operação XOR
    return dest.toString(16);
  };
}

      Cor: #<input type='text' ng-model='sourceValue'>

      Inversa: {{ inverseColor() }}

A: Encontrei um exemplo em PHP:
function color_inverse($color){
    $color = str_replace('#', '', $color);
    if (strlen($color) != 6){ return '000000'; }
    $rgb = '';
    for ($x=0;$x<3;$x++){
        $c = 255 - hexdec(substr($color,(2*$x),2));
        $c = ($c < 0) ? 0 : dechex($c);
        $rgb .= (strlen($c) < 2) ? '0'.$c : $c;
    }
    return '#'.$rgb;
}

Testando:
// preto -> branco
print color_inverse('#000000');
// --> retorna #ffffff

Créditos: Link

A: Se for apenas para exibição você pode resolver isso no CSS
-webkit-filter: invert(100%);
filter: invert(100%);

Via Javascript tem a solução nessa outra pergunta.
https://stackoverflow.com/questions/1664140/js-function-to-calculate-complementary-colour


text:
Q: How to link two rows in attribute table to the same polygon? There are two rows in an attribute table. I want to link both rows to the same polygon. How can I do this?

A: A feature only ever has one row in an attribute table.
If you have a requirement that suggests you need two or more then I recommend using a second table and adding a relate to it.
The help page About joining and relating tables is well worth reviewing.


text:
Q: How can i get vertical space between li tag using CSS i would like to get vertical space in between each
 tag  in one of my list items. I tried it using CSS Grid, but then i getting equal vertical space and has unnecessay extra space eventhough there is one line of sentence. Hopes anyone can help me to get a solution. Following is the code. Thanks in advance!

html {font-family: Arial, Helvetica, sans-serif;}
a {color:#555;text-decoration:none;}
.container {padding: 1.5rem;background-color: #cdcdcd;margin: 1rem;/* width: 50%; *//* border: 1px solid red; */}

@media only screen and (min-width:567px) {
.container {padding:3rem;background: #f9f9f9;}
}

.list {
    background: #fff;
}
.list__ul {
    list-style: none;
    padding: 0;
    margin: 0;
    column-count: 2;
    border:1px solid red;
}
.list__item {
    display: flex;
    align-items: flex-start;
    break-inside: avoid-column;
}

.list__item:before {
    content: "";
    width: .10rem;
    height: .1rem;
    padding: 2px;
    background-color: transparent;
    border: solid #555;
    border-width: 0 2px 2px 0;
    display: inline-block;
    transform: rotate(-45deg);
    -webkit-transform: rotate(-45deg);
    margin-right: .75rem;
    margin-top: .25rem;
}
.list__link {
    text-decoration: none;
    color: #666;
}

One Precise control In addition to the ability to place items accurately onto a created grid, the CSS Grid Layout specification contains rules that control what happens.

Two Default value One Precise control In addition to the ability to place items accurately onto a created grid, the CSS Grid Layout specification contains rules that control what happens

Three Sequential navigation

Four Algorithm specification

Five Dynamic Sources

Six Auto Placement

Seven Task Allocation

Eight Implicit Contents

Nine Absolute Specification

A: add padding to li element, if you want to isolate it only to this ul list then use something like:
.list__ul li {
     padding-top: 20px;
}

To skip the first li element:
.list__ul li:nth-child(1n+2) {
     padding-top: 20px;
}

In order to also have vertical space use padding-right or padding-left or try to use padding inside class element list__item.

A: You can simply add margin-bottom of your desired space in list__item class.e.g. I am using margin-bottom: 10px;. This will solve your problem.
.list__item {
    display: flex;
    align-items: flex-start;
    break-inside: avoid-column;
    margin-bottom: 10px;
}
.list__item:last-child {
                margin-bottom: 0px;
            }

A: If you add an after pseudo element to the ul element you can set its height to be the height of the ul minus the padding given to each li.
Then set the border on this pseudo element rather than on the ul.
If it is important that the ul takes only the space it looks as though it's taking then set its bottom margin to minus the padding given to each li.

html {
  font-family: Arial, Helvetica, sans-serif;
}

a {
  color: #555;
  text-decoration: none;
}

.container {
  padding: 1.5rem;
  background-color: #cdcdcd;
  margin: 1rem;
  /* width: 50%; */
  /* border: 1px solid red; */
}

@media only screen and (min-width:567px) {
  .container {
    padding: 3rem;
    background: #f9f9f9;
  }
}

.list {
  background: #fff;
}

.list__ul {
  list-style: none;
  padding-bottom: -20px;
  margin: 0;
  column-count: 2;
  position: relative;
}

.list__ul::after {
  content: '';
  position: absolute;
  width: 100%;
  display: inline-block;
  left: -1px;
  top: -1px;
  height: calc(100% - 10px);
  z-index: 1;
  border: 1px solid red;
}

.list__item {
  display: flex;
  align-items: flex-start;
  break-inside: avoid-column;
  padding-bottom: 10px;
}

.list__item:before {
  content: "";
  width: .10rem;
  height: .1rem;
  padding: 2px;
  background-color: transparent;
  border: solid #555;
  border-width: 0 2px 2px 0;
  display: inline-block;
  transform: rotate(-45deg);
  -webkit-transform: rotate(-45deg);
  margin-right: .75rem;
  margin-top: .25rem;
}

.list__link {
  text-decoration: none;
  color: #666;
}

One Precise control In addition to the ability to place items accurately onto a created grid, the CSS Grid Layout specification contains rules that control what happens.

Two Default value One Precise control In addition to the ability to place items accurately onto a created grid, the CSS Grid Layout specification contains rules that control what happens

Three Sequential navigation

Four Algorithm specification

Five Dynamic Sources

Six Auto Placement

Seven Task Allocation

Eight Implicit Contents

Nine Absolute Specification


text:
Q: Hugging face whoami endpoint returns unauthorized Can't make /whoami endpoint of hugging face API work. I'm using curl and pass a token that I've got from the UI in the Authorization header.
$ curl https://huggingface.co/api/whoami -H "Authorization: Bearer <token>"
> { "error": "Unauthorized" }

At the same time I can use the same token to get private models
$ curl https://huggingface.co/api/models/private/model -H "Authorization: Bearer <token>"
> {"id": "private/model", "modelId": "private/model", ...}

Is there something I do wrong?

A: Thanks for raising this!
The endpoint was updated to whoami-v2, it seems we missed updating that doc page. Here is a working example
curl https://huggingface.co/api/whoami-v2 -H "Authorization: Bearer your_token"

Note that we also have a Python library with a whoami method you can use if that's useful. https://github.com/huggingface/huggingface_hub/tree/main/src/huggingface_hub


text:
Q: PL/SQL parser to identify the operation on table I am writing a PL/SQL parser to identify the operations(Select,Insert,Delete) performed on the Table when I run Procedure, Function or Package.
GOAL:I Goal of this tool is to identify which all the tables will be affected by running the procedure,Fun to prepare with better test case.
Any better ideas or tool will really help a lot.
INPUT:
some SQL file with procedure
     or proc file.

OUTPUT required is:
SELECT from: First_table, secondTable
->    In procedure XYZ       --This is if the procedure is calling one more procedure
INSERT into: SomeTable
INSERT into: SomeDiffTable
->   END of procedure XYZ   --End of one more procedure.
DELETE from: xyzTable
INSERT into: OnemoreTable
My requirement is When I am parsing porc1 if it calls another proc2. I have to go inside that proc2 to find out what all the operation is performed in that and come back to proc1 and continue.:
For this I have to store the all procedure some where and while parsing I have to check each token(word with space) in the tempStorage to find out if it is  procedure or not.
As my logic's takes lot of time. Can any body suggest better logic to achieve my GOAL.

A: There's also the possiblity of triggers being involved.  That adds an additional layer of complexity.
I'd say you're better off mining DBA_DEPENDENCIES with a recursive query to determine impact analysis in the abstract; it won't capture dynamic SQL, but nothing will 100% of the time.  In your case, proc1 depends on proc2, and proc2 depends on whatever it depends on, and so forth.  It won't tell you the nature of the dependency - INSERT, UPDATE, DELETE, SELECT - but it's a beginning.
If you're really interested in determining the actual impact of a single-variable-value run of a procedure, implement it in a non-production system, and then turn auditing on your system up to 11:
begin
  for i in (select owner, object_type, object_name from dba_objects
             where owner in ([list of application schemas]
               and object_type in ('TABLE', 'PACKAGE', 'PROCEDURE', 'FUNCTION', 'VIEW')
  loop
    execute immediate 'AUDIT ALL ON ' || i.owner || '.' || i.object_type ||
                      ' BY SESSION';
  end loop;
end;
/

Run your test, and see what objects got touched as a result of the exectution by mining the audit trail.  It's not bulletproof, as it only audits objects that got touched by that execution, but it does tell you how they got touched.


text:
Q: Under what conditions does Mathematica give a natural antiderivative when integrating? Natural antiderivative is defined as follows, using Fourier transform:
$$f^{(-1)}(x)=\frac{i}{2\pi}\int_{-\infty}^{+\infty} \frac{e^{- i \omega x}}{\omega} \int_{-\infty}^{+\infty}f(t)e^{i\omega t}dt \, d\omega$$
Particularly, if $x=0$,
$$f^{(-1)}(0)=\frac{i}{2\pi}\int_{-\infty}^{+\infty} \frac{1}{\omega} \int_{-\infty}^{+\infty}f(t)e^{i\omega t}dt \, d\omega$$
Expressed as Mathematica code:
(I/Sqrt[2*Pi])*Integrate[(1/w)*FourierTransform[f[t], t, w], {w, -Infinity, Plus[Infinity]}]

That said, I wonder if Mathematica always adheres to the rule of providing the antiderivative which would satisfy this condition.
For instance, Integrate[Sin[x], x] gives -Cos[x], which satisfies the condition as -Cos[0] == -1.
I wonder how much this rule is adhered to in the output of Integrate.

A: Your equation has a sign error for the inverse Fourier transform. A simpler prescription is
I InverseFourierTransform[FourierTransform[f[t], t, w]/w, w, x]

Although there is a lrge range of function for which this works, it will of course fail for all those functions for which the Fourier transform can't be calculated. Anyway, it does work for polynomials, e.g. as follows:
Table[
 Integrate[x^n, x] ==
  I InverseFourierTransform[FourierTransform[t^n, t, w]/w, w, x], {n,
  1, 10}]

(* ==> {True, True, True, True, True, True, True, True, True, True} *)

But an example for which Integrate works and the Fourier approach doesn't is this simple case:
I InverseFourierTransform[FourierTransform[t^(1/2), t, w]/w,
  w, x]

(*
==> I InverseFourierTransform[FourierTransform[Sqrt[t], t, w]/w,
  w, x]
*)


text: Q: programmatically intercept traffic originated by Android 3rd party libraries included in my app I'm trying to write some code that intercepts any network traffic from/to my Android app, including traffic originated by 3rd party libraries, on a non-rooted devices. Is there a way to do it?