How to upload enterprise blog picture programatically in drupal 7

Question: I used "enterprise blog" module for user blog postings. From external php file, I have to upload user picture programatically (i.e., for App). I have configured bootstrap perfectly and user_load($uid) is working, means drupal functions are working properly, but when I am trying to upload picture programaically "file_save($file)" is not working. Please check the below code and give me any suggestions to upload enterprise blog picture.
 $tmp_photo_realpath = "images/".$userimgname;
      $tmp_photo = "images/".$userimgname;
      $file = new stdClass();
      $file->uid      = $uid;
      $file->status   = 0; // mark the file as temporary
      $file->filename = basename($tmp_photo_realpath);
      $file->uri      = $tmp_photo;
     // $file->filemime = image_type_to_mime_type(exif_imagetype($tmp_photo_realpath));
      $file->filesize = filesize($tmp_photo_realpath);
     $infofile = explode("/",$tmp_photo);
    $infoext = explode(".",end($infofile));
    $imgext = end($infoext);

  // The file should be an image
  $errors = array();
  $errors += file_validate_is_image($file);
  $errors += file_validate_image_resolution($file, variable_get('user_picture_dimensions', '100x100'));
  $errors += file_validate_size($file, variable_get('user_picture_file_size', '30') * 1024);

  // Make sure file extension is a valid image
  if (!in_array(strtolower($imgext), array('jpg', 'png', 'gif'))) {
    $errors[] = ' invalid image file extension.';
  }

  if (count($errors)) {
    drupal_set_message(t('Profile Image Import:') . ' ' . $errors[0], 'warning');
    // Clean up (set fid to avoid error messages)
    $file->fid = 0; file_delete($file);
  }
  else {
    // We'll need a valid file id on the file object; file_save() will give us one
    $file = file_save($file);
    // Update user account (fid is not empty, status is temporary -- image
    // will be moved to proper directory and assigned to the user)
    $fields['field_enterprise_blog_picture'] = $file;
    $account = user_save($account, $fields);
}

Comment: Do you really need to add a picture to User picture field or can be added to the image field(from Field)?
Comment: Image field which had a separate table as "field_data field_enterprise_blog_picture".
Answer: Ok, here is my testing example. I can't say that it works perfectly but in my case it works fine. And, of course, you can modify/customize it by your needs if you want (add validation, check file path, directories, and so on..):
function _executeFile($uri, $uid) {

  $file_url = file_create_url($uri);
  $file = system_retrieve_file($file_url, NULL, TRUE, FILE_EXISTS_REPLACE);

  if ($file) {
    $user = user_load($uid);
    $file = file_load($file->fid);
    $file->status = FILE_STATUS_PERMANENT;
    file_save($file);

    // file_usage_add($file, 'MY_MODULE', 'enterprize_picture', $file->fid);

    $file_info = image_get_info($file->uri);

    $user->field_enterprise_blog_picture[LANGUAGE_NONE][0]['fid'] = $file->fid;
    $user->field_enterprise_blog_picture[LANGUAGE_NONE][0]['alt'] = '';
    $user->field_enterprise_blog_picture[LANGUAGE_NONE][0]['title'] = '';
    $user->field_enterprise_blog_picture[LANGUAGE_NONE][0]['width'] = $file_info['width'];
    $user->field_enterprise_blog_picture[LANGUAGE_NONE][0]['height'] = $file_info['height'];
    $user->field_enterprise_blog_picture[LANGUAGE_NONE][0]['uid'] = $file->uid;
    $user->field_enterprise_blog_picture[LANGUAGE_NONE][0]['filename'] = $file->filename;
    $user->field_enterprise_blog_picture[LANGUAGE_NONE][0]['uri'] = $file->uri;
    $user->field_enterprise_blog_picture[LANGUAGE_NONE][0]['filemime'] = $file->filemime;
    $user->field_enterprise_blog_picture[LANGUAGE_NONE][0]['filesize'] = $file->filesize;
    $user->field_enterprise_blog_picture[LANGUAGE_NONE][0]['status'] = '1';
    $user->field_enterprise_blog_picture[LANGUAGE_NONE][0]['timestamp'] = $file->timestamp;
    $user->field_enterprise_blog_picture[LANGUAGE_NONE][0]['rdf_mapping'] = array();

    user_save($user);
  }
  else {
    // SET VALIDATION ERROR
  }
}

and call it like this:
define('DRUPAL_ROOT', getcwd());
require_once './includes/bootstrap.inc';
require_once './includes/file.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
_executeFile($uri /* e.g.: 'public://OTHER-OpenSourceSystem_1600x1200.jpg' */, $uid);

