text:
Q: What is an example of JSF "No Query Data" short-circuit from Restore View to Render Response Core JavaServer Faces Third Edition mentions a case where JSF can go from the Restore View phase directly to the Render Response Phase. What is a real-world example of this?

A: That will happen when there's no means of a postback request (i.e. it's a plain GET request) and the targeted view doesn't contain any view parameters (i.e. there are no <f:viewParam> tags in the view). There's then simply nothing to process on apply request values phase (collect request parameters), validations phase (convert/validate them), update model values phase (set bean properties) and invoke action phase (invoke bean action method). JSF will then just bypass all those phases.
The real world exampe is, well, just a plain GET request without view params like as when you open the page directly by following a link or bookmark or by entering its URL in browser address bar, where the targeted view doesn't have any <f:viewParam>.


text:
Q: how to retrieve data from MySQL using javascript I have a web page coded in PHP. This page is for posting a request for services. All services are stored in two separate tables along with prices.
As the user selects various services I want to fetch prices for the selected service and show it on per service basis and also a grand total of all services.
How can we do this?

A: Rather than a database query for every service they tick, you could add all the variables into the page as hidden vairables, then use Javascript to add them up.  This would be much less overhead.

A: I'm not totally sure what you're going for, but you can't actually fetch anything from MySQL with Javascript, but you can request a php script via xhr that will fetch the data, and then deal with it (add it up, etc.) via javascript.
If the number of services/prices isn't huge, you could load it all in to the page in the first place then use javascript to add things up and leave the server alone.
There are several javascript frameworks and libraries that make this sort of thing quite easy (xhr), have you looked into those?
http://mootools.net
http://dojotoolkit.com
http://jquery.com
http://www.prototypejs.org

A: If your data is too complex to pre-load as ck suggested, you can create a PHP page that generates JSON as your output.  Using a library like jQuery you could then pull that data into the page for handling.

A: Ajax a php page that will do the MySQL operations. Make sure to actually secure that stuff, escape the strings, and make sure to check if the command being sent is the one you actually want. Some users are smarter than the rest and may go 'Drop *' using your ajax method.
Not a very safe idea IMO, but if something use Ajax.

A: Don't pre-load the prices on the page; use AJAX to retrieve them. You might be making some assumptions that are not necessarily true when the page loads, and in some cases, you might want to manipulate the prices, based on the data supplied by the user. In any case, you are more likely to use AJAX later on.
Querying the database via AJAX is not difficult to implement, it makes your code more flexible, and it's very reliably fast.
Go for AJAX.

redpajama_set_name: RedPajamaStackExchange


text:
Q: ¿Porqué no me permite publicar un @types npm? Estoy tratando de crear un @types para otro npm que me gusta mucho fmt

{
  "name": "@types/fmt",
  "version": "1.0.0",
  "description": "",
  "main": "",
  "types": "./index.d.ts",
  "deprecated": false,
  "scripts": {},
  "repository": {
    "type": "git",
    "url": "git+https://github.com/PadRocha/-types-fmt.git"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/PadRocha/-types-fmt/issues"
  },
  "homepage": "https://github.com/PadRocha/-types-fmt#readme"
}

Este es el package.json
ingresé a mi usuario de npm correctamente
El error que regresa es el siguiente
npm ERR! code E403
npm ERR! 403 403 Forbidden - PUT https://registry.npmjs.org/@types%2ffmt - Forbidden
npm ERR! 403 In most cases, you or one of your dependencies are requesting
npm ERR! 403 a package version that is forbidden by your security policy.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\proch\AppData\Roaming\npm-cache\_logs\2020-11-21T23_02_32_967Z-debug.log

Cuando intento guardar un npm sin @types me lo permite pero con el mismo siempre me provoca el mismo error :(
Pensé que ya lo habrían creado pero cuando lo buscan @types/fmt te muestra como que no existe

A: Parece ser que estás un poco confundido sobre como las declaraciones de tipos son publicadas. Dentro de la documentación de TypeScript encontrarás información sobre cómo es posible obtener dichas declaraciones, en concreto nos interesa el apartado que habla sobre DefinitelyTyped/@types:

Definitions on DefinitelyTyped are also automatically published to npm under the @types scope.

DefinitelyTyped es un repositorio centralizado en el que se publican las declaraciones para miles de librerías que no cuentan con las mismas -declaraciones- por defecto (sucede mucho con paquetes que han sido escritos en JavaScript y no en TypeScript). La cita dice básicamente que toda aquella definición publicada dentro de ese repositorio estará disponible en el scope @types. Por lo que si quieres que las definiciones esten bajo ese scope, deberías leer cómo contribuir a ese repositorio para añadir nuevas definiciones.
Es por eso que al querer publicar en NPM obtienes un error 403

[...] una petición que resulta en un error 403 debería no ser repetida, y utilizar otra autorización no ayudará a que la petición se vuelva válida.

por lo que aunque brindes tus credenciales de accesso, el scope @types está "protegido" y solo es accesible con un PR satisfactorio a DefinitelyTyped.


text:
Q: Way to use maxgap in na.locf for xts timeseries in R? na.locf(xts_ts, maxgap=240) doesn't seem to respect maxgap for xts timeseries. I think that for xts timeseries na.locf.xts is invoked (which doesn't document maxgap), and not na.locf which is from zoo.
Am I doing something wrong?
Should I convert the xts ts to a zoo ts, then call na.locf with maxgap and the convert back to xts?

A: maxgap is included in na.locf.xts on R-forge as of revision 553.  Use install.packages("xts", repos="http://R-Forge.R-project.org") to get the latest revision from R-forge.


text:
Q: Closure contained in open set of $\mathbb R^n$ I am currently reading a proof of the Hyperplane separation theorem. It uses the following:
If $X\subseteq\mathbb R^n$ is a  convex set containing $0$, and  $\alpha\in (0,1)$, then the closure of $\alpha X:=\{\alpha x\mid x\in X\}$ is contained in $X$.
This seems highly intuitive. However, I am unable to verify it formally. Any hint on how it can be proven?

A: I don't think this is true without further conditions on $X$. Suppose:
$$X = \big\{(x,y) \in \mathbb{R}^2 : y > 0\big\} \cup \{(0,0)\},$$
i.e. that $X$ consists of everything strictly above the $x$-axis in the plane, union the origin.  $X$ is convex, but for any $\alpha > 0$ the closure of $\alpha X$ is everything weakly above the $x$-axis, which is not contained in $X$.


text:
Q: Encrypting/Decrypting JWE with Jose in Go I'm trying to create a JWE decryption function but having trouble determining how to use the Go Jose interface for doing so. I've factored the encryption using passphrase (I prefer a passphrase for this use case):
    token := jwt.NewWithClaims(
        jwt.SigningMethodHS256,
        claims,
    )
    ss, err := token.SignedString("thisisatestpassphraserighthere")
    if err != nil {
        panic("COULD_NOT_GENERATE")
        return
    }
    privateKey, err := rsa.GenerateKey(rand.Reader, 2048)
    if err != nil {
        panic(err)
    }
    publicKey := &privateKey.PublicKey
    encrypter, err := jose.NewEncrypter(
        jose.A128CBC_HS256,
        jose.Recipient{Algorithm: jose.RSA_OAEP, Key: publicKey},
        nil,
    )
    if err != nil {
        return
    }
    object, err := encrypter.Encrypt([]byte(ss))
    if err != nil {
        errRes = s.Error(codes.Internal, err, nil)
        return
    }
    key, err := object.CompactSerialize()
    if err != nil {
        errRes = s.Error(codes.Internal, err, nil)
        return
    }
    fmt.Println(key)

The above code creates a JWT, encodes it, compacts it and returns the key. It's not however totally clear how to decrypt it with the passphrase now.
There is an example for JWE on the Jose docs: https://godoc.org/gopkg.in/square/go-jose.v2#example-Encrypter--Encrypt
So I've factored this:
    object, err = jose.ParseEncrypted(Key)
    if err != nil {
        panic(err)
    }
    decrypted, err := object.Decrypt(...)

Inside the ellipses I'm not sure what to put though. I can't seem to determine how to pass in a key based on passphrase.

A: I was doing a few things wrong it seems. First of all rsa.GenerateKey uses a randomized value. This was totally wrong :-p the following is how you can encrypt a JWT into a JWE using a token:
rcpt := jose.Recipient{
    Algorithm:  jose.PBES2_HS256_A128KW,
    Key:        "mypassphrase",
    PBES2Count: 4096,
    PBES2Salt: []byte{ your salt... },
}
enc, err := jose.NewEncrypter(jose.A128CBC_HS256, rcpt, nil)
if err != nil {
   panic("oops")
}
jewPlaintextToken, err := enc.Encrypt(jwtToken)
if err != nil {
    panic("oops")
}
key, err := object.CompactSerialize()
if err != nil {
    panic("oops")
}

