text:
Q: Is it important for statisticians to learn machine learning? Is machine learning an important subject for any statistician to become acquainted with? It seems that machine learning is statistics. Why don't statistics programs (undergraduate and graduate) require machine learning?

A: Machine learning is about gaining knowledge/learning from data.  For example, I work with machine learning algorithms that can select a few genes that may be involved in a particular type of disease from DNA Microarray data (e.g. cancers or diabetes).  Scientists can then use these genes (learned models) for early diagnosis in the future (classification of unseen samples).
There is a lot of statistics involved in machine learning but there are branches of machine learning that do not require statistics (e.g. genetic programming).  The only time you would need statistics in these instances would be to see if a model that you have built using machine learning is statistically significantly different from some other model.
In my opinion, an introduction to machine learning for statisticians would be advantageous.  This will help statisticians to see real world scenarios of application of statistics.  However, it shouldn't be compulsory.  You may become a successful statistician and spend your whole life without ever having to go near machine learning!

A: Machine Learning is a specialized field of high dimensional applied statistics. It also requires considerable programming background which isn't necessary for a good quantitative program, especially at the undergraduate level but also to some extent at the graduate level. It has application only to the prediction aspect of statistics, whereas mathematical statistics as well as inferential and descriptive applied statistics require attention. Many programs offer students the chance to have a great deal of exposure to machine learning (CMU for instance), but industrial statisticians on the whole rarely get the chance to apply these tools, barring certain high profile tech jobs.
While I have recently seen many data scientist and machine learning positions in the job market, I think the general job description of "statistician" does not require a machine learning background, but does require an impeccable understanding of basic statistics, inference, and communication: these should really be the core of a graduate statistics program. Machine learning and data science are also relatively new as job titles and as disciplines. It would be a disservice to those seeking employment as statisticians to sway their problem solving strategies toward machine learning if it's mostly abandoned in business/pharma/bioscience enterprise for underwhelming efficacy in 10 or 20 years.
Lastly, I don't feel that machine learning tremendously enhances a solid understanding of statistics. Statistics is fundamentally a cross-disciplinary field and it's important to communicate and convince non-technical experts in your field (such as doctors, CFOs, or administrators) exactly why you chose the methodology you did choose. Machine learning is such a niche, highly technical field that, in many applied practices, only promises incrementally better performance than standard tools and techniques. Many of the methods in supervised and unsupervised learning are perceived by non-experts (and even some less trained experts) as "black box". When asked to defend their choice of a specific learning method, there are explanations that fall flat and draw on none of the applied problem motivated circumstances. This is a great risk to advising any decision making process.

A: OK, let's talk about the elephant of statistics with our sight blindfolded by what we've learnt from one or two people we've closely worked with in our grad programs...
Stat programs require what they see fit, that is, what is the most important stuff they want their students to learn given a limited amount of time the students will have on the program. Requiring one narrow area means kissing goodbye to some other areas that can be argued to be equally important. Some programs require measure theoretic probability, some don't. Some require a foreign language, but most programs don't. Some programs take Bayesian paradigm as the only thing worth studying, but most don't. Some programs know that the greatest demand for statisticians is in survey statistics (at least that's the case in the US), but most don't. Biostat programs follow the money and teach SAS + the methods that will sell easily to medical and pharma sciences.
For a person designing agricultural experiments, or collecting survey data via phone surveys, or validating psychometric scales, or producing disease incidence maps in a GIS, machine learning is an abstract art of computer science, very distant from statistics that they work with on a daily basis. None of these people will see any immediate benefit from learning support vector machines or random forests.
All in all, machine learning is a nice complement to other areas of statistics, but I would argue that the mainstream stuff like multivariate normal distribution and generalized linear models need to come first.


text:
Q: Flushing sequentially HTML table rows with Symfony/Twig I am adapting a standard HTML/PHP code to Symfony 4.4/Twig.
The adapted code runs fine except a part where a HTML table that is sequentially updated by flushing the output buffer (every 1-2 sec, as soon as new row data is available):
echo "
 Element1	 …  ElementN
";
ob_flush(); flush();

I can render the complete table (when all rows are available) through a Twig template in a controller with return $this->render('template.html.twig');, BUT I am unable to update the HTML page for displaying the table row by row as in the original code. This is blocking as I need to get results on the fly, not waiting for hours to see the first rows.
I unsuccessfully tried the Twig {% flush %} command place right after the  tag in the template as suggested here: Flushing output before rendering completed in Symfony/Twig
Could you please provide me suggestions to progress?
Thanks by advance.

A: After few new investigations, I understand much better the issue, and I found an acceptable workaround.
The behavior difference comes from the output data buffering of the tool chain: PHP, server API (gateway between PHP and web server), web server.

*

*The PHP buffer has 4KB by default (defined by the output_buffering param in php.ini)

*The server API buffer has usually 0KB for Apache Handler, 4KB for CGI/FastCGI

*The web server buffer for Apache or Symfony local web is likely 8KB

My orignal XAMPP config uses Apache Handler + Apache and reacts well to flush commands.
My new Symfony config uses CGI/FastCGI + its local web and does NOT react to them.
Both uses the same PHP 7.4 install.
I used various codes which confirm the size of the Symfony chain buffer at 8KB: as soon as reached the data output is displayed in the browser.
I did not find yet a way to reduce the Symfony chain buffer, so the workaround is to artificially fill my rows with an invisible HTML comment to the 8KB threshold. It is not so elegant, but there is no perf impact in my application.
I successfully tried different Twig objects/functions: simple Response/setContent, StreamedResponse/setCallback and Response/render. The cleanest seems to be the following:
`$response = new Response();
$HTML = "Text1";
$response = $this->render('Sandbox/row.html.twig', ['String' => $HTML]);
$response->send();
sleep(2);           // Just to simulate the processing time between 2 rows
$HTML = "Text2";
$response = $this->render('Sandbox/row.html.twig', ['String' => $HTML]);
return($response);`

redpajama_set_name: RedPajamaStackExchange


text:
Q: CreditCart payment for 1 fixed product (no PayPal, no Google Checkout, no Ubercart) I'm about to start a new Drupal website. My client needs CreditCart payment (in-site with authorize.net). So he doesn't want PayPal or Google Checkout through Credit Cart payment. As I know Ubercart is well working solution. but i have 1 fixed product. I don't need any shopping basket, etc. so Ubercart is too big for my need. I just need simply CC payment. Is there any smaller alternative to Ubercart for this purpose? what would you recommend?
Thanks a lot!!

A: Take a look at this module list on Drupal.org. Drupal.org has advanced searching, which allows you to easily find the modules you need.
I found a few modules on the list, that looks like they could fit your need, but I'll give you the whole list and let you check them out and decide for yourself.


text:
Q: PHP Frontcontroller I dont't want to use any framework, but I need a Frontcontroller,  Where I can get HELP?

