text:
Q: While-loop + fgets error #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <cstdlib>
int main ()
{
    char ans[100];
    int count;
    count=0;
    char *arr[100];
    char *srtarr[100];

    while(count<100)
    {
        if(strcmp(ans,"done\n")!=0)
        {
            printf("Enter names when done type done:");
            fgets(ans,100,stdin);
            arr[count]=strdup(ans);
        }
        printf("%s",arr[count]);
        count++;
     }

    system("pause");
    return 0;
}

When I run this code the program stops working. Im very new to c and might have made a few errors. I think the problem is either the while loop or the fgets() function.
EDIT: I corrected the while loop however I'm not understanding how to initialize the array. Doesn't each element within the array get filled as the loop progresses?

A: You initialize 'count' to 0, hit the while loop and use 'count - 1' as an array index.  An array index of -1 definitely could crash your program.

A: You have at least two cases of undefined behavior in your code:

*

*You don't in initialize any of the arrays, meaning the pointers in them are indeterminate.

*You use a negative index in the first iteration.

Also, you should not forget that fgets leave the newline in the string, so your string comparison will never succeed.

My recommended solution: A loop while count is less than 100, then inside the loop check for "done" (or rather "done\n") using ans (before duplicating it) and break out of the loop then.


text:
Q: QuickCheck limit to only certain data constructor I have a data type definition:
data Point = Point {x :: Int, h :: Int} | EmptyPoint

In my property test, I would like to limit the test only on the Point constructor cases. For example point1 - point2 = Point 0 0. This presumes that the accessor x is defined which is not the case with EmptyPoint.
in other words: I don't want EmptyPoint to be generated.
Is there a way to do that?

A: Instead of automatically deriving the Arbitrary class for your type (which is what, I assume, you're doing at the moment), you can just write one manually and make it generate your points however you want, for example:
instance Arbitrary Point where
    arbitrary = Point <$> arbitrary <*> arbitrary

Or in a slightly more verbose way if you like:
instance Arbitrary Point where
    arbitrary = do
        x <- arbitrary
        y <- arbitrary
        pure Point { x, y }

redpajama_set_name: RedPajamaStackExchange


text:
Q: Can't connect to SQL Managed Instance from Azure Function App (Login timeout expired) I'm trying to connect to a SQL managed instance from an Azure Function App written in Python. The managed instance is under a Network Security Group and has multiple Inbound-rules that controls access to it. The function app is hosted in the same Azure subscription, and all the Outbound IP Addresses are white-listed in the said security group, with 3342 port access. The function app works when tested in local machine (local machine's IP is white-listed too). But when deployed in cloud, it shows '[HYT00] [Microsoft][ODBC Driver 17 for SQL Server]Login timeout expired (0) (SQLDriverConnect)')'.
I'm using the following code to connect to the database:
server = '<server_name>.windows.net,3342'
database = 'database'
username = 'Admin'
password = "strongpassword"
cnxn = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server};SERVER='+server+';DATABASE='+database+';Uid='+username+';Pwd='+ password+';')

Function can be called anonymously, and when I do, there is an error and I see the following in the logs:
Result: Failure Exception: OperationalError: ('HYT00', '[HYT00] [Microsoft][ODBC Driver 17 for SQL Server]Login timeout expired (0) (SQLDriverConnect)') Stack: File "/azure-functions-host/workers/python/3.9/LINUX/X64/azure_functions_worker/dispatcher.py", line 407, in _handle__invocation_request call_result = await self._loop.run_in_executor( File "/usr/local/lib/python3.9/concurrent/futures/thread.py", line 58, in run result = self.fn(*self.args, **self.kwargs) File "/azure-functions-host/workers/python/3.9/LINUX/X64/azure_functions_worker/dispatcher.py", line 649, in _run_sync_func return ExtensionManager.get_sync_invocation_wrapper(context, File "/azure-functions-host/workers/python/3.9/LINUX/X64/azure_functions_worker/extension.py", line 215, in _raw_invocation_wrapper result = function(**args) File "/home/site/wwwroot/dbConnTest/__init__.py", line 22, in main cnxn = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server};SERVER='+server+';DATABASE='+database+';Uid='+username+';Pwd='+ password+';Connection Timeout=30;')

What should I do? Is this related to ODBC driver version? Or am I using the wrong IP Addresses? I've checked both the IP addresses in Azure Portal > Networking and in Azure CLI with:
az webapp show --resource-group <resource group> --name <function app> --query outboundIpAddresses --output tsv

What am I missing?

A: Partially solved by Microsoft Support. Function apps on Consumption plans apparently have different Outbound IP addresses than what is given in the Azure portal. So the recommendation was to add the data center of the specific region (of the function app) to the whitelist.
Relevant Documentation
I followed the link, downloaded a JSON file, found the data center IP address prefixes (under 'AzureCloud.' key) and added them to the whitelist.
The connection to DB code is:
server = 'tcp:<server-name>.public.xxxxxxxxxxx.database.windows.net,3342'
database = 'database'
username = 'Admin'
password = "verystrongpass_cantbreakit_nananana"
conn = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server};SERVER=' + server + ';DATABASE=' + database+';UID=' + username + ';PWD=' + password)
cursor = conn.cursor()


text:
Q: Replace substrings using regex So I've been trying to make this simple encryption program but I can't seem to figure out some things.  The phrase I need to enter is
This is a very big morning.

When I enter it though it returns the string
This is a ag',rery dug>?/ijeb..w ssadorninjeb..w

Instead I return
This is a ajedg>P/..w',rery dg>P/ijedg>P/..w ssadorninjedg>P/..w

I don't understand why and how to fix it? I've been learning java for around a month now so I'm still fresh and if there's a similar question that's already been answered please link me there and I'll delete this post.
Here's the code:
import static java.lang.System.out;
import java.util.Scanner;
class Encryption {
    public static void main(String[] args) {
        Scanner userInput = new Scanner(System.in);
        Crypto user1 = new Crypto();
        out.print("Please enter in a sentence: ");
        String user = userInput.nextLine();
        user1.encrypt(user);
        out.print(user1.getEncrypt());
    }
}

public Crypto() { }
public String myEn;
public void encrypt(String Sentence) {
    myEn = Sentence.replaceAll("v","ag',r")
                   .replaceAll("m" , "ssad")
                   .replaceAll("g" , "jeb..w")
                   .replaceAll("b" , "dg>P/");
}

public String getEncrypt() {
        return myEn;
}
}

A: The reason you're getting the different output is because the chained replaces take the return value of the previous replaces. So in your case, if there was a v, it would be changed with ag',r which has a g in it. That g would then trigger replaceAll("g" , "jeb..w").
To avoid this from happening, you should change the order of the replaces:
Sentence.replaceAll("g" , "jeb..w")
        .replaceAll("b" , "dg>P/")
        .replaceAll("v","ag',r")
        .replaceAll("m" , "ssad");

However, the first two replace statements can't be fixed because one replaces b with a string that has a g in it, and vice-versa, so you might want to change the characters you're replacing.

A: When you replace the g its replacement contains a b so then when you replace the b's you get all the b's from the g replacement also replaced. and also for the v's
What you could do is
Sentence.replaceAll("g" , "jeb..w")
    .replaceFirst("b" , "dg>P/")     // as no g's before b's and only want to replace the first
    .replaceFirst("v","ag',r")
    .replaceFirst("m" , "ssad");

But this only works for this one sentence.

What you could do:

*

*Create a map of all your characters to be replaced and there replacement.

*Create a list of the indices of each character that is to be replaced on the original string.

*Reverse the order of the list (highest to lowest)

*Starting from the first index in the list (the last character to be replaced) replace the character at that index with its replacement from the map

*Repeat 4 working backwards down the string.

A: Firstly, you should use replace(), not replaceAll(). Both replace all matches found, but replaceAll() uses regex to match and replace() uses plain text.
Next, your replacements are getting in the way of each other, so use a StringBuffer and work from the eighth and end backwards replacing one character at a time.
Decryption should likewise work one character at a time starting from the left.

A: As others already told you problem is that you are replacing characters in few iterations (replaceAll calls) instead of one. If you want to prevent replacing characters that ware used to replace other characters you can use appendReplacement and appendTail from Matcher class.
Here is how you can do it like
// We need to store somewhere info about original and its replacement
// so we will use Map
Map<String, String> replacements = new HashMap<>();
replacements.put("v", "ag',r");
replacements.put("m", "ssad");
replacements.put("g", "jeb..w");
replacements.put("b", "dg>P/");

// we need to create pattern which will find characters we want to replace
Pattern pattern = Pattern.compile("[vmgb]");//this will do

Matcher matcher = pattern.matcher("This is a very big morning.");

StringBuffer sb = new StringBuffer();// this will be used to create
                                     // string with replaced characters

// lets start replacing process
while (matcher.find()) {//first we need to find our characters

    // then pick from map its replacement
    String replacement = replacements.get(matcher.group());
    // and pass it to appendReplacement method
    matcher.appendReplacement(sb, replacement);

    // we repeat this process until original string has no more
    // characters to replace
}
//after all we need to append to StringBuffer part after last replacement
matcher.appendTail(sb);

System.out.println(sb);

Output:
This is a ag',rery dg>P/ijeb..w ssadorninjeb..w.

Voilà.


text:
Q: how to code previous and next button in pagination in php I already coded the pagination for my page, and it works well, but I could not figure out the way for the next and previous button If the page greater than 10 pages. Here is my code.

<?php
include '../controllers/config.php';

/// pagination
$numberpage = 5;
$page = isset($_GET['page']) ? (int) $_GET['page'] : 0;

$countSql = $sqlCon->prepare("select COUNT(id) from posts ");
$countSql->execute();
$row = $countSql->fetch();
$numberRecodes = $row[0];

$numberLink = ceil($numberRecodes / $numberpage);

$start = $page * $numberpage;
if (!$page) {
    $page = 0;
}

// select all data in table posts
$selectQuery = "select posts.category, posts.title, posts.create_date from posts limit $start, $numberpage";
$stmtArticle = $sqlCon->prepare($selectQuery);
$stmtArticle->execute();
$articleList = $stmtArticle->fetchAll();
$stmtArticle->closeCursor();
?>

this is the numbers link that can click on for pagination. How can I make a next and previous button in this block? Can you guys help me a little bit? So that is mean If I have 50 recodes in my database table, and divide by 5 so I will have 10 pages, and I want If the page more than 5 and then the button text will appear and I just click next for the rest of the number behind page 5. The same thing with the previous button.

   <?php
       for ($i = 0; $i < $numberLink; $i++) {
            $y = $i + 1;
         echo '' . $y . '';
         }
       ?>

Maybe something like this one:
image for pagination
thank you so much.