This is how you decrypt:
// Decrypt the receive key
jwe, err := jose.ParseEncrypted(jewPlaintextToken)
if err != nil {
    panic("oops")
}
decryptedKey, err := jwe.Decrypt("mypassphrase")
if err != nil {
    panic("oops")
}

If anyone sees any major problems/security issues with this method, please mention it.

A:
Inside the ellipses I'm not sure what to put though. I can't seem to determine how to pass in a key based on passphrase.

From the JWE example in the documentation, you must pass the private key. See the below part for decryption
https://godoc.org/gopkg.in/square/go-jose.v2#JSONWebEncryption.Decrypt
// Generate a public/private key pair to use for this example.
privateKey, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
    panic(err)
}

// Parse the serialized, encrypted JWE object. An error would indicate that
// the given input did not represent a valid message.
object, err = ParseEncrypted(serialized)
if err != nil {
    panic(err)
}

// Now we can decrypt and get back our original plaintext. An error here
// would indicate the the message failed to decrypt, e.g. because the auth
// tag was broken or the message was tampered with.
decrypted, err := object.Decrypt(privateKey)
if err != nil {
    panic(err)
}

fmt.Printf(string(decrypted))


text:
Q: AWS EC2 Could not open a connection to SQL Server My web application on EC2 is not able to connect to AWS RDS Db instance.
error: SqlException (0x80131904): A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)

Win32Exception (0x80004005): The network path was not found

I have hosted a web application on EC2.
Usin my local SSMS, I am able to connect and edit data on the AWS RDS.
on my local machine, I also pointed my Visual Studio application to the AWS RDS instance and it worked just fine.
Now, when I deployed my application to EC2, the application is not able to connect to the AWS RDS.
Using the AWS Toolkit for net, I have added permissions to the DB Security groups and granted rights to the EC2 Ip address and Private Ip as well. But no luck.
Please help......

A: Check the region you are connecting to.
I had initially created, the database in west region. And my local was continuing to connect to west region.
And when I gave all necessary permissions, I gave it to the database in east region. and my code application was still pointing to the west region. duh me.


text:
Q: mod_perl debugging & user-code-lines are not shown I'm playing around Apache::DB to debug my code under mod_perl.
I can have it running and see the variables, but I cannot see
the line of code with the instruction that is going to be executed
(even if the file pathname and line number printed apart seem right).
This happens only for my code, as all the mod_perl handlers are
managed correctly.
It should be the same problem
stackoverflow.com/questions/7584931/mod-perl-debugging-viewing-source
but as it was not solved I open it again, adding more data.
I have cut the problem a piece at a time, and now I have the most simple
configuration which can still reproduce the problem.
I reduced the httpd.conf file to only 35 lines
(45 are just LoadModule directives) preserving the test case.
The servers I must work on have the below versions for
APACHE/MOD_PERL/PERL.
I guess Apache::DB can do what I cannot grab it out,
but I've no clear idea on what is the missing step.
Thank you for any help.
______________________________________ DUMMY SCRIPT TO DEBUG
#!/usr/bin/perl
my $a=2;
print "Content-type: text/plain\n\n";
print "$a, $ENV{MOD_PERL}\n";
______________________________________ APACHE version

>httpd -v
Server version: Apache/2.2.8 (Unix)
Server built:   Feb 26 2009 22:38:17
______________________________________ MOD_PERL version

MOD_PERL => mod_perl/2.0.2
______________________________________ PERL version

>perl -v
This is perl, v5.8.5 built for i386-linux-thread-multi

execute Apache without forking
/usr/sbin/httpd  -X -DPERLDB -f /home/stef/simple.httpd.conf

simple.httpd.conf:
1 ServerRoot "/etc/httpd"
2 PidFile /tmp/stef.pid
3 Listen 192.168.60.201:4012
4 LoadModule access_module modules/mod_access.so
5 LoadModule auth_module modules/mod_auth.so
6 LoadModule auth_anon_module modules/mod_auth_anon.so
7 LoadModule auth_dbm_module modules/mod_auth_dbm.so
8 LoadModule auth_digest_module modules/mod_auth_digest.so
9 LoadModule ldap_module modules/mod_ldap.so
10 LoadModule auth_ldap_module modules/mod_auth_ldap.so
11 LoadModule include_module modules/mod_include.so
12 LoadModule log_config_module modules/mod_log_config.so
13 LoadModule env_module modules/mod_env.so
14 LoadModule mime_magic_module modules/mod_mime_magic.so
15 LoadModule cern_meta_module modules/mod_cern_meta.so
16 LoadModule expires_module modules/mod_expires.so
17 LoadModule deflate_module modules/mod_deflate.so
18 LoadModule headers_module modules/mod_headers.so
19 LoadModule usertrack_module modules/mod_usertrack.so
20 LoadModule setenvif_module modules/mod_setenvif.so
21 LoadModule mime_module modules/mod_mime.so
22 LoadModule dav_module modules/mod_dav.so
23 LoadModule status_module modules/mod_status.so
24 LoadModule autoindex_module modules/mod_autoindex.so
25 LoadModule asis_module modules/mod_asis.so
26 LoadModule info_module modules/mod_info.so
27 LoadModule dav_fs_module modules/mod_dav_fs.so
28 LoadModule vhost_alias_module modules/mod_vhost_alias.so
29 LoadModule negotiation_module modules/mod_negotiation.so
30 LoadModule dir_module modules/mod_dir.so
31 LoadModule imap_module modules/mod_imap.so
32 LoadModule actions_module modules/mod_actions.so
33 LoadModule speling_module modules/mod_speling.so
34 LoadModule userdir_module modules/mod_userdir.so
35 LoadModule alias_module modules/mod_alias.so
36 LoadModule rewrite_module modules/mod_rewrite.so
37 LoadModule proxy_module modules/mod_proxy.so
38 LoadModule proxy_ftp_module modules/mod_proxy_ftp.so
39 LoadModule proxy_http_module modules/mod_proxy_http.so
40 LoadModule proxy_connect_module modules/mod_proxy_connect.so
41 LoadModule cache_module modules/mod_cache.so
42 LoadModule suexec_module modules/mod_suexec.so
43 LoadModule disk_cache_module modules/mod_disk_cache.so
44 LoadModule file_cache_module modules/mod_file_cache.so
45 LoadModule mem_cache_module modules/mod_mem_cache.so
46 LoadModule cgi_module modules/mod_cgi.so
47 LoadModule apreq_module modules/mod_apreq2.so
48 LoadModule perl_module modules/mod_perl.so
49 <VirtualHost *:4012>
50   DocumentRoot /home/stef/TEST/
51   <IfDefine PERLDB>
52     <Perl>
53         #!/usr/bin/perl
54         use APR::Pool ();
55         use Apache::DB ();
56         Apache::DB->init();
57         __END__
58     </Perl>
59   </IfDefine>
60   <Directory "/home/stef/TEST/APACHE/code">
61        Options FollowSymLinks +ExecCGI Indexes
62        SetHandler perl-script
63        PerlHandler ModPerl::PerlRun
64        PerlSendHeader On
65        PerlSetupEnv On
66          <IfDefine PERLDB>
67                  PerlFixupHandler Apache::DB
68          </IfDefine>
69     Order allow,deny
70     Allow from all
71   </Directory>
72 </VirtualHost>
73 User stef
74 Group devel
75 ServerName ik2ss10.internal:4012
76 TypesConfig /etc/mime.types
77 ErrorLog /var/log/httpd/stef_error_log
78 LogLevel warn
79 CustomLog /var/log/httpd/stef_access_log combined
80 NameVirtualHost *:4012