A: I would recommend building a dynamic invocation front controller. This is what the frameworks use. Here is a link to get started.
http://www.phpwact.org/pattern/front_controller
This book has a great chapter on Presentation Patterns during which he covers the front controller pattern.
PHP Objects, Patterns and Practice, Third Edition (Expert's Voice in Open Source)
http://amzn.to/d3eU0r

A: *

*You should configure your mod rewriting. All requests should be go to index.php. And not domain part should be send to the GET parameter. For example: example.com/tratata/tratata.
print_r($_GET) should contains 'tratata/tratata';

*Create class, which will be explode this GET parameter. It is your FrontController.

*Create class tratataController.

*Load class by get Parameter.

Sorry for my english.

A: Pick a framework and look at the implementation of their FrontController. Figure out how it works and build your own.
That said, why on earth would you not want to use a framework? The only reason I can think of is that you want to know how it works. And for that just google and look at existing sources.

A: I have had the same issue, so I made my own. It's tiny, as the name suggests, and (hopefully simple to use. You just need to make sure that the correct Apache rewrite rules are in place. You can find the source on GitHub. https://github.com/samuelwilliams/Tiny-Front-Controller


text:
Q: How can i create SASS mixins and use in every project I want to create a scss file with different mixins that I want to use in any project by simply using @import "mixinfile" and not to copy that file in every project.
Similar to adding a folder to path in windows.
How can I do that?

A: Compass is Sass framework that not only provides a great deal of useful functions and mixins, but it allows you to easily create your own extensions.  If you bundle your extension as a gem (which I personally recommend doing), you won't have to remember where you put it on the filesystem.
http://compass-style.org/help/tutorials/extensions/
When an extension is installed as a Ruby gem (which is easy to do, even if you don't know a thing about Ruby), all you need to do is add a line like this to your config.rb file:
require "extension-name"

And it will make all of your stylesheets from within your extension accessible just like you had a copy of them in your project directory:
@import "extension-name/widgets";

The author of Compass has a screencast of how to write your own extension here (doesn't cover creating a gem out of the extension):
http://chriseppstein.github.com/blog/2010/08/01/building-a-personal-framework/

A: If you are on a mac, I would recommend you to use Codekit as a pre-compilator, it offer you the opportunity to import your own framework for every our your projects. Good stuff.
Look for @import Statements there http://incident57.com/codekit/help.php

A: let's say the name of your mixin would be "example". So you would write "@import example" in your .scss files. In order for it to work, you'd have to have a file called "_example.scss" in your stylesheets path.
Now, you say you want to share this mixin across projects. For that you'll have to load your mixin through a lib, and if we're talking about rails, the best way is to do it using rails engines (see bourbon gem source code). Then add it as a dependency in your gemfile (you can use the git uri or other types of source).


text:
Q: How can i write join query in android sqlite? Hi, I am new to android. I want to write query for join in sqlite. My code is -
public Cursor SearchCategory(SQLiteDatabase db){
        //return  db.query("category_master", null, "status = 'Active'", null, null, null, null);

        String Category_Sql = " select category_master.*,count(*) as cnt from product_master " +
                            "   left join category_master on product_master.category_id = category_master.category_id " +
                            "   where category_master.status = 'Active' group by category_master.category_id having cnt > 0 ";
        return db.query(Category_Sql);
    }

but it generate error. Where am I wrong?

A: It would have helped more if you could cite the error description.
Try running the query first in Portable SQLite explorer

A: you can use rawQuery
db.rawQuery("Select a.column1,b.column1 FROM table1 a JOIN table2 b ON a._id=b._id", null);

it should work


text:
Q: MathJax equations goes on next line when used between sentence I am using MathJax.js locally the equations are getting generated but the problem is the equation goes on the next line as shown in the image

Does anyone know how to solve this.
The main point is when i use the link of the server of MathJax.js it shows properly in the same line
<script src='../MathJax-master/MathJax.js?config=TeX-AMS-MML_HTMLorMML'>
</script>
<script>
MathJax.Hub.Config({tex2jax: { displayMath: [   ['\\(','\\)'] ] } });
 /*MathJax.Hub.Config({tex2jax: { displayMath: [ ['$$','$$'], ['\\(','\\)'] ] } });*/
 MathJax.Hub.Config({
    "HTML-CSS": { scale: 100, linebreaks: { automatic: false } },
    SVG: { linebreaks: { automatic:false } },
    displayIndent: "2em",
    displayAlign: "left" });

this is the code of the js nothing else is done and the laTEX is
(\alpha_c/\alpha_t)


text:
Q: Formatting 'Complex' Math Note: by 'complex' math I mean an equation with many steps involved and a wide mix of operators.
A programmer should know the order that operators are evaluated in an equation. However it can be a royal pain to look at an equation such as:
result = value_1 + value_2 * value_1 + value_3 / value_4 % value_5;

One option is to write out the equation in multiple steps such as:
part1 = value_2 * value_1;
part1 += value_1;

part2 = value_4 % value_5;
part2 = value_3 / part2;

result = part1 + part2;

Another option is to format the original equation with parenthesis such as:
result = (value_1 + (value_2 * value_1)) + (value_3 / (value_4 % value_5));

When dealing with complex math in code, how do you typically format it to maximize readability?

A: You're right -- every programmer should indeed know order of operations. If you come across code like your example:
result = value_1 + value_2 * value_1 + value_3 / value_4 % value_5;

and you're not sure whether % takes precedence over /, then you should absolutely look it up. Every smart programmer keeps at least one reliable reference manual for their language of choice within arm's reach. Learning (or re-learning) details like this is the way that you gain experience. If you take these opportunities every time they present themselves you'll soon find that you never have to look anything up because you know it cold.
The deeper problem with the example above is that it doesn't convey the programmer's intent. You should be able to read that line and know exactly what it does, but there's no way to know if it does what the author intended. Even if you wrote it, you probably won't remember exactly what you were thinking at the time. Well-named variables, white space, parentheses, and functions are all tools that you can use to help communicate what you expect your code to do and why. There's no sense in choosing to use one of those options; use whichever combination seems clear. Instead of:
float w = (m1 + m2 + m3) * a * d;

write:
float totalMass = mass1 + mass2 + mass3;
float force = totalMass * acceleration;
float work = force * displacement;

A: Generally, write for programmer first, for computer second. Compilers are aggressive optimizer these days (which sucks if you are trying to implement Kahan summation), so take liberty at introducing temp variables that make sense. Mixing more than two of [*, /, and % and ** (exp)] in one line is a bad idea, IMO - too many opportunities for bugs and it slows down whoever is trying to read this code. If you can use FP, then you have many tools to control the complexity. I would go through SICP book and videos that you can dl via torrent.
Just as with regular code, try to avoid 'formatting' - rather split things up into small functions and/or temp variables that make sense. The SICP book does complex stuff, and yet the code is never long. If you have to leave a long line on occasion, just do what makes sense. Again, a good lesson from LISP would be to try to align parenthesis from one line to the next.
In other languages see these examples:
http://en.wikipedia.org/wiki/Kahan_summation_algorithm
http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
The math is somewhat complex, and yet the code is not. It is all about controlling the complexity. Hopefully these two examples can set you in the right direction.

A: I use a mix:

*

*I heavily use temp variables in particular for results that are used multiple times (this is a bit of a micro optimization but it soothes my mind)

*and when it's still not really clear I use parenthesis and play with the spacing of it so priorities are clear at a glance and similar stuff lines up nicely even when not all variables are the same length:
result = (val_1   + value_2*val_1   ) +
         (value_3 -   val_4%value_5 );

A: Your question is about maximizing readability of an equation. I suggest the following:
A. Put in a comment or in your documentation with the equation clearly stated in its original mathematical form. Complex calculations should have a reference outside the code for people to build test cases and to understand where do the equations come form.
B. Splitting the equation enhances debugging of parts of the equation. It also allows you to catch overflows and similar problems that could occur. For example:
x= ((b*b) + Sqrt(b*b-(4*a*c))) / -1*2*a may lead to an error if b*b-(4*a*c) is negative or if a is zero. you can split this expression to report each case separately with a different error message.
If you have several expression, there may be a sub expression that repeats in several equations. It would be more efficient to calculate that expression separately to improve performance.
C. If you split an expression, make sure the intermediate expressions are assigned to the correct variable type. For example,
int j=Sqrt(b*b-(4*a*c)) is not good.
D. Writing long un-split equations may be not readable and makes tracking braces difficutl
So, I suggest you split with care.

A: I think readability is not such a big issue in such cases. Using parenthesis is one option. Other thing one can do is to use the multi-line statements like the one used by ratchet. Also, you use use commenting in all the programming language.
Therefore, just concentrate more on the computing algorithm and equations. Rest are very minor things to worry about

A: In Algol-like languages, I would do it like this:
result := value_1 +
          value_2 * value_1 +
          (value_3 / value_4) % value_5;

Note that I assume an arbitrary precedence rule for / over %.  I would use explicit parentheses in any language for this.
Lisp has standard formatting guidelines for such things, and it is completely explicit, e.g.:
(let ((result (+ value-1
                 (* value-2 value-1)
                 (mod (/ value-3 value-4)
                      value-5))))
  (do-something-with result))


text:
Q: Is there any apache utils that prints arrays some understandable strings I am doing some logging using org.slf4j.Logger in my code. There are places where it comes, i want to see the contents of the array, which mostly array of strings, array of object types. if object types mostly implemented with toString().
Is there any apache utils or something that gives arrays to to understandable strings?

A: As suggested in other answer, you can use Arrays.toString() to construct the "meaningful" string presentation for an Array.  Of course, it is assumed that you are using JDK 5+
A even more "correct" result should be using Arrays.deepToString(), for which if it is an other array instance contained in the array, the contained array is also properly converted to string.
If you are not using JDK5+, in Apache Commons Lang, you can make use of ArrayUtils.toString()
Given that you have mentioned about SLF4J Logger, there is something worth to look into.
When we are using SLF4J Logger, we always do something like
logger.info("data is {}", data);

The reason to do this instead of logger.info("data is " + data); is because the log message can be lazy-evaluated, only if the logger actually have INFO level enabled.  It is especially useful when the message is expensive to construct.
However, simply using Arrays.deepToString() is going to take away this advantage:
logger.info("data is {}", Arrays.deepToString(dataArray));

Expensive dataArray to string conversion is happening no matter the logger is enabled with INFO level.
In order to solve it, you can explicitly check for logger level before logging:
if (logger.isInfoEnabled()) {
    logger.info("data is {}", Arrays.deepToString(arrayData));
}

You may also consider making a helper like this (pseudo-code):
public class ArrayToStringHelper {
    Object[] arrayData;
    public ArrayToStringHelper(Object[] arrayData) {
        this.arrayData = arrayData;
    }
    @Override
    public String toString() {
        return Arrays.deepToString(arrayData);
    }
}

So that the Array to String conversion is delayed until it is actually needed:
logger.info("data is {}", new ArrayToStringHelper(arrayData));

A: No need for any third party library to do this. Just use Arrays.toString


text:
Q: Extend Cookie with auth_cookie_expiration not working I was trying to extend the Login Cookie with the following Code
function expiration_filter($seconds, $user_id, $remember){

    //if "remember me" is checked;
    if ( $remember ) {
        //WP defaults to 2 weeks; 14*24*60*60
        $expiration = 10*365*24*60*60; //10 Yrs;
    } else {
        //WP defaults to 48 hrs/2 days; 2*24*60*60
        $expiration = 2*24*60*60; //UPDATE HERE;
    }

    //http://en.wikipedia.org/wiki/Year_2038_problem
    if ( PHP_INT_MAX - time() < $expiration ) {
        //Fix to a little bit earlier!
        $expiration =  PHP_INT_MAX - time() - 5;

    }

    return $expiration;
}
add_filter('auth_cookie_expiration', 'expiration_filter', 99, 3);

The Cookie is set to a date in 10 years (2029) which seems fine, but after 2 weeks the user gets logged out.
Maybe I missed something in the Code or there is an extra Hook for everything beyond 2 weeks?


text:
Q: Swift share data model communicate between page. how it works I have a question. I have a DataModel from Class A passing to Class B. I would like Class B to retrieve the changed value from Class A. And They both can edit and share the same data.  However, now Class B cannot get any value from Class A. How can i make it
struct DataModel {
  var firstName: String = ""
  var lastName: String = ""
}

class ClassA {

 var dataModel: DataModel

  ClassB(dataModel: dataModel)
  dataModel.firstName = "ABC"
}

class ClassB {
   var dataModel: DataModel

   init(dataModel: dataModel) {
     self.dataModel = dataModel

     dataModel.firstName <--- Print Null
  }
}

A: As struct is a value type when you pass A.dataModel to B, a copy of dataModel is passed to B, not the original instance.
So just use class for your data modal instead of struct if you want to modify A.dataModel in A as well as B
in other words you need to pass reference of A.dataModel to B
class DataModel {
    var firstName: String = ""
    var lastName: String = ""
}


text:
Q: Testar se a imagem existe Pessoal utilizo o Intervention no Laravel 5.5 e utilizo as rotas dele com os filtros para gerar as imagens dinamicamente. Gostaria de saber como eu posso testar na classe do filtro e a imagem que passei ela existe no disco, caso não eu carrego uma imagem padrão do site. Obrigado

A: Não sei se é o melhor jeito mas fiz assim:
@if(strtoupper($file_headers = @get_headers('http://www.meuservidor.com.br/miniatura/'.$item['imagem'])[0])=='HTTP/1.1 200 OK')

Assim funcionou perfeitamente, mas com certeza tem o custo de 1 conexão a mais com o servidor por imagem. Se alguém souber um jeito melhor gostaria de saber. Principalmente se tiver como fazer isto direto no servidor de imagem seria TOP. Obrigado

A: Consegui resolver criando uma nova rota onde eu checo se o arquivo existe e se não existe eu coloco o arquivo padrão e depois encaminho para a rota padrão do Intervention. Deu certinho Desta forma.
Definição da rota:
Route::get('/imagecache/{template}/{filename}', 'ApiController@imagecache')->where('filename','[ \w\\.\\/\\-\\@\(\)]+');

Controller da rota:
public function imagecache($template, $filename)
{
    if(!Storage::disk('public')->exists($filename)){
        $filename='images/noimage.jpg';
    }
    return response()->redirectTo('/imagecache/'.$template.'/'.$filename);
}


text:
Q: pandas pivot table on predefined values I am trying to count values for multiple columns including values that might not occur in the column.
Given example data frame:
foo = pd.DataFrame({'A':[False,False,True], 'B':[None, False, True], 'C': [None, None, None]})

my final result would look like:

.value_counts() would not work here for me since it will miss some values plus it works primary on pd.Series. So far I tried pivot table but without success:
# returns KeyError: False
foo.pivot_table(index=[False, True, None], columns=foo.columns, aggfunc='count')

How can pandas count all occurrences for specified values in multiple columns ?

A: You can melt and crosstab:
bar = foo.melt(var_name='pivot_values').replace({None: 'None'})
# for some reason, even using "dropna=False" in crosstab still removes None

out = (pd.crosstab(bar['pivot_values'], bar['variable'], dropna=False)
         .reset_index().rename_axis(columns=None)
      )

Output:
  pivot_values  A  B  C
0        False  2  1  0
1         True  1  1  0
2         None  0  1  3


text:
Q: params is not being set in rails object In my params i have value batch_params[:end_date]
If i try Batch.new(end_date: "12/12/12") then it works just fine.
But if i write it like Batch.new(end_date: batch_params[:end_date]) it sets batch end date to nil. I have checked batch_params[:end_date] it contains "12/12/12". Don't know what exactly is going on.
Here is my batch_params function
def batch_params
  params.require(:batch).permit( :name, :start_date, :students, :end_date, :course_ids, :batch_id)
end

Any help would be appriciated
Here is what i am doing


text:
Q: Create Azure MYSQL instance for Organization I want to create an Azure MYSQL instance for my team in the organization. from what I can see I need to provide ip addresses of the devices which can access the MYSQL instance.
How can I configure the firewall rules such that the SQL instance is only available for my team?


text:
Q: best of 12 out of 14 in python I have a list of 14 numbers in a list
list=[0.0, 2.0, 2.0, 2.0, 2.0, 1.5, 1.0, 1.0, 1.0, 1.0, 0.5, 1.5, 1.0, 2.0]
I have to sum the best of 12 among the list
New to code have no idea.

A: l=[0.0, 2.0, 2.0, 2.0, 2.0, 1.5, 1.0, 1.0, 1.0, 1.0, 0.5, 1.5, 1.0, 2.0]
l.sort()
l=l[0:12]
print(l)
total=0
for element in range(0,len(l)):
    total=total+l[element]
print(total)

Hope this help! but try to learn this language by yourself, you will surely be enjoying python:)


text:
Q: ST_Distance_Sphere slow for distances less than 0.5 mile. Is there a way to optimise for finer distances? SELECT property.paon,
       property.saon,
       property.street,
       property.propertytype,
       property.postcode,
       property.lastsaleprice,
       Date(property.lasttransferdate),
       St_distance_sphere(Point(-1.3429, 54.5924), coords) * 0.000621371192 AS
       distance
FROM   property property
       INNER JOIN epc
               ON property.postcode = epc.postcode
                  AND Concat(property.paon, ', ', property.street) =
                      epc.address1
WHERE  property.lasttransferdate >= CURRENT_DATE() - INTERVAL 10 year
HAVING distance < 0.5
LIMIT  10

This query takes around 1.2 seconds with distance having < 0.5, getting much quicker as the distance increases. However, below 0.5 the speed starts to jump up to durations too long for an acceptable user experience.

*

*HAVING distance < 0.4 - 3.4 seconds

*HAVING distance < 0.3 - 6.3 seconds

*HAVING distance < 0.2 - 10.5 seconds

*HAVING distance < 0.1 - 43.8 seconds

The smaller the distance, the higher the accuracy in some cases, so it's important these smaller distances are more optimised for speed.
Useful Info

*

*Everything in where and join clause are indexed

*coords is a POINT and is indexed


text:
Q: Is it possible to assign default values to attributes when using rails scaffold command? How? For example, I want to generate a scaffold with a boolean field that defaults to false

A: No, you can not do that from command line.
You can read about available modifiers to pass from command line in docs.
Also, very nice practical (a bit old but still useful) article.
You can do at least the following stuff:
# Specify the type of the field
rails g model user email age:integer
# Add index for column
rails g model user email:index location_id:integer:index
# Add uniq index for column
rails g model user pseudo:string:uniq
# Set limit for field of integer, string, text and binary fields:
rails generate model user pseudo:string{30}
# generate decimal field with scale and precision:
rails generate model product 'price:decimal{10,2}'
# You can combine any single curly brace option with the index options:
rails generate model user username:string{30}:uniq
# options to generate reference columns (fields which are used in rails as foreign keys):
rails generate model photo album:references

A: Yes one way you can try to give the length but not able to give default value
rails g scaffold users firstname:string{50}


text:
Q: Spring boot server all shutdown at the same time for unknown reason We have a bunch of spring boot servers and they are different code base (but all cloned from the same base)
They all went down last night, at slightly different time. When I looked at the log, it didn't say much. Here is the log
2021-08-06 06:22:09.735  INFO 1 --- [       Thread-4] o.s.s.c.ThreadPoolTaskScheduler          : Shutting down ExecutorService 'threadPoolTaskScheduler'
2021-08-06 06:22:09.747  INFO 1 --- [       Thread-4] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'
2021-08-06 06:22:09.750  INFO 1 --- [       Thread-4] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Shutdown initiated...
2021-08-06 06:22:09.761  INFO 1 --- [       Thread-4] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Shutdown completed.

Here is the log from another project we have
2021-08-06 06:36:39.317  INFO 1 --- [       Thread-3] o.s.s.c.ThreadPoolTaskScheduler          : Shutting down ExecutorService 'taskScheduler'
2021-08-06 06:36:39.324  INFO 1 --- [       Thread-3] o.s.s.concurrent.ThreadPoolTaskExecutor  : Shutting down ExecutorService 'applicationTaskExecutor'
2021-08-06 06:36:39.329  INFO 1 --- [       Thread-3] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'
2021-08-06 06:36:39.341  INFO 1 --- [       Thread-3] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Shutdown initiated...
2021-08-06 06:36:39.354  INFO 1 --- [       Thread-3] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Shutdown completed.

What could be the reason and how do I troubleshoot this?
The springboot runs inside a docker image, running on ubuntu.
The servers were able to be rebooted immediately without issue.


text:
Q: How to use "back home" phrase? One can say "get back home" or "went back home" to talk about going back home after hanging out with friends.

In response to this question: Who do you usually like to hang out
  with? I say: Back home, I used to hang out with my collage colleagues, but nowadays, I usually go out with my work colleagues

"back home" refers to my country and the listener know that I am a foreigner. Is this a correct usage of the phrase. Is it idiomatic?

A: Yes this is idiomatic!
You often hear this used in the exact way you have in your question and it's pretty well established (at least in BrE).

Back Home - : in one's hometown : in the place one is from

It's worth noting that it's sometimes used to refer to ones house as well, even though this isn't the true definition.
E.g. Someone might say:

We don't need bread, we have that back home.

This sentence should really be:

We don't need bread, we have that back at home.

Clearly they mean back at the house, rather than in the home country! (Even though they will no doubt have bread "back home").


text:
Q: Start Script Even When Mac Sleeps I wrote a a python script to check the tmperature via API call and then change the color of my Philips Hue Lights regarding temperature and rain. The only problem I'm facing is that the whole thing runs - as a cronjob - on my MacBook Air(10.10.4) which is normally asleep at 6am.
Crontab and launchd is not a solution, because those don't wake the Mac. I tried a scheduled wake up with Energy Savers's schedule but due to the mac is closed it immediately falls asleep again. I thought about using caffeinated with a cronjob that runs a minute before the actual script to keep the MacBook alive(after the schedule from the energy saver kicks in) but no success.
There is a third party solution which also didn't work for me: power manager
The only thing that should work is to "prevent computer from sleeping automatically when the display is off" in the energy saver preferences. The computer is most of the time on the charger so this would work. Although there is a slight chance that I forget to not close the lid before going to sleep at night ;-)
so any solutions which do not include buying a mac mini for automatic tasks like this :-)
br.kg