text:
Q: In nodejs, how can I read a CSV header first but still handle the rest of the file asynchronously I want to read in a csv file, but based on the headers I want to query input from the user ('Is this column a string or a number column?').
This means that the routine is 'doubly' asynchronous; reading the stream and querying the user while processing the header row.
The libraries I've seen so far do not make it possible to handle the header row asynchronously or I'm missing something.
How could I implement this without having to reimplement the csv logic myself.
let csvHeader = null
fs.createReadStream(path)
    .pipe(csv_parse({ delimiter }))
    .on('data', function (csvrow) {
        //do something with csvrow
        if (csvHeader === null) {
            //handle header asynchronously
            csvHeader = ....
        } else {
            //handle row
        }
    })
    .on('end', function () {
        ....


text:
Q: C++ Armadillo Generate Indices uvec of a given vec or matrix without looping it Hellos guys,
My question might be obvious but i didn't find answers on other posts or Armadillo Doc.
I would like to create a vector B(arma::uvec in my case), with every index of a given vector A. So the needed elements are (0:A.n_elem-1). I could loop it, but I need to optimize time at its best, so I just want to know if I can generate it without looping it. Last point, I would like to avoid C++ 11.
Thank you for your time.
EDIT 1 :
I did use find_finite(X), to generate my indices vec, because my datas are all finite, i still don't know the proper way to do it.

A: I don't quite understand with every index of a given vector A, but if you need B to contain 0:A.n_elem-1, you can do:
vec B = regspace<vec>(0, A.n_elem-1)

Above code is equivalent to B = 0:length(A)-1, in MATLAB.
Hope that helps.


text:
Q: HTML/Bootstrap Table over flow and how workaround it I have a form wherein the user may search for example a name. after searching a table will come out. It works perfectly in the desktop but as you know I used bootstrap and it is responsive and usable in a mobile device. Now when I adjust the window size the nav bar collapses, design changes and becomes a mobile version. But then the table cannot go as small as the screen and it causes overflow on the right side. It cant go smaller because the words are long and cant we word wrapped with space because there is no space. So how do I make my nav bar and footer stretch to the width of the overflow?here is my sample interface...

      <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar">

      </button>
      Envoy Search Rackings

        <li class="<?php if(strpos($currentpage,"profile")==TRUE) {print $active;}
  ?>">Search Database

        <li class="<?php if(strpos($currentpage,"insert")==TRUE) {print $active;}
  ?>">Add Brochure

Export Data Modified

 Logout

and here is my nav bar code. my footer has no content yet so i'll just copy the code from navbar to strech just in case. Thank you very much! sorry if i explained too long!

A: If anybody stumbles over this and just wants to make the table fit the device width:
Use

 ...

 around your
 tags.
Not sure if this is what the OP wants, but I hope it helps anyone anyway :D

A: I wouldn't recommend stretching the nav and footer to full width as of table because user wouldn't be able see the menu button in the nav bar in first fold as it would be to the far right under scroll fold.
Basically for tables you will have to fix the container width to 100% and add overflow:auto scrollbar so user can scroll/slide just the table part to see more rather than the whole page.


text:
Q: HttpUrlConnection Post with header info but no body I am developing an Android app that uses an API I developed.
I am doing this connection using HttpUrlConnection and so far the login works fine. The problem arises with the logout. It´s not doing anything. When I do the logout request with Postman then it works fine, but with HttpUrlConnection it does not.
The logout works like this:
Do a POST request to http://ipaddress:12345/api/LogOut
and in the header include the token of the logged user. Then the server should go to the database and delete the token for that user:
This is how I´m trying to do the request:
URL url = new URL(getString(R.string.url) + "LogOut");
HttpURLConnection con = (HttpURLConnection) url.openConnection();

con.setRequestProperty("Content-Type", "application/json");
con.setRequestProperty("Token", TokenSingleton.getToken());

con.setReadTimeout(10000);
con.setConnectTimeout(15000);
con.setRequestMethod("POST");
con.setDoInput(true);
con.setDoOutput(true);
con.setUseCaches(false);

con.connect();
con.getOutputStream().flush();
con.getOutputStream().close();
con.disconnect();

A: Nothing happens until you do some input. At least call getResponseCode() to see whether you got a 200 or not. Preferably you should consume the input stream, if 200 <= response code <= 299, otherwise the error stream.
NB setDoOutput(true) sets the request method to POST. You don't need to do that yourself. And setDoInput(true) is the default. And close() implies flush().


text:
Q: Include joined table records by a specific query, if any Let's assume that I want to select an Author, includeing their books published in 1942 (one author has many books).
I tried doing this:
Author.findOne({
  where: {
    name: "Alice"
  },
  include: [{
    model: Book,
    where: {
      year: 1942
    }
  }]
}).then(authorAndTheirBooks => { ... })

authorAndTheirBooks is going to be null if there is no Book published in 1942. What I'd like to have is to get an empty array as books (if none was matched) and get the array of books if there are books published by Alice in 1942 (which already happens).
If I remove that filter, it works fine.
How to solve this? To fetch the author, including their books, which were published in 1942?


text:
Q: fontawesome 6.2 animations are not working at all I am trying to get a spinner icon to spin with no success. I have downloaded the latest font awesome and created a very basic html file to try and eliminate any variables to make it work.
Here is the html:
<!doctype html>

    <link href="C:/Users/<my-user-name>/Downloads/fontawesome-free-6.2.0-web/css/all.css" rel="stylesheet">

The above code renders the icon but the animation doesn't work.
The only thing I have noticed is that when I inspect the icon element in chrome and look at the style details for .fa-spin, it shows a style called animation-timing-function: var(--fa-animation-timing, linear); but when I hover over that style, text appears stating "--fa-animation-timing is not defined".
As far as I can tell from the fontawesome host yourself instructions I have included everything I need. I didn't delete any files from the extracted free font awesome download. I also tried the alternative option to referencing all.css, which involves referencing fontawesome.css, brands.css and solid.css.
What am I missing here?
Thanks so much in advance!

A: We just ran into this issue and found the potential reason.
https://fontawesome.com/docs/web/troubleshoot/
Points to https://developer.mozilla.org/en-US/docs/Web/CSS/@media/prefers-reduced-motion#user_preferences
And when we toggled "Show animations in Windows." The animations started working again.


text:
Q: Flutter Sdk 31+ MISSING_PERMISSIONS when permission is granted I am working on call log history app, and my application request call log history permission and phone state permission before user login. I can read call logs on lower than 31 sdk level real devices, but sdk level 31+ real devices give this error:

this is my android manifest file:

I can't found any way to fix this problem. My code is working all device lower than sdk 31.
How can I fix this.

A: I solved this problem like that.
Go to the app build.gradle file and change target and compile sdk versions. When some features can't work higher sdk, you should change your target sdk.


text:
Q: Excel function to join 2 columns in different file I'm new in Excel .
I want search matched values between F1.xlsx and F2.xlsx on the id. And write in the F2.xlsx the response on the id that exist in F1.xlsx.
Below a figure to represent my tables!.

Any helps

A: You can do this with a basic VLOOKUP function. It does not make a difference whether you select a range in the same workbook or in a different workbook, Excel will take care of putting the correct file and worksheet references in the formula. So when you are writing the formula and need to select the range in a different workbook, just click on the workbook F1.xlsx, and select the range you want.
The formula itself (which you put in cell D2 and then copy down):
=VLOOKUP(B2;'FULL-PATH-TO-YOUR-FILE[F1.xlsx]Sheet1'!$A$2:$C$7;3)
But you do not need to actually write the entire reference to the lookup range, if you select the range manually (with your mouse), Excel will do this. The Full path will not be added unless you close the F1.xlsx file.
Comment: you can use the same formula to put the name in the second file (based on the ID)


text:
Q: Inserting text between certain lines in a batch file using Python I want to insert around 4000 lines of text from one text file to another but the list of text must be inserted between the current lines leaving empty line above and below it.
e.g. output.txt
old text

new text
new text

old text

all the 4000 lines are in the following format: mydata /Alarm /Stop factor group1 cam.ad
The number of lines will increase every week so I can't specify to just copy the 4000 lines.
Can anyone give me advice on how to do this? I tried some scripts but I was only able to edit the line with the specified text so it didn't work when the number of lines increased and it didn't save them in the output file.
I tried the following script:
import fileinput

for line in fileinput.input('input.txt', inplace=1):
 print line,
 if line.startswith('old text'):
     print 'new text'

A: you have to work it out using an algorithm close to this:
here I consider new being the text that has to be imported into old.
open two files, the original one, and a temporary one tmp

*

*read all lines up to 'old text', and write them in tmp

*insert \n in tmp

*insert newtext in tmp

*insert \n in tmp

*insert 'old text' and all following lines in tmp

*copy the tmp file over old file

basically, in python that would look like
with open('oldfile') as old:
    with open('newfile') as new:
        with open('tmpfile') as tmp:
            …

sadly, without more context, I can't give you a better answer.


text:
Q: Angular - trying to use *ngif on router-outlet to share data from child to parent /angular tabs I'm using tabs in angular and trying to share data from child component "demandeConge" to the parent "congeComponent". The problem is that i want to do ngIf on the  to place this line of code [model]="model" (modelChanged)="modelChangeHandler($event)" in the router-outlet when the active routerlink is 'demandeConge'.
What i tried :
<div *ngIf="router.url=='demandeConge'">
    <router-outlet [model]="model" (modelChanged)="modelChangeHandler($event)"></router-outlet>
</div>

Parent component (ts file):
  label: string;
  route :string
}
@Component({
  selector: 'app-congeComponent',
  templateUrl: './congeComponent.component.html',
  styleUrls: ['./congeComponent.component.css']
})
export class CongeComponentComponent implements OnInit {
  @ViewChild(DemandeCongeComponent) child: DemandeCongeComponent;

  conge:Conge = new Conge();
  model : Date[] =[]
  tabs: TabItem[] = [
    {
      label: 'Range of days',
      route: 'demandeConge',
    },
    {
      label: 'Multiple days',
      route: 'demandeMultipleDays',
    },
  ];

    asyncTabs: Observable<TabItem[]>;

  constructor(private route: ActivatedRoute, router:Router) {
  }

  modelChangeHandler(model:Date[]) {
    this.model=model;
    console.log("[modelChangeHandler]:"+model)
  }

Parent HTML file:
<mat-card>
  <mat-card-title>Demander un congé</mat-card-title>
  <br>
  <mat-card-subtitle>Pick your range of dates or multiple dates</mat-card-subtitle>

  <nav mat-tab-nav-bar dynamicHeight>
    <a mat-tab-link *ngFor="let tabItem of tabs" [routerLink]="tabItem.route" routerLinkActive #rla="routerLinkActive"
      [active]="rla.isActive">
      {{tabItem.label}}
    </a>
  </nav>
  <div *ngIf="router.url=='demandeConge'">
    <router-outlet [model]="model" (modelChanged)="modelChangeHandler($event)"></router-outlet>
  </div>
  <!-- <app-demandeMultipleDays [model]="model" (modelChanged)="modelChangeHandler($event)"></app-demandeMultipleDays> -->
  <mat-card-actions>
    <button mat-button>Submit</button>
  </mat-card-actions>
</mat-card>

App-routing module :
      path:'congeComponent',
      component:CongeComponentComponent,
      children:[
        {
          path:'demandeConge',
          component:DemandeCongeComponent,
          // outlet:'rangeCone'
        },
        {
          path:'demandeMultipleDays',
          component:DemandeMultipleDaysComponent,
          // outlet:'multipleConge'
        }


text:
Q: Issues scrolling horizontally in Java/Selenium I've gone through previous posts on this and am still having problems getting this to work.
I have a small scroll bar I need to move to the right so that I can access items I need to test. The code for the scroll bar is as follows:

The scroll bar is inside a container, I don't know if that's an issue.

Here is my code:
 WebElement scroll = driver.findElement(By.xpath("//html/body/div[2]/main/div/ui-view/ui-view/div[2]/div/div[1]/su-flight-filters/div/aside/div/section/div/div/div[2]/div/div[2]/div"));
 JavascriptExecutor js = (JavascriptExecutor)driver;
 js.executeScript("document.getElementsByClassName('ngscroll-scrollbar').scrollRight += 50", "");

I do not get any errors but the scroll bar does not move either. I've tried values of 50, 250 and 400.
Anyone have any ideas?

A: .getElementsByClassName() returns a collection. Try
js.executeScript("document.getElementsByClassName('ngscroll-scrollbar')[0].scrollRight += 50", "");

to scroll the first matching element. You'll have to check and make sure the first match is the one you want.

A: Use Action class to move the slider, i find this as the convnent way
choose value of X is any its depends of width of your slider and if you use for loop to drag pointer on multiple position
 WebElement slider = driver.findElement(By.id("slider"));
    int width=slider.getSize().getWidth();
    Actions move = new Actions(driver);
     Action action = (Action) move.dragAndDropBy(slider, 30, 0).build();
    action.perform();


text:
Q: How to implement a search for optional fields using Spring data JPA? How to implement a search for optional fields using Spring data JPA? I already researched in several places, but nothing helped me.

A: After some time of trial and error, I was able to implement my search for optional fields.
1st) I extended my repository with the JpaSpecificationExecutor interface
package br.mp.mpce.sge.repository;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.stereotype.Repository;

import br.mp.mpce.sge.domain.Documento;
import br.mp.mpce.sge.domain.Setor;

@Repository
public interface DocumentoRepository extends JpaRepository<Documento, Integer>, JpaSpecificationExecutor<Documento> {

    Page<Documento> findPageBySetorCadastro(Setor setor, Pageable pageRequest);

}

2) I implemented methods that returned Specifications according to my search parameters.
package br.mp.mpce.sge.specifications;

import java.time.LocalDateTime;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.data.jpa.domain.Specification;

import br.mp.mpce.sge.domain.Documento;
import br.mp.mpce.sge.domain.Setor;

public final class DocumentoSpecification {

    public static Specification<Documento> byCodigo(Integer codigo) {
        return new Specification<Documento>() {

            private static final long serialVersionUID = -4943925466558950754L;

            @Override
            public Predicate toPredicate(Root<Documento> root, CriteriaQuery<?> query,
                    CriteriaBuilder criteriaBuilder) {
                return criteriaBuilder.equal(root.get("codigo"), codigo);
            }

        };
    }

    public static Specification<Documento> byAno(String ano) {
        return new Specification<Documento>() {

            private static final long serialVersionUID = 8333055743400529192L;

            @Override
            public Predicate toPredicate(Root<Documento> root, CriteriaQuery<?> query,
                    CriteriaBuilder criteriaBuilder) {
                return criteriaBuilder.equal(root.get("ano"), ano);
            }

        };
    }

    public static Specification<Documento> byDataInicial(LocalDateTime dataInicial) {
        return new Specification<Documento>() {

            private static final long serialVersionUID = -9172458840598392417L;

            @Override
            public Predicate toPredicate(Root<Documento> root, CriteriaQuery<?> query,
                    CriteriaBuilder criteriaBuilder) {
                return criteriaBuilder.greaterThanOrEqualTo(root.get("dataCadastro"), dataInicial);
            }

        };
    }

    public static Specification<Documento> byDataFinal(LocalDateTime dataFinal) {
        return new Specification<Documento>() {

            private static final long serialVersionUID = 1422089735211883866L;

            @Override
            public Predicate toPredicate(Root<Documento> root, CriteriaQuery<?> query,
                    CriteriaBuilder criteriaBuilder) {
                return criteriaBuilder.lessThanOrEqualTo(root.get("dataCadastro"), dataFinal);
            }

        };
    }

    public static Specification<Documento> bySetor(Setor setor) {
        return new Specification<Documento>() {

            private static final long serialVersionUID = -2336742358257555013L;

            @Override
            public Predicate toPredicate(Root<Documento> root, CriteriaQuery<?> query,
                    CriteriaBuilder criteriaBuilder) {
                return criteriaBuilder.equal(root.get("setorCadastro"), setor);
            }

        };
    }
}

3º) I implemented the class of service method.
public Page<Documento> findByFields(Integer codigo, String ano, String dataInicio, String dataFinal, Integer page,
            Integer lines, String direction, String orderBy) {
        UsuarioSS usuarioSS = UsuarioServiceImpl.authenticated();
        if (usuarioSS == null) {
            throw new PersonalizedAutorizationException("Acesso negado - Usuario deve estar autenticado");
        }

        Usuario usuario = usuarioService.findById(usuarioSS.getId());
        PageRequest pageRequest = PageRequest.of(page, lines, Direction.fromString(direction), orderBy);

        Specification<Documento> specification = DocumentoSpecification.bySetor(usuario.getSetor());

        if (codigo != null) {
            specification = specification.and(DocumentoSpecification.byCodigo(codigo));
        }

        if (ano != null) {
            specification = specification.and(DocumentoSpecification.byAno(ano));
        }
        if (dataInicio != null) {
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            LocalDate localDateInicio;
            localDateInicio = LocalDate.parse(dataInicio, formatter);
            LocalDateTime localDateTimeInicio = localDateInicio.atStartOfDay();
            specification = specification.and(DocumentoSpecification.byDataInicial(localDateTimeInicio));
        }
        if (dataFinal != null) {
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            LocalDate localDateFinal;
            localDateFinal = LocalDate.parse(dataFinal, formatter);
            LocalDateTime localDateTimeFinal = localDateFinal.atStartOfDay();
            specification = specification.and(DocumentoSpecification.byDataFinal(localDateTimeFinal));
        }

        Page<Documento> pageDoc = documentoRepository.findAll(specification, pageRequest);

        if (pageDoc.getContent().isEmpty()) {
            throw new PersonalizedObjectNotFoundException(super.messageSource.getMessage("error.notFound",
                    new String[] { super.messageSource.getMessage(
                            StringUtils.uncapitalize(super.getEntityClass().getSimpleName()), null,
                            StringUtils.uncapitalize(getEntityClass().getSimpleName()), null) },
                    "error.notFound", null));
        }

        return pageDoc;

    }