______________________________________ DEBUGGER SESSION
DB<4>
ModPerl::RegistryCooker::run(/usr/lib/perl5/vendor_perl/5.8.5/i386-linux-thread-multi/ModPerl/RegistryCooker.pm:203):
203:            eval { $cv->($r, @_) };
DB<4> s
ModPerl::RegistryCooker::run(/usr/lib/perl5/vendor_perl/5.8.5/i386-linux-thread-multi/ModPerl/RegistryCooker.pm:203):
203:            eval { $cv->($r, @_) };
DB<4>
ModPerl::ROOT::ModPerl::PerlRun::home_stef_TEST_APACHE_code_test_2epl::handler((eval 29)[/usr/lib/perl5/vendor_perl/5.8.5/i386-linux-thread-multi/ModPerl/RegistryCooker.pm:676]:1):
1:      package ModPerl::ROOT::ModPerl::PerlRun::home_stef_TEST_APACHE_code_test_2epl;sub handler {local $0 = '/home/stef/TEST/APACHE/code/test.pl';
DB<4> l
1==>    package ModPerl::ROOT::ModPerl::PerlRun::home_stef_TEST_APACHE_code_test_2epl;sub handler {local $0 = '/home/stef/TEST/APACHE/code/test.pl';
2       #line 1 /home/stef/TEST/APACHE/code/test.pl
3       #!/usr/bin/perl
4       my $a=2;
5       print "Content-type: text/plain\n\n";
6       print "$a, $ENV{MOD_PERL}\n";
7
8       }
9       ;
DB<4> n
ModPerl::ROOT::ModPerl::PerlRun::home_stef_TEST_APACHE_code_test_2epl::handler(/home/stef/TEST/APACHE/code/test.pl:2):
2:
DB<4> n
ModPerl::ROOT::ModPerl::PerlRun::home_stef_TEST_APACHE_code_test_2epl::handler(/home/stef/TEST/APACHE/code/test.pl:3):
3:
DB<4> p $a
2
DB<5> p $ENV{MOD_PERL}
mod_perl/2.0.2
DB<6> n
ModPerl::ROOT::ModPerl::PerlRun::home_stef_TEST_APACHE_code_test_2epl::handler(/home/stef/TEST/APACHE/code/test.pl:4):
4:
DB<6> n
ModPerl::RegistryCooker::run(/usr/lib/perl5/vendor_perl/5.8.5/i386-linux-thread-multi/ModPerl/RegistryCooker.pm:206):
206:            $rc = $self->error_check;


text:
Q: Asp.Net Mvc 3, jQuery, cross-domain I have a site "A" and to test cross site posts from site "B" using jQuery I've added this in Global.asax Application_BeginRequest
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "X-Requested-With");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "POST");

The post from site "B" looks like this:
$.ajax({
    type: 'POST',
    url: rootUrl,
    crossDomain: true,
    data: request.toPostData(),
    dataType: 'json',
    success: onsuccess,
    error: onerror
});

My problem now is that it lets through two requests to the controller action. One with formvalues and one without.
Of course I only want the last one, which holds the values. I hope anyone could explain and point me to a solution.

A: to go across domains, you need to use something like jsonp  http://en.wikipedia.org/wiki/JSONP

A: use dataType:'jsonp' and append your url with '&callback=?'
$.ajax({
    type: 'POST',
    dataType:'jsonp',
    url: rootUrl,
    crossDomain: true,
    data: request.toPostData(),
    success: onsuccess,
    error: onerror
});

for more reference http://www.ibm.com/developerworks/library/wa-aj-jsonp1/


text:
Q: How to switch between nautilus window and (gnome-)terminal I need a fast possibility to switch between a nautilus window and a (gnome-terminal) in the same working directory.
At the moment I'm using the following setup:
nautilus -> terminal: nautilus-open-terminal (rightclick > open terminal here) & close nautilus window manually
terminal -> nautilus: alias explorer="nautilus $(pwd) && exit"
My problem is, that on the one hand [nautilus -> terminal] takes some time (rightclick..manual close..): I'd like to have a hotkey or something more direct for this operation. And on the other hand [terminal -> nautilus] does only work when there is already a nautilus instance running somewhere, otherwise the terminal blocks running nautilus and doesn't close itself.
As I'm using a tiling window manager (XMonad) I don't want both windows to be running at the same time.
Any Ideas?


text:
Q: Add and remove classes when click on multiple divs using jquery I'm trying to style a menu I built and I add a different class on each div element every time someone clicks on them. How can I remove the already added class from this element when I click anyone of the other 3 divs?

$('.fashion-btn').click(function() {
  $(this).addClass("active-btn-red");
});

$('.garden-btn').click(function() {
  $(this).addClass("active-btn-pink");
});

$('.technology-btn').click(function() {
  $(this).addClass("active-btn-purple");
});

$('.auto-btn').click(function() {
  $(this).addClass("active-btn-deep-purple");
});
.categories-sidebar-popup-menu-row {
  padding: 10px 15px;
  cursor: pointer;
  display: block;
  position: relative;
  margin-left: 20px;
  margin-right: 20px;
  border-radius: 28px;
  margin-bottom: 10px;
  font-weight: 500;
  font-size: 16px;
  letter-spacing: -0.5px;
  color: #555B66;
}

.active-btn-red {
  background: #E53935;
  color: #fff!important;
}

.active-btn-pink {
  background: #D81B60;
  color: #fff!important;
}

.active-btn-purple {
  background: #8E24AA;
  color: #fff!important;
}

.active-btn-deep-purple {
  background: #5E35B1;
  color: #fff!important;
}

FASHION

GARDEN

TECHNOLOGY

AUTO

I know that i could do something like that for each one of them:
$('.fashion-btn').click(function() {
  $(this).addClass("active-btn-red");
  $('.garden-btn').removeClass("active-btn-pink");
  $('.technology-btn').removeClass("active-btn-purple");
  $('.auto-btn').removeClass("active-btn-deep-purple");
});

But as I will add more than 20 elements in my menu, I would like to ask if there any smarter/shorter way to make this work.

A: As @disinfor said in the comments, you could do something like this:

FASHION

GARDEN

TECHNOLOGY

AUTO

.categories-sidebar-popup-menu-row {
    padding: 10px 15px;
    cursor: pointer;
    display: block;
    position: relative;
    margin-left: 20px;
    margin-right: 20px;
    border-radius: 28px;
    margin-bottom: 10px;
    font-weight: 500;
    font-size: 16px;
    letter-spacing: -0.5px;
    color:#555B66;
}

.fashion-btn.active {
   background:#E53935;color:#fff!important;
}

.garden-btn.active {
  background:#D81B60;color:#fff!important;
}

.technology-btn.active {
  background:#8E24AA;color:#fff!important;
}

.auto-btn.active {
  background:#5E35B1;color:#fff!important;
}

$(".categories-sidebar-popup-menu-row" ).each(function (){
  $(this).click(function(){
    clearStyle();
    $(this).addClass("active");
  });
});

function clearStyle(){
  buttonWithActive = $('.categories-sidebar-popup-menu-row.active');
  buttonWithActive.removeClass('active');
}


text:
Q: Differences between "consult" and "counsel" Why are organizations that provide psychological help called "counselling services", while those that provide legal, medical, or financial services called "consulting services"?
Is "A consults B" equal to "B counsels A"?

A: The various forms of consult and counsel are derived via French from Latin consulo (consulere, consului, consultum). This word in itself carries conflicting meanings— asking for advice, receiving it, reflecting on it— and so it should be no surprise that the English derivatives have multiple usages, some of which are antonyms but others which are not.
In particular, the noun forms counselling and consulting refer to specific professional practices, beyond providing counsel or being consulted. After all, I can profess my fondness for music, but that does not make me a professor; I can account for all my golf clubs, but I am not performing accounting (or accountancy).
Counselling (BrE) / counseling (AmE) is idiomatically identified with

the provision of professional assistance and guidance in resolving personal or psychological problems

(emphasis added), perhaps because of common association. Similarly, therapy on its own will be intrepreted as psychotherapy or psychological therapy; one specifies physical therapy if undergoing an exercise regimen for muscles and joints rather than feelings and relationships.
Consulting is

the business of giving expert advice to other professionals

The "short" answer to your first question, then, is that counselling has become closely identified with advice given to individuals (whether alone or in groups) to assist with their emotional problems, whereas consulting is sought to address problems in a business or professional practice or process.
These usages color the use of counsel and consult as verbs. Generically, they mean simply to give advice and to seek advice respectively. To say she is counselling him without other context, however, will usually be interpreted as saying she is offering psychological or emotional guidance. And confusingly, especially in American usage, to consult can mean to be employed as a consultant— and thus to be giving rather than requesting advice: He consults for Accenture; She consults at the World Bank.
The noun forms counsel and consultation (sometimes abbreviated to consult) also have specific usages that can overshadow their generic ones. We can also speak of taking your mother's counsel or working in consultation with our partners. But counsel, thanks to television courtroom procedurals, can be taken as legal counsel, meaning either your lawyer or to the advice they officially provide. A consultation is the time a professional takes to evaluate your case, as when you first meet your lawyer or doctor about a particular issue: set up an appointment for your consultation.

