How to deal with multiple ClientHttpRequestInterceptors in Spring 4

Question: In RestTemplate, I have configured two ClientHttpRequestInterceptor (one for BasicAuthorization and another for Token based authentication.
From client side how I ask RestTemplate to use the correct ClientHttpRequestInterceptor to execute the API call.
Some API calls require BasicAuthorization to work. (For Ex: if the URL starts with "/admin" require BasicAuthorization, others require Token based Authentication)
How I can achieve this in Spring 4?
Answer: You could use two instances of RestTemplate, one for Basic auth and one for Token auth.
@Bean
@Qualifier("authRestTemplate")
public RestTemplate getAuthTemplate{
    // create rest template, add auth interceptor
}

@Bean
@Qualifier("tokenRestTemplate")
public RestTemplate getTokenTemplate{
    // create rest template, add token interceptor
}

Then, when autowiring the RestTemplate, use the desired @Qualifier
@Autowired
@Qualifier("authRestTemplate")
private RestTemplate authTemplate;

@Autowired
@Qualifier("tokenRestTemplate")
private RestTemplate tokenTemplate;

Another option would be adding two ClientHttpRequestInterceptor to the RestTemplate
class BasicAuthInterceptor implements ClientHttpRequestInterceptor {

    private final AuthService authService;

    public BasicAuthHeaderInterceptor(AuthService authService) {
        this.authService = authService;
    }

    @Override
    public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
        if(isApplicable(request)){
            String token = Base64Utils.encodeToString((authService.getUsername() + ":" + authService.getpassword()).getBytes(Charset.forName("UTF-8")));
            request.getHeaders().add("Authorization", "Basic " + token);
        }
        return execution.execute(request, body);
    }

}

class TokenInterceptor implements ClientHttpRequestInterceptor {

    private final AuthService authService;

    public TokenHeaderInterceptor(AuthService authService) {
        this.authService = authService;
    }

    @Override
    public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
        if(isApplicable(request)){
            request.getHeaders().add("Authorization", "Bearer " + tokenService.getToken());
        }
        return execution.execute(request, body);
    }

}

Then, add the two interceptors to the RestTemplate
@Bean
public RestTemplate restTemplate(){
    RestTemplate template = new RestTemplate();

    template.getInterceptors().add(new BasicAuthInterceptor(authService));
    template.getInterceptors().add(new TokenInterceptor(authService));

    return template;
}

Comment: I was actually looking for a solution where 'handler' class (Ex: InterceptorHandler) to select the correct handler based on the URL you are going to call.


How to create a perfectly round circle filled with text of variable sizes in CSS

Question: I have a react.js app and need to dynamically make a text of variable size look like its held perfectly in a circle (pic attached).
I tried by creating little divs on each side of the text to make it look like a circle but it was not good enough and too complex to implement for texts of different sizes
Comment: please don't repeat the same question after one month (we have a good memory ..)
Answer: Not the answer you look for but some hints about shape-outside :
it requires to know the length of your text and size your boxes into squares.
image or gradient can be used to push text from area where they are drawn.
example :

div:not([class]) {
  width: 24em;
  min-height: 24em;
  /* see me
  border:solid;
  border-radius:100%;
  */
}

p {
  margin: 0;
  text-align: justify;
}

div[class]:before {
  opacity: 0;
  width: 12em;
  height: 12em;
  content: '';
  float: left;
  clear: left;
  background: radial-gradient(circle at bottom right, transparent 70%, black 70%);
  shape-outside: radial-gradient(circle at bottom right, transparent 70%, black 70%);
  float: left;
}

div[class][id]:before {
  background: radial-gradient(circle at top right, transparent 70%, black 70%);
  shape-outside: radial-gradient(circle at top right, transparent 70%, black 70%);
  float: left;
}

div[class]:after,
div[class][id]:after {
  opacity: 0;
  content: '';
  width: 12em;
  height: 12em;
  float: right;
  background: radial-gradient(circle at bottom left, transparent 70%, black 70%);
  shape-outside: radial-gradient(circle at bottom left, transparent 70%, black 70%);
}

div[class][id]:after {
  content: '';
  float: right;
  background: radial-gradient(circle at top left, transparent 70%, black 70%);
  shape-outside: radial-gradient(circle at top left, transparent 70%, black 70%);
}

/* extra */

body {
  font-family: 'Times New Roman';
  font-size: 16px;
  line-height: 1.28em;
  display: grid;
  grid-template-columns: repeat(6, 1fr);
  grid-template-rows: repeat(6, 1fr);
  grid-flow: dense;
  max-width: 600px;
  margin: auto;
}

div {
  margin: auto;
}

body> :nth-child(1) {
  grid-row: 1 / span 2;
  grid-column: 2 / span 2;
  color: tomato
}

body> :nth-child(2) {
  grid-row: 3 / span 2;
  grid-column: 3 / span 2;
  color: green
}

body> :nth-child(3) {
  grid-row: 2 / span 2;
  grid-column: 5 / span 2;
  color: blue
}

Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est.
    Mauris placerat eleifend leo. Quisque sit amet est et sapien ullamcorper pharetra. Vestibulum erat wisi, condimentum sed, commodo vitae, ornare sit amet, wisi. Aenean fermentum, elit eget tincidunt condimentum, eros ipsum rutrum orci, sagittis tempus
    lacus enim ac dui. Donec non enim in turpis pulvinar facilisis. Ut felis. Praesent dapibus, neque id cursus faucibus, tortor neque egestas augue, eu vulputate magna eros eu erat. Aliquam erat volutpat. Nam dui mi, tincidunt quis, accumsan porttitor,
    facilisis luctus, metus

Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est.
    Mauris placerat eleifend leo. Quisque sit amet est et sapien ullamcorper pharetra. Vestibulum erat wisi, condimentum sed, commodo vitae, ornare sit amet, wisi. Aenean fermentum, elit eget tincidunt condimentum, eros ipsum rutrum orci, sagittis tempus
    lacus enim ac dui. Donec non enim in turpis pulvinar facilisis. Ut felis. Praesent dapibus, neque id cursus faucibus, tortor neque egestas augue, eu vulputate magna eros eu erat. Aliquam erat volutpat. Nam dui mi, tincidunt quis, accumsan porttitor,
    facilisis luctus, metus

Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est.
    Mauris placerat eleifend leo. Quisque sit amet est et sapien ullamcorper pharetra. Vestibulum erat wisi, condimentum sed, commodo vitae, ornare sit amet, wisi. Aenean fermentum, elit eget tincidunt condimentum, eros ipsum rutrum orci, sagittis tempus
    lacus enim ac dui. Donec non enim in turpis pulvinar facilisis. Ut felis. Praesent dapibus, neque id cursus faucibus, tortor neque egestas augue, eu vulputate magna eros eu erat. Aliquam erat volutpat. Nam dui mi, tincidunt quis, accumsan porttitor,
    facilisis luctus, metus

https://developer.mozilla.org/en-US/docs/Web/CSS/shape-outside The shape-outside CSS property defines a shape—which may be non-rectangular—around which adjacent inline content should wrap. By default, inline content wraps around its margin box; shape-outside provides a way to customize this wrapping, making it possible to wrap text around complex objects rather than simple boxes.

Browser support for shape-outside
Comment: Seems a good solution for me and It's a perfect answer for the canonical duplicate (https://stackoverflow.com/q/19909266/8620333).


How to capture only query strings using .htaccess PHP

Question:
.htaccess file

<IfModule mod_rewrite.c>
 RewriteEngine On
 RewriteBase /cms_project
 RewriteCond %{REQUEST_URI} single(.*)
 RewriteRule  ^(.+)$ single.php?url=$1
</IfModule>

URL: localhost/cms_project

//want to query strings single/posts/1/post-title
echo $_GET['url'];

OR

//function to get url query string convert it to an array
function getUrl() {
    if(isset($_GET['url'])) {
        $url = rtrim($_GET['url'],'/');
        $url = filter_var($url, FILTER_SANITIZE_URL);
        $url = explode('/', $url);
        return $url;
    }
  }
  print_r($_GET['url']);

Now I want get url query strings, when I enter url like
localhost/cms_project/single/posts/1/post-title
Now I expect to get single/posts/1/post-title OR ['single','posts','1','post-title'] array
But above code only return ['single.php'] array
Answer: Try this:
<IfModule mod_rewrite.c>
 RewriteEngine On
 RewriteBase /cms_project

 RewriteCond %{THE_REQUEST} ^GET\ /single\.php\?url=(.*) [NC]
 RewriteRule ^single\.php$ single/%1 [L]
 RewriteRule ^(.*)/(.*)$ single.php?url=$1/$2 [NC,L]  #OR ^single/(.*)$ single.php?url=single/$1
</IfModule>


Go to definition in VS code doesn't show the body of a function