4º) Implemented the search method in the restcontroller.
@RequestMapping(value = "/search", method = RequestMethod.GET)
    public ResponseEntity<Page<Documento>> findPageByFields(
            @RequestParam(value = "codigo", required = false) Integer codigo,
            @RequestParam(value = "ano", required = false) String ano,
            @RequestParam(value = "dataInicio", required = false) String dataInicio,
            @RequestParam(value = "dataFinal", required = false) String dataFinal,
            @RequestParam(value = "page", defaultValue = "0") Integer page,
            @RequestParam(value = "lines", defaultValue = "10") Integer lines,
            @RequestParam(value = "direction", defaultValue = "DESC") String direction,
            @RequestParam(value = "orderBy", defaultValue = "dataCadastro") String orderBy) {
        Page<Documento> pageDocumento = documentoService.findByFields(codigo, ano, dataInicio, dataFinal, page, lines,
                direction, orderBy);
        return ResponseEntity.ok().body(pageDocumento);
    }


text:
Q: How to match a space at the beginning of the expression python? I have the following String
"Sample"
however in some occurences there may be one or more spaces in the beginning:
"  Sample" or " Sample"
Without using trim, what regular expression can I use to match if there is one? I am using (\s+) for the current String. I want the space to be included as part of the same one group.

A: You don't need regular expressions:
s = " Sample"
if s[0] == ' ':
    # do something
else:
    # do something else

But if you want regex:
import re
s = ' Sample'
if re.match(r"\s+.+", s):
   # found space at beginning, do something

A: "   Sample".lstrip()

The reason that lstrip is prefereable is that there are any number of hidden (or unprintable) characters.  To get a regular expressions to capture all the purmutations is a little messy display wise.  Clear code is the best code.
There is the option of using POSIX character classes within your regex, however the re module does not seem to support them at this time. You will have to use a different module that supports the POSIX classes (regex 0.1.20120323).
(Note: Newly registered so I could not 'post more than 2 hyperlinks'.)
References:

*

*docs.python.org/library/string.html
"If chars is omitted or None, whitespace characters are removed."

*stackoverflow.com/questions/9897375/how-to-match-a-space-at-the-beginning-of-the-expression-python
"POSIX character classes ... [:space:]      \s  \s  [ \t\r\n\v\f]   Whitespace characters"

*pypi.python.org/pypi/regex
"POSIX character classes are supported. This is actually treated as an alternative form of \p{...}."

*http://pypi.python.org/pypi/regex
"Alternative regular expression module, to replace re."

A: Use find():
s = " Sample"
pos = 0
if s.find(' ') == pos:
    print 'Space found!'

You can then increment pos until you no longer find a space.


text:
Q: Error Building project on android studio 2.2 ubuntu 32 bit os I have this problem building my project ever since i  upgraded the minSdkVersion to 15 and buildToolsVersion to 25.0.3 i keep having this error
 Error:java.util.concurrent.ExecutionException: java.lang.RuntimeException: AAPT process not ready to receive commands
i have tried downgrading the build tool to 24 but i get this error
 25.0.0 is the minimum required to build


text:
Q: Longest Common Prefix - Divide and Conquer approach complexity analysis I am trying to understand how the time and space complexity for D&C approach of finding longest common prefix from the array of strings has been derived. Example: The array of strings is ["leet", "leetcode", "leeds","le"] and the output would be "le" It's a leetcode problem 14
Code:
public String longestCommonPrefix(String[] strs) {
    if (strs == null || strs.length == 0) return "";
        return longestCommonPrefix(strs, 0 , strs.length - 1);
}

private String longestCommonPrefix(String[] strs, int l, int r) {
    if (l == r) {
        return strs[l];
    }
    else {
        int mid = (l + r)/2;
        String lcpLeft =   longestCommonPrefix(strs, l , mid);
        String lcpRight =  longestCommonPrefix(strs, mid + 1,r);
        return commonPrefix(lcpLeft, lcpRight);
   }
}

String commonPrefix(String left,String right) {
    int min = Math.min(left.length(), right.length());
    for (int i = 0; i < min; i++) {
        if ( left.charAt(i) != right.charAt(i) )
            return left.substring(0, i);
    }
    return left.substring(0, min);
}

Complexity Analysis as stated on their website
Time Complexity: O(S), where S is the number of all characters in the array, S = mn. Time complexity is T(n) = 2 T(n/2) + O(m). Therefore time complexity is O(S).
Space Complexity:O(mlog(n))
I understood the part where T(n) = 2 T(n/2) + O(m) but from there how did they derived m*n as time complexity. For space complexity I think we are considering height of recursion tree times cost each recursive call takes.
n is the number of strings in an array and m is the length of prefix.

