text:
Q: How to filter nested Lists and Maps in scala I am trying to read a json file in order to calculate some metrics in scala. I managed to read the file and to conduct some outer filters but I have troubles understanding how to filter nested lists and maps.
Here is an example code (the real json is longer):
  val rawData = """[
  {
    "technology": "C",
    "users": [
    {
      "rating": 5,
      "completed": false,
      "user": {
        "id": 11111,
        "paid": true
      }
    },
    {
      "rating": 4,
      "completed": false,
      "user": {
        "id": 22222,
        "paid": false
      }
    }
    ],
    "title": "CS50"
  },
  {
    "technology": "C++",
    "users": [
    {
      "rating": 3,
      "completed": true,
      "user": {
        "id": 33333,
        "paid": false
      }
    },
    {
      "rating": 5,
      "completed": true,
      "user": {
        "id": 44444,
        "paid": false
      }
    }
    ],
    "title": "Introduction to C++"
  },
  {
    "technology": "Haskell",
    "users": [
    {
      "rating": 5,
      "completed": false,
      "user": {
        "id": 55555,
        "paid": false
      }
    },
    {
      "rating": null,
      "completed": true,
      "user": {
        "id": 66666,
        "paid": false
      }
    }
    ],
    "title": "Course on Haskell"
  }
  ]"""

  val data = rawData.toString.split("\n").toSeq.map(_.trim).filter(_ != "").mkString("")

I managed to get a list containing the 3 titles:
import scala.util.parsing.json._
val parsedData = JSON.parseFull(data)
val listTitles = parsedData.get.asInstanceOf[List[Map[String, Any]]].map( { case e: Map[String, Any] => e("title").toString }  )

Here are my 3 questions:

*

*Is that a good approach to obtain the list of the 3 titles?

*How to obtain a List containing the number of paid users for each of
the latter 3 titles?

*How to obtain a List containing the number of users who have
completed the course for each of the latter 3 titles?

Thanks in advance for the help

A: As the other answer suggested, you should use the play-json library. It's really powerful and has tons of features including object mapping and parsing and error handling.
  import play.api.libs.json._
  import play.api.data.validation.ValidationError

  case class User(id: String, paid: Boolean)
  object User {
    implicit val format: OFormat[User] = Json.format[User]
  }

  case class UserCourseStat(rating: Int, completed: Boolean, user: User)
  object UserCourseStat {
    implicit val format: OFormat[UserCourseStat] = Json.format[UserCourseStat]
  }

  case class Data(technology: String, title: String, users: List[UserCourseStat])
  object Data {
    implicit val format: OFormat[Data] = Json.format[Data]
  }

  val jsString = """[{"technology":"C","users":[{"rating":5,"completed":false,"user":{"id":11111,"paid":true}},{"rating":4,"completed":false,"user":{"id":22222,"paid":false}}],"title":"CS50"},{"technology":"C++","users":[{"rating":3,"completed":true,"user":{"id":33333,"paid":false}},{"rating":5,"completed":true,"user":{"id":44444,"paid":false}}],"title":"Introduction to C++"},{"technology":"Haskell","users":[{"rating":5,"completed":false,"user":{"id":55555,"paid":false}},{"rating":null,"completed":true,"user":{"id":66666,"paid":false}}],"title":"Course on Haskell"}]"""

  val rowData: JsValue = Json.parse(jsString)

  rowData.validate[List[Data]] match {
    case JsSuccess(dataList: List[Data], _) =>
      val chosenTitles = List("Course on Haskell", "Introduction to C++", "CS50")

      //map of each chosen title to sequence of it's users
      val chosenTitleToUsersMap = chosenTitles.map { title =>
        title -> dataList.filter(_.title == title)
          .flatMap(_.users.map(_.user))
          .toSet
      }.toMap
      //map of each chosen title to sequence of it's paid users
      val chosenTitleToPaidUsersMap = chosenTitleToUsersMap.map { case (title, users) =>
        title -> users.filter(_.paid)
      }

      //Calculate users who have completed each of the chosen title
      val allUsers = dataList.flatMap(_.users.map(_.user)).toSet

      val usersWhoCompletedAllChosenTitles = allUsers.filter{ user =>
        chosenTitles.forall { title =>
          chosenTitleToUsersMap.get(title).flatten.contains(user)
        }
      }

    case JsError(errors: Seq[(JsPath, Seq[ValidationError])]) =>
      //handle the error case
      ???
  }

Regarding the 3 questions you had:

*

*Is that a good approach to obtain the list of the 3 titles?

I can see 2 unsafe operations there, asInstanceOf and e("title"), latter one is because of not using the .get(key) method of the Map, it will throw and exception if key not found.

*How to obtain a List containing the number of paid users for each of the latter 3 titles?

Evaluated above in val named "chosenTitleToPaidUsersMap"

*How to obtain a List containing the number of users who have completed the course for each of the latter 3 titles?

Evaluated above in val named "usersWhoCompletedAllChosenTitles"

A: You can use play-json library to parse and retrieve the field you want. For example:
import play.api.libs.json.Json

val rawData1 = Json.parse("""[{"technology":"C","users":[{"rating":5,"completed":false,"user":{"id":11111,"paid":true}},{"rating":4,"completed":false,"user":{"id":22222,"paid":false}}],"title":"CS50"},{"technology":"C++","users":[{"rating":3,"completed":true,"user":{"id":33333,"paid":false}},{"rating":5,"completed":true,"user":{"id":44444,"paid":false}}],"title":"Introduction to C++"},{"technology":"Haskell","users":[{"rating":5,"completed":false,"user":{"id":55555,"paid":false}},{"rating":null,"completed":true,"user":{"id":66666,"paid":false}}],"title":"Course on Haskell"}]""")

val resultedList = (rawData1 \\ "title").toList.map(_.as[String])

A: I suggest you use the json4s library. It allows you to extract your data into case classes:
import org.json4s.jackson.JsonMethods.parseOpt
import org.json4s.DefaultFormats
implicit val formats = DefaultFormats

case class Tech(technology: String, users: Seq[TechUser], title: String)
case class TechUser(rating: Option[Int], completed: Boolean, user: UserInfo)
case class UserInfo(id: Int, paid: Boolean)

val rawData = """..."""
val Some(json) = parseOpt(rawData)
val Some(data) = json.extractOpt[List[Tech]]

After doing this, data is a regular Scala data structure that you can manipulate as you wish. For example, if you want to find for which title there is a user whose id is divisible by 5, it's done like this:
data.find(_.users.exists(_.user.id % 5 == 0)).map(_.title)
// Result: Some("Course on Haskell")

The answers to your three questions are one-liners just like this one, but I leave them to you as an exercise.


text: Q: How to tell VSCode to display a notification I want to tell VSCode to display a notification. I want to ping VSCode from another process running on the same machine. Is VSCode listening on localhost? Is there a way to send VSCode a payload and have VSCode display that payload in the IDE as a notification? I am looking for docs on this and it's hard to find.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Connect Crystal Report with DataSet I have a problem when I want to connect Crystal Report with DataSet in c#.

Error
failed to load database information, details: unable to load database connector 'crdb_adoplus.dll'. the correct version of the database client for this type of database may not be installed.

Here's a Screenshot
Can you help me please?

A: I had the same problem on Microsoft Visual studio 2019 by installing SP26 "SAP Crystal Reports runtime engine for .NET Framework (64-bit)" before "SAP Crystal Reports, version for Microsoft Studio".
The main problem is that the run-time engine doesn't copy crdb_adoplus.dll file which need to Crystal Report to load data from ADO.Net dataset.
If you also followed my installation sequence, you must:

*

*Remove "SAP Crystal Reports runtime engine for .NET Framework (XX-bit)" and "SAP Crystal Reports, version for Microsoft Studio" by the control panel.

*Run the "SAP Crystal Reports, version for Microsoft Studio" installer as Administrator. After the installation, it will automatically ask you to install the correct engine.

See also:
Crystal Report SP26 SetDataSource() Method failed in computers of clients in Visual Studio 2019

A: We are using Crystal Report's on 20+ server and we always install x32 and x64bit version.Today i installed SP30 from here for VS2019 https://www.tektutorialshub.com/crystal-reports/download-crystal-reports-for-visual-studio-2019/ , also today i tried to add a field to dataset and gave me 'crdb_adoplus.dll' error. After a lot of search, i installed x32 bit runtime both x64bit, it worked.

A: I had the same problem.
I uninstalled all crystal reports (for visual studio and runtime) and install only the version for Visual Studio and installed the runtime checking the last checkbox on the installation wizard (to install the correct runtime).
I think that when installing on top of an existing crystal some files are missing.


text:
Q: MVC bundles for remote CDN and local files I am currently using MVC 4 and I have ran into a limitation of the bundling I was hoping someone could help me with. I want to include both CDN delivered assets as well as local scripts in bundles. The problem is, that RegisterBundles(BundleCollection bundles) is a static method that accepts a static object as a parameter. Once I set useCDN and enableOptimizations to true, I can't debug and step through my local javascript anymore because it gets minified. Here is what I have so far:
public class BundleConfig
{

    public static void RegisterBundles(BundleCollection bundles)
    {
        // allow URLs in bundle declaration
        BundleTable.EnableOptimizations = true;
        bundles.UseCdn = true;

        string asset1= "/assets/javascript/framework/asset1/asset1.min.js";
        bundles.Add(new ScriptBundle("~/asset1", assembleBundleURL(asset1)));

        string asset2= "/assets/javascript/framework/asset2/asset2.mobile-1.3.1.min.js";
        bundles.Add(new ScriptBundle("~/asset2", assembleBundleURL(asset2)));

        bundles.Add(new ScriptBundle("~/bundles/myApp").Include(
            "~/Scripts/myApp/myApp1.js",
            "~/Scripts/myApp/myApp2.js",
            "~/Scripts/myApp/myApp3.js",
            "~/Scripts/myApp/myApp4.js"));
    }

    internal static string assembleBundleURL(string asset)
    {
        if (ConfigurationManager.AppSettings["externalWebAssetsHost"] == null)
            throw new Exception("externalWebAssetsHost url is required in web.config");

        string host = ConfigurationManager.AppSettings["externalWebAssetsHost"].ToString();
        string protocol = "https://";
        return protocol + host + asset;
    }

}

I want to include the CDN urls here through the bundling because it allows me to use web.config transforms to specify different URLs for my different environments. Otherwise I would just specifically include the CDN urls in the HTML and be done with it. The CDN assets I want to include are other in-house javascript libraries for common functionality and I don't want to include these in-house assets locally because it could become a versioning issue.
Is there a way to have two RegisterBundles methods that write to two separate BundleTables?
Or is there a way to have the bundling be instance driven instead of static so that for every differently sourced bundle (cdn or local) you can have different properties on the BundleTable class? In the end I want to be able to run my app locally in debug mode and be able to step through the javascript of my local files, but still pull in minified references from CDNs.
EDIT
If I set EnableOptimizations to false and remove the "min" from the asset filename, the bundles are still not rendered to the HTML in DEBUG mode. It seems like EnableOptimizations must be true if UseCdn is true.
UPDATE
I understand why the above code doesn't allow me to step into my javascript in debug mode. My question is: Is there a way to have more than one BundleTable class? Can the framework be extended to allow this instead of the static methods?

