text:
Q: java.lang.ClassNotFoundException: DataSource in Glassfish I'm getting a weird problem in GlassFish 2.1 - I'm a beginner with this container and I'm having trouble pinning this down.
I have a new install of GlassFish 2.1 with a JDBC connection pool defined called testDerbyPool. I then have a resource defined called jdbc/testDerbyPool pointing at that pool. The resource type is javax.sql.DataSource and I can successfully ping the pool.
I then have a single class in a webapp with this declaration:
@Resource(name="jdbc/testDerbyPool")
private javax.sql.DataSource source;

This declaration in my web.xml:
  <resource-ref>
    <res-ref-name>jdbc/testDerbyPool</res-ref-name>
    <res-type>javax.sql.DataSource</res-type>
    <res-auth>Container</res-auth>
  </resource-ref>

When I try to deploy the application, I get this error:
[#|2009-09-09T21:40:47.582+0100|SEVERE|sun-appserver9.1|javax.enterprise.system.container.web|_ThreadID=24;_ThreadName=Thread-32;_RequestID=1ca4ab80-ae39-4920-be18-f535b025bb51;|WebModule[/cptest1]PWC1275: Exception sending context initialized event to listener instance of class com.sun.faces.config.ConfigureListener

and a huge stack trace, starting:
java.lang.NoClassDefFoundError: LDataSource;
at java.lang.Class.getDeclaredFields0(Native Method)
at java.lang.Class.privateGetDeclaredFields(Class.java:2291)

with root cause:
Caused by: java.lang.ClassNotFoundException: DataSource
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1498)
at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:320)

I don't understand how DataSource can be 'not found'! Any ideas?

A: Next time I went back after asking the question, I noticed a build error in Eclipse, somehow gotten an extra JRE in the path marked 'unbound'. Looking around my system, I got a JVM point release update automatically between starting Eclipse up and doing the build/deploy.
Anyway, removed it, tried again, worked.
So check for build errors and build path problems if you see this problem.


text:
Q: Does there exist a $C>0$ such that $\|D(f^{-n})(f^{k}(q))\|\leq C\lambda^{n}$ for all $k\in\mathbb{Z}$ and $n\in\mathbb{N}$? Let $f\colon \mathbb{R}^{2}\to\mathbb{R}^{2}$ be a $C^{1}$-diffeomorphism. Let $\|\cdot\|$ denote the operator norm. Let $p$ and $q$ be such that $$\lim_{n\to\infty}f^{-n}(q)=\lim_{n\to\infty}f^{n}(q)=p.$$ Also suppose that there exists a $0<\lambda<1$ such that $$\|D(f^{-1})(p)\|<\lambda,\qquad\|Df(p)\|<\lambda.$$
Does there exist a $C>0$ such that $\|D(f^{-n})(f^{k}(q))\|\leq C\lambda^{n}$ and $\|D(f^{n})(f^{k}(q))\|\leq C\lambda^{n}$ for all $k\in\mathbb{Z}$ and $n\in\mathbb{N}$?
I have shown that there exists an integer $N\in\mathbb{N}$ such that $$\|D(f^{-1})(f^{k}(q))\|<\lambda,\qquad\|Df(f^{k}(q))\|<\lambda$$ for all $k\in\mathbb{Z}$ with $|k|\geq N$. Also, by the chainrule we have $$\|D(f^{-n})(f^{k}(q))\|\leq\prod_{i=1}^{n}\|D(f^{-1})(f^{k-i}(q))\|$$ and a similar estimation for $\|D(f^{n})(f^{k}(q))\|$.
Is my reasoning right? And how do I finish the proof?

redpajama_set_name: RedPajamaStackExchange


text:
Q: obtaining result of a nested loop into a list of dataframes many thanks for the comments and edits, I will try my best to provide a reproducible example.
list_1 is a data frame with 15 columns and 33000 rows.
accession <- rownames(list_1)
accession2 <-sample(accession)

list <- a   b   c   d
    g_1 1   0   0   1
    g_2 0   0   1   1
    g_3 0   1   0   1
    g_4 1   1   1   0
    g_5 0   1   0   0
    g_6 1   0   0   1
    g_7 1   1   0   0
    g_8 1   0   1   0
    g_9 1   0   1   0
   g_10 0   1   1   0

I want to compare each column to the other column in the data frame and find the row.names that are common between them, this will be done by the function
as.data.frame(rownames(get_intersect_members(list_1, (i), (j))))
 I want to save the result of all comparisons in out which has each comparison result stored in a list or as a column of a dataframe.
ideally the output will look like this -
out <- a_vs_b   a_vs_c  a_vs_d  b_vs_c  b_vs_d  c_vs_d
       g_7      g_8     g_1     g_10    g_3     g_2
       g_9      g_6

I have tried this -
out<- vector("list", 225L)
for (k in 1:225){
for(i in accession) {
for (j in accession2){
m= as.data.frame(rownames(get_intersect_members(list_1, (i), (j))))
}
 }
out[[k]]<-m
   }

I can successfully run the inner for loops but I am unable to save result of each comparison.
As mentioned by Aaron my code overwrites variable m and it save the value of last comparison instead of saving each result separately.


text:
Q: How to resize the clip-path background in a responsive way vertically? I'm having some troubles to do a responsive background using the css clip-path property. In my case, I have a background in my content container, and this container has more than 100% of the vh. This background has a clipped red bg in a 45º, so when I resize the window, to an intermediate size, the red bg not resize too.
Is there a way to resize a clip-path vertically and horizontally when  I resize the window?
.home {
    background-color: $bg-primary-color;
    &::before {
        width: 100%;
        min-height: 87.3rem;
        position: absolute;
        content: "";
        background-color: $bg-secondary-color;
        clip-path: polygon(0 0, 100% 0, 100% 100%, 0 56.3%);
        -webkit-clip-path: polygon(0 0, 100% 0, 100% 100%, 0 56.3%);

        @include response('tablet') {
            height: 110rem;
            clip-path: polygon(0 0, 100% 0, 100% 100%, 0 93%);
            -webkit-clip-path: polygon(0 0, 100% 0, 100% 100%, 0 93%);
        }

        @include response('phone') {
            height: 145rem;
        }
    }
}

Thanks!

A: Make sure the area of your clip-path remain a square shape and its big enough to cover your element.
Here is an example:

