text:
Q: How to apply an "interface" method to a set of rows in kdb? Sorry if this is a newbie question again.
I am trying to replicate the functionality of interfaces as seen in c++, rust etc. in kdb as is shown in a simple demonstration below:
q).iface.a.fun:{x*y+z}
q).iface.b.fun:{x*x+y+z}
q)ifaces:`a`b; // for demonstration purposes
q)tab:([]time:`datetime$();kind:`ifaces$();x:`long$();y:`long$();z:`long$());
q)n:10;
q)tab,:flip(n#.z.z;n?ifaces;n?10;n?10;n?10)

Now you would assume that the kind would be able to reference the `a`b fun methods of the iface interface as follows:
q)?[`tab;();0b;`max`ifaceval!((max;`x);(`.iface;`kind;`fun;`x;`y;`z))]
evaluation error:

fun

  [0]  ?[`tab;();0b;`max`ifaceval!((max;`x);(`.iface;`kind;`fun;`x;`y;`z))]
       ^

Obviously the functional nature of the select inhibits referencing the fun method on account of the symbol type field declarations.
You can avert this error by using enlist as follows:
q)?[`tab;();0b;`max`ifaceval!((max;`x);(`.iface;`kind;enlist`fun;`x;`y;`z))]
max ifaceval                                                                    ..
-----------------------------------------------------------------------------..
9   77 154 95 65 0 128 153 126 60 49 77 154 95 65 0 128 153 126 60 49 77 154 ..

However this duplicates the result of fun for each row.
How might one effectively go about this without getting the above malformed responses?
Thanks again.

A: Selecting ifaceval first will ensure each row is returned. max x is a scalar, which forces all the ifaceval entries into one row. The scalar will be expanded across all rows if a vector column precedes it.
q)?[`tab;();0b;`ifaceval`max!((`.iface;`kind;enlist`fun;`x;`y;`z);(max;`x))]
ifaceval                          max
-------------------------------------
160 11 126 28 32 60 76 10 112 168 8
96  10 77  24 16 35 60 6  63  104 8
96  10 77  24 16 35 60 6  63  104 8
96  10 77  24 16 35 60 6  63  104 8
96  10 77  24 16 35 60 6  63  104 8
160 11 126 28 32 60 76 10 112 168 8
96  10 77  24 16 35 60 6  63  104 8
160 11 126 28 32 60 76 10 112 168 8
160 11 126 28 32 60 76 10 112 168 8
160 11 126 28 32 60 76 10 112 168 8

I'm not sure if this is exactly what you're looking for though. If you want to calculate ifaceval for each row in the table, this should work.
q)?[tab;();0b;`ifaceval`max!(((';(`.iface;::;enlist`fun));`kind;`x;`y;`z);(max;`x))]
ifaceval max
------------
160      8
10       8
77       8
24       8
16       8
60       8
60       8
10       8
112      8
168      8

One point to make is that it's probably best to avoid using kdb keywords for column names. Although it works in functional queries, it does not for qSQL ones.
q)select max:max x from tab
'assign
  [0]  select max:max x from tab
                 ^


text:
Q: Ionic 3 - Building prod app gives extra ngfactory and metadata files Have a quick question.
I'm building an app with Ionic, and when I ran
ionic cordova build android --prod

It generated a lot of new files inside my "src/pages"

I'm just wondering if I should track these files in my Github, ignore them, or if there is any way to build in a different folder so I can keep my project files clean.
Thanks a lot.

A: I had the same issue while generating the build for release. Guess there is a bug somewhere when a specific error occurs, but I could remove these files safely without any issues and now my build is running without errors and won't generate all these files.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to handle delimiter with backslash in data How do i handle | which is also a delimiter in my data,
Here is a sample field value,
|152| XXXXXXXXXX XXXXXXXXXX.1001 0503~ADX\|0\|ZZ~NTE\|ADD\|XXXXXXXXXX/~SE\|40\|0060~GE\||

the value XXXXXXXXXX XXXXXXXXXX.1001 0503~ADX\|0\|ZZ~NTE\|ADD\|XXXXXXXXXX/~SE\|40\|0060~GE\ is a single field value but due to escaping the backslash, the values are moving to next fields.
I need to have the column value XXXXXXXXXX XXXXXXXXXX.1001 0503~ADX\|0\|ZZ~NTE\|ADD\|XXXXXXXXXX/~SE\|40\|0060~GE\ and it should not get split into multiple columns .How can I fix this.
regexp_replace(col(c), "\\\\|", "\\\\\\\\|")) is not working

A: As mentioned in the question, if you have data in format as
152| XXXXXXXXXX XXXXXXXXXX.1001 0503~ADX\|0\|ZZ~NTE\|ADD\|XXXXXXXXXX/~SE\|40\|0060~GE\||

Then, you should read it using sparkContext's textFile and replace \| with some other strings and then split with |, convert to dataframe and finally use regexp_replace function for replacing the converted string back to \|
val rdd = sc.textFile("path to the text file")
              .map(line => Row.fromSeq(line.replaceAll("\\\\\\|", "#%#").split("\\|", -1).toSeq))

val schema = StructType(Seq(StructField("col1", StringType, true),StructField("col2", StringType, true),StructField("col3", StringType, true)))

val df = spark.createDataFrame(rdd, schema)

df.withColumn("col2", regexp_replace(col("col2"), "#%#", "\\\\\\|")).show(false)

which should give you
+----+-----------------------------------------------------------------------------------+----+
|col1|col2                                                                               |col3|
+----+-----------------------------------------------------------------------------------+----+
|152 | XXXXXXXXXX XXXXXXXXXX.1001 0503~ADX\|0\|ZZ~NTE\|ADD\|XXXXXXXXXX/~SE\|40\|0060~GE\||    |
+----+-----------------------------------------------------------------------------------+----+

I hope the answer is helpful


text:
Q: Configuring NGINX to work with SAML Signing Certificate I've built an app using PHP (Laravel), and now we've deployed it to a client who wants to use Azure Single Sign On rather than the apps native username/password functionality.
The plan is for them to handle the SSO authentication via App Registration, and then send user details via a SAML request.
However the 'SAMLResponse' I get is encoded. They have sent me a .cer file (and an XML file for some reason), and I think I need to apply these to the server, but I don't know how.
The below is the setup their end, and I've red highlighted the files they've sent me.
I have full control over the server, which is Ubuntu 18.04 running NGINX. They also handle the SSL side of things separately, so NGINX is currently listening on port 80.


text:
Q: Identificar que campos se modificaron al actualizar un formulario y guardarlos Tengo un formulario que lo actualizo, pero me gustaría saber de que forma podría identificar que campos fueron los que se modificaron de forma especifica. Luego de eso guardarlos para que mas adelante puedan ser tomados en cuenta en una ponderación.
En donde a cada usuario se le reste un punto por cada modificación.
He intentado hacer una comparación antes de actualizar los datos y los que resulten diferentes entonces guardarlos en otra tabla que solo contendrá las modificaciones especificas. Aun no me ha funcionado del todo bien y creo que se podría hacer de una forma mas eficiente.
De esta forma en mi metodo update verifico los cambios y los guardo:
$facturaModificada =  new Modificacion;

    if($factura->documento != $request->documento){
        $facturaModificada->save();
    }

A: Puedes utilizar isDirty(). Primero guardas los cambios en el modelo.
$factura = find($request->id)->fill($request->all());

Posterior a eso, verificas si hubo algún cambio utilizando dicho método:
if($factura->isDirty()){
     // Obtienes los cambios y creas el nuevo registro
}

Si no quieres utilizar fill, puedes hacerlo manualmente:
$factura->atributo = $request->atributo;
...
$factura->save();

Nota: No usar el método update() para usar isDirty().
Si quieres revisar cuáles son los cambios, puedes obtenerlo mediante getChanges():
$factura->getChanges();

Y crear el nuevo registro con los cambios:
if($factura->isDirty()){
     Modificacion::create($factura->getChanges());
}


text:
Q: selenium with brave implementation Is there a way to Brave (Chromium web browser) browser directly as driver for Selenium
from selenium import webdriver as wd
driver=wd.Chrome(executable_path='/snap/bin/brave')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/timmy/.local/lib/python3.6/site-packages/selenium/webdriver/chrome/webdriver.py", line 73, in __init__
    self.service.start()
  File "/home/timmy/.local/lib/python3.6/site-packages/selenium/webdriver/common/service.py", line 98, in start
    self.assert_process_still_running()
  File "/home/timmy/.local/lib/python3.6/site-packages/selenium/webdriver/common/service.py", line 111, in assert_process_still_running
    % (self.path, return_code)
selenium.common.exceptions.WebDriverException: Message: Service /snap/bin/brave unexpectedly exited. Status code was: -11

brave does open but driver is undefined

A: I'm no expert, but here's how I got it to work. I didn't get the driver issue and I was able to open Brave using Selenium.  Notice that in the argument that I included the letter 'r' and backslashes.
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
options = Options()
browser = webdriver.Chrome(r"XXXXXX\XXXX\brave.exe")


text:
Q: Irregular grid for finite differences PDE solution I got a project in a class I'm taking. In this project, I need to solve fluid dynamics and heat equations.
Up to here, the problem is not so complicated, however the chamber shape is the problem:

as you can see, FE and JA makes this shape non rectangular. Since I want to keep the grid relatively simple, I though about creating a grid with "stairs" in those edges, that will look like that:

I can quite easily calculate the area lost and use it as a measurement for the solution quality (let's say that I can allow 0.5% or less area loss).
Is it a good solution, or is there any better methods, assuming that I want to keep the grid relatively simple?
Thanks!


text:
Q: In what sense do measures induced by heat kernel converge to Wiener measure? Let $p(t,x)$ denote the Gaussian density on $\mathbb{R}^d$ with variance $t$. To each finite partition $D=\{0=t_0,\dots,t_n=1\}$ of $[0,1]$ associate the measure on $(R^d)^n$, $\mu_D$ by $$\mu_D(dx)=\Pi_{i=1}^np(t_{i+1}-t_i, x_i-x_{i-1})dx_i.$$ These are the transition densities of $d$-dimensional BM started at $0$ and can be viewed as measures on path space - the product space $(R^d)^{[0,1]}$. Kolmogorov extension theorem then tells us that this net of measures $\mu_D$ extend to a measure $\mu$ on $(R^d)^{[0,1]}$, known as Wiener measure (the law of BM) -- once you fiddle around with Kolmogorov continuity theorem.
Now my question is, in what sense can do we have $\lim_{|D|\to 0}\mu_D=\mu$? In particular, for which path-functionals $f:(R^d)^{[0,1]}\to R$ do we have that $\mu_D(f)\to\mu(f)$? Even vague ideas/references would be much appreciated!


text:
Q: Is there a Chrome extension to make RSS work like Opera? When you're opening RSS URL, Opera shows a button to subscribe.
When you're browsing the site with RSS meta tags, Opera shows an icon to subscribe.
Is there any Chrome add-ons with the same logic?
Now I'm trying very stylish NewsSquares, but it can't do anything of these.

A: The RSS Agreggator chrome extension work and look like Opera:
https://chrome.google.com/webstore/detail/the-rss-aggregator/ffhafkagcdhnhamiaecajogjcfgienom

A: I think you're looking for the official RSS Subscription Extension


text:
Q: Use input parameter within lambda schedule in Cloudformation I'm trying to enable/disable lambda scheduled event based on environment, and not having much luck. If the env is prod, it should enable the schedule, and if it's dev it should disable it. However, the schedule status doesn't obey the condition. It's currently enabled in dev, but the template doesn't disable it. If I set the Enabled property to false manually, the schedule status does change to disable. So not sure where I'm going wrong (or if what I'm trying to do is possible). Any help is greatly appreciated!
Parameters:
  env:
    Type: String

Conditions:
  isProd:
    !Equals [!Ref env, prod]

Resources:
  func:
    Type: AWS::Serverless::Function
    Properties:
      Events:
        ScheduledEvent:
          Type: Schedule
          Properties:
            Schedule: rate(5 minutes)
            Enabled: !If [isProd, true, false]

A: Okay, so after a bit more searching, it looks like setting the Enabled property with conditional statements doesn't work so nice. The workaround I've put in place is to use conditional statements in the Schedule property.
ScheduledEvent:
  Type: Schedule
  Properties:
    Schedule: !If [isProd, "rate(5 minutes)", "cron(00 00 01 01 ? 1970)"]

Thanks to these posts for point me in the right direction:
Conditionally enabling an event schedule in AWS sam template file
Dynamically change event properties on aws cloudformation templates


text:
Q: Grouping together related sets I have a set S consisting of N sets, each containing 2 or more numbers. E.g.:
S={{1,2,6},{6,3,4,2},{6,2},{1,9,12},{7,8,12}}. So, here N=5
The question is: Determine which sets should be grouped together, depending on how many identical numbers they have. If, for instance, a set is a subset of a larger set (e.g. the second and third set in the example), then we would want that those are grouped together. However, also if there is a reasonable correlation between sets, we would want to group them together.
The total number of groups is given (P). The sizes of the groups are on average N/P, but they may vary.
I think there is probably a standard algorithm to tackle this problem, can anyone help me finding it? Thanks!

A: Here's an untested idea:
Create a graph with the sets as vertices and with the Jaccard index (A∩B) / (A∪B) as edge weight between sets A and B. Vertices with disjoint sets (and Jaccard index 0) are not connected.
Then use a clustering algorithm to divide the graph into clusters, where edges with a low weight are cut, so that you get P disjoint subgraphs. Correlation clustering might also be an approach, although you can't control the number of groups, but you could guess a threshold similarity.

A: The algorithm you are looking for is named k-means. It's an iterative  algorithm that converges N points into k predefined sets. The convergence may be stopped earlier, if you set a threshold for the number of iterations. In any cases, it stops when a state (p - 1) yielded the same sets of the current state (p).
In your case, you have k = P predefined points (a.k.a. centroids). Each of the N points in your dataset is a set itself. To put points together in a single cluster, k-means requires a similarity metric. That means you have to provide a function that, given two points from the data base, tells how similar they are.
As pointed by @MOehm, Jaccard index is a nice metric to evaluate the similarity in between sets. In general, as long as you decide which similarity metric to use, any clustering algorithm that allows use to set the number of final clusters is a solution.


text:
Q: Two sliders that depend on each other I defined two sliders which can have values between 0 and 200 each. One slider is for the minimum value and the second is for the maximum value.
Now a requirement is that minimum < maximum. I can ensure this requirment in the listeners method of the two sliders, but I would like to prevent that the user can even select values that don't meet this requirements on the slider. How can I do that?

A: If you are using a presentation pattern, like MVVM…
Bind each slider to a property in the presentation-model/view-model. Make sure you set Mode=TwoWay on the binding.
Now, in the view-model, you can make your setters do the work. They can either stop at the limit (where the other property is set), or also push the complementary property. For example, if max is set to 100, and the user slides min to 150, you can set max at 150 as well. As long as you're raising the property change notifications, the user will see the other slider move, too.

A: One way would be to bind the current "Minimum" slider value to the Minimum property of the Maximum slider and vice versa. This may lead to a slightly odd-feeling effect as the slider repositions itself, but it would certainly prevent invalid selections.


text:
Q: Session "user_id" from spring project to non-spring project I'm working on a small Java EE project which is gonna join a much bigger one. The main project was designed using maven and spring frameworks. Mine don't as it's really a basic one.
Here is my problem :
The main project already logged the user using the Active Directory of the company and store it into spring. The code looks like this :
@Configuration
@EnableWebMvcSecurity
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {

    private final String URL = "blablablabla";
    private final int PORT = 389;
    private final String MANAGER_DN = "CN=blablablabla,OU=blablablabla,OU=blablablabla,OU=blablablabla,OU=blablablablaFund,OU=EBS,DC=blablablabla,DC=blablablabla,DC=blablablabla";
    private final String MANAGER_PASSWORD = "blablablabla";
    private final String GROUP_BASE = "OU=blablablabla,OU=blablablabla,OU=blablablabla,OU=blablablabla,DC=blablablabla,DC=blablablabla,DC=blablablabla";
    private final String USER_SEARCH_BASE = "DC=blablablabla,DC=blablablabla,DC=blablablabla";
    private final String USER_SEARCH_FILTER = "(sAMAccountName={0})";
    private final String GROUP_ROLE_ATTR = "blablablabla";
    private final String GROUP_SEARCH_FILTER = "(member={0})";
    private final String ROLE_LDIG_ALPHA = "blablablabla";

    @Override
    @Autowired
    protected void configure(AuthenticationManagerBuilder authManagerBuilder) throws Exception {
        authManagerBuilder
            .ldapAuthentication()
                .userSearchBase(USER_SEARCH_BASE)
                .userSearchFilter(USER_SEARCH_FILTER)
                .groupRoleAttribute(GROUP_ROLE_ATTR)
                .groupSearchFilter(GROUP_SEARCH_FILTER)
                .groupSearchBase(GROUP_BASE)
                .contextSource().url(URL).port(PORT).managerDn(MANAGER_DN).managerPassword(MANAGER_PASSWORD);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/**").hasRole(ROLE_LDIG_ALPHA)
                .anyRequest().authenticated()
                .and()
            .formLogin()
            .and()
            .httpBasic();
    }
}

Now I need to retrieve user session information from my servlet for example without having the user log again (I repeat : I do not use the spring framework)
Is that possible?

A: A simple implementation would be to create a cookie in authentication handling project and store related non-sensitive information in it, then read the cookie in the other project.
another implementation would be to use jndi to register your object and then read in other needed place.


text:
Q: How do I make it so font-awesome icons have no text decoration? I seem to be having an issue where font awesome icons are rendering in purple for links that are already clicked. Here is how I set up the HTML:

CSS:
.notxtdec {
text-align: center;
align-items: center;
font-size: 12px;
text-decoration: none; }

A: .notxtdec selects a div, not your link. If you want to set the text-decoration for the hyperlink, you need to do something like this, which targets the anchor tag:
.notxtdec {
    text-align: center;
    align-items: center;
    font-size: 12px;
}

.notxtdec a {
    text-decoration: none;
}

text-decoration will just remove the underline that most browsers automatically add, so if you're trying to set the link, active, or visited colors, you need to add those rules as well:
/* anchor tags which have a valid href attribute */
.notxtdec a:link {
    color: #yourcolorhere
}

/* anchor tags which are being pressed/clicked */
.notxtdec a:active {
    color: #yourcolorhere
}

/* anchor tags which have an href which exists in the browser's history */
.notxtdec a:visited {
    color: #yourcolorhere
}

A: The example here can help you.
If you add something like this to your css file, it will always stay the same color even if you click on this link before.
a:link {
  color: red;
  text-decoration: none;
}

a:visited {
  color: red;
  text-decoration: none;
}


text:
Q: Compare Harvest to other source control systems? From the top, "source control" seems like a bad way to describe CA Harvest; it's a deployment control system, and it's actually pretty good at just deploying code.  I've found it to be lacking when doing source control tasks, though.
If you've used Harvest;

*

*what did it do right?

*what couldn't it do?

*what did it do with a workaround so hackish it took 3x longer than you'd expect?

A: (Someone correct me if I'm wrong.)  Harvest seems awesome for deployment control, enforcing steps along a deployment lifecycle, and getting a chain of approval for deployments to production.  That said, it's missing on the developer-friendly side.
It seems like I need to use the Workareas; they let me put all the code on my local machine, so I can do development.
With Workareas, I can only synchronize from the repository, but not get a report of what just sync'ed in; I don't know what changed, or who changed it, or why.
To add comments to checkins using Workareas, you have to manually enable the functionality in the preferences, which is a huge red flag to me.
I can't seem to figure out how to find out what changed since a specific time; what changed since Friday at 5 PM, for example?
There aren't any atomic commits; I can't commit files as a group, then roll the group back later if something goes wrong.  I can do it as a package, but that's heavyweight; a package should be able to contain hundreds of atomic commits/groups.
And worst of all, it's entirely unsupported by Stack Overflow and/or any other question-and-answer site I can find.  If I can't figure it out... I'm shooting blind.

A: We're currently migrating away from Harvest.

*

*Configuration management and code deployment. We have a pretty good process flow going.

*Branching and merging. Horrible SCM tool really.

*?


text:
Q: Scala - recursive compare function I'm working on a function to recursively run through a list of Ints and return a Boolean stating whether each item in the list is the same number. I've taken a stab at it below but it's not passing the tests I'm running. Here's what I've got, any suggestions are much appreciated. Thanks!
def equalList (xs : List[Int]) : Boolean = {
def equalAux (xs:List[Int], value:Int) : Boolean = {
    xs match {
        case Nil => true
        case x :: xs if (x == value) => equalAux(xs, x)
        case x :: xs if (x != value) => false
          }
}
  equalAux(xs, x)
}

A: As you said in your comment, you just need to make sure the list is not empty so you can give an initial value to your recursive function:
def equalList(xs: List[Int]): Boolean = {

  def equalAux (xs: List[Int], value: Int): Boolean = {
    xs match {
      case Nil => true
      case x :: xs if x == value => equalAux(xs, x)
      case x :: _ if x != value => false
    }
  }

  // Check to make sure the list has at least one item initially
  xs match {
    case Nil => true
    case head :: tail => equalAux(tail, head)
  }
}

println(equalList(List.empty))           // true
println(equalList(List(1)))              // true
println(equalList(List(1, 1, 1, 1)))     // true
println(equalList(List(1, 1, 1, 1, 2)))  // false
println(equalList(List(1, 2, 1)))        // false

A: Do you need a recursive function? If not, I would use Set as a trick:
myList.toSet.size <= 1 // because empty list returns true. Else make it == 1

If you do need recursion, then @Tyler answer is the answer I would also give.


text:
Q: Log JSON message in Camel Route I tried googling this and found nothing.
I know that you can use expression language like ${file:name} to log the file name, but how do you log the contents. How do you log the contents of the json message being passed forward?

A: You can log the body and headers of the exchange by writing
.log(LoggingLevel.INFO, "test", "${body} and ${headers}")

A: Depending on how you log, but you can use a TraceFormatter with showBody set to true, read http://camel.apache.org/tracer.html


text:
Q: Python Search multiple html files in a variable I have used Selenium driver to crawl through many site pages. Every time I get a new page I append the html to a variable called "All_APP_Pages". The variable All_APP_Pages is a variable holding html for many pages. Did not post code because its long and no relevant to issue. Python list "All_APP_Pages" as being of type bytes.
from lxml import html
from lxml import etree
import xml.etree.ElementTree as ET
from selenium.webdriver.common.by import By

dom = etree.HTML(All_APP_Pages)
xp = "//tr[.//span[contains(.,'Product Data Solutions (UHC MR)')] and .//td[contains(.,'SQLServer')] and .//td[contains(.,'MR')]]//a"
link = dom.xpath(xp)

print(link)

Once all pages have been scanned I need to get the link from this xpath
"//tr[.//span[contains(.,'Product Data Solutions (ABC MR)')] and .//td[contains(.,'SQLServer')] and .//td[contains(.,'MR')]]//a"

The xpath listed here works. However it only works with the selenium driver if driver is on the page where this link exists. That is why all page are in one variable since I dont know what page the link will be on. The print shows this result
[<Element a at 0x1c39dea1180>]

How do I get this value from link I so can check if value is correct?

A: You need to iterate the list and get the href value
dom = etree.HTML(All_APP_Pages)
xp = "//tr[.//span[contains(.,'Product Data Solutions (UHC MR)')] and .//td[contains(.,'SQLServer')] and .//td[contains(.,'MR')]]//a"
link = dom.xpath(xp)
hrefs=[l.attrib["href"] for l in link]
print(hrefs)


text:
Q: Why doesn't my compiler like this statement? This is supposed to return false if a character in the string isn't a letter or an apostrophe. Any idea why it doesn't work? And is there a better way that I can write it? I'm trying to write code like a C++ purist.
for (std::string::const_iterator it = S.begin(); it != S.end(); ++it)
    if ((*it < 'a' || *it >'z') && (*it > 'A' || *it < 'Z') && (*it != ''''))
        return false;

A: I see two mistakes:

*

*'''' should be '\''.

**it > 'A' || *it < 'Z' should be *it < 'A' || *it > 'Z'.


text:
Q: Normalized weighted Euclidian Distance Hi Guys I would like to get an euclidian distance and be able to compare multiple set o data but I am not sure how to normalized it properly
Each data set have values ranging from (-100->100) and with weight from (0-> 5)
I give you an example( I use python to calculate it):
def test2(x, y, z):
    return sqrt(sum(c*(pow(a-b, 2)) for a, b, c in zip(x, y, z)))

c = test2([90,-74,83],[57,83,-72],[1,4,3])

with a output distance of 414.4393803682271
I would like to translate that value on a scale from 0-100 how can I do it ?
Thx you very much

A: For example, if  $x $ is your Euclidean distance, then normalized value could be equal to $ N(x)=\frac{100x}{1 + x} $. (While $x$ goes from 0 to $ +\infty$, $N(x)$ goes from 0 to 100.)
There are many different functions -- we could give a more thorough answer if you would come up with some domain-specific constraints on normalizing function. (For example, you could consider sigmoid functions.)


text:
Q: Where to upload files in Jboss and later download them? We are moving one web app from Tomcat 7.0 to Jboss 7.1. In this web app there is a possibility to upload documents by the users. These documents can be then downloaded or deleted by the users as well.
The documents have been stored within the web application (this is a requirement, so we cannot store the documents in a DB or in another folder outside of the app on the web container).
When using Tomcat I could have done smth. like the following in java code to get an existing absolute path to the directory where the files were stored:
    String catalinaHome = "";
    String dataPath = "";

    try {
        if (System.getenv("CATALINA_HOME") != null) {
            catalinaHome = System.getenv("CATALINA_HOME");
        } else if (System.getProperty("catalina.base") != null) {
            catalinaHome = System.getProperty("catalina.base");
        }

        dataPath = catalinaHome + "/webappsdata/" + APP_NAME + UPLOADED_FILES;

How can I achieve the same or similar goal when we I now use Jboss 7.1 instead of Tomcat?
Using smth. like System.getProperty("JBOSS_HOME") didn't work for me.
Thanx a lot in advance.

A: I have found the following solution, which might not be elegant, but works for me. Using System.getProperties() I have got a loads of properties. The one keys that were interesting for me were: "jboss.server.data.dir" and "${project.artifactId}${project.version}" (the 2nd one gives you an absolute path to the deployed app).
Hope it helps somebody.


text:
Q: Qt QCompleter multiple matches I am trying to make QCompleter match several equivalent options which are separated with commas. There seemingly is no easy way to do that, but one line of QCompleter reference caught my attention, describing function QCompleter::splitPath: "When used with list models, the first item in the returned list is used for matching." Could this be used in the way I need - split the input string and return it so the unfinished last item is the first in the list? I didn't manage to make it work, but I may be doing something wrong.

A: Here is another way of doing it that I think is more in line with the original question. No need for a complex data model, uses a simple QStringListModel instead.
import sys
from PyQt4 import QtCore, QtGui

class test(QtGui.QWidget):
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)

        model = QtGui.QStringListModel()
        wordList = ['John Doe','Jane Doe','Albert Einstein', 'Alfred E Newman']
        model.setStringList(wordList)

        layout = QtGui.QVBoxLayout(self)
        self.line = QtGui.QLineEdit(self)
        layout.addWidget(self.line)

        complete = CustomCompleter(self)
        complete.setModel(model)
        complete.setCaseSensitivity(QtCore.Qt.CaseInsensitive)
        complete.setCompletionMode(0)
        complete.setWrapAround(False)

        self.line.setCompleter(complete)

class CustomCompleter(QtGui.QCompleter):
    def __init__(self, parent=None):
        QtGui.QCompleter.__init__(self, parent)

    def pathFromIndex(self, index):
        path = QtGui.QCompleter.pathFromIndex(self, index)

        lst = str(self.widget().text()).split(',')
        if len(lst) > 1:
            path = '%s, %s' % (','.join(lst[:-1]), path)

        return path

    def splitPath(self, path):
        path = str(path.split(',')[-1]).lstrip(' ')
        return [path]

#===============================================================================
# Unit Testing
#===============================================================================
if __name__ == '__main__':

    app = QtGui.QApplication(sys.argv)
    window = test()
    window.show()
    sys.exit(app.exec_())

A: From what I understand from your question and the doc, you could separate the user-inputted string with commas and make your completer check in your model for a completion.
BUT, after each comma, the index of your model (figure it like a two-dimension array of string) will be incremented.
For example, if you have the following input:
ABCD, EFGH, IJ
and you would like to the completer to finish IJ KL, you would have to have a model that is at least 3 indexes wide because the first text (ABCD) would be completed with the strings in the first column, EFGH would be completed with the second column of your model, etc.
So, I don't know if it could be used in your application.
Best of luck.

A: General purpose multi-completer code which supports all separators in the member DELIMITERS can be found in the code snip below. It seems easy but it was very annoying to debug due to very bad documentation on the pyQt side.
class CustomCompleter(QtGui.QCompleter):
    DELIMITERS = r'[()\[\]*+-=/\\]'
    def __init__(self, parent=None):
        QtGui.QCompleter.__init__(self, parent)
    def pathFromIndex(self, index):
        path = QtGui.QCompleter.pathFromIndex(self, index)
        string = self.widget().text()
        split = re.split(self.DELIMITERS, string)[-1]
        if len(split)==len(string):
            string_without_split = ''
        else:
            if len(split)>0:
                string_without_split = string[:-len(split)]
            else:
                string_without_split = string
        return string_without_split+path

    def splitPath(self, path):
        split = re.split(self.DELIMITERS, path)[-1]
        return [split]


text:
Q: Converting decimal values to non decimal in computed column in oracle sql I am trying to convert decimal values into non decimal number for a computed column in Oracle SQL.
Please see the below code. But I am not able to get the desired output.
Query:
Select cast(cost_account)*100/cast(amnt_fin) as "computed_LTV"
From Loan_app.

Here I Want a new column name as computed_LTV with the required calculation with no decimal in the output.

A: It is ROUND you're looking for, I presume.
SELECT ROUND (cost_account * 100 / amnt_fin) AS "computed_LTV" FROM Loan_app

A: If by "non-decimal number" you mean "integer", just use trunc():
Select trunc(cost_account * 100 / amnt_fin) as computed_LTV
From Loan_app;


text:
Q: System of three equation, find alpah for, one solution, no solution and infitne solution Hi guys having and issue with this question. part a) check and part b) help
So for the first part, I just took the inverse matrix which I assume to be correct as, the only two matrixs I know of that give an idenity is A*A^-1.
for the secon part I seemto be getting conflicting results.
So when I look at the bottom two equation they run parallel to each other, so when alpha=6 I should get no solutions, but when I use cramers I see that for the
determinat: D: I get: -a^2+5a+6 setiing that equal to zero I get: a=-1 a=6
for the other determinats
Dx= a^2-7a+6
Dy= -2a+12
Dz=0
now using the condtions for cramers that, if
If D = 0, and at least one of Dx, Dy, or Dz is non-zero, then the system has no solution.
and
If D = 0, and Dx = Dy = Dz = 0, then the system has infinitely many solutions.
I get that if a=6 then I get infintely solutions and when a=-1 I get no solutions.
So as D is only 0 at a=6 and a=1 then for one solution any number beside them two is vaild. Can someone please give advice be much appreciated.


text:
Q: What is going on with java.nio.charset.Charsets? So, as far as I can tell, this class doesn't exist in the standard Java library and is an addition in Dalvik. Is this correct?
My reason for thinking this is the android class "NdefRecord" contains reference to it and uses it but there is no way of importing it into a standard Java project (that I can find).
Is there any way to import this class to an Android project?
Where can I find it's up-to-date content, as used by the android project?

A: java.nio.charset.Charsets, which is different from Charset, is unique to Dalvik.  If you look at the comment header in the source file you will see:
@hide internal use only

This means it is not part of the public API, and should not be used by applications.  If you decide to use it anyway, you will need to access it through reflection.


text:
Q: How to handle jQuery Validation errors I have a form that i'm validating with some required fields in it. i'm using the jquery.validate plugin to validate the form. below is the snippet:
Js:
    var validator = $("#accountCreateForm").validate({

    // Specify the validation rules
    rules: {
        firstname: "required",
        lastname: "required",
        email: {
            required: true,
            email: true
        }
    },

    // Specify the validation error messages
    messages: {
        firstname: "Please enter your first name",
        lastname: "Please enter your last name",

        email: "Please enter a valid email address"
    }

});
$('#button').on("click", function(){
  $.wm.net.restRequest('/account/data',{
     //post the required data
  }).fail(function() {
    // do the error handling
  }).done(function() {
    //post data successfully
   });
 });

HTML:
 <form action="" method="post" id="register-form" >

First Name
<input type="text"  name="firstname" />

Last Name
<input type="text" id="lastname" name="lastname" />

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

<button id="button" type="submit" name="submit" >Submit</button>

 </form>

With the above initialization of the validation plugin, the form does not validate, mainly because im not doing anything in the error handling function. I'm not sure how can i handle the validation at the error function :
}).fail(function() {
    // do the error handling
  });

Thanks!

A: Your form name is 'register-form', but you are validating 'accountCreateForm'.
Here I tried this one with your form, this works for me:
var validator = $("#register-form").validate({

    // Specify the validation rules
    rules: {
        firstname: "required",
        lastname: "required",
        email: {
           required: true,
           email: true
        }
    },

    // Specify the validation error messages
    messages: {
        firstname: "Please enter your first name",
        lastname: "Please enter your last name",
        email: "Please enter a valid email address"
    }

});

$('#button').on("click", function(){

    if($('#register-form').valid())
    {
        /*  Do your saving, etc stuffs here */
        $('#register-form').submit();

    }

});


text:
Q: Scala 3 : Equality compilation error occurring only for certain types I am trying to understand Scala3 new "Multiversal Equality" feature. I am experiencing inconsistent behavior when comparing different types.
case 1. Compare Int with String:
  val x = 1
  val y = "One"

  x == y  // gives compilation error -> "Values of types Int and String cannot be compared with == or !="

*

*Compilation error even without importing scala.language.strictEquality

*This compiles in Scala2 without any errors

case 2. Compare two case classes:
  case class Cat(catname: String)
  case class Dog(dogname: String)
  val d = Dog("Frank")
  val c = Cat("Morris")

  d == c  // false, but it compiles

I am aware of the fact that I need to import scala.language.strictEquality to enforce Multiversal equality in case2. But why is it not required in case1?

A: Notice that
case 1. summon[CanEqual[Int, String]] doesn't compile even without importing scala.language.strictEquality
case 2. summon[CanEqual[Cat, Dog]]

*

*compiles without importing scala.language.strictEquality but

*doesn't compile with such importing.

a) Instances of type class CanEqual are generated by the compiler (as well as scala.reflect.ClassTag, scala.reflect.TypeTest, scala.ValueOf, scala.deriving.Mirror.Product, scala.deriving.Mirror.Sum, scala.deriving.Mirror)
  val specialHandlers = List(
    defn.ClassTagClass        -> synthesizedClassTag,
    defn.TypeTestClass        -> synthesizedTypeTest,
    defn.CanEqualClass        -> synthesizedCanEqual,
    defn.ValueOfClass         -> synthesizedValueOf,
    defn.Mirror_ProductClass  -> synthesizedProductMirror,
    defn.Mirror_SumClass      -> synthesizedSumMirror,
    defn.MirrorClass          -> synthesizedMirror)

https://github.com/lampepfl/dotty/blob/master/compiler/src/dotty/tools/dotc/typer/Synthesizer.scala#L489-L499
b) The thing is that the case when one of type parameters L, R of CanEqual[-L, -R] is a numeric value class (Byte, Short, Char, Int, Long, Float, Double) is handled differently:
  val synthesizedCanEqual: SpecialHandler = (formal, span) =>
    ...
    if canComparePredefined(arg1, arg2)
        || !Implicits.strictEquality && explore(validEqAnyArgs(arg1, arg2))
    ...

https://github.com/lampepfl/dotty/blob/master/compiler/src/dotty/tools/dotc/typer/Synthesizer.scala#L147-L148
Notice that here if the answer is given by canComparePredefined then it doesn't matter whether strictEquality is switched on.
c) canComparePredefined calls
def canComparePredefinedClasses(cls1: ClassSymbol, cls2: ClassSymbol): Boolean =
  ...

  if cls1.isPrimitiveValueClass then
    if cls2.isPrimitiveValueClass then
      cls1 == cls2 || cls1.isNumericValueClass && cls2.isNumericValueClass
    else
      cmpWithBoxed(cls1, cls2)
  else if cls2.isPrimitiveValueClass then
    cmpWithBoxed(cls2, cls1)
  ...
  else
    false

https://github.com/lampepfl/dotty/blob/master/compiler/src/dotty/tools/dotc/typer/Synthesizer.scala#L108-L114
Notice that here if one of L, R is a numeric value class then the other must be too (taking into account boxing) so that summon[CanEqual[Int, Int]], summon[CanEqual[Double, Double]], summon[CanEqual[Int, Double]] compile but summon[CanEqual[Int, String]] doesn't compile.

A: Universal equality only works for types without CanEqual instances already defined. As stated in Multiversal Equality:

Even though canEqualAny is not declared as given, the compiler will still construct an canEqualAny instance as answer to an implicit search for the type CanEqual[L, R], unless L or R have CanEqual instances defined on them, or the language feature strictEquality is enabled.

and since there is already an instance of CanEqual for String defined in the companion object as:
given canEqualString: CanEqual[String, String] = derived

universal equality will not work for String nor Int (as per @DmytroMitin the compiler makes special consideration to Scala's numeric types) even with strictEquality disabled.


text:
Q: Hot to remove first and last double quotes in Angular 4? Just like JavaScript, TypeScript also uses the double quote (") or single quote (') to surround string data.
I'm returning some data from back end which contains some HTML.
My API response:
afjhjhfsd

and I print this on view in angular 4 like {{response}}.
When I inspect in chrome browser it is showing like:
"
afjhjhfsd
"

Due to this reason it is also printing paragraph tag on angular 4 view.
Please help me into this.

A: try binding to innerHTML


text:
Q: Represent of a collection of binary data I'm working with signals in which the samples consist of Floats. Some of the algorithms I've written only require to know when the signal crosses the x-axis (i.e. positive value to a negative value and vice versa). When I'm doing these kinds of operations, I realized that I don't need to know the actual Float value of each sample. I just need to know whether the sample's value is positive or not.
I originally represented the signal as a Vector of Floats. After my discovery, I started representing it as a Vector of Boolean values (i.e. False for a negative value and True for a positive value). This turned out to be a lot more efficient and I improved the program's performance both in terms of run-time and memory consumption.
I'm still wondering if there isn't a more efficient way of representing this "collection of binary data". Something like a Bit Vector or Bit Array. I've found a BitArray on Hackage but it doesn't seem to support the same functionality that a Vector does.
Is there a more efficient way of representing the data of my use case or should I stick to a Vector of Boolean values?

A: Both one-bool-per-byte and one-bool-per-bit options are available from the vector and array packages respectively.
First, a Vector Bool from Data.Vector.Unboxed uses a byte array with one byte per Bool.  This can be verified from the source in module Data.Vector.Unboxed.Base where Vector Bool is defined as:
newtype instance Vector    Bool = V_Bool  (P.Vector    Word8)

and getting and setting are mediated through the functions:
fromBool :: Bool -> Word8
toBool :: Word8 -> Bool

Alternatively, it can be verified directly by profiling the program:
import Data.Vector.Unboxed as V
main = let v = V.replicate 1000000000 True
  in print (v ! 5)

and observing that it allocates just over 1,000,000,000 bytes.
Second, a UArray Int Bool from Data.Array.Unboxed is implemented as a bit vector, with one Bool per bit.  The relevant source is in Data.Array.Base, where you can see the bit manipulation used in the instance:
instance IArray UArray Bool where
    ...
    unsafeAt (UArray _ _ _ arr#) (I# i#) = isTrue#
        ((indexWordArray# arr# (bOOL_INDEX i#) `and#` bOOL_BIT i#)
        `neWord#` int2Word# 0#)

Again, this can be verified directly by profiling:
import Data.Array.Unboxed as A
main = let v = A.listArray (1,1000000000) (repeat True) :: UArray Int Bool
  in print (v ! 5)

and verifying that it allocates approximately 125,000,000 bytes.


text:
Q: R- Create function that selects entire row in data frame by column name This is a question for an R Programming class, but I have been working on it for several hours, over a period of a few days. I have done internet searches and referenced three different books. I have tried very hard to solve it on my own. I am finally asking for help.
I was given a csv, which I read into the program. This is the resulting dataframe, named df:
   name hw0 hw1 hw2 hw3 hw4 hw5 hw6 quiz1 quiz2 quiz3 quiz4 quiz5 quiz6 term1
1        20  14  30 100  50  60  36    12    15    30    15    25    25   100
2     A  20  13  30 100  50  60  30    11    15     0    14    25    25   100
3     B  20  14  30 100  50  60  36     8    11    24     8    13     9    95
4     C  20  14  28 100  50  60  36    12     4    25    13    24    14    95
5     D  20  12  30 100  50   0  33     7    15    26    12    22     0   100
6     E  20  14  30  90  30   0   0    10    15    30    15    21    15   100
7     F  20  13  30 100  48   0  36    12    15    30    15    25    23    95
8     G  20  14  26  85  40  42  33    11    15    23    11    17    16    90
9     H  20   0   0  85  50   0   0     0    15     0     0    15    10    85
10    I  20  14  15   0  10  48  30    11     0    27    11    14    16    60
11    J  20  14  29  80  35   0  36    11    13    24    12    14     0    70
12    K  20  14  29  97  50  60  36     4     7    19    11    20    15   100
13    L  20  14  30 100  45   0  36    10     6    26     8    16     7    80
14    M  20  14  30 100  50  60  36     7    15    28    14    25    25   100
15    N  20  11   0  95  20   0   0     8    14    26     7     9     0    95
16    O  20  12  28  97   0  40   0    11    10    27    11    15    15    70
17    P  20  13   0  90  45   0  20     4    13    30    10    20    17    90
18    Q  20  14  30 100  45   0  36     0    12    21    11    14    17    75
   term2 term3 exam1 exam2 exam3 final
1    100   100   100   100    95   100
2    100   100    97    97    80    97
3    100   100    83    85    73    73
4    100   100    88    75    56    77
5    100     0    90    87    72    81
6    100    80    92    82    69    79
7    100   100    90    95    87    90
8    100     0    89    79    81    78
9     90   100    62    83    42    75
10    90    72    78    78    66    81
11     0     0    79    77    51    78
12   100   100    79    77    57    81
13     0   100    68    74    76    76
14   100   100    99    98    82    99
15     0     0    70    70    52    61
16     0     0    63    66     0     0
17   100   100    75    72    56    64
18    90    75    72    84    54    63

QUESTION:
checkStudent <- function(df, studentName);
This function extracts a particular student's grades data from a data frame and returns them.
REQUIRED FORMAT:
checkStudent <- function(df, studentName)
{

}

TIPS PROVIDED:
inputs:
 df -- a data frame that contains all the grades data
 studentName -- name of a student
return:
 all the grades for the student whose name is given as studentName
purpose:
 extracting a particular student's grades data from a data frame and returning them
PROJECT TESTER- line of code and expected results:
checkStudent(df,"A")

   name hw0 hw1 hw2 hw3 hw4 hw5 hw6 quiz1 quiz2 quiz3 quiz4 quiz5
 2    A  20  13  30 100  50  60  30    11    15     0    14    25
   quiz6 term1 term2 term3 exam1 exam2 exam3 final
 2    25   100   100   100    97    97    80    97

I feel like I have been given everything and still can't get it right. I have tried:
checkStudent <- function(df, studentName)
{
  name <- studentName
  df["name", ]
}

and
checkStudent <- function(df, studentName)
{
  subset(df, "name" == studentName, 1:21)
}

and numerous other lines of code, too many to list.
Please help. I am truly stuck.
Again, this needs to be done strictly in R. If it matters, I'm using RStudio. Thank you so much.

A: You're really close.
Variables in R should never be encapsulated in quotes, but always are free standing. Additionally your code is just printing the row, it is not returning it.
Here's a slightly modify version of your first attempt, without the quotes.
checkStudent <- function(df, studentName)
{
  name <- studentName
  return(df[name, ])
}

Edit: Oops, I realized your rows aren't named as the students.
You'll need to make it more like this:
checkStudent <- function(df, studentName)
{
  my_row <- which(df$name == studentName)
  return(df[my_row, ])
}

A: Try with logical subsetting:
checkStudent <- function(x,y) x[x['name']==y,]

Test:
checkStudent(df,"A")
#  name hw0 hw1 hw2 hw3 hw4 hw5 hw6 quiz1 quiz2 quiz3 quiz4 quiz5 quiz6 term1 term2 term3 exam1 exam2 exam3 final
#1    A  20  13  30 100  50  60  30    11    15     0    14    25    25   100   100   100    97    97    80    97

data:
df <- structure(list(name = structure(1:17, .Label = c("A", "B", "C",
"D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P",
"Q"), class = "factor"), hw0 = c(20L, 20L, 20L, 20L, 20L, 20L,
20L, 20L, 20L, 20L, 20L, 20L, 20L, 20L, 20L, 20L, 20L), hw1 = c(13L,
14L, 14L, 12L, 14L, 13L, 14L, 0L, 14L, 14L, 14L, 14L, 14L, 11L,
12L, 13L, 14L), hw2 = c(30L, 30L, 28L, 30L, 30L, 30L, 26L, 0L,
15L, 29L, 29L, 30L, 30L, 0L, 28L, 0L, 30L), hw3 = c(100L, 100L,
100L, 100L, 90L, 100L, 85L, 85L, 0L, 80L, 97L, 100L, 100L, 95L,
97L, 90L, 100L), hw4 = c(50L, 50L, 50L, 50L, 30L, 48L, 40L, 50L,
10L, 35L, 50L, 45L, 50L, 20L, 0L, 45L, 45L), hw5 = c(60L, 60L,
60L, 0L, 0L, 0L, 42L, 0L, 48L, 0L, 60L, 0L, 60L, 0L, 40L, 0L,
0L), hw6 = c(30L, 36L, 36L, 33L, 0L, 36L, 33L, 0L, 30L, 36L,
36L, 36L, 36L, 0L, 0L, 20L, 36L), quiz1 = c(11L, 8L, 12L, 7L,
10L, 12L, 11L, 0L, 11L, 11L, 4L, 10L, 7L, 8L, 11L, 4L, 0L), quiz2 = c(15L,
11L, 4L, 15L, 15L, 15L, 15L, 15L, 0L, 13L, 7L, 6L, 15L, 14L,
10L, 13L, 12L), quiz3 = c(0L, 24L, 25L, 26L, 30L, 30L, 23L, 0L,
27L, 24L, 19L, 26L, 28L, 26L, 27L, 30L, 21L), quiz4 = c(14L,
8L, 13L, 12L, 15L, 15L, 11L, 0L, 11L, 12L, 11L, 8L, 14L, 7L,
11L, 10L, 11L), quiz5 = c(25L, 13L, 24L, 22L, 21L, 25L, 17L,
15L, 14L, 14L, 20L, 16L, 25L, 9L, 15L, 20L, 14L), quiz6 = c(25L,
9L, 14L, 0L, 15L, 23L, 16L, 10L, 16L, 0L, 15L, 7L, 25L, 0L, 15L,
17L, 17L), term1 = c(100L, 95L, 95L, 100L, 100L, 95L, 90L, 85L,
60L, 70L, 100L, 80L, 100L, 95L, 70L, 90L, 75L), term2 = c(100L,
100L, 100L, 100L, 100L, 100L, 100L, 90L, 90L, 0L, 100L, 0L, 100L,
0L, 0L, 100L, 90L), term3 = c(100L, 100L, 100L, 0L, 80L, 100L,
0L, 100L, 72L, 0L, 100L, 100L, 100L, 0L, 0L, 100L, 75L), exam1 = c(97L,
83L, 88L, 90L, 92L, 90L, 89L, 62L, 78L, 79L, 79L, 68L, 99L, 70L,
63L, 75L, 72L), exam2 = c(97L, 85L, 75L, 87L, 82L, 95L, 79L,
83L, 78L, 77L, 77L, 74L, 98L, 70L, 66L, 72L, 84L), exam3 = c(80L,
73L, 56L, 72L, 69L, 87L, 81L, 42L, 66L, 51L, 57L, 76L, 82L, 52L,
0L, 56L, 54L), final = c(97L, 73L, 77L, 81L, 79L, 90L, 78L, 75L,
81L, 78L, 81L, 76L, 99L, 61L, 0L, 64L, 63L)), .Names = c("name",
"hw0", "hw1", "hw2", "hw3", "hw4", "hw5", "hw6", "quiz1", "quiz2",
"quiz3", "quiz4", "quiz5", "quiz6", "term1", "term2", "term3",
"exam1", "exam2", "exam3", "final"), row.names = c(NA, -17L), class = "data.frame")


text:
Q: AJAX error function not throwing when db match not found UPDATED:
I have a code entry box that tried to find a match in a database. If a match is found, evrything works, but when a match is not found, I am having issues. See my code and results for a good and bad match below.
Here is my code:
function codeMatchTest() {
var discount;
if ($('#dbReturnString').val() == '') {
    alert("Please enter a discount code.");
} else {
$.ajax({
    type: "POST",
    url: "PROMO.svc/MatchCode",
    contentType: "application/json",
    async: false,
    dataType: "json",
    data: JSON.stringify({ codeInput: $('#dbReturnString').val().toLowerCase() }),
    success: function (json) {
        console.log(json.d);
        console.log(json.d[0].DISCOUNT);
        discount = JSON.parse(json.d);
        console.log(discount);
        console.log(json.d[0]["DISCOUNT"]);
        console.log(returnCustID());
        if (discount != null) {
            discount = discount[0].DISCOUNT;
        } else {
            alert("Not a valid code.");
            discount = 1;
        }
        //            alert("First: " + json.d[0]["DISCOUNT"] + " / Second: " + discount + " / Third: " + json.d);
        //            console.log("First: " + json.d[0]["DISCOUNT"] + " / Second: " + discount + " / Third: " + json.d);
        //            console.log(discount * 20);
    },
    error: function (json) {
        alert("There was an error with your request.");
    }
});
}
console.log(discount);
return discount;
}

Here are the console results for a good entry:
[{"DISCOUNT":0.5}]
undefined
[Object]
0: Object
DISCOUNT: 0.5
proto: Object
length: 1
proto: Array[0]
undefined
27382
0.5
Here are results for a bad, non-matching entry:
[]
undefined
[]
undefined
27382
Uncaught TypeError: Cannot read property 'DISCOUNT' of undefined
When a bad entry is made, "[]" is returned, which I think it just an empty json array, but it also says "undefined' for json.d. I am all sorts of confused now. I have tried many different ways to say if (json.d is empty, null, not = to a number, etc....) and nothing seems to work. Tring conditional such as if(discount[0].DISCOUNT >= 0) { run good code } doesn't work either, beucase the 'undefined' or '[]' result for some reason passes this condition. But it's empty, and not >= 0!!!
Any help is appreciated. This seems so simple and is causing me such trouble.

A: The error handler is only called if the server returns an HTTP error status (e.g., 404, 500, etc). You will either have to adjust the service to return an HTTP error status if there is no match in the service, or adjust your success handler to inspect the value of the result and treat an empty response appropriately.


text:
Q: Cannot modify a column which maps to a non key preserved table in pl/sql I am rewriting an old piece of code. I am getting following error when I've added following inside select a.* block
FROM USB.DFP_DATA A, BAS2_DFP_OBLIGOR_FACTS C
                    where a.as_of_date = v_date and a.DFPDEAL_TAX_ID_NBR=c.DFPDEAL_TAX_ID_NBR(+) and a.as_of_Date = c.as_of_date(+)

Could you please let me know how this error can be resolved? Thanks in advance for kind help!
--new code. user will enter INSTTABLE  and date and it should run and update fields.

IF INSTTABLE = 5 THEN
    V_BASEL_MIN :=0.08;
    V_BAS_RWA_RATE:=BAS_RWA_ADJ_RATE(V_DATE);

    UPDATE ( SELECT A.*,
                BAS2_RWA_CALC(BAS_CAPITAL_CALC_CD, NVL(CUR_BOOK_BAL,0), NVL(BAS_CAP_FACTOR_K,0), V_BASEL_MIN, V_BAS_RWA_RATE) AS V_BAS_EB_RWA,
                BAS2_RWA_CALC(BAS_CAPITAL_CALC_CD, NVL(CUR_BOOK_BAL,0), NVL(BAS_ICAAP_FACTOR_K,0), V_BASEL_MIN, V_BAS_RWA_RATE) AS V_BAS_ICAAP_EB_RWA,
                BAS2_RWA_CALC(BAS_CAPITAL_CALC_CD, NVL(AVG_BOOK_BAL,0), NVL(BAS_CAP_FACTOR_K,0), V_BASEL_MIN, V_BAS_RWA_RATE) AS V_BAS_AB_RWA,
                BAS2_RWA_CALC(BAS_CAPITAL_CALC_CD, NVL(BAS_UNUSED_COMMT,0), NVL(BAS_CAP_FACTOR_K_COMMT,0), V_BASEL_MIN, V_BAS_RWA_RATE) AS V_BAS_EB_RWA_COMMT,
                BAS2_RWA_CALC(BAS_CAPITAL_CALC_CD, NVL(BAS_UNUSED_COMMT,0), NVL(BAS_ICAAP_FACTOR_K_COMMT,0), V_BASEL_MIN, V_BAS_RWA_RATE) AS V_BAS_ICAAP_EB_RWA_COMMT,
                BAS2_RWA_CALC(BAS_CAPITAL_CALC_CD, NVL(BAS_UNUSED_COMMT,0), NVL(BAS_CAP_FACTOR_K_COMMT,0), V_BASEL_MIN, V_BAS_RWA_RATE) AS V_BAS_AB_RWA_COMMT,
                BAS2_RWA_CALC(BAS_CAPITAL_CALC_CD,NVL(BAS_PART_UNUSED_COMMT,0), NVL(BAS_CAP_FACTOR_K_COMMT,0), V_BASEL_MIN, V_BAS_RWA_RATE) AS V_BAS_PART_EB_RWA_COMMT,
                BAS2_RWA_CALC(BAS_CAPITAL_CALC_CD,NVL(BAS_PART_UNUSED_COMMT,0), NVL(BAS_ICAAP_FACTOR_K_COMMT,0), V_BASEL_MIN, V_BAS_RWA_RATE) AS V_BAS_ICAAP_EB_RWA_PART,
                BAS2_RWA_CALC(BAS_CAPITAL_CALC_CD,NVL(BAS_PART_UNUSED_COMMT,0), NVL(BAS_CAP_FACTOR_K_COMMT,0), V_BASEL_MIN, V_BAS_RWA_RATE) AS V_BAS_PART_AB_RWA_COMMT
                FROM USB.DFP_DATA A, BAS2_DFP_OBLIGOR_FACTS C
                    where a.as_of_date = v_date and a.DFPDEAL_TAX_ID_NBR=c.DFPDEAL_TAX_ID_NBR(+) and a.as_of_Date = c.as_of_date(+))
    SET
                BAS_EB_RWA = V_BAS_EB_RWA,
                BAS_ICAAP_EB_RWA = V_BAS_ICAAP_EB_RWA,
                BAS_AB_RWA = V_BAS_AB_RWA,
                BAS_EB_RWA_COMMT = V_BAS_EB_RWA_COMMT,
                BAS_ICAAP_EB_RWA_COMMT = V_BAS_ICAAP_EB_RWA_COMMT,
                BAS_AB_RWA_COMMT = V_BAS_AB_RWA_COMMT,
                BAS_PART_EB_RWA_COMMT = V_BAS_PART_EB_RWA_COMMT,
                BAS_ICAAP_EB_RWA_PART = V_BAS_ICAAP_EB_RWA_PART,
                BAS_PART_AB_RWA_COMMT = V_BAS_PART_AB_RWA_COMMT,
                BAS_EB_EXPECTED_LOSS = BAS2_EL_CALC(CUR_BOOK_BAL,bas_unused_commt,BAS_PD,BAS_LGD,BAS_LEQ,BAS_EAD,BAS_CAPITAL_CALC_CD),
                BAS_AB_EXPECTED_LOSS = BAS2_EL_CALC(AVG_BOOK_BAL,bas_unused_commt,BAS_PD,BAS_LGD,BAS_LEQ,BAS_EAD,BAS_CAPITAL_CALC_CD),
                BAS_EB_TOTAL_CAPITAL = round(BAS2_MGRL_CAPITAL(v_date, v_BAS_EB_RWA,v_BAS_EB_RWA_COMMT),2),
                BAS_AB_TOTAL_CAPITAL = round(BAS2_MGRL_CAPITAL(v_date, v_BAS_AB_RWA,v_BAS_AB_RWA_COMMT),2),
                BAS_PART_EB_EXPECTED_LOSS= BAS2_EL_CALC(0,bas_part_unused_commt,BAS_PD,BAS_LGD,BAS_LEQ,BAS_EAD,BAS_CAPITAL_CALC_CD),
                BAS_PART_AB_EXPECTED_LOSS= BAS2_EL_CALC(0,bas_part_unused_commt,BAS_PD,BAS_LGD,BAS_LEQ,BAS_EAD,BAS_CAPITAL_CALC_CD),
                BAS_PART_EB_TOTAL_CAPITAL= round(BAS2_MGRL_CAPITAL(v_date, 0,nvl(v_BAS_PART_EB_RWA_COMMT,0)),2),
                BAS_PART_AB_TOTAL_CAPITAL= round(BAS2_MGRL_CAPITAL(v_date, 0,nvl(v_BAS_PART_AB_RWA_COMMT,0)),2)
        WHERE
            (AS_OF_DATE = V_DATE);
END IF;

Expected-- It should run and update fields mentioned in SET block

A: Unfortunately, you will likely end up rewriting this with more modern MERGE syntax or doing the update in a different manner.
Your code is using an inline view as an updatable view, and there are some restrictions as to when you can update a view.
Oracle docs on views, (search for "Notes on updatable views")
A Look at Oracle Updatable Views


text:
Q: How does the area of $A+A$ compare to the area of $A-A$? The Minkowski sum of two sets $A$ and $B$ in the plane is defined as
$$A+B = \{ a + b \mid a \in A, b \in B \}.$$
The Minkowski difference $A-B$ is defined similarly.
For any convex set $A$, is it always true that $$|A-A| \ge |A+A|?$$
For example, if $A$ is a triangle, then $|A - A| = \frac{3}{2} |A + A|$. If $A$ is symmetric about a point, then $|A-A| = |A+A|$.

A: Yes.  By the Brunn–Minkowski inequality, $|A-A|^{1/2}\geq|A|^{1/2}+|-A|^{1/2}$, so $|A-A|\geq 4|A|$.  The hypotheses of this theorem do not include convexity, although they do include compactness.
On the other hand, under the assumption that $A$ is convex, $A+A = 2A$, and $|A+A|=4|A|$. Therefore $|A-A|\geq |A+A|$.


text:
Q: Sharedpreferences toggle state? I have a toggle that change the brightness in my device from manual to authomatic. It works but the state of button doesn't save.. There are two things i need right now.
1) Save the button state using sharedpreferences
2) Check when i open the application which kind of brightness there is in the phone.
This is the toggle in my onCreate:
autoBrightToggle = (ToggleButton)v.findViewById(R.id.luminosita);
        autoBrightToggle.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                if (autoBrightToggle.isChecked()) {
                    setAutoBrightness(true);
                } else {
                    setAutoBrightness(false);
                }
            }
        });

and the method:
void setAutoBrightness(boolean value) {
                if (value) {
                    Settings.System.putInt(getActivity().getContentResolver(), SCREEN_BRIGHTNESS_MODE, SCREEN_BRIGHTNESS_MODE_AUTOMATIC);
                } else {
                    Settings.System.putInt(getActivity().getContentResolver(), SCREEN_BRIGHTNESS_MODE, SCREEN_BRIGHTNESS_MODE_MANUAL);
                }
            }

i tryied in this way but not works:
sPrefdata  = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
        ToggleButton autoBrightToggle = (ToggleButton) findViewById(R.id.brightoggle); //Dichiaro il toggle
        boolean togglebrightness = sPrefdata.getBoolean("DATA", false);  a
            if (togglebrightness ) //if (tgpref) may be enough, not sure
            {

                autoBrightToggle .setChecked(true);
            }
                else
            {
                autoBrightToggle .setChecked(false);
            }

and so in the onClick
SharedPreferences sPref = getSharedPreferences(PREFS_NAME, 0);
            Editor editor = sPref.edit();
            editor.putBoolean("DATA", true); //or false
            editor.apply();

but doesn't work. Doesn't save the state and the method stops works. How can i solve? And how can i check which is the actual brightness?

A: Try the snippet given below, I've used it to save strings in shared preferences.
SharedPreferences.Editor ed = getSharedPreferences("DATA", 0).edit();
ed.putBoolean("DATA", true);
ed.commit();


text:
Q: How to implement routing in angular2 for user profile How to implement the user profile routing like this for username mark
mydomain.com/mark

and how to fetch the value of username 'mark' in the component?
Any sample code to implement this?
[Modified question with example]

A: app/app.routes.ts
import { provideRouter, RouterConfig } from '@angular/router';
import { HomeComponent }  from './home.component';
import { ContactCompnent }    from './contact.component';
import {UserComponent} from './user.component';
export const routes: RouterConfig = [
  { path: '', component: HomeComponent },
  { path: 'home', component: HomeComponent },
  { path: 'contact', component: ContactCompnent },
  { path: '<user>', component: UserComponent }
];
export const APP_ROUTER_PROVIDERS = [
  provideRouter(routes)
];

app.component.ts
import { Component } from '@angular/core';
import { ROUTER_DIRECTIVES } from '@angular/router';

@Component({
  selector: 'my-app',
  template: `

Component Router

      Home
      Contact
       <a [routerLink]="['/<user>']">user

    <router-outlet></router-outlet>
  `,
  directives: [ROUTER_DIRECTIVES]
})

export class AppComponent { }

Check live example here,
https://plnkr.co/edit/ySW9sYyV8Ou7tQB7biyx?p=preview


text:
Q: how to add Authorization header by using open api swagger doc I am trying to add Authorization header in the api call and could you please tell how to configure by using open api swagger doc.
code :
@Bean
public OpenAPI customOpenAPI(@Value("${application-description}") String appDesciption, @Value("${application-version}") String appVersion) {
    return new OpenAPI()
            .info(new Info()
                    .title("Access Management APIs")
                    .version("1.0")
                    .description("Access Management APIs for tp db")
                    .termsOfService("http://swagger.io/terms/")
                    .license(new License().name("Apache 2.0").url("http://springdoc.org")));
}

controller class:
@PutMapping(value = "/{aNumber}",
            produces = APPLICATION_JSON_VALUE)
public ResponseEntity<Object> updateSubsidyAward(@Valid @RequestBody UpdateAwardDetailsRequest awardUpdateRequest,
                                                 @PathVariable("aNumber") Long aNumber)
{

}

A: OpenApiConfig
package com.user.demoapp.config;

import io.swagger.v3.oas.models.Components;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Contact;
import io.swagger.v3.oas.models.info.Info;
import io.swagger.v3.oas.models.info.License;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class OpenApiConfig {

    @Bean
    public OpenAPI customOpenAPI() {
        return new OpenAPI()
                .components(new Components())
                .info(new Info()
                        .title("App_name")
                        .description("App_description")
                        .version("0.0.1")
                        .termsOfService("http://swagger.io/terms/")
                        .contact(new Contact().name("contact_name").email("contact_email_address"))
                        .license(new License().name("Apache 2.0").url("http://springdoc.org"))

                );
    }
}

Controller class
@CrossOrigin(allowCredentials = "true", allowedHeaders = "*")
@Tag(name = "api_title", description = "api_description")
@RestController
public class TestController {
    @Autowired
    private TestService testService;

    @Operation(summary = "api_summary ", description = "api_description", tags = { "api_Tag" })
    @PostMapping(path = "/test-api")
    public ResponseEntity<ApiResponseDTO> addTest(@RequestBody List<testDTO> testModel) {
        return testService.addtest(testModel);
    }
}

I hope you found what you are looking for :)

A: Add components(new Components()
.addSecuritySchemes())
@Bean
public OpenAPI customOpenAPI(@Value("${application-description}") String appDesciption, @Value("${application-version}") String appVersion) {

    final String securitySchemeName = "basicAuth";

        return new OpenAPI()
                .components(new Components()
                        .addSecuritySchemes(securitySchemeName, new SecurityScheme()
                                .type(SecurityScheme.Type.HTTP)
                                .scheme("basic"))
                )
                .info(new Info()
                    .title("Access Management APIs")
                    .version("1.0")
                    .description("Access Management APIs for tp db")
                    .termsOfService("http://swagger.io/terms/")
                    .license(new License().name("Apache 2.0").url("http://springdoc.org")));
}


text:
Q: Simplifying $\sqrt {11 - 4 \sqrt 7} - \sqrt {8 - 2 \sqrt 7}$
$$\sqrt {11 - 4 \sqrt 7} - \sqrt {8 - 2 \sqrt 7} = a$$

I'm having trouble solving this equation. I've tried squaring both sides and got this
$$11 - 4\sqrt{7} - 2 \sqrt{(11 - 4\sqrt{7})(8 - 2\sqrt{7})} + 8 - 2\sqrt{7} = a^2$$
after simplifying
$$19 - 6\sqrt{7} - 2 \sqrt{(11 - 4\sqrt{7})(8 - 2\sqrt{7})} = a^2$$
and that's where I got stuck.

A: Hint:
$11=(\sqrt7)^2+2^2$  and $\sqrt7-2>0$
$8=(\sqrt7)^2+1^2$ and  $\sqrt7-1>0$
Finally
$$\sqrt{a^2+b^2-2ab}=|a-b|=a-b\text{  if } a-b\ge0$$

A: There is a formula to simplify nested radicals like that
$$\sqrt{a-\sqrt{b}}=\sqrt{\frac{a+\sqrt{a^2-b}}{2}}-\sqrt{\frac{a-\sqrt{a^2-b}}{2}}$$
It is effective only if $(a^2-b)$ is a perfect square. In your example both of them have this property
$$\sqrt {11 - 4 \sqrt 7} - \sqrt {8 - 2 \sqrt 7} = a$$
$$\sqrt {11 -  \sqrt {112}} - \sqrt {8 -\sqrt {28}} = a$$
$$\sqrt {11 -  \sqrt {112}} =\sqrt{\frac{11+\sqrt{121-112}}{2}}-\sqrt{\frac{11-\sqrt{121-112}}{2}}=\sqrt{\frac{11+3}{2}}-\sqrt{\frac{11-3}{2}}=$$
$$=\sqrt 7-2$$
$$\sqrt {8 -\sqrt {28}} =\sqrt{\frac{8+6}{2}}-\sqrt{\frac{8-6}{2}}=\sqrt 7-1$$
so finally
$$\sqrt 7-2-(\sqrt 7-1)=-1$$

There is a similar formula for the sum
$$\sqrt{a+\sqrt{b}}=\sqrt{\frac{a+\sqrt{a^2-b}}{2}}+\sqrt{\frac{a-\sqrt{a^2-b}}{2}}$$


text:
Q: Button Navigation with React Router Header: I am trying to navigate to a new page from my Material UI button using the onClick method. I am confused about what to write in my handleClickSignIn function.
Code snippet from my Header.tsx file:
const HatsPage = () => (

      HATS PAGEHH

)

function handleClickSignIn() {
  <Route component= {HatsPage}></Route>
}

const Header = () => (

'

      Instaride

      <Button onClick= {handleClickSignIn}> Sign In</Button>
      <Button> Contact</Button>

);

This doesn't work and I get errors like:

expected assignment or function but got expression instead

A: The problem you're having it that you're generating a Route component every time the Sign In button is clicked.
Instead, you should use a Link component like so:
const Header = () => (

'

    Instaride

    <Link to={"/login"}> Sign In</Link>
    <Button> Contact</Button>

This will create a link component that, when clicked, will direct to the /login URL. To then render components at that URL you'll also need to define a Route. You've already done this with but need to define the path like so:
<Route path={"/login"} component={HatsPage} />

And then note that this Route, your Header component and any Link's need to be nested within an instance of a BrowserRouter.


text:
Q: Is there way to get System information (System Notes or History of changes) for the item line in a sales order via SuiteScript? I'm writing simple User Event script (using beforeSave entry in my case) for the Sales Order which reads every item line in it and changes some values in the item line according to the given circumstances.
The problem I've encountered:
If some field of the item line in the Sales Order was changed by the Administrator (role) just now or some time ago, this field should not be changed by my script. Via N/runtime module I can get current user role and verify that he changed something just now, but that doesn't help if the change has been done before the current edit "session".
How can I know, if any administrator changed something?
Can I get some history/log/system info for each item line in the sales order?
Thanks in advance

A: If you need to prevent your code from changing values on a Sublist (in your case the Item list on a Sales Order) only when an Admin was the one who initially set the value, then I would recommend using a custom record where you could store a list of fields or data per transaction that were changed by an admin. For example, on create of a Sales Order, your beforeSubmit user event would create this data tracking custom record and set some field to tie it one-to-one to your sales order (meaning you have 1 custom record for each sales order, but never more than 1, you could even store the internal ID of that custom record on the sales order in a hidden field so you dont have to look it up in future edits). In your custom record you could use a long text field (has a limit of 1 million characters I believe) to store JSON data representing fields or values that were set/changed by an Admin. On each edit, your user event code should check the role of the user interacting with the sales order and read/update the custom record accordingly. This would work on create, edit, copy, whatever (inline edits are not possible against an item list on a sales order so no need to account for those). This would require a decent amount of code in order to do the lookup and checking each time, but custom records are super fast and use very little governance so your users shouldn't see any notable performance loss. I recognize this is far from an ideal solution, but its a lot more feasible than the 'always helpful' NetSuite 'support' solution. Good luck, and hope this helped!

A: Todd's solution will work, but a bit of overkill to get all the field ids and store it in a custom record since you just wanted to know if there is a change on certain field.
Having a client script that is ticking a check box running on Field Changed would be much simpler solution. The client script will detect if it is the column or field(if needed) that you are tracking. If it is the field, then simply set the checkbox to 'T'. Then on your scheduled script you simply check this checkbox before updating the record.


text:
Q: How can i accept and run user's code securely on my web app? I am working on a django based web app that takes python file as input which contains some function, then in backend i have some lists that are passed as parameters through the user's function,which will generate a single value output.The result generated will be used for some further computation.
Here is how the function inside the user's file look like :
def somefunctionname(list):

    ''' some computation performed on list'''

    return float value

At present the approach that i am using is taking user's file as normal file input. Then in my views.py i am executing the file as module and passing the parameters with eval function. Snippet is given below.
Here modulename is the python file name that i had taken from user and importing as module
exec("import "+modulename)

result = eval(f"{modulename}.{somefunctionname}(arguments)")

Which is working absolutely fine. But i know this is not the secured approach.
My question , Is there any other way through which i can run users file securely as the method that i am using is not secure ? I know the proposed solutions can't be full proof but what are the other ways in which i can run this (like if it can be solved with dockerization then what will be the approach or some external tools that i can use with API )?
Or if possible can somebody tell me how can i simply sandbox this or any tutorial that can help me..?
Any reference or resource will be helpful.

A: It is an important question. In python sandboxing is not trivial.
It is one of the few cases where the question which version of python interpreter you are using. For example, Jyton generates Java bytecode, and JVM has its own mechanism to run code securely.
For CPython, the default interpreter, originally there were some attempts to make a restricted execution mode, that were abandoned long time ago.
Currently, there is that unofficial project, RestrictedPython that might give you what you need. It is not a full sandbox, i.e. will not give you restricted filesystem access or something, but for you needs it may be just enough.
Basically the guys there just rewrote the python compilation in a more restricted way.
What it allows to do is to compile a piece of code and then execute, all in a restricted mode. For example:
from RestrictedPython import safe_builtins, compile_restricted

source_code = """
print('Hello world, but secure')
"""

byte_code = compile_restricted(
    source_code,
    filename='<string>',
    mode='exec'
)
exec(byte_code, {__builtins__ = safe_builtins})

>>> Hello world, but secure

Running with builtins = safe_builtins disables the dangerous functions like open file, import or whatever. There are also other variations of builtins and other options, take some time to read the docs, they are pretty good.
EDIT:
Here is an example for you use case
from RestrictedPython import safe_builtins, compile_restricted
from RestrictedPython.Eval import default_guarded_getitem

def execute_user_code(user_code, user_func, *args, **kwargs):
    """ Executed user code in restricted env
        Args:
            user_code(str) - String containing the unsafe code
            user_func(str) - Function inside user_code to execute and return value
            *args, **kwargs - arguments passed to the user function
        Return:
            Return value of the user_func
    """

    def _apply(f, *a, **kw):
        return f(*a, **kw)

    try:
        # This is the variables we allow user code to see. @result will contain return value.
        restricted_locals = {
            "result": None,
            "args": args,
            "kwargs": kwargs,
        }

        # If you want the user to be able to use some of your functions inside his code,
        # you should add this function to this dictionary.
        # By default many standard actions are disabled. Here I add _apply_ to be able to access
        # args and kwargs and _getitem_ to be able to use arrays. Just think before you add
        # something else. I am not saying you shouldn't do it. You should understand what you
        # are doing thats all.
        restricted_globals = {
            "__builtins__": safe_builtins,
            "_getitem_": default_guarded_getitem,
            "_apply_": _apply,
        }

        # Add another line to user code that executes @user_func
        user_code += "\nresult = {0}(*args, **kwargs)".format(user_func)

        # Compile the user code
        byte_code = compile_restricted(user_code, filename="<user_code>", mode="exec")

        # Run it
        exec(byte_code, restricted_globals, restricted_locals)

        # User code has modified result inside restricted_locals. Return it.
        return restricted_locals["result"]

    except SyntaxError as e:
        # Do whaever you want if the user has code that does not compile
        raise
    except Exception as e:
        # The code did something that is not allowed. Add some nasty punishment to the user here.
        raise

Now you have a function execute_user_code, that receives some unsafe code as a string, a name of a function from this code, arguments, and returns the return value of the function with the given arguments.
Here is a very stupid example of some user code:
example = """
def test(x, name="Johny"):
    return name + " likes " + str(x*x)
"""
# Lets see how this works
print(execute_user_code(example, "test", 5))
# Result: Johny likes 25

But here is what happens when the user code tries to do something unsafe:
malicious_example = """
import sys
print("Now I have the access to your system, muhahahaha")
"""
# Lets see how this works
print(execute_user_code(malicious_example, "test", 5))
# Result - evil plan failed:
#    Traceback (most recent call last):
#  File "restr.py", line 69, in <module>
#    print(execute_user_code(malitious_example, "test", 5))
#  File "restr.py", line 45, in execute_user_code
#    exec(byte_code, restricted_globals, restricted_locals)
#  File "<user_code>", line 2, in <module>
#ImportError: __import__ not found

Possible extension:
Pay attention that the user code is compiled on each call to the function. However, it is possible that you would like to compile the user code once, then execute it with different parameters. So all you have to do is to save the byte_code somewhere, then to call exec with a different set of restricted_locals each time.
EDIT2:
If you want to use import, you can write your own import function that allows to use only modules that you consider safe. Example:
def _import(name, globals=None, locals=None, fromlist=(), level=0):
    safe_modules = ["math"]
    if name in safe_modules:
       globals[name] = __import__(name, globals, locals, fromlist, level)
    else:
        raise Exception("Don't you even think about it {0}".format(name))

safe_builtins['__import__'] = _import # Must be a part of builtins
restricted_globals = {
    "__builtins__": safe_builtins,
    "_getitem_": default_guarded_getitem,
    "_apply_": _apply,
}

....
i_example = """
import math
def myceil(x):
    return math.ceil(x)
"""
print(execute_user_code(i_example, "myceil", 1.5))

Note that this sample import function is VERY primitive, it will not work with stuff like from x import y. You can look here for a more complex implementation.
EDIT3
Note, that lots of python built in functionality is not available out of the box in RestrictedPython, it does not mean it is not available at all. You may need to implement some function for it to become available.
Even some obvious things like sum or += operator are not obvious in the restricted environment.
For example, the for loop uses _getiter_ function that you must implement and provide yourself (in globals). Since you want to avoid infinite loops, you may want to put some limits on the number of iterations allowed. Here is a sample implementation that limits number of iterations to 100:
MAX_ITER_LEN = 100

class MaxCountIter:
    def __init__(self, dataset, max_count):
        self.i = iter(dataset)
        self.left = max_count

    def __iter__(self):
        return self

    def __next__(self):
        if self.left > 0:
            self.left -= 1
            return next(self.i)
        else:
            raise StopIteration()

def _getiter(ob):
    return MaxCountIter(ob, MAX_ITER_LEN)

....

restricted_globals = {
    "_getiter_": _getiter,

....

for_ex = """
def sum(x):
    y = 0
    for i in range(x):
        y = y + i
    return y
"""

print(execute_user_code(for_ex, "sum", 6))

If you don't want to limit loop count, just use identity function as _getiter_:
restricted_globals = {
    "_getiter_": labmda x: x,

Note that simply limiting the loop count does not guarantee security. First, loops can be nested. Second, you cannot limit the execution count of a while loop. To make it secure, you have to execute unsafe code under some timeout.
Please take a moment to read the docs.
Note that not everything is documented (although many things are). You have to learn to read the project's source code for more advanced things. Best way to learn is to try and run some code, and to see what kind function is missing, then to see the source code of the project to understand how to implement it.
EDIT4
There is still another problem - restricted code may have infinite loops. To avoid it, some kind of timeout is required on the code.
Unfortunately, since you are using django, that is multi threaded unless you explicitly specify otherwise, simple trick for timeouts using signeals will not work here, you have to use multiprocessing.
Easiest way in my opinion - use this library. Simply add a decorator to execute_user_code so it will look like this:
@timeout_decorator.timeout(5, use_signals=False)
def execute_user_code(user_code, user_func, *args, **kwargs):

And you are done. The code will never run more than 5 seconds.
Pay attention to use_signals=False, without this it may have some unexpected behavior in django.
Also note that this is relatively heavy on resources (and I don't really see a way to overcome this). I mean not really crazy heavy, but it is an extra process spawn. You should hold that in mind in your web server configuration - the api which allows to execute arbitrary user code is more vulnerable to ddos.

A: For sure with docker you can sandbox the execution if you are careful. You can restrict CPU cycles, max memory, close all network ports, run as a user with read only access to the file system and all).
Still,this would be extremely complex to get it right I think. For me you shall not allow a client to execute arbitrar code like that.
I would be to check if a production/solution isn't already done and use that. I was thinking that some sites allow you to submit some code (python, java, whatever) that is executed on the server.


text:
Q: Relationship between a sheaf and the sheaf we get after applying the coherator. Let $X$ be a quasi-compact and
quasi-separated scheme. Now, consider the forgetful functor $i$ from the category of quasi-coherant sheaves on $X$ to category of $O_X$-modules.
$$i: Qcoh(X) \hookrightarrow Mod(X)$$
The right adjoint to this functor is called the coherator.
$$Q :Mod(X) \rightarrow Qcoh(X)$$
My question is if $F \in Mod(X)$ be a sheaf, then is $Q(F)$ is a subsheaf of $F$ in the category $Mod(X)$? More precisely is it true that,
   $$i\circ Q(F)\subset F $$
If not, can it be true with some additional conditions ?
Basically, I am trying to understand the connection between $F$ and $Q(F)$.
Thanks in advance!


text:
Q: Php Syntax error. Unsure where beginning of php
<?php
echo "Began";
$Title=$_GET["Title"];
$Des=$_GET["description"];
$Url=$_GET["url"];
$Date=$_GET["time"];
echo "4 lines";
$Loc=$_GET["location"];
$Num=$_GET["num"];
$info01=array($Title,$Des,$Url,$Date);
$info02=array("<title>","<description>","<date>","<url>");
$info03=array("</title>","</description>","</date>","</url>");

     $File = .$Loc."rss".$Num.".xml";
     $Handle = fopen($File, 'w');

     $Data = "<rss>\n";
     fwrite($Handle, $Data);
        for ($i=0; $i <= 3; $i++){
            echo $i;
             $Data = $info02[$i].$info01[$i].$info03[$i]."\n";
             fwrite($Handle, $Data);
        }

  $Data = "</rss>\n";
 fwrite($Handle, $Data);
 echo "Data Written";
 fclose($Handle);

?>

<form action="check.php" method="get">
Title <input type="text" name="Title">

Description <input type="text" name="description">

URL <input type="text" name="url">

DATE <input type="text" name="time">

Rss location <input type="text" name="location">

Rss Number <input type="text" name="num">
 <input type="submit">

Can any one help me with this?
I am getting an error, some where whether syntax or not, I do not know.
I looked at the code for some time an haven't seen why there are errors.
I think it could be syntax. thats as far as I got.
thank you in advances

A: Try using , You have added . infront of $Loc variable
 $File = $Loc."rss".$Num.".xml";

instead of
$File = .$Loc."rss".$Num.".xml";

A: Do not use "." (dot) before your variable ($Loc)
$Loc."rss".$Num.".xml";

A: $File = .$Loc."rss".$Num.".xml"; error may be with this line remove that . infront of $Loc

A: Remove first . from this
$File = .$Loc."rss".$Num.".xml";

to
$File = $Loc."rss".$Num.".xml";

A: Maybe it is the line
$File = .$Loc."rss".$Num.".xml";

I did not cross-check, but I think the dot right before $Loc should not be there.
Try this:
$File = $Loc."rss".$Num.".xml";


text:
Q: retrofit expected begin_array but was begin_object at line 1 column 2 path $ I'm learning retrofit following a youtube video
but right now I'm stuck. It shows me an error "retrofit expected begin_array but was begin_object at line 1 column 2 path $"
I'm trying to get json data from this site.
http://servicio-monkydevs.rhcloud.com/clientes/
Here is my code
MainActivity.java
resultadoTextView = (TextView) findViewById(R.id.Resultado);
    Retrofit restAdapter = new Retrofit.Builder()
            .baseUrl("http://servicio-monkydevs.rhcloud.com")
            .addConverterFactory(GsonConverterFactory.create())
            .build();

    ClienteService service = restAdapter.create(ClienteService.class);
    Call<Cliente> call = service.getCliente();
    call.enqueue(new Callback<Cliente>() {
        @Override
        public void onResponse(Call<Cliente> call, Response<Cliente> response) {
            if(response.isSuccessful()) {
                resultadoTextView.setText(call.toString());
            }else{
                resultadoTextView.setText("algo paso");
            }
        }

        @Override
        public void onFailure(Call<Cliente> call, Throwable t) {
            resultadoTextView.setText(t.getMessage());
        }
    });

ClientService.java
public interface ClienteService {
  @GET("/clientes")
  Call<Cliente> getCliente();
}

Client.java
public class Cliente {
private int id;
private String name;
private String username;
private String email;
private String phone;
private String website;
private String photo;

public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getUsername() {
    return username;
}

public void setUsername(String username) {
    this.username = username;
}

public String getEmail() {
    return email;
}

public void setEmail(String email) {
    this.email = email;
}

public String getPhone() {
    return phone;
}

public void setPhone(String phone) {
    this.phone = phone;
}

public String getWebsite() {
    return website;
}

public void setWebsite(String website) {
    this.website = website;
}

public String getPhoto() {
    return photo;
}

public void setPhoto(String photo) {
    this.photo = photo;
}

@Override
public String toString() {
    return "Cliente{" +
            "id=" + id +
            ", name='" + name + '\'' +
            ", username='" + username + '\'' +
            ", email='" + email + '\'' +
            ", phone='" + phone + '\'' +
            ", website='" + website + '\'' +
            ", photo='" + photo + '\'' +
            '}';
}}

What am I doing wrong?
UPDATE
I made these changes
public class Cliente {
@SerializedName("id")
private int id;
@SerializedName("name")
private String name;
@SerializedName("username")
private String username;
@SerializedName("email")
private String email;
@SerializedName("phone")
private String phone;
@SerializedName("website")
private String website;
@SerializedName("photo")
private String photo;
...

And this in the interface
public interface ClienteService {
  @GET("/clientes")
  Call<List<Cliente>> getCliente();
}

And this in the MainActivity as you say
 Call<List<Cliente>> call = service.getCliente();
    call.enqueue(new Callback<List<Cliente>>() {
        @Override
        public void onResponse(Call<List<Cliente>> call, Response<List<Cliente>> response) {
            if(response.isSuccessful()) {
                resultadoTextView.setText(call.toString());
            }else{
                resultadoTextView.setText("algo paso");
            }
        }

        @Override
        public void onFailure(Call<List<Cliente>> call, Throwable t) {
            resultadoTextView.setText(t.getMessage());
        }
    });

But now it shows me this error:
"retrofit2.executorCallAdapterFactory$ExecutorCallbackCall@6a3dd44"
It shows me this in this line
...
if(response.isSuccessful()) {
            resultadoTextView.setText(call.toString());  <-- HERE
        }else{
...

A: As you Can see the Given REST API url returning an array of Object , that is ArrayList but in your retrofit api service the return type is Only Cliente.
So change your ClientService.java to the below
public interface ClienteService {
 @GET("/clientes")
 Call<List<Cliente>> getCliente();
}

And change the Call.enque() method to this
Call<List<Cliente>> call = service.getCliente();
    call.enqueue(new Callback<List<Cliente>>() {
        @Override
        public void onResponse(Call<List<Cliente>> call, Response<List<Cliente>>  response) {
            if(response.isSuccessful()) {
               // your code to get data from the list
            }else{

            }
        }

        @Override
        public void onFailure(Call<List<Cliente>> call, Throwable t) {
            resultadoTextView.setText(t.getMessage());
        }
    });

A: *

*the firstly you need to change Call<Client> to Call<List<Client>> because response return list object client.

*the secondly prepare that Class Client implements Serializable to support parsing

I think that done


text:
Q: How to contain floats inside a DIV I have two inline elements within a div. One element is floated to the left and the other to the right. I have used absolute positioning to place the block containing inline elements at the bottom of a DIV.
Problem: The element floating to the right skews out of its container. How can I fix this so that it stays within its container? Here is the CodePen.
HTML

Bryce Canyon A Stunning U.S Travel Destination

        10 days ago
        Motivation

SCSS
.posts__post{
    height: 400px;
    width: 310px;
    margin: 40px auto;
    //margin-bottom: 40px;
    position: relative;
    text-align: left;
    background-color: white;
    border-radius: 5px 5px 5px 5px;
    box-shadow: 0px 0px 5px 0px rgba(0,0,0,0.15);

   .posts__post--preview img{
      width: 100%;
      height: auto;
      border-radius: 5px 5px 0px 0px;
    }

  .posts__post--tag{
      font-size: em(15);
      font-weight: bold;
      color: $light-grey;
   }

  .posts__post--meta{
    color: $light-grey;
    position: absolute;
    bottom: 25px;
    left: 0;
    display: block;
   }

  .posts__post--title, .posts__post--tag, .posts__post--meta{
   margin: 0 25px;
   display: inline-block;
   text-docoration: none;
  }

 .posts__post__timestamp{
  float:left;
  }

 .posts__post__tag{
  float:right;
 }
}

A: This is because of margin that you have given to posts__post--meta, instead of using margin use padding, and box-sizing:border-box
.posts__post--meta{
    padding: 0 25px;
    display: inline-block;
    text-docoration: none;
    width: 100%;
    box-sizing: border-box;
}

For more info about box-sizing

A: .posts__post--meta{
    color: $light-grey;
    position: absolute;
    bottom: 25px;
    left: 0;
    right:0; //add this
    display: block;
   }

A: Just to add a note I have noticed while I'm working on a php application. Using float within a
 is overridding the whole div. to clarify my point. if you have
 and within it you have
 and it has a float, it override the "page-wrapper" and stand alone. don't use it unless you really need it. Thanks


text:
Q: Detectar valor document.getElementById() dentro de un array Tengo una galería de imágenes donde intento que cuando el usuario haga click en cada una de ellas se muestre esa misma imagen en grande. Lo logro hacer con su correspondiente "id" y con javascript.
Ejemplo:

Hasta aquí bien, pero claro si son 20 imágenes e intento hacerlo en un array al intentar coger el valor dentro de [b]document.getElementById()[/b] no lo reconoce

texto en negrita
¿Cómo podría hacer que reconozca el valor del id dentro del array para luego devolverlo o llamarlo al hacer click en cada imagen?

A: Puedes hacerlo agregándoles una clase a dichas imágenes, como por ejemplo la clase imagen.

Aqui se mostrara la imagen cuando hagas clic

Básicamente tienes tu listado de imágenes y un lugar en donde mostrar la imagen como resultado, creamos un evento que escucha todo el documento y detecta el evento click en un objeto, pero si ese evento no coincide con la clase imagen entonces automáticamente abandona el evento, de lo contrario le asigna su atributo src que contiene la url de la imagen a la imagen más grande (resultado).

A: No te lo reconoce por que el id debe de estar entre comillas ....getElementById('elementID'). Intenta utilizando el caracter backtick (`) que significaría que estas utilizando template strings. Así :

const img = `document.getElementById('${myArray[i]}')`


text:
Q: Property variables cannot be read? In the header, I declare my
NSString *name;

Variable. Then I make it a property with
@property (nonatomic,retain) NSString *name;

And I synthesize it in the implementation
@synthesize name;

And, immediately, give it a value in the init method:
name = @"HELLO";

Later I add a child to my scene. This child, later, will try to access this property. It goes like
Battle *battleScene = (Battle*)self.parent;
NSLog(@"%@",battleScene.name);

But I get "null". Why is that?

A: Does the Battle class define name? Also, are you creating an instance of battleScene before or after you have set name = @"HELLO";?
For Example
@interface Battle : NSObject
{
    NSString *name;
}
@property (nonatomic,retain) NSString *name;
@end

A: One reason for this may be that self.parent is nil. This happens if you try to run the code in the init method of the child node.
CCNode* child = [[[CCNode alloc] init] autorelease];
// at this point the init method is run but parent of the child is still nil …
…

[self addChild:child];
// now the parent of the child is set, after it's been added to the hierarchy

If you do run this in the init method, move that code to the onEnter method instead:
-(id) init
{
     // self.parent == nil !!
}

-(void) onEnter
{
    // self.parent is guaranteed to be non-nil in onEnter
    Battle *battleScene = (Battle*)self.parent;
    NSLog(@"%@",battleScene.name);
}

A: name = @"HELLO";

does not set the property.
self.name = [NSString stringWithString:@"HELLO"];

will set the property for you.  It will retain the object for you and this is a good way to assign it because [NSString stringWithString:@"HELLO"] is autoreleased.  Using self.name = will release your previous name and retain the one you are setting.
You get this behavior by including retain in the property declaration


text:
Q: Build dashboard Is there a build dashboard somewhere for the different carbon/wso2 releases?
I just checked out the 4.0.3 tag of carbon ( https://svn.wso2.org/repos/wso2/carbon/platform/tags/4.0.3)
and I was assuming tags are stable. But the build failed with the following error
The project org.wso2.carbon:SecVerifier:4.0.0
(/wso2/4.0.3/products/integration/security-verifier/pom.xml) has 1 error
[ERROR]     Non-resolvable parent POM: Failure to find
org.wso2.carbon:integration:pom:4.0.0 in http://people.apache.org/repo/m2-incubating
repository was cached in the local repository, resolution will not be reattempted until
the update interval of apache-incubating has elapsed or updates are forced and
'parent.relativePath' points at wrong local POM @ line 22, column 13 -> [Help 2]

Are these tags stable? I am using Maven 3.0.5 and Java 1.6

A: WSO2 build status dashboard can be found with continuous build too, Bamboo.
If you are trying to build something on a released branch, the easiest would be to build only that component, as for released versions, we have published maven repos with build artifacts.