text:
Q: database operation with class I want to do all operation like insert, delete, update, etc. on database with class. So, where can I find best stable and updated db class library.
I already started working on it, But now I am stuck with it. As, I dont know how to write various class module for class like for security insert, delete or update etc.
I firstly wanted to check for input data for sql injection ,real escape strings
secondly do any DB operations. I don't know how to actually implement it  with class.
I don't know how to write a class function to achieve it.
<?php
/*
@author    :vikrant chauhan
project    :college portal
copyrights :2014-2015
*/

Class vcollege_portal
{

/************************/
     //properties//
/************************/

private $host;
private $user;
private $password;
private $database;
public  $myconn;

/************************/
   //methods//
/************************/

        function __construct($host, $user, $password, $database)
        {
        $this->host = $host;
        $this->user = $user;
        $this->database = $database;
        $this->password = $password;
        $this->connectToDatabase();
        $this->selectDatabase();
        }
/************************/
   //connection//
/************************/

        function connectToDatabase()
        {
        $conn= mysql_connect($this->host,$this->username,$this->password);
        if(!$conn){
        die ("Cannot connect to the database");}
        else{$this->myconn = $conn;
        echo "Connection established";}
        return $this->myconn;
        }
        function selectDatabase()
        {
        mysql_select_db($this->database);
        if(mysql_error()) {
        echo "Cannot find the database ".$this->database;}
        echo "Database selected..";
        }
        function closeConnection()
        {
        mysql_close($this->myconn);
        echo "Connection closed";
        }
/************************/
   //database security //
/************************/

/************************/
   //database insert //
/************************/

/************************/
   //database update //
/************************/

/************************/
   //database delete //
/************************/

}
?>

A: I hope this will help you. But, for you it's important to get the concepts.
Please see it and work accordingly.
http://code.tutsplus.com/tutorials/simple-php-class-based-querying--net-11863