As to your second question, yes, equal can be used as a verb, meaning either to be equal or to make equal. But unless dealing with numerical quantities, I think a native speaker would more likely ask if something is the same as another, or whether it is equivalent to or is equal to as you have done.


text:
Q: Assistance with this java method! please! darn Tables please excuse my noob, but my current level of java knowledge is quite base. I really need help with an exercise, but it is a little beyond my very basic level of Java, (i.e. I'm only confident in declaring variables lol) But here is the question word for word:

Complete a main method that will accomplish the following:
  you may assume that the class includes all appropriate set methods(also know as mutator methods) and get methods (also known as accessor methods). The output can be completed using the console output or GUI output.

*

*create a blue kitchen table with 4 legs

*create a brown dining table with 6 legs

*change the color of the kitchen table to pink

*print out the color of the dining table including text identifying which value you are printing and also the value itself.

*print out the number of tables including text identifying which value you are print and also the value its self."

So for the last two I need a
System.out.print("the color of the dining table is " + 'diningtable color')

and a
System.out.print("number of tables: " + 'numberOftables');

what's the rest? I really would appreciate help and I know that I need to practice ;)
EDIT
here is what I have now, not sure if my print line is correct:
public static void main (String[] args){
    //table 1

       table kitchenTable = new table();

       kitchenTable.setnumberOfLegs((int)4);
   kitchenTable.setcolor("blue");
    //table 2
    table DiningTable =new table();
    DiningTable.setnumberOfLegs((int)6);
    DiningTable.setcolor("brown");
 //change table 1 to pink
 kitchenTable.setcolor("pink");

 System.out.print("Dining Table Color is: " + kitchenTable.color());

  }

A: It looks like based on the sample code you've provided, you've got the right general idea with getters and setters.  Here's what I'll do: I'll provide an example using something other than a table.
public class Lamp {

    private boolean on = false;

    public Lamp(boolean isOn) {
        on = isOn;
    }

    public boolean isOn() {
        return on;
    }

    public void setOn(boolean isOn) {
        on = isOn;
    }

}

So here I have a constructor for my Lamp, and a getter and a setter for its one property, boolean on.  In order to create the Lamp with a starting state (or initialize it), I can simply call the constructor like the following:
Lamp myLamp = new Lamp(true);

Now I have a new Lamp object whose field on is set to true.
In order to manipulate the state of that variable, I can call the setter:
myLamp.setOn(false);

Now my lamp is off!
And to print out the state, I can try something like ...
System.out.println("Is the lamp on? " + myLamp.isOn());

Side comment: there's no need to cast an integer literal to an int, since it's already an int.  (In other words, no need for (int)6, since 6 is already an int.)


text:
Q: JavaScript class property inside vs outside constructor I'm struggling to understand the difference between defining a property inside vs outside the constructor. In the below example both properties are accessible on the instance in the same way, what is the difference?
class Foo {
  constructor() {
    this.bar = 1;
  }
  baz = 1;
}
const foo = new Foo();
console.log(foo.bar, foo.baz); // 1 1

A: Constructor initialisation allows for using values from the class instantiation, so they may be different for each instance, while properties defined in the class scope are global to all instances.
If you want to initialise a property with values from the instance, you need to do it in the constructor. Normally, if you want an attribute to be general to all instances, you would define it outside of the constructor, but you can also do it inside if you want.

A: They do the same thing.
Defining the property outside the constructor is new class field syntax. If you need to support older browsers, either use the constructor method, or use Babel to transpile the code first down to older syntax.
Note that class fields run before the constructor finishes - either right after the super call, if there is one, or at the very beginning of the constructor.

class Foo {
  prop = console.log('Class field running');
  constructor() {
    this.prop2 = console.log('Constructor running');
  }
}
const foo = new Foo();

Related: Private fields (also very new syntax) must be initialized outside of the constructor, so that the class can understand which fields are private at compile time:

class Foo {
  constructor() {
    this.bar = 1;
    // Not OK:
    // this.#foo = 1;
  }
  // OK:
  #baz = 1;
}
const foo = new Foo();

A: Actually, defining this.bar within the constructor is considered dirty code in ES6. You can expand any object by adding a property just the way you did. This is the way how it is done in ES5 and lower.
ES6 is mainly just syntactic sugar, meaning all you class definitions get boiled down to "native" JavaScript code. Behind the scenes, your definition of baz will end up in the transcript exactly the way you defined bar. However, for readability, the syntactic sugar was added in ES6 to define a property in a more class-like fashion.


text:
Q: can you switch over a std::any.type()? I want to explore how I can use std::any instead of void * or such constructs for message passing. So I created an example code to test this - see below.
The use of std::any looks nice, but I want to switch through the types to check which type the std::any is. It might no be possible, and I know I can use a if/elseif... block instead, but it would be very nice if I can create a switch statement so that if I use this in real code with 10-20 different types it will be more readable.
#include <string>
#include <iostream>
#include <sstream>
#include <any>
#include <typeindex>

struct ints { int a{1}; int b{2}; };
struct strings { std::string a{"string1"}; std::string b{"string2"}; };

void send_msg(std::any item)
{
    switch (item.type().hash_code())       // <------- HERE
    {
        case typeid(ints).hash_code():     // <------- HERE
            std::cout << "ints" << std::endl;
            break;
        case typeid(strings).hash_code():
            std::cout << "strings" << std::endl;
            break;
        default:
            std::cout << "unknown type\n";
    }
}

int main()
{
    strings s;
    send_msg(s);

    ints i;
    send_msg(i);
}

live example: https://godbolt.org/z/xPrMYM
I can't switch on the type_info returned by std::any::type, but I can switch on the hash_code() of the type_info, but that is not a constexpr I hoped it was though!
so I also tried getting the address of the type info and a few other tricks that I could find. But no luck so far...
Is there such a way?

A: I would also suggest a variant here if possible but for the concrete question:
If you can use boost and C++17 is your referred standard: They provide an extended typeid handling that can also be used for several compile time checks, see
https://www.boost.org/doc/libs/1_67_0/boost/type_index/ctti_type_index.hpp
Its underlying rawType is a const char* constexpr and the typeIndex itself can be used as a perfect replacement for std::type_info. Since the standard guarantees unique addresses for these type identifiers, even a simple address comparison should be possible here (not sure why this simplification is currently out commented inside the boost headers though).
To be usable with any, you might have to wrap it or to use a simple own any type.

A: What you're asking is std::visit, but with std::any
template<typename... Ts, typename F>
bool visit(F&& f, std::any x)
{
    auto result = ((x.type() == typeid(Ts) ?
        (std::forward<F>(f)(*std::any_cast<Ts>(&x)), true) : false) || ...);
    return result;
}

Since the std::any might contain anything, the visit might fail at runtime, which is why you certainly need some way to report the error†.
Use as
bool send_msg(std::any x)
{
    auto f = [](auto&& x){
        std::cout << x << '\n';
    };
    return visit<std::string, int>(f, x);
}

But then, using std::variant is just simpler
void send_msg(std::variant<std::string, int> x)
{
    auto f = [](auto&& x){
        std::cout << x << '\n';
    };
    visit(f, x);
}

†The complete visit implementation would be a bit more complicated.


text:
Q: OrderBy with a non-transitive IComparer Take a custom IComparer, that treats two doubles as equal if their difference is less than a given epsilon.
What would happen if this IComparer is used in a OrderBy().ThenBy() clause?
Specifically I am thinking of the following implementation:
public class EpsilonComparer : IComparer<double>
{
    private readonly double epsilon;

    public EpsilonComparer(double epsilon)
    {
        this.epsilon = epsilon;
    }

    public int Compare(double d1, double d2)
    {
        if (Math.Abs(d1-d2)<=epsilon) return 0;

        return d1.CompareTo(d2);
    }
}

Now this IComparer relationship is clearly not transitive. (if a ~ b  and  b ~ c then a ~ c)
With epsilon== 0.6 :

*

*Compare(1, 1.5) == 0

*Compare(1.5, 2) == 0
yet

*Compare(1, 2  ) == -1

What would happen if this IComparer was used in an OrderBy query, like this:
List<Item> itemlist;
itemList = itemlist.OrderBy(item=>item.X, new EpsilonComparer(0.352))
                   .ThenBy (item=>item.Y, new EpsilonComparer(1.743)).ToList();

Would the sort behave as one would expect, sorting the list first by X, then by Y, while treating roughly equal values as exactly equal?
Would it blow up under certain circumstances?
Or is this whole sort ill-defined?
What exactly are the consequences of using an IComparer without transitivity?
(I know that this is most likely undefined behavior of the c# language. I am still very much interested in an answer.)
And is there an alternative way to get this sorting behaviour?
(besides rounding the values, which would introduce artifacts when for two close doubles one is rounded up and the other down)
An online fidle of the code in this question is available here:

A: The problem is that the first sorting level (on X) can result in different orders already. Imagine that all items are within one epsilon of each other. Then all sort orders are consistent with your comparer because it will always return 0. The sort algorithm could flip coins and still provide a "right" answer. Not useful.
If the first level is arbitrarily sorted, you cannot expect the 2nd sorting level to work.
Of course, all of this discussion is moot because you are violating the precondition of the sorting API. Even if it happened to work, you couldn't be sure that it would work on a) all data b) on all future releases of .NET.
How can you still achieve your goal? Your problem is just ill-defined because many solutions are possible. I get what you want to achieve but it is not possible with your current definition of the problem.
I propose this: sort all items by X (without epsilon). Then, traverse the sorted items left-to-right and merge the items into groups that one epsilon wide at most. That gives you groups of items whose X-value is at most epsilon apart.
You can then use the group number as the first sorting level. It is just a simple integer, so no trouble sorting on it. For the Y field, you can then use a normal comparer without epsilon (or repeat the same trick).

A: view my code snippet here. it's just for first level sorting and not optimized.
OrderBy and ThenBy are using general algorithm. you need to re-implement OrderBy and ThenBy with special algorithm like mine. then it can work as OrderBy().ThenBy().
Detail of algorithm:
in a sorted sequence(x1 x2 x3...) under your EpsilonComparer, if x4>x1, then x5>x1. if x4=x1, then x3=x1 and either x5>x1 or x5=x1.
with epsilon(0.4), input following numbers:0.1, 0.6, 1, 1.1, 1.6, 2, 2, 2.6, 3, 3.1, 3.6, 4, 4.1, 4.6, 5, 5.1, 5.6, 6, 6.1, 6.6
result:0.1 0.6 1 1.1 (1.6 2 2 ) 2.6 3 3.1 3.6 4 4.1 4.6 (5 5.1 ) 5.6 (6 6.1 ) 6.6
(a,b,c) indicates these numbers are equal and the order of numbers is not fixed. they can be (a,b,c), (c,a,b) and any other order.
a b indicates a < b and order is fixed.
using System;
using System.Collections.Generic;
using System.Linq;

namespace Rextester
{
    class Program
    {
        public static void Main(string[] args)
        {
            new EpsilonSort(new EpsilonComparer(0.4), 0.1, 0.6, 1, 1.1, 1.6, 2, 2, 2.6, 3, 3.1, 3.6, 4, 4.1, 4.6, 5, 5.1, 5.6, 6, 6.1, 6.6).Sort();
        }
    }

    public class EpsilonSort
    {
        private readonly IComparer<double> m_comparer;
        private readonly double[] m_nums;
        public EpsilonSort(IComparer<double> comparer, params double[] nums)
        {
            this.m_comparer = comparer;
            this.m_nums = nums;
        }

        public void Sort()
        {
            Node root = new Node();
            root.Datas = new List<double>(this.m_nums);

            foreach (double i in (double[])this.m_nums.Clone())
            {
                this.ProcessNode(i, root);
            }

            this.OutputNodes(root);
        }

        private void OutputNodes(Node root)
        {
            if (root.Datas == null)
            {
                foreach (var i in root.Nodes)
                {
                    this.OutputNodes(i);
                }
            }
            else
            {
                if (root.Datas.Count == 1)
                {
                    Console.WriteLine(root.Datas[0]);
                }
                else
                {
                    Console.Write('(');
                    foreach (var i in root.Datas)
                    {
                        Console.Write(i);
                        Console.Write(' ');
                    }
                    Console.WriteLine(')');
                }
            }
        }

        private void ProcessNode(double value, Node one)
        {
            if (one.Datas == null)
            {
                foreach (var i in one.Nodes)
                {
                    this.ProcessNode(value, i);
                }
            }
            else
            {
                Node[] childrennodes = new Node[3];
                foreach (var i in one.Datas)
                {
                    int direction = this.m_comparer.Compare(i, value);
                    if (direction == 0)
                    {
                        this.AddData(ref childrennodes[1], i);
                    }
                    else
                    {
                        if (direction < 0)
                        {
                            this.AddData(ref childrennodes[0], i);
                        }
                        else
                        {
                            this.AddData(ref childrennodes[2], i);
                        }
                    }
                }
                childrennodes = childrennodes.Where(x => x != null).ToArray();
                if (childrennodes.Length >= 2)
                {
                    one.Datas = null;
                    one.Nodes = childrennodes;
                }
            }
        }

        private void AddData(ref Node node, double value)
        {
            node = node ?? new Node();
            node.Datas = node.Datas ?? new List<double>();
            node.Datas.Add(value);
        }

        private class Node
        {
            public Node[] Nodes;
            public List<double> Datas;
        }
    }

    public class EpsilonComparer : IComparer<double>
    {
        private readonly double epsilon;

        public EpsilonComparer(double epsilon)
        {
            this.epsilon = epsilon;
        }

        public int Compare(double d1, double d2)
        {
            if (Math.Abs(d1 - d2) <= epsilon) return 0;

            return d1.CompareTo(d2);
        }
    }
}


text:
Q: Duplicar página de categorias Tengo una página donde se me muestran las categorias loop-archive.php y tengo otra página loop-archive2.php donde quiero que también aparezcan las categorías, ¿cómo hago para que me muestren ahi tambien las categorias?

Me da ese error cuando duplico el contenido del loop-archive.php en el nuevo loop-archive2.php
Adjunto el código que estoy usando

<?php if ( ! have_posts() ) : ?>

<?php _e( 'Not Found', 'limon' ); ?>

<?php _e( 'Apologies, but the page you requested could not be found. Perhaps searching will help.', 'limon' ); ?>

<?php endif; ?>

                    <?php include('slide_nuevo.php')?>

<?php while ( have_posts() ) : the_post(); ?>

         <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>

     <?php $url=get_permalink();?>

                        <?php
      $id = $post->ID;
      $categorias = get_the_terms($id, 'tipos-de-tarifas');
      $count = 0;
      foreach($categorias as $categoria){
      $count ++;
      if($count == 1){
      $name = $categoria->slug;
      $id = $categoria->term_id;
      $name_id = 'tipos-de-tarifas_'.$id;
      $prueba = get_field('color', $name_id);
       }
      }
      ;?>

                         <a style="width:280px;min-height:200px!important;max-height:200px!important;" class="link" href="<?php echo $url;?>" >

<?php the_field('velocidad'); ?>

                         <div class="precio whitecolor padding_1em" style="background:<?php echo $prueba;?>;">

<?php the_field('precio'); ?>

,<?php the_field('decimales_precio'); ?>

€/mes

<?php the_field('condiciones'); ?>

        <a title="<?php printf( esc_attr__( 'Permalink to %s', 'limon' ), the_title_attribute( 'echo=0' ) ); ?>" rel="bookmark" href="<?php the_permalink(); ?>"><?php the_title(); ?>

                            <?php
      $id = $post->ID;
      $categorias = get_the_terms($id, 'tipos-de-tarifas');
      $count =  0;
      foreach($categorias as $categoria){
       $count++;
       //var_dump($categoria);
      $id = $categoria->term_id;
      $parent = $categoria->parent;
      if($count > 1){
       break;
      }
      //$ids = array_fill(0, 6, $id);
      //var_dump($ids);
       if($id == 15){
        }elseif($parent == 15){ }else{echo __('Ver cobertura', 'limon');}
      }
      ?>

                            <?php echo __('Alta online', 'limon');?>

                            <?php $caracteristicas = get_field('caracteristicas');
         $velocidad = get_field('velocidad_de_bajada_y_subida');

         $count = 0;
         if (!empty($caracteristicas)){
          foreach( $caracteristicas as $caracteristica){
           $count ++;
           $caracteristica = $caracteristica['caracteristica'];
           $par = $count%2;
           if($par != 0){
             echo '

'.$caracteristica.'.

';
           }else{
            echo '

'.$caracteristica.'.

';
           }

          }

       }?>

                            <?php if($velocidad){
        echo '

Velocidad de bajada/subida: '.$velocidad.'

';
        }?>

<?php endwhile; // End the loop. Whew. ?>

<?php wp_reset_query();?>

A: el foreach debes ponerlo dentro del siguiente if:
if ( $categorias && !is_wp_error( $categorias) ) {

    foreach foreach($categorias as $categoria){
    ...
    }

}


text:
Q: Set collation and locale for a column in create table statement using Java/JPA/Hibernate I am using PostgreSQL and want to create my database schema using JPA/Hibernate directly. In PostgreSQL I cannot (unfortunately) set the database default collation into ICU based collations, i.e. the following does not work:
CREATE DATABASE my_db ENCODING 'UTF8' LC_COLLATE 'und-x-icu' LC_CTYPE 'und-x-icu' TEMPLATE 'template0';

The reason can be read from this thread:
https://www.postgresql.org/message-id/flat/3366.1498183854%40sss.pgh.pa.us#3366.1498183854@sss.pgh.pa.us
This means that I need to set the default collation when ever I create a table in the database. This would mean that the CREATE TABLE statements should be something like:
CREATE TABLE my_table (
    my_column TEXT COLLATE "und-x-icu"
);

How can I do this using JPA annotations, or similar standard method?


text:
Q: How to add a conditional variable format to nginx log_format with setting escape=json? Can anyone with nginx configuration skills help me, please?
I have my nginx conf file and I want to change my log format so that if a value is not found, a hyphen would be logged.

Nginx logging [documentation][1] has this option documented, but only if the log_format is set to escape=default. I am currently using escape=json option and want to keep that. Right now the empty string is logged, if the value is not found. Can I modify the configuration somehow to have the hyphen as a default empty value?

A: I solved it by mapping the parameter as shown in
https://www.nginx.com/blog/avoiding-top-10-nginx-configuration-mistakes/#if
map $user_id $userId {
default "$user_id";
""      "-";
}


text:
Q: possible number of sums I need help finding a general formula for this specific problem-
$$(a_1+a_2+a_3+...+a_n)= x,  \ \ \ a_1,a_2,a_3,...,a_n∈[0,x] $$
How many permutations/combinations of this sum can be formed? (all positive integers and repetition allowed)
Here's an example where $x=2$ and $n=3$.
$$a_1+a_2+a_3=2, \ \ \ \ a_1,a_2,a_3\in[0,2]$$
$0+0+2 ...(1)$
$0+2+0 ...(2)$
$2+0+0 ...(3)$
$1+1+0 ...(4)$
$1+0+1 ...(5)$
$0+1+1 ...(6)$
Hence total $6$ combinations, but I can't seem to figure out a general formula for this.
By the way, this is my first question here so please excuse my unprofessional questioning.

A: This is just stars and bars concept.stars and bars
If you want a formula then okay. Here it is
$\binom{n+x-1}{x}$


text:
Q: Combining values in certain rows columnwise (in pandas) I do not still grok the right tool for what I need to do in pandas.
It probably needs groupby(), but I was not able to locate the pythonic way (or any other) in the docs or on the web yet.
I have a table with data of a similar structure (30-50 columns):
ID   name  Town     s1       s2       s3       s4

21   Joe   Bonn     rd       fd       NaN      aa
21   Joe   Bonn     NaN      hg       kk       NaN
22   Ann   Oslo     jg       hg       zt       uz
29   Mya   Rome     rd       fd       NaN      aa

I would like to combine rows with the same ID (that would be the index), combining the values in the rows without duplication, forming kind of a union of the string values.
So the result would be:
21   Joe   Bonn     rd       fd,hg    kk       aa
22   Ann   Oslo     jg       hg       zt       uz
29   Mya   Rome     rd       fd       NaN      aa

df.groupby(df.index).sum() was a guess, but it just gives one NaN next to each index.

A: Could try something as this, you need to drop missing values before using the join function:
df.groupby(["ID", "name", "Town"], as_index=False).agg(lambda col: ','.join(col.dropna()))

#   ID  name    Town    s1     s2    s3    s4
#0  21   Joe    Bonn    rd  fd,hg    kk    aa
#1  22   Ann    Oslo    jg     hg    zt    uz
#2  29   Mya    Rome    rd     fd          aa


text:
Q: Array of arrays element comparison Ruby I have an array which looks like
[[1, 2, "2 mins"], [2, 3, "4 mins"], [3, 2, "2 mins"]]

How can I filter subarrays so that I get the minimum value at position 2 or in case of equality the array of equal elements?

A: ar = [[1, 2, "2 mins"], [2, 3, "4 mins"], [3, 2, "2 mins"]]
p ar.group_by{|sub_ar| sub_ar[1]}.min.last
# => [[1, 2, "2 mins"], [3, 2, "2 mins"]]

A: I like how the following reads:
a = [[1, 2, "2 mins"], [2, 3, "4 mins"], [3, 2, "2 mins"]]

min_val = a.min_by { |e| e[1] }[1]
  #=> 2
a.select { |e| e[1] == min_val }
  #=> [[1, 2, "2 mins"], [3, 2, "2 mins"]]


text:
Q: Is the word ''persons'' correct? I've always thought plural form of the word person as people, but in many places I've seen it as 'peoples'.
There was a sign saying
''the room takes 85 peoples max''
Is ''peoples'' also correct? Thanks in advance.

A: persons
Oxford dictionaries

"Usage:
The words people and persons can both be used as the plural of person, but they are not used in exactly the same way. People is by far the more common of the two words and is used in most ordinary contexts: a group of people; there were only about ten people; several thousand people have been rehoused. Persons, on the other hand, tends now to be restricted to official or formal contexts, as in this vehicle is authorized to carry twenty persons; no persons admitted without a pass. In some contexts, persons, by pointing to the individual, may sound less friendly than people: the number should not be disclosed to any unauthorized persons."

peoples
Oxford dictionaries

2 (plural peoples) [TREATED AS SINGULAR OR PLURAL] The men, women, and children of a particular nation, community, or ethnic group:
the native peoples of Canada


text:
Q: ion-align-items class not centering ionic HTML element i want to center an ion-img inside ion-card
HTML :
<ion-grid>
  <ion-row >

  <ion-col size="12"  class="ion-justify-content-center">
      <ion-card  button="true">
        <ion-card-content class="ion-align-items-center">

          <ion-img src='./assets/images/souscription-assuré.svg' ></ion-img>

J'ai déjà une assurance

        </ion-card-content>
      </ion-card>
    </ion-col>

  </ion-row>
</ion-grid>

SCSS :
ion-img{
height: 20vh;
width: 20vh;
display: block;
}

i used ionic pre-built css classes ion-align-items-center and ion-justify-content-center but it's not centered yet

A: You just need to put the margin: auto; in the ion-img css.

A: Wrap it in a Div and use flexbox css.
.html

.scss
.flex-container {
  display: flex;
  justify-content:center;

}


text:
Q: Change Panel Font Weight I want to change font weight of:

*

*unity panel:

Unity Panel

*Window Menu bar and nautilus current folder label:

Window
to the font-weight: normal;
as you can see i already set unity tweak tool settings to the:
Default font: Ubuntu Regular 10
Document font: Ubuntu Regular 10
Window Title font: Ubuntu medium 10
But i just want the font-weight of those that i mentioned be normal and not regular.
I'm using ARC theme and i know i can change it by this file
/usr/share/themes/Arc/gtk-3.0/gtk.css

but i don't know which class is belonging to them.


text:
Q: message broker data connection with oracle express 11g How to make "oracle 11g express" connection from web-sphere message broker 8?
it is giving an error "invalid driver definition, jar not found".

A: File>New Database Definition File. Then new connection, choose JDBC driver as Oracle 11- Oracle thin driver default. Click on the triangle beside it and choose the path of the driver from your PC.


text:
Q: .htaccess redirect if file doesn't exist So here's what I'm trying to do. I have a simple framework and I am using mod rewrite to rewrite the urls so that they point to the correct files. I have a process folder which sits inside the web folder (the web folder is where all the actual website files like images, css, etc are).
This works great but what I am trying to do now is to have a default.php file to process the forms. The file works great if I point the form to it but I want to be able to point the form to it's proper file and if the file is not there then it uses the default.php
The forms are create by a class and the action is set to go to process/{ID OF THE FORM}.php The idea is that anyone can create a form using the class and if they don't need to do anything special, the default.php file will process the form.
I realize I can just set the form class to always use the default.php and then on the default.php file I can check if the proper file exits. If it does, then use that file, if it doesn't then keep processing the form but I am still curious to know if something like this would work on mod rewrite:
RewriteRule ^process/([^/]*) /web/process/$1
RewriteCond %{DOCUMENT_ROOT}/web/process/$1 !-f
RewriteCond %{DOCUMENT_ROOT}/web/process/$1 !-d
RewriteRule ^process/([^/]*) /web/process/default.php [L]

A: You generally should have your RewriteCond calls before your RewriteRule. The Rule triggers if the Conds are met.

A: This rule alone should do it:
RewriteCond %{DOCUMENT_ROOT}web/$0 !-f
RewriteRule ^process/[^/]+$ web/process/default.php [L]

If the requested path cannot be mapped to an existing file, it should be rewritten to the default file.


text:
Q: How do I publish an Uint8Array to IPFS, using its HTTP API on both browser and node.js? I've been trying to do so for several hours to no success. The relevant API endpoint is block/put. IT asks for the HTTP request to use multipart/form-data, but I'm not sure how to do it. Here is one attempt:
const req = require("xhr-request-promise");
const FormData = require("form-data");

(async () => {
  const form = new FormData();
  form.append("data", new Buffer([1, 2, 3]));
  console.log(await req("https://ipfs.infura.io:5001/api/v0/block/put", {
    method: "POST",
    body: form
  }));
})();

A: ipfs-http-client is perfect for this task:
const { create } = require('ipfs-http-client');

// connect to ipfs daemon API server
const ipfs = create('https://ipfs.infura.io:5001');

(async () => {
    await ipfs.block.put(new Uint8Array([1, 2, 3]));
})();


text:
Q: Difference between jQuery 3.0 and earlier versions with handling of '.load()'? I have a relatively simple 'lightbox.js' file that I've used for image galleries on a few websites since about 2013. From the beginning it has run with jQuery 1.8.3, but I'm updating one of the sites and thought I should update the jQ to 3.4.0. But my script doesn't work with jQuery 3.4.0 (or 3.4.1).
The gallery, working with jQuery 1.8.3, may be seen at: http://mull-bed-and-breakfast.co.uk/gallerytn
I now find that with jQuery 3.4.0 'lightbox.js' no longer works as intended. Instead I get the typical 'default' action from clicking on an image that has a link to a larger version - the image is shown centre-screen with a black background, but no frame and no controls. I conclude that jQuery 3.4.0 isn't getting to the end of the function, so doesn't read the 'return false'.
I've tried putting 'event.prevent.Default()' as the first line of the lightbox 'click' function. Now the process stops after creating the 80% overlay but before displaying the image. I suspect that there's something else in my original script that jQ 3.4.0 doesn't like.
I think I've tracked this down to the lines:
    $('<img />')
        .attr('src', $(this).attr('href'))
        .load(function() {
            positionLightboxImage();
        })
        .appendTo('#lightbox');

which is intended to append the 'image' element and position it centrally (and works in jQ 1.8.3)
From the jQuery documentation re .load(): "Note: Prior to jQuery 3.0, the event handling suite also had a method named .load(). Older versions of jQuery determined which method to fire based on the set of arguments passed to it."
I'm thinking that my use of '.load()' here is no longer supported in jQuery 3.4.0, but I've so far not worked out how else to call the 'positionLightboxImage' function at this point in the script. (the function is defined in my script).
How should this be done in jQ 3.0 ?

A: Use on('load', handler)
$('<img />')
        .attr('src', $(this).attr('href'))
        .on('load', positionLightboxImage)
        .appendTo('#lightbox');

Within positionLightboxImage() function ...  this will be the specific image element


text:
Q: python ftplib retrbinary æøå I'm having a strange problem with Nordic characters 'æøå' when I download using ftplib.
When using this part of the code:
source_file = 'file_w_æøå.zip'
ftp.retrbinary('RETR %s' % source_file, open(local_file, 'wb').write)

I get this error:
return getattr(self._sock,name)(*args)
UnicodeEncodeError: 'ascii' codec can't encode characters u'\xe6' in position 12-14: ordinal not in range(128)

The funny thing is, if i replace the string with the real value like this:
ftp.retrbinary('RETR %s' % 'file_w_æøå.zip', open(local_file, 'wb').write)

The file is downloaded with no problems?!
I've tried almost everything with decode/encode with utf-8, I'm only missing to try the right thing :)
Hopefully you guys can help :)
PS When in use special characters in the local_file variable, the it works with out errors.