A: You can use NoSleep: https://code.google.com/p/macosx-nosleep-extension/
It does what it says on the tin ...
Or, if you don't want to install that, just turn on internet connection sharing, and leave it plugged in. This stops the Mac from sleeping


text:
Q: Tipos de dados incompatíveis ao chamar procedure Estou com problemas em chamar a procedure seguinte no meu form:
procedure TDM_Maquinas.IBDSMaquinasCOD_LINHASetText(Sender: TField; const Text: string);
begin
  if Text <> '' then
  begin
    if Text = 'Linha 1' then
      sender.AsInteger := 1
    else if Text = 'Linha 2' then
      Sender.AsInteger := 2
  end;
end;

No botão salvar:
procedure TForm.salvar(Sender: TObject);
var
 ValorLinha : Integer;
begin
 ValorLinha := DM_Maquinas.IBDSMaquinasCOD_LINHASetText(DBComboBox2.Field, 'Linha 1'); //erro
end;

Estou com erro na linha a cima:

E2010 Incompatible types: 'Integer' and 'procedure, untyped pointer
  or untyped parameter'

Se mudarmos o tipo da variável ValorLinha para String o erro persiste.

A: Exatamente como informado no comentário, você precisa de uma função para retornar o valor desejado, ou alimentar uma variável no procedimento!
Função:
function TDM_Maquinas.IBDSMaquinasCOD_LINHASetText(Sender: TField; const Text: string): Integer;
begin
  if Text <> '' then
  begin
    if Text = 'Linha 1' then
      Result := 1
    else if Text = 'Linha 2' then
      Result := 2
  end;
end;

Ou modificando o procedimento para alimentar uma variável externa:
procedure TDM_Maquinas.IBDSMaquinasCOD_LINHASetText(Sender: TField; const Text: string);
begin
  _VariavelExterna := 0;

  if Text <> '' then
  begin
    if Text = 'Linha 1' then
      _VariavelExterna := 1
    else if Text = 'Linha 2' then
      _VariavelExterna := 2
  end;
end;

No botão salvar:
procedure TForm.salvar(Sender: TObject);
var
  ValorLinha : Integer;
begin
  DM_Maquinas.IBDSMaquinasCOD_LINHASetText(DBComboBox2.Field, 'Linha 1');
  ValorLinha := _VariavelExterna;
end;

Para todos os casos a melhor opção e correta é a função!

A: Você poderia criar mais um parâmetro na procedure, para alimentar a variável.
Exemplo:
procedure TDM_Maquinas.IBDSMaquinasCOD_LINHASetText(Sender: TField; const Text: string; aValorLinha: Integer);
begin
  if Text <> '' then
  begin
    if Text = 'Linha 1' then
      sender.AsInteger := 1
    else if Text = 'Linha 2' then
      Sender.AsInteger := 2;
    aValorLinha := Sender.AsInteger;
  end;
end;

No botão Salvar:
procedure TForm.salvar(Sender: TObject);
var
 ValorLinha : Integer;
begin
  DM_Maquinas.IBDSMaquinasCOD_LINHASetText(DBComboBox2.Field, 'Linha 1', ValorLinha);
end;


text:
Q: Compare 2 String columns in SQL Server Select query I am trying to compare 2 string columns in my SQL query but I'm unable to do so.
Below is the query that I am trying to execute:
 With tempTable as
 (
     Select
         Id, DTree.Name, DefID, ValStr, DTree.DComment
     from
         LLAttrData la, DTree
     where
         DefId = 726297 and
         DTree.DataId = la.ID and
         ValStr IS NOT NULL
         and AttrId in (3)
 )
 SELECT
     Id, Name, DefID, DComment,
     STUFF((SELECT ', ' + CAST(ValStr AS VARCHAR(20)) [text()]
            FROM tempTable
            WHERE ID = t.ID
            FOR XML PATH(''), TYPE).value('.','NVARCHAR(MAX)'), 1, 2, ' ') List_Output
 FROM
     tempTable t
 WHERE
     DComment NOT LIKE STUFF((SELECT ', ' + CAST(ValStr AS VARCHAR(20))
 [text()]
                              FROM tempTable
                              WHERE ID = t.ID
                              FOR XML PATH(''), TYPE).value('.','NVARCHAR(MAX)'), 1, 2, ' ')
 GROUP BY
     Id, Name, DefID, DComment

Below is the screenshot of the result that I am getting:

As you can see, the contents of DComment and List_Output columns are exactly similar. According to my query, there shouldn't have been any results displayed
(since I am using NOT LIKE operator for comparison)
Can anyone please help me out on this. Thanks !


text:
Q: Database Design for the following Scenario I am working on creating a database schema for the following Requirements:
Employees have certain attributes. These same attributes are found on jobs.
What I need to be able to do is search for employees based on a given job's attributes. For example, "Find me all employees that match job id = 1 and have the same attributes for it". (vice Versa for Searching for all jobs for a given employee). Here is my database schema.
Job (
   jobId,
   description
)