A: U could take a look if PEAR (http://pear.php.net/) do what u want to do.


text:
Q: Joomla language file reverse search I have a component with its language file. A field in one of our tables contains a string from the language file and in the client the string is substituted with the corresponding value but the user can query on it. Obviously, the user will query using the string he reads, not the corresponding one in the language file, is there a built-in way to get the language file constant, given the value and the language file?
As an example, my language file reads:
COM_MY_COMPONENT_FOO="bar"

And in my table I have:
+-------+-----------------------+
| id    |        some_value     |
+-------+-----------------------+
|   1   |  COM_MY_COMPONENT_FOO |
+-------+-----------------------+

Is there any way to get "COM_MY_COMPONENT_FOO" starting from "foo" (given that I already know the language file used by the user)? Reading the whole language file and reversing it might be too costly, even if I create a separated language file specifically for the "some_value" column.

A: It's far from perfect or elegant, but I found a working solution and I'll post it here for anybody unlucky enought to need this in the future.
Since language files are simple .ini files it's easy to read them as an associative array in PHP with parse_ini_file and reversing an associative array can be done with array_flip. Adding a simple control with isset allows to replicate JText behaviour when the string isn't defined in the language file:
$reverselang = array_flip(parse_ini_file($path_to_lang_file));
if(isset($reverselang[$my_string]){
      return $reverselang[$my_string];
}
return $my_string;

redpajama_set_name: RedPajamaStackExchange


text:
Q: Add a link to RSS feeds on Careers So I guess careers.stackoverflow.com has an RSS feed but there's no link to it on the search page. Maybe such a link could be added?

A: The RSS feeds are in the search jobs sidebar box. They reflect the current search parameters. They are tiny.


text:
Q: pythonanwhere newbie: I don't see sqlite option I see an option for MySql and Postgres, and have read help messages for sqlite, but I don't see anyway to use it or to install it.  So it appears that it's available or else there wouldn't be any help messages, but I can't find it.  I can't do any 'sudo', so no 'apt install', so don't know how to invoke and use it!

A: sqlite is already installed. You don't need to invoke anything to install it. Just configure your web app to use it.


text:
Q: xmm instructions - segmentation fault with memory source operand I'm trying to add 4 numbers to other 4 numbers in assembly language with SSE2 instructions, using XMM registers. I did succeed, but I came over something I didn't understand.
If I do the addition this way:
movdqu xmm0, oword [var1]
movdqu xmm1, oword [var2]
paddd xmm0, xmm1
movdqu oword [var1], xmm0

It works perfectly fine.
But if I try it this way:
movdqu xmm0, oword [var1]
paddd xmm0, oword [var2]
movdqu oword [var1], xmm0

It gives me a segmentation fault.
What is wrong with the second way of doing it? I'm using Nasm, Intel Atom N270, Linux Mint 12 32-bit

A: In the second example var2 needs to be 16 byte aligned, which I suspect is not the case.
In the first example you are using unaligned loads/stores so you don't see the problem there, but the paddd instruction in the second example requires a 16 byte aligned memory operand.


text:
Q: Jackson + Autovalue Builder bean validation I have a the following Event DTO class:
@AutoValue
@JsonDeserialize(builder = AutoValue_Event.Builder.class)
@JsonIgnoreProperties(ignoreUnknown = true)
public abstract class Event {

    public static Event.Builder builder() {
        return new AutoValue_Event.Builder();
    }

    public abstract UUID id();

    @NotNull
    public abstract Type type();

    @NotNull
    @JsonSerialize(using = LocalDateSerializer.class)
    @JsonDeserialize(using = LocalDateDeserializer.class)
    public abstract LocalDate date();

    @AutoValue.Builder
    public abstract static class Builder {

        @JsonProperty("id")
        public abstract Builder id(UUID id);

        @JsonProperty("type")
        public abstract Builder type(Type type);

        @JsonProperty("date")
        public abstract Builder date(LocalDate date);

   }
}

The validation works well for type and date attributes and Jackson throws a JsonMappingException as expected when the payload is not correct. Unfortunately, the returned error message is a text/plain like:
JsonMappingException: Can not construct instance of project.dto.AutoValue_Event$Builder, problem: Missing required properties: type.
Is there a way to handle those validation errors and return a explicit json error object?
I found this post  to catch the exception and return an explicit json but I can't map a custom error message on which field the deserialization failed (I don't want to parse the message exception to know which field is incorrect). Any idea?


text:
Q: create a JMeter https request with credentials (username and password) I want to create an https request to a server that requires username and password. Where can I provide the credentials? I couldn't find this option in the jmeter UI

A: To set up jmeter to access an https url:
Create an HTTP Request Defaults with your server name.
Set implementation to httpClient3.1 (it didnt work for me otherwise)
Set protocol to https
Create an HTTP Request for the login
I used spring security, so I set path to /j_spring_security_check
Set method to post
In the parameters section, add the params you need to log in in the section called Send Parameters with the request. In my case I had to send a username and password param exactly as its defined in my login form.
Finally add a Response assertion to search for a text response. Here I checked for the full display name of the logged in person, since that shows up in the response.
If you want to save the cookie you might also want to create an HTTP Cookie Manager for the thread group
I followed this doc:
http://jmeter.apache.org/usermanual/build-web-test-plan.html

A: It depends on authentication policy, if it's Basic Auth then it would be done through an Http Authorization Manager
If it's form based, then passing them as parameters in Http Request will do it.
If you don't know your option is to record through browser and JMeter Proxy Server:

*

*http://jmeter.apache.org/usermanual/jmeter_proxy_step_by_step.pdf

A: HTTP Request based Authentication

*

*Get your credentials names using Developer tools -> Network tab -> Your POST Request -> Headers tab -> Form Data section.

*Create a Test Plan with some name and some elements

*HTTP Request Defaults

*Empty HTTP Cookie Manager

*Login HTTP Request with credentials specified

*Required HTTP Request

*View Results Tree listener

Testing:
During Login Page passing jmeter gets a Cookie:

During a real request, jmeter uses the Cookie which have been set during Login Page passing:

Also, make sure you have CookieManager.save.cookies=true in your jmeter user.properties file. I've already done it earlier.
$ cat ~/.local/share/jmeter/bin/user.properties | grep Cookie
CookieManager.save.cookies=true

After file modification restart your jmeter.


text:
Q: What's this notation about partitions? Im reading a book and somewhere it says:

A partition of a set $A$ is a family of subsets of $A$, $\{A_a\}_{a\in I}$ such that

Where $I=\{x\mid x=1,\ldots,n\}$.

*

*$A_a\neq A_b\implies A_a\cap A_b=\emptyset$

*...
What does it mean? Does family just mean set? Is $\{A_1,\ldots,A_n\}$, $\{\{A_1,\ldots,A_n\}\}$ or $\{\{A_1\},\ldots,\{A_n\}\}$ a partition of $A$?

A: A family of subsets of $A$ just means a set whose elements are all subsets of $A$. So, a partition would look something like $\{A_1, ..., A_n\}$, where each $A_i \subseteq A$.
Note that there need not only be finitely many sets in the family (although in your case, there is). In that case, we introduce the notion of an indexing set. In the example above, our indexing set would be $\Bbb{N}_n$ (the set of all natural numbers less than or equal to $n$); this is to say, for each $i\in \Bbb{N}_n$, there is a set $A_i$ in the family.

A: A partition of a set $A$ is simply a collection/set of disjoint subsets (i.e. for any pair of subsets in the collection, their intersection is zero) of $A$ such that their union is $A$.
For example, let $P$ be partition of $A$ into $n$ parts, then $P=\{A_1,A_2,...A_n\}$ where $A_1\cup A_2\cup...\cup A_n = A$ and $A_i\cap A_j = \emptyset, \forall A_i\neq A_j$.
Depending upon the usage, $P$ may or may not be allowed to contain the empty set. The former case might be referred to as a weak partition.
Regarding your confusion:

A partition of a set $A$ is a family of subsets of $A$, $\{A_a\}_{a\in I}$ such that
Where $I=\{x\mid x=1,\ldots,n\}$.

This means that the partition is made up of $n$ subsets of $A$, denoted by $\{A_a| \forall a \in \{1,2,...n\}$. This is the same as the definition given above, just that it is in different("set-builder") notation.


text:
Q: How to get additional data from audio mp3 stream I'm currently developing iOS app for streaming audio for radio station, through mp3 file format.
I'm using AVPlayer and it is working like a charm!
In that stream (in mp3 file) server is also sending text data, more specifically title of song and name of the artist.
My questions are
 1. how to get that text data from continuous stream? in other words: how to approach problem of cutting mp3 stream into slices and get text data?
 2. which objects should I use? NSMutableData for example?
 3. which solution is better: slicing stream and getting that text or another service on server which return xml/json with title and artist of a current song played on radio?


text:
Q: Pass value one by one to the query condition and combine multiple rows I want to get all the role_ids based on the permission id from the #permission table with the matching permissionId in the #source_audit table Value column.
And then combine all the role_id for a given permission_id in a single row.
Any help is much appreciated
create table #permission (
    [permission_id] char(6) not null
)

insert into #permission
    values
    ('-336'),
    ('-12016'),
    ('-12014')

create table #source_audit
(
    role_id int,
    value nvarchar(max)
)

insert into #source_audit
    values
    ( 2453, '{"PermissionId":-336, "ConstraintTypeId":7}'),
    ( 2003, '{"PermissionId":-336, "ConstraintTypeId":7}'),
    ( 2123, '{"PermissionId":-12016, "ConstraintTypeId":7}'),
    ( 2893, '{"PermissionId":-14567, "ConstraintTypeId":7}')

Query tried so far and not working
    select srae.*, x.Permission_Id
    from #source_audit as srae
    inner join #permission as x
        on srae.value like '%' + CONVERT(varchar(32), permission_id) + '%'
        and srae.value like '%"ConstraintTypeId":7%'

Result Table

permission_id
role_id

-336
2453, 2003

-12016
2123

A: Your #source_audit.value data is JSON, so we can use OPENJSON on it to pull out the values.
It appears you want to match on absolute values of permission_id (ignoring negative sign).
SELECT
  p.permission_id,
  roles = STRING_AGG(s.role_id, ', ')
FROM permission p
JOIN source_audit s
    CROSS APPLY OPENJSON(s.value)
        WITH ( PermissionId int, ConstraintTypeId int ) j
  ON ABS(j.PermissionId) = ABS(p.permission_id) AND j.ConstraintTypeId = 7
GROUP BY
  p.permission_id;

On SQL Server 2016 or earlier, you need to use the FOR XML method
SELECT
  p.permission_id,
  roles = STUFF((
      SELECT CONCAT(', ', s.role_id)
      FROM source_audit s
      CROSS APPLY OPENJSON(s.value)
        WITH ( PermissionId int, ConstraintTypeId int ) j
      WHERE ABS(j.PermissionId) = ABS(p.permission_id)
        AND j.ConstraintTypeId = 7
      FOR XML PATH(''), TYPE
    ).value('text()[1]','nvarchar(max)'), 1, LEN(', '), '')
FROM permission p;

SQL Fiddle


text:
Q: How to choose the zone division for house price estimation? I'm developing a python script that have the aim to predict the house price using a regression model (in particular i use a polynomial regression). The features that i use for traint my model are:

*

*number of room

*squares metres

*number of bathroom

*if there is a terrace

*if there is a balcony

*latitude

*longitude

*zone

The zone is a nominal attribute that have about 200 values. This is a important attribute because the price of the house varies depending on the zone, there are a zone more expensive.
My question is, i should be use only the latitude and longitude or i can use the zone converted in binary for obtain a good regression result?

A: In my opinion there  are three different types of features you can generate from lat/long data: Categories, Clusters, and Distances.
Categories: Turn each record into a category or categories. Categories could be the country, city, point of interest (POI) or a different geo-spatial layer. Generally, this is called Reversed Geocoding (RGC) or POI extraction
OpenStreetMap. (Free, open source)
For RGC: Nominatim API, see the Reverse Geocoding
For POIs and additional layers: Overpass API
Commercial APIs
Google Places API
Foursquare API
Clusters: In some cases, you would want to treat points on a map in relation to other points. Therefore, you first cluster the points and then assign the cluster ID as a categorical feature in your feature set. Some approaches:
DBSCAN, a clustering method which clusters points based on proximity/density and is robust to outliers.
GMM which is good when your clusters are relatively close to each other but you want a good separation into clusters, or when you want to create soft assignments into clusters.
Hierarchical Clustering (), which creates a dendogram of clusters and allows you to tweak the threshold which decides on the number of clusters.
Spatio-temporal approaches: In some cases, you would want to incorporate the time domain into the model as well (for example when you want to detect the stays/visits of users in a place but ignore places they visit for a very short time).
The third feature type you could extract is distances: Distance from one point to the next, distance to a fixed point (e.g., origin), it all depends on your context. The go-to distance formula is Haversine distance () which calculates a distance given that the earth is a sphere and not flat.


text:
Q: MFMailComposer send email without presenting view I have created a sample iphone application , that sends an email to a particular user.The user address should be static.I am using MFMailComposer class to send an email from iphone.Its work fine.
Now i want to send email to user without presenting MFMailComposerView.Can we programmatically presses the MFMailComposer send button ?.So it will automatically sends an email.
Is this possible? If means how can i programmatically invoke the send button?
Plz help me?
Thanks in advance.....

A: Even if you could do this, it would very probably be thrown out of the app store or denied submission.  For security reasons the user should ALWAYS be able to see email they are sending.
If you want to send data without the user seeing it, transmit the information to a server.

A: As others have already said, doing this is a very bad idea. This is technically possible though, see the e-mail section of Stealth Messenger.


text:
Q: Java SSLSocket error: cannot be referenced from non-static context I am struggling to see what is wrong in here (part of the class):
public class Network implements Runnable {
    private static Network cachedInstance;

    private static boolean connected;

    //private Socket clientSocket;
    private SSLSocket clientSocket;
    private PrintWriter out;
    private BufferedReader in;

    private Map<String, SyncObject> waitForServer;

    private Network(final String hostname, final int port) {
        try {
            Socket baseSocket = new Socket();
            baseSocket.connect(new InetSocketAddress(hostname, port), Config.TIMEOUT);
            clientSocket = (SSLSocket)SSLSocketFactory.createSocket(baseSocket, hostname, port, true);
            clientSocket.startHandshake();
            out = new PrintWriter(clientSocket.getOutputStream(), true);
            in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
            connected = true;
        } catch (IOException ex) {
            connected = false;
        }

        waitForServer = new HashMap<>();
    }

I get an error:
C:\Users\Frank\Dropbox\NetbeansProjects\TradingCardGame\src\network\Network.java:47: error: non-static method createSocket(Socket,String,int,boolean) cannot be referenced from a static context
        clientSocket = (SSLSocket)SSLSocketFactory.createSocket(baseSocket, hostname, port, true);

How am I even being in a static context?
Regards.

A: SSLSocketFactory.createSocket is an instance method. This means that an instance of the SSLSocketFactory class should be created before one will be able to invoke createSocket method on it.
You may try this
SocketFactory sslSocketFactory = SSLSocketFactory.getDefault();
clientSocket = (SSLSocket) sslSocketFactory.createSocket(baseSocket, hostname, port, true);


text:
Q: Is this integration test or unit test? (testing rest controller in spring) I write tests for my rest controller in spring. And I have two questions.

1. Is this integration test or unit test?

2. Should I test here validation annotations like @NotNull and @Valid and other? If no, how to disable them? Because when I pass incorrect json to post request these annotations by default will give me bad request error in response.

External dependencies like services are mocked and class has @ExtendWith(SpringExtension.class)
@WebMvcTest(value = UserController.class, secure = false)
annotations.
@Test
void findByUsername_returnUser() throws Exception {
    when(userService.findByUsername(USERNAME)).thenReturn(Optional.ofNullable(user));
    when(converterContext.getConverter(ConverterShowUserDto.class)).thenReturn(converterShowUserDto);
    when(converterShowUserDto.convert(user)).thenReturn(showUserDto);
    this.mockMvc.perform(get("/user?username=" + USERNAME))
            .andDo(print())
            .andExpect(status()
                    .isOk())
            .andExpect(jsonPath("$.username", is(USERNAME)));
}

My example controller method looks like:
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
public ResponseEntity getById(@PathVariable(value = "id") @ExistAccountWithId int id) {
    Optional<User> user = userService.findById(id);
    ShowUserDto showUserDto = convert(user.get());
    return new ResponseEntity<>(showUserDto, HttpStatus.OK);
}

Validation is based only on custom annotations and exceptions are caught globally. So I dont have any validation inside controller methods. They are separated from each other.

A:
Is this integration test or unit test?

This is unit test. Here you are testing your controller. But it is slightly more than unit test I would say. Because you are testing not only your controller file(UserController), but the controller layer of spring(@WebMvcTest(...)).

Should I test here validation annotations like @NotNull and @Valid
  and other? If no, how to disable them? Because when I pass incorrect
  json to post request these annotations by default will give me bad
  request error in response.

Yes you have to(Or rather you can). That is what I meant, here you can test not only the contoller file, but the controller layer.  You can disable this if you want by registering a mockvalidator.

External dependencies like services are mocked and class has

hence it is not an integration test.


text:
Q: printf, print value to scientific notation I need to change two columns of a file to scientific notation.
The file looks like
test.txt
10177   1   A   AC  0.376827    0.0116338   0.0316735   0.713391    0.422784    0.936182
10352   1   T   TA  0.43176 0.00523364  0.0307872   0.865015    0.427932    0.680802

I have to change values in column 5 and 6 to scientific notation
I am aware of printf "%1.3e", $5 test.txt or printf "%1.3e", $6 test.txt.
However these commands add values from these columns in scientific notation at the beginning of test.txt.
How can i change values of columns 5 and 6 to scientific and keep them to be in column 5 and 6. Thank you for any suggestions.
Expect result would look like
test.txt
10177   1   A   AC  3.768e-01   1.163e-02   0.0316735   0.713391    0.422784    0.936182
10352   1   T   TA  4.318e-01   5.234e-03   0.0307872   0.865015    0.427932    0.680802

I am using the following code, which is obviously not correct :)
awk '{printf "%1.3e", $5}' test.txt > test1.txt
mv -f test1.txt test.txt

A: That will do the trick:
awk '{printf "%d %d %s %s %1.3e %1.3e %f %f %f %f\n", $1, $2, $3, $4, $5, $6, $7, $8, $9, $10}' test.txt > test1.txt
mv -f test1.txt test.txt

Change the spaces/tabs between the columns as needed.

A: $ awk -v OFS='   ' '{for (i=1;i<=NF;i++) printf (i~/^[56]$/?"%1.3e":"%s")"%s", $i, (i<NF?OFS:ORS)}' file
10177   1   A   AC   3.768e-01   1.163e-02   0.0316735   0.713391   0.422784   0.936182
10352   1   T   TA   4.318e-01   5.234e-03   0.0307872   0.865015   0.427932   0.680802

Add -i inplace with GNU awk to avoid explicitly creating the tmp file if that matter to you:
$ cat file
10177   1   A   AC  0.376827    0.0116338   0.0316735   0.713391    0.422784    0.936182
10352   1   T   TA  0.43176 0.00523364  0.0307872   0.865015    0.427932    0.680802
$
$ awk -i inplace -v OFS='   ' '{for (i=1;i<=NF;i++) printf (i~/^[56]$/?"%1.3e":"%s")"%s", $i, (i<NF?OFS:ORS)}' file
$
$ cat file
10177   1   A   AC   3.768e-01   1.163e-02   0.0316735   0.713391   0.422784   0.936182
10352   1   T   TA   4.318e-01   5.234e-03   0.0307872   0.865015   0.427932   0.680802

See the man page for details.


text:
Q: BASH_REMATCH shows empty string after regex match Just want to learn the BASH_REMATCH.
On ubuntu 16.10, I wrote a small script for BASH_REMATCH:
#!/bin/bash
x='sadas123fnrejkwhfklde'
if [[ $x =~ ([0-9]*) ]]
then
  echo "match"
  echo ${BASH_REMATCH[1]}
else
  echo "not match"
fi

However, when /i ran this script, only the "match" shows up, not the captured match!
The bash version is:
$ bash --version
GNU bash, version 4.3.48(1)-release (x86_64-pc-linux-gnu)
Copyright (C) 2013 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>

This is free software; you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.

Any feedback is appreciated.

A: ([0-9])* matches zero or more occurrences of digits anywhere in the string.  So, it is yielding a null string, which is a valid match.
Change the expression to ([0-9]+) so that it matches one or more digits.
#!/bin/bash
x='sadas123fnrejkwhfklde'
if [[ $x =~ ([0-9]+) ]]
then
  echo "match"
  echo ${BASH_REMATCH[1]}
else
  echo "not match"
fi

yields
match
123


text:
Q: почему-то выдается none вместо значений Есть такая програма:
from PIL import Image
im1=Image.open('test.jpg')
im1.convert('RGB')
im1=im1.getcolors()
print(im1)

И вместо числовых значений выдается none. Что я делаю не так?
Помогите пж.


text:
Q: How to drop some interaction terms from R formula I would like to drop some interaction terms from an R formula.  My situation is that I have one factor variable with lots of levels (call this A, and it takes values from 1-50), and another continuous variable that I would like to interact it with (call this B).
A*B

creates terms A1:B, A2:B, A3:B,...  I want a simple way to get rid of the first A1:B term.
Note: I saw some previous answers for the lm case that called update and then dropped some terms.  This will not work for me as I am trying to estimate a multinomial logit model with the mlogit package, and I cannot make the first estimation without dropping some interactions.
Edit: Although I am not attempting to use lm, if I could the following to occur, then I think it would solve my problem.
dd<-data.frame(A=sample(letters[1:10], 100, replace=T),B = runif(100),z=rexp(100))

#need to drop B term below
reg1 <- lm(z~A*B, dd)

#or need to drop Aa:B term here
reg2 <- lm(z~A*B - B, dd)

#but this doesn't work (I realize why, but this is an
#example of what I would like to have happen)
reg3 <- lm(z~A*B - B - Aa:B, dd)

A: I think you should be able to work with contrasts her to make this happen. Here we create our own contrast that adjusts the default contrast.treament behavior to skip the first two variables.
contr.skip2 <- function (n, contrasts = TRUE, sparse = FALSE)
{
    contr <- contr.treatment(n, 1, contrasts, sparse)
    contr[2, ] <- 0
    contr[, -1]
}

and then we can fit the model and pass along our special contrast
lm(z~A*B, dd, contrasts=list(A="contr.skip2"))

# Call:
# lm(formula = z ~ A * B, data = dd, contrasts = list(A = "contr.skip2"))
#
# Coefficients:
# (Intercept)           Ac           Ad           Ae           Af           Ag           Ah
#     1.09981     -0.14541     -0.86334     -0.18478     -0.77302      0.19681      0.23845
#          Ai           Aj            B         Ac:B         Ad:B         Ae:B         Af:B
#    -0.74962     -0.49014      0.09729      0.14705      1.09606      0.14706      0.88919
#        Ag:B         Ah:B         Ai:B         Aj:B
#    -0.62796     -0.70155      1.60253     -0.20564

and as you can see we no longer have Ab terms in the model.


text:
Q: ¿Que librería puedo usar en c++ para agilizar una búsqueda? Quiero hacer un buscador en c++ pero cargo una gran cantidad de datos, primero utilice una búsqueda secuencial y demora mucho, luego ordene los datos y aplique búsqueda binaria, mejoro pero no lo suficiente. He estado revisando y veo que hay estructuras que hacen esto pero no se cual usar, y si me pudieran dar un ejemplo de cómo usarlas estaría agradecido.

A: En lo personal me gusta utilizar el stdlib.h para los ordenamientos, búsquedas, mejoran las conversiones, memoria, tienen control de procesos.
#include<stdlib.h>


text:
Q: cordova camera plugin is not loading after moving to targetSdkVersion 31 After updating my App to targetSdkVersion 31 camera is not loading anymore.
When clicking on cameraBtn as shown bellow my app displays the alert "Camera unavailable". navigator.camera is undefined.
I'm familiar with the plugin usage, I have been using it for the last years successfully, but for some reason now I'm moving to targetSdkVersion 31 it is not working anymore.
I appreciate if anybody can give me directions here!
document.addEventListener('deviceready', function() {
    cameraBtn.addEventListener('click', function() {
        if (!navigator.camera) alert("Camera unavailable")
        else if (!navigator.camera.getPicture) alert(navigator.camera)
        navigator.camera.getPicture(
            function(imgData) { // success
            },
            function(msg) { // fail
            },
            {
                quality: 60,
                destinationType: Camera.DestinationType.DATA_URL,
                sourceType: Camera.PictureSourceType.CAMERA,
                mediaType: Camera.MediaType.PICTURE,
                encodingType: Camera.EncodingType.JPEG,
                cameraDirection: Camera.Direction.BACK,
                correctOrientation: true,
                targetWidth: 512,
                targetHeight: 512
            }
        );
    });
});

Here is my app plugin list:
C:\htdocs\app\myapp>cordova plugin list
cordova-plugin-barcodescanner 0.7.4 "BarcodeScanner"
cordova-plugin-camera 6.0.0 "Camera"
cordova-plugin-compat 1.2.0 "Compat"
cordova-plugin-device 2.1.0 "Device"
cordova-plugin-geolocation 4.1.0 "Geolocation"
cordova-plugin-whitelist 1.3.4 "Whitelist"

And this is my config.xml
<?xml version='1.0' encoding='utf-8'?>
<widget id="io.cordova.myapp"
        version="1.8.1"
        android-versionCode="10036"
        xmlns="http://www.w3.org/ns/widgets"
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:cdv="http://cordova.apache.org/ns/1.0">
    <name>Myapp</name>
    <description>
    </description>
    <author email="suporte@mydomain.com.br" href="http://www.mydomain.com.br">
    </author>
    <content src="index.html" />
    <access origin="*" />
    <allow-intent href="http://*/*" />
    <allow-intent href="https://*/*" />
    <allow-intent href="tel:*" />
    <allow-intent href="sms:*" />
    <allow-intent href="mailto:*" />
    <allow-intent href="geo:*" />
    <platform name="android">
        <allow-intent href="market:*" />
        <config-file after="uses-permission" parent="/manifest" target="AndroidManifest.xml">
            <uses-permission android:name="android.permission.INTERNET" />
            <uses-permission android:name="android.permission.CAMERA" />
            <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
            <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
            <uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" />
        </config-file>
        <edit-config file="app/src/main/AndroidManifest.xml" mode="merge" target="/manifest/application">
            <application android:usesCleartextTraffic="true" />
        </edit-config>
        <edit-config file="app/src/main/AndroidManifest.xml" mode="merge" target="/manifest/application/activity">
            <activity android:exported="true" />
        </edit-config>
    </platform>
    <platform name="ios">
        <allow-intent href="itms:*" />
        <allow-intent href="itms-apps:*" />
        <edit-config file="*-Info.plist" mode="merge" target="NSLocationAlwaysAndWhenInUseUsageDescription">
            <string>Myapp precisa da permissão para acessar a sua geolocalização para identificar a localização do seu dispositivo no módulo de Documentos de RH</string>
        </edit-config>
        <edit-config file="*-Info.plist" mode="merge" target="NSLocationWhenInUseUsageDescription">
            <string>Myapp precisa da permissão para acessar a sua geolocalização para identificar a localização do seu dispositivo no módulo de Documentos de RH</string>
        </edit-config>
        <edit-config file="*-Info.plist" mode="merge" target="NSLocationAlwaysUsageDescription">
            <string>Myapp precisa da permissão para acessar a sua geolocalização para identificar a localização do seu dispositivo no módulo de Documentos de RH</string>
        </edit-config>
        <edit-config file="*-Info.plist" mode="merge" target="NSCameraUsageDescription">
            <string>Myapp precisa da permissão para acessar a sua câmera para anexar fotos aos seus chamados</string>
        </edit-config>
        <edit-config file="*-Info.plist" mode="merge" target="NSPhotoLibraryUsageDescription">
            <string>Myapp precisa da permissão para acessar a sua galeria para anexar fotos aos seus chamados</string>
        </edit-config>
        <edit-config file="*-Info.plist" mode="merge" target="NSPhotoLibraryAddUsageDescription ">
            <string>Myapp precisa da permissão para acessar a sua galeria para salvar as fotos que serão anexadas aos seus chamados</string>
        </edit-config>
    </platform>
    <plugin name="cordova-plugin-whitelist" spec="1" />
    <plugin name="cordova-plugin-geolocation" spec="~4" />
    <plugin name="cordova-plugin-camera" spec="^6" />
    <plugin name="cordova-plugin-barcodescanner" spec="^0.7.4" />
    <preference name="android-minSdkVersion" value="30" />
    <preference name="android-targetSdkVersion" value="31" />
    <icon src="www/icon.png" />
    <icon height="57" platform="ios" src="ios/icon-57.png" width="57" />
    <icon height="72" platform="ios" src="ios/icon-72.png" width="72" />
    <icon height="114" platform="ios" src="ios/icon-114.png" width="114" />
    <icon height="120" platform="ios" src="ios/icon-120.png" width="120" />
    <icon height="144" platform="ios" src="ios/icon-144.png" width="144" />
    <icon height="152" platform="ios" src="ios/icon-152.png" width="152" />
    <icon height="1024" platform="ios" src="ios/icon-1024.png" width="1024" />
</widget>

A: I could solve the problem removing camera plugin and adding it with ANDROIDX_CORE_VERSION 1.8.0 as suggested on cordova-plugin-camera github
cordova plugin add cordova-plugin-camera --variable ANDROIDX_CORE_VERSION=1.8.0

Previously package.json was showing ANDROIDX_CORE_VERSION 1.6.+


text:
Q: What's the rule on hijacking Windows error codes for return from my own code? Are the error codes defined in WinError.h free to be hijacked and returned my by own code?
There are some generic Win32 error codes defined:

*

*ERROR_FILE_NOT_FOUND: "The system cannot find the file specified."
that of course i could use for my own purpose when a file is not found.
Then there are still some generic errors:

*

*ERROR_ACCESS_DENIED: "Access is denied."
but it's generally understood that this error comes when trying to access a file. i might have an HttpGet() function that returns ERROR_ACCESS_DENIED if the server returns a 401.
But then there are codes that are defined as being for a particular purpose. Imagine my HttpGet() function throws an error if the https certificate is not a type we support:

*

*ERROR_IPSEC_IKE_INVALID_CERT_TYPE: "Invalid certificate type"
except that code is defined quite clearly in WinError.h as belonging to IPSec:
///////////////////////////////////////////////////
//                                               //
//           Start of IPSec Error codes          //
//                                               //
//                 13000 to 13999                //
///////////////////////////////////////////////////

...

//
// MessageId: ERROR_IPSEC_IKE_INVALID_CERT_TYPE
//
// MessageText:
//
// Invalid certificate type
//
#define ERROR_IPSEC_IKE_INVALID_CERT_TYPE 13819L

But the error text is exactly what i want!
We have a financial system that requires a 2nd user to approve a transaction; this means that the entered credentials must be a different user than the first person:

*

*MK_E_MUSTBOTHERUSER: "User input required for operation to succeed"
or perhaps:

*

*ERROR_LOGON_TYPE_NOT_GRANTED: "Logon failure: the user has not been granted the requested logon type at this computer."
i get the sense that spelunking through WinError, cherry-picking error codes by the string they show and re-purposing them to indicate errors they were not designed for, is something Raymond would give me a slap for.
Are Windows error codes a freely available "pool" of error codes? Or are all Windows error codes only to be returned from Microsoft's code?
If i'm creating HRESULTS, i need to use some code. And it would be great if the user could call FormatMessage to turn my HRESULT into a string. (Especially since my return HRESULT could either me either my own code, or an HRESULT that was returned to me from Microsoft code).

A: When you define your own HRESULT codes, you are recommended to use FACILITY_ITF and define your codes in this range of application-defined codes. Yes the codes would overlap between applications, but you can also provide additional descriptive message through SetErrorInfo API and indicating support by implementing ISupportErrorInfo if you are implementing COM object/interface.
An excerpt from COM+ Programming book explains this in greater detail: COM+ programming: a practical guide using Visual C++ and ATL (page 67).
Simpler than that, you can use your custom facility code and this might be different in different modules, so you can easily identify which module is the source of the problem.
If you put MESSAGETABLE resource into your binary, FormatMessage API could resolve HRESULTs and extract description text for individual codes, just like it happens with regular Windows error codes (the app would still need to provide module handle to the API function).
See also: Creating your own HRESULT?

O.P. Edit:
From Microsoft's Open Protocol Specification of HRESULTs

2.1 HRESULT
The HRESULT numbering space is vendor-extensible. Vendors can supply their own values for this field, as long as the C bit (0x20000000) is set, indicating it is a customer code.
C (1 bit): Customer. This bit specifies if the value is customer-defined or Microsoft-defined. The bit is set for customer-defined values and clear for Microsoft-defined values. <1>
<1> Section 2.1: All HRESULT values used by Microsoft have the C bit clear.

This means that i can make up any HRESULT i like as long as i set the C bit. As a practical matter this means that i can any any code i like, e.g.:
E_LOGON_FAILURE = 0xA007052E;

Of course i didn't come up with this number at random.
First i set the high bit to 1, to indicate an error:
0x80000000

Then i "choose" an error code, e.g. 1326 (0x52E hex):
0x8000052E

Then i need to choose a facility. Let's chooooose, on i dunno, seven:
0x8007052E

Finally i set the Customer bit, to indicate it is not a Microsoft defined HRESULT:
0xA007052E

And coincidentally everything up until the last step is the guts of the Microsoft HRESULT_FROM_WIN32 macro:

Maps a system error code to an HRESULT value.
 HRESULT HRESULT_FROM_WIN32(DWORD x);

A: Don't go down this road, and just define your own.
Reuse of the codes themselves is pointless, since having your own codes is just one #define away.
Reuse of the error strings is not such a good idea either:

*

*These will be localized. So if your (English) application runs on a Chinese version of Windows, the user will see a mixture of the two languages.

*Microsoft might change the text at their whim, with a new release of Windows or with an update. For example, if you used ERROR_IPSEC_IKE_INVALID_CERT_TYPE to indicate HTTPS certificate errors, and Microsoft decided to fix their vague message to say "Invalid IPSEC IKE certificate type" instead? (I don't know what IKE is at all, and have only a vague notion about IPSEC, but you get the point.)

*You'll have no way of customizing the error messages to be clearer or more specific.

*Once users of your API start using FormatMessage, you'll be forever tied to the set of error codes and messages that Microsoft provides.
If you already know that Raymond Chen would slap you, why are you even considering this? ;)

A: i think i may have found my own answer, by actually reading the documentation:

System Error Codes
The System Error Codes are very broad. ...  Because these codes are defined in WinError.h for anyone to use, sometimes the codes are returned by non-system software.

Although only error codes are described as such (i.e. positive numbers from 0-15999).
But the same spirit starts to apply to COM error codes:

*

*E_NOTIMPL: 0x80004001 Not implemented

*E_INVALIDARG: 0x80070057 One or more arguments are invalid

*E_FAIL: 0x80004005 Unspecified error  (The dreaded 80004005 unspecified error, error)

In fact it's Delphi's safecall mapping that converts any generic exception into

*

*E_UNEXPECTED 0x8000FFFF Catastrophic failure
So it's quite expected to use Microsoft's HRESULT codes.

You also have the HRESULTs that are HRESULT formulations of the standard Win32 error codes, e.g. E_HANDLE is a wrapper around ERROR_INVALID_HANDLE (6):
E_HANDLE = 0x80070006;   //Invalid handle

Which is done using the HRESULT_FROM_WIN32 macro.
Although it might be morally questionable to use Microsoft HRESULTS outside generic facilities:

*

*FACILITY_NULL For broadly applicable common status codes such as S_OK.

*FACILITY_RPC For status codes returned from remote procedure calls.

*FACILITY_DISPATCH For late-binding IDispatch interface errors.

*FACILITY_ITF For most status codes returned from interface methods. The actual meaning of the error is defined by the interface. That is, two HRESULTs with exactly the same 32-bit value returned from two different interfaces might have different meanings.

*FACILITY_WIN32 Used to provide a means of handling error codes from functions in the Windows API as an HRESULT.


text:
Q: how do you create a large-hdpi AVD? i've got Eclipse 3.7.2 and Android plugin v23.0.2.1259578
what settings to i have to give in order to create an emulator that will pick up resources from res/layout-large-hdpi

A: nexus 7 should do it if you have that in the list


text:
Q: how to get this layout in wordpress website. Is there any plugin to get this?
I've found that grid clickable layout on hackhands.com and I want to integrate on my website.
source: https://hackhands.com/

A: You should use Visual Slide Box Builder plugin for this purpose.


text:
Q: Get size of data transferred by REST Web Services? I am using REST Web Services to upload a java object from a client to a server. How can I know the actual size of the data transferred per web service call?
I use Java 1.7, Jersey.
Part of the client code is below:
ClientResponse response = service.path(SERVER_PATH).path(myWebServiceMethod)
    .type(MediaType.APPLICATION_JSON).post(ClientResponse.class, myJavaObject);


text:
Q: Passing the variable whose value can change every time, from a php page to another I have a form from which i'm getting the values of two variables say username and password using POST method.
$Username=$_POST['Username'];
$Password=$_POST['Password'];

I tried passing these variables to another php page using the following code.
Click here

In the other page,i tried printing the variable as follows.
$User=$_GET['Username'];
echo $USer;

But,I didn't get the value stored in the varible. Instead,its printing "$Username" as the value as given in the anchor tag.
I just need to print the value stored in the variable $Username.
Please, help. Thanks in advance.

A: You're looking for the following:
<a href="abc.php?Username=<?php echo $Username; ?>&Password=<?php echo $Password; ?>">Click here

Although you should be careful if the variables contain special characters. So I'd advise using:
<?php echo urlencode($Username); ?>

<?php echo urlencode($Password); ?>

A: Since you haven't indicated that this is PHP code, $Username is interpreted as HTML, resulting in $Username as output. In order to output the actual value, you should add the appropriate tags, for example like this:
<a href="abc.php?Username=<?php echo $Username; ?> & Password=<?php echo $Password; ?>">Click here

By the way, given your code, you are not expected to echo anything, since variables are case sensitive in PHP, so $USer in your echo and $User the line before are two distinct variables.
Also note that:

*

*You shouldn't pass passwords through URIs in the first place,

*You don't seem to escape input,

*The whitespace before and after "&" character in the href attribute may not be what you really want to do.

A: You need to tell that $Username is actually a PHP variable, and not a HTML CDATA string. Convert your link code to:
<a href="abc.php?Username=<?php echo $Username; ?>&Password=<?php echo $Password; ?>">Click here

A: I think it's better if you put them in a session.
You can make it like this:
$Username=$_POST['Username'];
$Password=$_POST['Password'];

session_start():
$Username = $_SESSION['usernameSession'];
$Password = $_SESSION['passwordSession'];

In the other page just call the session
session_start();

echo ".$_SESSION['usernameSession']";


text:
Q: Why does calling glMatrixMode(GL_PROJECTION) give me EXC_BAD_ACCESS in an iPhone app? I have an iphone app where I call these three functions in appDidFinishLaunching:
glMatrixMode(GL_PROJECTION);
glOrthof(0, rect.size.width, 0, rect.size.height, -1, 1);
glMatrixMode(GL_MODELVIEW);

When stepping through with the debugger I get EXC BAD ACCESS when I execute the first line.  Any ideas why this is happening?
Btw I have another application where I do the same thing and it works fine.  So I've tried to duplicate everything in that app (#imports, adding OpenGLES framework, etc) but now I'm just stuck.

A: I've run into this with OpenGL calls if two threads are attempting to draw to the OpenGL scene at once.  However, that doesn't sound like what you're doing.
Have you properly initialized your display context and framebuffer before this call?  For example, in my UIView subclass that does OpenGL drawing, I call the following in its initWithCoder: method:
context = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES1];

