text:
Q: Convert Hex to signed 64-bit with bash In bash, need to convert E83E67529A1090E7 to -1711817203884453657
The following doesn't work:
$ printf "%d\n" "0xE83E67529A1090E7"
-bash: printf: warning: 0xE83E67529A1090E7: Numerical result out of range
9223372036854775807

Unsigned and positive signed values work
$ printf "%d\n" "0x183E67529A1090E7"
1746947309936087271
$ printf "%u\n" "0xE83E67529A1090E7"
16734926869825097959

but I specifically need a negative signed value which fails.

A: Use bash base built-in:
$ echo "$((16#E83E67529A1090E7))"
-1711817203884453657


text:
Q: Codeigniter Upload function does not work I am working on codeigniter and during creation of one of the APIs I got the issue. I tried to upload the image on Server as a file, while searching on the web, I got familiar with inbuild upload class in codeigniter. Please have a look at this code. I am sending file from Android using this tutorial.
public function upload_image_post(){

 $config['upload_path'] =base_url().'/uploads/';
    $config['file_name'] = rand() .'.jpg';
    $config['allowed_types'] = 'gif|jpg|jpeg|png';
    $config['max_size'] = 10000;
    $config['remove_spaces'] = TRUE;
    $config['encrypt_name'] = TRUE;
    // $file  = $this->input->post('file');

    $this->load->library('upload', $config);
// $this->upload->initialize($config);
    $file=$_FILES['uploaded_file'];
    // $this->upload->do_upload($file);
    if($file){
      $content=array(
        'image_id'=>'IMG'.rand(),
        'album_id'=> 'A',
        'sp_id'=>'asQ',
        'image_name'=>'aAA',
        'status'=>1,
        'tags'=>'s');
        /* This is working*/
        $res = $this->db->insert('ww_portfolio_images',$content);
      }else{
         $content=array(
        'image_id'=>'IMG'.rand(),
        'album_id'=> 'not file',
        'sp_id'=>'asQaaaaa',
        'image_name'=>'aAA',
        'status'=>1,
        'tags'=>'s');
        /* This is not working, Thats Obvious*/
        $res = $this->db->insert('ww_portfolio_images',$content);

      }

      // $destinationPath=APPPATH.'public/assets/uploads/ANKO.jpg';
    if($this->upload->do_upload('uploaded_file')) {
      $content=array(
        'image_id'=>'IMG'.rand(),
        'album_id'=> 'A',
        'sp_id'=>'aaaaaaaaaaaaaaaaas',
        'image_name'=>'aAA',
        'status'=>1,
        'tags'=>'s');
        /* This is not working*/
        $res = $this->db->insert('ww_portfolio_images',$content);
     $this->response(['result' =>'Success',]  , REST_Controller::HTTP_OK);
         // return ($arr_image_info['full_path']);
    }
    else{
     $content=array(
        'image_id'=>'IMG'.rand(),
        'album_id'=> 'A',
        'sp_id'=>'asass',
        'image_name'=>'aAA',
        'status'=>1,
        'tags'=>'s');

        $res = $this->db->insert('ww_portfolio_images',$content);
      /* This is working*/
      $this->response(['result' => 'ERrro']  , REST_Controller::HTTP_OK);
        // $this->response(['result' =>'Image error',], 433);
    }
   }

I can not figure out the problem I am facing here. I am receiving a file but it does not upload.
I have also tried to use $this->upload->do_upload() instead of $this->upload->do_upload('uploaded_file') and this $config['max_size'] = '10000'; instead of this $config['max_size'] = 10000; . Please help. Any help would be greatly appreciated.
Also, when this code run through web panel, it working fine.

A: Better if you provide some more detail for the type of error or warning that you are observing.
There could be number of reasons.
1) base_url() gives you the public URL. You have to specify the absolute or relative path to your upload folder.
2) (if you are using an Apache Server) Your Apache user don't have the write permission to the upload folder.
3) Folder path doesn't exists.
If the first one doesn't work, please check the rest of the points. Hope this help you.
Regards
Muaaz

A: Try using FCPATH
$config['upload_path'] = FCPATH . '/uploads/';

Or
$config['upload_path'] = './uploads/';

Then  http://www.codeigniter.com/user_guide/libraries/file_uploading.html#the-controller
<?php

class Example extends CI_Controller {

public function __construct() {
  parent::__construct();
  $this->load->helper('form');
}

// Name function what every you want remember to change it on view form.
public function upload() {

$config['upload_path']          = './uploads/';
$config['allowed_types']        = 'gif|jpg|png';
$config['max_size']             = 100;
$config['max_width']            = 1024;
$config['max_height']           = 768;

$this->load->library('upload', $config);

if ($this->upload->do_upload('uploaded_file')) {

   // Then the success stuff

   $upload_data = $this->upload->data();

   echo $upload_data['file_name'];

} else {
   // Errors
}

}

}

On view I would use the form helper functions form_open_multipart()
<?php echo form_open_multipart('example/upload');?>
<?php echo form_upload('uploaded_file', 'Upload');?>
<?php echo form_close();?>

A: *

*check your form input in the view

My form view :
<input id="document" type="file" data-browse-label="browse" name="document" data-show-upload="false" data-show-preview="false" class="form-control file" />

*

*other can be
permission issue for the uploads folder
if the folder does not exist you have to create it

And always try to debug the code with logs

document in the do_upload is the name of the input element in my view

       if ($_FILES['document']['size'] > 0) {
            $this->load->library('upload');
            $config['upload_path'] = 'uploads/images';
            $config['allowed_types'] = '*';
            $config['max_size'] = $this->allowed_file_size;
            $config['overwrite'] = false;
            $config['encrypt_name'] = true;
            $this->upload->initialize($config);
            if (!$this->upload->do_upload('document')) {
                $error = $this->upload->display_errors();
                $this->session->set_flashdata('error', $error);
                redirect($_SERVER["HTTP_REFERER"]);
            }
            $photo = $this->upload->file_name;
        }

redpajama_set_name: RedPajamaStackExchange


text:
Q: Run callback function with different values I ran the createCB from 2 different places and with different value
one time with the value "state"
and 2nd with the value "restarts"
a := createCB("state",wd)
b := createCB("restarts",wd)

func (c *CollectorWatchDog) createCB(field string, wd *cpwdObj) func() (interface{},[]attribute.KeyValue) {
    var value interface{}
    return func() (interface{},[]attribute.KeyValue) {
        err := c.runWDCommand("cpwd_admin","list")
        if err != nil {
            return nil, nil
        }

        if strings.Compare("state",field) == 0 {
            value = wd.state
            fmt.Println("createCB")
            fmt.Println("field")
            fmt.Println(field)
        } else if strings.Compare("restarts",field) == 0 {
            fmt.Println("createCB")
            fmt.Println("restarts")
            fmt.Println(field)
            value = wd.restarts
        }

        labels := wd.getStateRestartLabels()
        return value,labels
    }
}

I sent the CBs to a different function and activated them, one by one, but just the first one has activatead.
what can be the reason for that?


text:
Q: Update DataGrid on run-time I am creating Windows Application which has a Grid.
Grid's data source is a an Object of a Class.
Grid has two bands.
As shown in the below image on Band1, there is a Column named as Templates.
It has values from 1 to 10.
The requirement is that based on the selected values in the Template Field, Band2 must have no of rows.
e.g. if User selects 2 in the Template Field, Band2 must have two rows.
As its a run time process, Grid must be refreshed on the Run time.

In the below case if the value is changed from 2 to 3 in the template field, the open Band2 must be refreshed to show 3 rows.
I wrote some code but it was not able to refresh the grid on the run time.
 private void grdDataMapping_AfterCellUpdate(object sender, CellEventArgs e)
    {
 if (e.Cell.Column.Key.Equals("TemplateName"))
            {
                ValueList paramName = new ValueList();
                string templateName = e.Cell.Text;
                List<TemplateMapping> tempMappings = new List<TemplateMapping>();
                if (_dictTemplateNames.ContainsKey(templateName))
                {
                    for (int i = 0; i < templateName.Value; i++)
                        tempMappings.Add(new TemplateMapping());
                    mappingDetails.ListTemplateMapping = tempMappings;
                }
                grdDataMapping.Refresh();
            }

What am I missing here?

A: You could implement the interface INotifyPropertyChanged and some additional properties you may notify of. This way the ViewModel notifies the View (or vice versa) about any changes that have been made. Thus, you can easily control the content of all 3 DataGrids.
See INotifyPropertyChanged for more on this. There are plenty of articles around who help you archiving this.


text:
Q: How to load Keras model from a database (which is essentially not a .h5 file)? I have created a python script to pull weights information from database and now I want to load it as Keras.model , but script is generating error.
It is working perfectly fine when I am using file instead of extracting the data from database
This works perfectly fine if i use model_weights instead of model_weights_1.
In database this is stored as binary blob.
from keras.models import model_from_json
import tensorflow as tf
import pyodbc
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import configparser
from skimage.transform import resize
import matplotlib.pyplot as plt
import os
from io import StringIO,BytesIO
import h5py

model_struct=f'location of json file'
model_weights=f'location of weight file'
model_weights_1,=cursor.execute(("select query to get weights").fetchone()
model_struct_str,=cursor.execute(("select query to get json string").fetchone()
mdl = model_from_json(model_struct_str)
mdl.load_weights(model_weights_1)

It is throwing error
filepath.endswith(".h5")
TypeError: endswith first arg must be bytes or a tuple of bytes, not str
As Load model is expecting a file which ends with .h5
I also tried to create h5 file but i am unable to do that from binary blob.
Any help will be appreciated


text:
Q: Update parent entity change child entity collection I use Entity framework Core in a WPF application.
I have a model like this :
Parent_Entity
      _ Id
      _ Collection of Child_Entity
      _ Current_Child_Entity (not mapped)
The Current_Child_Entity is one of the collection. For exemple :
Collection of Child Entity :
child1
child2
Current_Child_Entity :
child2
When I try to save a change I do something like this :
1) AddOrUpdate(Current_Child_Entity)
2) AddOrUpdate(Parent_Entity)
The AddOrUpdate() method that I used is implemented this way :
public void AddOrUpdate(T entity)
        {
            if (!Context.Set<T>().Any(obj => obj == entity))
            {
                Context.Set<T>().Add(entity);
            }
            else
            {
                Context.Entry(entity).State = EntityState.Modified;
                Update(entity);
            }
        }

My issue is when I do the first update (with Current_Child_Entity), all seems good.
But when I go in the second update where I save the parent entity, it add a duplication of two Child_Entity with the same Id, the same properties in Collection of Child Entity. For exemple, if I updated child2 in the Collection Of Child Entity I get :
child1
child2
child2
It does this when I do in AddOrUpdate() :
Context.Entry(entity).State = EntityState.Modified;
Why a duplication of a Child Entity is done in the Collection at this instruction ?
There are something that I don't understand and could you explain me what I doing wrong ?
Thank's for the help.


text:
Q: Can't return multi-level resource/collection through API Question:
How do I return values of a resource through another resource?
If I have a pivot table inbetween (many to many relationship), does something change, other than the model function $this->hasMany(AnotherModel::class, 'pivottable')
?
For example:
There's a table called "tags", and another table called "tagtranslations"
"tag" only has an ID and timestamps
"tagtranslations" has id, tag_id, title, slug and timestamps
There are TagResource and TagTranslationResource
In TagTranslationResource I'm returning the "toArray"
public function toArray($request)
    {
        return parent::toArray($request);
    }
}