A: The m*n complexity comes from that O(m) term.  It's replicated (executed) n times: at each iteration, you split the list in half (by quantity of strings, n), digging down until your base case gets executed once for each of the n strings.  Each of those carries out an O(m) operation.
Also, each merge carries out an O(m) operation, for a total of 2*n-1  of those.  2*n-1 is O(n).  O(m) * O(n) is O(mn).
Is that clear enough?


text:
Q: How to Filter Records After GroupBy with LINQ + EF Core 6 Given this simple Contract entity and assuming that a customer can have many Contracts with different start dates and statuses.
public class Contract {
 [Key]
 int ContractId { get; set; }
 int CustomerId { get; set; }
 string Status { get; set; }
 DateTime ContractStartDate { get; set; }
}

I'm trying to write a query to find that latest contract for each customer and then filter out certain statuses. I need to filter the status after finding the latest contract, to ensure I'm getting their current status.

ContractID
CustomerID
ContractStartDate
Status

1
1
2022-01-01
Active

2
1
2022-31-05
Inactive

3
2
2022-01-03
Active

4
2
2022-31-07
Inactive

From the above data set, I would expect to get contracts 2 and 4 in the results. This is why I can't filter on status before grouping, because then the latest inactive row would be eliminated before I group them by customer to find the latest row.
I've tried something like, this:
var latestContracts = Query<Contract>()
    .GroupBy(grp => grp.CustomerId)
    .Select(s => s.OrderByDescending(s => s.ContractStartDate).First())
    .Where(w => w.Status == "Active");

but once I execute the query by calling ToListAsync(), etc. I get an error like this:
'The LINQ expression 'DbSet<Customer>()
    .GroupBy(c => c.CustomerId)
    .Select(g => g
        .AsQueryable()
        .OrderByDescending(e => e.
   I CC ContractStartDate)
        .First())
    .Where(e0 => e0.AccountContractTermStatus == "Active")' could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to 'AsEnumerable', 'AsAsyncEnumerable', 'ToList', or 'ToListAsync'. See https://go.microsoft.com/fwlink/?linkid=2101038 for more information.'

If I remove the Where call, the query works fine and gives the intended newest results. I know that the support for translating LINQ to SQL is still not fully complete, even in EF Core 6, but this seems like something that should be possible. Am I missing something simple or is this just not yet doable via LINQ?
Happy to provide more context, as I've greatly simplified a production query into something I could share publicly.

A: Try the following emulation of query which EF Core cannot translate. It is almost direct translation what EF Core should do in your case.
var dataQuery = Query<Contract>();

var latestContracts =
    from d in dataQuery.Select(d => new { d.CustomerId }).Distinct()
    from c in dataQuery
        .Where(c => d.CustomerId == c.CustomerId)
        .OrderByDescending(c => c.ContractStartDate)
        .Take(1)
    where c.Status == "Active"
    select c;

Or using Method Chain syntax:
var dataQuery = Query<Contract>();

var latestContracts = dataQuery
    .Select(d => new { d.CustomerId })
    .Distinct()
    .SelectMany(d => dataQuery
        .Where(c => d.CustomerId == c.CustomerId)
        .OrderByDescending(c => c.ContractStartDate)
        .Take(1))
    .Where(c => c.Status == "Active");


text:
Q: Copying specific objects(according to given condition) from array of objects into an another array in angularJS I want to create a new array of objects from an existing array of objects , such that new array will have only have those objects which matches the condition defined in if statement. Below is the code snippet which i am attempting
Requirement is that when key.status=='completed' condition gets hit ,only those object which have status : 'completed' in orders array will get copied to temp array .But because of using angular.copy whole copy of objects is getting copied in temp array .
 .
--------html-----

    {{order.id}} -- {{order.status}} -- {{order.name}}

-------xxxx------
-------JS----------

------xxx--------

A: You can do this using Array.filter:
$scope.temp = $scope.orders.filter(function(o){return o.key === 'completed'});


text:
Q: Dealing with underdetermination in Bayesian models Bayesian models are supposedly well equipped to deal with high-dimensionality problems, and can handle sparse data well, too. But suppose I've created a model that estimate more parameters than there are data points. Are there tricks to deal with this?

A: You say that there are several group-level parameters that you are interested in estimating. That sounds exactly like a hierarchical problem. Do some reading on hierarchical models and the key assumptions (like exchangability), and I think you'll find that your Bayesian background and this problem will easily fit into this paradigm.
The classic example of hierarchical modeling is analyzing data on many students within several schools. We'd expect the process of students' learning to be similar generally, but that better schools would have students with higher achievement, that is, that there is correlation at the student level because each student is not entirely independent of other students in the same school. Accounting for the features of schools that make some better and others worse will help identify salient feature of education, and account for the systematic variation at the student level.
More generally, I would suggest fitting simpler versions of the model and then increasing complexity and the number of parameters gradually. It's much easier to wrap one's mind around, and you will probably learn interesting things about your data along the way which will help you to fit more complex, more realistic models.
Ultimately, what research design is sensible always depends on the research question, but from your description, it sounds like this problem is amenable to a hierarchical approach.


text:
Q: Method used in After Insert, After Update and After Delete must fire only when once even though there are multiple DML(Add,update,delete) I have visualforce page which allows user to perform mixed dml (add/delete/update) on records at once. I have a method(that creates a opportunitylineitem showing the aggregate sum of records) is used in after insert, after update and after delete methods which will execute based on the dml performed on the vf page followed by apex trigger. If there is a use case where user insert a record & updates the existing record then the method executes twice both in after insert and after update which ends up in creating dupe records (in this case 2 opplineitem records where 1 opplineitem shows the calculated value of inserted records while 2nd one which is created in after update is showing both inserted & updated records. I'm struggling on how to just create only single Opplineitem (in this case 2nd one which has total of both inserted and updated records) showing all records. Please share your thoughts on how to approach this. Thanks!

VFP Controller
    public Opportunity opp;
    public List<Vendor_Fees__c> VendorFeesList {get;set;}
    public Integer rowIndex {get;set;}
    public List<Vendor_Fees__c> delVendorFees {get;set;}
    public OpportunityVendorFeesController_AC(ApexPages.StandardController controller){
        opp = (Opportunity)controller.getRecord();
        VendorFeesList = [Select Id, Vendor__c, Estimated_Fee__c, Estimated_Tax_Amount__c, Actual_Fee__c, Fees__c, Fee_Value__c, Fee_Type__c, Fee_Calc__c, Opportunity__c, Tax_Amount__c FROM Vendor_Fees__c where Opportunity__c = : opp.Id];
        delVendorFees = new List<Vendor_Fees__c> ();
    }
    public void addRow(){
        VendorFeesList.add(new Vendor_Fees__c(Opportunity__c = opp.Id));
    }
    public PageReference save(){
        try{
            upsert VendorFeesList;
            system.debug('delVendorFees-----'+delVendorFees);
            if(!delVendorFees.isEmpty()){
                delete delVendorFees;
                delVendorFees.clear();
            }
            VendorFeesList = [Select Id, Vendor__c, Estimated_Fee__c, Estimated_Tax_Amount__c, Actual_Fee__c, Fees__c, Fee_Value__c, Fee_Type__c, Fee_Calc__c, Opportunity__c, Tax_Amount__c FROM Vendor_Fees__c where Opportunity__c = : opp.Id];
            //return (new ApexPages.StandardController(accounts)).view();
            PageReference pageRef = new PageReference('/apex/OpportunityVendorFees_VF');
            pageRef.getParameters().put('id',opp.Id);
            return pageRef;
        }catch(DMLException de) {
            Apexpages.addMessage(new ApexPages.Message(ApexPages.SEVERITY.FATAL, de.getDmlMessage(0)));
            return NULL;
        }
    }
    public void deleteRow(){
        rowIndex = Integer.valueOf(ApexPages.currentPage().getParameters().get('rowIndex'));
        if(VendorFeesList[rowIndex].Id != null)
            delVendorFees.add(VendorFeesList[rowIndex]);
        VendorFeesList.remove(rowIndex);
    }
enter code here

//Triggerhandler
public void OnAfterInsert(List<Vendor_Fees__c> newVendorFees, Map<Id,Vendor_Fees__c> newVendorFeesMap){
    system.debug('After Insert vf------');
    oliPassAndCostUpsert(newVendorFees,newVendorFeesMap);
}
public void OnAfterUpdate(Vendor_Fees__c[] newVendorFees, Map<Id,Vendor_Fees__c> oldVendorFeesMap,Map<Id,Vendor_Fees__c> newVendorFeesMap){
    system.debug('After update vf------');
    oliPassAndCostUpsert(newVendorFees,newVendorFeesMap);
}

public void OnAfterDelete(Vendor_Fees__c[] oldVendorFees, Map<Id,Vendor_Fees__c> oldVendorFeesMap){
    system.debug('After delete vf------');
    oliPassAndCostUpsert(oldVendorFees,oldVendorFeesMap);
}

//Apex Trigger
trigger VendorFeesTrigger_AT on Vendor_Fees__c (before insert, before update, after insert, after update, after delete) {
Triggers_Configutaion__mdt apexTrigger = [Select Id, Active_Trigger__c From Triggers_Configutaion__mdt WHERE MasterLabel ='Vendor Fees Trigger'];
if(apexTrigger.Active_Trigger__c){
    VendorFeesTriggerHandler_AC handler = new VendorFeesTriggerHandler_AC();
    //Before Insert
    if(Trigger.isInsert && Trigger.isBefore){
        handler.OnBeforeInsert(Trigger.new);
    }

    // After Insert
    else if(Trigger.isInsert && Trigger.isAfter){
        handler.OnAfterInsert(Trigger.new, Trigger.oldMap);
    }

    // Before Update
    else if(Trigger.isUpdate && Trigger.isBefore){
        handler.OnBeforeUpdate(Trigger.new, Trigger.oldMap, Trigger.newMap);
    }

    // After Update
    else if(Trigger.isUpdate && Trigger.isAfter){
        handler.OnAfterUpdate(Trigger.new, Trigger.oldMap, Trigger.newMap);
    }

    /*
    // Before Delete
    else if(Trigger.isDelete && Trigger.isBefore){
        //handler.OnBeforeDelete(Trigger.old, Trigger.oldMap);
    }
    */
    // After Delete
    else if(Trigger.isDelete && Trigger.isAfter){
        handler.OnAfterDelete(Trigger.old, Trigger.oldMap);
    }
    /*
    // After Undelete
    else if(Trigger.isUnDelete){
        //handler.OnUndelete(Trigger.new);
    } */
}else{
    system.debug('----Skipped Account Trigger----');
}


text:
Q: dbpedia spotlight performance I installed the dbpedia spotlight service according to:
https://github.com/dbpedia-spotlight/dbpedia-spotlight/wiki/Run-from-a-JAR
and installed the larger models.
and ran 10 JSON text based queries  from a small client program. The time for execution was 315 seconds. Is this  performance to be expected? The queries were not particularly long:
A typical query was 3000 characters.


text:
Q: How to cache relational query data in parse? I am wondering if it's possible to save parse objects in cache together with the related objects when doing a relational query. Let's say this is how I would normally query and pin data in cache if I have network.
ParseQuery<ParseObject> books = ParseQuery.getQuery("Book");
books.include("author");
books.findInBackground(new FindCallback<ParseObject>() {
        public void done(List<ParseObject> books, ParseException e) {
            if (e == null) {
                 ParseObject.unpinAllInBackground("allBooks", books, new DeleteCallback() {
                    public void done(ParseException e) {
                        if (e != null) {
                            // There was some error.
                            return;
                        }
                        // Add the latest results for this query to the cache.
                        ParseObject.pinAllInBackground("allBooks", books);
                    }
                });

                for (ParseObject book : books) {
                     String authorName = book.getParseUser("author").getString("name");
                     String bookTitle = book.getString("title");
                 }

            } else {
                Log.d("query error", e.toString());
            }
       })
})

And this is how I would load data from the cache initially before I call the query above.
ParseQuery<ParseObject> books = ParseQuery.getQuery("Book");
        books.fromPin("allBooks");
        books.findInBackground(new FindCallback<ParseObject>() {
            public void done(List<ParseObject> books, ParseException e) {
                if (e == null) {
                    Log.d("cache results", String.valueOf(books.size()));
                    String authorName = book.getParseUser("author").getString("name");
                    String bookTitle = book.getString("title");
                } else {
                    Log.d("cache error", e.toString());
                }
            }
        });

The problem is when I load from cache, the data for the ParseUser author is not pinned. And I get this error.
java.lang.IllegalStateException: ParseObject has no data for 'name'. Call fetchIfNeeded() to get the data.

How do I make sure that the author ParseUser data is also pinned together with the rest of the data? Thanks


text:
Q: PayPal SOAP: "Declaration of PayPal::raiseError() should be compatible with that of PEAR::raiseError()" I have downloaded the Paypal API for PHP (SOAP) and I'm getting this error:

Strict standards: Declaration of
  PayPal::raiseError() should be
  compatible with that of
  PEAR::raiseError() in
  ....paypal/PayPal.php on line 24

when I call this:
$handler =& ProfileHandler_Array::getInstance(
        array(    'username'        => $this->api_username,
                'certificateFile' => $this->api_certificate,
                'signature'       => $this->api_signature,
                'subject'         => $this->api_subject,
                'environment'     => (($this->api_test)?'Sandbox':'Live')
        )
        );

Any idea?
Regards
Javi

A: This is a bug and should be fixed. Please open a report in the pear bugtracker.


text:
Q: Warning: Cell is formatted as text or preceded by an apostrophe I have created a XSL report using PHPExcel successfully. In that XSL report, I am displaying some percentage values with symbol %(like 70%). The problem is, cell containing the % symbol shows warning message as:
The number in this cell is formatted as text or preceded by an apostrophe.
If I select the XSL warning from XSL sheet and Convert to Number then warning has disappeared.
How to resolve (disappear) warnings from XSL report using PHPExcel?
Please help me to solve this issue.
Thanks.

A: If you want to write a percentage value to a cell then you write that number dividedby 100, and format as a percentage
$value = 70;
$objPHPExcel->getActiveSheet()->setCellValue('A1',$value / 100);
$objPHPExcel->getActiveSheet()->getStyle('A1')
    ->getNumberFormat()
    ->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_PERCENTAGE);