Question: When I right click on a function and then select "Go to definition" there shows up a module with that function, but it only shows the parameters which have to be passed to it, and I can't see anything about the body of the function.
Here is what's shown when I went to the definition of itertools.dropwhile:
Comment: There is no function body to be shown.  This is a module that's implemented in C, not Python.
Comment: Oh. And the same happens with ```math.sqrt```? Because when I go to definition it shows ```def sqrt(x: SupportsFloat) -> float: ...```. And also with ```print``` function.
Comment: What @jasonharper said will apply to many (but not all) of the built-ins…which means you'll actually have to read its [documentation](https://docs.python.org/3/).
Comment: The actual implementation is in C, here: [cpython/itermodules.c](https://github.com/python/cpython/blob/3.8/Modules/itertoolsmodule.c#L1153).
Answer: As mentioned in the comments, VSCode can only show you source code it has access to, and many of the Python builtins and stdlib (including the itertools module) are implemented in compiled C -- there's no source code to show you.
Answer: Sometimes this happens if you develop code that runs inside an environment whose libraries are not visible in your main OS.
One way to solve this is by opening the terminal in VSCode and doing a pip install <library> to install the library and make VSCode aware of it.
Comment: This is a good point (although note that this is the `itertools` library from the standard lib, so no need to install it; also, `pip install ` is not always the correct way forward and depends on the development environment). However, in this case, there is no Python code to show for the definition of this function. VSCode then falls back on showing the [type stub](https://mypy.readthedocs.io/en/stable/stubs.html) (if any) for that function/value, so it's doing the right thing here.


Passenger error: No such file or directory - config/environment.rb

Question: I installed Redmine on MacOSX Server 10.6.8 according to this installation description. So far everything works fine: When I start webrick the server serves the Redmine pages. The gems and redmine are installed under the user "redmine".
After that I aimed configuring apache2 with passenger as described here. As suggested by the description I also installed the passenger-pane which stores its virtual host configuration files in /private/etc/apache2/passenger_pane_vhosts. This is what I came up with after a lot of manual try and error. At least, now I can reach a passenger error page.
// redmine.vhost.conf
<VirtualHost *:80>
  ServerName myserver
  ServerAlias localhost
  DocumentRoot "/Users/redmine/Sites/redmine"
# RackEnv production
# RackBaseURI /
  RailsEnv production
  RailsBaseURI /
# PassengerUser www-data
# PassengerGroup www-data
  <Directory "/Users/redmine/Sites/redmine">
    Order allow,deny
    Allow from all
  </Directory>
</VirtualHost>

However, the passenger module still runs into the following errors.
Error message: No such file or directory - config/environment.rb

The /var/log/apache2/error_log of the web server stated the following.
[warn] NameVirtualHost *:80 has no VirtualHosts
[notice] Apache/2.2.21 (Unix) Phusion_Passenger/3.0.12 configured --
  resuming normal operations
[ pid=21824 thr=2151905620 file=utils.rb:176 time=2012-06-01 18:22:07.126 ]: ***
  Exception Errno::ENOENT in PhusionPassenger::ClassicRails::ApplicationSpawner
  (No such file or directory - config/environment.rb) (process 21824,
  thread #<Thread:0x0000010086f2a8>):

I experimented with the user switch functionality of passenger as described in the documentation - as you can tell from my configuration file. Though, I was not successful.

UPDATE: (04.06.2012)
After I changed the DocumentRoot and Directory path to /Users/redmine/Sites/redmine/public as suggested by Holger the Redmine site is reachable under http://myserver. However, it is not reachable under http://myserver/redmine; the 404.html of the public/ folder is served.
I guess Redmine is reachable under http://myserver because I overwrite the DocumentRoot for the whole Apache server (?). That is not what I want, though. Without setting the DocumentRoot in redmine.vhost.conf I encounter the following error page.
Forbidden
You don't have permission to access / on this server.
Additionally, a 403 Forbidden error was encountered while trying to
use an ErrorDocument to handle the request.
Apache/2.2.21 (Unix) Phusion_Passenger/3.0.12 Server at myserver Port 80

Question: How must I configure the server to get the desired http://myserver/redmine url?
Answer: According to the Passenger documentation you have to use the public directory as the document root. In your case this would be /Users/redmine/Sites/redmine/public.
That way, only truly public files are in the document root and Passenger finds the correct application root. You should never put any actual code files (or even worse: configuration files) into the document root as they are freely readable by anyone.
Comment: Sounds good. When I change the path the server delivers the `/Users/redmine/Sites/redmine/public/404.html` page. How can I retrieve Redmine instead?
Answer: Only for Users, which installed Redmine with the Bitnami-Stack:
I realy wonder, why i got the same Error which described the ThreadOpener after upgrade and restart my OS.
The Distribution also had installed apache and mysql, and start this one.
BitNami has its own apache- & Mysql-Server inside of the Bundle.
Solution:
stop Apache & mysql, and start the BitNami one with:
cd /opt/redmine-2.3.1-3
ctlscript.sh start mysql
ctlscript.sh start apache

That solve my problem!
Comment: Thanks for your answer but it doesn't seem to relate to the question.  The OP does not mention using BitNami and his error was that a config file could not be found rather than Apache and MySQL were not running.
Answer: To mount as a /redmine URL, try a
RewriteBase /redmine/

in your VirtualHost


meaning of this operator ??

Question: given the operator
$ P_{\Lambda } = (f\in L^{2}(R)^{even}| f(q)=0 , |q| \ge \Lambda) $
what does it mean? the operator $ P_{\Lambda} $ acts over a function $f(q) $ by setting this (even) function to zero whenever $ |q| \ge \Lambda $
how could i evaluate its Eigenvalues and Eigenfunctions ?? thanks
$ P_{\Lambda} T_{n}= \mu _{n} T_{n} $ , can we have a mening to $ P_{\Lambda}^{k} $ ? its power iteration, does this operator have a geommetric meaning ?
Answer: You probably mean $P_\Lambda f(q)=0$. It is multiplication by $\mathbb{1}_{[-\Lambda,\Lambda]}$, the indicator function of $[-\Lambda,\Lambda]$, it restricts functions to that interval, in a sense.
This operator is a projection, $P^2=P$. It is the identity on its image, functions supported on $[-\Lambda,\Lambda]$, so its only eigenvalue is $1$, with eigenvectors all functions in its image.
A last remark is that this is really an operation you will find alot in analysis and physics, cutting some parts of a function (for instance frequencies higher than $\Lambda$, when applied to a Fourier transform $f=\hat g$).
EDIT: A big mistake: $0$ is also an eigenvalue: $P_\Lambda f=0=0\cdot f$ for functions supported outside $[-\Lambda,\Lambda]$ (that is, equal to $0$ in that interval). This holds more generally for projections, for all eigenfunction $f$, either $Pf=f$ or $Pf=0$.
Apologies.

meaning of this operator ??


SSSD, openLDAP, MIT Kerberos: "id username" doesn't find enty in LDAP, but ldapsearch does

Question: I have installed openLDAP, MIT Kerberos and SSD on Debian 10 Systems based on this tutorial Integrated Kerberos-OpenLDAP provider on Debian squeeze.
Each of the three components is on its own Proxmox LXC Container.
ldap: 192.168.1.120  (ldap2)
Kerberos: 192.168.1.128  (kerb)
Client with SSD: 192.168.1.129  (test)
The IPs can be resolved by DNS.
The Problem:
When I call 'id username' I get no result.
But with the same filter I get a result with ldapsearch.
Log on Client after 'id test05' (SSD loglevel 6)
==> /var/log/sssd/sssd_nss.log <==
(Thu Jan 16 16:03:48 2020) [sssd[nss]] [accept_fd_handler] (0x0400): Client connected!
(Thu Jan 16 16:03:48 2020) [sssd[nss]] [sss_cmd_get_version] (0x0200): Received client version [1].
(Thu Jan 16 16:03:48 2020) [sssd[nss]] [sss_cmd_get_version] (0x0200): Offered version [1].
(Thu Jan 16 16:03:48 2020) [sssd[nss]] [nss_getby_name] (0x0400): Input name: test05
(Thu Jan 16 16:03:48 2020) [sssd[nss]] [cache_req_send] (0x0400): CR #1: New request 'User by name'
(Thu Jan 16 16:03:48 2020) [sssd[nss]] [cache_req_process_input] (0x0400): CR #1: Parsing input name [test05]
(Thu Jan 16 16:03:48 2020) [sssd[nss]] [sss_parse_name_for_domains] (0x0200): name 'test05' matched without domain, user is test05
(Thu Jan 16 16:03:48 2020) [sssd[nss]] [cache_req_set_name] (0x0400): CR #1: Setting name [test05]
(Thu Jan 16 16:03:48 2020) [sssd[nss]] [cache_req_select_domains] (0x0400): CR #1: Performing a multi-domain search
(Thu Jan 16 16:03:48 2020) [sssd[nss]] [cache_req_search_domains] (0x0400): CR #1: Search will check the cache and check the data provider
(Thu Jan 16 16:03:48 2020) [sssd[nss]] [cache_req_set_domain] (0x0400): CR #1: Using domain [xxxxxxx.net]
(Thu Jan 16 16:03:48 2020) [sssd[nss]] [cache_req_prepare_domain_data] (0x0400): CR #1: Preparing input data for domain [xxxxxxx.net] rules
(Thu Jan 16 16:03:48 2020) [sssd[nss]] [cache_req_search_send] (0x0400): CR #1: Looking up firstname.lastname@example.com
(Thu Jan 16 16:03:48 2020) [sssd[nss]] [cache_req_search_ncache] (0x0400): CR #1: Checking negative cache for [email@example.com]
(Thu Jan 16 16:03:48 2020) [sssd[nss]] [cache_req_search_ncache] (0x0400): CR #1: [firstname.lastname@example.com] is not present in negative cache
(Thu Jan 16 16:03:48 2020) [sssd[nss]] [cache_req_search_cache] (0x0400): CR #1: Looking up [firstname.lastname@example.com] in cache
(Thu Jan 16 16:03:48 2020) [sssd[nss]] [cache_req_search_cache] (0x0400): CR #1: Object [email@example.com] was not found in cache
(Thu Jan 16 16:03:48 2020) [sssd[nss]] [cache_req_search_dp] (0x0400): CR #1: Looking up [firstname.lastname@example.com] in data provider
(Thu Jan 16 16:03:48 2020) [sssd[nss]] [sss_dp_issue_request] (0x0400): Issuing request for [0x55bd0978aee0:1:firstname.lastname@example.com@xxxxxxx.net]
(Thu Jan 16 16:03:48 2020) [sssd[nss]] [sss_dp_get_account_msg] (0x0400): Creating request for [xxxxxxx.net][0x1][BE_REQ_USER][firstname.lastname@example.com:-]
(Thu Jan 16 16:03:48 2020) [sssd[nss]] [sss_dp_internal_get_send] (0x0400): Entering request [0x55bd0978aee0:1:email@example.com@xxxxxxx.net]

==> /var/log/sssd/sssd_xxxxxxx.net.log <==
(Thu Jan 16 16:03:48 2020) [sssd[be[xxxxxxx.net]]] [dp_get_account_info_handler] (0x0200): Got request for [0x1][BE_REQ_USER][email@example.com]
(Thu Jan 16 16:03:48 2020) [sssd[be[xxxxxxx.net]]] [dp_attach_req] (0x0400): DP Request [Account #3]: New request. Flags [0x0001].
(Thu Jan 16 16:03:48 2020) [sssd[be[xxxxxxx.net]]] [dp_attach_req] (0x0400): Number of active DP request: 1
(Thu Jan 16 16:03:48 2020) [sssd[be[xxxxxxx.net]]] [sdap_search_user_next_base] (0x0400): Searching for users with base [ou=users,dc=lan,dc=xxxxxxx,dc=net]
(Thu Jan 16 16:03:48 2020) [sssd[be[xxxxxxx.net]]] [sdap_get_generic_ext_step] (0x0400): calling ldap_search_ext with [(&(uid=test05)(objectclass=posixAccount)(uid=*)(&(uidNumber=*)(!(uidNumber=0))))][ou=users,dc=lan,dc=xxxxxxx,dc=net].
(Thu Jan 16 16:03:48 2020) [sssd[be[xxxxxxx.net]]] [sdap_get_generic_op_finished] (0x0400): Search result: No such object(32), no errmsg set
(Thu Jan 16 16:03:48 2020) [sssd[be[xxxxxxx.net]]] [sdap_search_user_process] (0x0400): Search for users, returned 0 results.
(Thu Jan 16 16:03:48 2020) [sssd[be[xxxxxxx.net]]] [sysdb_search_by_name] (0x0400): No such entry
(Thu Jan 16 16:03:48 2020) [sssd[be[xxxxxxx.net]]] [sysdb_delete_user] (0x0400): Error: 2 (No such file or directory)
(Thu Jan 16 16:03:48 2020) [sssd[be[xxxxxxx.net]]] [dp_req_done] (0x0400): DP Request [Account #3]: Request handler finished [0]: Success
(Thu Jan 16 16:03:48 2020) [sssd[be[xxxxxxx.net]]] [_dp_req_recv] (0x0400): DP Request [Account #3]: Receiving request data.
(Thu Jan 16 16:03:48 2020) [sssd[be[xxxxxxx.net]]] [dp_req_reply_list_success] (0x0400): DP Request [Account #3]: Finished. Success.
(Thu Jan 16 16:03:48 2020) [sssd[be[xxxxxxx.net]]] [dp_table_value_destructor] (0x0400): Removing [0:1:0x0001:1::xxxxxxx.net:firstname.lastname@example.com] from reply table
(Thu Jan 16 16:03:48 2020) [sssd[be[xxxxxxx.net]]] [dp_req_destructor] (0x0400): DP Request [Account #3]: Request removed.
(Thu Jan 16 16:03:48 2020) [sssd[be[xxxxxxx.net]]] [dp_req_destructor] (0x0400): Number of active DP request: 0

==> /var/log/sssd/sssd_nss.log <==
(Thu Jan 16 16:03:48 2020) [sssd[nss]] [cache_req_search_cache] (0x0400): CR #1: Looking up [firstname.lastname@example.com] in cache
(Thu Jan 16 16:03:48 2020) [sssd[nss]] [cache_req_search_cache] (0x0400): CR #1: Object [email@example.com] was not found in cache
(Thu Jan 16 16:03:48 2020) [sssd[nss]] [cache_req_search_ncache_add_to_domain] (0x0400): CR #1: Adding [firstname.lastname@example.com] to negative cache
(Thu Jan 16 16:03:48 2020) [sssd[nss]] [sss_ncache_set_str] (0x0400): Adding [email@example.com] to negative cache
(Thu Jan 16 16:03:48 2020) [sssd[nss]] [cache_req_process_result] (0x0400): CR #1: Finished: Not found
(Thu Jan 16 16:03:48 2020) [sssd[nss]] [sss_dp_req_destructor] (0x0400): Deleting request: [0x55bd0978aee0:1:email@example.com@xxxxxxx.net]
(Thu Jan 16 16:03:48 2020) [sssd[nss]] [client_recv] (0x0200): Client disconnected!

/var/log/syslog on the ldap2 host (only 3 lines with loglevel 256)
Jan 16 16:03:48 ldap2 slapd[238]: conn=1067 op=6 SRCH base="ou=users,dc=lan,dc=xxxxxxx,dc=net" scope=2 deref=0 filter="(&(uid=test05)(objectClass=posixAccount)(uid=*)(&(uidNumber=*)(!(uidNumber=0))))"
Jan 16 16:03:48 ldap2 slapd[238]: conn=1067 op=6 SRCH attr=objectClass uid userPassword uidNumber gidNumber gecos homeDirectory loginShell krbPrincipalName cn modifyTimestamp modifyTimestamp shadowLastChange shadowMin shadowMax shadowWarning shadowInactive shadowExpire shadowFlag krbLastPwdChange krbPasswordExpiration pwdAttribute authorizedService accountExpires userAccountControl nsAccountLock host rhost loginDisabled loginExpirationTime loginAllowedTimeMap sshPublicKey userCertificate;binary mail
Jan 16 16:03:48 ldap2 slapd[238]: conn=1067 op=6 SEARCH RESULT tag=101 err=32 nentries=0 text=

As you can see the openLDAP search is called with
base: ou=users,dc=lan,dc=xxxxxxx,dc=net
filter:
(&(uid=test05)(objectclass=posixAccount)(uid=*)(&(uidNumber=*)(!(uidNumber=0))))

When I do this search directly on the openLDAP host I get a result:
ldapsearch -Y GSSAPI -b ou=users,dc=lan,dc=xxxxxxx,dc=net "(&(uid=test05)(objectclass=posixAccount)(uid=*)(&(uidNumber=*)(!(uidNumber=0))))" cn  uid
SASL/GSSAPI authentication started
SASL username: email@example.com
SASL SSF: 256
SASL data security layer installed.
# extended LDIF
#
# LDAPv3
# base <ou=users,dc=lan,dc=xxxxxxx,dc=net> with scope subtree
# filter: (&(uid=test05)(objectclass=posixAccount)(uid=*)(&(uidNumber=*)(!(uidNumber=0))))
# requesting: cn uid
#
.
# test05, users, lan.xxxxxxx.net
dn: uid=test05,ou=users,dc=lan,dc=xxxxxxx,dc=net
cn: test05
uid: test05

/var/log/syslog on the ldap2 host
Jan 16 16:19:08 ldap2 slapd[238]: conn=1068 fd=24 ACCEPT from IP=[::1]:37252 (IP=[::]:389)
Jan 16 16:19:08 ldap2 slapd[238]: conn=1068 op=0 BIND dn="" method=163
Jan 16 16:19:08 ldap2 slapd[238]: conn=1068 op=0 RESULT tag=97 err=14 text=SASL(0): successful result:
Jan 16 16:19:08 ldap2 slapd[238]: conn=1068 op=1 BIND dn="" method=163
Jan 16 16:19:08 ldap2 slapd[238]: conn=1068 op=1 RESULT tag=97 err=14 text=SASL(0): successful result:
Jan 16 16:19:08 ldap2 slapd[238]: conn=1068 op=2 BIND dn="" method=163
Jan 16 16:19:08 ldap2 slapd[238]: conn=1068 op=2 BIND authcid="email@example.com" authzid="email@example.com"
Jan 16 16:19:08 ldap2 slapd[238]: conn=1068 op=2 BIND dn="cn=admin,dc=lan,dc=xxxxxxx,dc=net" mech=GSSAPI sasl_ssf=256 ssf=256
Jan 16 16:19:08 ldap2 slapd[238]: conn=1068 op=2 RESULT tag=97 err=0 text=
Jan 16 16:19:08 ldap2 slapd[238]: conn=1068 op=3 SRCH base="ou=users,dc=lan,dc=xxxxxxx,dc=net" scope=2 deref=0 filter="(&(uid=test05)(objectClass=posixAccount)(uid=*)(&(uidNumber=*)(!(uidNumber=0))))"
Jan 16 16:19:08 ldap2 slapd[238]: conn=1068 op=3 SRCH attr=cn uid
Jan 16 16:19:08 ldap2 slapd[238]: conn=1068 op=3 SEARCH RESULT tag=101 err=0 nentries=1 text=
Jan 16 16:19:08 ldap2 slapd[238]: conn=1068 op=4 UNBIND
Jan 16 16:19:08 ldap2 slapd[238]: conn=1068 fd=24 closed
Jan 16 16:19:30 ldap2 slapd[238]: conn=1069 fd=24 ACCEPT from IP=[::1]:37254 (IP=[::]:389)
Jan 16 16:19:30 ldap2 slapd[238]: conn=1069 op=0 BIND dn="" method=163
Jan 16 16:19:30 ldap2 slapd[238]: conn=1069 op=0 RESULT tag=97 err=14 text=SASL(0): successful result:
Jan 16 16:19:30 ldap2 slapd[238]: conn=1069 op=1 BIND dn="" method=163
Jan 16 16:19:30 ldap2 slapd[238]: conn=1069 op=1 RESULT tag=97 err=14 text=SASL(0): successful result:
Jan 16 16:19:30 ldap2 slapd[238]: conn=1069 op=2 BIND dn="" method=163
Jan 16 16:19:30 ldap2 slapd[238]: conn=1069 op=2 BIND authcid="firstname.lastname@example.com" authzid="firstname.lastname@example.com"
Jan 16 16:19:30 ldap2 slapd[238]: conn=1069 op=2 BIND dn="cn=admin,dc=lan,dc=xxxxxxx,dc=net" mech=GSSAPI sasl_ssf=256 ssf=256
Jan 16 16:19:30 ldap2 slapd[238]: conn=1069 op=2 RESULT tag=97 err=0 text=
Jan 16 16:19:30 ldap2 slapd[238]: conn=1069 op=3 SRCH base="ou=users,dc=lan,dc=xxxxxxx,dc=net" scope=2 deref=0 filter="(&(uid=test05)(objectClass=posixAccount)(uid=*)(&(uidNumber=*)(!(uidNumber=0))))"
Jan 16 16:19:30 ldap2 slapd[238]: conn=1069 op=3 SRCH attr=cn uid
Jan 16 16:19:30 ldap2 slapd[238]: conn=1069 op=3 SEARCH RESULT tag=101 err=0 nentries=1 text=
Jan 16 16:19:30 ldap2 slapd[238]: conn=1069 op=4 UNBIND
Jan 16 16:19:30 ldap2 slapd[238]: conn=1069 fd=24 closed

My SSSD configuration
cat /etc/sssd/sssd.conf
[sssd]
config_file_version = 2
services = nss, pam
domains = xxxxxxx.net

[nss]
debug_level = 6
override_shell = /bin/bash
filter_users = root
filter_groups = root

[pam]
offline_credentials_expiration = 60

[domain/xxxxxxx.net]

# A domain with identities provided by LDAP and authentication by Kerberos

debug_level = 6
cache_credentials = true

# -- Authentication provider --
auth_provider = krb5
krb5_server = kerb.xxxxxxx.net
krb5_realm = XXXXXXX.NET
krb5_ccachedir = /tmp

# -- Access provider --
access_provider = permit

# -- Change Password provider --
chpass_provider = krb5

# -- Identity provider --
id_provider = ldap
ldap_uri = ldap://ldap2.xxxxxxx.net
ldap_search_base = dc=lan,dc=xxxxxxx,dc=net
ldap_user_search_base = ou=users,dc=lan,dc=xxxxxxx,dc=net

ldap_sasl_mech = GSSAPI
ldap_sasl_authid = host/test.xxxxxxx.net
ldap_krb5_keytab = /etc/ldap/ldap.keytab
ldap_krb5_init_creds = true

# -- SUDO provider --
sudo_provider = none

This is my LDAP configuration
# config
dn: cn=config
objectClass: olcGlobal
cn: config
olcArgsFile: /var/run/slapd/slapd.args
olcAuthzRegexp: {0}"uid=ldapadm,cn=XXXXXXX.NET,cn=gssapi,cn=auth" "cn=admin,
 dc=lan,dc=xxxxxxx,dc=net"
olcAuthzRegexp: {1}"uid=([^,]+),cn=gssapi,cn=auth" "uid=$1,ou=users,dc=lan,dc=
 xxxxxxx,dc=net"
olcAuthzRegexp: {2}"uid=([^,]+),cn=XXXXXXX.NET,cn=gssapi,cn=auth" "uid=$1,ou
 =users,dc=lan,dc=xxxxxxx,dc=net"
olcAuthzRegexp: {3}"uid=host/([^,]+).XXXXXXX.NET,cn=xxxxxxx.net,cn=gssapi,
 cn=auth" "cn=$1,ou=hosts,dc=lan,dc=xxxxxxx,dc=net"
olcDisallows: bind_anon
olcLogLevel: 256
olcPidFile: /var/run/slapd/slapd.pid
olcRequires: authc
olcSaslHost: ldap2.xxxxxxx.net
olcSaslRealm: XXXXXXX.NET
olcTLSCACertificateFile: /etc/ssl/openldap/certs/ca-chain-cert.pem
olcTLSCertificateFile: /etc/ssl/openldap/certs/ldap2-server-cert.pem
olcTLSCertificateKeyFile: /etc/ssl/openldap/private/ldap2-server-key.pem
olcTLSProtocolMin: 3.1
olcToolThreads: 1

# {0}config, config
dn: olcDatabase={0}config,cn=config
objectClass: olcDatabaseConfig
olcDatabase: {0}config
olcAccess: {0}to * by dn.exact=gidNumber=0+uidNumber=0,cn=peercred,cn=external
 ,cn=auth manage by * break
olcRootDN: cn=admin,cn=config

# {1}mdb, config
dn: olcDatabase={1}mdb,cn=config
objectClass: olcDatabaseConfig
objectClass: olcMdbConfig
olcDatabase: {1}mdb
olcDbDirectory: /var/lib/ldap
olcSuffix: dc=lan,dc=xxxxxxx,dc=net
olcAccess: {0}to attrs=userPassword,shadowLastChange by dn="cn=admin,dc=lan,dc
 =xxxxxxx,dc=net" write by dn="cn=sssdman,ou=manager,dc=lan,dc=xxxxxxx,dc=
 net" read by dn="cn=mailman,ou=vmail,ou=services,dc=lan,dc=xxxxxxx,dc=net"
 read by self write by anonymous auth by * none
olcAccess: {1}to dn.base="" by * read
olcAccess: {2}to dn.subtree="ou=vmail,ou=services,dc=lan,dc=xxxxxxx,dc=net"
 by dn="cn=admin,dc=lan,dc=xxxxxxx,dc=net" write by dn="cn=mailman,ou=vmail,
 ou=services,dc=lan,dc=xxxxxxx,dc=net" read by self write by anonymous auth
 by * none
olcAccess: {3}to dn.subtree="cn=krb5,ou=services,dc=lan,dc=xxxxxxx,dc=net" b
 y dn="cn=admin,dc=lan,dc=xxxxxxx,dc=net" write by dn="cn=adm-srv,cn=krb5,ou
 =services,dc=lan,dc=xxxxxxx,dc=net" write by dn="cn=kdc-srv,cn=krb5,ou=serv
 ices,dc=lan,dc=xxxxxxx,dc=net" read by * none
olcAccess: {4}to * by dn="cn=admin,dc=lan,dc=xxxxxxx,dc=net" write by dn="cn
 =sssdman,ou=manager,dc=lan,dc=xxxxxxx,dc=net" read by self write by anonymo
 us auth by * none
olcLastMod: TRUE
olcRootDN: cn=admin,dc=lan,dc=xxxxxxx,dc=net
olcRootPW: {SSHA}...

I'm struggling with this problem for two days now.
google was no help.
Can anybody help me to fix this?
Answer: Your olcAccess statements are too strict to allow the principal used by sssd to read that data that you want it to see.

The offending line is:
olcAccess: {4}to *
 by dn="cn=admin,dc=lan,dc=xxxxxxx,dc=net" write
 by dn="cn=sssdman,ou=manager,dc=lan,dc=xxxxxxx,dc=net" read
 by self write
 by anonymous auth
 by * none

You probably want something like:
olcAccess: {4}to *
 by dn="cn=admin,dc=lan,dc=xxxxxxx,dc=net" write
 by dn="cn=sssdman,ou=manager,dc=lan,dc=xxxxxxx,dc=net" read
 by dn.one="ou=hosts,dc=lan,dc=xxxxxxx,dc=net"
 by self write
 by anonymous auth
 by * none

This assumes your olcAuthzRegexp: {3} statement is working as you want it, but I'd check to make sure about that too. (kinit -k and ldapwhoami -Y will be your friends for that.)

You could also make a more specific olcAccess with to attrs=@posixAccount,@posixGroup by ....
Answer: Thank you very much for your answer. You are absolutely right.
I didn't think about an authentication error because there is no message about that in the logs.
When I change the olcAccess statement to
olcAccess: {4}to *
 by dn="cn=admin,dc=lan,dc=xxxxxxx,dc=net" write
 by dn="cn=sssdman,ou=manager,dc=lan,dc=xxxxxxx,dc=net" read
 by self write
 by anonymous auth
 by * read    <--- this works, but it is not what I want

it works.
Then changed my configuration according to your suggestions and everything is ok.
Here are the changes I made:

changed olcAuthzRegexp statement to

dn: cn=config
add: olcAuthzRegexp
olcAuthzRegexp: "uid=host/([^,]+).xxxxxxx.net,cn=gssapi,cn=auth" "cn=$1,ou=hosts,ou=sssd,ou=services,dc=lan,dc=xxxxxxx,dc=net"

dn: cn=config
add: olcAuthzRegexp
olcAuthzRegexp: "uid=host/([^,]+).xxxxxxx.net,cn=XXXXXXX.NET,cn=gssapi,cn=auth" "cn=$1,ou=hosts,ou=sssd,ou=services,dc=lan,dc=xxxxxxx,dc=net"

It is very important that these host entries are before the uid entries.
Otherwise you get a match for a host with the uid mapping.

changed olcAccess statement to

olcAccess: {4}to *
 by dn="cn=admin,dc=lan,dc=xxxxxxx,dc=net" write
 by dn="cn=sssdman,ou=manager,dc=lan,dc=xxxxxxx,dc=net" read
 by dn.one="ou=hosts,ou=sssd,ou=services,dc=lan,dc=xxxxxxx,dc=net" read
 by self write
 by anonymous auth
 by * none

added the host 'test' to the new location in the DIT

dn: cn=test,ou=hosts,ou=sssd,ou=services,dc=lan,dc=xxxxxxx,dc=net
cn: test
objectclass: device
objectclass: hostObject
objectclass: authorizedServiceObject
objectclass: top
authorizedService: host
host: test.nottebrok.net
description: Test Host

Comment: Edit: I moved the host olcAuthzRegexp before the uid olcAuthzRegexp. Now it works.


not working scanf() when the product has 2 or more words

Question: The code following 200 products found in supermarket selves. I want to write a code that at first shows all the available products and if you type one of them it returns the product, it's price and quantity.Τhe problem is that  if i type scanf("%s",insertproduct); it recognises only the products with one word. I saw in other posts that the solution is to write scanf("%[^\t\n]s",insertproduct);.
But when i do this the program ignores that scanf and terminates after the
printf("\nPlease select the desirable product to see it's quantity and price.\n\n");

One thought is to add _ between products with more than one word, but it will take a lot of time. Any thoughts about that particular scanf() ?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <io.h>
#include <conio.h>
#include <fcntl.h>
#include <locale.h>

struct supermarket
{
    char name[50];
    float price;
    int quantity;
};

int main(void) {
    struct supermarket product[200] = {
            {"sugar",1.2,127},
            {"greek coffee",2.03,200},
            {"milk",1.83,150},
            {"6pack small eggs",3.03,22},
            {"AAA bateries",2.2,20},
            {"AA bateries",2.3,29},
            {"6-pack big eggs",3.5,17},
            {"Frosties",4.5,30},
            {"All Bran",4.7,32},
            {"Special K",5.2,19},
            {"Honey Nut Loops",4.3,33},
            {"Coco Pops",4.09,28},
            {"White Bread",0.5,50},
            {"Black Bread",0.7,55},
            {"Toast Bread",1.73,66},
            {"cinamon",1.9,500},
            {"salt",1,423},
            {"pepper",1.29,325},
            {"coca cola 330ml",0.45,980},
            {"coca cola 500ml",0.9,745},
            {"coca cola 2lt",1.6,300},
            {"coca cola 1lt",1.3,1025},
            {"pepsi 330ml",0.45,980},
            {"pepsi 500ml",0.9,745},
            {"pepsi 2lt",1.6,300},
            {"pepsi 1lt",1.3,1025},
            {"7-up 330ml",0.6,682},
            {"fanta 330ml",0.4,741},
            {"fanta 1lt",1.1,120},
            {"fanta 500ml",0.75,267},
            {"mild mustard", 1.45,612},
            {"Hot mustard",1.85,387},
            {"Ketchup",1.6,400},
            {"mayonaise",2.1,346},
            {"apples",0.20,105},
            {"oranges",0.4,222},
            {"bananas",0.42,55},
            {"lettuce",0.12,141},
            {"potatoes 1kg",0.7,75},
            {"tomatoes",0.35,199},
            {"onions",0.11,425},
            {"grape-fruits",0.55,94},
            {"fresh salads",2.22,23},
            {"canned mushrooms",1.5,422},
            {"fresh mushrooms 200gr",1.98,55},
            {"oreos",1.59,257},
            {"Tide",2.47,730},
            {"Pampers",5.89,123},
            {"Mr Clean",5.01,35},
            {"Mr Proper",4.99,8},
            {"Kool-Aid",2.45,103},
            {"Knorr",3.05,308},
            {"Palmolive",3.01,617},
            {"Scotch-Brite",2.3,970},
            {"Cheetos",1.25,487},
            {"Top Ramen",6.27,109},
            {"Tomato sauce",0.59,1589},
            {"Goya Beans",3.21,300},
            {"Quaker Oats",3.39,32},
            {"Cream of Wheat",3.09,91},
            {"Nesquick",1.75,799},
            {"Silk Soy Milk",3.14,50},
            {"Philadelphia",4.15,6},
            {"Soy Sauce",1.09,45},
            {"A1 steak sauce",4.89,643},
            {"Barbeque sauce",5.79,94},
            {"Lays",2.5,567},
            {"Lays oregano",2.7,163},
            {"Pringles",1.85,421},
            {"Ajax",4.59,2548},
            {"Cleanex",5.27,941},
            {"Fountain",5.55,559},
            {"Mountain Dew",6.09,852},
            {"10 DVD",3.09,1896},
            {"Lipton ice tea",2.44,53},
            {"Lipton tea",1.29,633},
            {"Listerine",5.52,188},
            {"Centrum",9.99,588},
            {"Snapple",5.88,22},
            {"Purina 1",12.99,33},
            {"Wiskas",6.22,79},
            {"Pedigree Pal",9.99,10},
            {"Gatorade",2.13,1000},
            {"Amstel",0.99,111},
            {"Heineken",1.01,155},
            {"Guiness",1.8,77},
            {"McFarland",1.65,74},
            {"Estrella Damn",1.32,488},
            {"Stella Artois",0.87,14},
            {"Corona",1.11,347},
            {"Pilsner",1.74,166},
            {"Budweiser",1.77,654},
            {"Chimay Blue",2.12,344},
            {"Chimay Red",2.35,179},
            {"Chimay Black",2.55,333},
            {"Chimay Yellow",2.65,198},
            {"Beck's",1.72,188},
            {"Carlsberg",1.67,843},
            {"Paulaner",2.89,42},
            {"Erdinger",3.02,7},
            {"Colgate",1.75,644},
            {"butter",1.28,399},
            {"Peanut-Butter",2.74,211},
            {"PB&J",3.15,25},
            {"Barilla Linguini",2.58,941},
            {"Barilla spaghetti",1.56,357},
            {"Barilla tortellini",2.08,700},
            {"Barilla papardelle",3.58,9},
            {"Barilla lazagne",2.99,88},
            {"Advil",7.99,499},
            {"pears",0.26,2985},
            {"peaches",0.27,2456},
            {"Kiwi",0.36,2145},
            {"nectarines",0.38,2365},
            {"melon",0.39,951},
            {"watermellon",0.4,961},
            {"grapes",0.53,582},
            {"cherries",0.6,714},
            {"olives",0.09,936},
            {"pickles",0.87,195},
            {"halvah",1.33,2015},
            {"frulite orange-juice",1.61,478},
            {"frulite lemon-juice",1.62,477},
            {"frulite pineapple-juice",1.63,456},
            {"frulite carrot-juice",1.64,698},
            {"frulite banana-juice",1.65,874},
            {"frulite mixed-juice",1.66,599},
            {"rusks 160gr",1.35,588},
            {"rusks 320gr",2.03,589},
            {"rusks 400gr",2.72,523},
            {"rusks 500gr",3.74,542},
            {"vanila biscuits",3.30,699},
            {"cinamon biscuits",3.32,698},
            {"almond biscuits",3.35,612},
            {"butter biscuits",3.54,609},
            {"chocolate biscuits",3.41,59},
            {"cherry croissant",0.47,1025},
            {"apricot croissant",0.48,1058},
            {"chocolate croissant",0.41,1089},
            {"vanilla croissant",0.41,1054},
            {"vanilla-chocolate croissant",0.74,1036},
            {"cocoa croissant",0.27,1011},
            {"double-sized croissant",1.4,555},
            {"Derby",0.24,1000},
            {"Kinder Bueno",1.22,642},
            {"Kinder egg",0.91,377},
            {"Nivea hair-gel",5.88,417},
            {"Fructise hair-gel",5.97,429},
            {"Excellence hair-gel",4.88,437},
            {"mixed cake",3.99,11},
            {"chocolate cake",3.26,31},
            {"vanilla cake",3.36,44},
            {"orange cake",3.46,66},
            {"orange-chocolate cake",3.86,94},
            {"raisins cake",3.06,52},
            {"vakalaos",6.98,20},
            {"galeos",7.40,30},
            {"frozen shrimps",13.80,40},
            {"gavros",5.98,50},
            {"frozen octopus",6.36,90},
            {"fresh octopus",7.23,70},
            {"fresh shrimps",15.98,80},
            {"espresso",2.25,1896},
            {"6 chicken legs",6.66,11},
            {"2 chicken breasts",4.59,37},
            {"whole chicken",3.12,45},
            {"roasted chicken",4.97,48},
            {"capuccino",2.55,1478},
            {"jacobs vanilla",4.96,2458},
            {"jacobs chocolate",4.85,2365},
            {"jacobs caramel",4.87,2148},
            {"jacobs classic",4.59,1895},
            {"liquid fabric softener",5.22,1025},
            {"concentrated fabric softener",6.22,1048},
            {"noxzema saving foam 200ml",2.2,4832},
            {"loreal saving foam 200ml",2.6,613},
            {"nivea saving foam 200ml",2.8,2000},
            {"gillette saving foam 200ml",2.32,992},
            {"bic saving foam 200ml",2.13,469},
            {"noxzema saving foam 400ml",4.44,817},
            {"loreal saving foam 400ml",4.42,802},
            {"nivea saving foam 400ml",4.77,808},
            {"gillette saving foam 400ml",5.25,707},
            {"bic saving foam 400ml",5.21,303},
            {"Giotis baby-cream",7.10,111},
            {"Nounou baby-cream",7.05,223},
            {"Farin lacte baby-cream",6.82,334},
            {"Nutricia baby-cream",8.5,445},
            {"Ariel 5kg",22.5,556},
            {"Ariel 2kg",10.94,667},
            {"Ariel 1kg",5.31,778},
            {"Elvive shampoo",6.99,889},
            {"Wash and go shampoo",4.98,991},
            {"Proderm shampoo",7.22,882},
            {"Pantene shampoo",6.44,773},
            {"Fructis shampoo",7.13,664},
            {"Gliss shampoo",3.19,552},
            {"toilet paper 8 rolls",3.77,668},
            {"toilet paper 12 rolls",5.99,3},
            {"toilet paper 16 rolls",6.54,13}
    };

    int choise;

    printf("Please enter 1 and hit Enter to continue.\n");
    scanf("%d", &choise);

    int i;

    printf("See our full list of products.\n\n");
    for(i = 0 ; i < 200 ; i++){
        printf("%s\n", product[i].name);
    }
    char insertproduct[50];

    printf("\nPlease select the desirable product to see it's quantity and price.\n\n");
    scanf("%s", insertproduct);
    for (i = 0 ; i < 200 ; i++) {
        if(strcmp(product[i].name, insertproduct) == 0) {
            printf("You selected: %s. Price: %.2f euro. Quantity: %d items.\n\n",
                product[i].name,
                product[i].price,
                product[i].quantity);
        }
    }
    return 0;
}

Comment: try `scanf(" %[^\t\n]",insertproduct);`
Comment: Did you type all this by hand?
Comment: Have you heard about database systems?
Comment: I tried BLUEPIXY's proposal to try scanf(" %[^\t\n]",insertproduct); and it worked. The odd is that yesterday i tried to type scanf("%[^\t\n]",insertproduct); and it didn't work. It seems that the space between " and % makes the whole difference.
Answer: scanf() will stop reading when it finds a white space character, although you can fix your code and make scanf() work, I think in this case it is better to use fgets()
The clearStdin() function, in the following code has two tasks, first clear the '\n' and other possible spaces left by
scanf("%d", &choise);

If you input invalid data, to allow to repeat the call without causing an infinite loop, and then if the input is valid, take them too so that fgets() doesn't find a '\n' in the stream and returns with an empty string.
Try this corrected code
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct supermarket
{
    char name[50];
    float price;
    int quantity;
};

void clearStdin()
{
    int chr;
    while (((chr = getchar()) != EOF) && (chr != '\n'));
}

int main(void) {
    struct supermarket product[200] = {
            {"sugar",1.2,127},
            {"greek coffee",2.03,200},
            {"milk",1.83,150},
            {"6pack small eggs",3.03,22},
            {"AAA bateries",2.2,20},
            {"AA bateries",2.3,29},
            {"6-pack big eggs",3.5,17},
            {"Frosties",4.5,30},
            {"All Bran",4.7,32},
            {"Special K",5.2,19},
            {"Honey Nut Loops",4.3,33},
            {"Coco Pops",4.09,28},
            {"White Bread",0.5,50},
            {"Black Bread",0.7,55},
            {"Toast Bread",1.73,66},
            {"cinamon",1.9,500},
            {"salt",1,423},
            {"pepper",1.29,325},
            {"coca cola 330ml",0.45,980},
            {"coca cola 500ml",0.9,745},
            {"coca cola 2lt",1.6,300},
            {"coca cola 1lt",1.3,1025},
            {"pepsi 330ml",0.45,980},
            {"pepsi 500ml",0.9,745},
            {"pepsi 2lt",1.6,300},
            {"pepsi 1lt",1.3,1025},
            {"7-up 330ml",0.6,682},
            {"fanta 330ml",0.4,741},
            {"fanta 1lt",1.1,120},
            {"fanta 500ml",0.75,267},
            {"mild mustard", 1.45,612},
            {"Hot mustard",1.85,387},
            {"Ketchup",1.6,400},
            {"mayonaise",2.1,346},
            {"apples",0.20,105},
            {"oranges",0.4,222},
            {"bananas",0.42,55},
            {"lettuce",0.12,141},
            {"potatoes 1kg",0.7,75},
            {"tomatoes",0.35,199},
            {"onions",0.11,425},
            {"grape-fruits",0.55,94},
            {"fresh salads",2.22,23},
            {"canned mushrooms",1.5,422},
            {"fresh mushrooms 200gr",1.98,55},
            {"oreos",1.59,257},
            {"Tide",2.47,730},
            {"Pampers",5.89,123},
            {"Mr Clean",5.01,35},
            {"Mr Proper",4.99,8},
            {"Kool-Aid",2.45,103},
            {"Knorr",3.05,308},
            {"Palmolive",3.01,617},
            {"Scotch-Brite",2.3,970},
            {"Cheetos",1.25,487},
            {"Top Ramen",6.27,109},
            {"Tomato sauce",0.59,1589},
            {"Goya Beans",3.21,300},
            {"Quaker Oats",3.39,32},
            {"Cream of Wheat",3.09,91},
            {"Nesquick",1.75,799},
            {"Silk Soy Milk",3.14,50},
            {"Philadelphia",4.15,6},
            {"Soy Sauce",1.09,45},
            {"A1 steak sauce",4.89,643},
            {"Barbeque sauce",5.79,94},
            {"Lays",2.5,567},
            {"Lays oregano",2.7,163},
            {"Pringles",1.85,421},
            {"Ajax",4.59,2548},
            {"Cleanex",5.27,941},
            {"Fountain",5.55,559},
            {"Mountain Dew",6.09,852},
            {"10 DVD",3.09,1896},
            {"Lipton ice tea",2.44,53},
            {"Lipton tea",1.29,633},
            {"Listerine",5.52,188},
            {"Centrum",9.99,588},
            {"Snapple",5.88,22},
            {"Purina 1",12.99,33},
            {"Wiskas",6.22,79},
            {"Pedigree Pal",9.99,10},
            {"Gatorade",2.13,1000},
            {"Amstel",0.99,111},
            {"Heineken",1.01,155},
            {"Guiness",1.8,77},
            {"McFarland",1.65,74},
            {"Estrella Damn",1.32,488},
            {"Stella Artois",0.87,14},
            {"Corona",1.11,347},
            {"Pilsner",1.74,166},
            {"Budweiser",1.77,654},
            {"Chimay Blue",2.12,344},
            {"Chimay Red",2.35,179},
            {"Chimay Black",2.55,333},
            {"Chimay Yellow",2.65,198},
            {"Beck's",1.72,188},
            {"Carlsberg",1.67,843},
            {"Paulaner",2.89,42},
            {"Erdinger",3.02,7},
            {"Colgate",1.75,644},
            {"butter",1.28,399},
            {"Peanut-Butter",2.74,211},
            {"PB&J",3.15,25},
            {"Barilla Linguini",2.58,941},
            {"Barilla spaghetti",1.56,357},
            {"Barilla tortellini",2.08,700},
            {"Barilla papardelle",3.58,9},
            {"Barilla lazagne",2.99,88},
            {"Advil",7.99,499},
            {"pears",0.26,2985},
            {"peaches",0.27,2456},
            {"Kiwi",0.36,2145},
            {"nectarines",0.38,2365},
            {"melon",0.39,951},
            {"watermellon",0.4,961},
            {"grapes",0.53,582},
            {"cherries",0.6,714},
            {"olives",0.09,936},
            {"pickles",0.87,195},
            {"halvah",1.33,2015},
            {"frulite orange-juice",1.61,478},
            {"frulite lemon-juice",1.62,477},
            {"frulite pineapple-juice",1.63,456},
            {"frulite carrot-juice",1.64,698},
            {"frulite banana-juice",1.65,874},
            {"frulite mixed-juice",1.66,599},
            {"rusks 160gr",1.35,588},
            {"rusks 320gr",2.03,589},
            {"rusks 400gr",2.72,523},
            {"rusks 500gr",3.74,542},
            {"vanila biscuits",3.30,699},
            {"cinamon biscuits",3.32,698},
            {"almond biscuits",3.35,612},
            {"butter biscuits",3.54,609},
            {"chocolate biscuits",3.41,59},
            {"cherry croissant",0.47,1025},
            {"apricot croissant",0.48,1058},
            {"chocolate croissant",0.41,1089},
            {"vanilla croissant",0.41,1054},
            {"vanilla-chocolate croissant",0.74,1036},
            {"cocoa croissant",0.27,1011},
            {"double-sized croissant",1.4,555},
            {"Derby",0.24,1000},
            {"Kinder Bueno",1.22,642},
            {"Kinder egg",0.91,377},
            {"Nivea hair-gel",5.88,417},
            {"Fructise hair-gel",5.97,429},
            {"Excellence hair-gel",4.88,437},
            {"mixed cake",3.99,11},
            {"chocolate cake",3.26,31},
            {"vanilla cake",3.36,44},
            {"orange cake",3.46,66},
            {"orange-chocolate cake",3.86,94},
            {"raisins cake",3.06,52},
            {"vakalaos",6.98,20},
            {"galeos",7.40,30},
            {"frozen shrimps",13.80,40},
            {"gavros",5.98,50},
            {"frozen octopus",6.36,90},
            {"fresh octopus",7.23,70},
            {"fresh shrimps",15.98,80},
            {"espresso",2.25,1896},
            {"6 chicken legs",6.66,11},
            {"2 chicken breasts",4.59,37},
            {"whole chicken",3.12,45},
            {"roasted chicken",4.97,48},
            {"capuccino",2.55,1478},
            {"jacobs vanilla",4.96,2458},
            {"jacobs chocolate",4.85,2365},
            {"jacobs caramel",4.87,2148},
            {"jacobs classic",4.59,1895},
            {"liquid fabric softener",5.22,1025},
            {"concentrated fabric softener",6.22,1048},
            {"noxzema saving foam 200ml",2.2,4832},
            {"loreal saving foam 200ml",2.6,613},
            {"nivea saving foam 200ml",2.8,2000},
            {"gillette saving foam 200ml",2.32,992},
            {"bic saving foam 200ml",2.13,469},
            {"noxzema saving foam 400ml",4.44,817},
            {"loreal saving foam 400ml",4.42,802},
            {"nivea saving foam 400ml",4.77,808},
            {"gillette saving foam 400ml",5.25,707},
            {"bic saving foam 400ml",5.21,303},
            {"Giotis baby-cream",7.10,111},
            {"Nounou baby-cream",7.05,223},
            {"Farin lacte baby-cream",6.82,334},
            {"Nutricia baby-cream",8.5,445},
            {"Ariel 5kg",22.5,556},
            {"Ariel 2kg",10.94,667},
            {"Ariel 1kg",5.31,778},
            {"Elvive shampoo",6.99,889},
            {"Wash and go shampoo",4.98,991},
            {"Proderm shampoo",7.22,882},
            {"Pantene shampoo",6.44,773},
            {"Fructis shampoo",7.13,664},
            {"Gliss shampoo",3.19,552},
            {"toilet paper 8 rolls",3.77,668},
            {"toilet paper 12 rolls",5.99,3},
            {"toilet paper 16 rolls",6.54,13}
    };

    int  choise;
    int  i;
    char insertproduct[50];

    printf("Please enter 1 and hit Enter to continue.\n");
    while (scanf("%d", &choise) != 1)
    {
        printf("invalid, choice\n");
        printf("Please enter 1 and hit Enter to continue.\n");

        clearStdin();
    }
    clearStdin();

    printf("See our full list of products.\n\n");
    for (i = 0 ; i < 200 ; i++) {
        printf("%s\n", product[i].name);
    }

    printf("\nPlease select the desirable product to see it's quantity and price.\n\n");
    if (fgets(insertproduct, sizeof(insertproduct), stdin) != NULL)
    {
        size_t length;

        length = strlen(insertproduct);
        /* remove possible '\n' consumed by fgets */
        if (insertproduct[length - 1] == '\n')
            insertproduct[length - 1] = '\0';
        for (i = 0 ; i < 200 ; i++) {
            if (strcmp(product[i].name, insertproduct) == 0) {
                printf("You selected: %s.\n\tPrice: %.2f euro.\n\tQuantity: %d items.\n\n",
                    product[i].name,
                    product[i].price,
                    product[i].quantity);
            }
        }
    }
    return 0;
}

One thing you should know is that fgets() does read the '\n' character from the stream, so before comparison you should remove it from the array where you are holding the input string.
Comment: Some small ideas: No need to post all 200 line of data. 2) Suggest checking `length != 0` before `[length - 1]` 3) As the length is to be 1 less, why not `insertproduct[--length] = '\0'`? 4) minor: check `'\n'` first as in `while (((chr = getchar()) != '\n') && (chr != EOF));`


What is the correct way to write the model equation for a linear probability model?

Question: I'm trying to write down the equation describing a linear probability model.
If I was writing out the equation for an OLS model with continuous y with observation unit i , I would write:
$$y_i = \beta_0 + \beta_1 x_{i1} + \beta_2 x_{i2} + \epsilon_i  $$
If I were specifying the model for a probit model, I would write:
$$ Pr(y_i =1) = \Phi(\beta_0 + \beta_1 x_{i1} + \beta_2 x_{i2}) $$
or something thereabouts.
To be clear, a linear probability model is just an OLS model in which Y is a 0/1 indicator variable for some particular outcome. I know this is kind of a pedantic question, but how do you formally indicate in the first equation that $y_i$ is an indicator variable for an outcome just so that it's clear from the equation what you are doing?
Alternatively, is this a silly question and you just write the first equation and clarify the meaning of $y_i$ in the text?
edit: Maybe I'm encouraging too much analysis here. Simply put, what would be the reasonable equation to write down in a basic empirical driven paper to say "this is the form of the model and the relevant data items" where you were running a linear probability model?
Comment: @wildgunman The expectation of a 0/1 variable is the same as the probability its 1
Comment: [*Estimating equation*](https://en.wikipedia.org/wiki/Estimating_equations) is a term with a technical meaning. What you have here seem to be (partially specified) models.
Comment: Sorry, that's right. I'll edit the question.
Comment: Somehow your Wikipedia reference successfully manages to write down this model: what aspect of that reference, then, requires clarification?
Comment: @whuber I'm not sure that it does though. It writes $E[Y|X]$, which doesn't make it clear that Y is an indicator variable and then it writes $Pr(Y=1|X)$ which is a statement of probability rather than a factual statement of Y as an indicator variable. It strikes me that the correct thing to do is to explicitly declare Y as an indicator variable. Tell me why I'm wrong about this interpretation?
Comment: And indeed, Wikipedia explicitly declares $Y$ is an indicator.  What more is there to add?
Answer: You could write both regression models (and all others) the exact same way:  $Y | X= x \sim p(y|x)$, for some conditional distributions $p(y|x)$.  The case of binary $Y$ implies that these distributions are Bernoulli.
OLS is an estimation procedure, not a model. The distributions $p(y|x)$ are not specified by stating "OLS."
On the other hand, OLS is a good estimation procedure to use when the $p(y|x)$ are normal, homoscedastic, and have a conditional mean function that is a straight line.


Eval() for setting Form controls property

Question: I work on an Access VBA 2013 application, and this part of the project focuses on form controls and buttons.
I want to lock/unlock control modification thanks to buttons set aside.
For more genericity, I wanted the subs called by the events call homemade functions:
Sub LockAssociateControl(fctName As String, val As Boolean)
    Dim code As String
    code = "Forms!" & getModuleName & ".Controls!" & fctName & ".Locked = " & CStr(val)
    Debug.Print (code) 'just to test
    Eval code
End Sub

(getModuleName is also a homemade function that returns the right name of the module calling the function)
For example, this one is called like below:
Private Sub FirstName_Exit(Cancel As Integer)
    Call LockAssociateControl("FirstName", True)
End Sub

and in "code" variable, it sets "Forms!Module1.Controls!Name.Locked = True" (with Module1 generated by getModuleName, and Name as the parameter (I haven't found better yet)).
Now I want this code evaluated in order to avoid me from hard coding every event sub.
My problem is that an error occurs at the Eval() line and says:

Error Code: 2770. The object to which you reffered in the Visual Basic procedure as an OLE object is not an OLE object

I've looked around StockOverflow and others forums to find out what's wrong with Eval(), and I found that this function's behavior is not made for what I want. So I tried to find another way to do that, as Evaluate function doesn't exist in Access, etc, but I found nothing really helpful.
I tried to use DoCmd or Call or various transformations on the parameter string of Eval(), but nothing has worked so far...
So here's my question: Do any of you have a solution for that problem? And if not, do you know an alternative not to have to write in every event function full statements like: Forms!Module1.Controls!Name.Locked = False?
Comment: How about first testing if your approach works at all by hardcoding it? If that works, then try eval().
Comment: Due to my incapacity to find generic way to do, I indeed did a copied verion of the form I'm working on, and I'm currently dealing with this version to work other aspects of the code. That's a temporary solution but I hope not get stuck with this version forever, due to its non-flexibility.
Answer: You can do what you want easier without using Eval() ...
Sub LockAssociateControl(fctName As String, pVal As Boolean)
    Forms(getModuleName).Controls(fctName).Locked = pVal
End Sub

Note I changed the argument name from val to pVal to avoid confusing it with the Val() function.


C Coin Flip "You win/You lose" Message

Question: I'm starting with coding and just tried making a simple coin flip function. I tried to make it to show a "you win" or "you lose" message if you chose the right one, but it didn't work. What can I do?
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

typedef enum coin {HEADS, TAILS} coin;

coin flipCoin();

int main()
{
    char answer;

    printf("Choose HEADS or TAILS\n");
    scanf(" %c", &answer);

    if( (answer=='h') || (answer=='t') ) printf("Let's start:\n");
    else printf("Let's start anyway...\n");

    srand( time(NULL) );

    for (int i=0; i < 1; i++)
        if (flipCoin() == HEADS) printf("HEADS\n");
        else printf("TAILS\n");

    return 0;
}

coin flipCoin()
{
    if (rand() % 2 == 0 ) return HEADS;
    else return TAILS;
}

Edit: the code I used for "win/lose":
if((answer=='h') && (flipCoin()== HEADS)) printf("You win!\n");
else printf("you lose!\n");
if((answer=='t') && (flipCoin()== TAILS)) printf("You win!\n");
else printf("you lose!\n");

Comment: Where, in your code, is the attempt to show a "you win" or a "you lose" message?
Comment: What is the error?
Answer: You did not mention "you win" or "you lose" in your code. Mention it in

if (flipCoin() == HEADS) printf("HEADS\n");
else printf("TAILS\n");

Moreover, I didn't understand the need of for loop.
Comment: Oh sorry, I tried doing this
`if((answer=='h') && (flipCoin()== HEADS)) printf("You win!\n");
    else printf("you lose!\n");

    if((answer=='t') && (flipCoin()== TAILS)) printf("You win!\n");
    else printf("you lose!\n");`
Answer: The code you have posted doesn't seem to show that you have tried to display "you win" or "you lose". I'm not 100% sure why you decided to use a loop. I would have tried something similar to this:
coin result = flipCoin();
if(result== HEADS && answer == 'h'){
    printf("HEADS, you win!\n");
}else if(result == TAILS && answer == 't'){
    printf("TAILS, you win!\n");
}else{
    printf("You Lost");
}

The next thing you can try to do is allow the player to keep playing and count their score.
Comment: Oh sorry, I tried doing this `if((answer=='h') && (flipCoin()== HEADS)) printf("You win!\n"); else printf("you lose!\n"); if((answer=='t') && (flipCoin()== TAILS)) printf("You win!\n"); else printf("you lose!\n");`
Comment: But your idea worked, thank you!

C Coin Flip "You win/You lose" Message


Does $Re\left( \int_{\gamma} f \right) = \int_{\gamma} Re(f)$?

Question: I'm currently studying complex analysis. My current thinking is as follows:
Let $f(t)=x(t)+iy(t)$. By definition, $$\int_{\gamma} f(t) \, \mathrm{d}t = \int_{a}^{b} f(\gamma(t)) \gamma'(t) \, \mathrm{d}t$$
and so by substitution, $$\int_{\gamma} f(t) \, \mathrm{d}t = \int_{a}^{b}x(\gamma(t))\gamma'(t) \, \mathrm{d}t + i \int_{a}^{b} y(\gamma(t))\gamma'(t) \, \mathrm{d}t.$$
Thus, $$Re\left( \int_{\gamma} f \right) =\int_{a}^{b}x(\gamma(t))\gamma'(t) \, \mathrm{d}t.$$
Now, $$\int_{\gamma} Re(f(t))\, \mathrm{d}t = \int_{\gamma}x(t) \, \mathrm{d}t = \int_{a}^{b} x(\gamma(t))\gamma'(t) \, \mathrm{d}t.$$
We see that these expressions are indeed the same, and so $Re\left( \int_{\gamma} f \right) = \int_{\gamma} Re(f)$. This seems so straightforward, and I've been trying for ages to come up with a counter example, but I haven't been able to find one. What are your thoughts?
Comment: Yes, you should really avoid writing $\int_{\gamma} f$. Usually in the context of complex analysis we are working with $\int_{\gamma} f(z)\,dz$, but there are some situations where integrals such as $\int_\gamma f(z)\,|dz|$ also pop up.
Comment: The notation $\int_\gamma f$ can be a little misleading from a formal perspective.
Answer: This is not true. Take for example $\gamma$ as the unit circle and $f(z) = z$.
Then $\int_\gamma z\,dz = 0$, but
\begin{align}
\int_\gamma x\,dz &= \frac12\left(\int_\gamma z\,dz + \int_\gamma \bar z\,dz\right)\\
&= 0 + \frac12 \int_\gamma \frac{\bar z z}{z}\,dz \\
&= \frac12 \int_\gamma \frac{1}{z}\,dz = \pi i.
\end{align}
Comment: Great counter example! Thank you!
Answer: No: Define $f(x + iy) = iy$, and $\gamma$ is the line segment connecting $0$ and $i$. Then
$$\int_{\gamma} f = \int_0^1 (it) (i dt) = -\frac 1 2$$
On the other hand, $\Re{f} = 0$.

The flaw in the proof is that $\gamma'(t)$ need not be real.
Comment: Of course! $y'(t)$ need not be real, totally missed that. Owww... Thank you!


Noncommutative geometry (Notation)

Question:
The representation π in (6.35) can be extended to a surjective map
  $$\mathbb{I}⊗π : CC(\mathcal{E}) → C(\mathcal{E})$$ , (8.13) namely, any compatible
  connection is the composition of π with a universal compatible
  connection.

The above is taken from hep-th/9701078v1 page 121. I would like to know what does the notation $CC({E})$ stand for. Anyone familiar with the verbiage of noncommutative geometry please have a crack at it?
Answer: In the absence of a Hermitian connection on a right $\mathcal{A}$-module $\mathcal{E}$, $CC(\mathcal{E})$ denotes the affine space of all universal connections on $\mathcal{E}$ (p. 114); when $\mathcal{E}$ is also given a Hermitian structure, then, by slight abuse of notation, $CC(\mathcal{E})$ also denotes the affine space of all universal connections on $\mathcal{E}$ compatible with the Hermitian structure (p. 117), and this is the definition that's relevant on p. 121. What (8.13) is saying is that every connection on a finitely generated projection right $\mathcal{A}$-module $\mathcal{E}$ with respect to the noncommutative de Rham calculus induced by the spectral triple $(\mathcal{A},H,D)$ can be obtained as the "representation" of a universal connection on $\mathcal{E}$ (equivalently, can be lifted to a universal connection).

Noncommutative geometry (Notation)


Python e Kivy: Como selecionar e copiar todo o texto de um Text Input

Question: Olá!
Estou tentando aprender Kivy...
1) Gostaria de selecionar todo o texto dentro de um Text Input em Kivy. Qual atributo devo estudar para eu mesmo alterar meu código?;
2) Após selecionar todo o texto, o botão copiar deveria copiar o texto. Qual atributo devo estudar para eu mesmo alterar meu código?;
3) Assunto a parte: como fazer para  que os caracteres com acento sejam reconhecidos? Não sei nem como perguntar para pedir que me indiquem o que eu devo pesquisar para corrigir isso.
Exemplo arquivo: main.py
from kivy.app import App
class MainApp(App):
    def build(self):
        self.title = 'Meu primeiro app'
if __name__ == '__main__':
    MainApp().run()

Exemplo arquivo: main.kv
FloatLayout:
    Label:
        text: "Título do meu app"
        font_size: '60sp'
        top: 350
    TextInput:
        text: "Escreva aqui seu texto"
        height: "350px"
        width: 350
        top: 500
        size_hint: None, None
        pos_hint: {'center_x': 0.5,}
    Button:
        text: "Botão 1"
        height: 40
        width: 120
        top: 140
        size_hint: None, None
        pos_hint: {'center_x': 0.4,}
    Button:
        text: "Botão 2"
        height: 40
        width: 120
        top: 140
        size_hint: None, None
        pos_hint: {'center_x': 0.6,}
    Button:
        text: "Selecionar"
        height: 40
        width: 120
        top: 95
        size_hint: None, None
        pos_hint: {'center_x': 0.4,}
    Button:
        text: "Copiar"
        height: 40
        width: 120
        top: 95
        size_hint: None, None
        pos_hint: {'center_x': 0.6,}

Comment: A questão está clara e objetiva. Sobre o código concordo que poderia estar mais completo, porém, preferi apresentar só essa parte, pois é melhor apresentar algo limpo do que uma bagunça que nem eu estava entendendo. Eu não preciso que mexam no código. Apenas preciso de uma indicação: qual atributo para selecionar o texto eu devo estudar? Você pode fazer uma indicação?
Comment: já tentei até usar o exemplo dessa página ---> https://coredump.pt/questions/50433534/python-kivy-how-to-select-a-textinput-without-mouse-click <--- mas não funciona. Inclusive já tentei reproduzir igual como está, mas a janela fica toda preta.
Answer: Bom, seja bem vindo ao mundo kivy!

1) Gostaria de selecionar todo o texto dentro de um Text Input em Kivy. Qual atributo devo estudar para eu mesmo alterar meu código?;

Isso é possível com o método select_all() do TextInput ou então usar o atalho ctrl + a. Caso queira copiar somente um texto selecionado dentro do TextInput, use o método selection_text().
Exemplo:
BoxLayout:
    orientation: 'vertical'
    TextInput:
        id: texto
        hint_text: "Escreva aqui seu texto"
    Button:
        text: 'Selecionar'
        on_release:
            texto.select_all()

2) Após selecionar todo o texto, o botão copiar deveria copiar o texto. Qual atributo devo estudar para eu mesmo alterar meu código?;

Use o método copy(data='') do TextInput ou então usar o atalho ctrl + c. Com o método copy(data='') você pode passar um texto como atribuição para o parâmetro data copy(data = 'algum texto aqui') ou então caso você não passe nada, ele copiará tudo que estiver selecionado em seu TextInput. Exemplo:
Button:
    text: 'Copiar'
    on_release:
        texto.copy()

3) Assunto a parte: como fazer para que os caracteres com acento sejam reconhecidos? Não sei nem como perguntar para pedir que me indiquem o que eu devo pesquisar para corrigir isso.

Isso é possível carregando o script do kivy script.kv pelo Builder.load_string() modificando o encoding para utf-8. Exemplo:
home.kv
<Home>:
    orientation: 'vertical'
    Label:
        text: 'ÁLGÙÑ TÊXTÕ CÓM ÀCENTÛAÇÃO!!!'

home.py
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.boxlayout import BoxLayout

class Home(BoxLayout):
    pass

with open('home.kv', 'r', encoding = 'utf8') as screen:
    Builder.load_string(screen.read())

class MainApp(App):
    def build(self):
        return Home()

MainApp().run()

Pra finalizar, segue um exemplo sintetizado com todas as suas perguntas:
main.py
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.boxlayout import BoxLayout

for nome in ['home']: # Dessa maneira você consegue chamar mais telas
    with open(f'{nome}.kv', 'r', encoding = 'utf8') as tela:
        Builder.load_string(tela.read())

class Home(BoxLayout): pass

class MainApp(App):
    def build(self):
        return Home()

if __name__ == '__main__':
    MainApp().run()

home.kv
<Button>:
    font_size: sp(30)

<Home>:
    orientation: 'vertical'
    TextInput:
        id: texto
        size_hint: 1, .8
        hint_text: "Escreva aqui um textão!"
        font_size: sp(30)
    BoxLayout:
        size_hint: 1, .2
        Button:
            text: 'Selecionar'
            on_release:
                texto.select_all()
        Button:
            text: 'Copiar'
            on_release:
                texto.copy()
        Button:
            text: 'Colar'
            on_release:
                texto.paste()

Animação do Exemplo:

Referências:

https://github.com/kivy/kivy/issues/4003
https://kivy.org/doc/stable/api-kivy.uix.textinput.html#kivy.uix.textinput.TextInput.selection_text


Is it possible to model with a linear regression the relationship between a dependent continuous variable and an independent categorical variable?

Question: I raised this question after a project that I made on DataCamp.com where a linear regression was trained to model the relationship between movie genre revenues (dependent variable) and movie genre(independent variable).
The first answer I gave to myself is No.
As a self-taught data scientist, I wanted to prove it, and I spent several days reading questions and trying to understand where formally was the fallacy.
Dataset Composition
We have a dataset containing some of the Disney Films since 1935 and their inflation-adjusted revenues, movie rating, and movie genre; the dataset is freely available here.
The dataset is not complete just as an example Dumbo-Robin Hood-Bambi are missing.
Goal
Build a linear regression model to predict the adjusted gross using dummy variables obtained from movie genres.
From the regression model, check the effect of each genre by looking at its coefficient given in units of box office gross dollars.
Process and Thesis
"Since linear regression requires numerical variables and the genre variable is a categorical variable, we will use a technique called one-hot encoding to convert the categorical variables to numerical. This technique transforms each category value into a new column and assigns a 1 or 0 to the column.
For this dataset, there will be 11 dummy variables, one for each genre except the action genre which we will use as a baseline. For example, if a movie is an adventure movie, like The Lion King, the adventure variable will be 1 and other dummy variables will be 0.
Since the action genre is our baseline, if a movie is an action movie, such as The Avengers, all dummy variables will be 0."
But mathematically what happens?
If we call $y$ our target, $\theta_i$ our coefficients and $x_i$ our dummy variables we will have the following equation:
$$y=\theta_0*x_0 + \theta_1*x_1 + \theta_2*x_2 + ... + \theta_n*x_n  $$
So what happens when we want to estimate the value of a genre, like an horror movie based on our hypothesis:
$$y_{horror}=\theta_{action} + \theta_{adventure}*x_{adventure} + \theta_{musical}*x_{musical} + ... + \theta_{horror}*x_{horror}  $$
The author used the action movies as baseline. So it follows:
$$y_{horror}=\theta_{action} + 0 + 0 + ... + \theta_{horror}*x_{horror}  $$
Answer: Yes - we call it an ANOVA, which is just linear regression with categorical predictors.
Answer: Linear regression is a linear model used to represent the relationship between one or more explanatory or independent variables and the target variable also called the dependent variable.
Linear regression has some assumptions:

Variables should be normally distributed
Independent variable should have linear and additive relationship with the target
There should be no linear relationship among the independent variables
Target should not be autocorrelated
Homoscedasticity should not be there in data

The main reason why is not possible to model a linear regression between a Continuous Variable and a categorical variable is in point 2.
In fact, the Pearson Correlation Coefficient will be 0 in that situation or something near to it.
$$\rho_{XY}= {Cov_{XY}\over \sigma_x*\sigma_y}$$
The best estimator, the one that reduces the error between the estimated value and the actual value of a film, based on movie genre is the sample mean.

An intuitive representation of what happens when you try to model a linear regression with just a categorical variable is the following:

Moreover, instead of creating one singular estimator for the 12 genres, I created a specific estimator for each genre, and obviously, an exception in 1 case the MSE was lower.
Here the original notebook.
Here my notebook.
One further work is to conduct an ANOVA analysis and to evaluate if there is a sensible difference in the variance and mean of each movie genre.
The same concept can be applied to the value of a house based only on the neighborhood/district where is located.
I will really happy if my demonstration is correct, or if I am missing something due to my lack of knowledge and If there is any gap I have to abridge.
Comment: I'm not sure why you say that (2) is violated. As far as I can see it's clearly fulfilled. My main question about using linear regression (without any transformations) would really rather about the error distribution, amongst other issues linear regression would allow for negative revenue (I guess depending on the definition that's possible), variation might be lower in low revenue genres and higher in higher grossing genres.


Disable all but RC4 in apache

Question: Our PCI compliance vendor requires that we disable all but RC4 encryption on our web server.  Currently our apache config file looks like this:
SSLHonorCipherOrder On
SSLCipherSuite RC4-SHA:HIGH:!ADH:!AES256-SHA:!ECDHE-RSA-AES256-SHA384:!AES128-SHA:!DES-CBC:!aNull:!eNull:!LOW:!SSLv2

However, https://www.ssllabs.com reports the following ciphers are allowed:

TLS_RSA_WITH_RC4_128_SHA
TLS_DHE_RSA_WITH_AES_256_CBC_SHA
TLS_DHE_RSA_WITH_AES_128_CBC_SHA
TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA
TLS_RSA_WITH_3DES_EDE_CBC_SHA

How can I configure apache to only allow RC4?
Comment: Oh, in that case they're idiots and you should go find another vendor.
Comment: What @MichaelHampton said. Your auditor's understanding of security (at least WRT crypto algorithms) is fundamentally flawed (and it's worth noting that RC4 (at least RC4-CBC) has its own theoretical flaws. You should find an auditor who understands this stuff a bit better, or bone up on it enough to argue them into submission...
Comment: Disable all but RC4? That's a new one. [Mitigating BEAST only requires that RC4-SHA be the first cipher offered](http://blog.phonefactor.com/2011/09/23/slaying-beast-mitigating-the-latest-ssltls-vulnerability/), which you had already done, not disabling everything else.
Comment: I didn't really want to do it, but when I called them, they insisted on only having RC4 enabled. (I think they would allow TLS 1.1 or 1.2 ciphers, but few clients support those)
Answer: Interesting how things change.   This is an old message but shows up in google searches so I should add that RC4 is now (2015) considered insecure and should not be used at all for PCI compliant sites.
Answer: Turns out it was pretty easy.  The "High" option in my original question was including the other ciphers.  By reducing it to the following, I got what I wanted:
SSLCipherSuite RC4-SHA

Comment: The reason for that was the allow of `HIGH`, which adds all of the ciphers from that set.
Answer: 403 labs is my PCI DSS compliance scan vendor.  They require only RC4-SHA for SSL 3.0 and TLS 1.0.  Their reasoning is that moving RC4-SHA to the top is the server preferred cipher suite not the clients.  So the client could negotiate a block cipher on the list that is vulnerable to beast.  Which all TLS 1.0 CBC ciphers are.
On my Apache server I only have RC4-SHA enabled.  On my IIS boxes I have RC4-SHA plus all the TLS 1.2 only ciphers enabled.

Disable all but RC4 in apache


Criação de vetor em c++

Question: O que signifia o new int[2] em
int* vetor = new int[2];
Comment: Será alocada uma área de memória que comporta 2 int e vetor apontará para o início desta área.
Comment: É uma forma embutida na linguagem de fazer malloc(2 * sizeof(int)), que é como se faria em C.
Answer: Significa que você esta criando um vetor de 2 posições, o valor dentro dos colchetes indica o tamanho que você quer utilizar para a criação do vetor.

Criação de vetor em c++


django.core.exceptions.ImproperlyConfigured: You're using the staticfiles app without having set the STATIC_ROOT setting to a filesystem path

Question: Estou tentando adicionar a minha aplicação ao heroku, para que esteja disponível na web. Mas na hora de fazer o deploy recebo a seguinte mensagem de erro:
django.core.exceptions.ImproperlyConfigured: You're using the staticfiles app without having set the STATIC_ROOT setting to a filesystem path.

Error while running '$ python manage.py collectstatic --noinput'.

Já fiz diversas procuras na internet sobre essa mensagem de erro, ja alterei varias vezes o STATIC_ROOT , testei também com STATIC_URL mas nada resolve meu problema.
Segue abaixo o trecho de código do settings.py responsável pelo static.
if os.getcwd() == '/app':
   import dj_database_url
   DATABASES ={
    'default': dj_database_url.config(default='postgres://localhost')
   }

  #Honra o cabeçalho 'X-Forwarded-Proto' para request.is_secure()
  SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')

  #Cabeçalho para permitir todos os hosts
  ALLOWED_HOSTS = ['*']

  #Configurações de recursos estáticos
  BASE_DIR = os.path.dirname(os.path.abspath(__file__))

  STATIC_ROOT = 'staticfiles'

  STATICFILES_DIRS = (
     os.path.join(BASE_DIR, 'static'),
  )

Trecho do código do wsgi.py
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'learning_log.settings')

application = Cling(get_wsgi_application())

E a organização dos arquivos e pasta está disposta nessa maneira:
-learning_log
     ---learning_log
     -----settings.py
     -----wsgi.py
     -----static
     --------placeholder.txt (.txt apenas para não deixar o static vazio)

Answer: Tenta adicionar o "/" antes do nome, assim por exemplo:
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')

Caso seja a versão mais recente do Django use
STATIC_URL = '/static/'
STATIC_ROOT = BASE_DIR / 'staticfiles'

E caso tenha arquivos estáticos dentro de uma app
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'app1/static'),
    os.path.join(BASE_DIR, 'app2/static')
]