Full code added, not picture perfect, still a newbi:
#!/usr/local/bin/python
# -*- coding: utf-8 -*-
import os
import sys
import ConfigParser
import ftplib
import codecs

sysCodec = sys.getfilesystemencoding()
print('sysCodec: %s' % sysCodec)

# Get the argument (a) Section in config file
extract_conf = sys.argv[1]

configParser = ConfigParser.SafeConfigParser()
configFilePath = r'C:\\FTP_DL\\config.ini'
configParser.read(configFilePath)

#set variable from Config file
try:
    host = configParser.get(extract_conf, 'url')
    #print('Host %s'  % host)
    user = configParser.get(extract_conf, 'user')
    #print('User %s'  % user)
    pw = configParser.get(extract_conf, 'pw')
    #print('PW %s'  % pw)
    ftp_dir = configParser.get(extract_conf, 'ftp_dir').decode('utf-8')
    print('FTP_DIR: %s'  % ftp_dir)
    dest_dir = configParser.get(extract_conf, 'dest_dir').decode('utf-8')
    print('DEST_DIR: %s'  % dest_dir)
    dest_file = configParser.get(extract_conf, 'dest_file').decode('utf-8')
    print('DEST_FILE: %s'  % dest_file)
    source_file = configParser.get(extract_conf, 'source_file').decode('utf-8')
    print('SOURCE_FILE: %s'  % source_file)
    local_file = os.path.join(dest_dir, dest_file)
    print('Local_File: %s' % local_file)