text:
Q: Undefined variable login in D:\wamp\www\tp\resume.php on line 9 I'm sorry because I'm a beginner in php and also in stack, I already asked my question but it gives me limited because of the signal, thank you for helping me without reporting and thank you very much.
i Create an "index.html" page which asks the user for a username and a password, This form redirects to a "forme.php" page, which contains fields to be filled in by the user, when I enter them user data and I click on the resume button, the button will redirect me to resume.php and display my user data, but I also want to display the identifier that entered in the 1st form, it gives me error:Undefined variable: login in D:\wamp\www\tp\resume.php on line 9 .
index.html
<form method="post" action="formulaire.php">
          login
          <input name="login" type="text">

          mot de pass
          <input name="password" type="password">

          <input name="Submit" type="submit" value="Enregistrer">
       </form>

formulaire.php
<?php
       $login=$_POST["login"];
       $password=$_POST["password"];

       if($login!="aaaaa" && $password!="aaaaa"){
        echo "
vous avez pas le droit d'acceder a cette page
";
       }else { ?>
         <form method="post" action="resume.php">
          email
          <input name="email" type="text">

          Genre:
          <input type="radio" name="gender" value="female">F
          <input type="radio" name="gender" value="male">M
          <input type="radio" name="gender" value="Autre">Autre

          citation préféré
          <input type="textarea" name="citation" style="height: 50px;width:450px;">

          </input>

          L'auteur
          <input name="auteur" type="text">

          nombre d'ouvrage:
          <select name="ouvrage" id="pet-select">
              <option value="">--Please choose an option--</option>
              <option value="1">1</option>
              <option value="2">2</option>
              <option value="3">3</option>
              <option value="4">4</option>
              <option value="5">5</option>
              <option value="6">6</option>
          </select>

          <input type="checkbox" name="ouvrage1" value="ouvrage1">
          ouvrage 1

          <input type="checkbox" name="ouvrage2" value="ouvrage2">
          ouvrage 2

          <input name="Submit" type="submit" value="resume">
         </form>
       <?php } ?>

resume.php

<?php echo $login ?>

    <?php
       $email    = $_POST["email"];
       $gender   = $_POST["gender"];
       $citation = $_POST["citation"];
       $auteur   = $_POST["auteur"];
       $ouvrage  = $_POST["ouvrage"];
       $ouvrage1 = $_POST["ouvrage1"];
       $ouvrage2 = $_POST["ouvrage2"];
       echo "email : " .$email."||genre : ".$gender."||ciattion : ".$citation."|| auteur : ".$auteur."|| ouvrage : ".$ouvrage." || ouvrage1 : ".$ouvrage1."|| ouvrage2 :" .$ouvrage2;
    ?>

A: Inside of formulaire.php You need to "carry" $login
There's a couple ways of doing this ..
One is with SESSIONS  --  You can put session_start() at the TOP of formulaire.php and at the top of resume.php inside <?php tags  IE
<?php
session_start();

In formulaire.php SET the session variable $_SESSION['login'] = $login;
In resume.php DEFINE $login as $login = $_SESSION['login'];

The other way is to set an input and "forward" it.  Create the following input in formulaire.php:
 <input type="hidden" name="login" value="<?= $login ?>">

And call it in resume.php
$login = $_POST['login'];


text:
Q: R list of dataframe conserving column and data structure I have a dataframe like:
colum1  column2   column3    column4
0.34    0.45      4450       21
0.32    0.46      4451       41
0.41    0.12      2150       38
.
.
.

This dataframe contains 2000 elements. I would like to create a list of 100 dataframes with randomly selected rows. I have coded a prototype:
matrix_sampling<-list()
counter=1
original_data <- a

while( counter < 101) {
 sub_sample <- data.frame(original_data[sample(nrow(original_data), 20), ])
 matrix_sampling <- c(matrix_sampling, sub_sample)
 counter = counter+1
}

However when I access to the following matrix:
matrix_sampling[[1]] it print 0.34 I was expecting the first dataframe. I really would like a data structure like:
matrix_sampling[1] = dataframe1
matrix_sampling[2] = dataframe2
...

Where I can even see the column's names.

A: You can use replicate. In the example below we generate a list with two dataframes, each containing five rows of iris. So you would need to adjust this accordingly.
n_rows <- 5
samples <- 2

set.seed(1)
out <- replicate(n = samples,
                 expr = iris[sample(1:nrow(iris), size = n_rows),],
                 simplify = FALSE)
out
#[[1]]
#    Sepal.Length Sepal.Width Petal.Length Petal.Width    Species
#40           5.1         3.4          1.5         0.2     setosa
#56           5.7         2.8          4.5         1.3 versicolor
#85           5.4         3.0          4.5         1.5 versicolor
#134          6.3         2.8          5.1         1.5  virginica
#30           4.7         3.2          1.6         0.2     setosa

#[[2]]
#    Sepal.Length Sepal.Width Petal.Length Petal.Width    Species
#135          6.1         2.6          5.6         1.4  virginica
#141          6.7         3.1          5.6         2.4  virginica
#98           6.2         2.9          4.3         1.3 versicolor
#93           5.8         2.6          4.0         1.2 versicolor
#10           4.9         3.1          1.5         0.1     setosa


text:
Q: NullPointerException wrong context? I cant understand what is wrong?
list_item
    <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="?android:attr/activatedBackgroundIndicator">

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/imageView"
        android:src="@drawable/no_avatar"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/name"
        android:layout_gravity="top|center_horizontal"
        android:layout_marginLeft="10dp"/>

    <CheckBox
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/checkbox"
        android:id="@+id/checkBox"
        android:clickable="true"
        android:paddingLeft="@dimen/abc_action_bar_overflow_padding_start_material"
        android:singleLine="false"
        android:textAppearance="@color/colorAccent"
        android:layout_gravity="right" />
</LinearLayout>

fragment_list
    <android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/rootLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true">

        <ListView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:id="@+id/listView"
            android:layout_margin="@dimen/activity_vertical_margin"/>

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_add_white_24dp"
        app:layout_anchor="@id/listView"
        app:layout_anchorGravity="bottom|right|end"
        app:elevation="6dp"
        app:pressedTranslationZ="12dp"
        app:backgroundTint="@color/colorAccent"
        app:rippleColor="@color/colorPrimary"/>
</android.support.design.widget.CoordinatorLayout>

FragmentList.java
 @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    View v = inflater.inflate(R.layout.fragment_list, container, false);
    fab = (FloatingActionButton) getView().findViewById(R.id.fab);
    listView = (ListView) v.findViewById(R.id.listView);

    //обработка добавления человека - нажатие на fab
    fab.setOnClickListener(new View.OnClickListener() {
        @Override public void onClick(View v) {
            //TODO добавление!!!
            Toast.makeText(v.getContext(), "Новая запись добавлена", Toast.LENGTH_SHORT).show();
        }
    });

    //создание курсора
try{
    SQLiteOpenHelper databaseHelper = new DatabaseHelper(v.getContext());
    SQLiteDatabase db = databaseHelper.getWritableDatabase();
    Cursor cursor = db.query("PEOPLE", new String[] {"_id", "NAME", "CHECKBOX"}, null, null, null, null, null);
    CursorAdapter listAdapter = new SimpleCursorAdapter(v.getContext(), R.layout.list_item, cursor, new String[]{"NAME", "CHECKBOX"}, new int[]{R.id.name, R.id.checkBox}, 0);
        listView.setAdapter(listAdapter);
        //переход к первой записи в курсоре
        if (cursor.moveToFirst()){
            //получение данных из курсора
            nameText = cursor.getString(1);
            isAvatar = (cursor.getInt(2)==1);
            //заполнение чекбокса, тест имени и аватар
            CheckBox checkBox = (CheckBox) v.findViewById(R.id.checkBox);
            TextView textView = (TextView) v.findViewById(R.id.name);
            ImageView image = (ImageView) v.findViewById(R.id.imageView);
            checkBox.setChecked(isAvatar);
            textView.setText(nameText);
            if (checkBox.isChecked()) {
                image.setImageResource(R.drawable.avatar);
            } else image.setImageResource(R.drawable.no_avatar);
        }
    } catch (SQLiteException e){
        Toast.makeText(v.getContext(), "База данных недоступна", Toast.LENGTH_SHORT).show();
    }

        //обработка нажатия по чекбоксу