and in TagResource I'm returning
return
        [
            'id' => $this->id,
            'title' => TagTranslationResource::collection($this->title),
            'slug' =>  TagTranslationResource::collection($this->slug)
        ];

and in Controller I'm calling back Tag with tagtranslations
public function index(Request $request)
    {

        $tags = Tag::with('tagtranslation')->get();
        //return $tags;

        return TagResource::collection($tags);
    }

when, in TagResource I call, for example

return [
  'title' => new TagResource($this->title),
  'slug'  => new TagResource($this->slug)
]

I only get null fields in my JSON api response
and the response I get for the
'title' => TagTranslationResource::collection($this->title)
is an error "Call to a member function first() on null"
Can someone please explain what's happening here? :D
I also tried with
 TagResource::collection(TagTranslation::all())->$this->title
but it can't convert to string


text:
Q: Is it possible to update from an action/method other than the update action/method in Ruby on rails? Is it possible to update from an action/method other than the update action/method?
For example in my users controller I already have an update method for other parts of my users account.
I need a separate one for changing my users password. Is it possible to have something like this:
def another_method_to_update
  user = User.authenticate(current_user.email, params[:current_password])
  if user.update_attributes(params[:user])
    login user
    format.js   { render :js => "window.location = '#{settings_account_path}'" }
    flash[:success] = "Password updated"
  else
    format.js   { render :form_errors }

  end
end

Then have my change password form know to use that method to perform the update?
It has 3 fields:
current password
new password
confirm new password
and I use ajax to show the form errors.
Kind regards

A: Yes you can:
Add this in routes.rb:
resources :users do
  member do
    put :another_method_to_update
  end
end

In the view, you have to use the following URL:
another_method_to_update_user_path(@user)


text:
Q: How do I set up a Stanford CoreNLP Server on Windows to return sentiment for text I am attempting to set up a local server on Windows with Stanford CoreNLP to calculate sentiment scores for over 1M article and video texts. I don't know Java, so I will need some help.
I successfully installed Stanford CoreNLP 3.6.0, and I have a server running with:
java -mx4g -cp "*" edu.stanford.nlp.pipeline.StanfordCoreNLPServer