Associative law is not self evident

Question: The statement:
"It is important to understand that the associative law is not
self-evident; indeed, if $a*b=a/b$ for positive numbers $a$ and $b$
then, in general, $(a*b)*c\ne a*(b*c)$." - p. 3, A. Beardon, Algebra
and Geometry.
I am unclear as to how to take the assumption $a*b=a/b$. Does he mean
that we suppose, as an alternative (thought experiment),
that $a*b :=
a/b$ and substitute
$(a/b)$ for each $(a*b)$ and prove the inequality of the resulting
statement? Or, should one notice that
$a*b=a/b$ is true when $b=1$, but then note that the domain was
assumed to be
 $\mathbb{R}_+$, therefore $(a*b)*c \ne a*(b*c)$ in general?
Comment: You take it as an example.
Comment: $*$ isn't multiplication here. The author is asking you to suppose you have a group where the binary operation (written $*$) is the division operation.   The author could have said, "suppose $*$ is $/$, i.e., division."
Comment: An addendum that could be added to most of the answers is that mathematicians very rarely write $*$ for ordinary multiplication. For expressions $X$ and $Y$, "$X$ times $X$" is commonly written $XY$, $X\cdot Y$ or $X\times y$ but seldom $X*Y$. $*$ is a programming language thing.
Answer: You are basically right in your guesses. What is being emphasized is that not all binary operations (i.e. things that take two inputs from your set and return a third element of the set) that one can define are necessarily associative just because they are binary operations. In this example they are saying that if you define the particular example of a binary operation, to which they give the name $*$, on the set $\Bbb R^+$, as in this example, i.e. $a*b={a\over b}$, then
$$(a*b)*c={{a\over b}\over c}={a\over bc}$$
and
$$a*(b*c)={a\over {b\over c}}={ac\over b}$$
by direct computation.
At this point you might object and say "but doesn't $*$ mean multiplication?" If so, you can replace the symbol $*$ by another one if it helps you, $\oplus$ is a nice one as well, the point is it's the binary operation we've defined, no matter what it looks like on paper as a symbol.
Now, by definition two real numbers, $x,y\in\Bbb R$, the definition of equality is