Employee(
  employeeId,
  firstName,
  lastName,
  startDate,
  email
)

Attribute(
   attributeId,
   description
)

JobAttribute(
  jobId, (FK to Jobs.jobId)
  attributeId (FK to Attributes.attributeId)
)

EmployeeAttribute(
   employeeId, (FK to Employees.employeeId)
   attributeId (FK to Attributes.attributeId).
)

Query for "Find me all employees that match job id = 1 and have the same attributes for it".  would then look like :
SELECT DiSTINCT e.employeeId
FROM Employee e
INNER JOIN EmployeeAttribute ea
ON e.attributeId = ea.AttributeId
and e.employeeId = ea.employeeId
WHERE ea.AttributeId In (
Select ja.attributeId
FROM Job j
inner join JobAttribute ja
    on j.jobId = ja.jobId
inner join AttributeTable at
    on ja.attributeId = at.attributeId
where jobId = 1
)
order by e.startDate asc

The query would return all employees that have at least one attribute the same as the job.
How would the query look like if I need to return all employees that have ALL attributes assigned to them as per the jobs using this schema?
Is this good design for query performance. I also want to make this as flexible as possible to allow new attributes to be added with minimal code change.

A: Ok, your first query, "Find me all employees that match job id = 1 and have the same attributes for it", could be simpler as below
SELECT DISTINCT E.EmployeeId
FROM
Employee E
INNER JOIN EmployeeAttribute EA ON (EA.EmpId = E.EmployeeId)
INNER JOIN JobAttribute JA ON (EA.AttributeId = JA.AttributeId)
WHERE AJ.JobId = 1

on your query on retrieving employees matching all attributes for a given job
SELECT EA.EmployeeId, COUNT(EA.EmployeeId)
FROM EmployeeAttribute EA
INNER JOIN JobAttribute JA on EA.AttributeId = JA.AttributeId
WHERE JA.JobId = @jobId
GROUP BY EA.EmployeeId
HAVING COUNT(EA.EmployeeId) >= (SELECT COUNT(AttributeId) FROM JobAttribute J where J.JobId = @jobId)

You may have to join with Employee master to get other details of the employee. Both the queries assume that there is a PK on the derived tables which is a combination of both FKs.
In terms of performance, use the query execution plan and define your indexes accordingly.


text:
Q: SocketTimeoutException while connecting to hbase on VB

I have my hbase installed in Ubuntu on Virtual Box. In Windows I have written a program in java to check if a table exists ?
@Test
public void checkTableExists() throws IOException
{
    Configuration conf = HBaseConfiguration.create();
    conf.set("hbase.zookeeper.quorum", "192.168.1.3");
    conf.set("hbase.zookeeper.clientPort.property", "2181");
    conf.set("hbse.client.retries.number", "3");
    conf.set("zookeeper.recovery.retry", "2");

    Connection connection = ConnectionFactory.createConnection(conf);

    Admin admin = connection.getAdmin();

    System.out.println(admin.tableExists(TableName.valueOf("test1")));

    admin.close();
    connection.close();

}

But I am not getting the output. Instead, I am getting this error:
17:52:05.661 [hconnection-0x5e2c3d18-shared--pool1-t1] DEBUG org.apache.hadoop.hbase.ipc.RpcClientImpl - Use SIMPLE authentication for service ClientService, sasl=false
17:52:05.662 [hconnection-0x5e2c3d18-shared--pool1-t1] DEBUG org.apache.hadoop.hbase.ipc.RpcClientImpl - Connecting to localhost/127.0.0.1:35899
17:52:06.668 [hconnection-0x5e2c3d18-shared--pool1-t1] INFO org.apache.hadoop.hbase.client.RpcRetryingCaller - Call exception, tries=11, retries=35, started=58956 ms ago, cancelled=false, msg=Connection refused: no further information row 'test1,,' on table 'hbase:meta' at region=hbase:meta,,1.1588230740, hostname=localhost,35899,1512303024113, seqNum=0
17:52:06.670 [main] DEBUG org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate - Retrieved ApplicationContext from cache with key [[MergedContextConfiguration@71bbf57e testClass = HbaseApplicationTest, locations = '{}', classes = '{}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{}', contextCustomizers = set[org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@6a41eaa2, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@0, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@0, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@13805618], contextLoader = 'org.springframework.test.context.support.DelegatingSmartContextLoader', parent = [null]]]
17:52:06.670 [main] DEBUG org.springframework.test.context.cache - Spring test ApplicationContext cache statistics: [DefaultContextCache@2e4b8173 size = 1, maxSize = 32, parentContextCount = 0, hitCount = 2, missCount = 1]
17:52:06.671 [main] DEBUG org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate - Retrieved ApplicationContext from cache with key [[MergedContextConfiguration@71bbf57e testClass = HbaseApplicationTest, locations = '{}', classes = '{}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{}', contextCustomizers = set[org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@6a41eaa2, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@0, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@0, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@13805618], contextLoader = 'org.springframework.test.context.support.DelegatingSmartContextLoader', parent = [null]]]
17:52:06.671 [main] DEBUG org.springframework.test.context.cache - Spring test ApplicationContext cache statistics: [DefaultContextCache@2e4b8173 size = 1, maxSize = 32, parentContextCount = 0, hitCount = 3, missCount = 1]
17:52:06.673 [main] DEBUG org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate - Retrieved ApplicationContext from cache with key [[MergedContextConfiguration@71bbf57e testClass = HbaseApplicationTest, locations = '{}', classes = '{}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{}', contextCustomizers = set[org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@6a41eaa2, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@0, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@0, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@13805618], contextLoader = 'org.springframework.test.context.support.DelegatingSmartContextLoader', parent = [null]]]
17:52:06.673 [main] DEBUG org.springframework.test.context.cache - Spring test ApplicationContext cache statistics: [DefaultContextCache@2e4b8173 size = 1, maxSize = 32, parentContextCount = 0, hitCount = 4, missCount = 1]
17:52:06.673 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'org.springframework.boot.test.mock.mockito.MockitoBeans'
17:52:06.673 [main] DEBUG org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate - Retrieved ApplicationContext from cache with key [[MergedContextConfiguration@71bbf57e testClass = HbaseApplicationTest, locations = '{}', classes = '{}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{}', contextCustomizers = set[org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@6a41eaa2, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@0, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@0, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@13805618], contextLoader = 'org.springframework.test.context.support.DelegatingSmartContextLoader', parent = [null]]]
17:52:06.674 [main] DEBUG org.springframework.test.context.cache - Spring test ApplicationContext cache statistics: [DefaultContextCache@2e4b8173 size = 1, maxSize = 32, parentContextCount = 0, hitCount = 5, missCount = 1]
17:52:06.713 [main] DEBUG org.springframework.test.context.support.AbstractDirtiesContextTestExecutionListener - After test method: context [DefaultTestContext@711f39f9 testClass = HbaseApplicationTest, testInstance = HbaseApplicationTest@184f6be2, testMethod = checkTableExists@HbaseApplicationTest, testException = org.apache.hadoop.hbase.client.RetriesExhaustedException: Failed after attempts=36, exceptions:
Sun Dec 03 17:52:06 IST 2017, null, java.net.SocketTimeoutException: callTimeout=60000, callDuration=79009: Connection refused: no further information row 'test1,,' on table 'hbase:meta' at region=hbase:meta,,1.1588230740, hostname=localhost,35899,1512303024113, seqNum=0
, mergedContextConfiguration = [MergedContextConfiguration@71bbf57e testClass = HbaseApplicationTest, locations = '{}', classes = '{}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{}', contextCustomizers = set[org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@6a41eaa2, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@0, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@0, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@13805618], contextLoader = 'org.springframework.test.context.support.DelegatingSmartContextLoader', parent = [null]]], class annotated with @DirtiesContext [false] with mode [null], method annotated with @DirtiesContext [false] with mode [null].
17:52:07.202 [main] DEBUG org.springframework.test.context.support.AbstractDirtiesContextTestExecutionListener - After test class: context [DefaultTestContext@711f39f9 testClass = HbaseApplicationTest, testInstance = [null], testMethod = [null], testException = [null], mergedContextConfiguration = [MergedContextConfiguration@71bbf57e testClass = HbaseApplicationTest, locations = '{}', classes = '{}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{}', contextCustomizers = set[org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@6a41eaa2, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@0, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@0, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@13805618], contextLoader = 'org.springframework.test.context.support.DelegatingSmartContextLoader', parent = [null]]], class annotated with @DirtiesContext [false] with mode [null].
17:52:07.232 [Thread-0] INFO org.springframework.context.support.GenericApplicationContext - Closing org.springframework.context.support.GenericApplicationContext@80503: startup date [Sun Dec 03 17:50:17 IST 2017]; root of context hierarchy
17:52:07.233 [Thread-0] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'lifecycleProcessor'
17:52:07.233 [Thread-0] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@5e57643e: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.event.internalEventListenerProcessor,org.springframework.context.event.internalEventListenerFactory,org.springframework.boot.test.mock.mockito.MockitoPostProcessor$SpyPostProcessor,org.springframework.boot.test.mock.mockito.MockitoPostProcessor]; root of factory hierarchy
Where am I going wrong ?


text:
Q: Understanding Scanner in Java I am trying to understand Scanner class in java, out of some examples trying I am in ambiguity with below two programs, where I dont see any difference logically but output is telling that there is something I am missing. Please help me on this
public static void main(String args[]) {
        Scanner scanner1=new Scanner(System.in);
        String s=scanner1.nextLine();
        scanner1.close();

        // create a new scanner with the specified String Object
        Scanner scanner = new Scanner(s);

       // print the next line
       System.out.println("" + scanner.nextLine());

       // check if there is a next line again
       System.out.println("" + scanner.hasNextLine());

       // print the next line
       System.out.println("" + scanner.nextLine());

       // check if there is a next line again
       System.out.println("" + scanner.hasNextLine());

       // close the scanner
       scanner.close();
       }

above program is printing below output
Hello World! \n 3+3.0=6
Hello World! \n 3+3.0=6
false

While the below program which i dont see any difference with above is showing the different output
public static void main(String[] args) {

        String s="Hello World! \n 3 + 3.0 = 6";
        // create a new scanner with the specified String Object
        Scanner scanner = new Scanner(s);

       // print the next line
       System.out.println("" + scanner.nextLine());

       // check if there is a next line again
       System.out.println("" + scanner.hasNextLine());

       // print the next line
       System.out.println("" + scanner.nextLine());

       // check if there is a next line again
       System.out.println("" + scanner.hasNextLine());

       // close the scanner
       scanner.close();
       }

output of above program is
Hello World!
true
3 + 3.0 = 6
false

A: If \n is written in the file you can't use nextLine() [with two backslash it will give you java.util.NoSuchElementException]because there is not \n (end of line) but instead there is \n (two backslash).
To read the file and replace the \n in the text with actual EOL,you can use the sc.useDelimiter("\\n") for new line but then it might break the functionalities of scanner's some method.
Scanner s = new Scanner("Hello World! \\n 3 + 3.0 = 6");
s.useDelimiter("\\\\n");
System.out.println(s.next());
System.out.println(s.next());

will give you the output like
Hello World!
3 + 3.0 = 6