Running this http post from my other computer works, and I get an expected response (xxx.xxx.xxx.xxx is the server's IP address):
wget --post-data 'the quick brown fox jumped over the lazy dog' 'xxx.xxx.xxx.xxx:9000/?properties={"tokenize.whitespace": "true", "annotators": "tokenize,ssplit,pos,lemma,parse", "outputFormat": "json"}' -O -

However, the response doesn't contain sentiment. The obvious solution would be to add an annotator:
wget --post-data 'the quick brown fox jumped over the lazy dog' 'xxx.xxx.xxx.xxx:9000/?properties={"tokenize.whitespace": "true", "annotators": "tokenize,ssplit,pos,lemma,parse,sentiment", "outputFormat": "json"}' -O -

However, on the server side, I get this error:
java.lang.IllegalArgumentException: Unknown annotator: sentiment
at edu.stanford.nlp.pipeline.StanfordCoreNLP.ensurePrerequisiteAnnotators(StanfordCoreNLP.java:281)
at edu.stanford.nlp.pipeline.StanfordCoreNLPServer$CoreNLPHandler.getProperties(StanfordCoreNLPServer.java:476)
at edu.stanford.nlp.pipeline.StanfordCoreNLP$CoreNLPHandler.handle(StanfordCoreNLPServer.java:350)
at com.sun.net.httpserver.Filter$Chain.doFilter(Unknown Source)
at sun.net.httpserver.AuthFilter.doFilter(Unknown Source)
at com.sun.net.httpserver.Filter$Chain.doFilter(Unknown Source)
at sun.net.httpserver.ServerImpl$Exchange$LinkHandler.handle(Unknown Source)
at com.sun.net.httpserver.Filter$Chain.doFilter(Unknown Source)
at sun.net.httpserver.ServerImpl$Exchange.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.thread.run(Unknown Source)

The next obvious solution would be to add a parameter to starting the server, which runs:
java -mx4g -cp "*" edu.stanford.nlp.pipeline.StanfordCoreNLPServer -annotators "tokenize,ssplit,pos,lemma,parse,sentiment"

Running the same http posts from before gives the same exact result and error, respectively.
Am I doing something wrong, or is there some modification to the core code that it needs to work? I don't know Java, so I am unable to make those changes.
As a side note, this similar command starts a console, and seems to load sentiment correctly:
java -mx4g -cp "*" edu.stanford.nlp.pipeline.StanfordCoreNLP -annotators "tokenize,ssplit,pos,lemma,parse,sentiment"

[main] INFO edu.stanford.nlp.pipeline.StanfordCoreNLP - Adding annotator tokenize
[main] INFO edu.stanford.nlp.pipeline.TokenizerAnnotator - TokenizerAnnotator: No tokenizer type provided. Defaulting to PTBTokenizer.
[main] INFO edu.stanford.nlp.pipeline.StanfordCoreNLP - Adding annotator ssplit
[main] INFO edu.stanford.nlp.pipeline.StanfordCoreNLP - Adding annotator pos
Reading POS tagger model from edu/stanford/nlp/models/pos-tagger/english-left3words/english-left3words-distsim.tagger ... done [0.5 sec].
[main] INFO edu.stanford.nlp.pipeline.StanfordCoreNLP - Adding annotator lemma
[main] INFO edu.stanford.nlp.pipeline.StanfordCoreNLP - Adding annotator parse
[main] INFO edu.stanford.nlp.parser.common.ParserGrammar - Loading parser from serialized file edu/stanford/nlp/models/lexparser/englishPCFG.ser.gz ... done [0.4 sec].
[main] INFO edu.stanford.nlp.pipeline.StanfordCoreNLP - Adding annotator sentiment

Entering interactive shell. Type q RETURN or EOF to quit.
NLP> _

A: Try running with the GitHub version of the code. Your first solution is correct -- the fact that it could not find the sentiment annotator is a bug in the code:
wget --post-data 'the quick brown fox jumped over the lazy dog' 'xxx.xxx.xxx.xxx:9000/?properties={"annotators": "tokenize,ssplit,pos,lemma,parse,sentiment", "outputFormat": "json"}' -O -

(A side note: the tokenize.whitespace property is in the documentation to show that you can pass in arbitrary properties, but I recommend against using it in production).


text:
Q: MVC, Jquery.Ajax: How to return a partial view with nested partial view datatable? Using jquery.ajax, I am trying to return a view, that has a nested partial view to display a datatable.   The initial view is returning, but the datatable is not showing or rendering.
AJAX
$.ajax({
        type: "GET",
        url: "/Controller/Action,
        data: {
            custNum: custNum
        },
        success: function (data) {
            $('#DivToRenderResults').html(data);
        }

Controller
 public ActionResult Action(string custNum)
       {
            Model ReturnModel = GetData(custNum)

            if (Request.IsAjaxRequest())
            {
                return PartialView(ReturnModel);
            }
            return View(ReturnModel );
        }

Model
public class Model
{
    public FirstViewsModel FirstViewsModel {get;set;)
    public IEnumerable<DataTableModel> DataTableModel {get;set}
}

I ultimately want to use ajax to dynamically load different tabs that all will have nested datatables in partial views, but I am unable to get this first one to work.   Please help, & thank you!
Target View

  <\div>

// Inside the div
@model Model

    // FirstViewModelInfo

          // This one is not rendering in the return
          @Html.Partial("_DataTableView", Model)


text:
Q: SML program to delete char from string I am newbie to SML, trying to write recursive program to delete chars from a string:
remCharR: char * string -> string

So far wrote this non-recursive prog. Need help to write recursive one.
- fun stripchars(string,chars) = let
=    fun aux c =
=       if String.isSubstring(str c) chars then
=          ""
=       else
=          str c
= in
=     String.translate aux string
= end
= ;

A: You have already found a very idiomatic way to do this. Explicit recursion is not a goal in itself, except perhaps in a learning environment. That is, explicit recursion is, compared to your current solution, encumbered with a description of the mechanics of how you achieve the result, but not what the result is.
Here is one way you can use explicit recursion by converting to a list:
fun remCharR (c, s) =
    let fun rem [] = []
          | rem (c'::cs) =
              if c = c'
              then rem cs
              else c'::rem cs
    in implode (rem (explode s)) end

The conversion to list (using explode) is inefficient, since you can iterate the elements of a string without creating a list of the same elements. Generating a list of non-removed chars is not necessarily a bad choice, though, since with immutable strings, you don't know exactly how long your end-result is going to be without first having traversed the string. The String.translate function produces a list of strings which it then concatenates. You could do something similar.
So if you replace the initial conversion to list with a string traversal (fold),
fun fold_string f e0 s =
    let val max = String.size s
        fun aux i e =
          if i < max
          then let val c = String.sub (s, i)
               in aux (i+1) (f (c, e))
               end
          else e
    in aux 0 e0 end

you could then create a string-based filter function (much alike the String.translate function you already found, but less general):
fun string_filter p s =
    implode (fold_string (fn (c, res) => if p c then c::res else res) [] s)

fun remCharR (c, s) =
    string_filter (fn c' => c <> c') s

Except, you'll notice, it accidentally reverses the string because it folds from the left; you can fold from the right (efficient, but different semantics) or reverse the list (inefficient). I'll leave that as an exercise for you to choose between and improve.
As you can see, in avoiding String.translate I've built other generic helper functions so that the remCharR function does not contain explicit recursion, but rather depends on more readable high-level functions.

Update: String.translate actually does some pretty smart things wrt. memory use.
Here is Moscow ML's version of String.translate:
fun translate f s =
    Strbase.translate f (s, 0, size s);

with Strbase.translate looking like:
fun translate f (s,i,n) =
    let val stop = i+n
    fun h j res = if j>=stop then res
              else h (j+1) (f(sub_ s j) :: res)
    in revconcat(h i []) end;

and with the helper function revconcat:
fun revconcat strs =
    let fun acc [] len       = len
          | acc (v1::vr) len = acc vr (size v1 + len)
        val len = acc strs 0
        val newstr = if len > maxlen then raise Size else mkstring_ len
        fun copyall to []       = () (* Now: to = 0. *)
          | copyall to (v1::vr) =
        let val len1 = size v1
            val to   = to - len1
        in blit_ v1 0 newstr to len1; copyall to vr end
    in copyall len strs; newstr end;

So it first calculates the total length of the final string by summing the length of each sub-string generated by String.translate, and then it uses compiler-internal, mutable functions (mkstring_, blit_) to copy the translated strings into the final result string.
You can achieve a similar optimization when you know that each character in the input string will result in 0 or 1 characters in the output string. The String.translate function can't, since the result of a translate can be multiple characters. So an alternative implementation uses CharArray. For example:

*

*Find the number of elements in the new string,
fun countP p s =
    fold_string (fn (c, total) => if p c
                                  then total + 1
                                  else total) 0 s

*Construct a temporary, mutable CharArray, update it and convert it to string:
fun string_filter p s =
    let val newSize = countP p s
        val charArr = CharArray.array (newSize, #"x")
        fun update (c, (newPos, oldPos)) =
            if p c
            then ( CharArray.update (charArr, newPos, c) ; (newPos+1, oldPos+1) )
            else (newPos, oldPos+1)
    in fold_string update (0,0) s
     ; CharArray.vector charArr
    end

fun remCharR (c, s) =
    string_filter (fn c' => c <> c') s

You'll notice that remCharR is the same, only the implementation of string_filter varied, thanks to some degree of abstraction. This implementation uses recursion via fold_string, but is otherwise comparable to a for loop that updates the index of an array. So while it is recursive, it's also not very abstract.
Considering that you get optimizations comparable to these using String.translate without the low-level complexity of mutable arrays, I don't think this is worthwhile unless you start to experience performance problems.


text:
Q: Add Contact form ajax with shortcode in wordpress I'm creating a plugin for my contact form using ajax and add shortcode wordpress . I don't get how to do it and it work perfect, and read several forums about the admin- ajax.php but do not understand how to pass data to this file.
This is the code :
<?php

/*
Plugin Name: Formulario de contacto
Plugin URI: http://www.e-world.co
Description: Formulario de contacto con ajax
Version: 1.0
Author: Jorge Moreno
Author URI: http://www.e-world.co
license: GLP2
*/

function the_action_function(){
    $adminemail = "jorge.moreno@e-world.co";

                                if ($_GET['send'] == 'comments')
                                {

                                    $_uname = $_POST['name'];
                                    $_uemail = $_POST['email'];

                                    $_website   =   $_POST['website'];
                                    $_comments  =   stripslashes($_POST['comment']);

                                    $email_check = '';
                                    $return_arr = array();

                                    if($_uname=="" || $_uemail=="" || $_comments=="")
                                    {
                                        $return_arr["frm_check"] = 'error';
                                        $return_arr["msg"] = "Please fill in all required fields!";
                                    }
                                    else if(filter_var($_uemail, FILTER_VALIDATE_EMAIL))
                                    {

                                    $to = $adminemail;
                                    $from = $_uemail;
                                    $subject = "Renew Email: " .$_uname;

                                    $message =  'Name:   ' . $_uname . '

 Email:   ' . $_uemail . '

 website:   ' . $_website .  '

 Comment:  ' . $_comments;

                                    $headers = "MIME-Version: 1.0\r\n";
                                    $headers .= "Content-type: text/html; charset=iso-8859-1\r\n";
                                    $headers .= "Content-Transfer-Encoding: 7bit\r\n";
                                    $headers .= "From: " . $from . "\r\n";

                                    @mail($to, $subject, $message, $headers);

                                    } else {

                                    $return_arr["frm_check"] = 'error';
                                    $return_arr["msg"] = "Please enter a valid email address!";

                                }

                                echo json_encode($return_arr);
                                }
}

function createAjaxContactForm() {
    return '

                            <form action="process.php" method="post" name="ContactForm" id="ContactForm" >

                                    <input type="text" class="form-control" name="name" placeholder="Full Name *">

                                    <input type="text" class="form-control" name="email" placeholder="Email *">

                                    <input type="text" class="form-control" name="website" placeholder="Website">

                                    <textarea rows="5" class="form-control" name="comment" placeholder="Your Message *" style="height:175px;"></textarea>

                                <input class="btn btn-default" type="submit" value="ENVIAR" name="submitf" id="submitf">
                            </form>

';
}

add_shortcode('AjaxContactForm', 'createAjaxContactForm');

 ?>

and my ajax:
jQuery(function(){
    jQuery("#ContactForm").submit(function(){
        jQuery("#submitf").value='Please wait...';

        jQuery.post("password/wp-admin/admin-ajax.php", jQuery("#ContactForm").serialize(),
        function(data){
            if(data.frm_check == 'error'){

                    jQuery("#message_post").html("
ERROR: " + data.msg + "!
");
                    document.ContactForm.submitf.value='Resend >>';
                    document.ContactForm.submitf.disabled=false;
            } else {
                jQuery("#message_post").html("
Your message has been sent successfully!
");
                jQuery("#submitf").value='Send >>';
                }
        }, "json");

        return false;

    });
});

A: This is ajaxurl write this code your-theme/functions.php
<?php function frontend_custom_ajaxurl() { ?>

    <?php
  }
add_action('wp_head','frontend_custom_ajaxurl');

This is your php function can do anything. And also write this code in your-theme/functions.php file
function your_function() {
    parse_str($_POST['data'], $params);
    print_r($params)
    exit;
}
add_action('wp_ajax_your_function', 'your_function');
add_action('wp_ajax_nopriv_your_function', 'your_function');

This is JQuery.
jQuery("#ContactForm").submit(function(event) {
    event.preventDefault();
    jQuery("#submitf").value = 'Please wait...';
    var data = {
        action: 'your_function', // here php function such as your_function
        data: jQuery("#ContactForm").serialize(),
    };
    jQuery.post(ajaxurl, data, function(response) {
        ......................
    });
});

Any confusion comment?

A: for ajax use this code :

use the below code in .php file and replace $ with jQuery if it not works

$().ready(function() {
    var ajaxurl = "<?php echo admin_url('admin-ajax.php'); ?>";
    $.post(
        ajaxurl, {
            'action': 'set_the_city',
            //pass all the parameter from the form in key value pairs here
        },
        function(output) {
            console.log(output)
        });
});

WordPress provides a hook for ajax call use that instead.
add_action('wp_ajax_set_the_city', 'set_the_city');
add_action('wp_ajax_nopriv_set_the_city', 'set_the_city');

function set_the_city() {
    //all the data can be retrieved by $_REQUEST so do the coding for the_action_function() here.
}


text:
Q: IndexOutOfBound when grabbing filtered item from custom list view I've created a custom listview which generates the correct data but when I try to search for a specific item by its name, it returns the correct item but then crashes 1 second later due to an IndexOutOfBoundException, not quite sure why considering I've initialized all arrays to the correct size.
BossAdapter.java Boss.java
ListView listView;
int[] boss_icon = {R.drawable.boss_1, R.drawable.boss_2, R.drawable.boss_3,
        R.drawable.boss_4, R.drawable.boss_5, R.drawable.boss_6, R.drawable.boss_7,
        R.drawable.boss_8, R.drawable.boss_9, R.drawable.boss_10, R.drawable.boss_11,
        R.drawable.boss_12, R.drawable.boss_13, R.drawable.boss_14, R.drawable.boss_15,
        R.drawable.boss_16, R.drawable.boss_17, R.drawable.boss_18};
String[] boss_title=  new String[18];
BossAdapter adapter;
String[] bossTime=  new String[18];
Handler handler;
String[] bossAppearance=  new String[18];
EditText search_view;
ArrayList<Boss> bossList;
int bossID;

private int getID(String name){
    int id = 0;

    switch(name){
        case "다크 지란트":
            id = 0;
            return id;
        case "머쉬맘":
            id = 1;
            return id;
        case "MARK52 ALPHA":
            id = 2;
            return id;
        case "깡패 바라하":
            id = 3;
            return id;
        case "데블린 워리어":
            id = 4;
            return id;
        case "닉시":
            id = 5;
            return id;
        case "에피":
            id = 6;
            return id;
        case "자이언트 라바아이":
            id = 7;
            return id;
        case "둔둔":
            id = 8;
            return id;
        case "레버넌트 좀비":
            id = 9;
            return id;
        case "우르자":
            id = 10;
            return id;
        case "부기콜리":
            id = 11;
            return id;
        case "그리폰":
            id = 12;
            return id;
        case "프랑케네뜨":
            id = 13;
            return id;
        case "경비대장 차우":
            id = 14;
            return id;
        case "그리피나":
            id = 15;
            return id;
        case "매드오네뜨":
            id = 16;
            return id;
        case "자이언트 터틀":
            id = 17;
            return id;
    }

    return id;
}
private void createListview(){
    listView = (ListView) findViewById(R.id.list_view);
    search_view = (EditText)findViewById(R.id.search_text);

    boss_title = getResources().getStringArray(R.array.boss_array);

    bossList = new ArrayList<Boss>();

    adapter = new BossAdapter(getApplicationContext(), bossList);

    listView.setAdapter(adapter);
    listView.setTextFilterEnabled(true);
    bossTime = getKoreanTime();

    // Moved our object creation here, so that it should only be done once.
    for (String boss : boss_title) {
        bossID = getID(boss);
        bossAppearance = bossAppearance(bossID);

        Boss bossObject = new Boss(boss_icon[bossID], boss, bossTime[bossID], bossAppearance[bossID]);
        bossList.add(bossObject);

    }

    handler = new Handler();
    Runnable update = new Runnable() {
        @Override
        public void run() {
            bossTime = getKoreanTime();
            int count = adapter.getCount();

            for(String boss: boss_title){
                bossID = getID(boss);
                bossAppearance = bossAppearance(bossID);
                ((Boss) adapter.getItem(bossID)).setBoss_time(bossTime[bossID]); // Re-set time
                ((Boss) adapter.getItem(bossID)).setBoss_appearance(bossAppearance[bossID]);
            }

            adapter.notifyDataSetChanged(); // Notify our update
            handler.postDelayed(this, 1000);
        }
    };
    handler.postDelayed(update, 10);

    EditText myFilter = (EditText) findViewById(R.id.search_text);
    myFilter.addTextChangedListener(new TextWatcher() {

        public void afterTextChanged(Editable s) {
        }

        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        public void onTextChanged(CharSequence s, int start, int before, int count) {
            adapter.getFilter().filter(s.toString());
        }
    });

}

Strings.xml

    Boss Timer
<string-array name="boss_array">
    <item>다크 지란트</item>
    <item>머쉬맘</item>
    <item>MARK52 ALPHA</item>
    <item>깡패 바라하</item>
    <item>데블린 워리어</item>
    <item>닉시</item>
    <item>에피</item>
    <item>자이언트 라바아이</item>
    <item>둔둔</item>
    <item>레버넌트 좀비</item>
    <item>우르자</item>
    <item>부기콜리</item>
    <item>그리폰</item>
    <item>프랑케네뜨</item>
    <item>경비대장 차우</item>
    <item>그리피나</item>
    <item>매드오네뜨</item>
    <item>자이언트 터틀</item>

</string-array>

LOGCAT
07-24 17:11:18.628  11159-11159/baegmon.com.bosstimer E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: baegmon.com.bosstimer, PID: 11159
java.lang.IndexOutOfBoundsException: Invalid index 1, size is 1
        at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
        at java.util.ArrayList.get(ArrayList.java:308)
        at baegmon.com.bosstimer.BossAdapter.getItem(BossAdapter.java:38)
        at baegmon.com.bosstimer.MainActivity$1.run(MainActivity.java:158)
        at android.os.Handler.handleCallback(Handler.java:739)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:135)
        at android.app.ActivityThread.main(ActivityThread.java:5257)
        at java.lang.reflect.Method.invoke(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:372)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)

A: This is the problem!
bossList = new ArrayList<Boss>();
adapter = new BossAdapter(getApplicationContext(), bossList);

You populate the bossList after passing it to the adapter!
for (String boss : boss_title) {
    bossID = getID(boss);
    bossAppearance = bossAppearance(bossID);

    Boss bossObject = new Boss(boss_icon[bossID], boss, bossTime[bossID], bossAppearance[bossID]);
    bossList.add(bossObject);

}

Seems like I was wrong, the problem could be in the R.array.boss_array resource!
After seeing the resource could the encoding be the problem?
One entry is: <item>MARK52 ALPHA</item> and all the others are something in Korean. Could that possibly cause an issue?
Try changing one of the values to something like 'example' and run it again. If the error says that the array size is 2 than that is your problem.
You should also call adapter.notifyDataSetChanged(); after adding or removing items from the list!

A: You forgot to notify the adapter about the change in dataset.
// Moved our object creation here, so that it should only be done once.
for (String boss : boss_title) {
    ...
}
adapter.notifyDataSetChanged(); // This is required

Just to avoid any confusion, the above for loop is the first one shown in code.

A: Here is the problem, boss_title having 18 items. You are trying to iterating the loop from 0 to 18 and after that you are getting the nth item which is not there in the list.
((Boss) adapter.getItem(bossID)).setBoss_time(bossTime[bossID]);

bossID may be something else which is greater than the size of the list
....
for(String boss: boss_title){
                bossID = getID(boss);
                bossAppearance = bossAppearance(bossID);
                ((Boss) adapter.getItem(bossID)).setBoss_time(bossTime[bossID]); // Re-set time
                ((Boss) adapter.getItem(bossID)).setBoss_appearance(bossAppearance[bossID]);
            }


text:
Q: how to get point set (x,y) in a desired area in r
The figure is the plot of x,y set in a excel file, total 8760 pair of x and y. I want to remove the noise data pair in red circle area and output a new excel file with remain data pair. How could I do it in R?

A: Both R and EXCEL read and write .csv files, so you can use those to transfer the data back and forth.
You do not provide any data so I made some junk data to produce a similar problem.
DATA
set.seed(2017)
x = runif(8760, 0,16)
y = c(abs(rnorm(8000, 0, 1)), runif(760,0,8))
XY = data.frame(x,y)

One way to identify noise points is by looking at the distance to the nearest neighbors.  In dense areas, nearest neighbors will be closer. In non-dense areas, they will be further apart.  The package dbscan provides a nice function to get the distance to the k nearest neighbors. For this problem, I used k=6, but you may need to tune for your data. Looking at the distribution of distances to the 6th nearest neighbor we see that most points have 6 neighbors within a distance of 0.2
XY6 = kNNdist(XY, 6)
plot(density(XY6[,6]))

So I will assume that point whose 6th nearest neighbor is further away are noise points. Just changing the color to see which points are affected, we get
TYPE = rep(1,8760)
TYPE[XY6[,6] > 0.2] = 2
plot(XY, col=TYPE)

Of course, if you wish to restrict to the non-noise points, you can use
NonNoise = XY[XY6[,6] > 0.2,]

A: Using @G5W's example:
Make up data:
set.seed(2017)
x = runif(8760, 0,16)
y = c(abs(rnorm(8000, 0, 1)), runif(760,0,8))
XY = data.frame(x,y)

Fit a quantile regression to the 90th percentile:
library(quantreg)
library(splines)
qq <- rq(y~ns(x,20),tau=0.9,data=XY)

Compute and draw the predicted curve:
xvec <- seq(0,16,length.out=101)
pp <- predict(qq,newdata=data.frame(x=xvec))
plot(y~x,data=XY)
lines(xvec,pp,col=2,lwd=2)

Keep only points below the predicted line:
XY2 <- subset(XY,y<predict(qq,newdata=data.frame(x)))

plot(y~x,data=XY2)
lines(xvec,pp,col=2,lwd=2)

You can make the line less wiggly by lowering the number of knots, e.g. y~ns(x,10)


text:
Q: Create formula checkbox field I am trying to create a formula checkbox type field on custom object, which gets checked if related list "Notes & Attachment" has any files uploaded to it.

A: You can't do this. There's no way a formula can reference child objects (with a few special exceptions for standard relationships). Instead, you could make a checkbox field, make it read-only, and update via a trigger when a note/attachment is added/deleted to a parent record.


text:
Q: Performance implication of (mongo.Client).Ping I've recently noticed some odd behavior while testing the performance of writing or reading to a MongoDB serveless cluster.
I don't think is related to the serverless option, but as a context I'm using a new serverless cluster in AWS (Ireland region) which I interact with from my local machine.
Some demo code:
package main

import (
    "context"
    "fmt"
    "log"
    "time"

    "go.mongodb.org/mongo-driver/mongo"
    "go.mongodb.org/mongo-driver/mongo/options"
)

type Item struct {
    Value string `bson:"value"`
}

func main() {
    ctx := context.Background()
    client, err := mongo.Connect(ctx, options.Client().ApplyURI("add-url"))
    if err != nil {
        log.Fatalln(err)
    }

    err = client.Ping(ctx, nil)
    if err != nil {
        log.Fatalln(err)
    }

    collection := client.Database("test").Collection("test")
    item := Item{
        Value: "foo",
    }
    start := time.Now()
    _, err = collection.InsertOne(ctx, item)
    if err != nil {
        log.Fatalln(err)
    }

    fmt.Println("Item added in", time.Since(start))
}

This works fine, producing results of about 60ms consistently.
However, if I remove the err = client.Ping(ctx, nil) part the times jump to over 500ms consistently. Why does this happen?
Not much info I get from the docs.

A: From the documentation of NewClient method:
The NewClient function does not do any I/O and returns an error if the given options are invalid. The Client.Connect method starts background goroutines to monitor the state of the deployment and does not do any I/O in the main goroutine to prevent the main goroutine from blocking. Therefore, it will not error if the deployment is down.

The Client.Ping method can be used to verify that the deployment is successfully connected and the Client was correctly configured.

After you remove Ping instruction, InsertOne takes longer due to the overhead of creating the connection to the server. You may try to measure how long Ping command takes and it should be around 500ms.


text:
Q: Clarification about aop configuration in spring-context.xml I am learning aop spring and came across two ways of defining aop in spring-context.xml please see below:
<aop:aspectj-autoproxy />

    <bean id="customerBo" class="com.example.customer.impl.CustomerImpl" />

    <!-- Aspect -->
    <bean id="logAspect" class="com.example.aspect.LoggingAspect" />

The second one is:
<beans>

 <aop:aspectj-autoproxy>
<aop:include name = "logAspect"/>
<aop:aspectj-autoproxy/>

<bean id="logAspect" class="com.example.aspect.LoggingAspect" />

</beans>

The second one is more verbose but are they doing the same thing?
Thanks in advance for the help.


text:
Q: glibc detected-double free or corruption I have the following function which reads a buffer from a serial device, get some tokens and print these tokens every 10 seconds. I want these results to save them in a data.txt which I created in my Desktop. In the first loop I have the results and also I have them in the txt file but the second time I have this error
***glibc detected***/home/pi/Desktop/programming/bin/Debug/programming: double free or corruption(top):0x00dbe178 ***

I know that the problem is something with the free memory which I have allocated but I do not know where is the problem in my code and how can I fix it.Can anyone help me?
int learn_port2(int fd)
{
   int i;
   char buff[260];
   memset(buff, 0, sizeof(buff));
   char nodo[6] = "";
   char temp[6] = "";
   char hr[6] = "";
   char dw[6] = "";
   char vcc[6] = "";
   char* ptr;

   FILE *fp=fdopen(fd,"a+");
   FILE *ft = fopen("/home/pi/Desktop/data.txt","a+");
   time_t now;
   time(&now);

   while(fgets(buff, sizeof(buff), fp) != NULL)
   {
    fputs(buff,stdout);
    char *pos = strchr(buff,'N');
    if (pos)
    {

         ptr = strtok(buff, "Nodo_,=:V()");
         i = 0;
       while (ptr != NULL)
         {
          if (i == 0)
             strcat(nodo, ptr);
          if (i == 2)
             strcat(temp, ptr);
          if (i == 4)
             strcat(hr, ptr);
          if (i == 6)
             strcat(dw, ptr);
          if (i == 8)
             strcat(vcc, ptr);

          ptr = strtok(NULL, "Nodo_,=:V()");
          i++;
         }
       printf("Results: %s, %s, %s, %s, %s\n", nodo, temp, hr, dw, vcc);
       fprintf(ft,"%s,%s,%s,%s,%s\n", nodo, temp, hr, dw, vcc);

         fclose(ft);
      memset(nodo, 0, sizeof(nodo));
      memset(temp, 0, sizeof(temp));
      memset(hr, 0, sizeof(hr));
      memset(dw, 0, sizeof(dw));
      memset(vcc, 0, sizeof(vcc));
      printf("\n");
     }
  }

A: The posted code doesn't compile (I guess the missing } is at the end), but I can point out some problems:

*

*you don't nul-terminate buff after reading it, so strchr and/or strtok could go off the end

*you strcat into fixed-size buffers, without checking whether the thing you're copying fits. You could easily write off the end of your buffers here

*you fclose(ft) multiple times. You must do this only once, outside the loop

You should fix all three, and post your new compilable code if there's still an error.


text:
Q: Fast reading, writing of png images One of the fastest implemented mathematica function to read png images was showed  here by MarcoB
The code for reading a png he proposed is:
First@Image`ImportExportDump`ImageReadPNG[imageFileName];

Following this I tried out if ImageWritePNG exists and indeed, one can use:
Image`ImportExportDump`ImageWritePNG[imageFileName, image];

How can I find information that ImageReadPNG and ImageWritePNG exist and how they are used?

A: Here's one way you might find such a function.
Mathematica generally has descriptive names even for undocumented internal functions, so you can often find useful things by searching for appropriate substrings in symbol names. For example:
(* do a PNG import to make sure relevant functions are loaded *)
Import["any.png"];

(* search for symbols containing "PNG" *)
?*`*PNG*

One of the symbols is Image`ImportExportDump`ImageReadPNG which sounds like it might be useful. Check if we can see the definition:
GeneralUtilities`PrintDefinitions[Image`ImportExportDump`ImageReadPNG]

In this case there is nothing useful here.
To see if (and how) the function is used during a PNG import, use Trace:
Trace[Import["any.png"], Image`ImportExportDump`ImageReadPNG[___],
  TraceInternal -> True]

{{{Image`ImportExportDump`ImageReadPNG["any.png"]}}}

So it looks like the function just takes the filename as an argument. Next you can test it and time it to find out if it's any better than simply using Import.
This is the sort of approach you need to take to uncover undocumented functions - there is inevitably an element of trial and error and often you will find nothing useful at all. Of course you should always save your work before this kind of experimentation.


text:
Q: Given that B has rational co-ordinates and A , B are equidistant from H. I need to find B(h,k). I am given two points $A(3,5)$ and $H (\sqrt{2},\sqrt{5})$ and a third point $B(h,k)$ . Given that
$B$ has rational co-ordinates and A , B are equidistant from H. I need to find $B(h,k)$.
What I tried :
$AH^2 = BH^2$
$h^2 + k^2  - 2\sqrt{2}(h-3) - 2\sqrt{5}(k-5)-34=0$     ------------>(1)
In the book , it is given that since $B(h,k)$ are rational so $h-3=0 , k-5=0$
I didn't understand this step . Eq(1) gives the locus of possible points B. So what does $h-3=0$
and $k-5=0$ got to do with $(h,k)$ being rational?

A: The sum of a (nonzero) rational number and an irrational number is never zero. Therefore, the expression labeled as equation one is only zero if the irrational terms are each themselves zero. This yields $2\sqrt{2}(h-3)=0$ and $-2\sqrt{5}(k-5)=0$, from which the result follows.


text:
Q: htaccess redirect old links to new website index and manually redirect some exceptions We have created a new website which has a different page structure that the old one. We still want to have the contact page pointing to the contact page on the the website, the team page to the new one, and so on.
The new website is on another domain and the links are not the same - for example on the old website we had www.example.com/contact and now we have www.newexample.com/contact-us.
I would like to be able to do manual redirects for the important pages like this
Redirect 301 old_link new_link

And all the pages that are not covered in the list of manual redirects should be redirected to the new website's index.
Is this possible, or is it a better approach?
Thank you

A: You can set up this rule in your old document root:
RewriteEngine On
#Redirect to new structure
RewriteRule ^contact$ http://www.newexample.com/contact-us [L,R=301]

#Redirect all to www.newexample.com:
RewriteCond %{HTTP_HOST} ^(www\.)?example\.com$ [NC]
RewriteRule ^(.*) http://www.newexample.com/$1 [R=301,L]

You need to set this for the new site:
#Redirect all 404 Errors to http://www.newexample.com
ErrorDocument 404 http://www.newexample.com

A: you can put a Rewrite condition for each of the old urls like RewriteCond %{REQUEST_URI} !(old_link) [NC] and then put a Rewrite rule that serves all other links RewriteRule ^(|/|/(.*))$ new_link [R=301,L]

A: Another method:
Redirect all request to a php file using .htaccess an manage via php
<?
$url=$_SERVER['QUERY_STRING'];
$start= strrpos($url,'/')+1;

if ( strpos($url,"/old_structure/")!==false ) $newest="/new_structure";

$url=substr($url,$start);
$url=trim($url);
$domain="domain.com". $newest ."/$url";

Header( "HTTP/1.1 301 Moved Permanently" );
Header( "Location: http://$domain" );
die();
?>


text:
Q: How to log an ALS model within a mlflow run? I currently work on a databricks cluster trying to log an ALS model within a mlflow run.
Trying multiple different approaches I either get a TypeError "cannot pickle '_thread.RLock' object" stopping my run or an OSError "No such file or directory: '/tmp/tmpxiznhskj/sparkml'" not stopping my run but I am not able to load that model back into my code.
Here is the prep code to play around a little bit:
import mlflow
import logging
from pyspark.ml.evaluation import RegressionEvaluator
from pyspark.ml.recommendation import ALS
from pyspark import SparkContext, SparkConf

data = [{"User": 1, "Item": 1, "Rating": 1},
        {"User": 2, "Item": 2, "Rating": 3},
        {"User": 3, "Item": 3, "Rating": 1},
        {"User": 4, "Item": 2, "Rating": 4},
        {"User": 1, "Item": 2, "Rating": 3},
        {"User": 2, "Item": 3, "Rating": 2},
        {"User": 2, "Item": 4, "Rating": 1},
        {"User": 4, "Item": 1, "Rating": 5}
        ]

conf = SparkConf().setAppName("ALS-mlflow-test")
sc = SparkContext.getOrCreate(conf)
rdd = sc.parallelize(data)
df_rating = rdd.toDF()

(df_train, df_test) = df_rating.randomSplit([0.8, 0.2])

logging.getLogger("mlflow").setLevel(logging.DEBUG)

*

*Using this as a base I tried different approaches, starting with the mlflow.sklearn.log_model method:

with mlflow.start_run() as run:
    model_als = ALS(maxIter=5, regParam=0.01, userCol="User", itemCol="Item", ratingCol="Rating", implicitPrefs=False,
          coldStartStrategy="drop")

    model_als.fit(df_train)
    mlflow.sklearn.log_model(model_als, artifact_path="test")

which results in the following error:
_SklearnCustomModelPicklingError: Pickling custom sklearn model ALS failed when saving model: cannot pickle '_thread.RLock' object

*Next I tried using a WrapperModel for my ALS model (the Wrapper does not actually do something yet):

class MyModel(mlflow.pyfunc.PythonModel):
    def __init__(self, model):
        self.model = model

    def predict(self, context, model_input):
        return self.my_custom_function(model_input)

    def my_custom_function(self, model_input):
        return 0

with mlflow.start_run():
    model_als = ALS(maxIter=5, regParam=0.01, userCol="User", itemCol="Item", ratingCol="Rating", implicitPrefs=False,
          coldStartStrategy="drop")
    my_model = MyModel(model_als)
    model_info = mlflow.pyfunc.log_model(artifact_path="model", python_model=my_model)

resulting in a more general but basically the same error as in step 1:
TypeError: cannot pickle '_thread.RLock' object

*I then tried putting my model within a pipeline (again nothing fancy just plain and simple for a test):

from pyspark.ml import Pipeline

with mlflow.start_run() as run:
    model_als = ALS(maxIter=5, regParam=0.01, userCol="User", itemCol="Item", ratingCol="Rating", implicitPrefs=False,
          coldStartStrategy="drop")

    pipeline = Pipeline(stages=[model_als])
    pipeline_model = pipeline.fit(df_train)
    mlflow.spark.log_model(pipeline_model, artifact_path="test-pipeline")

This time the code executed but having a look at the debug log there also went something wrong:
stderr: Setting default log level to "WARN".
To adjust logging level use sc.setLogLevel(newLevel). For SparkR, use setLogLevel(newLevel).
2023/01/05 08:54:22 INFO mlflow.spark: File '/tmp/tmpxiznhskj/sparkml' not found on DFS. Will attempt to upload the file.
Traceback (most recent call last):
  File "/databricks/python/lib/python3.9/site-packages/mlflow/utils/_capture_modules.py", line 162, in <module>
    main()
  File "/databricks/python/lib/python3.9/site-packages/mlflow/utils/_capture_modules.py", line 137, in main
    mlflow.pyfunc.load_model(model_path)
  File "/databricks/python/lib/python3.9/site-packages/mlflow/pyfunc/__init__.py", line 484, in load_model
    model_impl = importlib.import_module(conf[MAIN])._load_pyfunc(data_path)
  File "/databricks/python/lib/python3.9/site-packages/mlflow/utils/_capture_modules.py", line 134, in _load_pyfunc_patch
    return original(*args, **kwargs)
  File "/databricks/python/lib/python3.9/site-packages/mlflow/spark.py", line 832, in _load_pyfunc
    return _PyFuncModelWrapper(spark, _load_model(model_uri=path))
  File "/databricks/python/lib/python3.9/site-packages/mlflow/spark.py", line 727, in _load_model
    model_uri = _HadoopFileSystem.maybe_copy_from_uri(model_uri, dfs_tmpdir)
  File "/databricks/python/lib/python3.9/site-packages/mlflow/spark.py", line 404, in maybe_copy_from_uri
    return cls.maybe_copy_from_local_file(_download_artifact_from_uri(src_uri), dst_path)
  File "/databricks/python/lib/python3.9/site-packages/mlflow/tracking/artifact_utils.py", line 100, in _download_artifact_from_uri
    return get_artifact_repository(artifact_uri=root_uri).download_artifacts(
  File "/databricks/python/lib/python3.9/site-packages/mlflow/store/artifact/local_artifact_repo.py", line 79, in download_artifacts
    raise IOError("No such file or directory: '{}'".format(local_artifact_path))
OSError: No such file or directory: '/tmp/tmpxiznhskj/sparkml'

*Nevertheless, I tried loading the model, since the code ran through:

from pyspark.ml import PipelineModel

logged_model = 'runs:/xyz123/test'

# Load model
loaded_model = PipelineModel.load(logged_model)

results in the error:
org.apache.hadoop.fs.UnsupportedFileSystemException: No FileSystem for scheme "runs"

*I then tried the auto generated code from databricks:

import mlflow
logged_model = 'runs:/xyz123/test'

# Load model
loaded_model = mlflow.spark.load_model(logged_model)

# Perform inference via model.transform()
loaded_model.transform(data)

results in the following error:
AttributeError: 'list' object has no attribute '_jdf'

*Last piece of code would be (but was not able to get to it yet, since I can't load the model):

evaluator = RegressionEvaluator(metricName="rmse", labelCol="Rating", predictionCol="prediction")

df_pred = loaded_model.transform(df_test)
rmse = evaluator.evaluate(df_pred)

df_pred.display()

print("Root-mean-square error explicit = " + str(rmse))

user_recs = loaded_model.recommendForAllUsers(2)
user_recs.display()

I conclusion what I am trying to achieve is simply logging the provided ALS model within my mlflow run.
I ran out of ideas what could be wrong or what else I could try
Thanks in advance!

A: As of MLFlow 2.1.1 pyspark.ml.recommendation.ALS is not on the allowlist. Using the pipeline as you tested in #3 is the appropriate way to log unsupported spark.ml models.
It looks like you might have hit an environment issue when logging your model, as I was able to get the following implementation working both on Databricks and locally.
Log within run
import mlflow
from mlflow.models.signature import infer_signature
from pyspark.ml import Pipeline
from pyspark.ml.recommendation import ALS

# get a bigger test split from your data
(df_train, df_test) = df_rating.randomSplit([0.6, 0.4])

with mlflow.start_run() as run:
    # initialize als model
    als = ALS(
        maxIter=5,
        regParam=0.01,
        userCol="User",
        itemCol="Item",
        ratingCol="Rating",
        implicitPrefs=False,
        coldStartStrategy="drop",
    )

    # build and fit pipeline
    pipeline = Pipeline(stages=[als])
    pipeline_model = pipeline.fit(df_train)

    # test predict and infer signature
    predictions = pipeline_model.transform(df_test)
    signature = infer_signature(df_train, predictions)

    # log model
    mlflow.spark.log_model(
        pipeline_model, artifact_path="spark-model", signature=signature
    )

    mlflow.end_run()

Reload for inference
On Databricks you need to first move the model from the experiment into the model registry. This can be done via the UI or with the following commands.
# construct the model_uri from generated run_id and the set artifact_path
run_id = "2f9a5424b1f44435a9413a3e2762b8a9"
artifact_path = "spark-model"
model_uri = f"runs:/{run_id}/{artifact_path}"

# move the model into the registry
model_details = mlflow.register_model(model_uri=model_uri, name=model_name)

# load model
version = 1
model_uri = f"models:/{model_name}/{version}"
loaded_model = mlflow.spark.load_model(model_uri)

# test predict
loaded_model.transform(df_test).show()

+----+------+----+----------+
|Item|Rating|User|prediction|
+----+------+----+----------+
|   2|     3|   2| 1.0075595|
+----+------+----+----------+

Log directly to registry
Alternatively, you can also log directly to the model registry.
# log model
model_name="als-model"
mlflow.spark.log_model(
    pipeline_model,
    artifact_path="spark-model",
    registered_model_name=model_name
)

# log model
version = 1
model_uri = f"models:/{model_name}/{version}"
loaded_model = mlflow.spark.load_model(model_uri)

# test predict
loaded_model.transform(df_test).show()

Logging as custom pyfunc
I also tried wrapping the ALS model and the pipeline in a custom pyfunc  and in both cases I received the same exact error. I believe there is something unserializable with the ALS model that prevents this...


text:
Q: Implementing Proximity Text Search in Java I'm looking for a simple way to implement proximity search in java.
By Proximity search I mean how it is defined by Lucene:

Lucene supports finding words are a within a specific distance away.
  To do a proximity search use the tilde, "~", symbol at the end of a
  Phrase. For example to search for a "apache" and "jakarta" within 10
  words of each other in a document use the search:
"jakarta apache"~10

More specifically: as a start I would like to implement a method of the following form:
public static boolean proximityMatches(String txt, String term1, String term2, int wordDistance) {

// for the inputs:
// txt= "this is a really foo barred world", term1="foo", term2="world", wordDistance=4
// return true

// for the inputs:
// txt= "this is a really foo barred world", term1="this", term2="bar", wordDistance=1
// return false

}

Notes:

*

*I know how to write a function to satisfy the requirements I've put up there -- what I'm looking for is an accepted standard way to implement this.

Thanks.

A: If there's an accepted standard way to do this, it's to use Lucene.  There are some regex gimmicks you can use, like this one from RegexBuddy's library (where word1 and word2 are placeholders for the search terms, and the 3 in {1,3}? is the maximum distance):
\b(?:word1(?:\W+\w+){1,3}?\W+word2|word2(?:\W+\w+){1,3}?\W+word1)\b

Trouble is, this relies on an extremely simplistic, arbitrary notion of what constitutes a word.  It doesn't match contractions or hyphenated words, but it does match "words" with digits and underscores in them.  You could tweak the regex to deal with those problems, but more will pop up to replace them.  And ugly as it already was, each tweak makes the regex that much less readable, that much harder to maintain.
This barely scratches the surface of what full-text search engines save you from.  If you have a very specific, tightly constrained task to accomplish, regexes or other "syntax-level" tools might suit.  But if you need to work at the semantic level, recognizing natural-language words and phrases, you want a search engine or other dedicated tool.

A: If you are looking for the word to the left you could try this.
String str = "Lucene supports finding words are a within a specific distance away.";
boolean found = false;
int start = str.length() -1;
int end = str.length();

    while ( !found )
    {
        if ( str.substring( start, end).contains( "specific" ) )
        {
            int total = end - start;
            System.out.println( "You word has been found " + total + " characters to the left" );
            found = true;
        }
        else
        {
            start -= 1;
        }
    }


text:
Q: Do I need to use MetaTag http-equiv with DTD XHTML 1.0 Transitional//EN? I use Asp.net
In my document I use:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

I would like to know if is necessary to add also this MetaTag:
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

Thanks for your tme on this.

A: You should add the meta tag, though it is not compulsory.
The DOCTYPE doesn't not automatically tell you what the character set is, so you should add the information that the file is encoded as UTF-8.
You should also ensure the content-type HTTP header is also set to UTF-8.

A: Doctype Definition

The doctype declaration should be the very first thing in an HTML document,
  before the  tag.
The doctype declaration is not an HTML tag; it is an instruction to the web
  browser about what version of the markup language the page is written in.
The doctype declaration refers to a Document Type Definition (DTD). The DTD
  specifies the rules for the markup language, so that the browsers render the
  content correctly.

See the reference:
http://www.w3.org/QA/Tips/Doctype
http://www.w3.org/TR/html4/struct/global.html
Character Encoding

The document character set for XML and HTML 4.0 is Unicode (aka ISO 10646).
  This means that HTML browsers and XML processors should behave as if they
  used Unicode internally. But it doesn't mean that documents have to be
  transmitted in Unicode. As long as client and server agree on the encoding,
  they can use any encoding that can be converted to Unicode. Read more about
  the document character set.
It is very important that the character encoding of any XML or (X)HTML document
  is clearly labeled, so that clients can easily map these encodings to Unicode.
  This can be done in the following ways...

See The Reference http://www.w3.org/International/O-charset
Both are necessary, but not dependent to each other.

A: Yes this is perfectly fine to add that just make sure the file extension has .aspx or whatever attached to it.
Example ASP page with html:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

Hello There!

<%Response.Write(now())%>

Hope this helps.


text:
Q: How to query auto set axis bounds in bokeh? I've created a plot and let bokeh choose the axis bounds automatically.  Now I want to know what the min and max values of that axis are (specifically because I want to overlay the plot of a mathematical function and want to know over what range to evaluate it).
The obvious approach was to query fig.y_range.start and fig.y_range.end, but it appears those are set to None when autoscaled, so they look like input parameters.
How do I determine what the results of autoscaling were?

A: This information is not available in Python, those bounds are only computed in the browser, in JavaScript. If you need explicit details/control, you will need to set the ranges manually, e.g.
p = figure(x_range=(0, 137))


text:
Q: Do all Lists in Java maintain insertion order The List javadocs mentions that Lists are ordered. However, I cannot see anything specifying the nature of the ordering. Can we rely on lists e.g. ArrayList and LinkedList maintaining insertion order?
I am asking about the instance where we do not call set or sort.

A:
However, I cannot see anything specifying the nature of the ordering.

Funnily enough, it's mentioned in the second sentence of its documentation:

The user of this interface has precise control over where in the list each element is inserted.

Without calling List#set or List#sort, the only methods that will add elements to the List are List#add and List#addAll, both of which append them to the end (unless you call one of the overloaded methods and specify an index); you can also add elements to the List via its ListIterator.
If List did not maintain insertion order, it would have mentioned it in its documentation.  If you're still unsure, feel free to look over the source code, which is available online.


text:
Q: Crop background of the layout I would like to make this kind of background

I tried to get this with corner radius, but unsuccessfully. What do I need to use, to cut it like this? or to even make this kind of background:

A: Create it as a .png file, and set the transparency to something less than 100% (probably about 70%), then add it to your drawable folder. In your XML file, you call then write android:background="@drawable/your_back_image"
Android will automatically strech it for you so it will always fit the screen.


text:
Q: scraping price from the website using python I tried to scrape the price from the website below:
https://www.emma-sleep.com.au/diamond-hybrid/
The price i wanna get should be 674.55.
Below is my code:
web_url = 'https://www.emma-sleep.com.au/diamond-hybrid/'
web_response = requests.get(web_url)
b_soup = BeautifulSoup(web_response.text, 'html.parser')
price=b_soup.find_all('span', {'class': 'installment__full-price'})
price

it will return me of a price of 1000 somehow, which is wrong
[ $1,000.00 ]
could someone please tell me where i get it wrong?
seems like the price is in the 'script' tage when i checked the html code.
Thanks :)

A: The price is calculated in javascript. For that you need to use an API like Selenium that first renders the page in the browser then allows you to access the HTML.
Target html tags:

   $674.55

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager

web_url = 'https://www.emma-sleep.com.au/diamond-hybrid/'

s = Service(ChromeDriverManager().install())
driver = webdriver.Chrome(service=s)

# web driver goes to page
driver.get(web_url)

# to give time for the page to load
driver.implicitly_wait(3)

price = driver.find_element(By.XPATH, "//span[@class='regular-price text-orange']/span[@class='price']").text
print(price)

Output:
$674.55

You can also use the XPATH expression:
//span[contains(@class, 'regular-price')]/span[@class='price']


text:
Q: Backbone Collection url with dynamic parameters I'm writing a Rails app with Backbone.js.
In Rails, I have a route in config/routes.rb that takes an argument like this: /api/u/foo. It gets all posts by the argument, in this case foo. The output of this is all posts by foo. Foo is a user, who has many posts.
In Backbone, I need to set the url attribute on the collection to take arguments from the route, like this: /u/foo. I want that to go get /api/u/foo.json. How could I do this? I tried taking a user argument on the Backbone route, but I could't get it to the collection.
The relevant part of the routes.rb file:
scope 'api' do
  get "/u/:user", :action => "index", :controller => "posts"
end

A: Assuming foo is your parameter, it only makes sense that Backbone would apply that URL to fetch a single user, not a collection.
I believe your routes are already fine where /api/u should return the collection and /api/u/123 a single user. What you want is to send extra parameters to /api/u?foo=bar to filter your collection.
Just send these in your .fetch() call in Backbone to get it working. Apply the necessary changes in your controller to filter according to the various parameters possible.
Update
Knowing you want posts per user, your question actually has to do nested routes. It has already been asked here:
Backbone and Rails Nested Routes
The documentation on Backbone.js is here: http://documentcloud.github.com/backbone/#FAQ-nested
To stay a bit more restful, I would define the routes as so:
scope '/api' do
  resources :users, only: [], path: 'u' do
    resources :posts, only: :index
  end
end

Which results in:
api_user_posts GET    /api/u/:user_id/posts(.:format)      api/posts#index


text:
Q: mongodb query not using index I have a index:
{
    "sourceName" : 1,
    "addedDate" : 1,
    "sourceKey" : 1,
    "appKey" : 1,
}

But when I try to do
db.myCollection.find({and:[
               {sourceName: "mySourceName"},
               {addedDate: 1414878162405},
               {sourceKey:"mySource Key"},
               {appKey: "test"}]
               }).explain()

It shows cursor is BasicCursor i.e it is not using the index:
{
    "cursor" : "BasicCursor",
    "isMultiKey" : false,
    "n" : 0,
    "nscannedObjects" : 500,
    "nscanned" : 500,
    "nscannedObjectsAllPlans" : 500,
    "nscannedAllPlans" : 500,
    "scanAndOrder" : false,
    "indexOnly" : false,
    ...
}

Can anyone please explain me why my query is not using defined index??

A: Your query object uses and instead of the $and operator so it's looking for an field named 'and' in your documents that contains your query values.
But you don't need to be using $and anyway, as multiple query terms are implicitly ANDed so you can just do:
db.myCollection.find({
       sourceName: "mySourceName",
       addedDate: 1414878162405,
       sourceKey:"mySource Key",
       appKey: "test"}
   }).explain()

That should be able to use your index just fine.


text:
Q: Storing and getting values from sharedpreferences in android I want to store values in sharedpreferences and getting values from sharedpreferences finally display the values in listview. Next I want to remove values from list when click on longpress on specific value .After removing values status updated in sharedpreferences. i done this one but problem is when close application and open again i have to display  sharedpreferences vales in listview. but it display NullPointerExeption,
actually my requirement is 1)storing values in sharedpreferences and display values in listview for every click .allowed only five values.And that list values are available in onresume() method also.
2) when long press on specific value of listview it have to remove and and updated values are stored in sharedpreferences also.
my code
public class ListViewDemo1 extends Activity {
    /**
     * Called when the activity is first created.
     */
    Button btn;
    static int count;
    private ListView list;
    public static ArrayList<String> values = new ArrayList<String>();
    ArrayList countList = new ArrayList();
    private ArrayAdapter adapter;
    SharedPreferences shared;
    Editor editor;
    private static ArrayList<String> sharedList;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        list = (ListView) findViewById(R.id.list);
        btn = (Button) findViewById(R.id.btn);
        shared = this.getSharedPreferences("Myprefernces", Context.MODE_WORLD_WRITEABLE);
        editor = shared.edit();
        btn.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                // TODO Auto-generated method stub
                sharedList = new ArrayList();
                count++;
                if (count == 1) {
                    values.add("one");
                    countList.add(count);
                }
                if (count == 2) {
                    values.add("two");
                    countList.add(count);
                }
                if (count == 3) {
                    values.add("three");
                    countList.add(count);
                }
                if (count == 4) {
                    values.add("four");
                    countList.add(count);

                }
                if (count == 5) {
                    values.add("five");
                    countList.add(count);
                }
                if (count > 5) {
                    --count;
                    Toast.makeText(getApplicationContext(), "" + count, 100).show();
                }
                //put values to sharedpreferences
                editor.putInt("SIZE", values.size());
                for (int i = 0; i < values.size(); i++) {
                    editor.putString("addr" + i, values.get(i));
                }
                editor.commit();
                // getting values from sharedpreference
                int size = shared.getInt("SIZE", 0);
                for (int k = 0; k < size; k++) {
                    sharedList.add(shared.getString("addr" + k, ""));
                }
                adapter = new
                        ArrayAdapter(ListViewDemo1.this, android.R.layout.simple_list_item_1, sharedList);
                list.setAdapter(adapter);
            }
        });
        list.setOnItemLongClickListener(new OnItemLongClickListener() {

            public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
                                           int arg2, long arg3) {
                // TODO Auto-generated method stub
                --count;
                values.remove(arg2);
                sharedList.remove(arg2);
                editor.clear();
                editor.commit();
                editor.putInt("SIZE", sharedList.size());
                for (int i = 0; i < sharedList.size(); i++) {
                    editor.putString("addr" + i, sharedList.get(i));
                }
                editor.commit();
                adapter.notifyDataSetChanged();

                return true;
            }
        });

    }

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        if (sharedList.size() > 0) {
            adapter = new
                    ArrayAdapter(ListViewDemo1.this, android.R.layout.simple_list_item_1, sharedList);
            list.setAdapter(adapter);
        }
    }
}