.box {
  height:100vh;
  background:url(https://i.picsum.photos/id/1074/1000/1000.jpg) center/cover;
  clip-path:polygon(-100vmax -100vmax,100% -100vmax,100% 100%,-100vmax -50vmax);
  /* change the -50vmax to control the angle*/
}
<div class="box">

</div>

Below an illustration to understand the trick where your element is the red shape and the clip-path the black shape


text:
Q: Angular2 router, get route data from url, to display breadcrumbs I am using angular2 router.
To draw the breadcrumb of an url, lets say site.com/a/b/c/15 I do the following:

*

*Get the route of site.com/a/b/c/15 and get the pretty name associated to the route

*Get the route of site.com/a/b/c and get the pretty name associated to the route

*Get the route of site.com/a/b and get the pretty name associated to the route

*Get the route of site.com/a and get the pretty name associated to the route

So lets say I do have the following routes:
{ path: 'a', component: A, data:{prettyName: 'I am A'}}
{ path: 'b', component: B, data:{prettyName: 'I am B'}},
{ path: 'c', component: C, data:{prettyName: 'I am C'}},

The result of my process would be an array containing {"I am C", "I am B", "I am C"} and thanks to that I can display a nice breadcrumb "I am A > I am B > I am C" that explains the current route.
This use to work with the router-deprecated doing
this.router.recognize(url).then((instruction) => {
    instruction.component.routeData.get('prettyName') // Would return 'I am ..'

However now; with the last router I am not able to process this recognize logic anymore.
How to get the route data associated to an url ?

A: Updated for RC5
Instead of starting with the current URL and trying to get the routes from the URL, you can get all of the activated routes (associated with the primary outlet) from the RouterState:

After the end of each successful navigation lifecycle, the router builds a tree of ActivatedRoutes, which make up the current state of the router. We can access the current RouterState from anywhere in our application using the Router service and the routerState property.
The router state provides us with methods to traverse up and down the route tree from any activated route to get information we may need from parent, child and sibling routes. -- reference

Subscribe to router events, then, after each NavigationEnd event, walk down the tree of ActivatedRoutes from the root:
import { Component } from '@angular/core';
import { Router, ActivatedRoute, NavigationEnd } from '@angular/router';
import 'rxjs/add/operator/filter';

@Component({
  selector: 'breadcrumbs',
  template: `

    breadcrumbs:

      {{breadcrumb.label}}
      >

`
})
export class BreadcrumbsComponent {
  breadcrumbs: Array<Object>;
  constructor(private router:Router, private route:ActivatedRoute) {}
  ngOnInit() {
    this.router.events
      .filter(event => event instanceof NavigationEnd)
      .subscribe(event => {  // note, we don't use event
        this.breadcrumbs = [];
        let currentRoute = this.route.root,
            url = '';
        do {
          let childrenRoutes = currentRoute.children;
          currentRoute = null;
          childrenRoutes.forEach(route => {
            if(route.outlet === 'primary') {
              let routeSnapshot = route.snapshot;
              console.log('snapshot:', routeSnapshot)
              url += '/' + routeSnapshot.url.map(segment => segment.path).join('/');
              this.breadcrumbs.push({
                label: route.snapshot.data.breadcrumb,
                url:   url });
              currentRoute = route;
            }
          })
        } while(currentRoute);
      })
  }
}

Routes look like this:
{ path: '', component: HomeComponent, data: {breadcrumb: 'home'}}

Plunker - RC.5, router 3.0.0-rc.1

See also https://stackoverflow.com/a/38310404/215945 for a similar solution.

A: So far, the most feasable solution is (done):

*

*Make the routes export/importable

*Get the current url update from router.events subscribe

*On url change, loop on the routes's path, see if the pattern match the url

*If the patter match the url, get the data from the matching route

Pros: works
Cons: redoing url-route recognition manuall without using the ng2 router one

A: Any breadcrumb solution has to handle -

*

*declarative approach of defining breadcrumbs in Application routing.

*dynamic asynchronous way to update any route with a label from the server response.

*way to skip specific routes from displaying in breadcrumbs.

I have created an Angular library to handle all these, called xng-breadcrumbs - https://github.com/udayvunnam/xng-breadcrumb
feel free to check, An Angular app developed showing the breadcrumbs usage - https://xng-breadcrumb.netlify.com
Angular library planning, creation, and continuous release is well documented in this medium article


text:
Q: Xamarin Studio mac error When I try to build an app (no matter which one) Xamarin throws the next error:
Xamarin.Android.Common.targets: Warning: No -tsa or -tsacert is
provided and this jar is not timestamped. Without a timestamp, users
may not be able to validate this jar after the signer certificate's
expiration date (2046-10-17) or after any future revocation date.


text:
Q: Provision XSLTListViewWebPart with  or  and customize the XslLink I've created some custom List Definitions (aka List Templates) and am provisioning List Instances of them into my site.  I am then provisioning Pages (Wiki/WebPartPages) that refer to the lists/views that I've setup.  I am trying to do this using the  element and then specify only the properties I want to change, rather than exporting a  (which isn't localizeable).  I can work with the Title property fine, however, when I try to specify the XslLink property, my web part will not provision correctly:
<View List="Lists/MyList" BaseViewID="105" WebPartZoneID="wpz" ID="g_6BFC14DC_62A4_4512_A360_EB4A0FC4DBD1">
 <![CDATA[
  <webParts>
   <webPart xmlns="http://schemas.microsoft.com/WebPart/v3">
    <metaData>
     <type name="Microsoft.SharePoint.WebPartPages.XsltListViewWebPart, Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" />
     <importErrorMessage>Cannot import this Web Part.</importErrorMessage>
    </metaData>
    <data>
     <properties>
       <property name="Title" type="string">Me</property>
       <property name="XslLink" type="string">~site/Assets/xsl/my.xsl</property>
     </properties>
    </data>
   </webPart>
  </webParts>
  ]]>
</View>

For troubleshooting purposes, when I hard code the server relative url to my site (rather than using the "~site" reference), it also does not work.  I check the contents of the page (using ?contents=1) and my web part is shown there, but likely as an "ErrorWebPart".  I check the ULS logs and I get a vague "unexpected error" with DesignText and SourcePreabmle:DWP references.
Again, all this works fine if all I customize is the Title property, which makes me think my markup within the CDATA is correct.  I've confirmed that the XslLink property (exposed via the DataFormWebPart from which XsltListViewWebPart ultimately derives) is, in fact, a string using ILSpy.
This also works fine if I get the  content - using the "Save site as a template" functionality and extracting this page's contents into my feature.
Do I maybe need to use the old <WebPart> syntax instead of the newer <webParts>?  Based on what I see in the Blog site template onet.xml (SiteTemplates\Blog\Xml\Onet.xml), it looks like the newer <webParts> is appropriate.
I see this in both a Sandboxed and Farm solution scenario.
thanks in advance!

A: For any one still looking for an answer:
Property Setting using ~site works fine unless it is in included in
 <![CDATA[... ]]>

What I mean is,
<Property name"x">~site/zzz</property>

works fine if set directly in a web part .
But this
<![CDATA[<Property name"x">~site/zzz</property>]]>

will not work.
    To have this working, use encoded value for "~" i.e. "~".
    So try this instead
<![CDATA[<Property name"x">~site/zzz</property>]]>

will work.

A: Yeah, run into this before also, but with a Content By Query web part with custom XSLT. You can't use the ~token in the path, it just doesn't know what to do with it.
I don't know of a particular workaround for your situation, but for a custom web part that you are deploying, you can create a feature receiver that grabs the .webpart file, reads the XML, finds the token, replaces it with the actual site or site collection value, and saves the file back. I am not sure if there is a similar workaround that can be done for declarative lists and views.


text:
Q: are singletons always closed? I am learning about metric spaces and I find it very confusing. Is this a valid proof that a singleton must be closed?
If $(X,d)$ is a metric space, to show that $\{a\}$ is closed, let's show that $X \setminus \{a\}$ is open. Choose $y \in X \setminus \{a\}$ and set $\epsilon = d(a,y)$. Then since $a \not \in B(y,\epsilon)$, we have that $B(y,\epsilon) \subset X \setminus \{a\}$ so that $X \setminus \{a\}$ is open.

A: Your proof is okay. More generally, we can define any topological space to be $T_1$ if its singleton sets are closed (or equivalently, for any points $x \neq y$, there is an open set containing $x$ and not containing $y$). $T_1$ is an example of a separation axiom. You've shown that metric spaces are $T_1$, but much stronger separation axioms hold for metric spaces.
Credit to Squirtle for providing similar details in a comment.


text:
Q: How can I locate Y coordinate of my elements in array I need some help.
I try to locate Y coordinate of multiple div with the same class (.section-container)
but console.log return me 0 for each div.
(2) [div.section-container, div.section-container]
2 0
Do You have any idea please ?
const sectionSelector = element !== undefined
                      ? element.querySelectorAll('.section-container')
                      : false;

const sectionArr = Array.from(sectionSelector);

const PosY = function()
  {
  sectionArr.forEach( function(e)
    {
    const pos = e.getBoundingClientRect();
    const y   = pos.top;
    console.log(y)
    })
  }

PosY();

Thks for your help !

A: Have you already tried to use pos.y instead of pos.top?
top is only a relative value, described in MDN (https://developer.mozilla.org/de/docs/Web/API/Element/getBoundingClientRect)

A: I cannot see anything wrong with the code as far as it is given, but we don't have the HTML so I have added some to test things.
The code works fine as long as the HTML is there for it to work on. Hopefully comparing what is in this snippet and what you actually have will throw some light on the problem.


text:
Q: Why doesn't the Federation have a law for genocide? In The Survivors, Picard makes the following statement towards Kevin Uxbridge:

We are not qualified to be your judges. We have no law to fit your crime. You're free to return to the planet, and to make Rishon live again.

That sounds like a gigantic cop-out;
First of all their qualification to be his judges is merely tied to their inability to hold him responsible for anything, as his abilities seem near omnipotent from the human's perspective.
However, my main quarrel is with the second sentence. For all intents and purposes, Kevin Uxbridge committed genocide. Something that humans are very familiar with from their own past. So the Federation would have to had dropped the law regarding genocide at some point.
I realise that the Federation doesn't just consist of humans, but wouldn't that be something humans would have been inclined to add to the Federation charter when drafting it?
This spineless statement is so deviant from the Federation and Star Trek philosophy (that is, in- and out-of universe) that I wonder why Picard, and by extension the writers, worded it like that.

A: Actually, it's a recognition that humans are not perfect.  It's not a cop-out at all.  It's a simple acknowledgement that we (as if I'm a part of the Federation) are not fit, and have no authority to judge some crimes.
It may seem like a cop-out, but it stems from the understanding that power leads to corruption.  If the Federation went around enforcing humanity's laws and morals on every species they interacted with, what would be left of freedom?  The Federation would be nothing more than an empire, or a dictatorship.  There is a balance between freedom and morality.
The crime here was immense.  The disdain in Picard's voice showed that clearly, he, personally DID judge this to be a heinous crime.  But to do anything about it leads down the path to greater evil.  Yes, this was one man (being), not an entire civilization.  But when you allow yourself to judge like this, where do you stop?

A: Picard is saying that a law against a single individual erasing the existence of an entire species across the galaxy has never been contemplated or established in Federation legal precedent. To their knowledge it's never been done so never came up while drafting laws. Such an act is so far outside their realm of possibility that they never drafted a law against it. That would be like passing a law stipulating that a person can't reverse the earth's orbit around the sun.
To convict him of mass murder or even a single murder they would have to have some proof or evidence beyond just his 'confession'. All evidence of any wrongdoing was erased.
Say if some clever Federation prosecutor could somehow get a conviction for murder, what would be the penalty? Capital punishment? Life imprisonment? How would that sentence be imposed or carried out on a creature that can literally 'erase' humanity with a thought? They have no ability to hold him against his will much less kill him.
As it sits, Picard made the best (only) choice available by 'allowing' Kevin to return to the planet in a kind of self-imposed 'prison' with the warning that he be left alone.
From what we've seen so far in the Star Trek Universe, the only society qualified/capable of judging Kevin Uxbridge's actions is the Q. They alone have the ability to judge his actions and impose penalties.

A: Actually, that statement makes sense, including in-universe-philosophy-wise.

*

*Most likely, the crime happened outside Federation jurisdiction. One can quibble, but since Douwd were not Federation subjects, and neither were Husnock, any activity between the two of those races are not subject of Federation laws.

*Any laws imposed on other races would basically violate the principles driving Prime Directive (even if the letter wouldn't be violated since they aren't pre-space actors).

*Moreover, any competent lawyer would poke a tribble-ful of holes into ANY argument you can legally made:

*

*Uxbridge was acting in the condition of affect, emotional distress etc... etc... "temporary insanity" and all that.

*Husnock declared war, unprovoked, so this was not a civilian crime in the first place.

*Husnock were an existential threat, ala Borg.

*He was not a member of UFP military so UCMJ or its UFP equivalent didn't apply to his conduct.


text:
Q: File Uploads - Form submitted without saving file? I'm trying to upload a file and save it to the server, the types of files will be documents, mostly doc/docx or Pages' file
Why isn't the file being saved for the model Grade, and the attribute Answer?
Here's my Schema.rb file
ActiveRecord::Schema.define(:version => 20110920230706) do

  create_table "assignments", :force => true do |t|
    t.string   "name"
    t.string   "instructions"
    t.date     "due"
    t.integer  "scribd_id"
    t.decimal  "score"
    t.datetime "created_at"
    t.datetime "updated_at"
    t.binary   "handout"
  end

  create_table "grades", :force => true do |t|
    t.integer  "assignment_id"
    t.integer  "user_id"
    t.integer  "scribd_id"
    t.decimal  "score"
    t.text     "note"
    t.datetime "created_at"
    t.datetime "updated_at"
    t.string   "answer_file_name"
    t.string   "answer_content_type"
    t.integer  "answer_file_size"
    t.datetime "answer_updated_at"
  end

  create_table "users", :force => true do |t|
    t.string   "email",                                 :default => "", :null => false
    t.string   "encrypted_password",     :limit => 128, :default => "", :null => false
    t.string   "reset_password_token"
    t.datetime "reset_password_sent_at"
    t.datetime "remember_created_at"
    t.integer  "sign_in_count",                         :default => 0
    t.datetime "current_sign_in_at"
    t.datetime "last_sign_in_at"
    t.string   "current_sign_in_ip"
    t.string   "last_sign_in_ip"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  add_index "users", ["email"], :name => "index_users_on_email", :unique => true
  add_index "users", ["reset_password_token"], :name => "index_users_on_reset_password_token", :unique => true

end

Grade.rb
class Grade < ActiveRecord::Base
  belongs_to :assignment

  has_attached_file :answer

end

Show.html.erb
<%= stylesheet_link_tag "assignments" %>

<%= notice %>

<%= @assignment.name %>

Directions -
<%= @assignment.instructions %>

Turn In Assignment

(You can just drag it in here)

  <%= form_for @grade, :html => { :multipart => true, :id => "form"} do |f| %>
    <%= f.file_field :answer, :id => "file" %>
  <% end %>

assignments.js.coffee
$(document).ready ->
  $("#file").mouseenter ->
    $("#turn_in_box").css "border", "2px solid #D9D9D9"
    $("#turn_in_box").css "background", "#D9D9D9"
    $("#turn_in_box").css "color", "#393939"
    $("#turn_in_box").css "cursor", "pointer"
    $("#turn_in_box").css "box-shadow" ,"0px 0px 0px transparent"

  $("#file").mouseleave ->
    $("#turn_in_box").css "border", "2px solid #D9D9D9"
    $("#turn_in_box").css "background", "#393939"
    $("#turn_in_box").css "color", "#D9D9D9"
    $("#turn_in_box").css "cursor", "default"
  $("#file").bind 'dragover', (evt) ->
    evt.stopPropagation()
    evt.preventDefault()
  $("#file").bind 'drop', ->
    $("#drag").css "display", "none"
    $("#turn_in_assignment").text "Turning In Assignment..."
    $("#form").submit()

development.log
Started GET "/assignments/2" for 127.0.0.1 at 2011-09-20 16:08:38 -0700
  Processing by AssignmentsController#show as HTML
  Parameters: {"id"=>"2"}
  ←[1m←[36mUser Load (0.0ms)←[0m  ←[1mSELECT "users".* FROM "users" WHERE "users"."id" = 1 LIMIT 1←[0m
  ←[1m←[35mAssignment Load (0.0ms)←[0m  SELECT "assignments".* FROM "assignments" WHERE "assignments"."id" = ? LIMIT 1
  ←[1m←[36mGrade Load (0.0ms)←[0m  ←[1mSELECT "grades".* FROM "grades" WHERE "grades"."assignment_id" = 2 AND "grades".
Rendered assignments/show.html.erb within layouts/application (50.0ms)
Completed 200 OK in 183ms (Views: 132.0ms | ActiveRecord: 1.0ms)

Started GET "/assets/assignments.css?body=1" for 127.0.0.1 at 2011-09-20 16:08:39 -0700
Served asset /assignments.css - 304 Not Modified (0ms)

Started GET "/assets/jquery.js?body=1" for 127.0.0.1 at 2011-09-20 16:08:39 -0700
Served asset /jquery.js - 304 Not Modified (1ms)

Started GET "/assets/grades.css?body=1" for 127.0.0.1 at 2011-09-20 16:08:39 -0700
Served asset /grades.css - 304 Not Modified (0ms)

Started GET "/assets/application.css?body=1" for 127.0.0.1 at 2011-09-20 16:08:39 -0700
Served asset /application.css - 304 Not Modified (0ms)

Started GET "/assets/jquery_ujs.js?body=1" for 127.0.0.1 at 2011-09-20 16:08:39 -0700
Served asset /jquery_ujs.js - 304 Not Modified (0ms)

Started GET "/assets/assignments.js?body=1" for 127.0.0.1 at 2011-09-20 16:08:39 -0700
Served asset /assignments.js - 304 Not Modified (1ms)

Started GET "/assets/assignments.js.js?body=1" for 127.0.0.1 at 2011-09-20 16:08:39 -0700
Served asset /assignments.js.js - 304 Not Modified (0ms)

Started GET "/assets/grades.js?body=1" for 127.0.0.1 at 2011-09-20 16:08:39 -0700
Served asset /grades.js - 304 Not Modified (0ms)

Started GET "/assets/application.js?body=1" for 127.0.0.1 at 2011-09-20 16:08:39 -0700
Served asset /application.js - 304 Not Modified (0ms)

Started PUT "/grades/2" for 127.0.0.1 at 2011-09-20 16:08:47 -0700
  Processing by GradesController#update as HTML
  Parameters: {"utf8"=>"Γ£ô", "authenticity_token"=>"/MpatBt5HIrsYPF0PKeyhfsQjY+Z1yDXMRtZjW+fHA8=", "id"=>"2"}
  ←[1m←[35mGrade Load (0.0ms)←[0m  SELECT "grades".* FROM "grades" WHERE "grades"."id" = ? LIMIT 1  [["id", "2"]]
[paperclip] Saving attachments.
Redirected to http://localhost:3000/grades/2
Completed 302 Found in 51ms

Started GET "/grades/2" for 127.0.0.1 at 2011-09-20 16:08:47 -0700
  Processing by GradesController#show as HTML
  Parameters: {"id"=>"2"}
  ←[1m←[36mGrade Load (1.0ms)←[0m  ←[1mSELECT "grades".* FROM "grades" WHERE "grades"."id" = ? LIMIT 1←[0m  [["id", "2"
Rendered grades/show.html.erb within layouts/application (11.0ms)
Completed 200 OK in 28ms (Views: 25.0ms | ActiveRecord: 1.0ms)


text:
Q: How to refactor this GOTO (no resource deallocation involved)? This is a simple control-flow GOTO question, nothing about resource allocation.
There are two levels of checking if a piece of data is "good".  If and only if it passes the first check, we do the second check.  If the data fails either test, we use a default value instead.
The second check involves a few steps with intermediate data, so we can't just put it in a short-circuited || condition.  Furthermore, if the second test passes, we use the output of the second test instead of the original data.
This is the inner loop in a real-time processing situation, so efficiency is very important.  We don't want to do any of the calculations more than once.
if (firstCheck(data)) {
    result = analyze(data);
    if (secondCheck(result)) {
        use_result(result);
    }
    else {
        goto FAIL;
    }
}
else {
FAIL:
    use_result(DEFAULT_VALUE);
}

This GOTO seems to satisfy all my requirements with maximal efficiency.  I can think of some other ways to do it, but all would involve extra storage or conditionals.  I am wary of GOTOs though.  In fact, if I use this, it will be the first time I have ever used a GOTO.  So please, help me find the way out!

A: Well we can fix this without much work, but using a goto in this way isn't necessarily bad behavior - e.g. the linux kernel uses this convention for doing error handling in only one spot as well and I think the code is quite clear as is.
Using exceptions to fix this is obviously one solution, but this does cost performance in the error case, so I assume that's out of the question.
So if you want to, this should be fine:
if (firstCheck(data) && secondCheck(result = analyze(data)) {
    use_result(result);
}
else {
    // fail
}

A: Use continue to go to next loop iteration
if (firstCheck(data)) {
    result = analyze(data);
    if (secondCheck(result)) {
        use_result(result);
        continue;
    }
}
use_result(DEFAULT_VALUE);

A: You are not just using a goto. You are using a goto that goes into another scope. Much simpler:
if (firstCheck(data)) {
    result = analyze(data);
    use_result (secondCheck (result) ? result : DEFAULT_VALUE);
}
else {
    use_result(DEFAULT_VALUE);
}

Cleaner, no code duplication, and scalable:
int result = DEFAULT_VALUE;
if (firstCheck(data)) {
    int tmpResult = analyze(data);
    if (secondCheck (tmpResult))
        result = tmpResult;
}
use_result (result);


text:
Q: Show a div if dynamic created span class is present on page Have a site that has limited access to source code to edit.  It dynamically creates a span class

    Clearance
.

What I need is to show a div i have set to hidden saying price displayed may be open box unit.  This is what I have...
jQuery $(window).on('load', function(){
    clearance = $("#isclearance");
    if($('.img-flag-label .img-flag-clearance').is(':visible')){
        clearance.show();
    }
});

A: Stated previously, $('#ID').length will give you all elements. so:
if($('.img-flag-label').length >= 1){ clearance.show() }

Make sure your script is running after the element is or is not dynamically added. 'Dynamically' might happen server-side or client-side. If it's a client-side script it could be invoked after the page is loaded.
I also take it hidden means
#isclearance {display: none} because $.show() operates on the css display attr
EDIT: also you need to declare your variable clearance with var, let, const etc if this is the only code you have so far.


text:
Q: Weird Django TypeError: send_mail() takes at least 4 arguments (4 given) I am trying to actually test sending an email using mailtrap.io, and I set up the email server as directed, however, when I try to do the following:
form = InterestedForm(request.POST)
if form.is_valid():
    name = form.cleaned_data['name']
    email = form.cleaned_data['email']
    subject = "Index form: Interested in Ucodon"
    message = 'Name: ' + name + '\n' + 'Email: ' + email
    recipients=['test@gmail.com']
    send_mail(subject, message, recipients, fail_silently=False)
    thanks = True

I get the following error:
TypeError: send_mail() takes at least 4 arguments (4 given)

I have even tried the following:
send_mail(subject=subject, message=message, recipients=recipients, fail_silently=False)

Also, I have defined EMAIL_HOST_USER. I am currently using EMAIL_HOST='mailtrap.io'.

A: According to the documentation:
send_mail(subject, message, from_email, recipient_list, fail_silently=False, auth_user=None, auth_password=None, connection=None, html_message=None)¶

You are missing from_email argument.
Either set it, or pass None - in this case Django would use DEFAULT_FROM_EMAIL setting value:
send_mail(subject, message, None, recipients, fail_silently=False)

A: Subject, message, from_email and recipient are required. I do not see you have provided the from_email. You can refer to https://docs.djangoproject.com/en/dev/topics/email/#send-mail for more info.


text:
Q: Button Onclick EventHandler from CreateChildControls I have declared a button in my CreateChildControls method in my web part page:
TableCell updateCell = new TableCell();
        Update = new Button();
        Update.Text = "Update";
        Update.OnClientClick += new EventHandler(Update_OnClick);
        updateCell.Controls.Add(Update);
        ButtonRow.Controls.Add(updateCell);

This is the eventhandler that I created:
    private void Update_OnClick(object sender, EventArgs e)
    {
        if (_TYPE == "FIXED")
        {
            Item["Retail"] = txtFixedRetail.Text;
            Item.Update();
            EmailFixedAlert();
        }
    }

However JScript throws an error:
Microsoft JScript runtime error: 'System' is undefined

And produces this in the HTML:
<input type="submit" name="ctl00$m$g_c260f907_31c1_436b_b99e_9bf79427625c$ctl11"     value="Update" onclick="System.EventHandler;" />

Why is the eventhandler that I declared in the WebPart not passing to the Page?
Do I have to push all events to the Client?

A: Button.OnClientClick is assigning JavaScript to run in the browser
Button.Click is for Server side event handling


text:
Q: Sum of two squares modulo a prime in $4\mathbb Z + 1$ I am trying to find the number of solution of the equation
$$
x^2 + y^2 = 1
$$
in $\mathbb Z/p\mathbb Z$, where $p$ is a prime such that $p\in4\mathbb Z+1$.
Apart from the trivial solutions $(0,\pm 1)$ and $(\pm1, 0)$, there is no solution when $p=5$, but $(6,2)$ is also its solution when $p=13$. It seems that there exists nontrivial solutions for other moduli, but I do not see a regular pattern for them.
By an exhaustive search by a computer I strongly believe that if $p = 4n+1$ the number of the solutions is $4n$, though I do not see why.
I would be grateful if you could provide a clue.

A: If $p\equiv1\pmod4$, then there exists an integer, call it $i$, such that $i^2\equiv-1\pmod p$. Using that $i$ you can rewrite the equation as
$$
1=x^2+y^2=(x+iy)(x-iy).
$$
Now let's take $u=x+iy$ and $v=x-iy$ as new variables. The mapping $(x,y)\mapsto(u,v)$ is bijective, because we can find an inverse mapping
$x=(u+v)/2$, $y=(u-v)/(2i)$.
It is hopefully easy to see why the equation
$$
1=uv
$$
has $p-1$ solutions. The above bijectivity shows that the original equation then also has $p-1$ solutions.

A: There is a nice "geometric" picture here.
If you have a non-degenerate conic then any line intersects it in two points (counting multiplicity, infinity, and algebraic extensions).
So, if you can find any one point on the curve, then there is a one-to-one correspondence between lines passing through that point and points on the curve. (your given point corresponds to the tangent line)
If your chosen point lies in the ground field -- $\mathbb{Z} / p \mathbb{Z}$ in this case -- then there is a one-to-one correspondence between curves with a slope in $\mathbb{Z} / p \mathbb{Z}$ and points with coordinates in $\mathbb{Z} / p \mathbb{Z}$.
So if there are any solutions, then there are $p+1$ solutions if we count points "at infinity". So the answer to your question now boils down to showing there are two points at infinity.
What do points at infinity mean? The quickest explanation is algebraic: you can homogenize your equation by adding a new variable so that all terms have the same degree. In this case:
$$ X^2 + Y^2 = Z^2 $$
The projective points are coordinate triples $(X:Y:Z)$ where not all the terms are zero. However, $(X:Y:Z)$ and $(aX:aY:aZ)$ both refer to the same point.
The "ordinary" (affine) point with coordinates $(a,b)$ correspond to the projective point with coordinates $(a:b:1)$.
So my previous analysis says that there are $p+1$ distinct projective points. The points at infinity are the ones where $Z=0$, so if we plug that in, we get
$$ X^2 + Y^2 = 0 $$
and so we have two solutions: $(1:i:0)$ and $(1:-i:0)$, where $i$ is a solution to $t^2 + 1 = 0$. If $p$ is odd, then such an $i$ exists in $\mathbb{Z} / p \mathbb{Z}$ if and only if $p \equiv 1 \bmod 4$ (see quadratic residuosity).
Because we can always find at least one solution ($(1,0)$), this means we should see $p-1$ solutions when $p \equiv 1 \bmod 4$ and $p+1$ solutions when $p \equiv 3 \bmod 4$.

We can use the above recipe to derive a formula for the points. I'll describe it affinely. The line through $(1,0)$ with slope $m$ is given by the formula
$$ y = m(x-1) $$
If we plug this into our circle equation and solve, we get
$$ x^2 + (m(x-1))^2 = 1 $$
whose solutions are
$$ x=1 \qquad \qquad x = \frac{m^2-1}{m^2-1} $$
so the other point on the line with slope $m$ is
$$ \left( \frac{m^2-1}{m^2+1}, \frac{-2m}{m^2+1} \right) $$
This gives us all of the points on the circle other than $(1,0)$. It gives us that too, if we make the appropriate sense of $m=\infty$.
So we see that if $t^2 + 1 = 0$ has no solutions, then every value of $m$ gives us a point, so we have $p+1$ points. If $m^2 + 1 = 0$ has two solutions, then those don't give us points on the circle, and we get $p-1$ points. (Well, it gives us the aforementioned two points at infinity, which you aren't counting)


text:
Q: .htaccess Disable directory access across site EXCEPT for one directory In my site's root directory I have the following in my .htaccess file:
# Block access to directories without a default document.
#
# You should leave the following uncommented, as you shouldn't allow
# anyone to surf through every directory on your server (which may
# includes rather private places such as the CMS's directories).

<IfModule mod_autoindex.c>
    Options -Indexes
</IfModule>

And in my root I have myFolder/ which I need to be accessible without an index.html. This answer says to add the following .htaccess file in myFolder/ but it doesn't seem to work, I still get error 403 forbidden:
Allow from all
Options +Indexes

So how can I block access to every directory on my site except for myFolder/?
UPDATE
In my root .htaccess I also have some rewrite rules, and the following portion is causing myFolder/ to throw a 403 error inexplicably is the (7) Remove ".html" from the end of urls. section:
    # (7)
    RewriteBase /
    RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /(.+)\.html\ HTTP/
    RewriteRule ^(.+)\.html$ https://mywebsitenameredacted.com/$1 [R=302]
    RewriteRule ^([A-Za-z0-9_/]+)$ /$1.html [L] # THIS LINE SPECIFICALLY

The last line (RewriteRule ^([A-Za-z0-9_/]+)$ /$1.html [L]) is specifically causing the page to throw a 403. However, I cannot for the life of me figure out what about this regex pattern would result in a 403 forbidden error -- if anything it should be transforming the myDirectory/ endpoint to something else causing a 404 error... does anyone have any ideas how this line could be causing a 403 on a directory page?


text:
Q: Is it possible to adorn a LINE OF CODE with a Conditional Attribute? (or something similar) I plan to put a call to MethodBase.GetCurrentMethod() at the beginning of most methods (for informative logging), but since this would present a high overhead, it would be good if a conditional attribute could be used used like:
#define LogMethodNames

where...
[Conditional("LogMethodNames")]

was put above every line call GetCurrentMethod(), like:
void DoStuff()
{
    [Conditional("LogMethodNames")]
    logger.CurrentMethod = MethodBase.GetCurrentMethod();

    //  stuff done here
}

...so at least it could be excluded from release builds.
Is something along these lines possible?
Thanks!
Gregg
PS I would try this myself now but for some reason I couldn't get Attributes to work due to a compile error. Doh.
PPS If this can't work I'd create a method which assigns to the logger object, like:
void SetCurrentMethod(MethodBase currentMethod)
{
    logger.CurrentMethod = currentMethod;
}

and use:
void DoStuff()
{
    [Conditional("LogMethodNames")]
    SetCurrentMethod(MethodBase.GetCurrentMethod());

    //  stuff done here
}

Any thoughts?! Thanks  :-)

A: You are close - you would need to set the Conditional attribute on the method itself:
[Conditional("LogMethodNames")]
void SetCurrentMethod(MethodBase currentMethod)
{
    logger.CurrentMethod = currentMethod;
}

For more information please see The Conditional attribute:

The attribute Conditional enables the
  definition of conditional methods. The
  Conditional attribute indicates a
  condition by testing a conditional
  compilation symbol. Calls to a
  conditional method are either included
  or omitted depending on whether this
  symbol is defined at the point of the
  call. If the symbol is defined, the
  call is included; otherwise, the call
  (including evaluation of the
  parameters of the call) is omitted.


text:
Q: how to prove this inequality $\sum\frac{x}{(n-1)y+1}+\frac{1}{\sum x}\ge\frac{n+1}{n}$ if $x_{i}>0$,show that
$$\sum_{i=1}^{n}\dfrac{x_{i}}{(n-1)x_{i+1}+1}+\dfrac{1}{\sum_{i=1}^{n}x_{i}}\ge\dfrac{n+1}{n}$$
I have  proven $n=2$and $n=3$
$n=3$ case
let $x,y,z>0$.prove
$$\dfrac{x}{2y+1}+\dfrac{y}{2z+1}+\dfrac{z}{2x+1}+\dfrac{1}{x+y+z}\ge\dfrac{4}{3}$$
By Cauchy-Schwarz inequality we have
$$\sum_{cyc}\dfrac{x}{2y+1}\ge \dfrac{(x+y+z)^2}{2xy+2yz+2zx+x+y+z}\ge\dfrac{t^2}{\dfrac{2}{3}t^2+t}=\dfrac{3t}{2t+3}$$
where $t=x+y+z>0$
so we must prove
$$\dfrac{3t}{2t+3}+\dfrac{1}{t}\ge\dfrac{4}{3}$$
the last inequality it is clear true!

A: A proof for $n=4$.
Let $x+y+z+t=4u$.
Thus, by C-S and AM-GM we obtain:
$$\sum_{cyc}\frac{x}{3y+1}+\frac{1}{x+y+z+t}=\sum_{cyc}\frac{x^2}{3xy+x}+\frac{1}{x+y+z+t}\geq$$
$$\geq\frac{(x+y+z+t)^2}{3\sum\limits_{cyc}xy+x+y+z+t}+\frac{1}{x+y+z+t}=\frac{16u^2}{3(x+z)(y+t)+4u}+\frac{1}{4u}\geq$$
$$\geq \frac{16u^2}{3\left(\frac{x+z+y+t}{2}\right)^2+4u}+\frac{1}{4u}=\frac{4u}{3u+1}+\frac{1}{4u}.$$
Id est, it's enough to prove that:
$$\frac{4u}{3u+1}+\frac{1}{4u}\geq\frac{5}{4}$$ or
$$(u-1)^2\geq0$$ and we are done.
For $n\geq5$ this way does not help.


text:
Q: XML/DTD The content of element type "Movie" must match "(Title,Price)". [7] Hoping someone can point out the error here - its only an example piece I am trying, but I just cannot get the XML to parse.....
The DTD looks like this
<?xml version="1.0" encoding="UTF-8"?>
<!ELEMENT Movies (Movie*)>
<!ELEMENT Movie (Title, Price)>
<!ATTLIST Movie year CDATA #REQUIRED>
<!ELEMENT Title (#PCDATA)>
<!ELEMENT Price (#PCDATA)>

And the sample XML looks like this
(I can't stop the preview from interpreting the XML!!)
<?xml version="1.1"?>
<!DOCTYPE Movies SYSTEM "movies.dtd">
<Movies>
    <Movie year="1946">
        <Title>It's a Wonderful Life</Title>
        <Price>14.95</Price>
    </Movie>
    <Movie year="1965">
        <Title>The Great Race</Title>
        <Price>12.95</Price>
    </Movie>
    <Movie year="1974">
        <Title>Young Frankenstein</Title>
        <Price>16.95</Price>
    </Movie>
    <Movie year="1975">
        <Title>The Return of the Pink Panther</Title>
        <Price>11.95</Price>
    </Movie>
</Movies>

And the error I get is ...
The content of element type "Movie" must match "(Title,Price)".
for every 'Movie' entry in the database I'm hoping it is something stupid - 'cos I can't see it!
Thanks

A: XML version should be 1.0-:
<?xml version="1.0"?>

and final closing tag </Movies> missing - probably just missed pasting this onto the post.

A: OK - no other responses but I found the problem.
It was down to formatting of the XML file. I was a bit surprised, but I stripped out all line endss etc and everything was fine.


text:
Q: gradle not able to detect module I have a multimodule project. there is 2 modules:
- server module
- domain module
in the build.gradle of the domain module I put :
group = 'com.xxx.yyyy.zzz'
version = '1.0.0-SNAPSHOT'

and the server module imports the domain module as follow :
dependencies {
compile group: 'com.xxx.yyyy.zzz', name: 'domain', version: '1.0.0-SNAPSHOT'

...
}

howerver he is not able to detect it!
the jar is published to the maven m2 repo and I am able to see it. and i am using mavenLocal to get dependecies from the m2
repositories {
    mavenLocal()
    mavenCentral()
}

I deleted the gradle cache, stopped the gradle daemon without success!
Any idea ?
the build.gradle of the server module:
group = 'com.xxx.yyy.zzz'
version = '1.0.0-SNAPSHOT'
repositories {
    mavenLocal()
    mavenCentral()

}

apply plugin: "org.springframework.boot"
apply plugin: "net.ltgt.apt"
apply plugin: "maven"
apply plugin: 'base'
apply plugin: 'maven-publish'

dependencies {
    compile group: 'com.xxx.yyy.zzz', name: 'domaine', version: '1.0.0-SNAPSHOT'
// other dependecies ......
}

the build.gradle of the domain module:
group = 'com.desjardins.experiencecredit.gestiondemandes'
version = '1.0.0-SNAPSHOT'

repositories {
    mavenLocal()
    mavenCentral()
}

apply plugin: "maven"
apply plugin: 'base'
apply plugin: 'maven-publish'

uploadArchives {
    repositories {
        mavenDeployer {
            repository(url: mavenrepo)
        }
    }
}

jar.finalizedBy uploadArchives

the settings.gradle of the main project :
pluginManagement {
    repositories {
        gradlePluginPortal()
    }
}
rootProject.name = 'XXX'
include 'server'
include 'domaine'

A: If you have multiple modules in the same project, you should instead declare the dependencies using the project object:
settings.gradle at root project level
rootProject.name = 'my-application'

include 'server'
include 'domain'

Then define the build files - root project build.gradle, server module build.gradle and domain module build.gradle.
In the server module's build.gradle, declare the dependency as follows:
dependencies {
  compile project(':domain')

  ...
}

Refer: https://guides.gradle.org/creating-multi-project-builds/


text:
Q: Inverse of $x(e^{-x} - 1)$ for $x \geq 0$? Does anyone know if the inverse of $$f(x) = x(e^{-x} - 1)$$ on $\{ x \geq 0 \}$ is expressible in terms of known special functions? The natural function to consider is the Lambert $W$-function, but I haven't been able to see a relationship.
Context: During some research, I needed to compute the solution to $x(ap^{-x} - 1) = C$, where $a > 1$, $p \in (0,1)$, and $C > 0$. I believe I could do this if I had an expression for $f^{-1} (x)$.

A: Consider the function
$$f(x)=x \left(a \,p^{-x}-1\right)-C$$ for which $$f'(x)=x p^{-2 x} \left(p^x-a\right) \left(a x \log (p)-a+p^x\right)$$ the first derivative cancels at
$$x_1=0\qquad\qquad x_2=\frac{\log (a)}{\log (p)}\qquad\qquad x_3=\frac{1-W\left(\frac{e}{a}\right)}{\log (p)}$$we have
$$f(x_1)=-C\qquad\qquad f(x_2)=-C\qquad\qquad f(x_3)=-C+\frac{\left(W\left(\frac{e}{a}\right)-1\right)^2}{W\left(\frac{e}{a}\right) \log (p)}$$
$$f''(x_1)=-2 a \log (p)\quad f''(x_2)=(\log (a)-2) \log (p)\quad f''(x_3)=-\left(1+\frac{1}{W\left(\frac{e}{a}\right)}\right) \log (p)$$ So, since $p \in (0,1)$, $x_1$ and $x_3$ correspond to minimum points. Remains the problem of $x_2$; since it is negative, then no problem.
Now, you need numerical methods.
What I would suggest is to solve is
$$g(x)=\log\Big[x \left(a \,p^{-x}-1\right)\Big]-\log(C)$$
Trying for $a=2$, $p=\frac 13$, $C=123456$, Newton iterates would be
$$\left(
\begin{array}{cc}
n & x_n \\
 0 & 1.00000 \\
 1 & 5.36270 \\
 2 & 8.05263 \\
 3 & 8.13264 \\
 4 & 8.13268
\end{array}
\right)$$
In odger to generate some estimate, I expanded $g(x)$ as a series around $x=1$ and later used series reversion to get
$$x \sim 1+t-\frac{(a-p)^2+a p \log ^2(p)}{2 (a-p) (a \log (p)-a+p)}t^3+O(t^3)$$ where
$$t=-\frac{(a-p) \left(\log (C)-\log \left(\frac{a}{p}-1\right)\right)}{a \log (p)-a+p}$$
For the worked example, this gives
$$t=\frac{5 \log \left(\frac{123456}{5}\right)}{5+\log (729)}$$
and, using the expansion to $O(t^2)$ gives $x_0=5.36270$  while using the expansion to $O(t^3)$ gives $x_0=10.6567$. I suppose that it is coincidence that the average of these two estimes gives $8.00969$ which is quite close to the solution.
Notice that
$$g(1)=\log \left(\frac{a-p}{Cp}\right) \qquad \text{and} \qquad g''(1)=-\frac{a p \log ^2(p)}{(a-p)^2}-1~~<~~0$$ So, by Darboux theorem, if $g(1)<0$ (that is to say $C > \frac {a-p}p$) starting with $x_0=1+t$ ensures that the solution will be reached without any overshoot.

A: Another (simpler) solution.
Let $p^{-x}=e^y$
$$x \left(a \,p^{-x}-1\right)=C \implies y(a e^y-1)=K \quad \text{where} \quad K=-C \log(p) ~>~0 $$
So, the solution of the equation is lower bounded by the solution of
$$a y e^y=K \implies y_0=W\left(\frac{K}{a}\right)$$ One iteration of Newton method gives
$$y_1=y_0-\frac {y_0(a e^{y_0}-1)-K}{a e^{y_0} (y_0+1)-1 }=\frac{a e^{y_0} y_0^2+K}{a e^{y_0} (y_0+1)-1}$$
Trying for $a=2$, $p=\frac 13$, $C=123456$, we have $y_0=8.93461$ and $y_1=8.93467$ which is the solution for this number of figures. Then $x=8.13268$.


text:
Q: How to split a string into substrings of equal length So
split("There are fourty-eight characters in this string", 20)

should return
["There are fourty-eig", "ht characters in thi","s string"]

If I make currentIndex = string.startIndex and then try to advance() it further than a string.endIndex, I get "fatal error: can not increment endIndex" before I check if my currentIndex < string.endIndex so the code below doesn't work
var string = "12345"
var currentIndex = string.startIndex
currentIndex = advance(currentIndex, 6)
if currentIndex > string.endIndex {currentIndex = string.endIndex}

A: Here is a string extension you can use if you want to split a String at a certain length, but also take into account words:
Swift 4:
func splitByLength(_ length: Int, seperator: String) -> [String] {
    var result = [String]()
    var collectedWords = [String]()
    collectedWords.reserveCapacity(length)
    var count = 0
    let words = self.components(separatedBy: " ")

    for word in words {
        count += word.count + 1 //add 1 to include space
        if (count > length) {
            // Reached the desired length

            result.append(collectedWords.map { String($0) }.joined(separator: seperator) )
            collectedWords.removeAll(keepingCapacity: true)

            count = word.count
            collectedWords.append(word)
        } else {
            collectedWords.append(word)
        }
    }

    // Append the remainder
    if !collectedWords.isEmpty {
        result.append(collectedWords.map { String($0) }.joined(separator: seperator))
    }

    return result
}

This is a modification of Matteo Piombo's answer above.
Usage
let message = "Here is a string that I want to split."
let message_lines = message.splitByLength(18, separator: " ")

//output: [ "Here is a string", "that I want to", "split." ]

A: My solution with an array of characters:
func split(text: String, count: Int) -> [String] {
    let chars = Array(text)
    return stride(from: 0, to: chars.count, by: count)
        .map { chars[$0 ..< min($0 + count, chars.count)] }
        .map { String($0) }
}

Or you can use more optimised variant for large strings with Substring:
func split(text: String, length: Int) -> [Substring] {
    return stride(from: 0, to: text.count, by: length)
        .map { text[text.index(text.startIndex, offsetBy: $0)..<text.index(text.startIndex, offsetBy: min($0 + length, text.count))] }
}

A: I just answered a similar question on SO and thought I can provide a more concise solution:
Swift 2
func split(str: String, _ count: Int) -> [String] {
    return 0.stride(to: str.characters.count, by: count).map { i -> String in
        let startIndex = str.startIndex.advancedBy(i)
        let endIndex   = startIndex.advancedBy(count, limit: str.endIndex)
        return str[startIndex..<endIndex]
    }
}

Swift 3
func split(_ str: String, _ count: Int) -> [String] {
    return stride(from: 0, to: str.characters.count, by: count).map { i -> String in
        let startIndex = str.index(str.startIndex, offsetBy: i)
        let endIndex   = str.index(startIndex, offsetBy: count, limitedBy: str.endIndex) ?? str.endIndex
        return str[startIndex..<endIndex]
    }
}

Swift 4
Changed to a while loop for better efficiency and made into a String's extension by popular request:
extension String {
    func split(by length: Int) -> [String] {
        var startIndex = self.startIndex
        var results = [Substring]()

        while startIndex < self.endIndex {
            let endIndex = self.index(startIndex, offsetBy: length, limitedBy: self.endIndex) ?? self.endIndex
            results.append(self[startIndex..<endIndex])
            startIndex = endIndex
        }

        return results.map { String($0) }
    }
}

A: You must not use range that exceeds the string size. The following method will demonstrates how to do it:
extension String {
    func split(len: Int) -> [String] {
        var currentIndex = 0
        var array = [String]()
        let length = self.characters.count
        while currentIndex < length {
            let startIndex = self.startIndex.advancedBy(currentIndex)
            let endIndex = startIndex.advancedBy(len, limit: self.endIndex)
            let substr = self.substringWithRange(Range(start: startIndex, end: endIndex))
            array.append(substr)
            currentIndex += len
        }
        return array
    }
}

Usage:
"There are fourty-eight characters in this string".split(20)
//output: ["There are fourty-eig", "ht characters in thi", "s string"]

or
"⛵".split(3)
//output: ["", "", "⛵"]

Edit:
Updated the answer to work with Xcode 7 beta 6. The advance method is gone, replaced by advancedBy instance methods of Index. The advancedBy:limit: version is especially useful in this case.

A: endIndex is not a valid index; it is one more than the valid range.

A: Swift 5, based on @Ondrej Stocek solution
extension String {
    func components(withMaxLength length: Int) -> [String] {
        return stride(from: 0, to: self.count, by: length).map {
            let start = self.index(self.startIndex, offsetBy: $0)
            let end = self.index(start, offsetBy: length, limitedBy: self.endIndex) ?? self.endIndex
            return String(self[start..<end])
        }
    }
}

A: This problem could be easily solved with just one pass through the characters sequence:
Swift 2.2
extension String {
    func splitByLength(length: Int) -> [String] {
        var result = [String]()
        var collectedCharacters = [Character]()
        collectedCharacters.reserveCapacity(length)
        var count = 0

        for character in self.characters {
            collectedCharacters.append(character)
            count += 1
            if (count == length) {
                // Reached the desired length
                count = 0
                result.append(String(collectedCharacters))
                collectedCharacters.removeAll(keepCapacity: true)
            }
        }

        // Append the remainder
        if !collectedCharacters.isEmpty {
            result.append(String(collectedCharacters))
        }

        return result
    }
}

let foo = "There are fourty-eight characters in this string"
foo.splitByLength(20)

Swift 3.0
extension String {
    func splitByLength(_ length: Int) -> [String] {
        var result = [String]()
        var collectedCharacters = [Character]()
        collectedCharacters.reserveCapacity(length)
        var count = 0

        for character in self.characters {
            collectedCharacters.append(character)
            count += 1
            if (count == length) {
                // Reached the desired length
                count = 0
                result.append(String(collectedCharacters))
                collectedCharacters.removeAll(keepingCapacity: true)
            }
        }

        // Append the remainder
        if !collectedCharacters.isEmpty {
            result.append(String(collectedCharacters))
        }

        return result
    }
}

let foo = "There are fourty-eight characters in this string"
foo.splitByLength(20)

Since String is a pretty complicated type, ranges and indexes could have different computational costs depending on the view. These details are still evolving, thus the above one-pass solution might be a safer choice.
Hope this helps

A: String extension based on "Code Different" answer:
Swift 3/4/5
extension String {
    func components(withLength length: Int) -> [String] {
        return stride(from: 0, to: self.characters.count, by: length).map {
            let start = self.index(self.startIndex, offsetBy: $0)
            let end = self.index(start, offsetBy: length, limitedBy: self.endIndex) ?? self.endIndex
            return self[start..<end]
        }
    }
}

Usage
let str = "There are fourty-eight characters in this string"
let components = str.components(withLength: 20)

A: Here is a version, that works in the following situations:

*

*the given row length is 0 or smaller

*the input is empty

*the last word of a line does not fit: the word is wrapped into a new line

*the last word of a line is longer than the row length: the word is cut and wrapped partially

*the last word of a line is longer than multiple lines: the word is cut and wrapped multiple times.

extension String {

    func ls_wrap(maxWidth: Int) -> [String] {
        guard maxWidth > 0 else {
            Logger.logError("wrap: maxWidth too small")
            return []
        }
        let addWord: (String, String) -> String = { (line: String, word: String) in
            line.isEmpty
                ? word
                : "\(line) \(word)"
        }
        let handleWord: (([String], String), String) -> ([String], String) = { (arg1: ([String], String), word: String) in
            let (acc, line): ([String], String) = arg1
            let lineWithWord: String = addWord(line, word)
            if lineWithWord.count <= maxWidth { // 'word' fits fine; append to 'line' and continue.
                return (acc, lineWithWord)
            } else if word.count > maxWidth { // 'word' doesn't fit in any way; split awkwardly.
                let splitted: [String] = lineWithWord.ls_chunks(of: maxWidth)
                let (intermediateLines, lastLine) = (splitted.ls_init, splitted.last!)
                return (acc + intermediateLines, lastLine)
            } else { // 'line' is full; start with 'word' and continue.
                return (acc + [line], word)
            }
        }
        let (accLines, lastLine) = ls_words().reduce(([],""), handleWord)
        return accLines + [lastLine]
    }

    // stolen from https://stackoverflow.com/questions/32212220/how-to-split-a-string-into-substrings-of-equal-length
    func ls_chunks(of length: Int) -> [String] {
        var startIndex = self.startIndex
        var results = [Substring]()
        while startIndex < self.endIndex {
            let endIndex = self.index(startIndex, offsetBy: length, limitedBy: self.endIndex) ?? self.endIndex
            results.append(self[startIndex..<endIndex])
            startIndex = endIndex
        }
        return results.map { String($0) }
    }

    // could be improved to split on whiteSpace instead of only " " and "\n"
    func ls_words() -> [String] {
        return split(separator: " ")
            .flatMap{ $0.split(separator: "\n") }
            .map{ String($0) }
    }
}

extension Array {

    var ls_init: [Element] {
        return isEmpty
            ? self
            : Array(self[0..<count-1])
    }
}

A: The solution with a while loop is actually a bit more flexible than the one with the stride. Here is a slight update (Swift 5) of Adam's answer:
extension String {

func split(len: Int) -> [String] {

    var currentIndex = 0
    var array = [String]()
    let length = self.count

    while currentIndex < length {
        let startIndex = index(self.startIndex, offsetBy: currentIndex)
        let endIndex = index(startIndex, offsetBy: len, limitedBy: self.endIndex) ?? self.endIndex
        let substr = String( self[startIndex...endIndex] )
        array.append(substr)
        currentIndex += len
    }

    return array

}

}
We can generalise it to take a an array of Ints instead of a single Int. So that we can split a string into substrings of various lengths like so:
extension String {
func split(len: [Int]) -> [String] {

    var currentIndex = 0
    var array = [String]()
    let length = self.count
    var i = 0

    while currentIndex < length {
        let startIndex = index(self.startIndex, offsetBy: currentIndex)
        let endIndex = index(startIndex, offsetBy: len[i], limitedBy: self.endIndex) ?? self.endIndex
        let substr = String( self[startIndex..<endIndex] )
        array.append(substr)
        currentIndex += len[i]
        i += 1
    }

    return array

}

}
Usage:
func testSplitString() throws {
var retVal = "Hello, World!".split(len: [6, 1, 6])
XCTAssert( retVal == ["Hello,", " ", "World!"] )

retVal = "Hello, World!".split(len: [5, 2, 5, 1])
XCTAssert( retVal == ["Hello", ", ", "World", "!"] )

retVal = "hereyouare".split(len: [4, 3, 3])
XCTAssert( retVal == ["here", "you", "are"] )

}

A: code
People shouldn't use stride() for this.
An ordinary Range<Int> is enough.
This is a simple, yet optimized Swift5 solution:
extension String {
    func split(by length: Int) -> [String] {
        guard length > 0 else { return [] }
        var start: Index!
        var end = startIndex
        return (0...count/length).map { _ in
            start = end
            end = index(start, offsetBy: length, limitedBy: endIndex) ?? endIndex
            return String(self[start..<end])
        }
    }
}

*

*Since start and end indices are being tracked in map function,
it does not repeat itself.

*count/length takes care of when length exceeds count.

*guard is needed for the length <= 0 case.

usage
let splittedHangeul = "체르노빌같던후쿠시마원전폭발".split(by: 3)
let splittedEnglish = "THEQUICKBROWNFOXJUMPSOVERTHELAZYDOG".split(by: 6)

print(splittedHangeul)
print(splittedEnglish)
//["체르노", "빌같던", "후쿠시", "마원전", "폭발"]
//["THEQUI", "CKBROW", "NFOXJU", "MPSOVE", "RTHELA", "ZYDOG"]

A: A modern (2021+) solution is Chunked of the Swift Algorithms package
let string = "There are fourty-eight characters in this string"
let chunked = string.chunks(ofCount: 20)
print(Array(chunked))

A: extension String {
    func inserting(separator: String, every n: Int) -> String {
        enumerated().reduce("") { $0 + ((($1.offset + 1) % n == 0) ? String($1.element) + separator : String($1.element)) }
    }
}


text:
Q: Movilizer - Splash screen android When I try to customize the client Splash screen the following issue occurs:
I created a 480x800 image within the limits of 512kb as instructed by the customization guidelines.
When I set the image on a android client with a screen resolution of 1080x1920 it doesn't get stretched to full screen.
It happend to a Sony Xperia and HTC One M7 device (both 1080x1920), iOS devices show it correctly (fullscreen). am I doing something wrong?

A: This is an issue up to 2.3 ... the 2.3 Movilizer Android client solves the problem. In 2.3 there is a change of the layout resource file for splash screens to fill height.
Please note that as we speak this client is not yet released.


text:
Q: Hiding any elements of a class whose innerhtml contains a certain character? I'm not a developer, I'm a Googler working through a third-party whatsit service; I know MINIMAL Javascript and am stuck with inline scripting until the sub-boss recovers from his illness and changes my permissions. Everything related I've been able to find references jQuery. Is there a way to do what I need -- hide the elements of a class whose innerhtml contains a certain character -- without the benefit of this fabled jQuery?
Thank you for your patience!

A: Here is a variant that hides all elements that contains a specific character:
window.onload = function ()
{
    var character = "x", // The character to search for
        elements = document.body.getElementsByClassName("className");

    for (var i = 0, length = elements.length; i < length; i++)
    {
        if (elements[i].innerHTML.indexOf(character) !== -1)
        {
            elements[i].style.display = "none";
        }
    };
}

And a version to search against an array of characters:
window.onload = function ()
{   // The pattern to search for:
    var characters = ["x", "y", "z", "some words", "@&"],
        elements = document.body.getElementsByClassName("className");

    for (var i = 0, length = elements.length; i < length; i++)
    {
        for (var c in characters)
        {
            if (elements[i].innerHTML.indexOf(characters[c]) !== -1)
            {
                elements[i].style.display = "none";
            }
        };
    };
}


text:
Q: No canonical non-quadratic residue for primes $\equiv 1 \bmod 8$? Let $p$ be an odd prime number.

*

*If $p \equiv 3 \bmod 8$ or $p \equiv 5 \bmod 8$, $2$ is not a square mod $p$.

*If $p \equiv 3 \bmod 8$ or $p \equiv 7 \bmod 8$, $-1$ is not a square mod $p$.

If $p \equiv 1 \bmod 8$, there seems to be no way to choose a single $n \in \mathbb{Z}$ such that $n$ is not a square mod $p$ regardless of the choice of $p$. Can one prove that this is not the case? What if we continue searching for residues mod 16?
In fact, the more general question I would like to know the answer to, is the following: Can there be a finite set of natural numbers $S$ such that that for each prime number $p$, there exists an $n \in S$ such that $n$ is not a square mod $p$?

A: In other words given a finite set of numbers $S$ find a prime $p$ such that for all $n\in S$,  $n$ is a quadratic residue modulo $p$.
Now from quadratic reciprocity we have that
$$\left(\frac{n}{p}\right)=1 \Leftrightarrow p\equiv a_i \text{
(mod $4n$)}$$ where $a_i$ are some numbers depending on $n$.
It then follows from Dirichlet's theorem on primes in an arithmetic progression that there are infinitely many such primes.

A: A simple consequence of quadratic reciprocity is that if $n$ is odd, then
$$p \equiv 1 \pmod{4n} \implies \left(\frac{n}{p}\right)=1.$$
Pair this together with $p \equiv 1 \pmod 8 \implies \left(\frac{-1}{p}\right)=\left(\frac{2}{p}\right)=1$, and it's easy to see that for any finite set $S$, we can take $N$ to be the lcm of all elements of $S$, and then for any prime $p \equiv 1 \pmod{8N}$ the entirety of $S$ will be quadratic residues modulo $p$.
This also helps to explain why you are having particular difficulty finding a generic non-residue for primes congruent to $1$ mod $8$.


text:
Q: Running parallel Testng tests in Selenium I have a BaseClass which has @BeforeSuite method that takes browser and other login parameters from xml. I want to run 2 parallel tests with different parameters. Since i am using parameters in @BeforeSuite so it takes values only once and not running any parallel execution. I cannot use parameters in @BeforeTest or @BeforeMethod or @BeforeClass as I need to use these parameters only once for each test and i have multiple test cases in each class.
My xml is as below;

    <listeners>
    <listener class-name="Utility.Listeners" />
    </listeners>

 <test name="Tests1" >

      <parameter name="Browser" value="chrome" />
 <parameter name="username" value="d1" />
 <parameter name="password" value="P1" />
 <parameter name="Brand" value="TC" />

    <groups>
        <run>
            <include name="NatP"  />
        </run>
    </groups>

    <classes  >
     <class name="Maven.Dashboard"/>
     <class name="Maven.TopBottomWidget"/>
     <class name="Maven.Dashboard_BE"/>

     </classes>
</test>

      <parameter name="Browser" value="chrome" />
 <parameter name="username" value="d1K" />
 <parameter name="password" value="P1K" />
 <parameter name="Brand" value="TCK" />

    <groups>
        <run>
            <include name="NatP"  />
        </run>
    </groups>

    <classes  >

     <class name="Maven.Dashboard"/>
     <class name="Maven.TopBottomWidget"/>
     <class name="Maven.Dashboard_BE"/>

    </classes>
</test>

A: *

*You could try programmatic execution of testng by using the below code. You have to pass the parameters as maven run time arguments like below,

mvn clean install exec:java "-Dexec.mainClass=org.package.Test" "-DskipTests" "-Dexec.classpathScope=test" "-DBrowser=chrome,firefox"
The Test class is present inside src/test/java/, hence the classpathScope is mentioned as test in the above command. Also using the above maven command we are executing the main function of the Test class. This main method will in turn trigger the testng execution. The main method parse the existing testng XML file and add the arguments as parameters to each test. Each test will be run parallel with the thread size equal to the number of arguments you pass.
    import org.apache.commons.io.FileUtils;
    import org.apache.commons.lang.StringUtils;
    import org.testng.TestNG;
    import org.testng.xml.Parser;
    import org.testng.xml.XmlSuite;
    import org.testng.xml.XmlTest;

    import java.io.File;
    import java.io.InputStream;
    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.HashMap;
    import java.util.List;

    public class Test {

    public static void main(String[] args) throws Exception {

        List<String> browserList = StringUtils.isEmpty(System.
                getProperty("Browser")) ? new ArrayList<>() :
                Arrays.asList(System.getProperty("Browser").split(","));
        TestNG tng = new TestNG();
        File initialFile = new File("testng.xml");
        InputStream inputStream = FileUtils.openInputStream(initialFile);
        Parser p = new Parser(inputStream);
        List<XmlSuite> suites = p.parseToList();
        List<XmlSuite> modifiedSuites = new ArrayList<>();
        for (XmlSuite suite : suites) {
            XmlSuite modifiedSuite = new XmlSuite();
            modifiedSuite.setParallel(suite.getParallel());
            modifiedSuite.setThreadCount(browserList.size());
            modifiedSuite.setName(suite.getName());
            modifiedSuite.setListeners(suite.getListeners());
            List<XmlTest> tests = suite.getTests();
            for (XmlTest test : tests) {
                for (int i = 0; i < browserList.size(); i++) {
                    XmlTest modifedtest = new XmlTest(modifiedSuite);
                    HashMap<String, String> parametersMap = new HashMap<>();
                    parametersMap.put("browser", browserList.get(i));

                    modifedtest.setParameters(parametersMap);
                    modifedtest.setXmlClasses(test.getXmlClasses());
                }
            }
            modifiedSuites.add(modifiedSuite);
        }
        inputStream.close();
        tng.setXmlSuites(modifiedSuites);
        tng.run();
    }
}


text:
Q: MySQL Create Table Error Syntax Hello i am having an issue when trying to create a table inside of my database webhostc_MyRadContactForm
When i try to execute the statement below in phpMyAdmin i get this error
CREATE TABLE Contacts (
-> ContactID INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
-> ContactName VARCHAR(100),
-> ContactEmail VARCHAR(100),
-> ContactLeastFavoriteColor VARCHAR(10)
-> ContactDateCreated DATETIME
-> );

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '-> ContactID INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
      -> ContactName VARCHA' at line 2

Also phpMyAdmin flags these lines:

My server is running: 10.0.22-MariaDB

A: You are missing a comma just after ContactLeastFavoriteColor VARCHAR(10) and those arrows, ->, are not supposed to be there. The following is the correct syntax for creating your table:
CREATE TABLE Contacts (
  ContactID INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
  ContactName VARCHAR(100),
  ContactEmail VARCHAR(100),
  ContactLeastFavoriteColor VARCHAR(10),
  ContactDateCreated DATETIME
);

Good luck!!

A: There are two problems:

*

*Those -> symbols aren't part of SQL syntax. They're the prompts that the MySQL monitor prints when you enter a multi-line query. You can't copy them into PhpMyAdmin.

*You're missing a comma at the end of the ContactLeastFavoriteColor line.


text:
Q: automatic session timeout iphone I am developing an Iphone app for which I need to perform the automatic logout in the background itself, i.e after the Home Button for Iphone is pressed.
I have tried the following code for session timeout which works well for desktop. but this solution doesn't work in the background for Iphone as I have to wait complete 10 seconds to get redirected to the desired page.

 try link
Hey there.. is this working fine?

Can someone give the solution for this?
Also the session timeout interval in the above code is not getting resetted on the Iphone as I am being redirected to the desired page even if I am tapping the screen. How can I solve this issue?

A: iPhone Sdk hangs all task after 5 sec when it enters in background. It will support background task if app supports multitasking like audio play location update. One solution i can give you that save the time when you enter into background as well as save the time when you come to foreground. If it calculates more than the time to log out then hit the service you want for that.

A: Maybe something like this?

 try link
Hey there.. is this working fine?

The idea is to compute the time elapsed since the last activity. iOS devices pause JS when the browser is in the background, and for good reason, in my opinion.

A: How about something like this...
NOTE: I have a couple of MVC Razor snippets that could be switched out with anything else.  I haven't tested this but it's a good start.  Non Safari iOS browsers will ignore the pageshow/pagehide event handlers so this is NOT a complete solution for mobile devices.  Please feel free to improve upon this for broader cross browser functionality.  Also, this solution requires the use of the JQuery cookie plugin:  https://github.com/carhartl/jquery-cookie
///////// Client-Side Code
    //Safari iOS example that could be further developed to handle other mobile browsers
    var sessTimeCutOffInMs = 600000;   //600000 ms equals 10 minutes

    //Safari iOS event handler for resume tab and/or focus from sleep mode
    window.addEventListener("pageshow", function(e){
        var timeIn = getTime();
        var timeOut = $.cookie('timeOut');
        if(timeOut != null) {
            //Let us compare
            compareTimes(timeIn,timeOut);
        }
    }, false);

    //Safari iOS event handler when creating new tab/app switching and/or putting into sleep mode
    window.addEventListener("pagehide", function(e){
        var timeOut = getTime();
        $.cookie('timeOut', timeOut, { path: '/' });

    }, false);

    function getTime() {
        @{
        //MVC Razor syntax
         //formatted as milliseconds since 01.01.1970
         var _serverTime = DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalMilliseconds.ToString("F0");
        }
        var serverTime = @_serverTime;
        return serverTime;
        //return (new Date()).getTime();
    }

    function compareTimes(timeIn,timeOut) {
        var diff = timeIn - timeOut;
        //If the mobile page was asleep for 10 minutes or more, force iOS user to logout
        //Especially useful for when forms auth is set to slidingExpiration=true
        if(diff >= sessTimeCutOffInMs) {
            //Redirect to logout routine
            //MVC Razor code shown below for redirecting to my Home Controller/Action
            simpleReset('@(Html.ResolveUrl("~/Home/SignOut"))');
        }
    }

    function simpleReset(url) {
        window.location.href = url;
    }

///////////// MVC 4 HomeController.cs code fragment for SignOut() Action
    [AllowAnonymous]
    public ActionResult SignOut()
    {
        try
        {
            ViewBag.Message = "You are signed out.";

            //DELETE SSO Cookie
            HttpCookie ssoCookie = new HttpCookie("SMSESSION", "NO");
            ssoCookie.Expires = DateTime.Now.AddYears(-1);
            ssoCookie.Domain = ".myDomain.com";      //IMPORTANT:  you must supply the domain here
            Response.Cookies.Add(ssoCookie);

            //Look for an existing authorization cookie and kill it
            HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
            authCookie.Value = null;
            authCookie = null;
            Response.Cookies.Remove(FormsAuthentication.FormsCookieName);

            // clear authentication cookie
            //Overriding the existing FormsAuthentication cookie with a new empty cookie ensures
            //that even if the client winds back their system clock, they will still not be able
            //to retrieve any user data from the cookie

            HttpCookie cookie1 = new HttpCookie(FormsAuthentication.FormsCookieName, "");
            cookie1.Path = FormsAuthentication.FormsCookiePath;
            cookie1.Expires = DateTime.Now.AddYears(-1);
            cookie1.HttpOnly = true;
            Response.Cookies.Add(cookie1);

            // clear session cookie
            HttpCookie cookie2 = new HttpCookie("ASP.NET_SessionId", "");
            cookie2.Expires = DateTime.Now.AddYears(-1);
            Response.Cookies.Add(cookie2);

            //Explicitly destroy roles object and session
            SimpleSessionHandler.myRoles = null;
            Session.Clear();
            Session.Abandon();

            // Invalidate the Cache on the Client Side
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            Response.Cache.SetNoStore();

            FormsAuthentication.SignOut();
        }
        catch (Exception ex) {
            //Swallow it
            Log.LogError("AUTH COOKIE ERROR: " + ex.Message, ex);
        }

        //The loginUrl on IWH is actually a LOGOUT page for the SSO cookie
        return Redirect(FormsAuthentication.LoginUrl);

    }


text:
Q: Out of memory matlab I'm trying to solve a large linear programming task and have large matrixes.
After
[x,fval,exitflag] = linprog(f,A,b,[],[],lb,[],[]);

Matlab says:
Error using builtin
Out of memory. Type HELP MEMORY for your options.
Error in lipsol (line 720)
Rinf = builtin('_cholinf',sparse(P(perm,perm)));
Error in linprog (line 272)
[x,fval,lambda,exitflag,output]
=lipsol(f,A,B,Aeq,Beq,lb,ub,options,defaultopt,computeLambda);

Answer to memory command:
Maximum possible array:     87 MB (9.088e+07 bytes) *
Memory available for all arrays:    877 MB (9.197e+08 bytes) **
Memory used by MATLAB:    650 MB (6.817e+08 bytes)
Physical Memory (RAM):   3057 MB (3.206e+09 bytes)

So what shall I do to increase my memory?
Win 7 x86, 4 Gb RAM

A: Here is the MATLAB page on increasing the memory used for a process: http://www.mathworks.com/help/matlab/matlab_prog/resolving-out-of-memory-errors.html. This is what they say specifically about Windows systems: "Use the Windows Control Panel to change the size of the virtual memory paging file on your system. For more information, refer to the Windows help."


text:
Q: Cannot trigger Azure data factory pipeline on blob creation I want to trigger a data factory pipeline when a blob is created.
Following the article here, I am getting an error.
I have enabled EventGrid and DataFactory on the subscription. The data factory is set to Owner role for the entire storage account (using the new RBAC interface where you dont enter the managed object id, you just browse the names of your resources). Nothing has been done to the container level security. For storage account settings, under Firewalls and Virtual Networks, it is set to allow access from All Networks. I don't have any vnets or other virtual networking constructs defined in the resource group.
In the same data factory, I can create data sets that point to the same container, and can test connection and browse data just fine. But when trying to create the trigger, I am seeing this:
"Unable to list files and show data preview (...)"
error in data preview pane
I am the person who created the resource group and all of these resources. All resources are created in the same region (US Central.) Everything has been done through the Azure portal.


text:
Q: $X=\{f\in C[0,1]|f(0)=0\}$ is closed Let $$X=\{f\in C[0,1]|f(0)=0\}$$ with the sup norm. I have to show that this is a closed space, but if we define
$$f_n(x)=\begin{cases}1  & x\geq 1/n \\
nx & 0\leq x \leq 1/n \end{cases}
$$
$$\lim_{n \to \infty}f_n =\begin{cases}1& x\neq 0 \\
0& x=0 \end{cases}
 $$
where is my mistake?

A: An idea (hint): observe that
$$X=\Phi^{-1}\{0\}\;,\;\;\text{where}\;\;\Phi:C[0,1]\to\Bbb R\;\;\text{ is defined as}\;\;\Phi(g):=g(0)$$

A: Note that your example is not valid.
Say $f_n(x)$ converges to $f$. This implies for every $\epsilon>0$ there exists $N\in \mathbb{N}$ such that $||f_n(x)-f(x)||<\epsilon$ for all $n\geq N$.
Now note that in the sup norm  $||f_n(x)-f(x)||$= Supremum over all $x$ of $|f_n(x)-f(x)|$, which always equals $1$ irrespective of the value of $n$(Why?), hence for $\epsilon=1/2$ the condition of convergence will fail, hence the sequence of functions you defined does not convege to the function you thought it would.
I hope you understood your mistake.


text:
Q: IIS 7.5 App Pool write permissions denied I have a web application that is running on IIS 7.5 and is having some permission issues. The site will read/serve files, but will not write to any file location under any circumstances.  Ideally, I'd be writing to a non-local share, but I'm currently just trying to get the application to write to a local share/drive.  I've tried setting the identity to a domain service account set up specifically for this application, the built in Network Service account, and the ApplicationPoolIdentity with no luck.  It may be worth mentioning that this server is a virtualized instance running on shared hardware with other servers.
In order to try and grasp the issue, I have granted full control to:
(MACHINE NAME)
(MACHINE NAME)\Users
(MACHINE NAME)\IUSR
(MACHINE NAME)\IIS_IUSRS
(DOMAIN NAME)\(MACHINE NAME)
NT AUTHORITY\NETWORK SERVICE
NT AUTHORITY\SYSTEM
(APPLICATION POOL IDENTITY)
(DOMAIN NAME)\(SERVICE ACCOUNT NAME)

I have manually verified that all these accounts/groups have full control on the security tab of the file/folder.
The app pool is running under the .NET Framework v4.0 on the Integrated Managed Pipeline.  I've tried it with Load User Profile set to both true and false with no luck.  The site itself is set to application pass-through authentication.
The error thrown in the browser is:
Access to the path 'D:\Dataload\LOG.txt' is denied.

[UnauthorizedAccessException: Access to the path 'D:\Dataload\LOG.txt' is denied.]

I've tried writing to that file with it already created as well as not created.  I've also tried calling the file by its server path instead of the drive name.
Viewing the event in Microsoft's Process Monitor:
Operation: CreateFile
Result: ACCESS DENIED
Desired Access: Generic Write, Read Attributes
Disposition: OpenIF
Options:Sequential Access, Synchronous IO Non-Alert, Non-Directory File, Open No Recall
Attributes:n/a
ShareMode: Read
User:NT AUTHORITY\NETWORK SERVICE (this will correctly change depending on the identity I set)

Is there something I am missing with groups or accounts, or possibly an IIS setting I could be overlooking that prevents write access?

A: I figured out the answer to this a while back and forgot about my post here.  In this particular instance, the problem was with the Internet Explorer Enhanced Security Configuration settings on the server.  In order to see your settings in Windows Server 2008 R2, go to the Server Manager and have your view on the main page.  Once there, go down to the Security Settings section.  Here you will see an item called IE Enhanced Security Configuration (ESC), and next to it it's current settings for both administrators and users.  In my case, the default settings on this fresh server were set to On for both administrators and users.  Setting these to Off allowed the network service account to write to all locations it had been granted proper permissions to, thus solving the problem.


text:
Q: JavaCC lexical error on any type of whitespace I cleary have the unicode whitespace characters defined in my SKIP token like so:
    SKIP {
" "
| "\r"
| "\n"
| "\t"

}

However, when I run Java CC it parses all the tokens fine until I hit any of the above mentioning white space characters and it throws the following error:
Exception in thread "main" prjct1.TokenMgrError: Lexical error at line 1, column 25.  Encountered: "\r" (13), after : "Random:Word:Here"

So as you can see it runs fine until it hits the "\r". I get the same error with " ", "\n", and "\t". Any thoughts? thanks

A: Make sure you have a colon between the SKIP and your bracket.
SKIP: {
    " "
|   "foo"
|   "bar"
}

A: I had similar problem. Check your quotes. Are they neutral quotes such as " or left/right double  quotes"?
I had double quotes, after making them neutral quote, this error was gone.


text:
Q: Using the same instance of an object as the argument and as the calling object in calling a function I wrote a small program for an assignment in an object-oriented C++ class in which I had to write a function which displayed the magnitude of a complex number. It works when written this way and I know how to write it without arguments in the parameter, but I want to know if there is a functional problem with the code (the calling object and the argument are the same object).
// displays the magnitude of a complex number
void Complex::magnitude(Complex c) const {
    cout << "\nMagnitude of "; c.display(); cout << " = ";

cout.precision(3); cout.setf(std::ios::fixed, std::ios::floatfield);
cout << sqrt(pow(static_cast<double>(c.real), 2) +
            (pow(static_cast<double>(c.imag), 2)) ) << "\n";
} // end function magnitude

Here's the redundant part with c1 as the calling object and argument:
c1.magnitude(c1);

I know how to write this code without c1 as an argument for magnitude() and that all I have to do is delete the argument and delete "c." from the function and it will still work the same. My question is simply Is this be a problem functionally when a program is written like this?

A: Your code makes syntactically no sense. Either use a member function taking no argument, or a free-standing function with argument (or both).
namespace My {
  struct Complex {
    void magnitude() const;  // member function
     ...
  };
  void magnitude(Complex const&); // free-standing function
}

These can be used like this
My::Complex c1;
c1.magnitude();
magnitude(c1);

(However, using the name magnitude for a function not returning the magnitude is dangerous and therefore bad practice, better call it print_magnitude_to_stdout().)

A: This will not be a problem functionally, but logically if the function must take an object as an argument, you should make this function static.
In addition, since you are not modifying the incoming object, you should make the argument const. Finally, since copying the object may be more expensive than copying a reference, you may want to change the argument to be passed by reference.
static void Complex::magnitude(const Complex &c);

...

Complex myComplex(...);
Complex::magnitude(myComplex);

A: Functionally your code is OK, with one caveat: your function takes its argument by value, and therefore relies on the copy constructor. If the copy ctor is fine, your code is fine; otherwise, it may not be.
Stylistically, I find this code objectionable. It should either be a parameterless member function, or a one-argument static function (taking its argument by const reference).


text:
Q: На чем лучше писать сайт? Логистика.
Цель проекта: догружать наши машины грузом сторонних контрагентов, с последующей разгрузкой в торговых точках по маршруту следования.
Цель сайта: предоставить контрагентам возможность выбора маршрута и оформления заявки на перевозку.
Структура данных будет продиктована 1С- разработчиками. Работа в 1С первична: расписание маршрутов, объём свободного места в машине на маршруте - определяются сервером 1С. На плечи сайта ложится управление авторизацией пользователей, калькуляция для пользователя стоимости отправки по маршрутам заданного количества продукции, доступ в личный кабинет с историей заявок.
Не могу определиться, какая cms лучше или все-таки писать вручную. Прошу совета знатоков


text:
Q: Schema for pyarrow.ParquetDataset > partition columns
*

*I have a pandas DataFrame:

import pandas as pd

df = pd.DataFrame(data={"col1": [1, 2], "col2": [3.0, 4.0], "col3": ["foo", "bar"]})

*Using s3fs:

from s3fs import S3FileSystem

s3fs = S3FileSystem(**kwargs)

*I can write this as a parquet dataset

import pyarrow as pa
import pyarrow.parquet as pq

tbl = pa.Table.from_pandas(df)
root_path = "../parquet_dataset/foo"

pq.write_to_dataset(
    table=tbl,
    root_path=root_path,
    filesystem=s3fs,
    partition_cols=["col3"],
    partition_filename_cb=lambda _: "data.parquet",
)

*Later, I need the pq.ParquetSchema for the dumped DataFrame.

import pyarrow as pa
import pyarrow.parquet as pq

dataset = pq.ParquetDataset(root_path, filesystem=s3fs)
schema = dataset.schema

However parquet dataset -> "schema" does not include partition cols schema.
How do I get the schema for the partition columns?

A: I think you need give ParquetDataset a hint of the partition keys schema.
partition_schema = pa.schema([pa.field('col3', pa.string())])
partitioning = pa.dataset.partitioning(schema=partition_schema)

partitionaldataset = pq.ParquetDataset(
    root_path,
    partitioning=partitioning,
)

Which gives you this schema:
col1: int64
col2: double
col3: string

PS: I couldn't completely reproduce your example (I don't have access to S3) and I had to add use_legacy_dataset=False when writing and reading the dataset.

A: Turns out I have to explicitly dump "metadata".
table = pa.Table.from_pandas(df)
pq.write_to_dataset(
    table=table,
    root_path=path,
    filesystem=s3fs,
    partition_cols=partition_cols,
    partition_filename_cb=lambda _: "data.parquet",
)

# Write metadata-only Parquet file from schema
pq.write_metadata(
    schema=table.schema, where=path + "/_common_metadata", filesystem=s3fs
)

Docs https://arrow.apache.org/docs/python/parquet.html#writing-metadata-and-common-medata-files
I only care about the "common metadata" but you can dump row stats.


text:
Q: Change action menu text color and reduce spacing toolbar android? I am using the toolbar with navigation view for side menu
I also have 2 action menu items of which one denotes a numeric value and other is an image.
I need to reduce the spacing between those 2 menuitems and also change the color of the item text.

This is my activity XML
<?xml version="1.0" encoding="utf-8"?>

<android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/AppTheme.AppBarOverlay">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:popupTheme="@style/AppTheme.PopupOverlay"
        app:titleTextAppearance="@style/AppTheme.Toolbar.Title">

    </android.support.v7.widget.Toolbar>

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

<include layout="@layout/content_main" />

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

This is theme file
<resources>

<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>

</style>

<style name="AppTheme.NoActionBar">
    <item name="windowActionBar">false</item>
    <item name="windowNoTitle">true</item>
</style>

<style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" />

<style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light">
    <!-- Customize color of navigation drawer icon and back arrow -->
    <item name="colorControlNormal">@android:color/black</item>
    <item name="android:actionButtonStyle">@style/ActionButtonStyle</item>
    <item name="android:actionMenuTextColor">@android:color/black</item>
</style>

<style name="AppTheme.Toolbar.Title" parent="TextAppearance.Widget.AppCompat.Toolbar.Title">
    <!-- Set proper title size -->
    <item name="android:textSize">@dimen/abc_text_size_title_material_toolbar</item>
    <!-- Set title color -->
    <item name="android:textColor">@android:color/black</item>

</style>

<style name="ActionButtonStyle" parent="@android:style/Widget.Holo.Light.ActionButton">
    <item name="android:minWidth">0dip</item>
    <item name="android:paddingLeft">0dip</item>
    <item name="android:paddingRight">0dip</item>
</style>

This is the menu file
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
    android:id="@+id/lollyMenu"
    android:icon="@drawable/jar"
    android:orderInCategory="101"
    android:title=""
    app:showAsAction="always" />
<item
    android:id="@+id/Amt"
    android:orderInCategory="100"
    android:title="0"
    app:showAsAction="always" />
 </menu>

A: You can try negative margin and textColor:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
    android:id="@+id/lollyMenu"
    android:icon="@drawable/jar"
    android:orderInCategory="101"
    android:title=""
    app:showAsAction="always" />
<item
    android:id="@+id/Amt"
    android:orderInCategory="100"
    android:title="0"
    android:textColor="#fff"
    app:showAsAction="always"
    android:layout_marginRight="-10dp" />
 </menu>


text:
Q: how can I read the logging for odoo enterprise 14 installed on ubuntu 20 I'm developing a custom module for odoo and suddenly got this error:
Internal Server Error
The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.
And I don't know how to find the problem
I'm using odoo enterprise 14 installed on ubuntu 20
Please I need a way to understand what happen

A: You can read the status of the odoo service and will tell you the output of the logfile.
Try
sudo service odoo status

or
sudo service odoo-server status

The output will show the location of the log file.