if (!context || ![EAGLContext setCurrentContext:context] || ![self createFramebuffer])
{
    [self release];
    return nil;
}

The createFramebuffer method looks like the following:
- (BOOL)createFramebuffer
{
    glGenFramebuffersOES(1, &viewFramebuffer);
    glGenRenderbuffersOES(1, &viewRenderbuffer);

    glBindFramebufferOES(GL_FRAMEBUFFER_OES, viewFramebuffer);
    glBindRenderbufferOES(GL_RENDERBUFFER_OES, viewRenderbuffer);
    [context renderbufferStorage:GL_RENDERBUFFER_OES fromDrawable:(CAEAGLLayer*)self.layer];
    glFramebufferRenderbufferOES(GL_FRAMEBUFFER_OES, GL_COLOR_ATTACHMENT0_OES, GL_RENDERBUFFER_OES, viewRenderbuffer);

    glGetRenderbufferParameterivOES(GL_RENDERBUFFER_OES, GL_RENDERBUFFER_WIDTH_OES, &backingWidth);
    glGetRenderbufferParameterivOES(GL_RENDERBUFFER_OES, GL_RENDERBUFFER_HEIGHT_OES, &backingHeight);

    if (USE_DEPTH_BUFFER) {
        glGenRenderbuffersOES(1, &depthRenderbuffer);
        glBindRenderbufferOES(GL_RENDERBUFFER_OES, depthRenderbuffer);
        glRenderbufferStorageOES(GL_RENDERBUFFER_OES, GL_DEPTH_COMPONENT16_OES, backingWidth, backingHeight);
        glFramebufferRenderbufferOES(GL_FRAMEBUFFER_OES, GL_DEPTH_ATTACHMENT_OES, GL_RENDERBUFFER_OES, depthRenderbuffer);
    }

    if(glCheckFramebufferStatusOES(GL_FRAMEBUFFER_OES) != GL_FRAMEBUFFER_COMPLETE_OES)
    {
        return NO;
    }

    return YES;
}