Logcat
04-21 09:56:02.142: E/AndroidRuntime(1160): FATAL EXCEPTION: main
04-21 09:56:02.142: E/AndroidRuntime(1160): java.lang.RuntimeException: Unable to resume activity {com.views/com.views.ListViewDemo1}: java.lang.NullPointerException
04-21 09:56:02.142: E/AndroidRuntime(1160):     at android.app.ActivityThread.access$600(ActivityThread.java:141)
04-21 09:56:02.142: E/AndroidRuntime(1160):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
04-21 09:56:02.142: E/AndroidRuntime(1160):     at android.os.Handler.dispatchMessage(Handler.java:99)
04-21 09:56:02.142: E/AndroidRuntime(1160):     at android.os.Looper.loop(Looper.java:137)
04-21 09:56:02.142: E/AndroidRuntime(1160):     at android.app.ActivityThread.main(ActivityThread.java:5041)
04-21 09:56:02.142: E/AndroidRuntime(1160):     at java.lang.reflect.Method.invokeNative(Native Method)
04-21 09:56:02.142: E/AndroidRuntime(1160):     at java.lang.reflect.Method.invoke(Method.java:511)
04-21 09:56:02.142: E/AndroidRuntime(1160):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
04-21 09:56:02.142: E/AndroidRuntime(1160):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
04-21 09:56:02.142: E/AndroidRuntime(1160):     at dalvik.system.NativeStart.main(Native Method)
04-21 09:56:02.142: E/AndroidRuntime(1160): Caused by: java.lang.NullPointerException
04-21 09:56:02.142: E/AndroidRuntime(1160):     at com.views.ListViewDemo1.onResume(ListViewDemo1.java:114)
04-21 09:56:02.142: E/AndroidRuntime(1160):     at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1185)