except 'NoSectionError':
    print ('Section %s not found' % extract_conf)
    sys.exit()

ftp = ftplib.FTP(host)
ftp.login(user,pw)
ftp.cwd(ftp_dir)
ftp.retrbinary(retr, open(local_file, 'wb').write)
ftp.quit()


text:
Q: In naukri, Logout is not clicked instead someother link is clicked I m automating Logout process in Naukri site, used actions class to perform but most of the times it goes and click on someother link. please correct my code.
Here is the site used
DOM Tree
Code Below:
RemoteWebDriver driver;
WebDriverWait wait;
@Test
public void logout() throws InterruptedException{
    System.setProperty("webdriver.chrome.driver", "./drivers/chromedriver.exe");
     driver = new ChromeDriver();
     wait = new WebDriverWait(driver,20);
    driver.manage().window().maximize();
      driver.get("https://www.naukri.com/nlogin/login");
      driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
      String parentWindow = driver.getWindowHandle();
      WebElement google = driver.findElementByXPath("//a[@class='socialbtn google']");
      wait.until(ExpectedConditions.elementToBeClickable(google));
      google.click();
      wait.until(ExpectedConditions.numberOfWindowsToBe(2));
      Set<String> windows = driver.getWindowHandles();
      for (String eachWindow : windows) {
        if(!eachWindow.equals(parentWindow)) {
            driver.switchTo().window(eachWindow);
            gmailLogin();
        }
    }
      driver.switchTo().window(parentWindow);
      WebElement myNaukri = driver.findElementByXPath("//div[text()='My Naukri']/..");
      WebElement logout = driver.findElementByXPath("//a[text()='Logout']");
         Actions build = new Actions(driver);
         build.moveToElement(myNaukri).build().perform();
         wait.until(ExpectedConditions.elementToBeClickable(logout));
         build.click(logout).build().perform();
         Thread.sleep(5000);
         driver.close();

}

 public void gmailLogin() {
      WebElement email = driver.findElementById("identifierId");
      wait.until(ExpectedConditions.visibilityOf(email));
      email.sendKeys("emailID",Keys.ENTER);
      WebElement password = driver.findElementByName("password");
      wait.until(ExpectedConditions.visibilityOf(password));
      password.sendKeys("Password",Keys.ENTER);

  }