First function gets two variables as arguments and loads user object
and creates file object from URI, and sets file object properties to
user file field and saves it;
Second piece of code bootstraps system and just calls that function.. You can set your validation rules here
Comment: Ok. I"ll try and let you know
Comment: Thank you. It's working in single trail. Now it's fine. Previously I struggled with this issue from few days..
Comment: @JSinha I forgot to mention that you also should add file usage to the added file with [file_usage_add()](https://api.drupal.org/api/drupal/includes%21file.inc/function/file_usage_add/7) function. It prevents deletion of that file by others.. I'll add it to my answer...


php:get only date from timestamp SQL

Question: Currently I have a datetime like this:
2012-07-24 11:52:01

Now i want to show only date like 2012-07-24.
Can anyone give any php function?
Thanks.
Answer: just follow the following procedure
date("Y-m-d",strtotime("2012-07-24 11:52:01"));

in above code strtotime() returns value of date in seconds and "Y-m-d" transfers it in Y-M-D format of date as date() method is used.
Answer: Go ahead and use PHP's DateTime class. I was reluctant to move away from functions to classes, but it's really not that hard. Just pass the date string into the class object and then use the format method to output the date string in the way you want.
http://php.net/manual/en/class.datetime.php
$dt = new DateTime('2012-07-24 11:52:01');
echo $dt->format('Y-m-d');

Answer: $date = "2012-07-24 11:52:01";
$pieces = explode(" ", $date);
echo $pieces[0];

Comment: While this code may answer the question, providing
additional context regarding _why_ and/or _how_ this code
answers the question would significantly improve its
long-term value.  Please [edit] your answer to add some
explanation.
Answer: Check php manual for more reference: http://php.net/manual/en/function.date.php
Little research please
$today = date("Y-m-d ");

php:get only date from timestamp SQL


Additional mail check by a custom script on Exchange Server

Question: Customer would like to check e-mail content (including attachment parsing) from a list of accounts and, in case of some detected trigger words, to send a copy of the mail to a person who has to be aware.
A fast head-on solution was to send copies of all received mails to an in-between address, which is monitored by the parsing script developed in Python. However it is an additional load for the Exchange mail server deployed at the customer side.
Is there a smarter way, e.g., on the level of hub transport servers, to have the mail check with a custom self-developed script/program for a defined list of corporate accounts (addresses only in the list, without access credentials)?
Answer: If you really need to run some custom logic applied to a mail flow, you can go with Exchange Transport Agents. With them you can get your custom code invoked during specific stages of the SMTP sessions or message processing. This feature is available in on-premises Exchange only.
See Microsoft docs for more details:  https://learn.microsoft.com/en-us/exchange/mail-flow/transport-agents/transport-agents?view=exchserver-2019


Google map marker location issue

Question: I use Googe Map API.
When I use

the position of the marker is shifted to the right.
But when I use

It is showing properly.
I need width 100% and marker to see at the center.
How to do it? I guess  the CSS should play its role but I dont know how to adjust it.
Thank you!
Comment: possible duplicate of [Google Maps div not showing up in JSBin](http://stackoverflow.com/questions/20572196/google-maps-div-not-showing-up-in-jsbin)
Answer: Oh! I found it really fast.

Google map marker location issue


How to convert rows to columns with multiple rows and nulls

Question: I hope you can help me on this one:
I want to create a query in order to have the records of a table as columns but this columns can have multiple rows.
Example:
| Id | Value  | ColumnName    |
| 1  | A      | Q1            |
| 2  | B      | Q2            |
| 3  | C      | Q2            |
| 4  | D      | Q2            |
| 5  | E      | Q3            |
| 6  | F      | Q3            |

This is what I want:
| Q1   | Q2   | Q3
| A    | B    | E
| NULL | C    | F
| NULL | D    | NULL

How can I get this result in one single query? (I really need to have this in a query because I need to create a view for this)
Thanks and regards!
Comment: What version of SQL Server are you on? 2012? 2016?
Comment: The version is 2014
Answer: You can use conditional aggregation with row_number():
select max(case when columnname = 'Q1' then value end) as q1,
       max(case when columnname = 'Q2' then value end) as q2,
       max(case when columnname = 'Q3' then value end) as q3
from (select t.*,
             row_number() over (partition by columnname order by id) as seqnum
      from t
     ) t
group by seqnum;

Answer: You can try using pivot
select pv.* from
tablename
pivot
(max(Value) for columnname in ([Q1],[Q2],[Q3])) as pv


Which metric use for problem of clustering spatial data of wind direction and speed?

Question: I have  two dimensional spatial (x,y - coordinates of meteo stations) data for small region (so I could neglect the shape of earth globe), for each (x,y) I have one observation of wind direction and speed I need to design metric for clustering problem of such data. It's simple to do when we consider only directions or only the speed of wind but how to combine these quantities ? I try to analyse this problem using R.
Comment: What is your goal?  How is the clustering going to be used?
Answer: Use a flexible clustering algorithm, such as e.g. OPTICS. Where you can put in arbitrary dissimilarity functions. Then define a dissimilarity that uses you value attributes, but filters on the geographic distance, i.e. the dissimilarity is maximal when the objects are geographically distant. Try with different distances to find clusters of different geographical size.


Column core_event.hometask does not exist

Question: When I run my Django project on production server, I have this error:
ProgrammingError at /admin/core/event/

column core_event.hometask does not exist
LINE 1: ..._event"."is_approved", "core_event"."event_type", "core_even...

What I should do to fix it? Now I haven't "hometask" field in my model:
class Event(models.Model):
    name = models.CharField(max_length=100, null=True)
    author = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
    description = models.TextField(max_length=1000, blank=True, null=True)
    date_start = models.DateTimeField(null=True, blank=True)
    date_finish = models.DateTimeField(null=True, blank=True)

    image = models.ImageField(
        upload_to="event_images/", default='event_images/default.png', blank=True, null=True)
    is_approved = models.BooleanField(null=True)

    TYPE_CHOICES = (
        ('Event', "Мероприятие"),
        ('Lesson', "Урок"),
    )
    event_type = models.CharField(choices=TYPE_CHOICES, max_length=200, default="Мероприятие")
    topics = ArrayField(models.CharField(max_length=200), blank=True, null=True)
    materials = ArrayField(models.URLField(), blank=True, null=True)
    possible_users = models.ManyToManyField("core.User", blank=True, related_name='possible_users')
    actual_users = models.ManyToManyField("core.User", blank=True, related_name='actual_users')
    classes = models.ManyToManyField("core.Class", blank=True, related_name='classes')

Answer: From what you posted, looks like the field existed in the model before but not anymore. However, your admin.py still has reference to the old field of hometask.
So, go to admin.py, search for hometask, and remove it.


Transform JSON and create new one

Question: I'm working with JSON in Java, and I want to trasnform a JSON I have as entry :
{
   "index":{
      "mutlipleIndices":[
         {
            "index":"languages",
            "values":[
               "English",
               "German"
            ]
         },
         {
            "index":"editors",
            "values":[
               "AC. Renus",
               "Lodiga"
            ]
         }
      ],
      "simpleIndices":[
         {
            "index":"bookName",
            "values":"A song Of Ice and fire"
         },
         {
            "index":"nbPages",
            "valeurs":1600
         }
      ]
   }
}

int this :
    {
        "data": { ... Put here the entry JSON ... },
        "flatData": [
            {
                "key": "languages",
                "type": "string",
                "key_type": "languages.string",
                "value_string": ["English", "German"]
            },
            {
                "key": "editors",
                "type": "string",
                "key_type": "editors.string",
                "value_string": ["AC. Renus", "Lodiga"]
            },
            {
                "key": "bookName",
                "type": "string",
                "key_type": "bookName.string",
                "value_string": "A song Of Ice and fire"
            },
            {
                "key": "nbPages",
                "type": "float",
                "key_type": "nbPages.float",
                "value_float": 1600
            }
        ]
    }

My entry JSON is a JsonNode (Jackson library), how can I iterate on that object and create a new one ?
Basically what I thought I'd do is iternate on the entry json, find an entry and transform it
Thanks in advance
Answer: Create 2 pojos

Mapping the input json (let's call it MyJsonInput.java)
Mapping the output you want (let's call it MyOutputObject.java).

These 2 classes should have fields which matches the json structure.
Create a mapper:
ObjectMapper objectMapper = new ObjectMapper();

Read the json and translate it into your object:
MyJsonInput myInput = objectMapper.readValue(json, MyJsonInput.class);  //where json is a string with the content of your json file.

Now you have a MyJsonInput instance (myInput) containing the json data and you can do your logic to flatten it and fill your MyOutputObject.
To get the json string of MyOutputObject instance use:
String outputAsString = objectMapper.writeValueAsString(myOutputObject);

You can also threat your both input and output as a generic Map<String,Object> but in my opinion not the best way because it can get very complicated reading and parsing maps containing other maps, and not to mention that you need to cast your data into the appropriate type (string, number etc..)
Answer: https://github.com/octomix/josson
https://mvnrepository.com/artifact/com.octomix.josson/josson
implementation 'com.octomix.josson:josson:1.3.21'

-------------------------------------------------

Jossons jossons = new Jossons();
jossons.putDataset("input", Josson.fromJsonString(
    "{\n" +
    "   \"index\":{\n" +
    "      \"multipleIndices\":[\n" +
    "         {\n" +
    "            \"index\":\"languages\",\n" +
    "            \"values\":[\n" +
    "               \"English\",\n" +
    "               \"German\"\n" +
    "            ]\n" +
    "         },\n" +
    "         {\n" +
    "            \"index\":\"editors\",\n" +
    "            \"values\":[\n" +
    "               \"AC. Renus\",\n" +
    "               \"Lodiga\"\n" +
    "            ]\n" +
    "         }\n" +
    "      ],\n" +
    "      \"simpleIndices\":[\n" +
    "         {\n" +
    "            \"index\":\"bookName\",\n" +
    "            \"values\":\"A song Of Ice and fire\"\n" +
    "         },\n" +
    "         {\n" +
    "            \"index\":\"nbPages\",\n" +
    "            \"values\":1600\n" +
    "         }\n" +
    "      ]\n" +
    "   }\n" +
    "}"));
Map<String, String> dictionaryFinder = new HashMap<>();

// Define a dictionary function, $0 is the function parameter.
dictionaryFinder.put("flatIndices()",
    "$0->map(" +
    "key:index," +
    "type:if(values.isArray(),values[0],values).if(isText(),'string','float')," +
    "key_type:concat(index,'.',if(values.isArray(),values[0],values).if(isText(),'string','float'))," +
    "value_string:values)");

// Define a left concatenate operation to combine two arrays.
dictionaryFinder.put("allIndices",
    "flatIndices(input->index.multipleIndices) <+< flatIndices(input->index.simpleIndices)");

ResolverProgress progress = new ResolverProgress("\nProgress:");

// The query is a left concatenate operation to combine two objects.
JsonNode output = jossons.evaluateQueryWithResolver(
    "input->toObject('data') <+< allIndices->toObject('flatData')",
    dictionaryFinder::get, null, progress);

// Print result.
System.out.println(output == null ? null : output.toPrettyString());
// Print resolution progress.
System.out.println(String.join("\n", progress.getSteps()));

Output
{
  "data" : {
    "index" : {
      "multipleIndices" : [ {
        "index" : "languages",
        "values" : [ "English", "German" ]
      }, {
        "index" : "editors",
        "values" : [ "AC. Renus", "Lodiga" ]
      } ],
      "simpleIndices" : [ {
        "index" : "bookName",
        "values" : "A song Of Ice and fire"
      }, {
        "index" : "nbPages",
        "values" : 1600
      } ]
    }
  },
  "flatData" : [ {
    "key" : "languages",
    "type" : "string",
    "key_type" : "languages.string",
    "value_string" : [ "English", "German" ]
  }, {
    "key" : "editors",
    "type" : "string",
    "key_type" : "editors.string",
    "value_string" : [ "AC. Renus", "Lodiga" ]
  }, {
    "key" : "bookName",
    "type" : "string",
    "key_type" : "bookName.string",
    "value_string" : "A song Of Ice and fire"
  }, {
    "key" : "nbPages",
    "type" : "float",
    "key_type" : "nbPages.float",
    "value_string" : 1600
  } ]
}

Progress:
Round 1 : Resolving allIndices from flatIndices(input->index.multipleIndices) <+< flatIndices(input->index.simpleIndices)
Round 1 : Resolving flatIndices(input->index.multipleIndices) from $0->map(key:index,type:if(values.isArray(),values[0],values).if(isText(),'string','float'),key_type:concat(index,'.',if(values.isArray(),values[0],values).if(isText(),'string','float')),value_string:values)
Round 1 : Resolved flatIndices(input->index.multipleIndices) = Array with 2 elements
Round 2 : Resolving flatIndices(input->index.simpleIndices) from $0->map(key:index,type:if(values.isArray(),values[0],values).if(isText(),'string','float'),key_type:concat(index,'.',if(values.isArray(),values[0],values).if(isText(),'string','float')),value_string:values)
Round 2 : Resolved flatIndices(input->index.simpleIndices) = Array with 2 elements
Round 3 : Resolved allIndices = Array with 4 elements
Round 4 : Resolved query result = Object with 2 elements

Transform JSON and create new one


Correct way to add a tweet button?

Question: I'm trying to add a tweet button to my node.tpl.php in Drupal 6 - https://dev.twitter.com/docs/tweet-button.
I literally place the html+javascript within node.tpl like so:
Tweet
<

The result is a flickering button every time I refresh, so I'm thinking the javascript is loading incorrectly?
Ideally, I'd like to load the javascript within page.tpl.php, and ensure that it applies to node.tpl, but it doesn't appear to be working. I've also tried loading it using drupal_add_js within template.php various preprocessor methods.
I rather not use any of the social media modules - such as AddToAny, ShareThis, or ServiceLinks - partly because I feel this should be cut and dry w/o module dependency.
So I guess my question is - what is the best way to load that twitter javascript code within node.tpl to avoid the flickering button?
Answer: Do not place the ',array(
  'type' => 'inline',
  'scope' => 'footer'
));

Comment: I'll lose some points for this, but something isn't sitting right. Let's say I don't want to use hook_init() in a custom module to make this call, and instead add it to my theme - I couldn't get your above code to work correctly within HOOK_preprocess_page within my themes template.php. I think part of the reason is that the custom theme we're using doesn't print javascripts out in footer, only header or Drupal.setting. Even if I change your code to address those scopes, I can't get the script to load anywhere. I'll research "page's callback" function a bit more, but any hints?

Correct way to add a tweet button?


Do imbalanced categorical predictors do any harm when classifying?

Question: Assume I want to do some, say, churn analysis on a dataset. Decision Trees, for instance, are relatively robust to skewed distributions in the (numerical) features, but are rather poor on imbalanced targets (as is standard).
My question is: what about imbalanced categorical features e.g., the feature sex having 10% male and 90% females? Are classifiers such as Random Forest, Logistic Regression, and SVM robust against imbalanced categorical features? If not, are there some ways to overcome this by e.g., under/oversample features or...?
Clearly, if we have a small dataset it is a problem, but generally speaking, I am curious.
Comment: I believe Yes but would like to hear of any systematic research into the question.
Comment: That is exactly my thoughts
Comment: A related research area is optimal experimental design for (e.g.) logistic regressions. One way to measure the a priori effect of covariate imbalance would be to compare a heavily imbalanced design of size N to the optimal design of size N (given an optimality criterion, a parameter vector, etc. etc.). I think this is where the systematic research lies.
Comment: Agreed, but if there was some analytical proof/papers regarding it, that would be great. I might set down and to some testing my self instead. I really struggle to find anything about it, so I doubt it is a problem which is often encountered (thus is maybe not problem?)
Answer: It might be that, with the feature having so little diversity, the usual idea in regression and supervised learning problems to use variation in the features to explain variation in the outcome breaks down. However, it might be that a feature that occasionally takes a value is quite informative. You give an example where $90\%$ of the observations are female and the remaining $10\%$ male. It might be that subject sex is a strong predictor of the outcome and is screaming at you that a particular outcome is likely, such as using the sex of a cow to predict if it can produce milk. Thus, I would hesitate to exclude a feature just because it lacks balance in its categories.
Comment: (+1). A subsequent question might be "How likely is it that the predictor is screaming at me just out of (bad) luck?".


Integral $ \int_E \frac{1}{x^ay^b}dxdy \qquad E={x>0,y>0,xy \geq 1}$

Question: I'm asked to compute:
$$ \int_E \frac{1}{x^ay^b}dxdy \qquad E={x>0,y>0,xy \geq} 1$$
but I'm really finding difficulties in doing it as the domain is unlimited. I can pretty much solve this kind of integrals when the domain is limited and there is a problem in one or more than one points, but how can I compute this in an efficient way?
I am also a little bit concerned about polar coordinates: I think that it could be a good way to do it, but people here, on other questions, told me that I should avoid doing it to prevent other issues.
Can you please help me understanding how to proceed in problems like this one?
Thanks in advance.
EDIT
We notice that we can express the domain as $E=\{x>0, y>\frac{1}{x}\}$ so we have:
$$\int_E \frac{1}{x^ay^b}dxdy= \int_0^{+\infty}\left(\int_{\frac{1}{x}}^{+\infty}\frac{1}{x^ay^b}dy\right)dx=\int_0^{+\infty}\frac{1}{x^a}\left[ \frac{1}{(1-b)y^{b-1}} \right]_{\frac{1}{x}}^{\infty}dx$$
Let's suppose $b>1$ (otherwise the integral diverges):
$$\frac{-1}{b-1}\int_0^{+\infty} \frac{1}{x^a}x^{b-1}dx=\frac{-1}{b-1}\int_0^{+\infty} \frac{1}{x^{a-b+1}}dx$$
But now we have something that diverges for all values of $a,b$ as it has both problems in $0$ and at $\infty$.
Is this correct?
Comment: When you integrate with respect to $y$ first, then with respect to $x$, that is an iterated integral. If you integrate with respect to $x$ first, then with respect to $y$, that is the other iterated integral. The double integral integrates both together. When the function is continuous and the region is bounded, all three will diverge or converge to the same limit together. But for discontinuous functions or unbounded regions, convergence of the double integral still implies convergence of the iterateds to the same value, but divergence of the double does not imply divergence of the iterateds.
Comment: The condintions describing $E$ are equivalent to $00$). So you could first integrate over $y$, form $1/x$ to $\infty$, and then over $x$ from $0$ to $\infty$. Does that make sense?
Comment: It seems like the integral diverges though... Is that a possible answer?
Comment: Sure it is a possible answer and your process it's exactly what I did. But I don't feel so confident about it.. I don't know if it is formally correct.
Comment: If the double integral converges, then both of the iterated integrals must also converge. (Going the other way is not always true, but double Integral $\implies$ iterated integrals always holds.) Since one of the iterated integrals diverges, the double integral cannot converge.
Comment: Can you please tell me what do you mean by iterated integrals? And, btw, if you want to review my answer I'll be glad to upvote and accept your answer.
Comment: Thanks a lot! If you want to post an answer I'll upvote you!
Answer: Because convergence of the double integral $$\int_E \frac{dxdy}{x^ay^b}$$ would imply convergence of both the iterated integrals $$\int_0^\infty \frac 1{x^a}\int_{1/x}^\infty \frac{dy}{y^b}dx$$ and $$\int_0^\infty \frac 1{y^b}\int_{1/y}^\infty \frac{dx}{x^a}dy,$$ the fact that $\int_0^\infty \frac 1{x^a}\int_{1/x}^\infty \frac{dy}{y^b}dx$ diverges to $\infty$ is enough to prove that $\int_E \frac{dxdy}{x^ay^b}$ does not converge.
(It is not enough to prove it diverges to $\infty$ as well. It could potentially diverge in other ways, but it cannot converge while one of the iterated integrals diverges.)
So your calculation is enough to show the integral does not converge.
Comment: Thanks a lot! :)