This is pretty much boilerplate code, as generated by the OpenGL ES Application template in XCode.  Perhaps by not initializing things before calling glMatrixMode(), you're getting a crash.
Also, why are you doing OpenGL drawing in applicationDidFinishLaunching:?  Wouldn't a view or view controller be a more appropriate place for OpenGL calls than your UIApplicationDelegate?

A: Unlikely to be the problem given the date on which you submitted the bug, but you'd also see something like this if you use the Apple example code and run on an ES 2.0 capable device, as it removes the matrix stack from the spec, though the function definitions will remain visible to the compiler since the device also supports ES 1.1.

A: I've seen this error in many different situations but never specifically in yours. It usually comes up as a result of the application trying to access memory that has already been released.
Can you confirm that rect is still allocated?

A: You need to replace the current matrix with the identity matrix before calling glOrthof. This can be done with glLoadIdentity()

A: Restart the iPhone Simulator. This issue is definitely due to the OpenGL context not being set properly.  I found that sometimes the iPhone Simulator has issues and needs to be restarted for the OpenGL context to get set properly by [EAGLContext setCurrentContext:].


text:
Q: How to open Lightning component in new window I have linked my lightning component with Quick action button, my requirement is I want to open lightning component in a new window.
How should I achieve this

A: You should consider using lightning:navigation.
Target component
should implement lightning:isUrlAddressable
<aura:component implements="lightning:isUrlAddressable" access="global" >
Test
</aura:component>