//        checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener(){
//            @Override
//            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
//                checkBox.isChecked();
//            }
//        });

        return v;
}

//обработка нажатия пункте списка
public void onListItemClick(){

}

//закрытие базы данных и курсора
@Override
public void onDestroy(){
    super.onDestroy();
    cursor.close();
    db.close();
}

}
Why CheckBox checkBox = (CheckBox) v.findViewById(R.id.checkBox) is null?
I tried many variations but became stupid ((
debug screenshot

A: You are inflating fragment_list layout that does not contain checkbox, imageview or text view. That's why you are getting this error.
implement this cursor adapter
public class MyCursorAdapter extends CursorAdapter {

    public MyCursorAdapter(Context context, Cursor cursor, int flags) {
        super(context, cursor, 0);
    }

    @Override
    public View newView(Context context, Cursor cursor, ViewGroup parent) {
        return LayoutInflater.from(context).inflate(R.layout.mylist_row, parent, false);
    }

    @Override
    public void bindView(View v, Context context, Cursor cursor) {

        if (cursor.moveToFirst()){
            //получение данных из курсора
            nameText = cursor.getString(1);
            isAvatar = (cursor.getInt(2)==1);
            //заполнение чекбокса, тест имени и аватар
            CheckBox checkBox = (CheckBox) v.findViewById(R.id.checkBox);
            TextView textView = (TextView) v.findViewById(R.id.name);
            ImageView image = (ImageView) v.findViewById(R.id.imageView);
            checkBox.setChecked(isAvatar);
            textView.setText(nameText);
            if (checkBox.isChecked()) {
                image.setImageResource(R.drawable.avatar);
            } else image.setImageResource(R.drawable.no_avatar);
        }

    }

}

now in onCreateview
MyCursorAdapter todoAdapter = new MyCursorAdapter(this.getActivity(), cursor, 0);
        lvItems.setAdapter(todoAdapter);

A: You are looking up checkBox on the view (v): CheckBox checkBox = (CheckBox) v.findViewById(R.id.checkBox); Yet v is assigned to (fragment_list) here View v = inflater.inflate(R.layout.fragment_list, container, false); BUT fragment_list does not contain checkBox and so v.findViewById(R.id.checkBox) returns null.
When you use the SimpleCursorAdapter as you want to use it, then you need to create a class that extends SimpleCursorAdapter, you can then access/inflate the "row-item" layout file in getView (final int pos, View view, ViewGroup parent) - you will then be able to say: CheckBox checkBox = (CheckBox) view.findViewById(R.id.checkBox).


text:
Q: Алгоритм Евклида проблемы с синтаксисом bash Только начал работать с bash и синтаксис очень непонятен. В чем мои ошибки?
#!/bin/bash
function_Euclids() {
while [ $1 -ne 0 ] && [ $2 -ne 0 ]
    do
            if [[ $1 -gt $2 ]]
                    then
                            let $1+=$1/$2
                    else    let $2+=$2/$1
            fi
    done
    let a=$1+$2
    echo" $a"
                    }

function_Euclids

A: Во первых, при вызове функции function_Euclids вы забыли передать ей аргументы.
Во вторых, не надо ничего присваивать аргументам. Заведите пару локальных переменных, присвойте им значения аргументов и работайте с ними. Т.е. как-то так:
p1=$1
p2=$2
while [ $p1 -ne 0 ] && [ $p2 -ne 0 ]
do
   ....

В третьих, выражение для let должно быть строкой (кстати, имена переменных в ней можно использовать без $ (разыменования)). Вот в таком духе:
let a="p1 + p2"

*

*(конечно, без пробелов можно написать так: let a=p1+p2 (или let a=$p1+$p2, тут строка для вычисления образуется в результате текстовой подстановки), но без них код выглядит не слишком привлекательно).

И наконец, в четвертых -- в алгоритме Евклида вычисляются не частные, а остатки (и они не добавляются, а замещают прошлые значения p1 и p2). Т.е. надо вот так:
let p1="p1 % p2"

вместо let $1+=$1/$2
В результате получаем
#!/bin/bash

function_Euclids() {
    p1=$1
    p2=$2
    while [ $p1 -ne 0 ] && [ $p2 -ne 0 ]
    do
        if [[ $p1 -gt $p2 ]]
        then
            let p1="p1 % p2"
        else
            let p2="p2 % p1"
        fi
    done
    let a="p1+p2"
    echo "a = $a"
}

function_Euclids $1 $2

По хорошему, надо бы еще проверить $1 и $2 перед вызовом функции, но это уж вы как-нибудь сами потренируйтесь.


text:
Q: Как изменить панель в зависимости от выбора? мне нужно сделать что-то типа TreeView, суть в том, что-бы когда пользователь выбирает некий класс менялась основная панель, реализовать всё нужно на JavaFX, буду благодарен за любую помощь.

A: import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeView;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.FlowPane;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;

import java.util.function.Supplier;

public class Main extends Application {

    public void start(Stage primaryStage) throws Exception {
        final BorderPane rootScene = new BorderPane();

        TreeItem<NamePaneFactory> root = new TreeItem<>(new NamePaneFactory("Root", () -> null));
        root.getChildren().addAll(
                new TreeItem<>(new NamePaneFactory("Pane1", Pane1::new)),
                new TreeItem<>(new NamePaneFactory("Pane2", Pane2::new))
        );

        TreeView<NamePaneFactory> treeView = new TreeView<>(root);
        treeView.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> {
            rootScene.setCenter(newValue == null ? null : newValue.getValue().factory.get());
        });

        rootScene.setLeft(treeView);
        primaryStage.setScene(new Scene(rootScene));
        primaryStage.show();
    }

    static class NamePaneFactory {

        final String name;

        final Supplier<? extends Pane> factory;

        public NamePaneFactory(String name, Supplier<? extends Pane> factory) {
            this.name = name;
            this.factory = factory;
        }

        @Override
        public String toString() {
            return name;
        }
    }

    static class Pane1 extends BorderPane {
        public Pane1() {
            super(new Label("Pane1"));
        }
    }

    static class Pane2 extends FlowPane {
        public Pane2() {
            super(new Label("Pane2"));
        }
    }

}


text:
Q: How can we prove the following statement? In the evaluation of the integral
$$ I = \int_0^1 x^{-x} \ \mathrm{d}x,$$
we can easily prove that
$$I = \sum_{q \geq 1} \frac{1}{q^q}$$
by the use of the gamma function.
But how can we prove the value of the sum, given by $\approx 1.291$? Even a link to a proof of the latter would be very appreciated! Thanks!
Note: I am not asking for a proof of the integral's equality to the sum. I am asking for a proof or a reference to a proof of the value given by the sum; $1.291$...

A: The sum itself converges very quickly. For any partial sum up to $n > 1$:
$$ \sum_{q\geq 1} \frac{1}{q^q} - \sum_{1\leq q \leq n} \frac{1}{q^q} < \sum_{q\geq n+1}\frac{1}{(n+1)^q} = \frac{1}{n(n+1)^n}$$
For example, if we were to add up the first four terms, we get that
$$\sum_{q\geq 1} \frac{1}{q^q} - 1.2909\dots < \frac {1}{2500} = .0004$$

A: $$I=\int_{0}^{1} x^{-x} dx = \int_{0}^{1} \exp[-x \ln x]~ dx= \int_{0}^{1} \sum_{n=0}^{\infty} \frac{(-1)^n (x \ln x)}{n!}^n$$
Let $x=e^{-t}$, then
$$I=\sum_{n=0}^{\infty} \int_{0}^{\infty} \frac{t^n~e^{-(n+1)t}}{n!} dt$$
Now use $\int_{0}^{\infty} t^n e^{-at} dt =\frac{n!}{a^{n+1}}$
Then $$I=\sum_{n=0}^{\infty} \frac{1}{(n+1)^{n+1}}=\sum_{n=1}^{\infty} \frac{1}{n^n}$$


text:
Q: redirect Location but not URL How do I redirect the user to a different route without redirecting the URL in vanilla Express? For example, if I have the routes
express = require('express');
app = express();

app.route('/old').get(function(req, res, next) {
    res.redirect('/new');
});

app.route('/new').get(function(req, res, next) {
    res.send('This is the new route');
});

app.listen(3000);

and I point my browser to http://localhost:3000/old, the application successfully redirects, and the page says This is the new route, but the URL has changed, as well, to http://localhost:3000/new. How do I get the application to redirect to the new route but keep the old URL (http://localhost:3000/old)?
I'm fine installing another middleware (as if I don't already have a million already), but ideally, I'd like to do this without extra middleware. Also, I'm doing this completely in Express.js, without PHP, nginx, or anything else. I will be using Angular.js in my application, but this seems like more of a server-side behavior, rather than client-side. I do redirect on the client side sometimes, but I don't want to do it all the time.

A: rather than redirect, how about just send a get request using request module
and do a callback to update content.
var request = require('request');

app.route('/old').get(function(req, res, next) {

  request.get('/new', function(err, response, body) {
    if (!err) {
      req.send(body);
    }
  });
});

A: You can have a helper method that both routes use:
express = require('express');
app = express();

const newHandler = function(req, res, next) {
    res.send('This is the new route');
};
app.route('/old').get(newHandler);
app.route('/new').get(newHandler);

app.listen(3000);

Note, req.url will be different inside newHandler for the two different routes, so you may need to handle that.


text:
Q: Deploying a .Net application built in VSTS to a remote agent machine I have been trying to figure this out for a few days to no avail.
I have an MVC .Net Application that is stored in a GIT repo in VSTS. When I check in code it is being built and unit testa are being run in the cloud.
Now If these unit tests succeed I would like the project to be deployed to a remote machine that has the VSTS agent installed. I can see the agent in the VSTS web interface but I don't know how I get the automatic build to send the completed build to d:/mydeploypath on the remote agent machine.
Is this possible?

A: Absolutely possible!
There are build steps available to copy files to a remote machine such as Copy Files over SSH and Windows Machine File Copy. But if you are trying to deploy the code to the machine you are building on, you can use the Copy Files step since it won't require credentials. Since it is a web application, there are a few steps like IIS Utilities to stop\start the application pool so the files won't be locked for the deployment.
So using the Copy Files build step, you could use $(Agent.BuildDirectory) as the source directory (or wherever you have your build output going) and set the target folder to your desired destination on the machine.
The build/release variables helped me out a lot during the development of our release process:
https://learn.microsoft.com/en-us/vsts/pipelines/build/variables?view=vsts