A: You instantiate sharedList only in onClick() method of a button. This method is not called when your activity is resumed and sharedList is null.
You need to check if it's not null:
@Override
protected void onResume() {
    // TODO Auto-generated method stub
    super.onResume();
    if(sharedList != null && sharedList.size()>0){
        adapter=new ArrayAdapter(ListViewDemo1.this,android.R.layout.simple_list_item_1,sharedList);
        list.setAdapter(adapter);
    }
}

A: The problem i think is with initialization(or rather not doing that),
static int count;
public static ArrayList<String>  values = new ArrayList<String>();
private static ArrayList<String> sharedList;

Now for eg, not initialized count to a value before:
count++;
if(count==1){

Same needs to be done for sharedList, like new ArrayList...
And yes, the reason being onCreate() is not called before onResume() every time, for more on the refer Android Activity Life Cycle
Check Figure 1. The activity lifecycle. on that link.
It will give you a better idea for your implementation/requirement and how to initialize or work with sharedPref and other components for your activity.

A: read this I hope help you http://developer.android.com/guide/topics/data/data-storage.html
You can use SharedPreferences:
To save data:
SharedPreferences.Editor editor = getPreferences(MODE_PRIVATE).edit();
 editor.putString("text", mSaved.getText().toString());
 editor.putInt("selection-start", mSaved.getSelectionStart());
 editor.putInt("selection-end", mSaved.getSelectionEnd());
 editor.commit();

To retrieve data:
SharedPreferences prefs = getPreferences(MODE_PRIVATE);
String restoredText = prefs.getString("text", null);
int selectionStart = prefs.getInt("selection-start", -1);
int selectionEnd = prefs.getInt("selection-end", -1);


text:
Q: Right-angled triangle ABC (I'm only a Year 7 so please explain clearly how you found the solution)
In the right angled triangle $ABC$, a point $M$ on the hypotenuse $BC$ is such that $AM$ is perpendicular to $BC$. Also, $MC$ is $8$ cm longer than $BM$, and the ratio $AB:AC=3:5$
How many centimetres is the hypotenuse?
I started by calling the length of $BM=y$, and $MC=y+8$  and then using similar triangle ratios created fractions $\frac{AM}{MC} =  \frac{BM}{AM}$ which cancelled out to make $\frac{BM}{MC}$ which substitutes into $\frac{y}{y+8}$ but then I got stuck. Can anyone help me?. By the way, the answer is $17$.

A: This is how I did it:

Since $ \angle AMC =  \angle AMB =  90°$ , apply the Pythagoras Theorem in $   \triangle AMC $ and $ \triangle AMB $
$$\implies (y+8)^2 + x^2 = (5k)^2$$
$$\implies y^2 + 16y + 64 + x^2 = 25k^2 ...(1)$$
Also, $$x^2 + y^2 = (3k)^2$$
$$\implies x^2 + y^2 = 9k^2 ....(2)$$
Now, substituting $(2)$  into  $(1)$ ,
$$9k^2 + 64 + 16y = 25k^2$$
$$\implies 16y + 64 = 16k^2$$
$$\implies y + 4 = k^2$$ (dividing both sides by $16$ )
$$\implies BC = 2y + 8 = 2k^2$$
Now, on applying Pythagoras Theorem in $\triangle BAC$ ,  we get
$$ 9k^2 + 25k^2 = 4k^4$$
$$\implies 34 = 4k^2$$ (dividing both sides by $ k^2 $ )
$$\implies BC = 2k^2 = 17 cm $$ (dividing both sides by $ 2 $ )
NOTE: To clear your confusion regarding $3k$ and $5k$, the $k$ has been written because $AB$ and $AC$ may not necessarily be $3cm$ and $5cm$ respectively (and they are not in this case also). In order to maintain the ratio, we have expressed $AB$ as $3k$ and $AC$ as $5k$, where $k$ can be any positive real number. I hope it's clear. If it's not, then please write in the comments below.

A: Call $BM=y$. We know that $AB=0.6AC$. Time to invoke Euclid:
$$(0.6AC)^2=y\cdot(2y+8)\text{ and } AC^2=(y+8)\cdot (2y+8).$$
Now divide the first equation by the second to solve
$$0.36=\frac{y}{y+8}.$$
EDIT: If you replace $8$ by $a$ and $0.6$ by $t$, the hypotenuse will be
$$a\cdot\frac{1+t^2}{1-t^2}.$$
(Provided that $t\neq1$; in this case there is no solution unless $a=0$.)


text:
Q: Web Server (Shared VPS Windows), store file checksums en masse for cron I tried looking for answers , so hopefully this is not a duplicate.
I am working on a web server, and what I need to do is maintain a checksum "database" of all files within the public_html folder.
I can run the cron job using PHP or C# , and so I'm comfortable with this in either language.

*

*[Goal]:   Maintain checksum database (properly) of all files (approx. 800,000)

*[Purpose]: Monitor changes and perform heuristics on new files (security related)

*[Problem]: Speed

*[Question]:  What in your opinion or expertise is the BEST way to store that information?

Windows Hosting environment.
I have to run a loop over every file in every subdirectory, and check if the current md5(file) is identical to the stored_md5(file), and if not , queue up some tasks for later.

*

*If it's stored in say a mysql database, it will have to have really good indexes on the MD5 32char checksum keys, or it will be incredibly slow to process.

*If it's stored in a file, then that checksum information has to be loaded into memory, which is not a good idea for my web server.

Thoughts? Recommendations?


text:
Q: How to convert java merge sort algo to cpp Problem
I have a source code in Java for sorting array elements using the merge sort algorithm. The principle uses a loop to compare an element in the array with the element in the next index in the array. If the earlier is bigger than the later then the numbers are swapped logically to reassign the array elements in the indices.
My problem is that the Java algo works but the C++ algo does not. The logic is the same, what am I doing wrong....
Code
Working Java Code
static void sort(int[] arr) {
    for (int i = 0; i < arr.length; i++) {
        for (int j = i + 1; j < arr.length; j++) {
            if (arr[i] > arr[j]) {
                int temp = arr[i];
                arr[i] = arr[j];
                arr[j] = temp;
            }
        }
    }
}

C++ Code built on the same merge sort pseudocode as the Java Source code but fails to work
void sorting(int d[]) {
    for (int i = 0; i < sizeof(d); i++) {
        for (int j = i + 1; j < sizeof(d); j++) {
            if (d[i] > d[j]) {
                int temp = d[i];
                d[i] = d[j];
                d[j] = temp;
            }
        }
    }
}

Input Format
Both methods got parameters from arrays initialized to a fixed size and then a loop was used to get input from user and asign to the array, the user has to enter the size of the array first.
Reliability of the merge sort algo in other languages
I have applied the mergesort pseudocode in JavaScript, Python and C# and they all worked. I do not know why C++ would be an exception, please help...

A: For starters there is no merge sort algorithm in your question.
In fact there is a modified selection sort algorithm.
This function declaration
void sorting(int d[])

is adjusted by the compiler to the declaration
void sorting(int *d)

That is the parameter has a pointer type.
So the expression
sizeof(d)

yields the size of a pointer not the number of element in the passed array.
You need also to pass to the function the number of elements in the array.
The function can look the following way
void sorting( int a[], size_t n )
{
    for ( size_t i = 0; i < n; i++ )
    {
        size_t min = i;

        for ( size_t j = i + 1; j < n; j++ )
        {
            if ( a[j] < a[min] ) min = j;
        }

       if ( i != min ) std::swap( a[i], a[min] );
    }
}

Another approach is using a template function that accepts an array by reference.
For example
template <size_t N>
void sorting( int ( &a )[N] )
{
    for ( size_t i = 0; i < N; i++ )
    {
        size_t min = i;

        for ( size_t j = i + 1; j < N; j++ )
        {
            if ( a[j] < a[min] ) min = j;
        }

       if ( i != min ) std::swap( a[i], a[min] );
    }
}

Here is a demonstration program that shows usage of the two functions.
#include <iostream>
#include <utility>

void sorting( int a[], size_t n )
{
    for (size_t i = 0; i < n; i++)
    {
        size_t min = i;

        for (size_t j = i + 1; j < n; j++)
        {
            if (a[j] < a[min]) min = j;
        }

        if (i != min) std::swap( a[i], a[min] );
    }
}

template <size_t N>
void sorting( int ( &a )[N] )
{
    for (size_t i = 0; i < N; i++)
    {
        size_t min = i;

        for (size_t j = i + 1; j < N; j++)
        {
            if (a[j] < a[min]) min = j;
        }

        if (i != min) std::swap( a[i], a[min] );
    }
}

int main()
{
    int a[] = { 5, 4, 3, 2, 1 };

    for (const auto &item : a)
    {
        std::cout << item << ' ';
    }

    std::cout << '\n';

    sorting( a, sizeof( a ) / sizeof( *a ) );

    for (const auto &item : a)
    {
        std::cout << item << ' ';
    }

    std::cout << '\n';

    int b[] = { 5, 4, 3, 2, 1 };

    for (const auto &item : b)
    {
        std::cout << item << ' ';
    }

    std::cout << '\n';

    sorting( b );

    for (const auto &item : b)
    {
        std::cout << item << ' ';
    }

    std::cout << '\n';
}

The program output is
5 4 3 2 1
1 2 3 4 5
5 4 3 2 1
1 2 3 4 5

A: In general you should use std::array or std::vector instead of raw arrays (int[]). They also offer more functions that you might know from Java or other languages. Also checkout std::swap.
#include <iostream>
#include <vector>
void sorting(std::vector<int>& d)
{
    for (int i = 0; i < d.size(); i++)
    {
        for (int j = i + 1; j < d.size(); j++)
        {
            if (d[i] > d[j])
            {
                std::swap(d[i], d[j]);
               /*
                int temp = d[i];
                d[i] = d[j];
                d[j] = temp;
              */
            }
        }
    }
}

int main()
{
    std::vector<int> test = {5,1,4,3,2};
    sorting(test);
    for( auto const& elem : test )
    {
        std::cout << elem << " ";
    }
    std::cout << "\n";
    return EXIT_SUCCESS;
}


text:
Q: How to apply background-image to a column of table in Email template (outlook 2007) I have added a background-image to my column but it does not working in outlook 2007, How can I make the background-image appears in outlook 2007 clients and fill the td 100% and control it's positioning.
I have tried this:-

<v:rect xmlns:v="urn:schemas-microsoft-com:vml" fill="true" stroke="false">
   <v:fill type="tile" src="" />
   <v:textbox inset="0,0,0,0" style="v-text-anchor:bottom;">

        Newsletter du <xsl:value-of  select="$"/>

    </v:textbox>
   </v:rect>

but this is what I got

I want the image fill completely the td and thanks!

A: thank you.. but I tried already those answers and I found that outlook 2007 do not rendre the image that's inside the conditionnel comments so I delete the conditionnel comments MSO and it works .. problem solved thank you for the support all


text:
Q: How to include unofficial parts library in LeoCAD on Ubuntu? I want to include the unofficial parts library on LeoCAD. I'm on Ubuntu 20.04 and the path to "library.bin" is /snap/leocad/2/usr/share/leocad/. So, I must copy 'ldrawunf.zip' to /snap/leocad/2/usr/share/leocad/ (see the LeoCAD docs) and I run the following command on terminal:
sudo cp ~/Downloads/ldrawunf.zip /snap/leocad/2/usr/share/leocad/

but it returns me this error:
cp: cannot create regular file '/snap/leocad/2/usr/share/leocad/ldrawunf.zip': Read-only file system

Can someone help me?


text:
Q: QuickFIX rejects ExecutionReport due to missing Symbol field I have a FIX client written in nQuickfix.net which is connected to a FIX server.
I send a NewOrderSingle and it sends me an ExecutionReport message.
But the message is not passed to the application layer, it is rejected in the QuickFIX layer.
When I check the log files, it says Required field missing(55). 55 means Symbol field which is not a required field in Execution Report. So, why does it reject the ExecReport?


text:
Q: Angular UI Bootstrap typeahead-append-to I'm trying to append the Angular UI Typeahead control to a custom element in my HTML.  The docs state this:

typeahead-append-to $ (Default: null) - Should the typeahead popup be appended to an element instead of the parent element?

I cannot for the life of me figure what to set this value to!  I have tried all combinations of '#elementId' and '.elementClass' but still having no luck.
I can append to the body no probs with typeahead-append-to-body="true", but that's not what I want to do.
Help please!
Cheers

A:
(UPDATE: The user-selected answer to this question has since been updated with an addendum that includes the current, correct way to accomplish this.)

So, sorry to necropost, but I was looking at this today and thinking that the selected solution seemed strange, and banged my head against it for a few hours.  While the selected solution may have been true at one point, as of right now it is not at all necessary to reference a scope property that references a DOM object.  All you have to do is pass a selector (I tried an ID-- other selectors might get sketchy) but wrap it in single-quotes inside your double-quotes in the attribute.  So:
<input uib-typeahead="val for val in vals" typeahead-append-to="#myTargetElement" />

won't work but
<input uib-typeahead="val for val in vals" typeahead-append-to="'#myTargetElement'" />

will work.  Note the extra single-quotes: " ' #myTargetElement ' ".

A: OUTDATED SEE THE EDIT SECTION FOR LATEST APPROACH
The typeahead-append-to attribute expects you to reference an element in your controller and bind to that:
$scope.appendToElement = window.document.querySelector('body');

<input uib-typeahead="val for val in vals" typeahead-append-to="appendToElement" />

The code in the typeahead directive that reads the attribute and appends the element can be seen here
EDIT
The directive has been updated and will accept a selector string like so:
<input uib-typeahead="val for val in vals" typeahead-append-to="'#appendToElement'" />

A: My little directive:
angular.module('typeahead-append-to-selector', ['ui.bootstrap'])
angular.module('typeahead-append-to-selector').directive('typeaheadAppendToSelector', [function () {
    return {
        controller: ['$scope', '$attrs', function ($scope, $attrs) {
            $scope.typeaheadAppendTo = document.querySelector($attrs.typeaheadAppendToSelector);
        }]
    }
}])

then add these attrs to the input:
typeahead-append-to="typeaheadAppendTo" typeahead-append-to-selector="#appendToThis"

Hope that helps someone


text:
Q: Angular 2 Directive implementing ControlValueAccessor doesn't update 'touched' property on change I'm trying to create my own Angular 2 Directive for Jquery UI Datepicker. I've seen some different approaches on the internet and in SO as well, but no one achieves the goal that I want to. So this is the code that I have so far:
import {Directive, ElementRef, Input, forwardRef} from '@angular/core';
import {ControlValueAccessor, NG_VALUE_ACCESSOR} from "@angular/forms";

declare  var $:any;

@Directive({
  selector: '[date-picker]',
  providers: [{
    provide: NG_VALUE_ACCESSOR,useExisting:
      forwardRef(() => DatePickerDirective),
    multi: true
  }]
})
export class DatePickerDirective implements ControlValueAccessor {
  private value: string;

  @Input('changeMonth') changeMonth:boolean = true;
  @Input('changeYear') changeYear:boolean = true;

  constructor(private el: ElementRef) {

  }

  ngAfterViewInit(){
    $(this.el.nativeElement).datepicker({
      changeMonth: this.changeMonth,
      yearRange: "1:100",
      changeYear: this.changeYear
    }).on('change', e => this.onChange(e.target.value));
  }

  onChange: Function = () => {};

  onTouched: Function = () => {};

  writeValue(val: string) : void {
    this.value = val;
  }

  registerOnChange(fn: Function): void {
    this.onChange = fn;
  }

  registerOnTouched(fn: Function): void {
    this.onTouched = fn;
  }
}

What is happening is that even when I select a date (picker) or type it directly on input field, it isn't updating "touched" property.
Do you have any ideas for fixing it?

A: For those who eventually have the same problem, I figured out a way to manage it, as you can below:
import {Directive, ElementRef, Input, forwardRef} from '@angular/core';
import {ControlValueAccessor, NG_VALUE_ACCESSOR} from "@angular/forms";

declare  var $:any;

export const CUSTOM_INPUT_DATE_PICKER_CONTROL_VALUE_ACCESSOR: any = {
  provide: NG_VALUE_ACCESSOR,
  useExisting: forwardRef(() => DatePickerDirective),
  multi: true
};

@Directive({
  selector: '[date-picker]',
  host: {'(blur)': 'onTouched($event)'},
  providers: [CUSTOM_INPUT_DATE_PICKER_CONTROL_VALUE_ACCESSOR]
})
export class DatePickerDirective implements ControlValueAccessor {
  private innerValue: string;

  @Input('changeMonth') changeMonth:boolean = true;
  @Input('changeYear') changeYear:boolean = true;

  constructor(private el: ElementRef) {
    $(this.el.nativeElement).datepicker({
      changeMonth: true,
      changeYear: true,
      dateFormat: 'dd/mm/yy'
    }).on('change', e => this.onChange(e.target.value));
  }

  public onChange: any = (_) => { /*Empty*/ }
  public onTouched: any = () => { /*Empty*/ }

  get value(): any {
    return this.innerValue;
  };

  //set accessor including call the onchange callback
  set value(v: any) {
    if (v !== this.innerValue) {
      this.innerValue = v;
      this.onChange(v);
    }
  }

  writeValue(val: string) : void {
    this.innerValue = val;
  }

  registerOnChange(fn: any): void {
    this.onChange = fn;
  }

  registerOnTouched(fn: any): void {
    this.onTouched = fn;
  }
}


text:
Q: Subtracting rasters using gdal_calculate command? How do I subtract two raster using gdal_calculate command?
Note that gdal_calc is different from gdal_calculate.py.
The rasters I am using have different dimensions.

A: Just worked out how to do this with gdal_calc.py - to get around issues with files with different dimensions (and resolutions) you can use a VRT.
gdalbuildvrt -separate combined.vrt dem1.tif dem2.tif
gdal_calc.py -A combined.vrt -A_band=1 -B combined.vrt -B_band=2 --calc="A-B" --outfile diff.tif

A: The basic syntax is similar to gdal_calc.py
i.e.
gdal_calculate -a a.tif -b b.tif --calc="a - b" --outfile c.tif

If your input rasters are unsigned (i.e Byte or UInt16 etc) and the result may contain negative values, you need to specifically cast to a signed type :
gdal_calculate -a a.tif -b b.tif --calc="Int16(a) - b" --outfile c.tif

If your rasters are multiband, you need to specify the band (unless you want multiband output)
gdal_calculate -a a.tif -b b.tif --calc="Int16(a[0]) - b[0]" --outfile c.tif

If your rasters have defined NoData values, use the --nodata flag. You don't need to specify the NoData values as the script will determine them from the rasters:
gdal_calculate --nodata -a a.tif -b b.tif --calc="Int16(a) - b" --outfile c.tif

A: On the help page an example is given:
gdal_calc.py -A input1.tif -B input2.tif --outfile=result.tif --calc="A+B"

This is addition, but subtraction is just as easy:
gdal_calc.py -A input1.tif -B input2.tif --outfile=result.tif --calc="A-B"


text:
Q: WPF and paypal integration I'm asking this after being swamped by the amount of info etc on integrating my app and can't work out the best/appropriate solution. Paypal seem to have supplied several options.
We have a WPF app, which takes customer orders etc. We want to use PayPal to handle card payments and it needs to be PCI Compliant (Level A). What is the best/appropriate solution for this. The idea is to use a Browser control to pass through the amount/customer info and take the customers card details over the phone, so the only thing the business user needs to enter is the card info.
Thanks for any help.

A: As i posted, this is the answer (it seems) is the pay pal .net sdk, link