Add to your quick action component
<lightning:navigation aura:id="navService"/>

And how to navigate from your quick action controller
        var pageReference = {
            type: 'standard__component',
            attributes: {
                componentName: 'c__helloTarget',
            },
            state: {
                "c__firstname": "John"
            }
        };

        var navService = component.find("navService");
        event.preventDefault();
        navService.navigate(pageReference);

This code directs you to /lightning/cmp/c__helloTarget?c__firstname=John

A: You can create a detail page button with URL:

URL:
/lightning/cmp/c__MyCompName?c__att1=some_value

When you add this to record page layout, it will open component directly. You can also add parameters (all parameters should start with c__). Your component can read parameters through state in isUrlAddressable.
Note: This is URL hack and will work as long as URLs template dont change.

A: Here are two Quick Action Button Lightning Component solutions to either open a pop-up window or new browser tab with a Visualforce Page (or whatever URL you want to redirect to):
Lightning Component:
<aura:component implements="force:lightningQuickAction,force:hasRecordId" access="global">
    <aura:handler name="init" action="{!c.openPage}" value="{!this}" />
</aura:component>

Controller (to open pop-up window):
({
    openPage : function(component,event){
        var w = 1020;
        var h = screen.height-120;
        var left = (screen.width/2)-(w/2);
        var top = 0;
        var recordId = component.get('v.recordId');
        //Open Pop-up Window with Visualforce Page
        window.open('/apex/YOUR_VISUALFORCE_PAGE?id='+recordId, 'Sales Contract', 'toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=yes, resizable=yes, copyhistory=no, width='+w+', height='+h+', top='+top+', left='+left);
        //Close Action Button Modal
        $A.get('e.force:closeQuickAction').fire();
    }
})

Controller (to open new browser tab):
({
    openPage : function(component,event){
        var recordId = component.get('v.recordId');
        //Open New Browser Tab with Visualforce Page
        window.open('/apex/YOUR_VISUALFORCE_PAGE?id='+recordId,'_blank');
        //Close Action Button Modal
        $A.get('e.force:closeQuickAction').fire();
    }
})


text:
Q: Failed to load next.config.js After cloning the repository I created and set my .env.local file, ran npm i then ran npm run dev. The server starts, env is loaded from .env.local however it immediately fails prompting me with the following:
error - Failed to load next.config.js, see more info here https://nextjs.org/docs/messages/next-config-error
Error: Not supported
    at Object.loadConfig [as default] (C:\Users\Nick\Desktop\rebuild\node_modules\next\dist\server\config.js:399:74)
    at async NextServer.loadConfig (C:\Users\Nick\Desktop\rebuild\node_modules\next\dist\server\next.js:110:22)
    at async NextServer.prepare (C:\Users\Nick\Desktop\rebuild\node_modules\next\dist\server\next.js:92:24)
    at async C:\Users\Nick\Desktop\rebuild\node_modules\next\dist\cli\next-dev.js:126:9
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! rebuild@0.1.0 dev: `next dev`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the rebuild@0.1.0 dev script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\Nick\AppData\Roaming\npm-cache\_logs\2021-10-29T19_47_30_427Z-debug.log

The NextJS documentation says: See the error message in your terminal where you started next to see more context. however all it is telling me is Not Supported.
I'm not familiar with the error and was looking for guidance.

A: I ended up uninstalling Node and everything related to it. Reinstalled with Node v14.0.0 and it seemed to work.
Thanks all for your help!

A: This error Error: Not supported is likely coming up because the installed Node.js version is not supported by the used Next.js version.
e.g. Next.js v12 doesn't support Node.js v10:

The minimum Node.js version has been bumped from 12.0.0 to 12.22.0, which is the first version of Node.js with native ES modules support

This version discrepancy can arise for several reasons, sometimes quite unexpected, and also seemingly "out of nowhere", because not only a "wrong" Node.js version can be installed, but also different Node.js versions can be installed in different paths.
Solutions:
(Note that after the below solutions you also might need to delete the folders .next and node_modules, and re-install the node modules again, e.g. yarn or npm install).
1. different computer
If you pull the repository on a different computer, where a different Node.js version is installed:
Solution: update Node.js to the supported version.
2. different environment
If you build the repository inside a different environment, where a different Node.js version is referenced (e.g. in Webstorm vs. a separate Terminal):
Solution: make sure you are using the correct environment, or use the correct path to Node.js, or update Node.js.
3. different build commands
If you use different build commands, which do or do not specify a (absolute) path to a specific node.js installation:

*

*e.g. /usr/bin/node ... --> use absolute path to specific node.js installation.

*e.g. node ... --> use node installation as specified in the $PATH environment variable, e.g. /home/(username)/.nvm/versions/node/v14.18.1/bin/node.

Solution: Modify the build script to use the correct path to Node.js, or update the Node.js version under the used path.
4. broken build setup
If for some reason the build setup in Webstorm gets lost or breaks, which apparently can happen sometimes, e.g. when switching branches:
(You can verify this by trying to build inside a separate terminal.)
Solution: Fix the build setup in Webstorm to use the correct Note.js path, or update Node.js under the used path.

A: I solved this by upgrading to the latest version of nodeJS


text:
Q: Order of DynamoDB multiple conditions query I am studying DynamoDB and confuse on the order.
a. Could I use multiple conditions in the KeyConditions field of query command to do the 'AND' query? i.e. Set condition to the following keys:
hash part of primary key,
range part of primary key,
local secondary index 1,
b. If it's workable, how would DynamoDB sort the result?

A: DynamoDB can only use one index at a time so you can't really query using both a range primary key AND a secondary index.
The sort will be based on the index actually used.
The conditions are filtering out results and are not limited to indices.


text:
Q: SQL Statement return 'FALSE' in ELSE block this is my SQL code:
if NOT EXISTS (select * from tblArtist where Artist= 'The Rolling Stones')
INSERT INTO tblArtist (Artist)
Output inserted.ID, 'TRUE' as isNewEntry
Values('The Rolling Stones')
ELSE (Select ID from tblArtist
Where Artist = 'The Rolling Stones');

this works so far. But if it comes to the else block it should return 'FALSE' as isNewEntry...
now i cannot just use Output keyword because i think it cant be used with select keyword.
Thanks for your help!

A: Like this?
if NOT EXISTS (select * from tblArtist where Artist= 'The Rolling Stones')
INSERT INTO tblArtist (Artist)
Output inserted.ID, 'TRUE' as isNewEntry
Values('The Rolling Stones')
ELSE (Select ID, 'FALSE' as isNewEntry from tblArtist
Where Artist = 'The Rolling Stones');


text:
Q: How to show and parse rsync progress in Python? I am using the development version of rsync with --info-progress option. I am writing a python program which transfer files from server to local computer using rsync:
finalresult = subprocess.Popen(['sshpass', '-p', password, 'rsync', '-avz', '--info=progress2', 'hostname:/filename', '/home/nfs/django/user'],
                                    stdout=subprocess.PIPE).communicate()[0]

When I run the program in the terminal, it doesn't show me the progress however if I use the rsync utility independently it shows the progress. I want to see the progress in the Terminal and parse or take the progress percentage to use it later to show progress bar to the user in real time. Thank you!
Edit:
This is what I have tried so far:
The code above stores the command processing in finalresult variable. I tried to print finalresult variable in the django template but it doesn't returns anything.

A: Sorry, but that probably cannot be done neither with subprocess nor with the rest of the standard library. And that is because inside subprocess.communicate() you would find:
def wait(self):
   """Wait for child process to terminate.  Returns returncode
   attribute."""
   if self.returncode is None:
      # Try calling a function os.waitpid(self.pid, 0)
      # Ignore Interrupted System Call (errno.EINTR) errors
      pid, sts = _eintr_retry_call(os.waitpid, self.pid, 0)
      self._handle_exitstatus(sts)
   return self.returncode