text:
Q: Devise column confirmed_at no longer updates after rails 3.2 + devise 2.0 After upgrading to rails 3.2 and devise 2.0
and clicking the confirmation link sent by email or copied from console in development, the confirmed_at column does not get updated. So the result is that you can't login.
What would be the approach to fix this since nothing comes up in the logs, attributes accessible has confirmed_at included,so the column should be updateable.

A: Few axes for your troubleshooting.
At first (the obvious :-) ) that you have activated confirmable in the user model
devise : :confirmable

Then, check that the following columns are defined in your database and in your model (similar if you are on Mongoid, with a different type)
## Confirmable
t.string   :confirmation_token
t.datetime :confirmed_at
t.datetime :confirmation_sent_at
# t.string   :unconfirmed_email # Only if using reconfirmable

And finally (I do not know it apply to you and making the issue) but there was a change in 2.0 regarding confirmable

Besides, a few configuration options were renamed or removed:
Devise.confirm_within was renamed to Devise.allow_unconfirmed_access_for;

What is then giving you the rails console for the new user just just crated?
Should give something like
User.last
 => #<User .... email: "youremail@example.com", confirmation_token: "abch76UfqHBBxHw97123", confirmed_at: nil, confirmation_sent_at: 2012-02-10 11:06:41 UTC, unconfirmed_email: nil, ....>