How to calculate cos, sine, etc. Without a calculator?

Question: I am currently studying computer science at university, and one of this semesters courses I am taking is linear algebra and calculus II. Every week there is a graded quiz, and a mid and end of semester exam. We are not allowed to use calculators in any of these.
Today in the quiz, I failed to get an answer to one of the questions regarding the angle between two vectors, because I had to work out $\cos x = \frac2{2\sqrt\frac43}$. But I had no idea what angle that resulted in.
I was just wondering if anyone had some tips as to how best to solve these problems in the future?
Comment: $$\frac{2}{2\sqrt{\frac{4}{3}}} = \frac{\sqrt{3}}{2}.$$
Comment: $\cos\bigg(\dfrac\pi2~x\bigg) \approx \big(1-x^2\big) \bigg(1-\dfrac{x^2}{4.5}\bigg)~$ makes for a decent approximation when $x\in\big[0,1\big]$.
Answer: Well, surely the first step is to write that as $\cos(x) = \frac{\sqrt{3}}{2}$. Could you have done it then?
At that point, it's about remembering a common triangle.
Answer: You can draw a unit circle and then calculate the trig values provided you can use a protractor+compass. Also, it is generally recommended one learns sin cos tan values for all  multiples of $15^\circ$.
Also, in your case, it can be greatly simplified as well... yielding :
$$\cos(x) = \frac{\sqrt{3}}{2} \Rightarrow x = 30^\circ$$
$30$ degrees is one solution.
Also... learning values of degrees 0,30,45,60,90 and 15 can make it easy to compute many problems you come across by using identities like sin(a+b) expansion, etc.
Comment: Also... learning values of degrees 0,30,45,60,90 and 15 can make it easy to compute many problems you come across by using identities like sin(a+b) expansion, etc.
Comment: NB I've changed the degree numbers by adding a $^\circ$ to them. The usual trigonometric functions are defined for radians (i.e. $x=\frac\pi6$).
Comment: I've mentioned it's degrees in my answer... thanks anyway!
Answer: If you simplify what you got, it is $\frac{\sqrt{3}}{2}$.  There are several special angles related to a few triangles.  The triangles (in degrees) are the $[30-60-90][1]$ triangle and the $[45-45-90][2]$ (isoceles) triangle.  You can use these to calculate a number of cosines and sines using the unit circle.  For example, if you want $\sin\left(\frac{3\pi}{4}\right)$, you notice that this is $\frac{\pi}{4}$ radians beyond the $y$-axis.  Thus you can embed a $45-45-90$ triangle against the $y$-axis and calculate values.  Here is a video.


clean VS 2015 Enterprise + Xamarin Install: error: NuGet Package restore failed for project

Question: Hello i have a clean Installation of VS2015 Enterprise + Xamarin.
Then just start a New Projekt (Xamarin Forms Portable) add a Button and want to test on Android Emu.
Then i get the Following 5 Errors and i don't know, how to solved it.
errors
start Projekt
Comment: Same problem here, using the Caliburn.Micro Hello.Forms sample app.
Answer: Try to restore the NuGet packages manually. Navigate to Tools > Nuget Package Manager > Manage NuGet Packages for Solution. If you see the button "Restore packages," click it. Make sure the packages are up to date. Furthermore, check your Android SDK is up to date. Navigate to Tools > Android > Android SDK Manager.
Comment: no button "Restore packages", nuget packages are up to date. Android sdk install all updates. still don't work
thx for help
Comment: @evgen1j that means you probably use a very old NuGet manager. Try to use Tools|Extensions and Updates to update to the latest.
Answer: If you don't need the UWP project, you can delete it or try yo install this nuget package: https://www.nuget.org/packages/Xamarin.Forms/188.8.131.5282
For the other errors, install this Nuget Package: https://www.nuget.org/packages/Xamarin.Android.Support.v7.MediaRouter/18.104.22.168
Answer: Maybe a long shot but I had similar problems when restoring packages in Visual Studio 2015, and that was caused by a custom nuget server I added to sources (with authetication). Try temporary disable any of these if you got any, in the Tools -> Options -> NuGet package manager
Answer: You can try the following:

Remove the reference of Xamarin Forms portable library from your WinSetupDemo.UWP project, I believe Xamarin forms doesn't support UWP unless you use Xamarin Forms v2.1 and above
Make sure that the Android Support Library is installed correctly, search for it in the Xamarin components store and follow the setup instructions, make sure it installs correctly, one of the reasons it fails is that your directory hiererchy is too deep so that file names become too long, if this is the case, try installing your Android SDK at a top level directory such as C:\Android


Is the AUC a robust metric to determine which network architecture to use?

Question: I would like to figure out which hyperparameters/network architectures work best on a specific binary dataset.  To compare them, I do k-fold cross-validation, use different MLP or ConvNet architectures and tune hyperparameters for both. For each, I compute the ROC-curves and am supposing that the iterations with higher AUC (area under curve) are necessarily better.  Is this justifiable?
Comment: This is 100% justifiable in ML.
Comment: thanks, are there other metrics worth exploring as well?
Answer: This is standard practice: run a lot of experiments, pick the one with the highest score on the hold-out. The caveats here are straightforward: The AUC is a statistic, and like every other statistic it is subject to random variation, so picking the highest AUC value might be slightly worse in reality than another hyper-parameter configuration by chance. But this is the nature of living with randomness.
You might be interested in this answer, which indirectly addresses how one might efficiently search for a good hyper-parameter configuration:
Optimization when Cost Function Slow to Evaluate
You could also carry out a statistical test to compare whether one ROC curve is significantly better than another. See: Statistical significance (p-value) for comparing two classifiers with respect to (mean) ROC AUC, sensitivity and specificity
There are all sorts of other metrics that people use to measure model performance. Some of them are:

log loss/cross-entropy
Brier score
TPR at a specific FPR
Area under the precision-recall curve

Generally, you might be interested in scoring-rules.


Solve for x when $(\log_x (5x))(\log_7 x)=2$

Question: I've been trying to use the change of base property but I'm not having much luck. Can anyone give me any ideas on how I should approach this problem? The answer is 49/5
Thanks.
Answer: Hint:
$$\log_x(5x)=\frac{2}{\log_7 x} = \frac{\log_7 49}{\log_7 x}$$
I hope that you have tested the conditions for the logarithms to be defined.
Answer: Hint:  Use properties of logs:  $\log xy=\log x+\log y\\\log\frac xy=\log x-\log y\\\log a^x=x\log a\\b^{\log_bx}=x=\log_bb^x\\\log_ba=\frac{\log_xa}{\log_xb}$.
Answer: Using change-of-bases, we have $\log_x(5x) \cdot \log_7(x)= \frac{\log (5x)}{\log (x)} \cdot \frac{\log (x)}{\log (7)} = \frac{\log (5x)}{\log 7} = \log_7(5x)= 2$, where the base of the intermediate $\log$s do not really matter.
Answer: $$\log_x 5x \cdot \log_7 x = 2$$
$$\log_x 5x = \frac{2}{\log_7 x}$$
$$\log_x 5x = \frac{2\log_x 7}{log_x x}$$
$$\log_x 5x = 2\log_x 7$$
$$\log_x 5x = \log_x 49$$
$$\implies 5x = 49$$
$$x =\frac{49}{5}$$


How to Explode PySpark column having multiple dictionaries in one row

Question: I have a spark dataframe with one column having multiple dictionaries:

id
result

1
{'key1':'a', 'key2':'b'}, {'key1':'d', 'key2':'e'}, {'key1':'m', 'key2':'n'}

2
{'key1':'r', 'key2':'s'}, {'key1':'t', 'key2':'u'}

I need the final output as:

id
key1
key2

1
a
b

1
d
e

1
m
n

2
r
s

2
t
u

And planning to explode this twice to get the results.
Although, The column result is of StringType() and therefore I am unable to explode it using the explode function:
df.withColumn("output", explode(col("result")))

Error:

AnalysisException: cannot resolve 'explode(result)' due to data type mismatch: input to function explode should be array or map type, not string;
'Project [result#9651, explode(result#9651) AS output#9660]
+- Relation[result#9651] json

Please help on how to resolve this.
Answer: First convert the result column to an array of struct structure using the from_json function, and then expand it using the inline function.
json_schema = """
    array<struct<key1:string,key2:string>>
"""
df = df.withColumn('result', F.from_json(F.concat(F.lit('['), 'result', F.lit(']')), json_schema)) \
    .selectExpr('id', 'inline(result)')
df.show(truncate=False)


Posting form data

Question: I have an HTML form which I want to post data to then display some text to the user.  I've heard several people discuss this idea:
should the user go from [form page] -> [processing form post page] -> [display page] or should the user just go to a combined [form page] -> [processing form / display page]
I've heard arguments the former is more secure while the latter is less redirects.
What are some answers?
Comment: I see this a lot, even no response when someone who was thanked by the OP nicely describes the accept button and asks to click it. The FAQ should be updated to give acceptance its own title; and more importantly there should be a limit to the open questions one can have, say 5. Questions should have to be accepted or closed.
Comment: @SuperDuck maybe that number should be dependent on how much rep you have. Someone who has asked a large number of questions is likely to have more (truly) unanswered questions.
Comment: @zzzzBov - I agree, that would be better so the number can even begin with 2 or 3 for the first questions and get much bigger shortly; in the end we just want new users to learn and get used to it.
Comment: @ everyone:  I've gone back and "Accepted" all of my answers.
Answer: To avoid caching issues, resubmission on refresh issues and similar problems: Use the POST-REDIRECT-GET pattern.

Browser makes HTTP POST request with form data
Server processes data and responds with a redirect response
Browser makes HTTP GET request (possibly including an id that is related to the submitted data in the query string)
Server responds with a 200 response and the information
Answer: From what your question asked, you could just have the [form page] -> [form page to process and display].

Posting form data


Probability exercise: exchange uniform in a soccer match

Question: At the end of a soccer match, each of the 22 players exchanges the uniform of his own team randomly with one of the other 21 players (it means that if player A exchanges its uniform with player B, also B exchanges its uniform with A). Let $X$ be the number of players that after the exchange still wear the uniform of their original team. Compute
1) $P(X=7)$
2) $P(X=6)$
3) $P(X=8)$
I thought that $X=7$ and $X=6$ are impossible events, so that their probability is 0. I have lots of troubles for point 3). I'd like to compute this probability as
$\frac{\text{number of favourable cases}}{\text{total number of cases}}$.
I considered as total number of cases the number of possible couples of players, i.e. $\binom{22}{2}$. So, for instance, $P(X=0)=11^2/\binom{22}{2}$.
But, how can I compute the number of favourable couples for the event $X=8$?
Thanks.
Answer: By symmetry (essentially the argument that rules out $X=7$ and $X=6$), there must be four players from each team that keep their colours. There are $11\choose 4$ ways to pick these in the first team and after that $3$ ways to pick the swapping partner of the alphabetically first of these players. The same goes for the other team. Finally, there are $(11-4)!$ ways to macth the remaining players with opponent players.
Comment: There is something that I don't understand.
Comment: Let me explain: 1) I guess you meant $(11-4)^2$ rather than $(11-4)!$. 2) When you do $\binom{11}{4}\times 3$ you count in this way more than once a given couple. For instance, call A, B, C, D, E the first five players of the first team; then, $\{A,B,C,D\}$ and $\{A,B,C,E\}$ are two of the $\binom{11}{4}$ possible combinations. So, when you perform $\binom{11}{4}\times 3$ you count twice the couple $AB$, $BC$ and $AC$. 3)Please, could you write your complete formula for $P(X=8)$?


Does an ajax callback work within a Views style plugin?

Question: My module has a custom Views style plugin. In the style settings form, I want to implement an ajax callback, such as described here: https://www.drupal.org/docs/8/api/javascript-api/ajax-forms
However, I haven't had any luck. I can get a spinning effect, but nothing happens afterward. Here's an example of what I've tried:
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\HtmlCommand;

  public function TestCallback(array $form, FormStateInterface $form_state) {
    $ajax_response = new AjaxResponse();
    $text = 'Text to see if this is working';
    $ajax_response->addCommand(new HtmlCommand('#foo', $text));

    return $ajax_response;
  }

  /**
   * {@inheritdoc}
   */
  public function buildOptionsForm(&$form, FormStateInterface $form_state) {
    parent::buildOptionsForm($form, $form_state);

    $form['test'] = [
      '#title' => t('TEST!'),
      '#type' => 'select',
      '#options' => [
        '' => t('None'),
        'foo' => t('Bar'),
      ],
      '#ajax' => [
        'event' => 'change',
        'callback' => '::TestCallback',
    // having the line below uncommented seems to help
    //'url' => views_ui_build_form_url($form_state),
      ],
      '#prefix' => '

',
      '#default_value' => '',
    ];
  }

If I uncomment the commented 'url', I get this error:
Uncaught TypeError: Cannot read property 'settings' of undefined
at resetSize (<anonymous>:34:32)
at later (debounce.js?v=8.6.3:20)

If I keep it commented, I get:
Failed to load resource: the server responded with a status of 500 ()
/admin/structure/views/ajax/display/view_name/page_1/style_options?
_wrapper_format=drupal_ajax&ajax_form=1&_wrapper_format=drupal_ajax:1
Uncaught Drupal.AjaxError
ajax.js?v=8.6.3:500

What's missing and/or incorrect?
Comment: I believe it could have something to do about a missing form ID for the style plugin.
Answer: From what I understand seeing the AJAX docs, I think you're not supposed to return an AjaxResponse object. You're supposed to return a renderable array from the Ajax callback.
Sample Code
public function buildOptionsForm(&$form, FormStateInterface $form_state) {
  parent::buildOptionsForm($form, $form_state);
  $form['test'] = [
    '#title' => t('TEST!'),
    '#type' => 'select',
    '#options' => [
      '' => t('None'),
      'foo' => t('Bar'),
    ],
    '#ajax' => [
      'event' => 'change',
      'wrapper' => 'ajax-output-container',
      // Since views style options forms are complex, they're built by
      // Drupal in a different way. To bypass this problem we need to
      // provide the full path to the Ajax callback.
      'callback' => __CLASS__ . '::testCallback',
    ],
    '#prefix' => '

',
    '#default_value' => '',
  ];
}

/**
 * This is the AJAX callback.
 *
 * It generates the output for the AJAX request. The output REPLACES
 * the "wrapper" you define in #ajax.
 */
public function testCallback(array $form, FormStateInterface $form_state) {
  // This element will replace the DIV#foo you have in your #prefix.
  $elem = [
    '#type' => 'markup',
    '#markup' => '
Is it not working!>
',
  ];
  return $elem;
}

Debugging

Make sure that on page load, you're getting a div with the correct ID in your field prefix. You can put some default text in the prefix so that you can see it on page load?
If HTML tags are being stripped from your #prefix markup for some reason, then try injecting a separate item in the form with #markup.
Comment: The addition of "'callback' => __CLASS__ . '::testCallback'," makes it work!
Comment: Thanks for including the sample code. I'm still getting the same errors, unfortunately.
Comment: Can you share the entire error message backtrace? Can you see in the network tab of the dev console to check what output Drupal is returning for the AJAX request?
Comment: OK, I'm getting this in the DB log: Symfony\Component\HttpKernel\Exception\HttpException: The specified #ajax callback is empty or not callable. in Drupal\Core\Form\FormAjaxResponseBuilder->buildResponse() (line 67 of /app/web/core/lib/Drupal/Core/Form/FormAjaxResponseBuilder.php).
Comment: If I click on the URL in the network tab, I also see this:
[{
 "command": "insert",
 "method": "prepend",
 "selector": null,
 "data": "\n\n\u003C!-- THEME DEBUG ... BEGIN OUTPUT from \u0027core\/themes\/classy\/templates\/misc\/status-messages.html.twig\u0027 --... Error message\u003C\/h2\u003E\n                    An unrecoverable error occurred. The uploaded file likely exceeded the maximum file size (100 MB) that this server supports.\n                \u003C\/div\u003E\n      \u003C\/div\u003E\n    \n\u003C!-- END OUTPUT ...",
 "settings": null
}]
Comment: I had to add the double colons and the rest works for me correctly.
Comment: Followed the debugging steps, but still the same issues. What Style plugin have you been testing this on?
Comment: Tried this on a custom styles plugin I was working on. Now it should work for sure.
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/88710/discussion-between-jigar-mehta-and-andileco).
Answer: $route_name = "views_ui.form_{$form_key}"; might be the problem.
Try to print somewhere this result under buildOptionsForm function and see if it is the problem: views_ui_build_form_url($form_state)->toString();
If You keep it commented, error happens because their is no url nor '#wrapper' which is needed for ajax.
Here you can investigate this error deeper:
https://api.drupal.org/api/drupal/core%21modules%21views_ui%21admin.inc/function/views_ui_build_form_url/8.2.x
Answer: I think you maybe experiencing an issue related to this Drupal core issue. See this issue comment and this one about implementing a work-around.


Permutation/Combination problem - choosing 2 objects from different categories

Question: Context: there are three candies in a basket (5 red, 4 blue, 5 green). How many ways can you choose 2 candies with different color?
Should I use permutation or combination w/ this? I tried using: 14!/(14-2)! = 182 ways; but it's marked as wrong.
Answer: Hint:
You can choose $5\times4$ pairs of candies s.t. one of them is red and one of them is blue.
Of course there are more possibilities.
Comment: Sorry, but I still don't get it! So by 5 x 4 is it literally 5 times 4 (like 20)?
Comment: Yes. Do you agree that there are $20$ possibilities to choose a pair of candies such that one of them is red and the other is blue? Btw, what do you mean with: "there are three candies in a basket". Maybe I misunderstand something there. Aren't there $14$ candies in total?
Comment: Yes I agree. Also I meant 3 groups. So yeah, there are 14 candies.
Comment: Well then: $5\times 4+5\times5+4\times5=65$ possibilities. The first term corresponds with "red and blue" the second with "red and green" and the third with "blue and green".


ActiveModel::Model inheritance not working as expected

Question: I'm trying to use inheritance with the classical "type" attribute. On initialize User with type: "Admin" I expect an Admin object but it returns a User object. How can I make a class to act like a model and also make it act like it has STI?
class User
  include ActiveModel::Model
  attr_accessor :type

  def persisted?
    false
  end
end

class Admin < User
end

user = User.new(type: "Admin")
 #=> #<User:0x007ff68a1ade60 @type="Admin">
Comment: `type` is just an instance variable here. When you instantiate a new user and provide `type` it just sets that variable. `Admin.new` will give you an object of class `Admin`.
Answer: class User
  include ActiveModel::Model

  def self.build(type: 'User')
    klass = Kernel.const_get(type)
    if klass.ancestors.include?(User)
      klass.new
    else
      raise "you are just not my type"
    end
  end

  def persisted?
    false
  end
end

class Admin < User
end