A: I'm assuming that in the first snippet you are typing Hello World! \n 3+3.0=6 to the standard input. "\n" is not parsed as new line in this case (it is parsed as the character '\' followed by the character 'n'). You have to actually press the enter button after typing "Hello World! " in order for the scanner to split the input into two lines.
On the other hand, when the Scanner takes the input from a String, "\n" is treated as a new line character.
Oh, and it does appear you have a typo in your first snippet. I was assuming you are using a Scanner that takes its input from System.in (you probably got the code of the two snippets mixed up).


text:
Q: Finding the vector $\vec c$ directed along the bisector of the angle between the vectors $\vec a$ and $\vec b$ where $|\vec c|=\sqrt 2$
Problem :
Find the vector $\vec{c}$ directed along the bisector of the angle between the vectors $\vec{a}=\hat{i}+2\hat{j}+\hat{k}$ and $\vec{b}=2\hat{i}-\hat{j}+\hat{k}$ where $|\vec{c}|=\sqrt{2}$

Please suggest how to proceed in such problems , no idea how to find bisector of angle, however done in straight lines but not in vectors. please suggest will be of great help. thanks.

A: Comsider the unit vectors $$\hat{a}=\frac{1}{\sqrt{6}}\left(\begin{matrix}1\\2\\1\end{matrix}\right)$$
And  $$\hat{b}=\frac{1}{\sqrt{6}}\left(\begin{matrix}2\\-1\\1\end{matrix}\right)$$
Then the vector in the direction either internally or externally bisecting the angle between $a$ and $b$ is parallel to $$\hat{a}\pm\hat{b}$$
So you can calculate either of these, divide by the modulus and multiply by $\sqrt{2}$ and you have what you want.