A: The easy way is using WinRM-IIS Web App Deployment task.
To generate the web deployment package, you can specify these arguments in MSBuild Arguments box of Visual Studio Build task:
/p:SkipInvalidConfigurations=true /p:DeployOnBuild=true  /p:WebPublishMethod=Package /p:PackageLocation="$(build.artifactstagingdirectory)" /P:PackageTempRootDir=""


text:
Q: Convert sequence of numbers to random-looking IDs? I'm working on an application where I need to generate unique, non-sequential IDs.  One of the constraints I have is that they must consist of 3 digits followed by 2 letters (only about 600k IDs).  Given my relatively small pool of IDs I was considering simply generating all possible IDs, shuffling them and putting them into a database.  Since, internally, I'll have a simple, sequential, ID to use, it'll be easy to pluck them out one at a time & be sure I don't have any repeats.
This doesn't feel like a very satisfying solution.  Does anyone out there have a more interesting method of generating unique IDs from a limited pool than this 'lottery' method?

A: Use a finite group.  Basically, take a 32 or 64-bit integer, and find a large number that is coprime to the maximum value for your integer; call this number M.  Then, for all integers n, n * M will result in a unique number that has lots of digits.
This has the advantage that you don't need to pre-fill the database, or run a separate select query -- you can do this all from within one insert statement, by having your n just be an auto-increment, and have a separate ID column that defaults to the n * M.

A: This can be done a lot of different ways, depending on what you are trying to optimize (speed, memory usage, etc.).
ID pattern = ddd c1c[0]
Option 1 (essentially like hashing, similar to Zak's):
1 Generate a random number between 0 and number of possibilities (676k).
2- Convert number to combination
    ddd = random / (26^2)
    c[0] = random % (26)
    c[1] = (random / 26) % 26

3- Query DB for existence of ID and increment until a free one is found.
Option 2 (Linear feedback shift register, see wikipedia):
1- Seed with a random number in range (0,676k).  (See below why you can't seed with '0')
2- Generate subsequent random numbers by applying the following to the current ID number
    num = (num >> 1) ^ (-(num & 1u) & 0x90000u);
3- Skip IDs larger than range (ie 0xA50A0+)
4- Convert number into ID format (as above)
*You will need to save the last number generated that was used for an ID, but you won't need to query the DB to see if it is used.  This solution will enumerate all possible IDs except [000 AA] due to the way the LFSR works.
[edit] Since your range is actually larger than you need, you can get back [000 AA] by subtracting 1 before you convert to the ID and have your valid range be (0,0xA50A0]

A: You could generate a random ID conforming to that standard, do a DB select to see if it exists already, then insert it into a DB to note it has been "used". For the first 25% of the life of that scheme (or about 150k entries), it should be relatively fast to generate new random ID's. After that though, it will take longer and longer, and you might as well pre-fill the table to look for free IDs.

A: Depending on what you define as sequential, you could just pick a certain starting point on the letters, such as 'aa', and just loop through the three digits, so it would be:
001aa
002aa
003aa
Once you get to zz then increment the number part.

A: You could use modular arithmetic to generate ids. Pick a number that is coprime with 676,000 and for a seed. id is the standard incrementing id of the table. Then the following pseudocode is what you need:
uidNo = (id * seed) % 676000
digits = uidNo / 676
char1 = uidNo % 26
char2 = (uidNo / 26) % 26
uidCode = str(digits) + chr(char1+65) + chr(char2+65)

If a user has more than one consecutively issued id, they could guess the algorithm and the seed and generate all the ids in order. This may mean the algorithm is not secure enough for your use case.


text:
Q: Compare aspect ratios given width and height Given a list of screen sizes, how do I detect which ones are in 4:3 16:9 aspect ratio?
I can use width / height to get it but for 16:9 sizes I sometimes get 1.778 and sometimes I get 1.777778 due to rounding errors.

A: You can force the rounding to be always the same, and then you can compare the values:
float ratio = (int)((width / height) * 100);

You will get always 177 for 16:9 and 133 for 4:3
good luck

A: Check if 4 * height == 3 * width or 16 * height == 9 * width.
Remember the definition of a rational number: It is an equivalence class of pairs of integers (m, n) subject to the equivalence (m, n) ≡ (m', n') if and only if n' m = n m'.

A: compare with some epsilon proximity.
should be something like:
double epsilon = 0.01;
if(math.abs(screen1.height/screen1.width - screen2.height/screen2.width) < epsilon)
{
//equal ratios
}

A: you must use an epsilon value for the comparison.
You can have a look at: http://www.cygnus-software.com/papers/comparingfloats/comparingfloats.htm


text:
Q: Subtraction Doubles in C++ I'm doing a homework assignment where I need to use the McLaurin Series to evaluate for cosh(x) ans sin(x). Each time the program runs, the user inputs a number from 0-10 to specify how many terms to evaluate the series too. The user then inputs the value of x to evaluate to. Once the user hits enter, 10 increments of the series will be calculated and printed out. In addition, I have to find the exact error as well. To do this, I created several different functions for both sinh and cosh that performed the calculations of a specific term. For example: the code below evaluates the term up to 10!.
void cosFunction10(double power, double value)
{
     double cosh_x = 0;
     double math_cosh = 0;
     double exact_error;
     double x;

     if (value < 0)
         x = -0.1*0;

     for (int i = 0; i < 11; ++i)
     {
         cosh_x = (1.0 + ((x*x)/(2.0*1.0)) + ((x*x*x*x)/(4.0*3.0*2.0*1.0)) + ((x*x*x*x*x*x)/(6.0*5.0*4.0*3.0*2.0*1.0)) + ((x*x*x*x*x*x*x*x)/(8.0*7.0*6.0*5.0*4.0*3.0*2.0*1.0)) + ((x*x*x*x*x*x*x*x*x*x)/(10.0*9.0*8.0*7.0*6.0*5.0*4.0*3.0*2.0*1.0)));
         math_cosh = cosh(x);
         exact_error = (math_cosh - cosh_x);

         cout << setiosflags(ios::scientific) << setprecision(3) << x << "\t";
         cout << setiosflags(ios::scientific) << setprecision(5) << cosh_x << "\t";
         cout << math_cosh << "\t";
         cout << exact_error << endl;
         x = x + (0.1*value);
     }
 }

If I run the program and put in these values: 10 (the nth term) and -6 (value for x).
This is what I should get:
(2nd increment)
 x                Series            Exact (using the cmath functions)    Exact % Error
 -6.000e-001      1.18547e+000      1.18547e+000                        0.00000e+000

The next 2 out puts would be the same for the exact error, until I get to the 4th increment
 x                Series            Exact (using the cmath functions)    Exact % Error
 -1.800e+100      3.10747e+000      3.10747e+000                        -7.67243e-005

When I run my code, I do not get the above results:
(2nd increment)
 x                Series            Exact (using the cmath functions)    Exact % Error
-6.000e-001      1.18547e+000      1.18547e+000                         4.55325e-012

So it seems that something is going wrong because my exact error isn't even close to the same as to what I'm given. I understand that there may be slightly different values, which is expected but not to this extent.
Any suggestions would be much appreciated,
Thank you

A: There MUST be such a difference because cosh(x) is defined in a different way which is according to the formula given below:

Please see here for more details.
However, if you are calculating the amount based on computation of MacLaurin series, the problem is that you are not accumulating the values in the right way. The below implementation is perhaps what you actually needed:
void cosFunction(double x)
{
    double cosh_x = 1;
    double math_cosh;
    double exact_error;
    double factorial = 1;
    double x_pow = 1;

    for (int i = 0; i < 11; ++i) {
            cosh_x = x_pow/factorial;
            x_pow = x*x*x_pow;
            factorial = factorial* (2 * i + 1) * (2 * i + 2);
    }

    math_cosh = cosh(x);
    exact_error = (math_cosh - cosh_x);
    cout << setiosflags(ios::scientific) << setprecision(5) << exact_error << endl;

}

A: As revealed in the comments, the error you get is actually extremely small, less than 10-11. In addition, you must take into account that the way you compute cosh and the way it's done by the built-in function is not the exact same. Both methods are ultimately approximations, but they work in different ways, hence the rounding errors and approximation errors they produce will be slightly different.
You cannot expect the error to be "flat 0".

A: The correct answer may be, in a mathematical sense, zero. But in a practical computing sense, it won't be zero:
Imagine if you're doing arithmetic with fixed decimal precision, say 8 digits. You would represent 1.0/3.0 as .33333333. But that would make 3.0 * (1.0/3.0) turn into 3.0 * .33333333 which would be .999999999. So while in a mathematical sense, 1.0 - (3.0 * (1.0 / 3.0)) should be zero, with fixed decimal precision, you may well get something like .00000001.
The same rules apply to fixed binary precision, which is what you get when you use a double.

A: //Part of the problem is that in the line after the 'for' nothing changes (typo?.) The
//following works for x = 0.5`
//Note that the loop works properly for all terms including the first which is 1.0

#include <iostream>
#include <math.h>

using namespace std;

int factorial(int n)
{
    return (n == 1 || n == 0) ? 1 : factorial(n - 1) * n;
}

int main()
{
    // use taylor series to approximate cosh(x) - use 7 terms
    double x = 0.5;
    double top, bot;
    double s = 0.0;

    for (int i = 0; i < 7; i++)
    {
        top = pow(x,double(i)*2.0);
        bot = double(factorial(i*2));
        s  += (top / bot);
    }
    cout << "myCosh     " << s << endl;
    cout << "cosh       " << cosh(x)<< endl;
    cout << "difference " << fabs(s - cosh(x)) << endl;
    return 0;
}

A: I ran your function with the cout operation modified as follows:
cout << setiosflags(ios::fixed) << setprecision(12);
cout << "for x="<<x<<": "<<math_cosh<<" - "<<cosh_x<<" = "<<exact_error<<"\n";

I chose my own value for value, since you didn't indicate what you were using.
I get the following result, which demonstrates that math_cosh and cosh_x are not the same.  Your problem seems to be that you didn't see enough digits to notice that they were different.
for x=0.003233200000: 1.000005226796 - 1.000005226791 = 0.000000000005
for x=0.006466400000: 1.000020907237 - 1.000020907164 = 0.000000000073
for x=0.009699600000: 1.000047041489 - 1.000047041120 = 0.000000000369
for x=0.012932800000: 1.000083629824 - 1.000083628658 = 0.000000001166
for x=0.016166000000: 1.000130672624 - 1.000130669778 = 0.000000002846
for x=0.019399200000: 1.000188170381 - 1.000188164480 = 0.000000005901
for x=0.022632400000: 1.000256123697 - 1.000256112765 = 0.000000010932
for x=0.025865600000: 1.000334533282 - 1.000334514632 = 0.000000018650
for x=0.029098800000: 1.000423399955 - 1.000423370081 = 0.000000029875
for x=0.032332000000: 1.000522724646 - 1.000522679112 = 0.000000045534
for x=0.035565200000: 1.000632508392 - 1.000632441726 = 0.000000066667

Regarding the homework assignment, to calculate cosh(x) using the Maclaurin series: Your function, as written, is not very precise since it only computes the first three terms of the series 1 + 0 + x*x/2.  You are not computing x^n or n! beyond n=2.  To generate a more precise result, you need to be accumulating more terms of the series -- as in the following...
int NUMBER_OF_TERMS=10; // the number of terms to compute (including zero terms)
for ( int i=0; i<NUMBER_OF_TERMS; i++ )
   {
   cosh_x += (i%2==0?1:0)*term; // even derivatives are 1, odd derivatives are 0
   term *= x/(i+1); // apply incremental power and factorial
   }

This still doesn't guarantee exactness.  Due to rounding errors, you can't be sure to perfectly match the built-in function cosh(x) unless you duplicate its algorithm exactly.  Both functions will only produce an approximation, since for most input values, the pure mathematical output would be a transcendental number -- and such a number cannot be exactly represented in a double.
You should also keep in mind that the Maclaurin series is a polynomial-based approximation which is most accurate near x=0.  As is the nature of polynomials, an incomplete summation may eventually (as x moves away from 0) diverge very rapidly from the correct answer.  This is why, in the example output above, the error values are smaller for smaller values of x.

Regarding scientific notation vs. fixed-point precision:
Scientific notation shows you the most significant non-zero digits of a number -- even if those digits start 12 places to the right of the decimal point.  When reading scientific notation, it is important to be aware of the information after the e since this describes the true magnitude of the number.  double-precision values can store approximately 20 decimal digits of real information.  This is nice for doing many repeated calculations, but it usually isn't very meaningful when comparing two numbers for equality.
What you can do, although this may not be in the scope of your assignment, is limit the fixed-point precision of the difference.  Here is an example of how you might do that:
const double PRECISION=1e-4; // indicates the number of fractional digits to keep
exact_error = round(exact_error/PRECISION)*PRECISION; // limit precision

...or it might be simpler to just check for the close-to-zero case ...
if ( fabs(exact_error)<PRECISION/2 ) exact_error = 0; // close enough to zero


text:
Q: Execution of data step despite of the errors I am executing the following code to combine a large number of data sets . Here is code:
 %macro combine;
 data modelfit;
 set
 %do i = 30 %to 116 %by 3 ;
  stat&i
   %end;
    ;
 %end;
 run;
%mend;
%combine;

However, few of the data sets are not present. Hence, the data set is failing to execute. How can I prevent the data step from stopping to execute and combine the data sets that are there . Can anybody please help me with this

A: Check if the files exist before adding them in the loop:
%macro combine;
 data modelfit;
 set
     %do i = 30 %to 116 %by 3 ;
       %if %sysfunc(exist(stat&i)) %then %do ; stat&i %end ;
     %end;
        ;
 run;
%mend;
%combine;


text:
Q: Libraries, projects, modules and packages in Intellij Idea I'm a beginner programmer and I'm learning how to work with Intellij IDEA. A project in IntelliJ IDEA has some different structures like libraries, modules and packages.
Can someone explain what the difference is between those structures and when to use a particular structure? e.g. I can't choose my package name (of a class) arbitrarily when it's already part of a module. What is the connection between those? I'm primarily having difficulties understanding the difference between a package and a module. (characters)

A: A project in intellij consists of modules. Modules can be java modules, or android modules or whatever. Modules contain your java code and all that stuff. A Module can reference a library which can be a project library or a global library. Global libraries have to be defined only once. Project library in every project you need them.
Packages are a java concept and are IDE independent.
Lets say I wanna do a little game. I would create a intellij Project called "mySuperGame". Then I would create two java modules from intellij, called "logic" and "ui". In the module settings of "ui" I would specify a project library to use opengl and a dep. to "logic". The package name of my logic classes would be "com.mysupergame.logic.XXX".
See http://confluence.jetbrains.com/display/IDEADEV/Structure+of+IntelliJ+IDEA+Project for more information.

A: IntelliJ IDEA supports everything eclipse has. But vise versa might not be true. Please check this table for the differences. IntelliJ support intelligent perspective and has many windows.

Read the documentation from IntelliJ idea.

A: Below comparison between Visual Studio (.NET) and IntelliJ (Java), which might be helpful for .NET developers migrating to Java:


text:
Q: Working with results from CURL call XML I have been working with some code for many hours today, wondering if someone could point me in a better direction than I'm going now.
I have PHP code that is fetching an array of data by sending XML via send_request_via_curl($host,$path,$content).
My function:
function send_request_via_curl($host,$path,$content)
{
$posturl = "https://" . $host . $path;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $posturl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HTTPHEADER, Array("Content-Type: application/x-www-form-urlencoded"));
    curl_setopt($ch, CURLOPT_HTTPHEADER, Array("Content-Type: text/xml;charset=utf-8"));
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $content);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
//  curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    $response = curl_exec($ch);
    return $response;
}