> u = User.build(type: 'Admin) # => instance of Admin
> u = User.build # => instance of User
> u = User.build(type: 'Object') # => RuntimeError

Comment: I think more is needed for subclasses to work with form_for


How can I filter information from a Django error message?

Question: When an error occurs on my Django site (typically a 500), I get a really long error message back from the server (as shown in this example):
TypeError at /c/ajax/import_onboard/
argument of type 'NoneType' is not iterable

Request Method: POST
Request URL: http://127.0.0.1:8000/c/ajax/import_onboard/
Django Version: 1.8.11
Python Executable: C:\Python27\python.exe
Python Version: 2.7.10
Python Path: ['C:\\Repos\\my-app', 'C:\\Python27\\lib\\site-packages\\setuptools-18.0.1-py2
.7.egg', 'C:\\windows\\system32\\python27.zip', 'C:\\Python27\\DLLs', 'C:\\Python27\\lib', 'C:\\Python27
\\lib\\plat-win', 'C:\\Python27\\lib\\lib-tk', 'C:\\Python27', 'C:\\Python27\\lib\\site-packages']
Server time: Tue, 19 Jul 2016 14:59:19 +0000
Installed Applications:
('myapp_1',
 'myapp_2',
 'myapp_3',
 'django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'debug_toolbar',
 'debug_panel')
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware',
 'debug_panel.middleware.DebugPanelMiddleware')

Traceback:
File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in get_response
  132.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Python27\lib\site-packages\django\views\decorators\csrf.py" in wrapped_view
  58.         return view_func(*args, **kwargs)

... snip ...

I hate having such a long response. Is there a way I can remove items like Python Version, Python Path, Installed Applications, etc. from what gets printed? I'd love to just have the traceback info so I don't have to scroll down to see where the problem is.
Answer: You may redefine error view with own template:
handler500 = 'mysite.views.my_custom_error_view'

https://docs.djangoproject.com/en/1.9/topics/http/views/#customizing-error-views
no other way.


Can I use the first value of a multivalue field as another field? ("Cover" use case)

Question: My content type uses an unlimited number of images as "screenshot".
I would like to be able to manage the FIRST screenshot of the set as the "cover" of the content type, so to define a "field_cover" and telling Drupal "The value for this field is the first value of field_screenshot".
In this way I could reference field_cover in my views for some special cases (like showing the latest mynodes in home page, using the "cover" as the image).
Answer: I'm not aware of a "wrapper" field type, but you have a few options.
I've done the same myself in Views by filtering by the "delta" value, which is the individual values in a multivalue field. That way it's easy to require "delta = 0" and get the first value. This has a limitation of currently not working with arguments/contextual filters though.
A second option is the to ctools recently added support for delta values. You can render a field and set both offset, range and reversal of deltas.
Final option I can think of is Computed Field, which could be programmatically coded to act as field wrapper.
Comment: I didn't think of the "delta" options in filters... thank you. By now this works for me.


When will a bowler's delivery be declared as a dead ball?

Question: What is the term dead ball mean in Cricket?
and
When will be a bowler's delivery considered as a dead ball?
Answer: Note that while a no ball and a wide ball are types of delivery, dead ball is a state. Put simply, the ball is not dead whenever it is in play.
According to Law 23.5:

The ball ceases to be dead - that is, it comes into play - when the bowler starts his run up or, if he has no run up, his bowling action.

The ball then will eventually become dead in different ways. The most common outcome is probably when the ball, after being played by the batsman, becomes "finally settled in the hands of the wicket-keeper or of the bowler" (Law 23.1). It is also dead, for instance, after a batsman is dismissed, a boundary is scored, or lost ball is called. There are further instances where umpires explicitly declare the ball to be dead: these include when a player is seriously injured, or when the bails fall from the striker's wicket before he plays the ball.
In relation to your second question, dead balls are counted as one of the over, unless:

the striker has not had an opportunity to play it (for instance, if the bowler drops the ball during his run up)
the striker was not ready (with a good reason) and did not attempt to play the ball (for instance, if the batsman pulls away due to movement behind the bowler's arm, and the bowler still bowls the ball)

This is merely a summary of the dead ball law (Law 23) and it is worth reading it to get a fuller understanding.


Integer solutions to $x^2+1=ay$

Question: I'd like to know if there is a formula for finding integer solutions to equations of the form
$$x^{2}+1=ay$$
where $a\in\mathbb{Z}$, and $x$ and $y$ are unknowns.
Comment: Perhaps including what you've tried/context would be helpful.
Comment: For any prime $p\equiv 1 \pmod 4$, we can solve $x^2+1\equiv 0 \pmod p$,  which gives you infinitely many solutions.  Of course, even in that case it is hard to write them down explicitly.
Comment: X=any odd number , y=2 will give an integer a always , have I understood your problem correctly??@Krypto14
Comment: @AtulMishra $a$ is a given constant and we are solving for $(x,y)$
Comment: If you are interested in this kind of problems maybe you can to read a consequence of the abc conjecture for a different diophantine equation (the satement of the abc conjecture also is explained in the article): Florian Luca, *THE DIOPHANTINE EQUATION* $P(x)=n!$ *AND A RESULT OF M. OVERHOLT*, Glasnik Matematicki, Vol. 37, No.2 (2002), [here](https://web.math.pmf.unizg.hr/glasnik/vol_37/no2_04.html) you've free access, from the Department of Mathematics of University of Zagreb (Croatia), see [here](https://web.math.pmf.unizg.hr/glasnik/). Is not required a response of this message, good luck.
Answer: This is equvalent to solving
$$
x^2 \equiv -1 \pmod a
$$
That is a well-known problem; look up Quadratic Residues on https://en.wikipedia.org/wiki/Quadratic_residue for example.  The punch line is that if $a$ is prime or if you can factor $a$, the problem is fairly easy; if
$a$ is composite and so large that you cannot factor it, the problem is very hard.
Answer: Of course you need $a \ne 0$.  You need $x$ to be a square root of $-1 \mod a$, and then $y = (x^2+1)/a$.  For $-1$ to have a square root $\mod a$, you need $a$ to be either odd or $2$ times an odd number,
and to have no prime factors $\equiv 3 \mod 4$.  Then if $a$ has $k$ distinct odd prime factors, there are $2^k$ possible values for $x \mod a$.

Integer solutions to $x^2+1=ay$


What is "Self-Hosting"?

Question: Up to now I thought self-hosting was for example, running its own nextcloud server on a virtual private server.
I read the wikipedia article, and it talks about something different:

Self-hosting is the use of a computer program as part of the toolchain or operating system that produces new versions of that same program—for example, a compiler that can compile its own source code.

Source: https://en.wikipedia.org/wiki/Self-hosting
If "Running its own nextcloud server on a virtual private server" is not self-hosting.
How to call "Running its own nextcloud server on a virtual private server"?
On stackoverflow it's definied like this:

Operating independently of a hosting infrastructure.

Source: https://stackoverflow.com/questions/tagged/self-hosting
Comment: The tag information on [so] says: "Self-hosting refers to a program or service which does not require a hosting environment. This term is often used to describe WCF web services that do not require IIS as their web host - a self-hosted WCF service establishes its own HTTP endpoints and listeners and is responsible for its own routing, security, and configuration management." But that's what SO has chosen to use the tag for. Our context is different, as TomTom has noted below.
Comment: @MichaelHampton where did you see the long explanation. If I look at the tag "self-hosting" I only see the string which I wrote into my question. ..... Ah, now I see, you can click on "learn more". I am sorry I only read "Operating independently of a hosting infrastructure.".
Answer: First you try to simplify the world too much. Self-Hosting has different meanings in different contexts, so ignoring the context is not good. Another example of self-hosting, i.e. (and running along the not using hosting infrastructure) is self hosting a web application in another application because it is inot "the web application that matters". Example? I have systems here that do X and expose a REST based web API to control them. The api is self-hosted by the applications, not using IIS or Apache.
So, the general tenor of your question is wrong - you try to fold various contexts into one term, that generally does not work. I.e. your wikipedia article is a general programming principle for compiler development. The moment a compiler can compile itself is self hosting. But that has NOTHING to do with any relevance of web hosting at all. Different context.

How to call "Running its own nextcloud server on a virtual private server"?

Hosting. What different is it from any other hosting? Just because you use a VPS? No, not relevant at all in this context.
Answer: Self-Hosting a website or public and private web services mean that a person is capable of configuring a regular computer into a webserver over either a dynamic IP address through port forwarding or static IP address which doesn't need port forwarding. For example, i self-host my website on an Acer laptop with windows 10 through a DNS software call NOIP and port forwarding through ISP router.

What is "Self-Hosting"?


Find the greatest integer $k$ for which $1991^k$ divides $1990^{{1991}^{1992}}+1992^{{1991}^{1990}}$

Question: Find the greatest integer $k$ for which $1991^k$ divides $$1990^{{1991}^{1992}}+1992^{{1991}^{1990}}$$
It is easy to see that $k \geq 1$ as $1990 \equiv -1$ and $1992 \equiv 1 \pmod{1991}$
Also, I thought that perhaps as $1991$ is the product of two distinct primes, it would be worth looking at small values of $(pq)^k||(pq-1)^{{pq}^{pq+1}}+(pq+1)^{{pq}^{pq-1}}$ for primes $p$ and $q$. Any help would be really appreciated.
Comment: is it $1990^{\left( 1991^{1992} \right)}$ or $\left( 1990^{1991} \right)^{1992}$
Comment: I'm pretty sure it's the former. But I'm not certain. This was the problem as I found it. I think it's from an IMO shortlist.
Comment: The existing answers show $k$ can be at least $1991$. I haven't followed the link to the detail of the "Lifting the Exponent Lemma", but do we know there is no greater value for $k$?
Comment: @DanZimm by convention, $ a^{b^c} $ means $a^{(b^c)}$ not $(a^b)^c$.
Answer: Let $a=1991$, and let $$b=(a-1)^{ a^{a+1} } + (a+1)^{ a^{a-1} }$$
The goal is to compute $\nu_{a}(b)$. To do so, we will evaluate $b$ modulo $a^{a+1}$.
Applying binomial expansions, $$b\equiv (-1)^{a^{a+1}} + 1 + a^{a-1} a\mod{a^{a+1}}$$ (because all the higher order terms vanish).
Since $a^{a+1}$ is odd, this simplifies to $$b \equiv a^a\mod{a^{a+1}}$$
Therefore, $\nu_{a}(b)=a$. To rephrase in the terminology of your question, $k=1991$.
Comment: Your wrote: "because all the higher order terms vanish". Do you have a proof of that?
Answer: I shall prove a more general result: Let $n>1$ be an odd positive integer. Then $n^n \|[(n-1)^{n^{n+1}}+(n+1)^{n^{n-1}}]$.
Proof:
\begin{align}
(n-1)^{n^2}+(n+1)=\sum_{i=0}^{n^2}{\binom{n^2}{i}(-1)^{n^2-i}n^i}+(n+1) & \equiv \binom{n^2}{1}n-1+(n+1) \pmod{n^2}\\
& \equiv n \pmod{n^2}
\end{align}
Now applying Lifting the Exponent Lemma on each prime factor of $n$, we have $n^n \|[(n-1)^{n^{n+1}}+(n+1)^{n^{n-1}}]$.
For your special case, $k=1991$.
Comment: The "lifting the exponent lemma" link is dead.
Comment: @Inceptio Indeed. Of course that requires the exponent to be odd, which is indeed the case here.
Comment: (+1) For *Lifting the exponent lemma*. This seems pretty interesting. It can be used in Olympiad without mentioning the proof right?
Comment: @Inceptio yes. In this case, one would write $n=\prod_{i=1}^{m}{p_i^{a_i}}$, then $v_{p_i}((n-1)^{n^{n+1}}+(n+1)^{n^{n-1}}) =v_{p_i}((n-1)^{n^2}+(n+1))+v_{p_i}(n^{n-1}) =v_{p_i}(n^n)$
Comment: I'm guessing $v_p(x^n+y^n)=v_p(x+y)+v_p(n)$ has been used here.


SPF and DMARC - is spf policy used?

Question: I understand how SPF is involved with DMARC alignment, but one thing I can't get clear: is the SPF policy (-all or ~all) used in DMARC? Or does DMARC merely use the IP ranges?
The issue is, that as we all know, SPF breaks forwarding. DKIM is a lot better when it comes to forwarding. So, now that I have DKIM+DMARC implemented, can I relax my SPF policy because DMARC will take care of checking SPF alignment?
Answer: DMARC actually evaluates your SPF result, looking for a PASS, as well as alignment between the smtp.mailfrom domain and the header.from domain. As long as SPF does not produce a pass, (whether you have ?all, ~all or -all mechanism at the end), DMARC will not consider the SPF result a PASS.
The same holds true for DKIM. The header.d domain should align with the header.from domain and the result should be PASS.
However, and to answer your question partly, some servers will interpret an SPF hard fail (-all) as a reason to reject your emails, even though it passes DMARC on DKIM.
On the other hand, not all receiving servers check on DMARC. So an SPF soft fail (~all)will not cause an email to be rejected on it's own (generally speaking). At the same time SPF is not the greatest tool for protecting against spoofing, since SPF is checked on the smtp.mailfrom domain instead of the header.from domain, and only the latter is visible to the recipient (in most client software). And thus the alignment requirement in DMARC.
In terms of what is better for forwarding: it depends. Some forwarders will rewrite the Return-Path (a.k.a. snmtp.mailfrom), which will fix SPF, but break DMARC alignment. Others will, for example, add a piece of text to the subject field which in turn will break the DKIM signature (if the subject was one of the signed headers). It's not so clear-cut. Authenticated Received Chain (ARC) is a protocol that is helpful in this respect, be it still in development.
My advice would be to use SPF with a soft fail mechanism and use DMARC with a reject policy. Also, use SPF and DKIM complimentary for optimal results.
My opinion: You're publishing a clear directive in DMARC. It is up to the recipient to implement corresponding checks. In fact, a receiving server can be configured to completely ignore both SPF (hard) fail and DMARC reject policies. That's not the senders responsibility, but the recipients prerogative.
Answer: It just checks if the IP/Host is in the SPF record , the overall logic is:
If the sending IP address is contained in the SPF record = SPF PASS
If the sending IP address is not contained in the SPF record = SPF FAIL

(see sites like http://knowledge.ondmarc.com/learn-about-dmarc/all-you-need-to-know-about-spf-dkim-and-dmarc where the above logic is quoted from).
The policies of DMARC and SPF are independent. I would not change SPF policies because there is a DMARC policy. You should consider that not all mail servers use DMARC but do use SPF. So the SPF policy should make sense on its own.
Comment: OK, so the policies are independent. That's mostly what I need to know. Whether or not I want to support people forwarding mail, is another question, for me.
Comment: Agreed. If you want to be strict at all with DMARC it is best to only block when both SPF and DKIM are false. In any other case it is quite certain you will have a lot false positives and bring misery to many users.
Comment: His question is, "...can I relax my SPF policy...?" You don't answer that question.
Comment: He asks: Or does DMARC merely use the IP ranges?
Comment: Yes, his question is a little broad but your answer is only a partial. I would have posted it as a comment.
Comment: The second part question has an answer that is largely opinion based. There is no golden answer. But I see your point.

SPF and DMARC - is spf policy used?


Is it possible to understand and use Relationships and Contextual Filters without knowing SQL?

Question: Are there any good, layman descriptions of contextual filters and relationships for those site builders that aren't developers?
Is it possible to be comfortable with Relationships and Contextual Filters without knowing SQL? If so, how?
Answer: By knowing SQL you can have better understanding but it is not necessary.

Relationships give you information about entities that are not listed in the fields b joining current content with other entities. For example detail information about the author of the node is not in the fields, Only it's uid is in there, so by selecting author as relationships you can get the rest of the information.
Contextual filters are similar to regular filters in that you can use mainly the same fields to filter the records on. Where contextual filters differ greatly is that you do not set the filtering value when you create the View, but it is taken from context. Contextual filters are great for when the View needs to display content dynamically depending on various contextual conditions


Select em Entity Framework não está funcionando

Question: Estou realizando uma consulta utilizando LINQ, consulta bem simples estou utilizando o seguinte método.
public void verificaAcesso( string usuario, string senha)
{
    using (DbBancoContext banco = new DbBancoContext())
    {
        var resultadoConsulta = from u in banco.USUARIOS_PROCESSO
                                where
                                   u.USUARIO == usuario
                                   && u.SENHA == senha
                                   && u.DT_CANCELAMENTO != null
                                select u.ID_USUARIO;
    }
}

Só que não estou tendo retorno algum mas quando verifico o conteúdo da variável resultadoConsulta exibe o seguinte conteúdo.
{SELECT [Extent1].[ID_USUARIO] AS [ID_USUARIO]
 FROM [dbo].[USUARIOS_PROCESSO] AS [Extent1]
 WHERE ([Extent1].[USUARIO] = @p__linq__0) AND ([Extent1].[SENHA] = @p__linq__1) AND ([Extent1].[DT_CANCELAMENTO] IS NOT NULL)}

O que estou fazendo de errado?
Comment: Ola. A consulta nao foi ainda efectuada, so sera efectuada quando utilizar o resultado. Para trazer logo o resultado pode adicionar `.ToList()` no final da query.
Comment: @Omni Eu dei um +1 no seu comentário mas seria bacana responder a pergunta. Apenas pelo seu comentário, ninguém poderia me condenar por tentar fazer `...select u.ID_USUARIO.ToList();` na última linha.
Comment: @Caffé estava a sair do trabalho e nao deu, mas ainda bem que respondeu =) upvoted
Answer: Adicione uma linha:
var idsUsuarios = resultadoConsulta.ToList(); O resultado estará em idsUsuarios.
Ou envolva sua query por parêntesis, adicionando o nela uma chamada para ToList:
    var resultadoConsulta = (from u in banco.USUARIOS_PROCESSO
                            where
                               u.USUARIO == usuario
                               && u.SENHA == senha
                               && u.DT_CANCELAMENTO != null
                            select u.ID_USUARIO).ToList();

e daí sim o resultado estará em resultadoConsulta.
O que seu código faz até agora é apenas criar a query e não executá-la.
Comment: @Rabelos Se fosse pra apostar, eu diria que o teu filtro de data de cancelamento está equivocado. Da maneira como está, você só retorna o ID dos usuários que "foram cancelados" (campo `DT_CANCELAMENTO != null`), se é que esta é a sua linguagem de negócio. Será que não deveria ser `&& u.DT_CANCELAMENTO == null`?
Comment: Sua ajuda foi boa mas tem um pequeno problema no meu caso quando verifico o valor do resultado ele me da um count = 0 será que não seria erro na minha connectionstring
Comment: @Rabelos O único erro que imagino na `connectionstring` é ela estar apontando para a base errada, de outro modo você teria uma exceção e não uma quantidade inesperada de registros. Parece que simplesmente não há registros que satisfaçam o filtro. Verifique: letras maiúsculas e minúsculas no nome do usuário (o banco pode estar case sensitive), se a senha está criptografada no banco e não criptografada na consulta, se os usuários cujos Ids você pretendia retornar realmente foram cancelados (DT_CANCELAMENTO != null).
Comment: Reparei nisso meu caro @Caffé distraído pela raiva do não entendimento uahuauahau. Muito obrigado pela ajuda.


What's going on in a Rugby Union "choke tackle"?

Question: A player with the ball is tackled, and rather than being brought to the ground, he is held up by the tackler(s).
The referee shouts "Maul" and then awards a scrum to the defending team.
What exactly is happening here? Why is this considered a maul, and why does that mean it's a scrum to the defenders (as opposed to the more conventional mauls)?
Answer: Rugby laws can be confusing at times and the latest law book runs to 146 pages.  It doesn't help that some of the terminology commonly used isn't completely consistent with the law.
For example, Law 14 defines a tackle as follows -

REQUIREMENTS FOR A TACKLE

For a tackle to occur, the ball-carrier is held and brought to ground by one or more opponents.
Being brought to ground means that the ball-carrier is lying, sitting or has at least one knee on the ground or on another player who is on the ground.
Being held means that a tackler must continue holding the ball-carrier until the ball-carrier is on the ground.

With this definition it should be clear that the "choke tackle" described in your first sentence, isn't in fact a tackle at all.
However, at this point if it's just the ball carrier and one (or more) opposition players/would-be tackers involved then it's not a maul either and it remains "open play."
Law 16 defines a maul as follows -

FORMING A MAUL

A maul can take place only in the field of play.
It consists of a ball-carrier and at least one player from each team, bound together and on their feet.
Once formed, a maul must move towards a goal line

The key requirement here is that a team-mate of the ball-carrier needs to join in the "chock tackle" for a maul to be considered formed.  At this point the referee would usually shout "Maul".
For the referee to then award a scrum to the opposition team, the maul must end unsuccessfully.
Law 16 lists the conditions for this to occur -

A maul ends unsuccessfully when:
a. The ball becomes unplayable.
b. The maul collapses (not as a result of foul play).
c. The maul does not move towards a goal line for longer than five seconds and the ball does not emerge.
d. The ball-carrier goes to ground and the ball is not immediately available.
e. The ball is available to be played, the referee has called "use it" and it has not been played within five seconds of the call.
Sanction: Scrum

With a well worked "choke tackle", the opposition will often have the upper hand and the maul will end unsuccessfully for the ball-carrier's team. Hence the opposition being awarded a scrum.

A few further comments -
Assuming that your comment about "more conventional mauls" refers to what happens after (proper) tackles, then these are actually called Rucks and are covered in Law 15.
You might observe that I haven't used the terms "attacking team" or "defending team" in my answer.  That's because the law definition of these isn't what you think it is.   It's not about who has the ball - it's about in which half of the pitch play is currently taking place!
Comment: No by "conventional mauls" I mean just the normal mauls where the team with the ball is somewhat in control - I suppose in most cases the successfully ending ones. But going by what you're saying, am I right i taking that a choke tackle earns a scrum because the player with the ball has found himself - unintentionally - in a maul where he cannot play the ball or move forward (and therefore it will end unsuccessfully thereby conceding the scrum)? Could it be avoided if one of his team-mates do not bind? Shouldn't the referee have to wait five seconds before awarding the scrum?
Comment: Yes you are right. Without support from team mate(s) the ball carrier is likely to either have the ball ripped from him or get bundled back down the pitch losing possession and/or ground. If the referee decides the ball is unplayable then they can blow immediately. (This is especially the case in youth rugby where safety considerations mean that you want to avoid collapsed mauls if possible.)


meta replacing same method in two different tests not working?

Question: Test controller is as follows
def justTest(){

    def res = paymentService.justTest()

    [status: res.status]

}

Test service method is as follows
def justTest(){

}

Now the two test cases are as follows. Payment service method justTest was modified in both cases to return two different values.
    @Test
    void test1(){

        PaymentService.metaClass.justTest = {['status': true]}

        def res = controller.justTest()
        assertEquals(res.status, true)

        GroovySystem.metaClassRegistry.removeMetaClass(PaymentService.class)

  }

Second test is as follows
    @Test
    void test2(){

        PaymentService.metaClass.justTest = {['status': false]}

        def res = controller.justTest()
        assertEquals(res.status, false)

        GroovySystem.metaClassRegistry.removeMetaClass(PaymentService.class)

}

One test is failing. When i used debugger, i noticed that this replacement is not working
PaymentService.metaClass.justTest = {['status': true]}

So i am wondering why one meta replacement is working and another not working? Is it not possible to change the same method in two different test cases using meta programming? I appreciate any help. Thanks!
Comment: I have not used JUnit but I would suggest to mock `PaymentService` instead of using `metaClass`. Also, try moving the following line as the first line of test `GroovySystem.metaClassRegistry.removeMetaClass(PaymentService.class)`
Answer: I would take a different approach:
void test1(){
    controller.paymentService = new PaymentService() {
        def justTest() {['status': true]}
    }

    def res = controller.justTest()
    assertEquals(res.status, true)
}

Or if you were using Spock instead of JUnit:
void test1() {
    controller.parymentService = Stub() {
         justTest() >> [status: true]
    }
    // ...  other code
}


datatables over wcf service

Question: We would like to pass datatable of information from main application over a web service and finally to the client application.
Does anyone know if there are any issues passing datatables as far as corruption? does datatables have their own checksum or way to check if data has been corrupt?
Comment: I think it would be better and easier to serialize your datatable into json format
Comment: Generally, the objects will be serialized/deserialized when passing from a consuming app into a WCF service so if theres an issue sending the data then the deserialization would fail.
Comment: Ok. do you think that the data inside the data table could ever get corrupt?   we are sending information through a web service to remote clients that have bad connection. just wondering if there was a bad line , could any of the values inside the datatable get corrupted.  apparently this happens sometimes with excel. when you send an excel file sometimes the values in some areas get corrupt for whatever reason. could just be an excel issue.
Answer: You should serialize datatable to json
you may use this function:
Public Function SerializeDataTable(dt As DataTable, tableName As String) As String
    Try
        Dim resultMain As New Dictionary(Of String, Object)()
        Dim index As Integer = 0

        For Each row As DataRow In dt.Rows
            Dim result As New Dictionary(Of String, Object)()

            For Each column As DataColumn In dt.Columns
                If column.DataType = GetType(DateTime) AndAlso row(column) <> DBNull.Value Then
                    result.Add(column.ColumnName, DirectCast(row(column), DateTime).ToString("dd/MM/yyyy"))
                Else
                    result.Add(column.ColumnName, row(column).ToString())
                End If
            Next

            resultMain.Add(tableName & index.ToString(), result)
            index += 1
        Next

        Dim js As New JavaScriptSerializer()
        Return js.Serialize(resultMain)
    Catch ex As Exception
        Throw ex
    End Try
End Function

datatables over wcf service


Bound for the sum of vectors in $\mathbb{R}^n$

Question: I have the following problem (it seems to be very famous, but I couldn't find reference)

Problem. Given $k$ vectors $v_1,v_2,\ldots,v_k\in\mathbb{R}^n$ such that for each $i$ the inequality $|v_i|\leq 1$ holds (here $|v|$ is the euclidean $|\cdot|_2$ norm). Prove that there exist $\varepsilon_1,\varepsilon_2,\ldots,\varepsilon_k\in\{-1,1\}$ such that the following inequalty holds
  $$
\left|\sum_{i=1}^{k}\varepsilon_i v_i\right|\leq\sqrt{n}.
$$

For $k\leq n$ it can be shown by probabilistic argument (i. e. by averaging $\left|\sum\varepsilon_i v_i\right|^2$ over all $2^k$ possible $k$-tuples $(\varepsilon_1,\varepsilon_2,\ldots,\varepsilon_k)\in\{-1,1\}^n$). However, this approach can't be extended for $k>n$. Moreover, this bound is sharp because we can take any orthonormal basis $v_1,v_2,\ldots,v_n$ in $\mathbb{R}^n$ and then inequality will turn to equality (for any choice of $\varepsilon_i$).
It's unclear for me how even to solve the problem in case $n=2$.
So, how to solve this problem?
Update. It seems that this is an open problem for $n\geq 3$ (found the following question on MO: https://mathoverflow.net/questions/272373/balanced-vectors)
Comment: Could you check above condition (in $\mathbb{R}^2$) for $v_1$ = $(\cos(\theta),\sin(\theta))$ , $v_2$ = $(\cos(\theta),-\sin(\theta))$ and $v_3 = (1,0)$ for $\theta = 4.2625(rad)$? I ran python code for check and I think I found the vectors does not have such $\varepsilon$ makes norm not greater then $\sqrt{2}$.
Comment: We can take $\varepsilon_i=1$ for each $i$.
Comment: Didn't the result gives $\sim \sqrt{2.1918}$ in that case?
Comment: The sum is equal to $u=(2\cos\theta+1,0)$, so $|u|=|2\cos\theta+1| <1$. If I'm not mistaken, then $\cos\theta\approx -0.437$.
Comment: I found serious mistake on my code, You are right. And seems to there is no exception for the proposition in the case $k=3,n=2.$
Comment: Are there really n (not k?) epsilons or is that a typo?
Comment: @Sophie, yes, it was a mistake.
Answer: Here is the proof for the case $n=2$ (the case $n=1$ is easy). To start with, we will prove the following statement:

Lemma. Given three vectors $v_1$, $v_2$, and $v_3$ in $\mathbb{R}^2$ such that length of each vector $v_i$ is at most $1$. Then, there are indices $i$ and $j$ such that $v_i+v_j$ or $v_i-v_j$ has length at most $1$.

Proof. Consider six vectors $\pm v_i$ with initial point at the origin $O$. Then, the six corresponding rays divide the plane into the six regions. Hence, there are two vectors with the angle at most $2\pi/6=\pi/3$ between them. Without loss of generality we can suppose that this two vectors are $v_1$ and $v_2$. Then, $|v_1-v_2|\leq 1$ because $\angle(v_1,v_2)\leq \pi/3$. Thus, we can choose $i=1$ and $j=2$.
Now, if $k\geq 3$, we can apply the lemma $k-2$ times and then use the case $k=2$ (just consider vector $v_i\pm v_j$ instead of $v_i$ and $v_j$).
Maybe this lemma can be extended to the higher dimensions, but I can't prove it.


passing command line arguments to a shell script doesn't work

Question: I want to write a script that will change to different directories depending on my input. something like this:
test.sh:
#!/bin/bash
ssh machine001 '(chdir ~/dev$1; pwd)'

But as I run ./test.sh 2 it still goes to ~/dev. It seems that my argument gets ignored. Am I doing anything very stupid here?
Answer: Bash ignores any variable syntax inside the single-quoted(') strings. You need double quotes(") in order to make a substitution:
#!/bin/bash
ssh machine001 "(chdir ~/dev$1; pwd)"

Answer: The parameter is enclosed in single quotes, so it isn't expanded on the local side. Use double-quotes instead.
#!/bin/bash

ssh machine001 "chdir ~/dev$1; pwd"

There's no need for the (...), since you are only running the pair of commands then exiting.


If matrices $A,B$ similar, find nonsingular $S$ s.t.$B=S^{-1}AS$

Question: Consider the matrices below
$$A=\begin{bmatrix}9&4&5\\-4&0&-3\\-6&-4&-2\end{bmatrix}$$
and
$$B=\begin{bmatrix}2&1&0\\0&2&0\\0&0&3\end{bmatrix}$$
These matrices have the same eigenvalues $\{2,2,-3\}$ and the same Jordan Canonical Form so they are similar.
In trying to find $S$ s.t. $B=S^{-1}AS$ I set
$$S=\begin{bmatrix}a&b&c\\d&e&f\\g&h&k\end{bmatrix}$$
and then tried to solve the system of 9 equations with 9 unknowns
$$B=S^{-1}AS\Leftrightarrow SB=AS$$
but Matlab showed it is rank deficient so it provided only the zero solution.
How can I find such matrix $S$?
Is there a systematic way to do that in the general case when both $A,B$ are $n\times n$ matrices?
Comment: Find a basis of eigenvectors and generalized eigenvectors.
Comment: I think you may have made an error with "Matlab". There are certainly nonzero solutions for these linear equations, see my answer.
Answer: Yes, there is a systematic way. It works as you said. Writing $AS=SB$ as a system of equations in the $n^2$ variables of $S$, we just solve this system of linear equations. In general, there will be several solutions, including $S=0$ of course. But then we impose the condition $\det(S)\neq 0$, which is a polynomial inequality on the variables of $S$. Then we obtain all possible invertible $S$ with $AS=SB$. Again, there are many such $S$ in general.
So, explicitly, solving the linear equations, we obtain
$$
S=\begin{pmatrix} s_1 & s_4 & s_7 \cr -\frac{s_1}{2} & \frac{s_1-2s_4}{4} &
-\frac{2s_7}{3} \cr -s_1 & -s_4 & -\frac{2s_7}{3} \end{pmatrix}
$$
for arbitary parameters $s_1,s_4,s_7$. However,
$$
\det(S)=\frac{s_1^2s_7}{12},
$$
so that we can take all such $S$ with $s_1s_7\neq 0$.
Answer: Notice that $B$ is precisely the Jordan form of $A$, so it suffices to find a Jordan basis for $A$.
We have:
$$A - 2I =\begin{bmatrix}7&4&5\\-4&-2&-3\\-6&-4&-4\end{bmatrix},\quad (A - 2I)^2 =\begin{bmatrix}3&0&3\\-2&0&-2\\-2&0&-2\end{bmatrix}$$
so $\ker (A - 2I)^2 =  \operatorname{span}\{e_1- e_3, e_2\} = \operatorname{span}\left\{\pmatrix{1 \\ 0\\ -1}, \pmatrix{0\\1\\0}\right\}$.
$$A - 3I = \begin{bmatrix}6&4&5\\-4&-1&-3\\-6&-4&-5\end{bmatrix} \implies \ker (A - 3I) = \operatorname{span}\left\{\pmatrix{-3 \\ 2 \\ 2}\right\}$$
Therefore, one Jordan basis is
$$\left\{(A - 2I)e_2, e_2, \pmatrix{-3 \\ 2 \\ 2}\right\} = \operatorname{span}\left\{\pmatrix{4 \\ -2\\ -4}, \pmatrix{0\\1\\0}, \pmatrix{-3 \\ 2 \\ 2}\right\}$$
So the similarity matrix is
$$S = \begin{bmatrix}4&0&-3\\-2&1&2\\-4&0&2\end{bmatrix}$$
Comment: @mechanodroid Can you explain how you replaced vector $[1\ 0\ -1]^T$ you found in the basis of $\ker (A - 2I)^2$ with $(A - 2I)e_2=[4\ -2\ -4]^T$ ?
Comment: @mgus In this case, the Jordan basis for the generalized eigenspace $\ker (A - 2I)^2$ can be found by picking a vector $v \in \ker (A - 2I)^2$ which is not in $\ker (A - 2I)$. Then the basis will be $\{(A - 2I)v, v\}$.
I picked $v = e_2$.
Answer: Since $A$ and $B$ have the same Jordan normal form $J$, there exist invertible matrices $P$ and $Q$ such that
$$P^{-1}AP=J=Q^{-1}BQ\text{.}$$
Then
$$B=(PQ^{-1})^{-1}APQ^{-1}\text{.}$$
Answer: Let $v_1=(-2,1,2)$, $v_2=(-1,0,1)$, and $v_3=(-3,2,2)$. Then $A.v_1=2v_1$, $A.v_2=2v_2+v_1$, and $A.v_3=3v_3$. Therefore, if$$M=\begin{pmatrix}-2&-1&-3\\1&0&2\\2&1&2\end{pmatrix},$$then$$M^{-1}.A.M=\begin{pmatrix}2&1&0\\0&2&0\\0&0&3\end{pmatrix}=B.$$
Comment: Can you explain you found $\mathbf{v}_2$ since it's not an eigenvector? I also found $\mathbf{v}_1$ and $\mathbf{v}_3$ for eigenvalues 2 and 3, respectively but I am not sure where the $\mathbf{v}_2$ comes from.
Comment: @mgus In order to find $v_2$, after finding $v_1$ I solved the equation $A.v=2v+v_1$ and took one of the solutions.
Comment: But, what is the intuition behind it? I mean which equation should I solve in the general case if I have many eigenvalues with algebraic multiplicity larger than 1?
Comment: @mgus The intuition come from the Jordan normal form, with all those $1$'s right above the main diagonal. In this case, if the multiplicity of $1$ was $3$ and if I knew that the Jordan normal form had a block like$$\begin{pmatrix}2&1&0\\0&2&1\\0&0&2\end{pmatrix},$$then I would go after a vector $v_3$ that would be a solution of the equation $A.v=2v+v_2$. And so on.


Como ocultar um objeto em javascript

Question: Estou tentando ocultar um objeto em JavaScript, estou usando o comando  style.display = 'none'; mas sem sucesso ainda.
Como posso ocultar o objeto por JavaScript, não por CSS?
objeto:

o codigo fonte esta nesta pagina
http://natupote.net16.net/
https://embed.plnkr.co/fXDmAe6uClOY80AIGwp9/
Comment: Porque o form-tab-2 não está em: /*BOTAO IR PARA BANDEIJA*/ ?
Comment: porque ele eu nao quero ocultar ele por CSS, somente por javascript, quero ocultar e exibir ele com o pressionar de um botao que farei futuramente, mas o foco do problema e ocultar o botao por javascript mesmo
Comment: eu fiz o q vc disse pelo console do chrome e funcionou mesmo, mas eu estou tentando anexar o comando que vc disse no codigo fonte da pagina, para que execute sozinho, obrigado pela ajuda
Comment: eu estou editando pelop plnkr https://embed.plnkr.co/fXDmAe6uClOY80AIGwp9/ se vc abrir vai ver q eu colei seu comando no
Answer: Segue uma forma maneira de ocultar este elemento Html:
document.getElementById("form-tab-2").style.display = "none";

Para testar: acesse a URL da página com o Google Chrome, em seguida pressione F12, clique na opção "Console", digite o comando acima no console e tecle ENTER.

Após digitar e teclar enter:

Para aplicar ao seu JavaScript e ter certeza que este elemento não está sendo exibido, coloque o código abaixo no início de seu JavaScript:
document.addEventListener("DOMContentLoaded", function(event) {
    setTimeout(function(){
         document.getElementById("form-tab-2").style.display = "none";
    }, 1000);
});

Comment: Eu colei este comando e não ocultou ainda
Comment: eu estou fazendo ele no plunkr https://embed.plnkr.co/fXDmAe6uClOY80AIGwp9/
Comment: entendi, funciona mesmo, mas estou tentando anexar este comando no codigo fonte da pagina, para que na inicialização oculte o objeto, ainda sem sucesso...
Comment: No plunk funcionou: coloque o código abaixo no início de seu JavaScript:

    document.addEventListener("DOMContentLoaded", function(event) {
        setTimeout(function(){
             document.getElementById("form-tab-2").style.display = "none";
        }, 1000);
    });
Comment: Editei a resposta.
Comment: Testou? Deu certo?
Comment: funcionou sim, obrigado, vc fez em 50 min oq eu to tentando fazer  ja faz 1 dia

Como ocultar um objeto em javascript


How I can validate response with Form Request and ajax json for laravel 8

Question: I have been using laravel for a short time, and I have been reading about good practices, I want to make an ajax json request with a validation in the form, I have seen that it is better to create a class "extend FormRequest" to better manage the information, in my case I am using validator but I don't know how to manage it in such a way to simplify the controller code as much as possible.
Currently I have:
Controller:
public function store(Request $request)
{
    if($request->ajax()) {
        $messages = [
            'nombre.required'       => 'El campo nombre es necesario',
            'descripcion.required'  => 'El campo descripción es necesario',
        ];
        $rules = [
            'nombre' => 'required',
            'descripcion' => 'required',
            'url' => 'required|alpha_dash'
        ];
        $validator = Validator::make($request->all(), $rules, $messages);
        if ($validator->fails()) {
            return response()->json([
                'status' => 400,
                'errors' => $validator->messages()//$validator->errors()
            ]);
        } else {
            $crear = new Proyecto([
                'nombre'      => $request->nombre,
                'descripcion' => $request->descripcion,
                'url'         => $request->url
            ]);
            $crear->save();

            return response()->json([
                'status' => 200,
                'message' => 'Registro insertado con éxito'
            ]);

        }
    }else{
        return view("404");
    }
}

Model:
class Proyecto extends Model
{
   use HasFactory;
   protected $table = 'proyecto';
   protected $primaryKey = 'id_proyecto';
   protected $fillable = ['nombre', 'descripcion', 'url'];
   public function getRouteKeyName()
   {
       return 'url';
   }
}

js:
$('#crear_proyecto').submit(function(e){
    e.preventDefault();

    var formu = $("#crear_proyecto").serialize();

    $.ajax({
        type: "POST",
        url: "proyecto/crearproyecto",
        data: formu,
        dataType: "json",
        beforeSend:function(){
            $(".loader").show();
        },
        success: function (data) {
            $('#crear_proyecto').find('span.text-danger').remove();
            if (data.status == 400) {
                $.each(data.errors, function (key, error_value) {
                    $('#'+key).after(""+error_value+"");
                });
                $(".loader").fadeOut("slow");
            }else{
                $(".loader").fadeOut("slow");
                alert(data.message);
                $('#crear_proyecto').trigger("reset");
                $("#nombre").focus();
                $('#modalformu').modal('toggle');
            }
        }
    });

I do not know if the code I have previously put is a bad practice or to leave it like that, what I have been seeing is to leave the controller as light as possible by creating a RequestForm, but I do not know how to adapt it with json and ajax, the idea was to do something like that:
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Validation\ValidationException;
class PostProyectoRequest extends FormRequest
{
/**
 * Determine if the user is authorized to make this request.
 *
 * @return bool
 */
public function authorize()
{
    return true;
}

/**
 * Get the validation rules that apply to the request.
 *
 * @return array
 */
public function rules()
{
    return [
        'nombre' => 'required',
        'descripcion' => 'required',
        'url' => 'required|alpha_dash',
    ];
}

public function messages()
{
    return [
        'nombre.required'       => 'El campo nombre es necesario',
        'descripcion.required'  => 'El campo descripción es necesario'
    ];
}

}
EDIT
Now I have this code in the controller:
public function store(PostProyectoRequest $request)
{
    $crear = new Proyecto([
        'nombre'      => $request->nombre,
        'descripcion' => $request->descripcion,
        'url'         => $request->url
    ]);

    $crear->save();
    return response()->json([
        'status' => 200,
        'message' => 'Registro insertado con éxito'
    ]);
}

And this y RequestForm
namespace App\Http\Requests;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Facades\Validator;

class PostProyectoRequest extends FormRequest
{
 /**
  * Determine if the user is authorized to make this request.
  *
  * @return bool
  */
  public function authorize()
  {
     return true;
  }

  /**
  * Get the validation rules that apply to the request.
  *
  * @return array
  */
  public function rules()
 {
     return [
         'nombre'      => 'required',
         'descripcion' => 'required',
         'url'         => 'required|alpha_dash'
     ];
 }

 public function messages()
 {
     return [
         'nombre.required'       => 'El campo nombre es necesario',
         'descripcion.required'  => 'El campo descripción es necesario'
     ];
 }
 protected function failedValidation(Validator $validator)
 {
    if($this->wantsJson())
    {
        $response = response()->json([
            'status' => 400,
            'errors' => $validator->errors()//$validator->errors()
        ]);
    }else{
        $response = redirect()
            ->route('guest.login')
            ->with('message', 'Ops! Some errors occurred')
            ->withErrors($validator);
    }

    throw (new ValidationException($validator, $response))
        ->errorBag($this->errorBag)
        ->redirectTo($this->getRedirectUrl());
}

}
Comment: I really like the failedValidation approach in your EDIT.
Answer: So you are actually right on track and you don't need to keep the old validation in the controller anymore. You want to do something like this.
//old
//public function store(Request $request)

//new
public function store(PostProyectoRequest $request)
{
    $crear = new Proyecto([
        'nombre'      => $request->nombre,
        'descripcion' => $request->descripcion,
        'url'         => $request->url
    ]);
    $crear->save();

    //you can't have two responses because the first one would run only because
    return response()->json([
        'status' => 200,
        'message' => 'Registro insertado con éxito'
    ]);

    //or

    $response = [
        'status' => 200,
        'message' => 'Registro insertado con éxito'
    ];
    return json_encode($response);
}

So is instead of using the normal Request facade, you would use the form request PostProyectoRequest you created. By doing so, you are telling the controller to pass the request through the form request which would validate it and if any of the validation fails it, it would return a validation error and wouldn't run the code in the controller. Read more about form requests here also read about early returns and returns in general
Comment: I have found the solution after looking through the internet, I have updated the post, now it does not return any error, where is the method:
failedValidation

I give the issue turned out and I thank you very much for your help.
Comment: Thanks, I have left the code as you have put it, but when there is a failure I get the following message (Is this message normal?):

HTTP/1.1 422 Unprocessable Entity
message The given data was invalid.

P.D: I have updated the code in the first message just below Edit.
Comment: yes, it is normal when the validation fails.  you would get the error message and what validation failed. so you just need to highlight the field or show the message on your frontend
Comment: With validator in controller the browser return this:
[HTTP/1.1 200 OK]

But with RequestForm i hava this:
HTTP/1.1 422 Unprocessable Entity]

Why?
Comment: console log the response and paste it here. if it is failing now, it means your earlier validation wasn't validating properly. paste the response. also send screenshot of the filled form from frontend