$$x=y\iff x-y=0$$

and given two fractions, ${p\over q}, {r\over s}\in\Bbb R^+$ the definition of equality is

$${p\over q}={r\over s}\iff ps-qr=0.$$

In your case:
$${a\over bc}-{ac\over b}=0$$
$$\iff {a\over bc}={ac\over b}$$
$$\iff ab-abc^2=0$$
$$\iff ab=abc^2$$
for every $a,b,c\in\Bbb R^+$, however this condition clearly requires $c^2=1$ which is only true for $c=1$ over the positive real numbers, so the operation is not associative, because the relation only holds for a single positive real number, $c=1$, rather than all positive reals.
Comment: Very comprehensive, thank you Adam!
Comment: One of the best answers I've seen to a question.
Answer: Here, the $*$ represents an arbitrary binary operation, not multiplication as you think. The definition of $*$ is a map $\mathbb{R}_+ \times \mathbb{R}_+ \rightarrow \mathbb{R}_+$ that is defined by $*(a,b)=\frac{a}{b}$. Now, $a*b$ is just an alternate way of representing $*(a,b)$.
Now why isn't $*$ associative? Well, we have $(a*b)*c=(a/b)*c=(a/b)/c=\frac{a}{bc}$, and $a*(b*c)=a*(b/c)=a/(b/c)=\frac{ac}{b}$, hence $(a*b)*c \not= a*(b*c)$.
Comment: Fujoyaki, not sure how it happened, but your answer, which was more timely than some others but didn't show up until much later upon a third refresh of the browswer. Very nice answer and wording, thank you!
Answer: I think you're assuming that * means multiplication. But in this situation it represents a general binary operation, and in particular, division.
Comment: Thank you anon, you nailed it. I could only give the answer to one (due to shortcomings in this SE system IMHO), but I surely appreciate your help (and fast!).
Comment: @Joe Ah yes, the only-one-answer "shortcoming." That is a fight you will not win. (To give the policy its due, I do think it's helped keep SE sites remain *Q&A* focused rather than devolving into discussion forums.)
Answer: In general, without making any assumptions, $\ast$ stands just for a group operation. In your cited example, it is defined to be division. Therefore, in this case, $(a \ast b) \ast c = (a/b)/c \neq a/(b/c) = a \ast (b \ast c)$, except for trivial cases.
Comment: herrsimon, I am torn because you gave the answer succinctly and, as I now see, correctly, with the case worked out. I'd give you the answer too if I could. I was helped by some of the additional details Adam provided. Clearly, you also provided the answer. I wish this was just a points system and not only one getting the answer credit. All three responses were the answer, just varying levels of comprehensiveness/length. I appreciate succinct too! My intent was to give you two points, anon 1, and Adam the answer. Alas, somehow I gave you one and anon 2 and I can't yet change that.

Associative law is not self evident


Python Unicode in files

Question: I can't get a grip on how Python handles Unicode in files...
f = open('test.txt', 'w')
f.write('abc')
f.close()

That gives a file of 3 bytes.
f = open('test.txt', 'w')
f.write('abcé')
f.close()

That gives a file of 5 bytes (the é takes up two bytes but how does Python knows that it must read 2 bytes there?)
f = open('test.txt', 'w')
f.write('abcそ')  # a Japanese character
f.close()

That gives a file of 6 bytes (the そ takes up three bytes but how does Python knows that it must read 3 bytes there?)
So I can understand that Unicode takes two bytes, but it is sometimes 1, or 2 or 3 bytes, I fail to see how it works.
Comment: I don't know why this matters but that's not a Chinese character.
Comment: http://en.wikipedia.org/wiki/Variable-length_code, http://en.wikipedia.org/wiki/UTF-8
Comment: oops ... you're right it's Japanese, changed the comment...
Comment: Besides the Wikipedia links, there is also [this article by Joel Spolsky](http://www.joelonsoftware.com/articles/Unicode.html).
Comment: @John, thanx I have that book on the shelf ;-) just wasn't aware that the .write defaults to utf-8... however I should have known...
Answer: By default, it writes the output file with an encoding of UTF-8, which is a variable-length encoding: it encodes ASCII characters (code points U+0000-U+007F) using 1 byte, code points U+0080-U+07FF (which includes Latin-1 characters such as é) using 2 bytes, code points U+0800-U+FFFF (which includes Chinese and Japanese characters such as そ) using 3 bytes, and code points U+10000-U+10FFFF using 4 bytes.
If you want to use a different encoding, such as UTF-16, you can use str.encode to use your desired encoding:
# Save the string as UTF-16 little-endian
f = open('test.txt', 'w')
f.write(u'abcそ'.encode('utf-16le')  # Output will be 8 bytes
f.close()

Comment: It's not so much what `write` does but rather how the interpreter interprets your code: your code is likely being saved to disk by your editor in UTF-8, so when the interpreter reads it, it sees a UTF-8 string literal, so that's what gets passed through to the file.
Comment: thanks, the documentation http://docs.python.org/tutorial/inputoutput.html says nothing that the write defaults to utf-8, but this explains it all.
Comment: It was the python interpreter I used, so that defaults to UTF-8, thanx again!

Python Unicode in files


Login no Wordpress com WebService (AD)

Question: Tenho um página em PHP que conecta a um WebService e efetua a validação do usuário no AD.
Gostaria que esta pagina fosse chamada quando fosse digitado a o URL do site feito em WordPress, pois nela crio os cookies:

<?php
if(isset($_POST['login']) && isset($_POST['senha'])) {
if (empty($_POST['login']) || empty($_POST['senha']) ) {
 $error = 'Preencha todos os campos.';
} else {
 $client = new SoapClient('http://endereco-do-webservices/servico.asmx?WSDL', array('login'=> "usuario-servico",'senha'=> "******"));
    $vars = $client->Autentica(array('login' => stripslashes($_POST['login']), 'senha' => $_POST['senha']));
    if($vars->AutenticaResult == true) {
  $var = $_POST['login'];
        $dominio = preg_split('/\\\/', $var, -1, PREG_SPLIT_NO_EMPTY);
        if($dominio[0]==$var){
            $dominio[0] = 'meu-dominio';
            $dominio[1] = $var;
        }
  $search = $client->BuscaLogin(array('dominio'=>$dominio[0],'login' => $dominio[1]));
  $email = $search->BuscaLoginResult->Mail;
  $nome = $search->BuscaLoginResult->Nome;
  $dominiofin = $search->BuscaLoginResult->Dominio;
  setcookie("MyAuth", 'true', time()+50400);
  setcookie("MyMailAuth", $email, time()+50400);
  setcookie("MyNomeAuth", $nome, time()+50400);
  setcookie("MyDominioAuth", $dominiofin, time()+50400);
  header("location: /meu-site");
 } else {
  $error = 'Login inválido';
 }
}
}
?>

 <!DOCTYPE html>

  <meta charset="UTF-8">
  <meta content="IE=10" http-equiv="X-UA-Compatible" />
  <title>Verifica Login</title>

  <meta name="viewport" content="width=device-width, initial-scale=1.0">

 <?php if($error) {
echo '';
} ?>
<img src="<?php bloginfo('template_url'); ?>/img/mylogo.png" alt="">
<form method="post">
 <input type="text" name="login" placeholder="Login" />
 <input type="password" name="senha" placeholder="Senha" />
 <input type="submit" value="Entrar">
</form>

Que são validados no header.php do tema:

<?php
if(!isset($_COOKIE['AGAuth'])) {
 $url = bloginfo('template_url');
 header('Location:'.$url.'?page_id=73');
 exit();
}
?>

Com ligar um registro da tabela wp_posts a uma página PHP na pasta do tema.
Answer: Você não precisa de uma página pra isso, pode só rodar o código em um hook bem cedo na inicialização, como after_setup_theme, por exemplo:
// no arquivo functions.php
add_action( 'after_setup_theme', 'inicializa_cookies' );
function inicializa_cookies() {
    setcookie("MyAuth", 'true', time()+50400);
    // etc
}

Nesse caso o código rodaria em 100% dos page loads, logo que o tema é carregado.
Comment: Muito obrigado pela resposta. Mas quero setar os cookies somente quando for informados um login e senhas validado no AD. Por isso queria executar um página que já existe e faz a validação.
Comment: A resposta do AD vai pra uma URL específica? Como o WP sabe que recebeu essa informação?
Comment: Editei a resposta e coloquei o código da página que faz a validação no AD. Na verdade a página faz e validação e funciona corretamente. O que preciso é sempre que acessar o site o WordPress redirecione para esta página que se chama autentica.php. Se o usuário fo valido ser criado os cookies e o acesso concedido.

Login no Wordpress com WebService (AD)


Trying to prove a result about sequencse and series

Question:
Suppose $\lim_{n \to \infty} a_n = L$ finite, then
$$ \lim_{x \to \infty} e^{-x} \sum_{n=0}^{\infty} \frac{ a_n x^n }{n!}
 = L $$

Try:
we know $a_n x^n = ( \sqrt[n]{a_n} x )^n $. So, we can write the series as exponential
$$ \lim_{x \to \infty} e^{-x} e^{\sqrt[n]{a_n} x} = \lim \frac{e^{x}}{e^{ -\sqrt[n]{a_n} +1} }$$
but, here I am stuck. Is my idea right? or am I on the wrong track?
Comment: I don't see how to make your approach work. Are you familiar with $\epsilon \delta$ proofs?
Comment: Should be summing up all $a_i$ aswell?
Comment: Have you tried pushing e^-x inside and taking a natural log?
Answer: Let $\epsilon>0$ and let $N$ be large enough that $|a_n-L|<\epsilon$ for $n\geq N$. Then
\begin{align}|e^{-x}\sum_{n\geq 0} a_n \frac{x^n}{n!} - L| &=e^{-x}|\sum_{n\geq0} (a_n-L)\frac{x^n}{n!}|\\& =e^{-x}|\sum_{N>n\geq0} (a_n-L)\frac{x^n}{n!}+\sum_{n\geq N} (a_n-L)\frac{x^n}{n!}|\\&
\leq e^{-x}|\sum_{N>n\geq0} (a_n-L)\frac{x^n}{n!}|+e^{-x}\sum_{n\geq N} |a_n-L|\frac{x^n}{n!} \\& \leq e^{-x}|\sum_{N>n\geq0} (a_n-L)\frac{x^n}{n!}|+ e^{-x}\epsilon \sum_{n\geq N}\frac{x^n}{n!}\\
&\leq  e^{-x}|\sum_{N>n\geq0} (a_n-L)\frac{x^n}{n!}|+\epsilon.\end{align}
Letting $x \rightarrow \infty$,
$$\limsup_{x\rightarrow \infty}|e^{-x}\sum_{n\geq 0} a_n \frac{x^n}{n!} - L|\leq \epsilon,$$
and finally the result follows by letting $\epsilon \rightarrow 0$.


Making File Field description required

Question: My users always skip adding the "description" to the file field because they can. I tried implementing the code posted here:
How do I make Drupal File Description Field Required?
(and thank you) -- but I have a question. My users now do see a red asterisk suggesting that the description is required ... but if they do not enter a description, they may still click save and create the node ... with no description entered in the box. Any ideas on how to get this to really force the issue and require the description?
Answer: If you like you can add to the hook_field_widget_form_alter and then add a validation callback:
  $form['#validate'][] = 'my_validate_function';

Then create a my_validate_function($form, &$form_state) which contains a check on the values and calls a form_set_error($name, $message) if a value is wrong or missing.
/**
 * Implements hook_field_widget_form_alter().
 */
function MYMODULE_field_widget_form_alter(&$element, &$form_state, $context) {
  if ($context['field']['field_name'] == 'field_MYFIELD' && $context['instance']['widget']['type'] == 'file_generic') {
    $context['form']['#validate'][] = 'my_validate_function';
  }
}

/**
 * Require description to be set.
 */
function my_validate_function($form, &$form_state) {
  if ($form_state['values']['description'] == '') {
    form_set_error('description', 'Description must not be empty.');
  }
}

This may need to be changed above:
$form_state['values']['description']

Comment: this is probably good direction ... but I can't figure out how to append this info to the other code snippet / custom module. I tried googling drupal form validation for required fields, but could not work it out.

Making File Field description required