$headers = array(
    "Content-type: text/xml;charset=utf-8",
    "Accept: application/xml",
    "Cache-Control: no-cache",
    "Pragma: no-cache",
    "Content-length: " . strlen($content),
    );

$content = '<?xml version="1.0" encoding="utf-8"?>
                <soap:Envelope    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
                <soap:Body>
                <GetLocations xmlns="http://tempuri.org/">
                    <AuthLogin>ClientName</AuthLogin>
                    <UserName>MyUser</UserName>
                    <Password>SomePassword</Password>
                </GetLocations>
            </soap:Body>
            </soap:Envelope>';

$response = send_request_via_curl($host,$path,$content);

EDIT:
I'm getting closer, I implemented Baba's code and now getting a different error:
Warning: Unknown: Node no longer exists in....
I have the same code from above, with this now processing the response:
if ($response)
{

$xml = new SimpleXMLElement($response);
$xml->registerXPathNamespace("soap", "http://schemas.xmlsoap.org/soap/envelope/");
$path = $xml->xpath("//soap:Body");
$path = $path[0] ;
foreach($path->GetLocationsResponse->GetLocationsResult->SearchLocations->children() as $table)
{
echo $table->Table->LocationName . "
";
}

Here's the true XML returned - I noticed Firebug made all the XML lowercase, whereas the source code has capitals mixed in which I think might matter.
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>
<GetLocationsResponse xmlns="http://tempuri.org/">
<GetLocationsResult>
<SearchLocations>

<LocationName>

<LocationId>103501</LocationId>
<LocationName>Albuquerque, New Mexico, USA</LocationName>

<LocationId>101600</LocationId>
<LocationName>Atlanta, Georgia, USA</LocationName>

</SearchLocations>
</GetLocationsResponse>
</GetLocationsResult>
</soap:Body>
</soap:Envelope>

THANKS!!!

A: The response you got is not HTML but XML but it looks like Your XML is wrong there is an invalid tag or you must have made mistake ... see
  <LocationName>Hawaii</Location>
                             ^--- it should be LocationName

It should be like this
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
    <soap:Body>
        <getlocationsresponse xmlns="http://tempuri.org">
            <getlocationsresult>
                <SearchLocations>

                        <LocationID>10322</LocationID>
                        <LocationName>Hawaii</LocationName>

                </SearchLocations>
            </getlocationsresult>
        </getlocationsresponse>
    </soap:Body>
</soap:Envelope>

Read This XML
$xml = new SimpleXMLElement($data);
$xml->registerXPathNamespace("soap", "http://schemas.xmlsoap.org/soap/envelope/");
$path = $xml->xpath("//soap:Body");
$path = $path[0] ;
foreach($path->getlocationsresponse->getlocationsresult->SearchLocations->children() as $table)
{
     echo $table->LocationName . "
";
}

Output
 Hawaii

------ Edit --------
Your new XML is wrong again .. this is what it should look like http://codepad.org/JgJfqnrA

A: Baba is correct, the built in functions for parsing XML are the best way to do this but you could also use regex if the XML is really sent back with mismatching tags.
function regex_all( $capture, $haystack, $return=1 ) {
  preg_match_all( "#$capture#", $haystack, $match );
  return $match[ $return ];
}

foreach( regex_all('<LocationName>(.*?)<\/', $data) as $locationName ) {
  echo "$locationName
";
}

This would not be the preferred method because the regex isn't as reliable.


text:
Q: What exception does MS Test throw when the test run is abruptly stopped(perhaps in the task manager or because of a crash) I am trying to run a set of tests in MS Test and log the results. If the test is abruptly stopped during the run, I would like the state to be saved. How can I accomplish this?
Does MS Test throw any exception before ending the test?

A: If what MSTest is testing crashes in any way, MSTest will do it's best to record it.  A hard unmanaged crash, say, that translates into an AccessViolationException is bad and anything could happen including silent exit.  If MSTest is interrupted with Ctrl-C, it will be caught and noted, I think after the current test is finished.  If MSTest is stopped using Task Manager with "End Process" this translates into Win32 TerminateProcess which unconditionally causes the process to exit with no recourse for any sort of handling.  Perhaps you could print something out at the end and if it is not in the log then you can assume it was interrupted.


text:
Q: How to install tflearn module on anaconda distribution in windows 10 I have already install most of the libraries on anaconda. In one of my code is showing that No module named 'tflearn'.
I also used the command conda install tflearn.
it shows the failed message.
   PackagesNotFoundError: The following packages are not available from
   current channels:

*

*tflearn

Current channels:

*

*https://repo.continuum.io/pkgs/main/win-64

*https://repo.continuum.io/pkgs/main/noarch

*https://repo.continuum.io/pkgs/free/win-64

*https://repo.continuum.io/pkgs/free/noarch

*https://repo.continuum.io/pkgs/r/win-64

*https://repo.continuum.io/pkgs/r/noarch

*https://repo.continuum.io/pkgs/pro/win-64

*https://repo.continuum.io/pkgs/pro/noarch
what should i do.

A: I found a simple approach for Anaconda.
Go here (https://github.com/tflearn/tflearn) to make a clone of the tflean repository or download a copy in a zip form. Extract the files in the zip file.
Launch the anaconda prompt and navigate to the folder that contains the extracted downloaded files.
Then run:
python setup.py install
You can find my source from here (http://tflearn.org/installation/)
I hope this helps.

A: For python2
sudo pip install tflearn

For python3
sudo pip3 install tflearn

A: open your anaconda terminal and run:
conda install -c derickl tflearn

A: It seems that on the anaconda website tflearn is only listed as an OSX package, so you can either download the source and install that manually
Or you could do
pip install tflearn

Also, make sure you got tensorflow installed

A: Try this:
conda install -c bjrn tflearn

It should work.

A: Couldn't use a regular anaconda install, i had the same issue you had so this worked for me:

pip install tflearn

A: Anaconda install in Windows 10
I installed it just by typing
pip install tflearn

Collecting tflearn
   Downloading tflearn-0.5.0.tar.gz (107 kB)
Requirement already satisfied: numpy
Requirement already satisfied: six
Collecting Pillow
   Downloading Pillow-8.0.1-cp37-cp37m-win_amd64.whl (2.1 MB)
Successfully built tflearn
Installing collected packages: Pillow, tflearn
Successfully installed Pillow-8.0.1 tflearn-0.5.0