text:
Q: docker with php, nginx, redis, memcached connection refused 111 I have a project with Yii2 + nginx + php + redis + other services
What I want
so that each  php, nginx, redis, etc... service located in a separate container
that does not work:
access to redis from Yii2 (another container)?
configurations:
file:
/frontend/config/main.php
return [
    'components' => [
    'cache' => [
        'class' => 'yii\redis\Cache',
        'redis' => [
            'hostname' => '127.0.0.1',
            'port' => 6379,
            'database' => 1,
],

docker-compose.yml
version: '3'

services:
  nginx:
    restart: always
    container_name: mnginx
    build:
      context: ./
      dockerfile: ./docker/nginx/nginx.docker
    ports:
      - "80:80"
    links:
      - php-fpm
    volumes:
      - ./:/var/www/html/ztt.loc
  php-fpm:
    restart: always
    container_name: mphp
    ports:
      - "9000:9000"
    build:
      context: ./
      dockerfile: ./docker/php/php-fpm.docker
    volumes:
      - ./:/var/www/html/ztt.loc
  redis:
    build:
      context: ./
      dockerfile: ./docker/redis_data/redis.docker
    container_name: mredis
    restart: always
    expose:
      - 6379
    ports:
      - 6379:6379
  memcached:
    image: memcached:1.6.17
    container_name: mymemcached
    restart: always
    command: "-p 11211 -m 256 -c 8092"
    ports:
      - "11211:11211"

/docker/nginx/nginx.docker
FROM nginx:1.20-alpine
COPY ./docker/nginx/conf/nginx.conf /etc/nginx/nginx.conf
COPY ./docker/nginx/conf/ztt.loc.conf /etc/nginx/conf.d/ztt.loc.conf

/docker/php/php-fpm.docker
FROM php:7.4.30-fpm
COPY ./docker/php/conf/php-fpm.conf /usr/local/etc/php-fpm.conf
COPY ./docker/php/conf/www.conf /usr/local/etc/php-fpm.d/www.conf
COPY ./docker/php/conf/php.ini /usr/local/etc/php/php.ini

ADD https://github.com/mlocati/docker-php-extension-installer/releases/latest/download/install-php-extensions /usr/local/bin/
RUN chmod +x /usr/local/bin/install-php-extensions && \
install-php-extensions zip memcached

/docker/nginx/conf/nginx.conf
user       nginx nginx;
worker_processes  auto;

error_log  /var/log/nginx/error.log notice;
pid        /var/run/nginx.pid;
worker_rlimit_nofile 8192;

events {
    worker_connections  4096;
}

http {
    include    /etc/nginx/mime.types;
    include    /etc/nginx/fastcgi.conf;
    index    index.html index.htm index.php;

    default_type application/octet-stream;
    log_format   main '$remote_addr - $remote_user [$time_local]  $status '
        '"$request" $body_bytes_sent "$http_referer" '
        '"$http_user_agent" "$http_x_forwarded_for"';
    access_log   /var/log/nginx/access.log main;
    sendfile     on;
    tcp_nopush   on;

    server_names_hash_bucket_size 128;

    include /etc/nginx/conf.d/*.conf;
}

/docker/nginx/conf/ztt.loc.conf
server {
    charset utf-8;
    client_max_body_size 128M;

    listen 80;
    server_name ztt.loc;
    root /var/www/html/ztt.loc/frontend/web;

    error_log /var/log/nginx/ztt.loc.log;

    location / {
        try_files $uri $uri/ /index.php$is_args$args;
    }

    location ~ \.(js|css|png|jpg|gif|swf|ico|pdf|mov|fla|zip|rar)$ {
        try_files $uri =404;
    }

    location ~ ^/assets/.*\.php$ {
        deny all;
    }

    location ~ \.php$ {
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_pass php-fpm:9000;
        try_files $uri =404;
    }

    location ~* /\. {
        deny all;
    }
}

/docker/redis_data/redis.docker
FROM redis:6.2.7
COPY ./docker/redis_data/conf/redis.conf /usr/local/etc/redis/redis.conf
CMD [ "redis-server", "/usr/local/etc/redis/redis.conf" ]

/docker/redis_data/conf/redis.conf
bind 127.0.0.1
protected-mode no
port 6379
tcp-backlog 511
timeout 60
tcp-keepalive 300
daemonize no
pidfile /var/run/redis_6379.pid
loglevel notice
#logfile "/usr/local/var/log/redis.log"
databases 6
always-show-logo no
set-proc-title yes
proc-title-template "{title} {listen-addr} {server-mode}"
stop-writes-on-bgsave-error yes
rdbcompression yes
rdbchecksum yes
dbfilename dump.rdb
rdb-del-sync-files no
dir ./
replica-serve-stale-data yes
replica-read-only yes
repl-diskless-sync no
repl-diskless-sync-delay 5
repl-diskless-load disabled
repl-disable-tcp-nodelay no
replica-priority 100
acllog-max-len 128
lazyfree-lazy-eviction no
lazyfree-lazy-expire no
lazyfree-lazy-server-del no
replica-lazy-flush no
lazyfree-lazy-user-del no
lazyfree-lazy-user-flush no
oom-score-adj no
oom-score-adj-values 0 200 800
disable-thp yes
appendonly no
appendfilename "appendonly.aof"
appendfsync everysec
no-appendfsync-on-rewrite no
auto-aof-rewrite-percentage 100
auto-aof-rewrite-min-size 64mb
aof-load-truncated yes
aof-use-rdb-preamble yes
lua-time-limit 5000
slowlog-log-slower-than 10000
slowlog-max-len 128
latency-monitor-threshold 0
notify-keyspace-events ""
hash-max-ziplist-entries 512
hash-max-ziplist-value 64
list-max-ziplist-size -2
list-compress-depth 0
set-max-intset-entries 512
zset-max-ziplist-entries 128
zset-max-ziplist-value 64
hll-sparse-max-bytes 3000
stream-node-max-bytes 4096
stream-node-max-entries 100
activerehashing yes
client-output-buffer-limit normal 0 0 0
client-output-buffer-limit replica 256mb 64mb 60
client-output-buffer-limit pubsub 32mb 8mb 60
hz 10
dynamic-hz yes
aof-rewrite-incremental-fsync yes
rdb-save-incremental-fsync yes
jemalloc-bg-thread yes

when i am going to:
http://ztt.loc/site/index
page result:
Database Exception – yii\db\Exception
Failed to open redis DB connection (tcp://127.0.0.1:6379, database=1): 111 - Connection refused
Error Info: Connection refused

Its ubuntu 20.04 on local machiene;
I am installed redis-cli;
and i am has access from this redis-client.

A: Problem is that you haven't exposed the port in the redis container, it means its not accessible to your machine neither to other containers. You also need to bind it to your local port port so you can access it by pointing to localhost.
You can read further in docker's docs
 redis:
    build:
      context: ./
      dockerfile: ./docker/redis_data/redis.docker
    container_name: mredis
    restart: always
    expose:
      - 6379
    ports:
      - 6379:6379

Note the difference in the binding and exposing of port 6379*

A: change your
docker-compose.yml
to
version: '3'

networks:
  myztt:
    driver: bridge
    ipam:
      config:
        - subnet: 172.18.0.0/16
          gateway: 172.18.0.1

services:
  nginx:
    restart: always
    container_name: mnginx
    build:
      context: ./
      dockerfile: ./docker/nginx/nginx.docker
    ports:
      - "80:80"
    networks:
      myztt:
        ipv4_address: 172.18.0.100
    volumes:
      - ./:/var/www/html/ztt.loc
  php-fpm:
    restart: always
    container_name: mphp
    build:
      context: ./
      dockerfile: ./docker/php/php-fpm.docker
    volumes:
      - ./:/var/www/html/ztt.loc
    networks:
      myztt:
        ipv4_address: 172.18.0.101
  redis:
    build:
      context: ./
      dockerfile: ./docker/redis_data/redis.docker
    container_name: mredis
    restart: always
    networks:
      myztt:
        ipv4_address: 172.18.0.103

and change connection url to 172.18.0.103 in file: /frontend/config/main.php
'cache' => [
            'class' => 'yii\redis\Cache',
            'redis' => [
                'hostname' => '172.18.0.103',
                'port' => 6379,
                'database' => 1,
            ],
        ],


text:
Q: Error: soomla inApp purchase when click buy button I am trying sandbox testing for my App but encounter an error when I click the buy button on an iOS device.
Here is my console output in Xcode:

applicationWillResignActive() applicationDidBecomeActive()
2016-07-23 12:52:04.670 MyApp[2429:768800] [* ERROR *] SOOMLA
  SoomlaStore:  An error occured for product id "com.myapp.coin20000"
  with code "0"      and description "Error Domain=SKErrorDomain Code=0
  "Cannot connect to iTunes Store"
  UserInfo={NSLocalizedDescription=Cannot connect to iTunes Store}"
SOOMLA StoreEvents SOOMLA/UNITY OnUnexpectedStoreError
UnityEngine.DebugLogHandler:LogFormat(LogType, Object, String,
  Object[]) UnityEngine.Debug:Log(Object)
  Soomla.SoomlaUtils:LogDebug(String, String)
(Filename:
  /Users/builduser/buildslave/unity/build/artifacts/generated/common/runtime/UnityEngineDebugBindings.gen.cpp
  Line: 37)

Please help me determine what to do to fix this error.
Thanks!

A: Oh! problem resolved.
Bundel identifire mismatch on itunestore and unity.


text:
Q: Is it possible to bypass a hardware wifi switch, if `rfkill unblock all` does not work? Summary
I have recently revived an old Sony Vaio VGN-N230E laptop of mine, and installed Linux Mint on it:
gctrindade@gctrindade-VGN-N230E ~ $ lsb_release -irc
Distributor ID: LinuxMint
Release:        13
Codename:       maya
gctrindade@gctrindade-VGN-N230E ~ $ uname -or
3.2.0-23-generic GNU/Linux

The laptop works just fine, except for one problem: it has a hardware wifi switch that is slightly "loose". As a consequence, the laptop will randomly/constantly switch its wifi off, even when physically idle (something to do with some spring, perhaps?).
When that happens, rfkill displays the wifi as "hard blocked":
gctrindade@gctrindade-VGN-N230E ~ $ rfkill list
0: phy0: Wireless LAN
        Soft blocked: no
        Hard blocked: yes

This is particularly frustrating, seeing how I'm connecting to it remotely (SSH).

A few things I have tried:
Checking the BIOS for some sort of wlan/wifi setting. I failed to find anything related to it. (Note: I have not tried to "reset to factory defaults", as some other posts have suggested.)
Doing rfkill unblock all does not work, as the wifi remains "hard blocked".
Doing ifconfig wlan0 up fails with the following error message:
gctrindade@gctrindade-VGN-N230E ~ $ ifconfig wlan0 up
SIOCSIFFLAGS: Operation not possible due to RF-kill

Doing ip link set wlan0 up also fails:
gctrindade@gctrindade-VGN-N230E ~ $ ifconfig wlan0 up
RTNETLINK answers: Operation not possible due to RF-kill

Doing lsmod | grep sony revealed that a module called sony_laptop was loaded, and so I proceeded to do echo "blacklist sony_laptop" >> /etc/modprobe.d/blacklist.conf and rebooted my computer. Unfortunately, the problem persists.
Doing rm /etc/rfkill and rebooting does not work, as the wifi remains "hard blocked".
Doing rfkill event, followed by rfkill unblock xxxxxxxxxx.xxxxxx (with the number shown by the previous command) does not work, either.

Is it possible to bypass the hardware switch altogether?
Hopefully you guys have an idea how to solve this. It is really frustrating to have to come back to the laptop, just to squeeze the wifi switch (harder) onto the ON position every couple of hours.
Perhaps this has some valuable information:
gctrindade@gctrindade-VGN-N230E ~ $ lshw -c network
[sudo] password for gctrindade:
  *-network
       description: Ethernet interface
       product: 88E8036 PCI-E Fast Ethernet Controller
       vendor: Marvell Technology Group Ltd.
       physical id: 0
       bus info: pci@0000:02:00.0
       logical name: eth0
       version: 16
       serial: 00:13:a9:4f:a9:73
       capacity: 100Mbit/s
       width: 64 bits
       clock: 33MHz
       capabilities: pm vpd msi pciexpress bus_master cap_list ethernet physical tp 10bt 10bt-fd 100bt 100bt-fd autonegotiation
       configuration: autonegotiation=on broadcast=yes driver=sky2 driverversion=1.30 firmware=N/A latency=0 link=no multicast=yes port=twisted pair
       resources: irq:43 memory:d6000000-d6003fff ioport:2000(size=256)
  *-network
       description: Wireless interface
       product: PRO/Wireless 3945ABG [Golan] Network Connection
       vendor: Intel Corporation
       physical id: 0
       bus info: pci@0000:06:00.0
       logical name: wlan0
       version: 02
       serial: 00:19:d2:23:7f:eb
       width: 32 bits
       clock: 33MHz
       capabilities: pm msi pciexpress bus_master cap_list ethernet physical wireless
       configuration: broadcast=yes driver=iwl3945 driverversion=3.2.0-23-generic firmware=15.32.2.9 ip=192.168.15.4 latency=0 link=yes multicast=yes wireless=IEEE 802.11abg
       resources: irq:44 memory:da000000-da000fff

Thanks in advance!


text:
Q: Least Square of Multiple Lines If a line can be described as $$ y = mx + c $$ and we have multiple lines, we can have these lines described in matrix form
$$\begin{bmatrix}1 & -m_1\\1 & -m_2\\ \vdots & \vdots\\1 & -m_n\end{bmatrix}\begin{bmatrix}y \\ x\end{bmatrix}=\begin{bmatrix} c_1\\ c_2\\ \vdots\\ c_n\end{bmatrix} $$
I can get the value of $x$ and $y$ by using least square method. But when we have noise in calculation such as
$$\begin{bmatrix}1 & -m_1+\delta_1\\1 & -m_2+\delta_2\\ \vdots & \vdots\\1 & -m_n+\delta_n\end{bmatrix}\begin{bmatrix}\hat{y} \\ \hat{x}\end{bmatrix}=\begin{bmatrix} c_1+\epsilon_1\\ c_2+\epsilon_2\\ \vdots\\ c_n+\epsilon_n\end{bmatrix} $$
can we calculate the deviation of $\hat{x}$ and $\hat{y}$ from $x$ and $y$ (or is there any other way to describe that problem)?
Thanks

A: I'm not sure about what you wrote, but here is the usual setup.
Assume a set of $m$ data points $\{(x^{(1)}, y^{(1)}), \dots, (x^{(m)}, y^{(m)})\}$, where $x^{(i)}$ can be viewed as inputs to some function and $y^{(i)}$ as the corresponding outputs. The model assumed is the following
$$
y = f(x; \theta)+n
$$
where $f(x;\theta)$ is a function of the input data and some parameter vector $\theta$, and $n$ is noise (error).
For simplicity, assume $m=3$ and $f(x;\theta) = \theta_0 + \theta_1 x$. Hence, we can write
$$
y^{(1)} = \theta_0 + \theta_1 x^{(1)} + n^{(1)} \\
y^{(2)} = \theta_0 + \theta_1 x^{(2)} + n^{(2)} \\
y^{(2)} = \theta_0 + \theta_1 x^{(3)} + n^{(3)} \\
$$
or equivalently, in matrix-vector form
$$
y_d =
\begin{bmatrix}
1 & x^{(1)}\\
1 & x^{(2)}\\
1 & x^{(2)}
\end{bmatrix}
\begin{bmatrix}
\theta_0 \\
\theta_1
\end{bmatrix}
+ n_d
=
X_d \theta + n_d
$$
where subscript $d$ is put to emphasize that the elements correspond to "data" (in contrast to model).
Now, in least-squares the goal is to find $\theta$ minimizing $||n_d||^2 = ||y_d - X_d \theta||^2$. That is, to solve
$$
\min_\theta ||y_d - X_d \theta||^2,
$$
hence, the name least-squares, i.e., you seek the minimum (least) of the (sum of) squares since $||n_d||^2 = (n^{(1)})^2 + (n^{(2)})^2 + (n^{(3)})^2$.
One can show that the solution to this problem is given by
$$\theta = X_d^{+} y_d$$
where $X_d^{+}$ denotes the Moore-Penrose pseudo inverse of $X_d$.


text:
Q: Hovering over presence indicator doesnt bring pop up I have some strange behavior. When im on user profile and i hover over the "prescense indicator" i do not get a pop up, as strange as it my seen ...
How could it be? Do i need to activate maybe something?
Thanks in advance

A: As I know it requires a special plugin to Internet Explorer - it can be not installed or corrupted. And I suppose it doesn't work in other browsers at all.

A: The presense "popup" is an ActiveX control installed by OCS, Lync or Messenger. AFAIK it wonly works in IE 32bit (because the ActiveX are 32bit).  In SP there is some Javascript that calls the control and pops it up.
Are your status indicators for people showing as grey (which would indicate that the communication with Lync isnt operational) or green/orange/red which would indicate the communication is working with Lync.


text:
Q: EventStore 3.0 and Publishing Events So what would be the recommended way to publish events via Event Store 3.0?  Assuming I wire up the EventStore like this:
.UsingAsynchronousDispatchScheduler()
.DispatchTo(new DelegateMessageDispatcher(DispatchCommit))

where 'DispatchCommit' looks like this:
DispatchCommit(Commit commit)

I can watch the committed events fire off as expected.  However, ES 2.0 had the IContainer passing into the message dispatcher and I could resolve a bus instance and send events.  Shall I use a class that implements IDispatchCommits ?
Anyone using ES 3.0 with any thoughts?

A: Here's the code I'm using in production to dispatch commits: https://gist.github.com/1311195
I have my container configured to only create a single instance of the dependency.


text:
Q: r how to set x and y ranges in an animation video generated with saveVideo I make mpeg videos using the code below. r.mean is a spatRaster (the format for rasters in the terra package)
library(terra)
animation::saveVideo(animate(r.mean, n=1, pause = 0, sub = title_animate, col = rev(colorList), videoName_out))

I have included a screenshot of one frame of the animation. There is lots of white space above and below the actual image. I'd like to set the y range from -60 to 90. I've seen one example of use of saveVideo that looks like this with par parameters included in {}
saveVideo({
par(xxx, yy, zzz)},
some other stuff)

But I haven't had any luck making that work.

A: Here is a minimal, self-contained, reproducible example.
Example data
library(terra)
r <- rast(nlyrs=3)
values(r) <- rep(1:3, ncell(r))

You can use the ani.height and ani.width arguments.
animation::saveGIF(animate(r, n=1), ani.height=200, ani.width=300)


text:
Q: Reset the value of a GroupBox? So here's my problem : I want to do a Tic Tac Toe program, and I have 9 buttons and 2 progress bar (for the score)
I want that when the progress bar X or Y does a PerformStep, all the 9 buttons (in a GroupBox) resets to its initial value (Enable = true and Text = " ", because I disable it after the user clicked on it and the text changes for X or O depending of the player turn).
Is there a command that I can write for every buttons resets or I must do that one by one ?

A: If you want to reset all buttons more efficiently, you could reset them in a loop.
This would require that the buttons be collected together first, for example:
public partial class Form1 : Form
{
    List<Button> ticTacToeButtons = new List<Button>();

    public Form1()
    {
        InitializeComponent();

        ticTacToeButtons.Add(button1);
        ticTacToeButtons.Add(button2);
        ...
    }

Then, you can loop over them as needed:
    private void resetTicTacToeButtons()
    {
        foreach (Button button in ticTacToeButtons)
        {
            button.Enabled = true;
            button.Text = " ";
        }
    }


text:
Q: Mount host dir into docker container without volume? Is mounting (--mount or -v) a host directory or host volume into a container only possible if the image defines a volume?
I tried to do
docker run -d -v maven-m2-repo:/root/.m2 maven:3-jdk-8-alpine SOME-MAVEN-PROJECT-RUN

as described in https://github.com/carlossg/docker-maven in order to preserve Maven repository directory between container runs, but nothing gets ever written into my volume or host directory.
The Dockerfile doesn't define any volumes:
docker image inspect 08790c3343de
...
"ContainerConfig": {
  ...
  "Volumes": null,

A: If you want to create bind mount with -v, you need to provide absolute path -v /path/to/maven-m2-repo:/root/.m2 or relative path -v ./maven-m2-repo:/root/.m2, otherwise docker treats them as volume names.


text:
Q: Mobile website contacts I am currently working on creating contacts on mobile website.
I have already created the link to mobile number. But I want to rebuilt it so that there will be just some button and when you click on it it will automatically add the person into contacts. Is there any option using HTML and JS?

A: I'm not sure any phone would allow the browser (some website) to access data on the phone (such as your contacts list).
Edit: I guess there'll soon be ways to access contacts information from a web app, but seems like it'll be read only.

A: Did you check this answer? It suggests creation of a vcf that can then be downloaded on click of a button..


text:
Q: Error in NMI pod after adding and installing Bitnami External DNS via Terraform and Helm - No AzureIdentityBinding found for pod I am struggling to get the azureIdentity for ExternalDNS bound and get DNS entries into our zone(s).

Key error:  I0423 19:27:52.830107       1 mic.go:610] No AzureIdentityBinding found for pod default/external-dns-84dcc5f68c-cl5h5 that matches selector: external-dns. it will be ignored
Also, no azureAssignedIdentity is created since there is no match for the pod and selector/aadpodidbinding.

I'm building IaaC using Terraform, Helm, Azure, Azure AKS, VSCODE, and so far, three Kubernetes add-ons - aad pod identity, application-gateway-kubernetes-ingress, and Bitnami external-dns.
Since the identity isn't being bound, an azureAssignedIdentity isn't being created and ExternalDNS isn't able to put records into our DNS zone(s).
The names and aadpodidbindings seem correct.  I've tried passing in fullnameOverride in the Terraform kubectl_manifest provider for the Helm install of Bitnami ExternalDNS.  I've tried suppressing the suffixes on ExternalDNS names and labels.  I've tried editing the Helm and Kubernetes YAML on the cluster itself to try to force a binding.  I've tried using the AKS user managed identity which is used for AAD Pod Identity and is located in the cluster's nodepools resource group.  I've tried letting the Bitnami ExternalDNS configure and add an azure.json file, and I've also done so manually prior to adding and installing ExternalDNS.  I've tried assigning the managed identity to the VMSS of the AKS cluster.
Thanks!
JBP

PS C:\Workspace\tf\HelmOne> kubectl logs pod/external-dns-84dcc5f68c-542mv
: Refresh request failed. Status Code = '404'. Response body: getting assigned identities for pod default/external-dns-84dcc5f68c-542mv in CREATED state failed after 16 attempts, retry duration [5]s, error: <nil>. Check MIC pod logs for identity assignment errors\n"
time="2021-04-24T19:57:30Z" level=debug msg="Retrieving Azure DNS zones for resource group: one-hi-sso-dnsrg-tf."
time="2021-04-24T20:06:02Z" level=error msg="azure.BearerAuthorizer#WithAuthorization: Failed to refresh the Token for request to https://management.azure.com/subscriptions/8fb55161-REDACTED-3400b5271a8c/resourceGroups/one-hi-sso-dnsrg-tf/providers/Microsoft.Network/dnsZones?api-version=2018-05-01: StatusCode=404 -- Original Error: adal: Refresh request failed. Status Code = '404'. Response body: getting assigned identities for pod default/external-dns-84dcc5f68c-542mv in CREATED state failed after 16 attempts, retry duration [5]s, error: <nil>. Check MIC pod logs for identity assignment errors\n"
time="2021-04-24T20:06:02Z" level=debug msg="Retrieving Azure DNS zones for resource group: one-hi-sso-dnsrg-tf."

PS C:\Workspace\tf\HelmOne> kubectl logs pod/aad-pod-identity-nmi-vtmwm
I0424 20:07:22.400942       1 server.go:196] status (404) took 80007557875 ns for req.method=GET reg.path=/metadata/identity/oauth2/token req.remote=10.0.8.7
E0424 20:08:44.427353       1 server.go:375] failed to get matching identities for pod: default/external-dns-84dcc5f68c-542mv, error: getting assigned identities for pod default/external-dns-84dcc5f68c-542mv in CREATED state failed after 16 attempts, retry duration [5]s, error: <nil>. Check MIC pod logs for identity assignment errors
I0424 20:08:44.427400       1 server.go:196] status (404) took 80025612263 ns for req.method=GET reg.path=/metadata/identity/oauth2/token req.remote=10.0.8.7

PS C:\Workspace\TF\HelmOne>  kubectl logs pod/aad-pod-identity-mic-86944f67b8-k4hds
I0422 21:05:11.298958       1 main.go:114] starting mic process. Version: v1.7.5. Build date: 2021-04-02-21:14
W0422 21:05:11.299031       1 main.go:119] --kubeconfig not passed will use InClusterConfig
I0422 21:05:11.299038       1 main.go:136] kubeconfig () cloudconfig (/etc/kubernetes/azure.json)
I0422 21:05:11.299205       1 main.go:144] running MIC in namespaced mode: false
I0422 21:05:11.299223       1 main.go:148] client QPS set to: 5. Burst to: 5
I0422 21:05:11.299243       1 mic.go:139] starting to create the pod identity client. Version: v1.7.5. Build date: 2021-04-02-21:14
I0422 21:05:11.318835       1 mic.go:145] Kubernetes server version: v1.18.14
I0422 21:05:11.319465       1 cloudprovider.go:122] MIC using user assigned identity: c380##### REDACTED #####814b for authentication.
I0422 21:05:11.392322       1 probes.go:41] initialized health probe on port 8080
I0422 21:05:11.392351       1 probes.go:44] started health probe
I0422 21:05:11.392458       1 metrics.go:341] registered views for metric
I0422 21:05:11.392544       1 prometheus_exporter.go:21] starting Prometheus exporter
I0422 21:05:11.392561       1 metrics.go:347] registered and exported metrics on port 8888
I0422 21:05:11.392568       1 mic.go:244] initiating MIC Leader election
I0422 21:05:11.393053       1 leaderelection.go:243] attempting to acquire leader lease  default/aad-pod-identity-mic...
E0423 01:47:52.730839       1 leaderelection.go:325] error retrieving resource lock default/aad-pod-identity-mic: etcdserver: request timed out

resource "helm_release" "external-dns" {
    name          = "external-dns"
    repository    = "https://charts.bitnami.com/bitnami"
    chart         = "external-dns"
    namespace     = "default"
    version       = "4.0.0"

  set {
      name  = "azure.cloud"
      value = "AzurePublicCloud"
  }

  #MyDnsResourceGroup
  set {
      name  = "azure.resourceGroup"
      value = data.azurerm_resource_group.dnsrg.name
  }

  set {
      name  = "azure.tenantId"
      value = data.azurerm_subscription.currenttenantid.tenant_id
  }

  set {
      name  = "azure.subscriptionId"
      value = data.azurerm_subscription.currentSubscription.subscription_id
  }

  set {
      name    = "azure.userAssignedIdentityID"
      value   = azurerm_user_assigned_identity.external-dns-mi-tf.client_id
  }

  #Verbosity of the logs (options: panic, debug, info, warning, error, fatal, trace)
  set {
      name  = "logLevel"
      value = "trace"
  }

  set {
      name  = "sources"
      value = "{service,ingress}"
  }

  set {
      name  = "domainFilters"
      value = "{${var.child_domain_prefix}.${lower(var.parent_domain)}}"
  }

  #DNS provider where the DNS records will be created (mandatory) (options: aws, azure, google, ...)
  set {
      name  = "provider"
      value = "azure"
  }

  #podLabels: {aadpodidbinding: <selector>} # selector you defined above in AzureIdentityBinding
  set {
      name  = "podLabels.aadpodidbinding"
      value = "external-dns"
  }

  set {
      name = "azure.useManagedIdentityExtension"
      value = true
  }
}

resource "helm_release" "aad-pod-identity" {
    name       = "aad-pod-identity"
    repository = "https://raw.githubusercontent.com/Azure/aad-pod-identity/master/charts"
    chart      = "aad-pod-identity"
  }

  resource "helm_release" "ingress-azure" {
    name          = "ingress-azure"
    repository    = "https://appgwingress.blob.core.windows.net/ingress-azure-helm-package/"
    chart         = "ingress-azure"
    namespace     = "default"
    version       = "1.4.0"

  set {
      name        = "debug"
      value       = "true"
  }

  set {
      name        = "appgw.name"
      value       = data.azurerm_application_gateway.appgwpub.name
  }

  set {
      name        = "appgw.resourceGroup"
      value       = data.azurerm_resource_group.appgwpubrg.name
  }

  set {
      name        = "appgw.subscriptionId"
      value       = data.azurerm_subscription.currentSubscription.subscription_id
  }

  set {
      name        = "appgw.usePrivateIP"
      value       = "false"
  }

  set {
      name        = "armAuth.identityClientID"
      value       = azurerm_user_assigned_identity.agic-mi-tf.client_id
  }

  set {
      name        = "armAuth.identityResourceID"
      value       =  azurerm_user_assigned_identity.agic-mi-tf.id
  }

  set {
      name        = "armAuth.type"
      value       = "aadPodIdentity"
  }

  set {
      name        = "rbac.enabled"
      value       = "true"
  }

  set {
      name        = "verbosityLevel"
      value       = "5"
  }

  set {
      name        = "appgw.environment"
      value       = "AZUREPUBLICCLOUD"
  }

  set {
      name        = "metadata.name"
      value       = "ingress-azure"
  }

  }

PS C:\Workspace\tf\HelmOne> kubectl get azureassignedidentities
NAME                                                   AGE
ingress-azure-68c97fd496-qbptf-default-ingress-azure   23h

PS C:\Workspace\tf\HelmOne> kubectl get azureidentity
NAME                            AGE
ingress-azure                   23h
one-hi-sso-agic-mi-tf           23h
one-hi-sso-external-dns-mi-tf   23h

PS C:\Workspace\tf\HelmOne> kubectl edit azureidentity one-hi-sso-external-dns-mi-tf
apiVersion: aadpodidentity.k8s.io/v1
kind: AzureIdentity
metadata:
  annotations:
    kubectl.kubernetes.io/last-applied-configuration: |
      {"apiVersion":"aadpodidentity.k8s.io/v1","kind":"AzureIdentity","metadata":{"annotations":{},"name":"one-hi-sso-external-dns-mi-tf","namespace":"default"},"spec":{"clientID":"f58e7c55-REDACTED-a6e358e53912","resourceID":"/subscriptions/8fb55161-REDACTED-3400b5271a8c/resourceGroups/one-hi-sso-kuberg-tf/providers/Microsoft.ManagedIdentity/userAssignedIdentities/one-hi-sso-external-dns-mi-tf","type":0}}
  creationTimestamp: "2021-04-22T20:44:42Z"
  generation: 2
  name: one-hi-sso-external-dns-mi-tf
  namespace: default
  resourceVersion: "432055"
  selfLink: /apis/aadpodidentity.k8s.io/v1/namespaces/default/azureidentities/one-hi-sso-external-dns-mi-tf
  uid: f8e22fd9-REDACTED-6cdead0d7e22
spec:
  clientID: f58e7c55-REDACTED-a6e358e53912
  resourceID: /subscriptions/8fb55161-REDACTED-3400b5271a8c/resourceGroups/one-hi-sso-kuberg-tf/providers/Microsoft.ManagedIdentity/userAssignedIdentities/one-hi-sso-external-dns-mi-tf
  type: 0

PS C:\Workspace\tf\HelmOne> kubectl edit azureidentitybinding external-dns-mi-binding
apiVersion: aadpodidentity.k8s.io/v1
kind: AzureIdentityBinding
metadata:
  annotations:
    kubectl.kubernetes.io/last-applied-configuration: |
      {"apiVersion":"aadpodidentity.k8s.io/v1","kind":"AzureIdentityBinding","metadata":{"annotations":{},"name":"external-dns-mi-binding","namespace":"default"},"spec":{"AzureIdentity":"one-hi-sso-external-dns-mi-tf","Selector":"external-dns"}}
  creationTimestamp: "2021-04-22T20:44:42Z"
  generation: 1
  name: external-dns-mi-binding
  namespace: default
  resourceVersion: "221101"
  selfLink: /apis/aadpodidentity.k8s.io/v1/namespaces/default/azureidentitybindings/external-dns-mi-binding
  uid: f39e7418-e896-4b8e-b596-035cf4b66252
spec:
  AzureIdentity: one-hi-sso-external-dns-mi-tf
  Selector: external-dns

  resource "kubectl_manifest" "one-hi-sso-external-dns-mi-tf" {
    yaml_body = <<YAML
apiVersion: "aadpodidentity.k8s.io/v1"
kind: AzureIdentity
metadata:
  name: one-hi-sso-external-dns-mi-tf
  namespace: default
spec:
  type: 0
  resourceID: /subscriptions/8fb55161-REDACTED-3400b5271a8c/resourceGroups/one-hi-sso-kuberg-tf/providers/Microsoft.ManagedIdentity/userAssignedIdentities/one-hi-sso-external-dns-mi-tf
  clientID: f58e7c55-REDACTED-a6e358e53912
  YAML
}

resource "kubectl_manifest" "external-dns-mi-binding" {
    yaml_body = <<YAML
apiVersion: "aadpodidentity.k8s.io/v1"
kind: AzureIdentityBinding
metadata:
  name: external-dns-mi-binding
spec:
  AzureIdentity: one-hi-sso-external-dns-mi-tf
  Selector: external-dns
YAML
}

A: The managed identity I'm using was not added to the virtual machine scale set VMSS.  Once I added it, the binding works and the azureAssignedIdentity was created.
Also - I converted the AzureIdentity and Selector lines in my AzureIdentity YAML from upper case first letters to lower case first letters.
Correct:
azureIdentity:
selector:


text:
Q: How to convert a BVH node object into a simple array? I am working on an Opengl ray-tracer, which is capable of loading obj files and ray-trace it. My application loads the obj file with assimp and then sends all of the triangle faces (the vertices and the indices) to the fragment shader by using shader storage objects. The basic structure is about to render the results to a quad from the fragment shader.
When I load bigger obj-s (more than 100 triangles), it took so much time for the computer to do the intersections, so I started creating a BVH-tree to speed up the process.
My BVH splits up the space into two axis-aligned-bounding-boxes recursively based on the average median of the triangles faces contained in the AABB.
I succeed to build the BVH tree structure (on CPU) and now I want to convert it to a simple array, then send it to fragment shader (to a shader storage buffer).
This is the structure of my BVH class.
class BvhNode {

public:
    BBox bBox;
    vector<BvhNode> children;
    bool isLeaf;
    int depthOfNode;

    vector<glm::vec3> primitiveCoordinates;

    BvhNode() {}

    ~BvhNode() {}

    BvhNode(vector<glm::vec3> &primitiveCoordinates) {
        this->primitiveCoordinates = primitiveCoordinates;
    }

    void buildTree(vector<glm::vec3> &indicesPerFaces, int depth) {...}

    glm::vec3 calculateCenterofTriangle(glm::vec3 vec, glm::vec3 vec1, glm::vec3 vec2) {...}

    glm::vec3 getCoordinatefromIndices(float index) {...}

    BBox getBBox(vector<glm::vec3> &indices) {...}
};

But first I would like to convert it to a simple array, as GLSL does not support pointers. I have read about a binary tree can be converted into an array (if the tree is complete of course). I am pulling out of my hair. How can I iterate over the whole node, including children and of course how to complete it with empty nodes (to fulfill the definition of complete binary tree)? I started to write a method seen below, but I got segmentation fault when I declare the nodes variable as global variable. I don't know why.
vector<BvhNode> nodes; // it is a global variable

void putNodeIntoArray(BvhNode node) {

    nodes.push_back(node.children.at(0));
    nodes.push_back(node.children.at(1));
}

I guess, when I am creating the tree, I need to sign somehow in every nodes, where the left and the right children starts.
Any help is appreciated.

A: One way to lay out binary tree nodes in an array is: for all nodes in the tree, if a given node has array index i, its children are at indices 2i + 1 and 2i + 2 (described more fully here).

Assuming you have a complete tree, you can write your tree to an array with a simple breadth-first traversal:
In pseudo-code:
int current_index = 0;
node[] array = new node[2^n];
q nodes;
q.add(root);
while (!q.empty) {
   node current_node = q.front()
   array[current_index] = current_node;
   if (current_node.left != null)
      q.add(current_node.left);
   if (current_node.right != null)
      q.add(current_node.right);
   current_index++;
}

If your tree is not complete (which it probably won't be, but it depends on your BVH implementation), you'll need to modify this slightly to correctly track the index each node should go in. It will also waste space, as described in the link above.
Rather than lay out the nodes in breadth-first order, it is also possible to lay them out (more efficiently) in depth-first order as described in Physically Based Rendering here.


text:
Q: Function to clean a Data Frame column with variable text How can I set a function that can cleans through a given text passed into a Data Frame. The text will be my variable, so I can put whatever sentence and the function will clean it by applying lower case, removing characters, etc. My attempt goes like this:
def my_function(x):
    # Applies a few cleaning steps to the exceptions df:
    # Sets text to lower case:
    x.iloc[:, 0].str.lower()
    # Removes breaks:
    x.iloc[:, 0].replace(r'\n', ' ', regex=True)
    # Sets text to lower case:
    x.iloc[:, 0].str.lower()
    # Removes a more extensive set of 'special' characters:
    remove_these = ["!",'"',"%","&","'","(",")","#","*","?",
                    "+",",","-",".","/",":",";","<","=",">",
                    "@","[","\\","]","^","_","`","{","|","}",
                    "~","–","'", "*"]
    for char in remove_these:
        x.iloc[:, 0].str.replace(char, ' ')
    # Removes numbers:
    x.iloc[:, 0].replace(r'\d+', ' ', regex=True)
    # Removes single characters:
    x.iloc[:, 0].replace(r'\b[a-zA-Z]\b', ' ', regex=True)
    # Removes extra spaces (trim) from both ends:
    x.iloc[:, 0].str.strip()
    # Removes double spacing:
    x.iloc[:, 0].replace(r' +', ' ', regex=True)
    # Removes spaces --:
    x.iloc[:, 0].replace(r'--', '', regex=True)

Since the variable text would be passed into a DF, I thought using the first column always, hence the iloc[:, 0].
Then my variable text would be set like this:
my_variable = "WHAT A WONDERFUL WORLD!"
df_Text = pd.DataFrame({my_variable})

But when applying this, it won't work, the output is 'None':
output = my_function(df_Text)
print(output)

What am I doing wrong? Thanks a lot.

A: Your function doesn't actually alter the dataframe in any way, and it doesn't return anything.
Try this.
mport pandas as pd

def my_function(x):
    # Applies a few cleaning steps to the exceptions df:
    # Sets text to lower case:
    x.iloc[:, 0] = x.iloc[:, 0].str.lower()
    # Removes breaks:
    x.iloc[:, 0] = x.iloc[:, 0].replace(r'\n', ' ', regex=True)
    # Sets text to lower case:
    x.iloc[:, 0]  = x.iloc[:, 0].str.lower()
    # Removes a more extensive set of 'special' characters:
    remove_these = ["!",'"',"%","&","'","(",")","#","*","?",
                    "+",",","-",".","/",":",";","<","=",">",
                    "@","[","\\","]","^","_","`","{","|","}",
                    "~","–","'", "*"]
    for char in remove_these:
        x.iloc[:, 0] = x.iloc[:, 0].str.replace(char, ' ')
    # Removes numbers:
    x.iloc[:, 0] = x.iloc[:, 0].replace(r'\d+', ' ', regex=True)
    # Removes single characters:
    x.iloc[:, 0] = x.iloc[:, 0].replace(r'\b[a-zA-Z]\b', ' ', regex=True)
    # Removes extra spaces (trim) from both ends:
    x.iloc[:, 0] = x.iloc[:, 0].str.strip()
    # Removes double spacing:
    x.iloc[:, 0] = x.iloc[:, 0].replace(r' +', ' ', regex=True)
    # Removes spaces --:
    x.iloc[:, 0] = x.iloc[:, 0].replace(r'--', '', regex=True)
    return x

my_variable = "WHAT A WONDERFUL WORLD!"
df_Text = pd.DataFrame({my_variable})

output = my_function(df_Text)
print(output)

                      0
0  what wonderful world


text:
Q: getSupportActionBar() in AppCompatActivity cannot be applied to androidx.appcompat.widget.Toolbar I am getting an error while developing the toolbar I have searched solution on the internet and dint gets any solution working as I am new to android development.
I have tried to change the androidx.appcompat.widget.Toolbar to android.support.v7.widget.toolbar then I am getting an error as v7 cannot be resolved
main Activity
   package com.nanb.chaton;
   import androidx.appcompat.app.AppCompatActivity;
   import androidx.appcompat.widget.Toolbar;

   import android.os.Build;
   import android.os.Bundle;

   public class MainActivity extends AppCompatActivity {
     private Toolbar main_toolbar;
     @Override
     protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_main);

       Toolbar main_toolbar = findViewById(R.id.toolbar);
       getSupportActionBar(main_toolbar);
       getSupportActionBar().setTitle("ChatOn");
     }
   }

I am getting an error in the getSupportActionBar it says that it cannot be applied with AppCompatActivity to androidx.appcompat.widget.Toolbar

A: You can use:
getSupportActionBar();

instead of getSupportActionBar(toolbar); which doesn't exist.
Instead if you would like to set the actionbar you have to use:
setSupportActionBar(toolbar);

A: I think you want to add Back button in Your toolbar.
Use this code is may help you:
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import android.os.Bundle;

public class SecondActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);

        Toolbar toolbar= findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);

    }

    //Must use this, if you are using- androidx.appcompat.widget.Toolbar;
    @Override
    public boolean onSupportNavigateUp() {
        onBackPressed();
        return true;
    }

A: Toolbar toolbar= findViewById(R.id.toolbar);
toolbar.setTitle(" ");


text:
Q: Why is there an error about headers and authorization in a Stripe dependency? Stripe HTTP request dependency returns an error about headers, but these are not configurable.
Using a GET request seems fine, but a post route fails with the error:
error [err_invalid_char]: invalid character in header content ["authorization"]
app.post('/charge',function(req,res){

  stripe.charges.create({
      amount: 10,
      description: 'Charge',
      currency: 'gbp',
      customer: 'cus_EXgisfTr7LuiO9'
  },function(err,result){
    if(err){
      res.status(400);
      res.send(err);
    }
    else{
      res.status(201);
      res.send(result);
    }
  });
});

Hitting the endpoint https://myapp.herokuapp.com/charge with an HTTP POST request returns this to the console:
error [err_invalid_char]: invalid character in header content ["authorization"]
This is a Stripe dependency however and not configured by the developer.

A: The above error occurs when the Stripe Secret API key is passed incorrectly.
Just for the help,
const Stripe = require('stripe');
const stripe = Stripe(env.STRIPE_TEST_SECRET_KEY);

make sure you change the key as per the production/development environment.
Cheers.