And the link you received (which you can also manually copy paste in the browser should be similar to (and consistent with the above confirmation token)

Confirm my account

The user in the console should be modified accordingly
User.last
 => #<User .... email: "youremail@example.com", confirmation_token:nil, confirmed_at: confirmed_at: 2012-02-10 11:28:04 UTC, confirmation_sent_at: 2012-02-10 11:06:41 UTC, unconfirmed_email: nil, ....>

If when you copy the link in the browser still does not work, can you copy the last lines of the logs?
the ones around
20:36:51 web.1     | Started GET "/users/confirmation?confirmation_token=abch76UfqHBBxHw97123" for 127.0.0.1 at 2012-02-10 20:36:51 +0900
20:36:51 web.1     | [127.0.0.1] Processing by Devise::ConfirmationsController#show as HTML
20:36:51 web.1     |  [127.0.0.1]   Parameters: {"confirmation_token"=>"abch76UfqHBBxHw97123"}

A: (I moved it to a diffent answer because it deserve it I think)

{"confirmation_token"=>"PAPe74HyVmRheFbaBAaw"} User Load (0.4ms) SELECT users.* FROM users WHERE users.confirmation_token = 'PAPe74HyVmRheFbaBAaw' LIMIT 1 (0.2ms) BEGIN (0.1ms) COMMIT Completed 401 Unauthorized in 15ms

Are you using together with CanCan? That is a Cancan config issue!
If you remove CanCan it will probably work :-). Nevertheless, there is a elegant solution in the CanCan Wiki for this case.
Put the following in your ApplicationController
check_authorization :unless => :devise_controller?

https://github.com/ryanb/cancan/wiki/Ensure-Authorization

Conditionally Check Authorization
As of CanCan 1.6, the check_authorization method supports :if and :unless options. Either one takes a method name as a symbol. This method will be called to determine if the authorization check will be performed. This makes it very easy to skip this check on all Devise controllers since they provide a devise_controller? method.

class ApplicationController < ActionController::Base
  check_authorization :unless => :devise_controller?
end


text:
Q: Redirecting to specific pages after radio button is selected I would like to Redirect to one of two pages containing two separate basic math functions in Javascript. The pages should be linked to one of two radio buttons given and redirected upon the user clicking the "okay" button.

function myFunction() {
  var x = document.getElementById("x");
  var y = document.getElementById("y")

  if (x.checked = true); {
    //* redirect link when Okay button is click
  } else(y.checked = true); {
    //* redirect link when Okay button is clicked
  }
}
<!DOCTYPE html>

What would you like to convert?

  <form action="/action_page.php">
    <input type="radio" name="converter" value="grams" id="x">Grams to ounces

    <input type="radio" name="converter" value="ounces" id="y">Ounces to grams

    <input type="button" onclick="myFunction()" value="Okay!">

  </form>

A: You should use a select box it'll be easier for you
<select id="myChoice">
  <option value="grams">grams</option>
  <option value="ounces">ounces</option>
</select>

and in your JS
function myFunction() {
    var theChoice = document.getElementById("myChoice")

    switch (theChoice.value){
      case 'grams':
         //redirect;
         break;
      case 'ounces':
         //redirect
         break;
}

A: it's simple just create an element of type a, put the attributes and simulate a click() to redirect
here's the pen example:
https://codepen.io/lucassoomago/pen/YbKwJx
the following example does not redirect because the stack overflow does not allow, if you want to see redirecting use the link above

      function myFunction() {
        var x = document.getElementById("x");
        var y = document.getElementById("y")

        var a = document.createElement("a");

        if (x.checked == true)
        {
          a.setAttribute('href', 'https://www.google.com');
          a.setAttribute('target', 'blank');
        }else if (y.checked == true)
        {
          a.setAttribute('href', 'https://www.youtube.com');
          a.setAttribute('target', 'blank');
        }

        a.click()
      }

What would you like to convert?

    <form action="/action_page.php">
       <input type="radio" name="converter" value="grams" id="x">Grams to
        ounces

       <input type="radio" name="converter" value="ounces" id="y">Ounces to
        grams

       <input type="button" onclick="myFunction()" value="Okay!">

       </form>

A: The following will check if the checkbox is ticked and then redirect you to the url you define. I have used else if as else would have redirected you to location y if neither checkbox was selected in your example.
<form action="/action_page.php">
    <input type="radio" name="converter" value="grams" id="x">Grams to
    ounces

    <input type="radio" name="converter" value="ounces" id="y">Ounces to
    grams

    <input type="button" onclick="myFunction()" value="Okay!">

</form>


text:
Q: Como abrir o teclado numérico num campo formatado? Tenho um campo de texto que recebe o CPF, ele possui uma máscara de CPF, porém como é um campo texto, em Mobile ele não abre direto naquele teclado numérico e quando mudo o tipo dele para number, ele só escreve os 3 primeiros dígitos e apaga tudo quando chega no "." da formatação do campo.
<html>
    <div class="form-separador">
        <input type="text"  class="input1"  id="cpf" name="cpf"
               placeholder="000.000.000-00" value="%%=v(@Cpf)=%%" required >
    </div>
</html>

$(document).ready(function(){
  $('#cpf').mask('000.000.000-00', {reverse: true});
});

A: Atualize a versão do maskinput para a versão 1.4.
Adicione type="tel" e remova o atributo maxlength da entrada ou defina-o como um valor certo para não interferir com a ação do cursor, como 20.
Fonte: https://stackoverflow.com/a/29437478/4312593


text:
Q: Are there any use cases when it is acceptable to use Spring beans created by constructor call? I am pretty new to Spring and I study using "Spring in Action" (fourth edition) by Craig Walls. The interest is not only on how to write code that is working, but also on the correct principles of using Spring.
Regarding the following piece of code from page 142, Listing 5.6:
public class HomeControllerTest {

    @Test
    public void testHomePage() throws Exception {
        HomeController controller = new HomeController();
        MockMvc mockMvc = standaloneSetup(controller).build();
        mockMvc.perform(get("/")).andExpect(view().name("home"));
    }
}

My questions are generated by the following thoughts:

*

*The general understanding is that Spring uses Dependency Injection as a way to reduce the management overhead of object dependencies, increase modularity, simplify testing and code reuse. However, doesn't it imply that beans must be created and managed by the container? Since I started reading on the subject, the first detail that I memorized stated that new should never appear in a well-written piece of code that follows DI.

*Could this be a solution in case we want to test a Stateful bean? I mean, if there are multiple independent tests to be run on the same instance, each of them testing the same state of the bean. Even though I found out that there is a suitable annotation for doing this (@DirtiesContext(classMode = ClassMode.AFTER_EACH_TEST_METHOD)).

*Is there another use case that is difficult or impossible to solve otherwise (except for using new)?

A more 'to the letter' implementation would use @ContextConfiguration to specify the ApplicationContext.
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = WebConfig.class)
@WebAppConfiguration
public class HomeControllerTest {

    @Autowired
    HomeController controller;

    @Test
    public void testHomePage() throws Exception {
        MockMvc mockMvc = standaloneSetup(controller).build();
        mockMvc.perform(get("/")).andExpect(view().name("home"));
    }
}

A: *

*yes, you shouldn't use new to create Spring bean instances (otherwise they're not Spring beans anymore) in production code. But the whole point of DI is to let you create and manually inject your objects with fake dependencies in unit tests. So the test code here is perfectly fine.

*Yes, each unit test is free to create its own bean instance and to populate it the way it needs to. Stateful beans are extremely rare, though. They're usually stateless.

*Another place where using new to create a Spring bean is precisely in @Bean-annotated methods of configuration classes. The whole point of these methods is precisely to create and initialize the Spring beans that will then be used and injected by Spring. But again, using new in unit tests is absolutely fine, and the right thing to do.