On Unix the os.waitpid() function call means: Wait for completion of a child process given by process id pid, and return a tuple containing its process id and exit status indication. So, you have to wait until the child process is finished.
The closest alternative would be pexpect, but it still won't do the progress bar analysis. A possible solution would be hacking rsync and patching its progress output so that pexpect could work with it.


text:
Q: rails deeply nested form_for not able to save twice I have a form where teams can register for a tournament. The form saves & routes as expected when I first save the form, however if I return to the root_path & repeat the process of registering a team, the form doesn't save at all (clicking on the "Submit" button does nothing).
My feeling is that something is hanging around from the original save that is stopping a new one from happening, but I'm not able to put my finger on what it is. Code is below, hope it is sufficient.
(routes.rb)
root 'tournaments#index'
  resources :tournaments do
    resources :teams do
      resources :players, :only => [:new, :create]
    end
  end

(models)
class Tournament < ApplicationRecord
  has_many :teams
  has_many :players, :through => :teams

  accepts_nested_attributes_for :teams
  accepts_nested_attributes_for :players
end

class Team < ApplicationRecord
  belongs_to :tournament, required: false
  has_many :players

  accepts_nested_attributes_for :players
end

class Player < ApplicationRecord
  belongs_to :team, required: false
  has_one :tournament, :through => :team
end

(tournaments_controller.rb)
  def index
    @tournaments = Tournament.all
  end

  def show
    @tournament = Tournament.find(params[:id])
  end

  def new
    @tournament = Tournament.new
  end

  def create
      @tournament = Tournament.new(tournament_params)
      if @tournament.save
      flash[:notice] = "#{@tournament.name} saved."
      redirect_to root_path
    else
      render :new
    end
  end

  private

  def tournament_params
    params.require(:tournament).permit(:name, :deadline, :divisions, :info, :payment, :tournament_date, team_attributes: [:name, :division, :contact_email, :contact_name])
  end

(teams_controller.rb)
    def create
        @team = Team.new(team_params)
        if @team.save
          flash[:notice] = "Team Registered."
          redirect_to tournament_team_path(params[:tournament_id], @team.id)
        else
          redirect_to new_tournament_team_path(params[:tournament_id])
        end
    end

    def new
        @tournament = Tournament.find_by_id(params[:tournament_id])
        @team = Team.new
        8.times do
          @team.players.build
        end
    end

    def show
    @tournament = Tournament.find(params[:tournament_id])
    @team = Team.find(params[:id])
    end

    private

  def team_params
    params.require(:team).permit(:name, :tournament_id, :division, :contact_name, :contact_email, players_attributes: [ :name, :gender, :referee ])
  end

Entry link from tournaments#show page to the teams#new action (this works ... as far as that it links to the correct page)
<%= link_to(new_tournament_team_path(params[:id])) do %>

Register Team

<% end %>

(teams/new.html.erb) - this is the form that doesn't work. I should use partials, but I'd like to get it working to start.

<%= @tournament.name %>

Team Registration

        <%= form_for [@tournament, @team] do |f| %>
        <%= f.hidden_field :tournament_id, :value => @tournament.id %>

                <%= f.label :division, "Division: " %>
                <%= f.select :division, options_for_select([["Mixed", "mixed"], ["Mens", "mens"]]) %>

                <%= f.text_field :name, required: '' %>

                <%= f.text_field :contact_name, required: '' %>

                <%= f.text_field :contact_email, required: '' %>

            <%= f.fields_for :players do |builder| %>

                   <%= builder.text_field :name, required: '' %>
                   <%= builder.select :gender, options_for_select([["Male", "male"], ["Female", "female"]]) %>
                   <%= builder.select :referee, options_for_select([["No", "no"], ["Yes", "yes"]]) %>

            <% end %>

    <%= f.submit 'Submit Team', :class => 'rounded_btn' %>

        <% end %>

This generates the following HTML output:

    <container>

Taipei Touch Association

Tournament Management System

Dummy Tournament

Team Registration

        <form class="new_team" id="new_team" action="/tournaments/1/teams" accept-charset="UTF-8" method="post"><input name="utf8" type="hidden" value="✓"><input type="hidden" name="authenticity_token" value="+CtsL2QcMjj1703iGPpwgs8vYu7TWJfWt9jTUgCYTMaFE9JdvYIMJqdb87z4vKuDzUgb8RO96Mdvk5fW/uJUSw==">
        <input value="1" type="hidden" name="team[tournament_id]" id="team_tournament_id">

                Division:
                <select name="team[division]" id="team_division"><option value="mixed">Mixed</option>
<option value="mens">Mens</option></select>

                <input required="required" type="text" name="team[name]" id="team_name">

                <input required="required" type="text" name="team[contact_name]" id="team_contact_name">

                <input required="required" type="text" name="team[contact_email]" id="team_contact_email">

                   <input required="required" type="text" name="team[players_attributes][0][name]" id="team_players_attributes_0_name">
                   <select name="team[players_attributes][0][gender]" id="team_players_attributes_0_gender"><option value="male">Male</option>
<option value="female">Female</option></select>
                   <select name="team[players_attributes][0][referee]" id="team_players_attributes_0_referee"><option value="no">No</option>
<option value="yes">Yes</option></select>

                   <input required="required" type="text" name="team[players_attributes][1][name]" id="team_players_attributes_1_name">
                   <select name="team[players_attributes][1][gender]" id="team_players_attributes_1_gender"><option value="male">Male</option>
<option value="female">Female</option></select>
                   <select name="team[players_attributes][1][referee]" id="team_players_attributes_1_referee"><option value="no">No</option>
<option value="yes">Yes</option></select>

                   <input required="required" type="text" name="team[players_attributes][2][name]" id="team_players_attributes_2_name">
                   <select name="team[players_attributes][2][gender]" id="team_players_attributes_2_gender"><option value="male">Male</option>
<option value="female">Female</option></select>
                   <select name="team[players_attributes][2][referee]" id="team_players_attributes_2_referee"><option value="no">No</option>
<option value="yes">Yes</option></select>

                   <input required="required" type="text" name="team[players_attributes][3][name]" id="team_players_attributes_3_name">
                   <select name="team[players_attributes][3][gender]" id="team_players_attributes_3_gender"><option value="male">Male</option>
<option value="female">Female</option></select>
                   <select name="team[players_attributes][3][referee]" id="team_players_attributes_3_referee"><option value="no">No</option>
<option value="yes">Yes</option></select>

                   <input required="required" type="text" name="team[players_attributes][4][name]" id="team_players_attributes_4_name">
                   <select name="team[players_attributes][4][gender]" id="team_players_attributes_4_gender"><option value="male">Male</option>
<option value="female">Female</option></select>
                   <select name="team[players_attributes][4][referee]" id="team_players_attributes_4_referee"><option value="no">No</option>
<option value="yes">Yes</option></select>

                   <input required="required" type="text" name="team[players_attributes][5][name]" id="team_players_attributes_5_name">
                   <select name="team[players_attributes][5][gender]" id="team_players_attributes_5_gender"><option value="male">Male</option>
<option value="female">Female</option></select>
                   <select name="team[players_attributes][5][referee]" id="team_players_attributes_5_referee"><option value="no">No</option>
<option value="yes">Yes</option></select>

                   <input required="required" type="text" name="team[players_attributes][6][name]" id="team_players_attributes_6_name">
                   <select name="team[players_attributes][6][gender]" id="team_players_attributes_6_gender"><option value="male">Male</option>
<option value="female">Female</option></select>
                   <select name="team[players_attributes][6][referee]" id="team_players_attributes_6_referee"><option value="no">No</option>
<option value="yes">Yes</option></select>

                   <input required="required" type="text" name="team[players_attributes][7][name]" id="team_players_attributes_7_name">
                   <select name="team[players_attributes][7][gender]" id="team_players_attributes_7_gender"><option value="male">Male</option>
<option value="female">Female</option></select>
                   <select name="team[players_attributes][7][referee]" id="team_players_attributes_7_referee"><option value="no">No</option>
<option value="yes">Yes</option></select>

            </form>

    <input type="submit" name="commit" value="Submit Team" class="rounded_btn" data-disable-with="Submit Team">

    </container>

Note: This problem persists even when using the nested_forms gem.

A: I deleted <%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %> from my /views/application.erb.html file & now the funtion seems to work.


text:
Q: How can I construct a SetJoin in JPA when there's no Set in my entity member field? I'm using JPA 2.0, Hibernate 4.1.0.Final, and MySQL 5.5.37.  I have the following entities
@Entity
@Table(name = "user_subscription",
    uniqueConstraints = { @UniqueConstraint(columnNames = { "USER_ID", "SUBSCRIPTION_ID" }) }
)
public class UserSubscription
{

    @Id
    @Column(name = "ID")
    @GeneratedValue(generator = "uuid-strategy")
    private String id;

    @ManyToOne
    @JoinColumn(name = "USER_ID", nullable = false, updatable = true)
    private User user;

    @ManyToOne
    @JoinColumn(name = "SUBSCRIPTION_ID", nullable = false, updatable = true)
    private Subscription subscription;

and
@Entity
@Table(name = "Subscription")
public class Subscription implements Serializable
{

    @Id
    @Column(name = "ID")
    @GeneratedValue(generator = "uuid-strategy")
    private String id;