A: enableOptimizations explicitly allows bundling and minification in development. If that's not what you want, then turn it off.


text:
Q: Polymorphic behavior in java I have following java code,
interface A {
    int a = 5;
}

class B {
    int a = 6;
}

public class C extends B implements A {
    int b = super.a;//Line 10
    public static void main(String[] a) {
        System.out.println(new C().b);//6

    }
}

I was expecting compiler error at line 10 because compiler will not know which "a" to refer. But there was no compiler error. Output is 6. Can someone explain  how it takes class B 's instance variable value(6) why not interface A's "a" value which is 5?.

A: super keyword is used to refer to the parent class which in this case is B. Hence you get output as 6.
a defined in interface A is static and a defined in Class B is an instance variable. Hence when we do super.a, it refers to the instance value of a which is defined in the Class B
If you rename the variable in B say as aa, you will get compiler error saying a cannot be resolved or is not a field because a defined in interface A is not directly accessible in class C, because it is by default static. To access a defined in interface A, we need to make an explicit call to A.a in class C
If you define, a as static in class B, and remove super, you will get compiler error: The field a is ambiguous


text:
Q: Maximal chains in vector space and its dimension Let $L$ be the vector space without other structures (topology and so on) over some field. We consider the chains (i.e. linearly ordered sets) of vector subspaces in $L$ (such chain is called a flag). The question is the following: is it true, that the cardinal number of the maximal chain (that can be built with Zorn's lemma) is $\dim(L)$?
The answer is obviously 'yes' if $L$ is finite dimensional. What about the infinite case?

A: The way you ask your question is quite confusing: typically "chain" means a well ordered set. In this case the answer is ${\bf YES}$. More precisely - you don't have the "maximal chain" but still each chain has cardinality not exceeding $dim(V)$: having a chain $V_\alpha$ you obtain a linearly independent sequence $v_\alpha\in V_{\alpha+1}\setminus V_\alpha$.
However you wrote "linearly ordered sets". In this case the answer is ${\bf NO}$: Let $V$ be a verctor space with basis $\mathbb{Q}$ and for every $r\in\mathbb{R}$ take $V_r=\mathop{\rm span} \{q \mid q< r  \}$.


text:
Q: How to have full citation in both references and footnote? I want my citations to both appear in the reference page, and in the footnotes of each page as a full citation. I can do \footfullcite after each citation manually to achieve the result, but then I have 60 citations to type in. is there a more convenient way to achieve what I want?
I have tried doing the verbose style and lipsum trick. However the resulting reference page is not in the ieee style that I want.
Thanks very much for your time. Just started using latex and finding it extremely helpful. and confusing at the same time
\usepackage[backend=bibtex,sorting=none,citestyle=ieee]{biblatex}
\addbibresource{ref.bib}
\begin{document}

free text free text free tex \cite{ref1}. free text free text \cite{ref3} \cite{ref4}.

\pagebreak
\printbibliography
\end{document}

A: Redefine the guts of \cite to do both what \cite used to do and \footfullcite:
\documentclass{article}

\usepackage[backend=bibtex,sorting=none,citestyle=ieee]{biblatex}

\makeatletter
\let\oldblx@cite@cite\blx@cite@cite
\def\blx@cite@cite#1#2#3#4{%
   \oldblx@cite@cite{#1}{#2}{#3}{#4}%
   \blx@cite@footfullcite{#1}{#2}{#3}{#4}%
}
\makeatother

\addbibresource{ref.bib}
\begin{document}

free text free text free tex \cite{ref1}. free text free text \cite{ref3} \cite{ref4}.

\pagebreak
\printbibliography
\end{document}


text:
Q: What are real life examples of the arc augmentation problem in tournaments, semicomplete digraphs or locally semicomplete digraphs? Suppose we have a digraph $G=(V,A)$ that is not yet $k$-strong. Assuming parallel arcs are not allowed, as long as $|V|\geq k+1$ we can always add a number of arcs to $A$ to make $G$ $k$-strong. Denote by $m_k(G)$ the smallest amount of arcs we must add in order to make $G$ $k$-strong.
What are relevant real life examples where this problem must be solved? In particular, can you, off the top of your heads, think of any relevant examples where this problem must be solved and the graph in question is either a tournament, a semicomplete digraph or a locally semicomplete digraph?
I hope this question does not break the rules of this forum. The reason I ask it is because I'm about to apply for a PhD grant at my university. I wrote my master's thesis on semicomplete digraphs, and while I find the work highly interesting for the theory itself, I'm not sure how to motivate someone who doesn't share my excitement for this type of graph. I want to better justify my project's relevance than by the cliché that "problems are intrinsically interesting".
Thanks in advance!


text:
Q: Angular2 styling issues caused by DOM attributes _ngcontent-* vs. _nghost-* I have an issue with scss and the cli: angular adds an attribute _nghost-fyw-1 to the apps tag (component) during runtime. at the same time it adds an attribute selector to my css called _ngcontent-fyw-1 which of course won't work.
Do you have an idea how i could change this behavior/ avoid it?
PS: it also applies to regular css.
my components .scss file looks like this:
my-comp {
  h1 {
    background-color: red;
  }
}

A: Well,
I found the answer myself. Using the default settings, you must not supply the wrapping my-comp element selector in the components css.
Instead use the * element selector to affect all elements nested in my-comp. Otherwise, angular will treat the my-comp selector as an additional element and thus add the _ng-content-* attribute, which of course is not present in the DOM.
Another option is to disable ViewEncapsulation for your component - be aware that it just affects the component my-comp
import {Component, ViewEncapsulation} from 'angular2/core'

@Component({
  selector: 'my-comp',
  encapsulation: ViewEncapsulation.None,
  ...
});

https://egghead.io/lessons/angular-2-controlling-how-styles-are-shared-with-view-encapsulation explains the three different settings modes perfectly.

A: update
It's ::ng-deep since a while.
See also the comments below.
original
You didn't provide too much details where you add your styles and what elements you target with the selectors.
The "official" way if you want styles to cross element boundaries is to use >>> like
:host >>> h1 {
  background-color: red;
}

*

*:host targets the current element.

*>>> (or /deep/) makes Angular ignore _nghost-xxx attributes which is used for component style encapsulation emulation.

See also Styles in component for D3.js do not show in angular 2

A: ::ng-deep works for me, adding into app.component.scss:
:host ::ng-deep .mat-card {
    background: #000 !important;
    color: #fff;
}

The documentation (https://angular.io/guide/component-styles) says:

The shadow-piercing descendant combinator is deprecated and support is
  being removed from major browsers and tools. As such we plan to drop
  support in Angular (for all 3 of /deep/, >>> and ::ng-deep). Until
  then ::ng-deep should be preferred for a broader compatibility with
  the tools.

Use it, with precaution...


text:
Q: Terminal is stuck after git push After I've pushed my code the terminal is stuck and only a blank line is displayed. It doesn't show any error. When I try to close terminal it shows processes are running. I don't know what happens. This is the third time I've pushed my code. It just worked at previews times. Everything has been set at first time push.

A: Try running git in verbose mode. run git push -v to have an idea of what's happening in your terminal.

A: Check the following possible options:

*

*$ git remote show origin
If it shows the URL as git://, try pushing to git using http://. Might be the case that the router is blocking the port.

*Check your SSH config (~/.ssh/config)

*See if your origin is directed to the correct URL (git remote -v) and that you have write access. Command: git gc

*Might be an issue with the Repo Hosting provider.

*Try this:
git config --global core.askpass "git-gui--askpass"
The prompt may ask for login credentials. If there is any error, check
git-gui--askpass: No such file or directory.


text:
Q: How to solve the problem, related to the lack of visibility of the bean? I'm writing an api in which I wanted to check the performance of the registration, while the application does not want to start because it does not see Bean -> PasswordEncoder.
Do you have any idea what I can do to make it work?
Problem:

Parameter 0 of constructor in com.example.socialplatform.service.AuthorizationService required a bean of type 'org.springframework.security.crypto.password.PasswordEncoder' that could not be found.
Consider defining a bean of type 'org.springframework.security.crypto.password.PasswordEncoder' in your configuration.`

My classes:
SecuritySettings
@EnableWebSecurity
public class SecuritySettings extends WebSecurityConfigurerAdapter {
/* base class security, provides all the default security configuration
which i can override and customize */

    @Override
    public void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity.csrf().disable()
                .authorizeRequests()
                .antMatchers("/api/authorization/**")
                .permitAll()
                .anyRequest()
                .authenticated();
    }

    @Bean
    public PasswordEncoder encoder() {
        return new BCryptPasswordEncoder();
    }
}

I tried rebuilding the project, and maven.

A: If this is a Spring Boot project, one easy way to fix the issue is to put this class under the same package as your main class. It works because the @SpringBootApplication implies the @Configuration and @ComponentScan annotations.
If this is not a SpringBoot project, you have to put the bean in the configuration class. This is a class annotated with @Configuration.


text:
Q: What is the difference between SHGO and Nevergrad optimization technique? I am currently trying to find some use cases to differentiate between the two optimization techniques i.e. Nevergrad (PSO) and SHGO. or which is more useful.
Please help me with this..


text:
Q: C++ Unable to populate a map of C arrays typedef std::map<std::string,int> string2intMap;
typedef string2intMap arrOfMaps[3] ;

//map : string --> array of maps of <std::string,int>
std::map<std::string,arrOfMaps> tryingStuff;

//map : string --> int
string2intMap s;
s["key"]= 100;

tryingStuff["hello"][0] = s;

The above code does not compile, the problematic line is :
tryingStuff["hello"][0] = s;
here is what the compiler shouts :
c:\program files (x86)\microsoft visual studio 10.0\vc\include\map(215): error C2440: '<function-style-cast>' : cannot convert from 'int' to 'std::map<_Kty,_Ty> [3]'
2>          with
2>          [
2>              _Kty=std::string,
2>              _Ty=int
2>          ]
2>          There are no conversions to array types, although there are conversions to references or pointers to arrays
2>          c:\program files (x86)\microsoft visual studio 10.0\vc\include\map(210) : while compiling class template member function 'std::map<_Kty,_Ty> (&std::map<_Kty,arrOfMaps>::operator [](const std::basic_string<_Elem,_Traits,_Ax> &))[3]'
2>          with
2>          [
2>              _Kty=std::string,
2>              _Ty=int,
2>              _Elem=char,
2>              _Traits=std::char_traits<char>,
2>              _Ax=std::allocator<char>
2>          ]
2>          c:\work\toot\tootcode\tootim\tools\doobim\doobim.cpp(95) : see reference to class template instantiation 'std::map<_Kty,_Ty>' being compiled
2>          with
2>          [
2>              _Kty=std::string,
2>              _Ty=arrOfMaps
2>          ]
2>
2>Build FAILED.
2>
2>Time Elapsed 00:00:01.38
========== Build: 1 succeeded, 1 failed, 5 up-to-date, 0 skipped ==========

Any idea how to make it work??
 (I don't want to change the data structure which is a
map : string --> array of maps of  )

A: You cannot store C-style arrays in containers because they are not assignable; you cannot do this:
int x[3] = { 0, 1, 2 };
int y[3] = { 3, 4, 5 };

x = y;

But containers need to be able to assign/copy the elements that they're storing.
Consider using a std::vector or a boost::array* instead of a raw C array.

* This can be found as std::array in more recent revisions of the C++ standard.

A: Basically array are not copyable.
What you want to use was a vector...
typedef std::map<std::string,int>  string2intMap;
typedef std::vector<string2intMap> arrOfMaps;

//map : string --> array of maps of <std::string,int>
std::map<std::string,arrOfMaps>    tryingStuff;

//map : string --> int
string2intMap s;
s["key"]= 100;

tryingStuff["hello"].push_back(s);


text:
Q: Python for loop ignoring if statement For some reason python is ignoring my if statement, even if the str(search) is in my list lista it still prints the elif statement regardless.
Am I doing something wrong?
search = input("what would you like to search for?:")
    for n in range(len(lista)):
         if str(search) in lista[n]:
             print(lista[n])
         elif str(search) not in lista[n]:
             print("search not found in list")
             break

A: Your elif will end the loop (because of the break) if the search wasn't found at the first position (because the if and elif are executed for each item in your list). In your case you could simply use a "trigger" to indicate at least one finding and do the if after the loop:
found = False
for n in range(len(lista)):
     if str(search) in lista[n]:
         print(lista[n])
         found = True
if not found:
     print("search not found in list")

However better would be to iterate over the list directly instead of a range of the length:
found = False
for item in lista:
     if str(search) in item:
         print(item)
         found = True
if not found:
     print("search not found in list")

If you don't like the trigger you can also use a conditional comprehension to get all the matches and use the number of matches as indirect trigger:
findings = [item for item in lista if str(search) in item]
if findings:  # you got matches:
    for match in findings:
        print(match)
else:         # no matches
     print("search not found in list")


text:
Q: Should the service in an MVC app return entities or list of entities I've a MVC application with Spring and Hibernate
I've each controller calling the service layer that call the dao
controller > service > dao

Should the service always return an entities?
I was trying to move the logic from the controller to the service. At the moment this is the logic in the controller
autenticate

retrieve user information (service call)

retrieve his appointments (other service call)

create a status response in xml

return appointemnts

As you can see if I move all the logic in the service I would need a service call that return an xml instead of a user or a list of appointemts.
Is this the right way or I should keep the logic in the controller and return from the service only entities?

A: As far as I understand it, I think that is immaterial to you.  What you must remember is

*

*To keep your service layer clean of data access implementations (for example: an import java.sql.whatever would be a bad idea inside your service layer)

*The service layer is the ideal place to put your declarative transaction management in.  The idea is to write transactional service layer methods, and under that, have a totally naive DAO layer that will have their connections injected, their errors managed outside, no commits, no rollbacks...

Your idea of moving the logic out of your controller layer is perfectly sound.  Your concern about the XML is legitimate, but, whatever your service layer returns, always remember that the format is a matter for the presentation layer.  Your service layer (and ideally the controller too) should be completely unaware of the format that will be rendered for the user.  This is the way to have a proper service layer that is reusable across the many presentation layers you could devise for your application.

A: Good question but hard to answer.
I'll try to help you find the answer that is correct for you:
What does the Service abstract over?
What does the Controller abstract over?
One possible set of answers is:
The Controller abstracts over the access mechanisms (xml, http, ...)
The Service abstracts over the business logic (beware the oxymoron) like: Who can see what appointments
The Daos abstract over the fact where stuff is stored. Appointments get retrieved the same way from Daos although one might come from an LDAP System and the other from a relational Database.
If these happen to be your answers you should move retrieval of user information and retrieval of appointments and user authentication to the service and rendering as xml stays in the Controller.
But it is really up to you and your team how you need to slice and dice the application.
One experiment that helps me to come up with reasonable answers is to think about other clients. What if a different application want this information. What would they access, how should the API look like?

A: I would say no, the service should not always return an entity (or list of entities).
It hard say without the actual code, but sometimes the following approach works better:
controller > facade > service > dao

The facade provides for your controller a method to create an appointment and returns xml back. At the same time, the service stays cleaner and let's say returns the user entity only
http://en.wikipedia.org/wiki/Facade_pattern

A: No, a service can return everything you want. There is no limit to what it provides for you. Even a DAO or repository does not have to return entities perse. They just need to return whatever you want from the database.
That said, with Spring there are preferred ways to handle certain tasks. For instance the XML you want to return from the service can be generated by message converters. All you need to do is ask for XML in the request and return the object or ResponseEntity <T> from the handler annotated with @ResponseBody.
Move and keep as much logic out of the controller as you can. Controllers that do a lot of the work are hard to test. This also applies to services by the way. It's better to split everything into little easy to manage pieces instead of having a large unit of work in one place.

A: I would not return xml from the service layer. Think about code reuse. What if that service will be needed later on other services. What will be of more use to you a list of users presented in an xml or a list of user objects. What if later on you need to present an users json? The controller should massage the data into a presentable format. At least that's my opinion.


text:
Q: Searching anagrams with Java 8 I have to write program which should be reading file for anagrams and show word + his anagrams. Txt files is very big, after using scanner, listOfWords size is: 25000.
Output example:
word anagram1 anagram2 anagram3 ...
word2 anagram1 anagram2...

I have code, it works but very slow:
  private static List<String> listOfWords = new ArrayList<String>();
  private static List<ArrayList<String>> allAnagrams = new ArrayList<ArrayList<String>>();

  public static void main(String[] args) throws Exception {
    URL url = new URL("www.xxx.pl/textFile.txt");
    Scanner scanner = new Scanner(url.openStream());
    while (scanner.hasNext()) {
      String nextToken = scanner.next();
      listOfWords.add(nextToken);
    }
    scanner.close();

    while (listOfWords.isEmpty() == false) {
      ArrayList<String> anagramy = new ArrayList<String>();
      String wzor = listOfWords.remove(0);
      anagramy.add(wzor);
      char[] ch = wzor.toCharArray();
      Arrays.sort(ch);
      for (int i = 0; i < listOfWords.size(); i++) {
        String slowo = listOfWords.get(i);
        char[] cha = slowo.toCharArray();
        Arrays.sort(cha);
        if (Arrays.equals(ch, cha)) {
          anagramy.add(slowo);
          listOfWords.remove(i);
          i--;
        }
      }
      allAnagrams.add(anagramy);
    }

    for (ArrayList<String> ar : allAnagrams) {
      String result = "";
      if (ar.size() > 1) {
        for (int i = 1; i < ar.size(); i++) {
          result = ar.get(i) + " ";
        }
        System.out.println(ar.get(0) + " " + result);
      }
    }
  }

I have to write it with Java 8 - streams but I don't know. It is possible to use Streams for reading from URL + searching anagrams? Could you help me with searching anagrams by Stream? Teacher told me that code should be shorter that mine with reading a whole list. Only a few lines, is that possible?

A: You can read the words from the file into a List or directly create a Stream of it:
try (InputStream is = new URL("http://www.someurl.pl/file.txt").openConnection().getInputStream();
     BufferedReader reader = new BufferedReader(new InputStreamReader(is));
     Stream<String> stream = reader.lines()) {
       //do something with stream
}

Then just stream over the list and collect the anagrams, where all words that have the same sorted list of characters are considered anagrams:
Map<String, List<String>> anagrams =
    stream.collect(Collectors.groupingBy(w -> sorted(w)));

The sorted method is just sorting the letters as you did in your example:
public static String sorted(String word) {
    char[] chars = word.toCharArray();
    Arrays.sort(chars);
    return new String(chars);
}

A: Let's create separate method which sorts letters. You can do this with Stream API as well:
private static String canonicalize(String s) {
    return Stream.of(s.split("")).sorted().collect(Collectors.joining());
}

Now you can read some Reader, extract words from it and group words by canonical form:
Map<String, Set<String>> map = new BufferedReader(reader).lines()
             .flatMap(Pattern.compile("\\W+")::splitAsStream)
             .collect(Collectors.groupingBy(Anagrams::canonicalize, Collectors.toSet()));

Next, you can remove single letter groups using Stream API for the third time:
return map.values().stream().filter(list -> list.size() > 1).collect(Collectors.toList());

Now you can pass some reader to this code to extract anagrams from it. Here's complete code:
import java.io.*;
import java.util.*;
import java.util.regex.Pattern;
import java.util.stream.*;

public class Anagrams {
    private static String canonicalize(String s) {
        return Stream.of(s.split("")).sorted().collect(Collectors.joining());
    }

    public static List<Set<String>> getAnagrams(Reader reader) {
    Map<String, Set<String>> map = new BufferedReader(reader).lines()
                                     .flatMap(Pattern.compile("\\W+")::splitAsStream)
                                     .collect(Collectors.groupingBy(Anagrams::canonicalize, Collectors.toSet()));
        return map.values().stream().filter(list -> list.size() > 1).collect(Collectors.toList());
    }

    public static void main(String[] args) throws IOException {
        getAnagrams(new StringReader("abc cab tat aaa\natt tat bbb"))
                .forEach(System.out::println);
    }
}

It prints
[att, tat]
[abc, cab]

If you want to use an URL, just replace the StringReader with new InputStreamReader(new URL("www.xxx.pl/textFile.txt").openStream(), StandardCharsets.UTF_8)

If you want to extract the first element of the anagram set, the solution should be modified slightly:
public static Map<String, Set<String>> getAnagrams(Reader reader) {
    Map<String, List<String>> map = new BufferedReader(reader).lines()
       .flatMap(Pattern.compile("\\W+")::splitAsStream)
       .distinct() // remove repeating words
       .collect(Collectors.groupingBy(Anagrams::canonicalize));
    return map.values().stream()
       .filter(list -> list.size() > 1)
       .collect(Collectors.toMap(list -> list.get(0),
                                 list -> new TreeSet<>(list.subList(1, list.size()))));
}

Here the result is the map where the key is the first element in anagram set (first occurred in the input file) and the value is the rest elements sorted alphabetically (I make a sublist to skip the first element, then move them into TreeSet to perform sorting; an alternative would be list.stream().skip(1).sorted().collect(Collectors.toList())).
Example usage:
getAnagrams(new StringReader("abc cab tat aaa\natt tat bbb\ntta\ncabr\nrbac cab crab cabrc cabr"))
        .entrySet().forEach(System.out::println);

A: You can try this method
//---------------Anagram---------------------------------
    String w1 = "Triangle".toLowerCase(), w2 = "Integral".toLowerCase();
    HashMap<String, Integer> w1Map = new HashMap<String, Integer>();
    HashMap<String, Integer> w2Map = new HashMap<String, Integer>();

    w1Map = convertToHashMap(w1);
    w2Map = convertToHashMap(w2);

   if( !(w1.equals(w2)) && (w1Map.keySet().equals(w2Map.keySet())))
       System.out.println(w1+" and "+w2+" are anagrams");
   else
       System.out.println(w1+" and "+w2+" are not anagrams");

calls below method
public static HashMap<String, Integer> convertToHashMap(String s) {
    HashMap<String, Integer> wordMap = new HashMap<String, Integer>();
    for (int i = 0;i < s.length(); i++){
        wordMap.put(String.valueOf(s.charAt(i)), Integer.valueOf(s.charAt(i)));
    }
    return wordMap;


text:
Q: How do I check a new Numbers file into git using Xcode? Apple's "Numbers" spreadsheet app just changed file formats, where the new one is bundle-based, essentially a single-icon representation as far as a user is concerned, but a folder of stuff under the hood. I have a spreadsheet where I keep track of App Store data and other things related to my app, and I love keeping it under source control closely tied to my source code and other project data.
What's the best way to add/commit the new file (actually a folder) into git? Ideally, it would be treated just like the old single-file-format file was treated. If I add it like I would normally do, it adds the folder with 50 files inside, and I'm worried that git won't keep up with the files that Numbers (transparently to the user) adds and removes inside that "bundle".
I found this previous post, but it wasn't helpful: Best approaches to versioning Mac "bundle" files
Basically, I don't want to "manage" anything related to what's inside the folder. Is there a way to do this right?


text:
Q: sort list by date in descending order - groovy madness I'm not able to sort a list of Objects by a Date in descending order
Let's say this is my class Thing
class Thing {

Profil profil
String status = 'ready'
Date dtCreated = new Date()
}

Inside the method I'm creating the List things
            List profiles = profil.xyz?.collect { Profil.collection.findOne(_id:it) }

            List things = []

and then I populate the list with each associated Thing of each profile
            profiles.each() { profile,i ->
                if(profile) {
                    things += Thing.findAllByProfilAndStatus(profile, "ready", [sort: 'dtCreated', order: 'desc']) as
                 }

Alright, now things has a lot of things in it, unfortunately the  [order: 'desc'] was applied to each set of things and iI need to sort the whole list by dtCreated. That works wonderful like
            things.sort{it.dtCreated}

Fine, now all the things are sorted by date but in the wrong order, the most recent thing is the last thing in the list
So I need to sort in the opposite direction, I didn't find anything on the web that brought me forward, I tried stuff like
            things.sort{-it.dtCreated} //doesnt work
            things.sort{it.dtCreated}.reverse() //has no effect

and I'm not finding any groovy approach for such a standard operation, maybe someone has a hint how I can sort my things by date in descending order ? There must be something like orm I used above  [sort: 'dtCreated', order: 'desc']
or isn't it?

A: How about
things.sort{it.dtCreated}
Collections.reverse(things)

Look here for some more useful list utilities

A: Instead of
things.sort{-it.dtCreated}

you might try
things.sort{a,b-> b.dtCreated<=>a.dtCreated}

reverse() does nothing because it creates a new list instead of mutating the existing one.
things.sort{it.dtCreated}
things.reverse(true)

should work
things = things.reverse()

as well.

A: You may also use things.first() and things.last() to extract the first and the last element of the list.


text:
Q: How to compile a c++ project that requires ? I downloaded a project that has these 2 lines in it:
#include <winsock2.h>
#include <Afxwin.h>

I'm confused about on how to compile this, because my standard compiler can't find the selected files.
What do I need to to configure my compiler's search path in order to successfully compile this?
The compiler I tried it with is Dev-C++.
Edit: I'm guessing I have to configure certain libraries to be used when compiling (but which?)

A: Are you building on Windows?
These are Microsoft includes files. If you have Visual Studio, winsock should be available. But for afx (MFC), you need a commercial edition I believe.
If you have a commercial Visual Studio and it still can't find them, it's just a matter of configuring the compiler to include the proper directories (but it should have come that way out of the box).

A: winsock2.h is part of the Windows SDK and Afxwin.h is the main MFC/ATL include file.
You should be able to download the current Windows SDK from the Microsoft site, but that will not include the MFC code - I'm pretty sure you'll need to have Visual Studio in order to be able to use MFC and ATL.


text:
Q: What is the connection between Conformal Field Theory and Renormalization group in QFT? As I know, the fundamental concept of QFT is Renormalization Group and RG flow.  It is defined by making 2 steps:

*

*We introduce cutting-off and then integrating over "fast" fields $\widetilde{\phi}$, where $\phi=\phi_{0}+\widetilde{\phi}$.

*We are doing rescaling: $x\to x/L$: $\phi_{0}(x)\to Z^{-1/2}(L)\phi(x)$.
This procedure defines RG flow on the manifold of quasi local actions: $\frac{dA_{l}}{dl}=B\{A_{l}\}$.
In this approach we have such notions as crytical points $A_{*}$, relevant and irrelevant fields, Callan–Symanzik equation etc, and we can apply it, say, to phase transitions.
Also we can introduce stress-energy tensor $T^{\mu\nu}$. And, as far as i know, if we consider scale transformations $x^{\mu} \to x^{\mu}+\epsilon x^{\mu}$ , we can obtain Callan–Symanzik equation, and if the theory have a crytical point: $\beta^{k}(\lambda^{k})=0$, then trace of stress energy tensor $\Theta(x)=T^{\mu}_{\mu}=0$, so our  correlation functions have symmetry at scaling transformation.
So the question is: As far as I know, at this point they somehow introduce conformal transformations and Conformal Field Theory. Can you explain, what place in Quantum Field Theory CFT takes? (I mean connection between them, sorry if the question is a little vague or stupid). How it relates to the RG approach exactly? (This point is very important for me). Maybe some good books?

A: I recently stumbled upon a good comment about this in Jared Kaplan's AdS/CFT notes

*

*Any quantum field theory which has hope of having an UV-completion can be viewed as as effective theory at point in the RG flow from an UV complete theory.

*Field theories at the UV fixed point are conformal.

*Hence all 'well-defined' field theories are either CFTs or points in the RG flow from one (UV) CFT to another CFT.
So in a sense, in Kaplan's words:

studying the space of CFTs basically amounts to studying the space of all well-defined QFTs

So that's one way of seeing the place of CFTs in general QFTs.

A: zzz's answer concerns QFTs as used in particle physics. However, OP also mentions phase transitions, thus statistical field theory, where the relationship between CFT and scale-invariant RG fixed points is more subtle.
Indeed, for local QFTs where unitarity is assumed, there are theorems showing that scale invariance implies conformal invariance, see e.g. https://en.wikipedia.org/wiki/C-theorem for the theorem of A. Zamolodchikov in 2D and discussion of the situation in 4D.
However, it is known that this link does not extend to general statistical field theories: for example, [1] use elasticity as a counter-example. The link between scale invariance and conformal invariance has been reviewed in [2].
[1] V. Riva and J. Cardy. "Scale and conformal invariance in field theory: a physical counterexample." Physics Letters B 622.3-4 (2005): 339-342.
[2] Y. Nakayama. "Scale invariance vs conformal invariance." Physics Reports 569 (2015): 1-93.


text:
Q: Python equivalent for write in file like in shell Is there a way to write in file like in shell script but in python by doing something similar to this:
cat >> document.txt <<EOF
Hello world 1
var=$var
Hello world 2
EOF

?

A: If I understand the question correctly, you are referring to the here document feature in bash. I don't think there is a direct equivalent in Python, but you can enter multi-line strings using """ (triple quotes) to delimit the start and end, e.g.
>>> long_string = """First
... Second
... Third"""
>>> print long_string
First
Second
Third

which you could then write to a file:
myFile = open("/tmp/testfile", "w")
myFile.write(long_string)
myFile.close()

and achieve much the same thing as your bash example.

A: with open('document.txt', 'w') as fp:
    fp.write('''foo
{variable}
    '''.format(variable = 42))

Though you probably want to do several calls to fp.write (or print) for each line, or use textwrap.dedent to avoid whitespace issues, e.g.
with open('document.txt', 'w') as fp:
    print >>fp, 'foo' # in 3.x, print('foo', file = fp)
    print >>fp, variable

It's probably best to just read the tutorial.


text:
Q: Segueing custom view cells to custom view controller I'm using a collection view to display a grid of custom collection view cells to represent category icons that will function as buttons to segue to a table view controller to display the categories listings. I'm using an array of "products" (labels) and "images" (images of the products) to display multiple custom cells based off a prototype as such
  func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {

    let cell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as! CollectionViewCell

    cell.imageView?.image = self.images[indexPath.row]

    cell.labelView?.text = self.products[indexPath.row]

    return cell
}

How would be able to segue my home page view controller to a single custom table view controller to display different category listings depending on which icon was selected? Any help is greatly appreciated, still getting used to xcode and swift

A: If I understand you correctly, you can use the same child UITableViewController and pass it different data depending on what cell is chosen.
First in the CollectionViewController implement
override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath)

Then perform the segue with the data
performSegue("identifier", sender: self.products[indexPath.row])

A: First your view controller has to conform to UICollectionViewDelegate then you have to implement this delegate method to perform a segue when a cell is selected:
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
    performSegueWithIdentifier("identifier", sender: nil)
}

Then check if the segue identifier matches, get indexPath of the selected cell, construct a tuple of the selected product and image and finally pass it to your destination tableViewController.
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if segue.identifier == "identifier" {
        let indexPath = collectionView.indexPathsForSelectedItems()!.first!
        let selectedProduct = (product: products[indexPath.row], image: images[indexPath.row])
        let controller = segue.destinationViewController as! YourTableViewController
        controller.product = selectedProduct
    }
}


text:
Q: Duda sobre ciclo o bucle for Tengo una duda sobre el ciclo for, es que tengo un formulario dónde mando y recibo las siguientes variables:
case 'updatePD': //ACTUALIZACION DEL COLABORADOR
if(!empty($_POST['consecutivo'])){

$n=count($_POST['consecutivo']);
$iddatospersonales=$_SESSION['iddatospersonales'];
$cedula=$_SESSION['numdocumcolaboradorview'];

for ($i=0; $i<$n; $i++) {
    $rutaarchivo="../../assets/files/upload/archivo/";

    if (empty($_POST['idprocesodisciplinario'][$i])) {
        $_POST['idprocesodisciplinario'][$i]=0;
    }

    if (empty($_POST['causa'][$i])) {
        $_POST['causa'][$i]=-1;
    }

    echo "CAUSA:  ". $_POST['causa'][$i]."  CONSECUTIVO:  ".$_POST['consecutivo'][$i];
    echo "<br>";

    $query=$obj->post_ejecutar("SELECT * FROM procesodisciplinario WHERE
idprocesodisciplinario=".$_POST['idprocesodisciplinario'][$i]."
ORDER BY idprocesodisciplinario");
    $opcion=pg_fetch_row($query);

    if(!empty($_FILES['cargadisciplinarios'])){
        if(!empty($_FILES['cargadisciplinarios'])){
            $cargadisciplinarios=$obj->cargar_archivo($_FILES['cargadisciplinarios']['name'][$i],$_FILES['cargadisciplinarios']['type'][$i],$_FILES['cargadisciplinarios']['size'][$i],$_FILES['cargadisciplinarios']['tmp_name'][$i],$_FILES['cargadisciplinarios'],$rutaarchivo,$iddatospersonales,'DISCIPLINARIO',$cedula);

            try {
                $filedisciplinario=$cargadisciplinarios['filename'];
            } catch (Exception $e) {
                echo "NO ES UN ARCHIVO VÁLIDO";
                $filedisciplinario="";
            }
        }
    }

Tengo un select que dependiendo de la elección del usuario se habilita o se deshabilita el otro select (La Causa):

El problema o el error que tengo es que al hacer la siguiente validación:
if (empty($_POST['causa'][$i])) {
    $_POST['causa'][$i]=-1;
 }

Si no llega esa variable como resultado debería traerme -1 en la causa, pero ese no es el problema si no que en el orden que me la trae no es el correcto ya que llega de última, cuando en realidad debería llegarme de primera anexo esta imagen para que sea más fácil de entender:


text:
Q: Issue in reading DateTime field I have a text box that shows date of the system
protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            TextBoxdate.Text = DateTime.Today.ToShortDateString();

        }
    }

and gets inserted into the Date type field of my database!
Now I am trying To create a view of my table on Grid view. In my WorkDataAccesslayer class I am retrieving values of my table. But getting error on retrieving Date i.e "WorkAssign.Date is inaccessible due to its protection level"
My WorkAssign class is as follows:
 public class Workassign
{

    public string listItem_1{get; set;}
    public string listItem_2{get ; set;}
    public string Description {get ; set;}
    DateTime Date {get; set;}
    public string Image { get; set; }

}

and my WorkDataAccessLayer class is as follows:
public class WorkDataAccessLayer
{

    public static List<Workassign> GetTable()
    {
        List<Workassign> listValues = new List<Workassign>();

        string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
        SqlConnection con = new SqlConnection(CS);
        {
            SqlCommand cmd = new SqlCommand("Select * from Assign_Work", con);
            con.Open();
            SqlDataReader rdr = cmd.ExecuteReader();

            while (rdr.Read())
            {
                Workassign ob = new Workassign();
                ob.listItem_1 =rdr["listitem_1"].ToString() ;
                ob.listItem_2 = rdr["listitem_2"].ToString();
                ob.Description = rdr["Description"].ToString();
                ob.Date = rdr["Date"].ToString();
                ob.Image = rdr["Image"].ToString();

                listValues.Add(ob);

            }

            return listValues;

        }

    }

A: Make it also public
public class Workassign
{

    public string listItem_1{get; set;}
    public string listItem_2{get ; set;}
    public string Description {get ; set;}
    public DateTime Date {get; set;}  // default is internal
    public string Image { get; set; }

}

otherwise you get the mentioned error at:
Workassign ob = new Workassign();
// ...
ob.Date = rdr["Date"].ToString();

http://msdn.microsoft.com/en-us/library/ms173121.aspx

A: Assign the Date Property as public inline with the other properties :
public DateTime Date {get; set;}
You may prefer to modify the get; and set; to be private individually.
More info on C# Class Properties : http://msdn.microsoft.com/en-us/library/w86s7x04.aspx


text:
Q: How to pass the currently logged in user as default to a form How do i pass the currently logged in user as default to a form?
I want the form to be pre-populated with the current user, but at the same time allow the user to change it (e.g. add the Customer for another user).
Here is my model:
class Customer (models.Model):

    shortname = models.CharField(max_length=30)
    name = models.CharField(max_length=50, blank=True)
    [...]
    user = models.ForeignKey(User)
    nextstep = models.DateField(auto_now=False, auto_now_add=False, default=(date.today() + timedelta(days=10)))

    def due_in(self):

        due_time = self.nextstep - date.today()
        overdue = due_time.days < 0
        return {'days': abs(due_time.days), 'overdue': overdue}

    def get_absolute_url(self):
        """Absolute URL des Partners"""
        return reverse('kundencenter:partner_detail', kwargs={'pk': self.pk}, current_app='kundencenter')

And my form:
class CustomerForm(forms.ModelForm):

    class Meta:
        model = Customer
        fields = [
            "shortname",
            "name",
            [...]
            "user",
        ]

        labels = {
            "shortname": 'Customer Shortname',
            "name": 'Full Name',
            }

And my view:
class CustomerCreateView(SuccessMessageMixin, CreateView):
    """Adds a new customer."""
    model = Customer
    template_name = 'customercenter/generic_new.html'
    form_class = CustomerForm
    success_message = "Customer %(name)s added."

A: You can use initial in your form while rendering the form.
form = CustomerForm(initial={'user':request.user})

See the docs for more details.

A: Extending Arpit Solanki's answer, you can add/override get_initial method  since you are using a Class Based View:
def get_initial(self):
    initial_data = super(CustomerCreateView, self).get_initial()
    initial_data.update({'user':self.request.user})
    return initial_data


text:
Q: \floatfoot and equations I am using \floatfoot to creates notes for a figure in a paper. I would like to include an equation in the notes for this figure. Specifically, I am trying to use the following code:
\floatfoot{Notes: The figure shows coefficients from the following specification:
$$ y = \alpha + \beta X $$
where $y$ is an outcome.}

When I compile this code, the PDF looks correct, although I get several errors in TeXnicCenter. I get errors like,
! Missing $ Inserted

where there are clearly no issues with a missing $ in the above code.
I was wondering if anyone has any recommendations to avoid getting these errors in TeXnicCenter. I've also tried to use the align and equation environments in the \floatfoot command and this generates different (but obviously still problematic) errors.

A: You can hide the equation in a \parbox or put the whole \floatfoot contents in a minipage as follows:

\documentclass{article}

\usepackage{floatrow}

\begin{document}

\begin{figure}
\floatbox{figure}{\caption{Caption}}
  {\rule{2cm}{2cm}
  \floatfoot{Notes: The figure shows coefficients from the following
  specification:\endgraf
  \parbox{\linewidth}{%
  \begin{displaymath}
    y = \alpha + \beta X
    \end{displaymath}}\endgraf
  where $y$ is an outcome.}}
\end{figure}

\begin{figure}
\floatbox{figure}{\caption{Caption}}
  {\rule{2cm}{2cm}
  \floatfoot{%
  \begin{minipage}{1.0\linewidth}
    Notes: The figure shows coefficients from the following
    specification:
  \begin{displaymath}
    y = \alpha + \beta X
  \end{displaymath}
  where $y$ is an outcome.
\end{minipage}%
}}
\end{figure}

\end{document}


text:
Q: How can I get the web server Gunicorn to use 0.0.0.0:443 (for HTTPS) without running as root? I'm trying to run a Flask application via HTTPS on Gunicorn.
Up to now I have been running it successfully via HTTP using a command like the following:
gunicorn --workers=4 "program.__main__:WSGI()" --bind=0.0.0.0:8080

Now I am trying to run it via HTTPS using a command like the following:
gunicorn --workers=4 "program.__main__:WSGI()" --bind=0.0.0.0:443 --certfile=fullchain.pem --keyfile=privkey.pem

When I run this as a normal user, I get output like the following:
[2018-08-13 21:26:28 +0000] [15170] [INFO] Starting gunicorn 19.9.0
[2018-08-13 21:26:28 +0000] [15170] [ERROR] Retrying in 1 second.
[2018-08-13 21:26:29 +0000] [15170] [ERROR] Retrying in 1 second.
[2018-08-13 21:26:30 +0000] [15170] [ERROR] Retrying in 1 second.
[2018-08-13 21:26:31 +0000] [15170] [ERROR] Retrying in 1 second.
[2018-08-13 21:26:32 +0000] [15170] [ERROR] Retrying in 1 second.
[2018-08-13 21:26:33 +0000] [15170] [ERROR] Can't connect to ('0.0.0.0', 443)

As root, it works, but I'm disinclined to run a web server as root. How should I run this securely?


text:
Q: How can you hibernate/suspend using the command line in linux?
Possible Duplicate:
Put 'nix box to sleep from command line?

I found that the solution was to do:
pmi action hibernate

But when I typed in that, it showed:
Error org.freedesktop.DBus.Error.ServiceUnknown:
 The name org.freedesktop.Hal was not provided by any .service files

I couldn't go further from here. Please help me to fix the problem.

A: In Ubuntu there's a script which is part of the pm-utils package - /usr/sbin/pm-suspend which can be used to suspend from the command line.
sudo /usr/sbin/pm-suspend

Additionally there is pm-hibernate to hibernate to disk and pm-suspend-hybrid to do a combined hibernate/suspend.

A: The low level way would be
echo -n mem > /sys/power/state

or for suspend-to-disk (hibernate)
echo -n disk > /sys/power/state

The available modes can be found by
cat /sys/power/state


text:
Q: VScode intellisense not working..any suggestions? When I type the code:
document.queryselector('.classname').

.style and other common suggestions do not appear in the suggested autocomplete menu when I begin to type after the parentheses.
But when I type
document.queryselector('body').

It does?

A: First of all, you should use querySelector, not queryselector.
Regarding your issue, there is a reason why VScode IntelliSense doesn't show style attribute.
Let's look at this example:
const element = document.querySelector('.classname')
const element2 = document.querySelector('body')

element has a type of Element. And element2 has type HTMLBodyElement which is subclass of HTMLElement.
Element VS HTMLElement
Element is the most general base class from which all element objects (i.e. objects that represent elements) in a Document inherit. It only has methods and properties common to all kinds of elements. More specific classes inherit from Element. And it doesn't have style attribute.
The HTMLElement interface represents any HTML element. It extends Element and has style attribute.
Then why element2 return HTMLBodyElement?
VSCode has hardcoded typing when you selecting by exact tag name. You can see that in lib.dom.d.ts
How can fix that?
You can add additional checking and VSCode will understand it:
const element = document.querySelector('.classname')

if (element instanceof HTMLElement) {
    element.style.display = 'none'
}


text:
Q: Structured Streaming using PySpark and Kafka, Py4JJavaError: An error occurred while calling o70.awaitTermination I tried to consume from Kafka using Spark, more specifically PySpark and Structured Streaming.
import os
import time
import time

from ast import literal_eval
from pyspark.sql.types import *
from pyspark.sql.functions import from_json, col, struct, explode
from pyspark.sql import SparkSession
os.environ['PYSPARK_SUBMIT_ARGS'] = '--packages org.apache.spark:spark-sql-kafka-0-10_2.11:2.3.0 pyspark-shell'

spark = SparkSession \
    .builder \
    .appName("Structured Streaming") \
    .getOrCreate()

    requests = spark \
  .readStream \
  .format("kafka") \
  .option("kafka.bootstrap.servers", "ip-ec2:9092") \
  .option("subscribe", "ssp.requests") \
  .option("startingOffsets", "earliest") \
  .load()

requests.printSchema()

# root  |-- key: binary (nullable = true)  |-- value: binary (nullable =
# true)  |-- topic: string (nullable = true)  |-- partition: integer
# (nullable = true)  |-- offset: long (nullable = true)  |-- timestamp:
# timestamp (nullable = true)  |-- timestampType: integer (nullable =
# true)

When I ran the next lines of code
rawQuery = requests \
        .selectExpr("topic", "CAST(key AS STRING)", "CAST(value AS STRING)") \
        .writeStream.trigger(processingTime="5 seconds") \
        .format("parquet") \
        .option("checkpointLocation", "/home/user/folder/applicationHistory") \
        .option("path", "/home/user/folder") \
        .start()
rawQuery.awaitTermination()

Py4JJavaError                             Traceback (most recent call
  last) /opt/conda/lib/python3.6/site-packages/pyspark/sql/utils.py in
  deco(*a, **kw)
       62         try:
  ---> 63             return f(*a, **kw)
       64         except py4j.protocol.Py4JJavaError as e:
/opt/conda/lib/python3.6/site-packages/py4j/protocol.py in
  get_return_value(answer, gateway_client, target_id, name)
      319                     "An error occurred while calling {0}{1}{2}.\n".
  --> 320                     format(target_id, ".", name), value)
      321             else:

Py4JJavaError: An error occurred while calling o70.awaitTermination. :
    org.apache.spark.sql.streaming.StreamingQueryException: Job aborted.
    === Streaming Query === Identifier: [id = c2b48840-5ba4-416e-a192-dcae94007856, runId =
    4afcca20-00cd-4187-a70b-1b742f1f5c0d] Current Committed Offsets: {}
    Current Available Offsets: {KafkaSource[Subscribe[ssp.requests]]:

I can't understand the reason of this error

Py4JJavaError: An error occurred while calling o70.awaitTermination

A: I just replaced the line rawQuery.awaitTermination() by
print(rawQuery.status)
time.sleep(60)
print(rawQuery.status)
rawQuery.stop()

and it works.


text:
Q: Add domain to hyperlinks after .load function I am trying to change the (internal) hyperlinks of loaded content into external (by adding a domain to the href) but something isn't working correct or loaded in the right order...
This is what I've tried so far.
First I created a php page loadingmodels.php, with only this in it:
<?php echo file_get_contents($_GET['url']); ?>

Then I load the external content in my content div:
$(function(){
    var contentURI= 'https://somepage #model-selector';
    $('#content').load('loadingmodels.php?url='+ contentURI);
});

This loades data like this in my content div:

Name1

Name2

Finally, and this I can't get to work, I would like add a domain the the internal hyperlinks; ie, change "/link1" into "https://someotherpage/link1".
This is what i tried (placed underneath the above code):
$(function(){
    $("a.btn-car-more").each(
        function() {
            href = $(this).attr('href');
            new_href = 'https://someotherpage' + href;
            $(this).attr('href', new_href);
        }
    );
});

Does anyone have an idea why it's not working?

A: The issue is because the load() call is asynchronous. Therefore you're trying to amend the .btn-car-more links before they exist in the DOM.
To fix this you need to run your logic in the callback of the load() method, to ensure that the HTML has been injected in to the DOM first. Try this:
jQuery(function($) {
  var contentURI = 'https://somepage #model-selector';
  $('#content').load('loadingmodels.php?url=' + contentURI, function() {
    $('a.btn-car-more[href^="/"]').attr('href', function(i, href) {
      return 'https://someotherpage' + href;
    });
  });
});

There's a couple of things to note in the example above. Firstly I used the 'attribute begins with' selector to only target the href attributes which are relative to the original path. Secondly, you can avoid the explicit each() loop by passing a function to attr() this function will be executed on each Element in the collection.


text:
Q: Graph visualization with cocoa/core graphics (iPad) I'm going to implement some GUI for the graph (not plot, the one with vertices and edges). And I what to ask what will be the best design. I thought about making vertices a subviews, that can handle gestures buy themselves and on some change of state telling superview abot it, and the super view will send a message to datasource (controller) so it can update the model. And I don't know how to work with edges, just draw them with CoreGraphics from the main view, and somehow determine if the gesture belongs to them? (I need to set up values for the edges, as I have a weighted graph) Or I should make edges as subviews too?
I know a lot of theory, but I had only a little experience of working with custom views and graphics, so I don't want to waste a lot of time doing it the "wrong way".
Thank you!
P.S. I'm using iOS5 SDK if it metters
EDIT
I want to make kind of educational application for graph algorithms like searching paths etc… And as far as I cat think of it, I need to:

*

*create vertices

*drag them

*connect them with edges

*set weight for edges

*(maybe set names of vertices)

*anyway I need to setup some properties of vertices (like start point and end point) so the naming should be the same

*also later I'll need to put some colors on edges to show what if the best path and how it was found, but I don't think it's a lot of trouble.

That's all probably.


text:
Q: How to block/prevent navigation in React Navigation v5? I need prevent navigation if I'm editing a certain screen.
I found this in the documentation: https://reactnavigation.org/docs/5.x/custom-routers/#blocking-navigation-actions but don't have a clear example, even because I'm using createStackNavigator
How should I implement to get access to this getStateForAction?
Or there is another way to block/prevent users to go to another screen globally?
Here is an example of how I'm doing the navigator.
import { createStackNavigator } from '@react-navigation/stack';
const StackNavigator = createStackNavigator<TTopLevelParams>();

const RootNavigator: React.FC = () => {
  return (
    <StackNavigator.Navigator initialRouteName={StartNav}>
      <StackNavigator.Screen
        component={IntroNav}
        name={IntroNav}
      />
      <StackNavigator.Screen
        component={StartNav}
        name={StartNav}
      />
    </StackNavigator.Navigator>
  );
};

export default RootNavigator;


text:
Q: Counting multiple vote choices in Doctrine with createQueryBuilder I'm working on a voting system, where user will be able to vote either yes, no or not sure to a given question.
These are being stored in a voteOptions table as choice with a value of either 0, 1 and 2 which is attached to a vote table that stores additional information. I struggling to work out how to count up the votes in a single function.
The function below counts a single choice, which I currently call once for each voteOption. I'm counting distinct users as they can appear more than once, but only their last vote counts:
public function countPollVotesByIsCurrentAndChoice(Poll $poll, $choice) {
    return $this->createQueryBuilder('v')
        ->leftJoin('v.voteOptions', 'vo')
        ->andWhere('v.poll = :poll')
        ->andWhere('v.isCurrentVote = :isCurrentVote')
        ->andWhere('vo.choice = :choice')
        ->setParameters(['isCurrentVote' => true, 'poll' => $poll, 'choice' => $choice])
        ->select('COUNT(DISTINCT v.user) AS vote_count')
        ->getQuery()
        ->getSingleScalarResult();
}

But I'd prefer to make a single call to get all 3 counts. I would really appreciate any advice about how best to do this.

A: You have to use COUNT() together with GROUP BY which will aggregate the choices to three possible answers and the COUNT function counts the number of records for each answer.
$query = $em->createQuery('SELECT count(vo.choice) AS cnt FROM AppBundle:Vote v JOIN v.voteOptions vo WHERE ... GROUP BY vo.choice');
$result = $query->getResult();

This query will not return an array with Vote objects but just an array with rows that contains columnames and values. print_r() will help you


text:
Q: Networking -- Padding of Data For a homework assignment, I was tasked with creating a "Ping Pong" layer that sits right above the Ethernet stack.
I was able to easily complete the task but when I tested my application over my wireless connection and tried communication with my desktop computer (ethernet) on the same network I found some odd behavior.
It seems like the packet is being padded with information I did not add.
From wireless->ethernet I get something like the following (as a hex output of the data received, taking off the ethernet header, periods are unprintable characters).
3-468...lkin54g......$
0Hl.........*../..2..
When my desktop responds to my laptop (ethernet->wireless) I get something like the following
3-468................
.....................
Is this expected behavior?

A: Yes.  Valid Ethernet frames have a minimum size of 64 bytes (including the Ethernet header and a 4-byte checksum at the end).

A: When you send packets across the network, the data you are sending is wrapped up into successively larger data structures at each level of the OSI network layer model.  When your operating system receives the packets of information, it unwraps the data as it goes up the layers.  Reading more about the OSI model could be useful for better understanding.
Here is a picture that illustrates what is going on at each layer, from an ebook.


text:
Q: How can I know client send FIN package in socket? In client, when call clent.close(), it will send a FIN packet to try to end the connection. Are there any API for server side to know there comes a FIN packet to close the connection in server side? If not, why? What's the best pratice to close connection in both side?
Client code:
    String host = "127.0.0.1";
    int port = 8899;
    Socket client = new Socket(host, port);
    String data = "Hello world";
    Writer writer = new OutputStreamWriter(client.getOutputStream());
    writer.write(data);
    writer.flush();
    writer.close();
    client.close();

A example can be seen here.

A: When the server receives a FIN, it will treat this as the end-of-stream condition.
In other words, every time you call read on the socket's InputStream, it will return -1 instead of reading any data - the same as if you were reading from a file and you got to the end of the file.

A: When the peer receives a FIN:

*

*read() will return -1

*readLine() will return null

*readXXX() will throw EOFException for any other X.

What won't happen:

*

*Socket.isClosed() won't magically become true

*Socket.isConnected() won't magically become false.


text:
Q: What is the meaning of u8R"delim(SomeTextInHere)delim" in C++? Right, here's something I've not seen before. The following snippet of code was found in the wild (though I'm paraphrasing since I don't have access to the original):
char str[] = u8R"delim(SomeTextInHere)delim";

Can anyone actually tell me what this means and what the equivalent would be in C?

A: I don't know how to translate it into C sir, but this is throwing almost all the new literals related stuff in one example.
u8: utf-8 string literal.
R: Raw string literal (no escape characters)
"delim(" ... ")delim": The prefix and suffix of the raw string literals.
                       They are used as delimiters, and you can write your own.

A: There is no equivalent in C as of yet. This is a C++11 feature that combines two things.
The u8 prefix means that the string will be encoded in UTF-8. The R prefix means that it is a raw string literal. Combining them means that the raw string will be UTF-8 encoded.
Raw strings are a way to get around all the escaping necessary for regular expressions and so forth. Normally, in a regex, you have to use a lot of "\" characters. But that's the C/C++ escape character, so in string literals, you have to use "\" instead. Raw string literals allow you to avoid that. In raw strings, there are no escape characters.
The way a raw string literal works is as follows. The R prefix is followed by " as usual. But the characters up to the first ( character are all considered part of the delimiter of the raw string. So, if you start a raw string with R"foo(, the string will continue until the parser sees, )foo".
This way, you can use ", \, and virtually any other characters, as long as you choose your delimiters will. The delimiter can be empty too, so R"(some stuff)" is equivalent to "some stuff". It ends when it sees )".


text:
Q: sbin/init crash after log in Hi I have been getting a problem where, every time I log into Ubuntu, a red exclamation mark appears in the top-right of the screen.  On clicking it, a window appears to say "Sorry, Ubuntu 12.04 has experienced an internal error".  Here are some of the information also given.
======================================
ExecutablePath
   /sbin/init
Package
upstart 1.5-0ubuntu7.2 [modified: sbin/initctl]
ProblemType
Crash
Title
init crashed with SIGSEGV
ApportVersion
2.0.1-0ubuntu17.8
Architecture
i386
.
.
.
ProcCmdline
/sbin/init
UnreportableReason
This is not an official Ubuntu package.  Please remove any third party package and try again.
UpgradeStatus
No upgrade log present (probably fresh install)
=========================================================
Is there a way to fix this?

A: In order to fix the error "Sorry, Ubuntu 12.04 has experienced an internal error" run the below command in the terminal,
sudo gedit /etc/default/apport

After running the command change the enabled parameter from 1 to 0 and then save the changes. Once you are done please reboot the machine, this might help you to fix.


text:
Q: Enabling triple slash auto-complete in visual studio for c++? When I type three slashes in a c# project in visual studio community 2017, then a placeholder for documentation appears, e.g.:
        /// <summary>
        ///
        /// </summary>
        /// <param name="ppcode"></param>
        /// <returns></returns>
        public double multForType(int ppcode)
        {
           //Implementation goes here.
        }

This somehow does not work for a c++ project. Is there a way to get this, or similar functionality, to work?

A: Yes, there is a downloadable extention: CppTripleSlash - xml doc comments for c++


text:
Q: Ruby on rails - nested forms with has_many through Basically, I want to write a web-based curation tool for clinical conditions (disease) and their underlying genetics. Say, I have a clinical condition (class: Phenotype), and I have "mutations"(class: Genotype) that belong to that condition - either individually (i.e. a given mutation is directly causing this condition) or as a group (two or more mutations together cause the condition). Each condition can have one or more of such groups (i.e. may be cause by different mutations or groups of mutations). So I figured I need to create a grouping class (class: GenotypeGroup) to make that association. What I cannot figure out is how to do the form... First, I would want to enter a phenotype with some description. I then would like to use the "show" view to add a new genotype_group to that phenotype (Add new genotype group). This would have to create, implicitly (since it is basically only a cross-reference table) the genotype_group and one or more genotypes which it links to the phenotype entry.
Right now, I have:
class Phenotype
  has_many :genotype_groups
  has_many :genotypes, through: :genotype_groups
  accepts_nested_attributes_for :genotype_groups
end

class GenotypeGroup
  belongs_to :phenotype
  has_many :genotypes
  accepts_nested_attributes_for :genotypes
end

class Genotype
 belongs_to :genotype
end

And zero idea how this would work in terms of nested forms. If anyone has a helpful web resources (been googling for > 1hour now, but apparently don't even know what the thing I am trying to do is called..) - that would be great!
Cheers,
M

A: Turns out I was missing two things:
a) When nesting the genotype object, I need to add a "Genotype.new" to the nested form element:
<% f.fields_for :genotypes, Genotype.new do |gt| %>
 something_here
<% end %>

b) I had to declare which variables should be carried (i.e. are permitted) by the params object in the respective controller(s) so that I could pass those values between the classes during the nested object creation.


text:
Q: How to display profile fields with no data in BuddyPress profile view? It seems like BuddyPress hides profile fields without data in profile view.
How can I change this functionality? So that all fields gets displayed, even if they haven't been filled up?

A: Create a template overload of this file: buddypress\bp-templates\bp-legacy\buddypress\members\single\profile\profile-loop.php
Then find this code:
<?php if ( bp_field_has_data() ) : ?>

    <tr<?php bp_field_css_class(); ?>>

       <?php bp_the_profile_field_name(); ?>

       <?php bp_the_profile_field_value(); ?>

<?php endif; ?>

And change it to:
<tr<?php bp_field_css_class(); ?>>

   <?php bp_the_profile_field_name(); ?>

   <?php bp_the_profile_field_value(); ?>

EDIT: We need to force the fetching of empty fields...
So also find this:
<?php if ( bp_has_profile() ) : ?>

And change to this:
<?php $args = array( 'hide_empty_fields' => false, 'hide_empty_groups' => false ); ?>

<?php if ( bp_has_profile( $args ) ) : ?>


text:
Q: http header spoofer in chrome I am trying to develop a chrome tool to spoof HTTP request and response headers. Request spoofing works fine. This code changes UA in request header but in response header I can't change anything. e.g. I am trying to change  "Set-Cookie" but it won't work. I have used two codes for response. Here's my code:
Request
var requestFilter = {
    urls: [ "<all_urls>" ]
  },

  extraInfoSpec = ['requestHeaders','blocking'],

  handler = function( details ) {

    var headers = details.requestHeaders,
      blockingResponse = {};

    for( var i = 0, l = headers.length; i < l; ++i ) {
      if( headers[i].name == 'User-Agent' ) {
        headers[i].value = 's';
        break;
      }
    }

    blockingResponse.requestHeaders = headers;
    return blockingResponse;
  };

chrome.webRequest.onBeforeSendHeaders.addListener( handler, requestFilter, extraInfoSpec );

Response
    chrome.webRequest.onHeadersReceived.addListener(function(details){
    details.responseHeaders[details.responseHeaders.length] = {name: 'Set-Cookie', value: 'some random value'};
    return {responseHeaders: details.responseHeaders};

    },{urls:["<all_urls>"],types:["xmlhttprequest","sub_frame"]},
    ["responseHeaders","blocking"]);

Response 2
    var responseListener = function(details){
    var rule = {
        "name": "Set-Cookie",
        "value": "Some Random Value"
    };
    details.responseHeaders.push(rule);
    return {responseHeaders: details.responseHeaders};
    };

    chrome.webRequest.onHeadersReceived.addListener(responseListener,
     {urls: [   "*://*/*" ] },
     ["blocking", "responseHeaders"]);


text:
Q: Shell script exits early for unclear reasons I'm using the following script to backup, using Borg Backup. But I'm running into an odd problem
Part of the script below does not execute. The script follows, then the output
SCRIPT:
#!/bin/bash

set -ex
set -o pipefail
export SERVER="myserver"
CLEVEL=zlib,9
. /home/faheem/.keychain/${HOSTNAME}-sh

#borg init -e none faheem@$SERVER:/mnt/backup-test
borg create -c 30 --compression $CLEVEL --stats faheem@ramnode:/mnt/backup-test::`hostname`-`date +%Y-%m-%d:%H.%M`  /home/faheem/test-borg
{ borg check faheem@$SERVER:/mnt/backup-test 2>&1 1>&3 | tr '\r' '\n' | grep -Ev "^Remote:\s*(Checking segments.*)?$" 1>&2; } 3>&1
mapfile -t testarchives < <(borg list --short faheem@$SERVER:/mnt/backup-test)
borg extract -n "faheem@$SERVER:/mnt/backup-test"::"${testarchives[-1]}"

OUTPUT:
+ set -o pipefail
+ export SERVER=ramnode
+ SERVER=ramnode
+ CLEVEL=zlib,9
+ . /home/faheem/.keychain/orwell-sh
++ SSH_AUTH_SOCK=/tmp/ssh-F7Uzg6CeQoTY/agent.5660
++ export SSH_AUTH_SOCK
++ SSH_AGENT_PID=5661
++ export SSH_AGENT_PID
++ hostname
++ date +%Y-%m-%d:%H.%M
+ borg create -c 30 --compression zlib,9 --stats faheem@ramnode:/mnt/backup-test::orwell-2016-09-16:05.04 /home/faheem/test-borg
+ borg check faheem@ramnode:/mnt/backup-test
+ tr '\r' '\n'
+ grep -Ev '^Remote:\s*(Checking segments.*)?$'

So the last two lines don't execute. But if I comment out the earlier lines, those two lines execute. Does anyone know what is going wrong?
UPDATE: If I take out grep (i.e. replace)
{ borg check faheem@$SERVER:/mnt/backup-test 2>&1 1>&3 | tr '\r' '\n' | grep -Ev "^Remote:\s*(Checking segments.*)?$" 1>&2; } 3>&1

with
{ borg check faheem@$SERVER:/mnt/backup-test 2>&1 1>&3 | tr '\r' '\n' 1>&2; } 3>&1

I get
+ set -o pipefail
+ export SERVER=ramnode
+ SERVER=ramnode
+ CLEVEL=zlib,9
+ . /home/faheem/.keychain/orwell-sh
++ SSH_AUTH_SOCK=/tmp/ssh-F7Uzg6CeQoTY/agent.5660
++ export SSH_AUTH_SOCK
++ SSH_AGENT_PID=5661
++ export SSH_AGENT_PID
++ hostname
++ date +%Y-%m-%d:%H.%M
+ borg create -c 30 --compression zlib,9 --stats faheem@ramnode:/mnt/backup-test::orwell-2016-09-17:03.18 /home/faheem/test-borg
+ borg check faheem@ramnode:/mnt/backup-test
+ tr '\r' '\n'
Remote: Checking segments 0.0%
Remote:
+ mapfile -t testarchives
++ borg list --short faheem@ramnode:/mnt/backup-test
+ borg extract -n faheem@ramnode:/mnt/backup-test::orwell-2016-09-17:03.18

Does the Remote: line correspond to grep failing to match the pattern and returning non-zero?
Here are a couple of relevant questions:
Can grep return true/false or are there alternative methods
and
Avoid grep returning error when input doesn't match
The latter question appears to be a similar situation, if not the same.

A: The set -e means that if grep returns non-zero (ie the pattern is not matched) then that, combined with pipefail means that the pipe fails and causes the script to abort.
So either

*

*remove set -e

*remove pipefail

*Add an || true in the grep segment to ensure that always returns zero

A: grep is designed to set an exit status according to whether or not a particular pattern is found, and in some cases is even used only for this purpose and any output is suppressed.  (That's the purpose of the -q switch to grep.)
sed is the "Stream EDitor" and is designed to filter a stream of text, converting it in some way (usually line by line) as it passes through.
Although there is a great deal of overlap between these two utilities, they do each have a specific purpose.  In this case you are evidently not interested in whether or not the pattern is found, you simply want to filter the text stream before passing it along.  That is a proper use case for sed, not for grep.

sed -E '/^Remote:\s*(Checking segments.*)?$/d' delme.txt

This is the exact equivalent of:
grep -Ev '^Remote:\s*(Checking segments.*)?$' delme.txt

...except that the grep command will give an error exit status if there are no lines besides those matching the pattern, and sed will not.


text:
Q: How would I loop through an array of objects and check for existence of key- or value parameter? Given this Array (key / value pairs):
 var array = [
    {name:  'Antonello',            location:'Barcelona'},
    {email: 'george@george.com',    name:'George'},
        {name:  'Mike',             coder: true}
    ]

how would a function look like that finds the element in an array of objects and returns the index (or -1 if no element of this kind).
NOTICE: this is a beginners exercise and no use of ES6 or findIndex.
This is my code. I want to check if either the key or the value is undefined. If not, return the array index.
function getIndex(array, key, value) {
    var indexFound = 0;
    for (var index in array) {
        if (array[index].key == undefined && array[index].value == undefined) {
            var indexFound = -1;
        } else {
            var indexFound = array[index];
        }
    }
    return indexFound
}

This is the function with the 3 parameters getIndex(array, key, value).
Expected outcome:
getIndex(array, "name", "Antonello") should return 0.
getIndex(array, "coder", false) should return -1.

A: Your implementation of  for...in loop is wrong, check the documentation here, for..in
Although you can use for..in loop for iterating over the array, important thing to note here from Mozilla docs is:-Documentation

Array indexes are just enumerable properties with integer names and are otherwise identical to general object properties. There is no guarantee that for...in will return the indexes in any particular order. The for...in loop statement will return all enumerable properties, including those with non–integer names and those that are inherited.
Because the order of iteration is implementation-dependent, iterating over an array may not visit elements in a consistent order. Therefore, it is better to use a for loop with a numeric index (or Array.prototype.forEach() or the for...of loop) when iterating over arrays where the order of access is important.

var array = [{
    name: 'Antonello',
    location: 'Barcelona'
  },
  {
    email: 'george@george.com',
    name: 'George'
  },
  {
    name: 'Mike',
    coder: true
  }
];

function getIndex(array, key, value) {
  var indexFound = -1;
  array.forEach((obj, index) => {
    if (obj[key] !== undefined && obj[key] === value) {
      indexFound = index;
    }
  });
  return indexFound;
}

var foundIndex = getIndex(array, 'name', 'Antonello');
console.log(foundIndex);

A:

var array = [
    {name:  'Antonello',            location:'Barcelona'},
    {email: 'george@george.com',    name:'George'},
    {name:  'Mike',             coder: true}
];

function getIndex(array, key, value) {
    var indexFound = -1;
    array.forEach(function(obj, index) {
        if (typeof obj[key] !== 'undefined' && obj[key] === value) {
            indexFound = index;
        }
    });
    return indexFound;
}

console.log(getIndex(array, "name", "Antonello"));
console.log(getIndex(array, "email", "george@george.com"));
console.log(getIndex(array, "coder", false));


text:
Q: Cannot Redirect Using $_SERVER Variables, PHP I have a PHP application (a request form) that first checks for an active $_SESSION before a user can access the site. Because of the timeout period set for this form there is rarely an active session. Here's the check:
if (isset($_SESSION['samlUserdata'])) {
    $attributes = $_SESSION['samlUserdata'];
    $user_department = $attributes['department'];
    $user_email = $attributes['email'];
    $user_employee_id = $attributes['employee_id'];
    $user_full_name = $attributes['full_name'];
}

...and here is the else {} that I use to grab the REQUEST_URI:
else {
    if (isset($_SERVER['REQUEST_URI'])) {
        $referer = $_SERVER['REQUEST_URI'];
        $redirect = "https://myinternalwebsite.net$referer";
    }
    header("Location: https://myinternalwebiste.net/confirm_auth.php?sso");
}

...and last, here is what I do with the $_GET
if (isset($_GET['sso'])) {
    if (isset($redirect)) {
        $auth->login($redirect);
    } else {
        $auth->login("https://myinternalwebsite.net/");
    }
}

However, once my session is killed I am never properly routed back to the URL set in the ['REQUEST_URI'], I am always just dumped onto the internal site's front page. I have troubleshooted this on and off for some time over the last week, to no avail. I've tried other variables in the $_SERVER array as well, such as ['REDIRECT_URL'].
I'm at a loss, and I'm sure this fairly simple for anyone with more experience than myself... so I am all ears and eager to learn.

EDIT:
Thank you for the comments below. Per your advice I will add the entirety of my code here, removing only the unnecessary parts. (And yes, I appreciate the tip to flip the initial (isset()) to (!isset(). Thank you for that.)
<?php
    session_start();
    $auth = new OneLogin\Saml2\Auth($saml_settings);

    if (isset($_SESSION['samlUserdata'])) {
        $attributes = $_SESSION['samlUserdata'];
        $user_department = $attributes['department'];
        $user_email = $attributes['email'];
        $user_employee_id = $attributes['employee_id'];
        $user_full_name = $attributes['full_name'];
    } else {
        if (isset($_SERVER['REQUEST_URI'])) {
            $referer = $_SERVER['REQUEST_URI'];
            $redirect = "https://example.net$referer";
        }
        header("Location: https://example.net/confirm_auth.php?sso");
    }

    if (isset($_GET['sso'])) {
        if (isset($redirect)) {
            $auth->login($redirect);
        } else {
            $auth->login("https://example.net/");
        }
    } else if (isset($_GET['slo'])) {
        $auth->logout();
    } else if (isset($_GET['acs'])) {
        $auth->processResponse();
        $errors = $auth->getErrors();

        if (!empty($errors)) {
            echo '
', implode(', ', $errors), '
';
        }

        if (!$auth->isAuthenticated()) {
            echo "
Not authenticated!
";
            exit();
        }

        $_SESSION['samlUserdata'] = $auth->getAttributes();
        if (isset($_POST['RelayState']) &&
OneLogin\Saml2\Utils::getSelfURL() != $_POST['RelayState']) {
        $auth->redirectTo($_POST['RelayState']);
        }
    } else if (isset($_GET['sls'])) {
        $auth->processSLO();
        $errors = $auth->getErrors();
        if (empty($errors)) {
            echo '
Sucessfully logged out!
';
        } else {
            echo '
', implode(', ', $errors), '
';
        }
    }

?>


text:
Q: jqplot - don't want to display / show the y axis I am using the jqplot charting library from quite sometime.
I don't want to display the y2axis (i.e when I am working with multiple axes/series)
Went through the documentation and found that 'show: false' will not show the axis.
Link here: http://www.jqplot.com/docs/files/jqplot-core-js.html#Axis.show
But this doesn't seem to work.
Any help would be greatly appreciated.
Thanks in advance

A: Fixed it.
Here's what I did.
axes: {
    yaxis: {
    tickOptions: {
        show: false
    },
    rendererOptions: {
        drawBaseline: false
    }
}

Setting tickoptions to false, hides the axis labels and ticks and drawBaseline: false hides the axis line.
Hope it helps.

A: You just need to specify showTicks : false
Here is a link on a working fiddle without yaxis ticks : http://jsfiddle.net/BLfRe/23/

A: I'm using jqplot and I wanted to hide the y2axis too in some case.
Using plot1.axes.y2axis.show = false; seems to work perfectly.
Can you put the piece of code you use in order to find what can cause your troubles?


text:
Q: Primefaces toggle color of dataGrid element by button click I would like to change the background color of an datgrid element by clicking on a commandbutton. I have no idea at the moment how to do this.
When I click on the following button, the element of the grid item is added to a list and I want to change the color of the panel item to (for e.g. yellow), so that the user could see, this element is marked.
<p:commandButton icon="ui-icon-pin-w"
                                    action="#{cmsMarkedDocumentHandler.addDocument(_document)}"/>

This is the code for my dataGrid.
<?xml version="1.0" encoding="UTF-8"?>
<ui:composition xmlns="http://www.w3.org/1999/xhtml"
    xmlns:ui="http://java.sun.com/jsf/facelets"
    xmlns:f="http://java.sun.com/jsf/core"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:p="http://primefaces.org/ui"
    xmlns:m="http://java.sun.com/jsf/composite/components/mmnet">

    <h:form id="docDataGridForm">
        <p:dataGrid id="docDataGrid"
                value="#{cmsDocumentSearchHandler.documentList}"
                var="_document"
                columns="2"
                rows="10"
                lazy="true"
                paginator="true"
                paginatorPosition="bottom"
                paginatorAlwaysVisible="false"
                paginatorTemplate="{CurrentPageReport}  {FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink}"
                rowsPerPageTemplate="5,10,15,20,25,50">

            <p:panel header="#{_document.shortName}" style="text-align:center">

                <h:panelGrid columns="2" style="width:100%" >
                    <p:outputLabel value="#{labels.name}" />
                    <p:outputLabel value="#{_document.name}" />

                    <p:outputLabel value="#{labels.dateiName}" />
                    <p:outputLabel value="#{_document.fileName}"/>

                    <p:outputLabel value="#{labels.aenderungsDatum} #{labels.aenderer}" />
                    <m:outputDateUser valueDate="#{_document.modDate}" valueUser="#{_document.modUser}" />

                    <p:commandLink update=":eastPanel" title="#{labels.details}">
                        <h:outputText styleClass="ui-icon ui-icon-search" style="margin:0 auto;" />
                        <f:setPropertyActionListener value="#{_document}"   target="#{documentHandler.entity}" />
                    </p:commandLink>

                    <m:cmsDocumentVersionLinks value="#{_document}" newLine="true" showDate="true"></m:cmsDocumentVersionLinks>

                    <p:outputLabel value="#{labels.merken}"></p:outputLabel>
                    <p:commandButton icon="ui-icon-pin-w"
                                    action="#{cmsMarkedDocumentHandler.addDocument(_document)}"/>

                </h:panelGrid>

            </p:panel>
        </p:dataGrid>
    </h:form>

    <h:form id="createCmsDocument">
    <p:outputPanel rendered="#{documentCategoryHandler.entity != null}">
        <m:formButtons id="createCmSDocButton"
                        entity="#{documentHandler.entity}"
                        renderCreate="true"
                        renderAbort="false"
                        renderDelete="false"
                        renderSave="false"
                        actionCreate="#{documentHandler.create()}"
                        updateCreate=":contentPanel :eastPanel"
                        rendered="true">
        </m:formButtons>
        </p:outputPanel>
    </h:form>

</ui:composition>

A: I had a similar requirement so I designed this solution.
In your cmsMarkedDocumentHandler class, use a HashSet to keep track of what is clicked:
    private Set<Document> selectedDocuments = new HashSet<Document>();
    // this will hold the currently selected document
    private Document document = new Document();

Your addDocument would be modified to toggle the elements on this HashSet:
public void addDocument() {
    // your other business logic
    if(this.selectedDocuments.contains(document)) {
        this.selectedDocuments.remove(document);
    } else {
        this.selectedDocuments.add(document);
    }
}

Need a new method to determine what CSS class applies to the current element in grid:
public String getStyleClass(final Document document) {
    if(this.selectedDocuments.contains(document)) {
        return "documentSelected";
    } else {
        return "";
    }
}

The primefaces code would look like this:
<p:dataGrid id="docDataGrid" value="#{cmsMarkedDocumentHandler.documentList}" columns="7" var="_document">
    <p:panel id="document-#{document.id}" styleClass="#{cmsMarkedDocumentHandler.getStyleClass(_document)}">
        <p:commandLink process="@this" action="#{cmsMarkedDocumentHandler.addDocument}" value="Add Document" update="@parent">
            <f:setPropertyActionListener value="#{_document}" target="#{cmsMarkedDocumentHandler.document}" />
        </p:commandLink>
    </p:panel>
</p:dataGrid>

When the commandLink is clicked, addDocument will put the _document into the HashSet (or remove it if it's already there) then the update attribute of commandLink will cause the @parent to refresh, which calls getStyleClass to apply the appropriate selected/notselected class. Good Luck!