    @OneToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "PRODUCT_ID")
    @NotNull
    private Product product;

Without altering the entities, how do I construct a JPA CriteriaBuilder query in which I look for User entities that do not have a particular Subscription entity "A", but have other subscription entities that match the same product as entity "A"?  I have tried this to no avail …
public List<User> findUsersWithSubscriptions(Subscription Subscription)
{
    final List<User> results = new ArrayList<User>();
    final CriteriaBuilder builder = m_entityManager.getCriteriaBuilder();
    final CriteriaQuery<UserSubscription> criteria = builder.createQuery(UserSubscription.class);
    final Root<UserSubscription> root = criteria.from(UserSubscription.class);

    Join<UserSubscription, Subscription> SubscriptionRoot = root.join(UserSubscription_.subscription);

    criteria.select(root).where(builder.equal(root.get(UserSubscription_.Subscription).get(Subscription_.product),subscription.getProduct()),
                                builder.notEqual(root.get(UserSubscription_.subscription), subscription));

I thought if I could build a SetJoin from the user -> subscription entities, I could say something like "not.in", but I'm not sure how to do that given the constraints.
Edit: This is the SQL produced by Vlad's post:
SELECT user1_.id                       AS id97_,
       user1_.creator_id               AS CREATOR15_97_,
       user1_.dob                      AS DOB97_,
       user1_.enabled                  AS ENABLED97_,
       user1_.expiration               AS EXPIRATION97_,
       user1_.first_name               AS first5_97_,
       user1_.grade_id                 AS GRADE16_97_,
       user1_.incorrect_logins         AS INCORRECT6_97_,
       user1_.last_name                AS last7_97_,
       user1_.middle_name              AS middle8_97_,
       user1_.organization_id          AS organiz17_97_,
       user1_.password                 AS password97_,
       user1_.reset_state              AS RESET10_97_,
       user1_.salutation               AS salutation97_,
       user1_.temporary_password       AS temporary12_97_,
       user1_.url                      AS url97_,
       user1_.user_demographic_info_id AS USER18_97_,
       user1_.user_name                AS user14_97_
FROM   sb_user_subscription subscription0_
       INNER JOIN sb_user user1_
               ON subscription0_.user_id = user1_.id
       INNER JOIN cb_subscription subscription2_
               ON subscription0_.subscription_id = subscription2_.id
       INNER JOIN sb_product product3_
               ON subscription2_.product_id = product3_.id
                  AND product3_.id = ?
                  AND subscription2_.id <>?

A: Check this query:
final CriteriaBuilder builder = m_entityManager.getCriteriaBuilder();
final CriteriaQuery<User> criteria = builder.createQuery(User.class);
final Root<UserSubscription> root = criteria.from(UserSubscription.class);

Join<UserSubscription, User> userJoin = root.join(UserSubscription_.user);
Join<UserSubscription, Subscription> subscriptionJoin = root.join(UserSubscription_.subscription);
Join<Subscription, Product> productJoin = subscriptionJoin.join(Subscription_.product);

criteria
    .select(userJoin)
    .where(cb.and(
         builder.equal(productJoin, subscription.getProduct()),
         builder.notEqual(subscriptionJoin, subscription)
);
return entityManager.createQuery(criteria).getResultList();

The output query looks fine and it should select Users with a given subscription.product and with a different subscription than the product parent's one.
You could try it in your SQL console, but it looks fine and it validates the initial requirement:

that do not have a particular Subscription entity "A", but have other
  subscription entities that match the same product as entity "A"


text:
Q: Survey analysis with categorical data and chart plotting I have a database that comes from a survey, and from this database I constructed a dataframe in R, that looks similar to this:
    cnt  <-as.factor(c("Country 1", "Country 2", "Country 3", "Country 1", "Country 2", "Country 3" ))
    bnk  <-as.factor(c("bank 1", "bank 2", "bank 3", "bank 1", "bank 2", "bank 3" ))
    qst  <-as.factor(c("q1", "q1", "q1", "q2","q2","q2" ))
    ans  <-as.numeric(c(1,1,2,1,2,3))
    df   <-data.frame(cnt, bnk, qst,ans)
names(df) <- c("Country", "Institute", "Question", "Answer")

      Country Institute Question Answer
1 Country 1    bank 1       q1      1
2 Country 2    bank 2       q1      1
3 Country 3    bank 3       q1      2
4 Country 1    bank 1       q2      1
5 Country 2    bank 2       q2      2
6 Country 3    bank 3       q2      3

It essentially this dataframe it shows that there two different questions - q1,q2, where the participants - here banks coming from different countries - have to respond in each question with a certain numeric scale.
My purpose is very simple. I want, for each question, to calculate and then plot the percentage of banks responded with 1, the percentage of them responded with 2, etc.
So, in our example, there are three banks. With regards to question 1, 2 of them answered 1 and one answered 2. So, I want to visualize - e.g through a bar chart - that there are 2/3 banks (i.e aprx. 67%) answered 1 and 1/3 (i.e aprx. 33% ) answered 2.  Similarly for question 2.
Not sure, whether it matters but the range of possible numeric answers might vary according to the question. That is, for q1 the available answers range from 1 to 2, but for question 2 might range from 1 - 5.
Can someone suggest how I can quickly implement this in R ?
Of course, one dirty way is to count the number of banks, count the number of "ones" in q1 (q2) and then calculate the respective fractions.  This method, however, is very time consuming and wondering whether are much better options available in R.
UPDATE
Doing all the above, I want for a couple of questions to create a bar chart that can look like this:

Where in the above example, the responses to question 8 that where equal to 1 were labeled - "My bank has being ...." and the responses that were equal to 2 with "My bank has being started ..." as the chart above shows.
Nevertheless, we can ignore the "labeling part" for the moment, as putting only 1 and 2 in the x axis will be sufficient.

A: Here's a quick answer with ggplot
library(ggplot2)

ggplot(df, aes(x=Question, fill=factor(Answer))) + geom_bar()

The output look like this:

To calculate the percentage:
library(dplyr)
library(tidyr)

(dat <- df %>% spread(Question, Answer))
    Country Institute q1 q2
1 Country 1    bank 1  1  1
2 Country 2    bank 2  1  2
3 Country 3    bank 3  2  3

dat$q1 %>% table/nrow(dat)
        1         2
0.6666667 0.3333333

dat$q2 %>% table/nrow(dat)

        1         2         3
0.3333333 0.3333333 0.3333333

Edit: Added plot to for the comment below
ggplot(df, aes(x=Answer, fill=factor(Question))) + geom_bar()

Edit: Added to address the Updated question:
df <- data.frame(answer=c(rep(1, 97), rep(2,3)))

ggplot(df, aes(x=as.factor(answer))) +
  geom_bar(aes(y=(..count..)/sum(..count..)), width=.5) +
  scale_y_continuous(labels = scales::percent) +
  geom_text(aes(y = ((..count..)/sum(..count..)), label = scales::percent((..count..)/sum(..count..))), stat = "count", vjust = -0.25) +
  labs(title = "Question 8", y = "Percent", x = "") +
  scale_x_discrete(labels=c("My bank has been using \n guarantees already for \n more than 5 years", "My bank has started to use \n guarantees in their last 5 year"))


text:
Q: Is it possible to use model's @property decorators with Model.values()? I have a model with the following fields and decorators:
class Item(models.Model):

    title = models.CharField(db_index=True, max_length=100)
    thumb = models.CharField(max_length=1000)
    vendor = models.CharField(max_length=15)
    url = models.CharField(max_length=255, unique=True)
    views = models.CharField(max_length=64)

    @property
    def parsed_thumb()
        return = self.url + "/static/" + self.thumb

which I query in a class based view with:
results = Items.objects.filter(title__icontains=query).order_by('-views')[offset:limit].values('id', 'url', 'title', 'vendor', 'thumb')

The problem is the call to values() returns db fields and, as far as I know, has no way of interacting with @property decorators that belong to the Items model.
I need the return value from parsed_thumb(). What are my options?

A: Querysets are there to interact with the database, where as properties are only accessible to model. You could annotate the property to work with the queryset using Concat, but this won't be using the property
results = Items.objects.filter(title__icontains=query).order_by('-views')
results = results.annotate(parsed_thumb=Concat('url', Value('/static/'), 'thumb'))[offset:limit].values('id', 'url', 'title', 'vendor', 'thumb', 'parsed_thumb')

A: If you have such simple method you can try to use QuerySet.extra
results = Items.objects.extra(
    select={'parsed_thumb': "url || '/static/' || thumb"}
).filter(title__icontains=query).order_by('-views')[offset:limit].values(
'id', 'url', 'title', 'vendor', 'thumb', 'parsed_thumb')


text:
Q: how can i retrieve id using this method? - codeignitor db The given syntax can insert the given values but i cannot retrieve the value with method. do anyone knoe how can i do that?
$supplier = array(
            'cname' => $request->getPost('cname'),
            'clname'  => $request->getPost('clname'),
            'tlidt'  => $request->getPost('tlidt'),
            'tledt'  => $request->getPost('tledt'),
            'pname'  => $request->getPost('pname'),
            'tla'  => $request->getPost('tla'),
        );
        $builder = $db->table('suppliers');
        $builder->insert($supplier);
        $id = $this->$db->insert_id();

A: Try inserting like that
$this->db->insert('suppliers',$supplier);
$id = $this->db->insert_id();
or try removing $ sign from your last line 'db'.


text:
Q: Find files with regex and their respective directory I'm working on the 'C:\Documents' directory.
It has many subdirectories and I need to find all the files that their filename starts with 'A0' prefix and ends with '.xls' extension. For example, 'A0SSS.xls' or 'A0ASDF.xls'
Is it possible to fetch all those files and get their directory?
For instace, if the file 'A0SSS.xls' is located on 'C:\Documents\Folder1', I need to know the file name (A0SSS.xls) along with their respective directory (C:\Documents\Folder1).

A: To find the path of the matching files, you  run a recursive search with a filter. I recommend for you to use pathlib, so you can easily get the parent folder for each of them. The list of parent folders can be redundant, if you have got multiple matching files in the same folder. There are many ways to make a list unique in python. One of them is to convert the list to set, which must be unique by definition, and convert it back to list.
from pathlib import Path

search_path = Path("C:\Documents")
results = list(search_path.rglob("A0*.xlsx"))
string_results = [str(matching_path) for matching_path in results]
containing_folders = [r.parent for r in results]
unique_folders = list(set(containing_folders))

print("matching files:")
for r in string_results:
    print(r)
print()
print("containing folders:")
for f in unique_folders:
    print(f)


text:
Q: Adding vertical text into existing pdf I am trying to modify an existing pdf, adding datas into it using FPDI and FPDF. So far everything is fine. The only thing I am stuck at is inserting vertical text into the pdf.
Tried searching online, but non of the codes really worked.
if($x==-1)
    $x=$this->x;
if($y==-1)
    $y=$this->y;
if($this->angle!=0)
    $this->_out('Q');
$this->angle=$angle;
if($angle!=0)

{
    $angle*=M_PI/180;
    $c=cos($angle);
    $s=sin($angle);
    $cx=$x*$this->k;
    $cy=($this->h-$y)*$this->k;

I tried this, but this doesnt work together with FPDI, i.e I can generate new pdfs with verical or angled texts. But what I am trying to do is to insert vertical text into the already exisitng pdf. Unfortunately, FPDF doesnt allow to set source file. FPDI does, but this code isnt working together with FPDI somehow.

A: The quoted code is extracted from this extension. The extension will work with FPDI as with FPDF by changing its extending class name as described here.
So the extension class definition will become e.g.:
class PDF_Rotate extends FPDI
{
    ...
}

And you can still use the methods of FPDI:
$pdf = new PDF_Rotate();
$pdf->AddPage();
$pageCount = $pdf->setSourceFile("template.pdf");
$tplIdx = $pdf->importPage(1);
$pdf->useTemplate($tplIdx);
$pdf->Rotate(100, 60, 90);
$pdf->Text(100, 60, 'Hello!');
$pdf->Rotate(0);
$pdf->Output();


text:
Q: Final output on slave pty is lost if it was not closed in parent. Why? I wrote and maintain a program rlwrap that uses a pseudo-terminal to communicate with a child process.  Pseudo-terminals (ptys) are found in all Unix(-like) systems, but they behave slightly differently on different platforms.
Case in point: In rlwrap, the parent process keeps the slave pty open to keep tabs on the child's terminal settings (on Linux and FreeBSD one can use the master for that, but not in Solaris, for example)
On FreeBSD (8.2) (but not Linux) this leads to the loss of the child's final output. For example:
#include <stdio.h>

/* save as test.c and compile with gcc -o test test.c -lutil */

#define BUFSIZE 255

int main(void) {
  int master, slave;
  char buf[BUFSIZE];
  int nread;

  openpty(&master, &slave, NULL, NULL, NULL);

  if (fork()) {       /* parent:                                                      */
    close(slave);     /* leave this out and lose slave's final words ... WHY?         */
    do {
      nread = read(master, buf, BUFSIZE);
      write(STDOUT_FILENO, buf, nread); /* echo child's output to stdout              */
    } while (nread > 0);
  } else {             /* child:                                                      */
    login_tty(slave);  /* this makes child a session leader and slave a controlling   */
                       /* terminal for it, then dup()s std{in,out,err} to slave       */
    printf("Feeling OK :-)\n");
    sleep(1);
    printf("Feeling unwell ... Arghhh!\n"); /* this line may get lost                 */
  }
  return 0;
}

The parent process will echo the child's output, as expected, but when I omit the close(slave) (keeping it open like in rlwrap):

*

*on FreeBSD, the parent doesn't see the final output line, it reads an EOF instead. (If anything, I would have expected the opposite - that keeping the slave end open would prevent the output from being lost)

*On Linux, on the other hand, an EOF is never seen, not even after the child has died (whether we close the slave or not)

Is this behaviour documented somewhere? Is there a rationale for it? Can I circumvent it without closing the slave in the parent process?
I found out that not making the slave a controlling terminal - replacing the login_tty call with a few simple dup() calls - will cure the problem. This is no solution for rlwrap however: quite a few commands need a controlling terminal (/dev/tty) to talk to, so rlwrap has to provide one for them.

A: I think there is unique separate behaviour for the Pty.

*

*The system terminates if the last data is written

*The system terminates if the child exits (broken pipe?)

The code relies on the pipe existing long enough to send the data through, but the child exiting may cause the virtual channel to be deleted before the data is received.
This would be unique to Pty, and not exist for real terminal.

A: On FreeBSD 10-STABLE I do get both output lines.
(You can replace openpty and fork with forkpty which basically takes care of login_tty as well.)
In FreeBSD 8.0, the old pty(4) driver was replaced by pts(4).
The new pty(4) behaves differently from the old one. From the manual;

Unlike previous implementations, the master and slave device nodes are destroyed when the PTY becomes unused.  A call to stat(2) on a nonexistent master device   will already cause a new master device node to be created.  The master device can only be destroyed by opening and closing it.

There might well have been significant changes between 8.0-RELEASE and 10.0-RELEASE
You also might want to look at the patch that is applied in the FreeBSD ports tree.

A: printf does buffered output depending of the class of output device.  Just try to put fflush(stdout); after the last printf to see if it's a problem with buffered output.

A: here is what I found on ubuntu linux
    Note: always check for errors
#include <stdio.h>
#include <stdlib.h>
#include <pty.h>    // openpty(),
#include <utmp.h>   // login_tty()
#include <unistd.h> // read(), write()

/* save as test.c and compile with gcc -o test test.c -lutil */

#define BUFSIZE (255)

int main(void)
{
    int master, slave;
    char buf[BUFSIZE];
    int nread;
    pid_t pid;

    if( -1 == openpty(&master, &slave, NULL, NULL, NULL) )
    { // then openpty failed
        perror( "openpty failed" );
        exit( EXIT_FAILURE );
    }

    // implied else, openpty successful

    pid = fork();
    if( -1 == pid )
    { // then fork failed
        perror( "fork failed" );
        exit( EXIT_FAILURE );
    }

    // implied else, fork successful

    if( pid )
    {    /* parent:                                                      */
        close(slave);     /* leave this out and lose slave's final words ... WHY?         */
        do
        {
            if( -1 == (nread = read(master, buf, BUFSIZE) ) )
            {// then, error occurred
                perror( "read failed" );
                exit( EXIT_FAILURE );
            }

            // implied else, read successful

            if ( nread )
            {
                write(STDOUT_FILENO, buf, nread); /* echo child's output to stdout  */
            }
        } while (nread);    /* nread == 0 indicates EOF */
    }

    else // pid == 0
    {    /* child:                                                      */
        if( -1 == login_tty(slave) )  /* this makes child a session leader and slave a controlling   */
                       /* terminal for it, then dup()s std{in,out,err} to slave       */
        { // then login_tty failed
            perror( "login_tty failed" );
            exit( EXIT_FAILURE );
        }

        // implied else, login_tty successful

        printf("Feeling OK :-)\n");
        sleep(1);
        printf("Feeling unwell ... Arghhh!\n"); /* this line may get lost */
    } // end if

    return 0;
} // end function: main

when the close() statement is commented out
then the parent never exits due to the read() statement blocking
when the close() statement is part of the source
then the parent exits with a read error from trying to read from a terminal that is 'missing' when the child exits
here is the output when close() commentedpout
Feeling OK :-)
Feeling unwell ... Arghhh!

then the parent hangs on the read() statement

here is the output when close() is not commented out
Feeling OK :-)
Feeling unwell ... Arghhh!
read failed: Input/output error

A: I'm not sure if I get this right:
independent from pty or not, as long as one process has the channel open, the OS should not pass an EOF to the reader (because there is still a writer). (after the fork there are two open channels)  only if you close the parent, a close on the slave should forward the EOF.
On a PTY, are you sure that NL's are handled correctly, since normally a CR should trigger the new-line.
(just a thought:
if it is a controling tty, things might change since the OS handles singal deliveries differently and closing the chanel would normaly terminate all children processes of the child. Could this be an issue if the parent still has the handle open? )


text:
Q: how to handle element.all(locator).each(eachFunction) in chai as promised I am using Protractor, Cucumber, and Chai-As-Promise
I try to test a search field, and verify the each search result contains the search input value.  My prototype works great when Chai and Chai-As-Promised are used.
Here is the test case:  user inputs "fruit", a list of items will be returned: Apple Fruit, Orange Fruit, Pear Fruit.
I have something like below:
// in object file
...
   searchResultField: {
    get: function () {
        return element.all(by.repeater('result in Fruit'))
    }
},

...
//  in step file
this.Then(/^display all search result$/, function(callback) {
    Page.searchResultField.each(function(element){
        element.getText().then(function(value) {
            expect(promise.fulfilled(value.indexOf('Fruit') >-1)).to.eventually.be.true.and.notify(callback);

        });
    });
});

"error_message": "ReferenceError: promise is not defined
1) Everything shows as [object object] in console log.
2) without chai as promised, the Each, and "toContain" or IndexOf work like a charm, and very straight forward.  With Chai and Chai-As-Promised, I am not able to get the Each method work, nor able to "loop" the Fruit list and "expect" each of item.  (Note: the "expect" is declared chai.expect.
This is different than the other similar posting:How do I handle an array of promises using Protractor w/ chai-as-promised
Because the other posting know how many items in the array, and has fixed value.  In my case, I won't know the number of entries in my array.
In addition, how can I convert a promised to a readable format: For example, I need to know the value of the
Page.searchResultField.count()

But I can only get the object value.


text:
Q: Intel MSR frequency scaling per - thread I'm extending the Linux kernel in order to control the frequency of some threads: when they are scheduled onto a core (any core!), the core's frequency is changed by writing the proper p-state to the register IA32_PERF_CTL, as suggested in Intel's manual.
But when different threads with different "custom" frequencies are scheduled, it appears that the throughput of all the thread increases, as if all the cores run at the maximum set frequency.
I did many trials and measurements in different conditions of load and configuration, but the result is the same.
After some trials with CPUFreq (with no running app, I set different frequencies on each core, and finally the measured frequencies, with cpufreq-info -w, were equal), I wonder if the CPU cores can really run at different, independent frequencies, or if there are hardware policies or constraints.
Finally, is there a CPU model which makes this fine-grained frequency scaling feasible?
The CPU I am using is Intel Core i5 750

A: You cannot control individual core frequencies for active cores. You can, however, control frequencies of all active cores to be the same. The reasons are in the previous answers - all cores are on the same active voltage plane.
Hopefully, the next-gen Haswell processors will make it possible to control each core separately.

A: I think you're missing a big piece of the picture!
Read up on power and clocks domains. All processor cores within a domain run at the same P-state (i.e., the same frequency and voltage). The P-state that all cores will run at in that domain will always be the P-state of the core requesting the highest P-state in that domain. The MSRs don't reflect this at all, nor do the interfaces that the kernel exposes.
Anandtech has a good article on this:
http://www.anandtech.com/show/2658/2
"This is all very similar to AMD's Phenom, but where the two differ is in how they handle power management. While AMD will allow individual cores to request different clock speeds, Nehalem attempts to run all of its cores at the same frequency; if one core is idle then it's simply power gated and the core is effectively turned off."
I haven't hooked a power-meter up to SB/IB, but my guess is that the behavior is the same.

A: cpufreq-info will display information about which cores need to be synchronous in their P-states:
[root@navi ~]# cpufreq-info
cpufrequtils 008: cpufreq-info (C) Dominik Brodowski 2004-2009
Report errors and bugs to cpufreq@vger.kernel.org, please.
analyzing CPU 0:
  driver: acpi-cpufreq
  CPUs which run at the same hardware frequency: 0 1 <---- THIS
  CPUs which need to have their frequency coordinated by software: 0 <--- and THIS
  maximum transition latency: 10.0 us.

At least because of that, I'd recommend going through cpufreq interfaces instead of directly setting registers, as well as making it possible to run on non-intel CPUs which might have uncommon requirements.
Also check on how to make kernel threads stick to specific core, to avoid unexpecteded switching, if you didn't do so already.

A: I want to thank everyone for the contribution!
Further investigating, I found other details I share with the community.
As suggested, Nehalem places all the cores in a single clock domain, so that the maximum frequency set among all the cores is applied to all of them; some tools may show different frequencies on idle cores, but it is sufficient to run any application to make the frequency raise to the maximum.
This, from my tests, also applies to Sandy Bridge, where cores and LLC slices all reside in the same frequency/voltage domain.
I assume that this behavior also happens with Ivy Bridge, as it is only a 'tick' iteration.
Instead, I believe that Haswell places cores and LLC slices in different, singular domains, thus enabling per-core frequencies. This is also advertized in several pages like
http://www.anandtech.com/show/8423/intel-xeon-e5-version-3-up-to-18-haswell-ep-cores-/4