text:
Q: .NET LINQ to Entities base where clause for generic Type I am using Entity Framework to access my domain models, all of which implement an interface (IPublishable) that specifies properties to indicate whether an item has been published.
When accessing items from the front end I always want to filter out unpublished items. So, every time I write a query I'm doing something similar to this (where the following DbSets Objects1 and Objects2 both implement IPublishable
context.Objects1.Where( x => x.IsPublished ...).OrderBy( x => x.Id).ToList()
context.Objects2.Where( x => x.IsPublished ...).First()

What would be ideal is if I could inject the common Where() clause into all my queries within my web app OR if there was a way to write an extension method which I could include in each query.
I tried to create the extension method for all linq queries
public static IEnumerable<T> FrontEnd<T>(this DbSet<T> dbSet) where T : class {
  return dbSet.Cast<IPublishable>().Where( x => x.IsPublished ...).Cast<T>();
}

And use like this...
context.Objects1.FrontEnd().Where( x => ...).OrderBy(...

However I get the error "LINQ to Entities only supports casting EDM primitive or enumeration types"
I'm new to EF, so any information would be a great help.
Thanks

A: UPDATED as per comments - this works
public static IQueryable<T> FrontEnd<T>(this DbSet<T> dbSet)
    where T : class, IPublishable
{
    return dbSet.Where(x => x.IsPublished);
}

and can be used like this:
context.Objects1.FrontEnd().Where( x => ...).OrderBy(...

You can try either of these options:
public static IQueryable<dynamic> FrontEnd(this DbSet<dynamic> dbSet)
{
    return dbSet.Where(x => (x as IPublishable).IsPublished);
}

or
public static IQueryable<T> FrontEnd<T>(this DbSet<T> dbSet)
    where T : class, IPublishable
{
    return dbSet.Where(x => x.IsPublished);
}

note:
the first option uses dynamic so is slower
with the second option you have to specify the type in the call to FrontEnd()
e.g.
context.Objects1.FrontEnd<Objects1>().Where( x => ...).OrderBy(...

A: I think LINQ to Entities does not know how to match the cast operator to SQL request. As a suggestion, you could try something like that:
IEnumerable<IPublishable> ReadPublishable(Expression<Func<DomainModelType, bool>> condition)

The expression act as a predicate. So you pass to the ReadPublishable function a predicate that filters the IPublishable objects you need. I tried successfully but only on simple predicates so,  I do not know whether that works if you make use of "is" or "as" operators.


text:
Q: What's the right way to build a asset source map in JavaScript/React? I need to create a source map for a list of SVG assets in my app where each asset has a set of properties. Example:
const myAssetMap = {
    dog: {
        name: Dog,
        svg: Dog.svg,
        bkgColor: '#EEE',
        textColor: '#FFF',
    },
    cat: {
        name: Cat,
        svg: CatFile.svg,
        bkgColor: '#EEE',
        textColor: '#FFF',
    },
    ....
}

Later, I can then find the desired properties like so:
const getMyParams = (name, type) => {
    return myAssetMap[name][type];
};

Is this the right way to do this? Would love to learn if there is a better way.

A: I guess there is no right answer, but you approach looks reasonable :)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Codeigniter Post keeps adding up Could not think of a a better title for this question. Anyways here is the problem.
I have a simple contact form. If the user goes to that page and enters wrong info (no email or message) then everything seems to work. I get the validation errors. But if they put the wrong information in say 6 times in a row, then click the browsers "back" button. They do not go to the previous page. They have to click 6 or 7 times to return to previous page. Am I doing something wrong?
class Contact extends CI_Controller {

    function index()
    {

        $data['title'] = "Contact Us";
        $data['main'] = 'contact';
        $this->form_validation->set_rules('email', 'Email', 'required|valid_email');
        $this->form_validation->set_rules('message','Message','required');

        if ($this->form_validation->run() == FALSE)
        {
            $this->load->vars($data);
            $this->load->view('template');
        }
        else
        {
             $contactdata['username'] = $this->input->post('email');
             $contactdata['title'] = "Contact Success";
             $contactdata['main'] = 'contactsuccess';
             $this->load->vars($contactdata);
             $this->load->view('template');
        }
}

A: you can check the request if it is come from a post request
class Contact extends CI_Controller {

    function index()
    {

        $data['title'] = "Contact Us";
        $data['main'] = 'contact';

        if($this->input->post()){

               $this->form_validation->set_rules('email', 'Email', 'required|valid_email');
               $this->form_validation->set_rules('message','Message','required');

              if ($this->form_validation->run() == FALSE)
              {
                  $this->load->vars($data);

              }
              else
              {
                 $contactdata['username'] = $this->input->post('email');
                 $contactdata['title'] = "Contact Success";
                 $contactdata['main'] = 'contactsuccess';
                 $this->load->vars($contactdata);
             }
        }
        else{
                 $this->load->vars($data);
        }

        $this->load->view('template');

  }


text:
Q: How to mosaic Landsat MSS data in R? I am trying to mosaic Landsat MSS scenes using the mosaic function in the R package raster. To explain the problem, I have considered here the four following TIF files, which I want to mosaic:

*

*LM03_L1TP_147044_19800220_20200906_02_T2_B4.TIF

*LM03_L1TP_147045_19800202_20200905_02_T2_B4.TIF

*LM03_L1TP_148044_19800221_20200905_02_T2_B4.TIF

*LM03_L1TP_148045_19800221_20200905_02_T2_B4.TIF

All the files are downloaded from the Earthexplorer portal of USGS. From the names of the above files, it can be seen that the tiles are situated next to each other, as their WRS paths and rows are 147, 148 and 44, 45, respectively. Also, the dates the images are taken are close to each other. I have tried to mosaic the scenes using the following R code:
require(raster)

r1 = raster("LM03_L1TP_147044_19800220_20200906_02_T2_B4.TIF")
r2 = raster("LM03_L1TP_147045_19800202_20200905_02_T2_B4.TIF")
r3 = raster("LM03_L1TP_148044_19800221_20200905_02_T2_B4.TIF")
r4 = raster("LM03_L1TP_148045_19800221_20200905_02_T2_B4.TIF")

r5 = mosaic(r1, r2, r3, r4, fun = mean)

However, I get the error:
Error in compareRaster(x, extent = FALSE, rowcol = FALSE, orig = TRUE,  :
  different CRS

Indeed, when I inquired using the function crs, I got the following:
> crs(r1)
CRS arguments:
 +proj=utm +zone=46 +datum=WGS84 +units=m +no_defs
> crs(r2)
CRS arguments:
 +proj=utm +zone=46 +datum=WGS84 +units=m +no_defs
> crs(r3)
CRS arguments:
 +proj=utm +zone=45 +datum=WGS84 +units=m +no_defs
> crs(r4)
CRS arguments:
 +proj=utm +zone=45 +datum=WGS84 +units=m +no_defs

Here I found the zone argument different for the scenes. I wonder what mistake I have made, and how to properly mosaic the scenes using the raster package in R.


text:
Q: Adding space in javascript timer I have script below:

it shows my timer like:
4w:2d:14h:10m:26s
What I want is to add space before and after : so can be like:
4w : 2d : 14h : 10m : 26s
how do i do that?

A: That is what CSS is for.
With it you can dynamically control its formatting based on portrait/landscape etc.

.days::before, .hour::before, .mini::before, .sec::before {
  content: ':';
  padding: 0 6px 0 3px;
}
4w
2d
14h
10m
26s

If you have a wrapper for those span's, you can do this

.datetime span:not(:first-child)::before {
  content: ':';
  padding: 0 6px 0 3px;
}

  4w
  2d
  14h
  10m
  26s

And add the letters
If you have a wrapper for those span's, you can do this

.datetime span:not(:first-child)::before {
  content: ':';
  padding: 0 6px 0 3px;
}
.week::after {
  content: 'w';
}
.days::after {
  content: 'd';
}
.hour::after {
  content: 'h';
}
.mini::after {
  content: 'm';
}
.sec::after {
  content: 's';
}

  4
  2
  14
  10
  26

A: Change you content adding section code with  :
var $this = $(this).html(event.strftime(''
       + '%-ww : '
       + '%-dd : '
       + '%Hh : '
       + '%Mm : '
       + '%Ss'));


text:
Q: Format restrictions for cell in Excel I want a cell to only have a specified format, e.g. "01-02-03", meaning "double digit dash double digit dash double digit".
I a user tries to enter something into the cell, an error should occurr telling him if the entered value is wrong.
Is this possible without creating a macro or complex VBA-scripts?

A: Here's a validation rule that uses the following conditions:

*

*There has to be 2 dashes, in the exact same positions as shown.

*With the exception of the dashes, the value contains only numbers.

Setup:
Step1: Select your cell and create a validation rule for it.
Step2: Choose Custom and enter the formula below (replace A1 with the cell you're referring to in your question).
=AND(ISNUMBER(MID(A1,1,2)+0), ISNUMBER(MID(A1,4,2)+0), ISNUMBER(MID(A1,7,2)+0), MID(A1,3,1)="-", MID(A1,6,1)="-")

Using this validation formula, the following sample entries will show the error "The value you entered is not valid" after the user de-selects the cell or presses Enter after typing the value.
ad-24-24
56-a6-34
456-234
123456
67-7890

A: You can use a custom format for a 6 digit number: 00-00-00, and then use Data Validation to limit text length to 6. It will still allow non-numeric characters unfortunately.
Alternatively you use use Whole Number Data Validation between 100000 and 999999, but obviously this wouldn't allow the number to begin with a 0.


text:
Q: Can you run training and evalutaion process from a single anaconda prompt? I am having trouble evaluating my training process during training a  Tensorflow2 Custom Object Detector. After reading several issues related to this problem I found that evaluation and training should be treated as two separate processes therefore I should use a new anaconda prompt for starting the evaluation job.
I am training on the ssd_mobilenetv2 640x640 version. My pipeline configuration:
model {
  ssd {
    num_classes: 6
    image_resizer {
      fixed_shape_resizer {
        height: 640
        width: 640
      }
    }
    feature_extractor {
      type: "ssd_mobilenet_v2_fpn_keras"
      depth_multiplier: 1.0
      min_depth: 16
      conv_hyperparams {
        regularizer {
          l2_regularizer {
            weight: 3.9999998989515007e-05
          }
        }
        initializer {
          random_normal_initializer {
            mean: 0.0
            stddev: 0.009999999776482582
          }
        }
        activation: RELU_6
        batch_norm {
          decay: 0.996999979019165
          scale: true
          epsilon: 0.0010000000474974513
        }
      }
      use_depthwise: true
      override_base_feature_extractor_hyperparams: true
      fpn {
        min_level: 3
        max_level: 7
        additional_layer_depth: 128
      }
    }
    box_coder {
      faster_rcnn_box_coder {
        y_scale: 10.0
        x_scale: 10.0
        height_scale: 5.0
        width_scale: 5.0
      }
    }
    matcher {
      argmax_matcher {
        matched_threshold: 0.5
        unmatched_threshold: 0.5
        ignore_thresholds: false
        negatives_lower_than_unmatched: true
        force_match_for_each_row: true
        use_matmul_gather: true
      }
    }
    similarity_calculator {
      iou_similarity {
      }
    }
    box_predictor {
      weight_shared_convolutional_box_predictor {
        conv_hyperparams {
          regularizer {
            l2_regularizer {
              weight: 3.9999998989515007e-05
            }
          }
          initializer {
            random_normal_initializer {
              mean: 0.0
              stddev: 0.009999999776482582
            }
          }
          activation: RELU_6
          batch_norm {
            decay: 0.996999979019165
            scale: true
            epsilon: 0.0010000000474974513
          }
        }
        depth: 128
        num_layers_before_predictor: 4
        kernel_size: 3
        class_prediction_bias_init: -4.599999904632568
        share_prediction_tower: true
        use_depthwise: true
      }
    }
    anchor_generator {
      multiscale_anchor_generator {
        min_level: 3
        max_level: 7
        anchor_scale: 4.0
        aspect_ratios: 1.0
        aspect_ratios: 2.0
        aspect_ratios: 0.5
        scales_per_octave: 2
      }
    }
    post_processing {
      batch_non_max_suppression {
        score_threshold: 9.99999993922529e-09
        iou_threshold: 0.6000000238418579
        max_detections_per_class: 100
        max_total_detections: 100
        use_static_shapes: false
      }
      score_converter: SIGMOID
    }
    normalize_loss_by_num_matches: true
    loss {
      localization_loss {
        weighted_smooth_l1 {
        }
      }
      classification_loss {
        weighted_sigmoid_focal {
          gamma: 2.0
          alpha: 0.25
        }
      }
      classification_weight: 1.0
      localization_weight: 1.0
    }
    encode_background_as_zeros: true
    normalize_loc_loss_by_codesize: true
    inplace_batchnorm_update: true
    freeze_batchnorm: false
  }
}
train_config {
  batch_size: 4
  data_augmentation_options {
    random_horizontal_flip {
    }
  }
  #data_augmentation_options {
    #random_crop_image {
      #min_object_covered: 0.0
      #min_aspect_ratio: 0.75
      #max_aspect_ratio: 3.0
      #min_area: 0.75
      #max_area: 1.0
      #overlap_thresh: 0.0
    #}
  #}
  optimizer {
    momentum_optimizer {
      learning_rate {
        cosine_decay_learning_rate {
          learning_rate_base: 0.04999999821186066
          total_steps: 50000
          warmup_learning_rate: 0.0026666000485420227
          warmup_steps: 600
        }
      }
      momentum_optimizer_value: 0.8999999761581421
    }
    use_moving_average: false
  }
  fine_tune_checkpoint: "pre-trained-models\ssd_mobilenet_v2_fpnlite_640x640_coco17_tpu-8\checkpoint\ckpt-0"
  num_steps: 50000
  startup_delay_steps: 0.0
  replicas_to_aggregate: 8
  max_number_of_boxes: 100
  unpad_groundtruth_tensors: false
  fine_tune_checkpoint_type: "detection"
  fine_tune_checkpoint_version: V2
  from_detection_checkpoint: true
}
train_input_reader {
  label_map_path: "annotations/label_map.pbtxt"
  tf_record_input_reader {
    input_path: "data/train.record"
  }

}
eval_config {
  metrics_set: "coco_detection_metrics"
  use_moving_averages: false
}
eval_input_reader {
  label_map_path: "annotations/label_map.pbtxt"
  shuffle: false
  num_epochs: 1
  tf_record_input_reader {
    input_path: "data/test.record"
  }
}

I have started the training with the command:
python model_main_tf2.py --model_dir=models/my_ssd2_3/ --pipeline_config_path=models/my_ssd2_3/pipeline.config --sample_1_of_n_eval_examples 1 --logtostderr

I was hoping that setting the number of evaluation examples will have an effect of starting the evaluation job. In any case I tried running the evaluation in a different terminal window with : python model_main_tf2.py --model_dir=models/my_ssd2_3 --pipeline_config_path=models/my_ssd2_3/pipeline.config --checkpoint_dir=models/my_ssd2_3/ --alsologtostderr
As soon as starting the evaluation the training job crashes with this error:error
The problem I think that I do not have the sufficient hardware:

*

*8GB RAM

*NVIDIDA GTX960M (2GB RAM)

Could it be a problem that all the input images that I use are 3000x3000, therefore the preprocesser has to load too many information? If so, is there any way to work around it? I would not want to resize all the images before generating TF record file, because I would have to re-label all the images. I clearly lack the insight of how the memory is being allocated during the start of the training process so some details would be much appreciated.
A second question is that during monitoring the training on tensorboard the images are displayed with various brightness I tried changing in the model_lib_v2.py file the 627 line to:
data= (features[fields.InputDataFields.image]-np.min(features[fields.InputDataFields.image]))/(np.max(features[fields.InputDataFields.image])-np.min(features[fields.InputDataFields.image]))
,

According to this solution:https://github.com/tensorflow/models/issues/9115
Without any luck. Is there a solution to this problem? Also it would be nice if I could monitor there the bounding boxes the modell proposes. Thank you.

A: With some changes to the train_loop function in model_lib.py, you can alternate between training and evaluation in the same application. See the example below.
From what I understand, the Tensorflow Object Detection API is developed with a focus on distributed learning and if you were using mulitple GPUs/TPUs then you could have some devices doing training and other devices doing evaluation. So I suspect the way model_lib.py is implemented currently does not fully support doing training and evaluation on the same device.
I'm not certain the root cause of the error you are seeing, typically I have seen Tensorflow throw OOM errors when there is a memory issue. It may be that how Tensorflow is using CUDA does not support two applications using the same device.
Regarding your second question, I followed the advice here on the same thread and this worked for me. Duplicating the code in the third code block below.  Initially, this did not appear to work for me because I naively updated the file in the Object Detection repository I created, but your application may be using the Object Detection API that is installed in your site-libs, so I would recommend confirming that the file you are changing is the same one being loaded in your import statements.
--
This is outside of the training loop
  ##Set up evaluation data and writer
  eval_config = configs['eval_config']
  eval_input_configs = configs['eval_input_configs']
  eval_input_config = eval_input_configs[0]
  eval_input = strategy.experimental_distribute_dataset(
    inputs.eval_input(
        eval_config=eval_config,
        eval_input_config=eval_input_config,
        model_config=model_config,
        model=detection_model))

  summary_writer_eval = tf.compat.v2.summary.create_file_writer(os.path.join(model_dir, 'eval', eval_input_config.name))

This is the modified train/evaluation loop. The evaluation happens near the end.
for _ in range(global_step.value(), train_steps, num_steps_per_iteration):

  tf.logging.info('Performing Training')
  with summary_writer_train.as_default():
    with tf.compat.v2.summary.record_if(lambda: global_step % num_steps_per_iteration == 0):

      losses_dict = _dist_train_step(train_input_iter)

      time_taken = time.time() - last_step_time
      last_step_time = time.time()
      steps_per_sec = num_steps_per_iteration * 1.0 / time_taken

      tf.compat.v2.summary.scalar(
          'steps_per_sec', steps_per_sec, step=global_step)

      steps_per_sec_list.append(steps_per_sec)

      logged_dict = losses_dict.copy()
      logged_dict['learning_rate'] = learning_rate_fn()

      for key, val in logged_dict.items():
        tf.compat.v2.summary.scalar(key, val, step=global_step)

      if global_step.value() - logged_step >= 0:
        logged_dict_np = {name: value.numpy() for name, value in
                          logged_dict.items()}
        tf.logging.info(
            'Step {} per-step time {:.3f}s'.format(
                global_step.value(), time_taken / num_steps_per_iteration))
        tf.logging.info(pprint.pformat(logged_dict_np, width=40))
        print_gpu_memory_usage()
        logged_step = global_step.value()

      if ((int(global_step.value()) - checkpointed_step) >=
          checkpoint_every_n):
        manager.save()
        checkpointed_step = int(global_step.value())

  tf.logging.info('Performing Evaluation')
  with summary_writer_eval.as_default():
    eager_eval_loop(
        detection_model,
        configs,
        eval_input,
        use_tpu=use_tpu,
        global_step=global_step,
        )

Fixing image rendering in TensorBoard
if record_summaries:
    imgs = features[fields.InputDataFields.image][:3]
    imgs = tf.div(tf.subtract(imgs, tf.reduce_min(imgs)), tf.subtract(tf.reduce_max(imgs), tf.reduce_min(imgs)))
    tf.compat.v2.summary.image(name='train_input_images', step=global_step, data=imgs, max_outputs=3)


text:
Q: Scala-Lift project in Eclipse Scala IDE errors I installed Scala IDE for Eclipse, and it seems to be working okay. So now I'm trying to import a Lift project (specifically -- autogenerated Lift project from Stax application platform), and now I'm having four errors at my workspace:
value net is not a member of package <root> Boot.scala /rss2lj/src/scala/bootstrap/liftweb line [3..6] Scala Problem

At lines:
import _root_.net.liftweb.util._
import _root_.net.liftweb.http._
import _root_.net.liftweb.sitemap._
import _root_.net.liftweb.sitemap.Loc._

Could anyone please help me out with it?
UPD: I found a discussion with solution for maven-based projects, but the project, I'm trying to work with is not maven-based.
I got an answer here, but the new error occured on the same lines:
error while loading Helpers, Scala signature Helpers has wrong version
 expected: 5.0
 found: 4.1 in /home/gleontiev/workspace/rss2lj/webapp/WEB-INF/lib/
lift-util-1.0.jar(net/liftweb/util/Helpers.class)

error while loading LiftRules, Scala signature LiftRules has wrong
version
 expected: 5.0
 found: 4.1 in /home/gleontiev/workspace/rss2lj/webapp/WEB-INF/lib/
lift-webkit-1.0.jar(net/liftweb/http/LiftRules.class)

error while loading Loc, Scala signature Loc has wrong version
 expected: 5.0
 found: 4.1 in /home/gleontiev/workspace/rss2lj/webapp/WEB-INF/lib/
lift-webkit-1.0.jar(net/liftweb/sitemap/Loc.class)

error while loading Menu, Scala signature Menu has wrong version
 expected: 5.0
 found: 4.1 in /home/gleontiev/workspace/rss2lj/webapp/WEB-INF/lib/
lift-webkit-1.0.jar(net/liftweb/sitemap/Menu.class)

A: The best place to ask questions like this is on the Scala IDE user mailing list.


text:
Q: jquery - reset button with `change` radio event I using radio buttons and need to listen on the change event like this :
   <input type='radio' name='test' value='1' checked /> radio1
   <input type='radio' name='test' value='2'/> radio2
   ....
   <button type='reset' /> Reset </button >

And In js:
 $('.disp_method input[type=radio]').each(function () {
    $(this).on('change', function () {
        if($(this).val() == 1) {
        alert("change to 1")
        } else if ($(this).val() == 2) {
         alert('change to 2')
        }
    })
})

When I click on button , the above js function work fine ,
but when I click radio2 and click reset button ,the radio can be reset to original state (radio1 selected) but the above event listening not work,it seem that can not listen change event when click reset
Please tell me what wrong?
Thanks in advance


text:
Q: How can I disable the responsive behaviour in Bootstrap 4? How can I disable the responsive behaviour in Bootstrap 4, while maintaining the styles? I want users that access the website in the mobile phone to have the same website as the desktop version and zoom in and zoom out with finger gestures. How can I do it?

A: While Bootstrap is not really made to be unresponsive, you can achieve something like that by altering the viewport meta-tag.
<meta name="viewport" content="initial-scale=0.1">
This will set the initial scale at 10% of the original scale.
Also see https://www.w3.org/TR/css-device-adapt-1/#translate-meta-to-at-viewport for more.

A: so i would suggest that you just put everything in the bootstrap grid and design it for mobile view only. so instead of using multiple classes for multiple screen sizes like "col-4 col-md-3" or flexible like "col" just use "col-n" classes only, so on mobile it'll look like you want it to look (also you would have to zoom in and out if you place enough content in the cols because with col-n you tell bootstrap to use n/12 of the available width on smallest screen size and up) and on desktop it'll show its full beauty without the need to zoom.
i hope this will help :)


text:
Q: Is it possible to upgrade Oracle 8i to 12c? We have an old server running Oracle 8i.
Is it going to be possible to directly update it to something newer like Oracle 12c, or would that require a complete uninstall and re-install?
If we had to completely uninstall and re-install, is it then a case of importing the database dump from Oracle 8i and it will be converted, or is that also a manual task?
Update
Thanks for everyones input. I have checked with our application vendor (the ones who originally installed Oracle 8i for us around 10 years ago) and their application that we use does work with Oracle 12c but they are not willing to do the update for us.
They have basically said that we should do the update, preferably on a new server and at that point they would be willing to get involved to check their application out using the new database version etc.
Is there some way to find Oracle experts capable of doing this job (preferably UK based)? I'm pretty new to Oracle (past experience is mainly Microsoft SQL Server), day to day management/security, scripting etc. is ok but I'd rather have someone in who has done this (many times?) before.
Thanks again!

A: There is no in-place upgrade possible but the existing exp utility is still supported for importing dmp files.
Some of the issues you need to research are:

*

*I have taken an export from an 8i database and imported it into an 11g with no issues. Importing into 12 should not be a problem but planning is everything!

*will you use the same character set?  Often organizations start with western only and need to use UTF16 for more compatibility with other languages.

*do yourself a favour and do an install on a new machine with new hardware.  12 requires more of everything, memory, hard drive.

*many 8i parameters are not supported so you need to establish if there are any custom settings that you need equivalents for

Of course this would need to be tested.

A: One option would be to use something like Erwin or Toad to reverse engineer the schema, create a new 11g/12c database with all of the tablespaces that you need, generate a script that would create all of the schemas and their types and tables without constraints, create the schemas and tables, create a db link to the old database from the new database, do insert into for each table, generate and run a script to create all of the constraints, views and stored procedures. You will want to script it and run the conversion more than once while you work out the details. You also want to check your stored procedures for any code for set transaction commands. As you probably know rollback segments went away with 9i, thus you can no longer set certain code to use a particular rollback segment. You will also be switching from dictionary managed table spaces to locally managed table spaces. Which means that you want to ignore any segment information in your tables. Just use automatic storage for your segments and let the database track extent size and make sure that pctincrease is set to 0. In addition check your block size 8k is usually good for most applications.
If you have a lot of data, you can split the inserts into multiple scripts that run from different sessions, thus you can do it in parallel. While you can do an export/import you don't want to import the data dictionary from 8i and you don't want to keep the old extent sizes.


text:
Q: How to add sidebar to kivy android app? I want a side bar for showing account details like: user name, profile etc. so i made an  rule in my kv file below how can i get this and what i did to get this this is also below: thanks in advance and rather then this program tips are always welcome.
this is my main.py
import kivy
kivy.require('1.9.0')

from kivy.app import App
from kivy.uix.floatlayout import FloatLayout
from kivy.animation import Animation

class MainScreen(FloatLayout):

    def menu_action(self):
        self.add_widget(SideBar())

class SideBar(FloatLayout):

    def on_touch_down(self, touch):
        if self.collide_point(*touch.pos):
            print('inside side')
        else:
            print('outside side')

class testApp(App):

    def build(self):
        return MainScreen()

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

this is my kv file test.kv
<MainScreen>:
    canvas.before:
        Rectangle:
            size: root.size
            source: 'static/images/back.jpg'
    ActionBar:
        pos_hint: {'top':1}
        background_color: 0, 0, 0, .1
        ActionView:
            use_separator: True
            ActionPrevious:
                app_icon: 'static/images/account.png'
                title: 'Account Maintainer'
                color: 0, 0, 0, 0
                with_previous: False
            ActionButton:
                id: menu
                icon: 'static/images/menu.png'
                on_press: root.menu_action()

<SideBar>:
    canvas.before:
        Color:
            rgba: 0, 0, 0, .6
        Rectangle:
            size: self.size
            pos: self.pos
    size_hint: (.8, 1)
    pos_hint: {'right': 1}

on clicking menu button a sidebar open when i agan click on menu button a new side bar open
  i want to disable it. How can i get this? and tell me if didn't
  understand//

A: If I understand correctly, you only want a sidebar to open on the first time the menu button is clicked. There are a couple ways to do this. One is to just keep track of whether a sidebar is already opened, and don't open a second. This can be done by changing your MainScreen class as below:
class MainScreen(FloatLayout):
    def __init__(self):
        super(MainScreen, self).__init__()
        self.has_sidebar = False

    def menu_action(self):
        if not self.has_sidebar:
            print('adding sidebar')
            self.add_widget(SideBar())
            self.has_sidebar = True
        else:
            print('not adding sidebar')

Another way is to disable the button when it has been clicked. In that case, your MainScreen class would look like:
class MainScreen(FloatLayout):
    def __init__(self):
        super(MainScreen, self).__init__()

    def menu_action(self):
        print('adding sidebar')
        self.add_widget(SideBar())
        self.ids['menu'].disabled = True


text:
Q: How to add binary resources I have a project that requires a bunch of graphic files in the executable. Since there is no file system at the target I cant just use the fopen function. One way would converting the file content to a C source code that contains the variable definition like this
unsigned char file1_content[] = {
   0x01, 0x02, ...
};

It's cumbersome to build such files even with a converter tool.
Is there any way to add binary files to the rdata section while specifying a variable name for each file? I think about using the linker script for this but didn't find a way.

A: It's not particularly cumbersome with a tool, and that's the classic solution. Search for "bin2c" to find some.
You simply need to include these "asset-building" steps in your build process, i.e. call the tool from the Makefile. This also means that the tool is only run if the source data has changed, which is nice.
At least the GNU linker (LD) seems capable of placing files in the sections of the output file (see the Section Placement documentation, like so:
.data : { afile.o bfile.o cfile.o }

But this sounds quite cumbersome, and it needs you to think about the sections of your executable file which often a bit too low-level. Also, it seems to require the input(s) to be object files, which kind of makes the problem circular since a generic binary asset isn't a linker-compatible object file.
I would recommend going with the bin2c approach.

A: You may use linker option --format along with -Wl, to pass it to linker, like:
gcc -Wl,--format=binary -Wl,myfile.bin -Wl,--format=default

Last setting format to default allows you to switch linker back to standard input format.
You may access your binary resources from sources via simple _binary_myfile_bin_start assembler symbol (for myfile.bin, for xxx.yyy it will be _binary_xxx_yyy_start and _binary_xxx_yyy_end) like:
extern uint8_t data[] asm("_binary_myfile_bin_start");

And next use data. It is much better then do objcopy by yourself, or use resource hacking.
UPD: Expanding with a little example -- main outputs first four bytes of its own object file:
#include "stdio.h"
#include "stdint.h"

extern uint8_t data[] asm("_binary_main_o_start");

int
main(void)
{
  fprintf(stdout, "0x%x, 0x%x, 0x%x, 0x%x\n", data[0], data[1], data[2], data[3]);
  return 0;
}

Now compile an run:
$ gcc -o main.o -c main.c
$ gcc -o main main.o -Wl,--format=binary -Wl,main.o -Wl,--format=default
$ ./main
0x7f, 0x45, 0x4c, 0x46


text:
Q: In which cases is this algorithm ineffective? It's about parallel matrix vector multiplication with multiple threads. The lines of the matrix will be "split" into blocks of as similar size as possible so each thread as about the same amount of lines to multiply, so the program is as fast as possible.
So I have a matrix a, number of threads t, block of lines for each thread s, the individual threads i and start of the block and end of the block which the thread should go through.
I have this algorithm:
01: int s = (int) Math.ceil((double) a.length / t);
02: for (int i = 0; i < t; i++) {
03:   start = i * s;
04:   end = Math.min((i + 1) * s, a.length);
05:   // ... create worker and threads
06: }

a.length is the number of lines of which the matrix consists.
Now my question is in which cases this algorithm proves to be ineffective... because apart from the obvious one (no threads obviously produces an error because of dividing by 0), I only have that there is one thread with 1 line and the other 7 threads with 8 lines if I have 57 lines and 8 threads... but it wouldnt be more effective if i had 7 threads with 7 lines and one thread with 8 lines would it?


text:
Q: Show that there exists $x \in H$ with $\|x\|=1$ and $|\langle Tx,x\rangle |=\|T\|$ Let $H$ be a Hilbert space and let $T:H\to H$ be a bounded self-adjoint linear operator.

Show that there exists $x \in H$ with $\|x\|=1$ and $|\langle Tx,x\rangle |=\|T\|$.

I know that $\|T\|=\sup\{|\langle Tx,x\rangle| : \|x\|=1\}$. I think the completeness can produce such $x$, but I don't know how to prove this.

A: This is not true. Consider for instance $T\in B(\ell^2(\mathbb N))$ given by
$$
Tx=(x_1/2, 2x_2/3, 3x_3/4,\ldots).
$$
As $Te_n=\tfrac{n}{n+1}\,e_n$, we have that $\|T\|=1$. But for any nonzero $x$ with $\|x\|=1$ we have
$$
|\langle Tx,x\rangle|=\sum_n\tfrac{n}{n+1}\,|x_n|^2<\sum_n|x_n|^2=1.
$$
So no such maximum exists.
When $T$ is compact, though, the answer is affirmative. For a selfadjoint compact $T$, we have via the Spectral Theorem that
$$
T=\sum_n\lambda_nP_n,
$$
where $\lambda_n\in\mathbb R$ for all $n$, and $\lambda_n\searrow0$. In this case $\|T\|=\max_n|\lambda_n|$. If we take $|\lambda_j|=\|T\|$, then put $x$ with $P_jx=x$ and $\|x\|=1$, and
$$
|\langle Tx,x\rangle|=|\lambda_j|=\|T\|.
$$


text:
Q: Converting a Json File to a Map using Gson I currently have the following Json File
    [
  {
    "documentId": "138",
    "results": [
      {
        "force_error": true
      },
      {
        "is_duplicate": false
      },
      {
        "is_odd": false
      },
      {
        "is_even": true
      }
    ]
  },
  {
    "documentId": "176",
    "results": [
      {
        "force_error": true
      },
      {
        "is_duplicate": false
      },
      {
        "is_odd": false
      },
      {
        "is_even": true
      }
    ]
  },...etc.

I am trying to take this file and make a map or hashmap of it (I later plan to compare it to a document on cosmodb). How can I turn this Json into an object using Gson? Thanks for the help!

Updated by @Jay Gong.
Sorry for updating your question directly since it can't be clear in the comment.
You have data like below:
  {
    "documentId": "138",
    "results": [
      {
        "force_error": true
      },
      {
        "is_duplicate": false
      },
      {
        "is_odd": false
      },
      {
        "is_even": true
      }
    ]
  }

Then you have other documents against it.
"is_odd": {
    "values": [{
        "source": "internal",
        "locale": "en-US",
        "value": false
    }]
},
"is_even": {
    "values": [{
        "source": "internal",
        "locale": "en-US",
        "value": true
    }]
}

Afterwards,you want to merge it by match-up properties.
{
        "documentId": "138",
        "results": [
          {
            "force_error": true
          },
          {
            "is_duplicate": false
          },
          "is_odd": {
            "values": [{
              "source": "internal",
              "locale": "en-US",
              "value": false
          }]
          },
          "is_even": {
            "values": [{
              "source": "internal",
              "locale": "en-US",
              "value": true
          }]
       }
    ]
  }

A: create two maps and add them
This is my proposal margeJson method and test :
import java.util.HashMap;
import java.util.Map;
import org.junit.Test;
import com.google.gson.Gson;

import static org.junit.Assert.assertTrue;

public class MargeJsonTest {

    String json1 = "{\"documentId\":\"138\",\"results\":[{\"force_error\":true},{\"is_duplicate\":false},{\"is_odd\":false},{\"is_even\":true}]}";
    String json2 = "{\"is_odd\":{\"values\":[{\"source\":\"internal\",\"locale\":\"en-US\",\"value\":false}]},\"is_even\":{\"values\":[{\"source\":\"internal\",\"locale\":\"en-US\",\"value\":true}]}}";

    @Test
    public void get() {
        //given
        Gson gson = new Gson();
        //when
        Map<String, Object> margeJson = margeJson(gson, json1, json2);
        //then
        assertTrue(margeJson.containsKey("documentId"));
        assertTrue(margeJson.get("documentId").equals("138"));
        assertTrue(margeJson.containsKey("results"));
        assertTrue(margeJson.containsKey("is_odd"));
        assertTrue(margeJson.containsKey("is_even"));

        //back to String JSON conversion
        System.out.println(gson.toJson(
                margeJson)); // {"is_even":{"values":[{"source":"internal","locale":"en-US","value":true}]},"documentId":"138","is_odd":{"values":[{"source":"internal","locale":"en-US","value":false}]},"results":[{"force_error":true},{"is_duplicate":false},{"is_odd":false},{"is_even":true}]}

    }

    private Map<String, Object> margeJson(Gson gson, String json1, String json2) {

        Map map1 = gson.fromJson(json1, HashMap.class);
        Map map2 = gson.fromJson(json2, HashMap.class);

        Map<String, Object> map = new HashMap<>();
        map.putAll(map1);
        map.putAll(map2);

        return map;

    }

}


text:
Q: How to find the End Date of the month and convert the date format using Python having a column where Month and year is given, Using Month and year need to find the Last date of the month, and hence convert the date format.
Where need to update StartDay using Date1 and EndDay using Date2.
Input Data
Date1     Date2    StartDay      EndDay

Apr2020  Dec2020
Nov2020  Feb2021
Sep2018  Oct2020
Jan2020  Nov2020
Mar2018  Sep2020

Expected Output
Date1     Date2     StartDay         EndDay

Apr2020  Dec2020    2020-04-01       2020-12-31
Nov2020  Feb2021    2020-11-01       2021-12-28
Sep2018  Oct2020    2018-09-01       2020-10-31
Jan2020  Nov2020    2020-01-01       2020-11-30
Mar2018  Sep2020    2018-03-01       2020-09-30

Code been using So Far:
df['month'] = df.Date2.str[:3]
df['year'] = df.Date2.str[3:7]

df['Date1'] = df.Date1.str[:3] + '-' + df.Date1.str[3:]
df['col'] = '01-' + df['Date1'].astype(str)
df['StartDay'] = pd.to_datetime(df['StartDay'], errors='coerce')
df['StartDay'] = df['StartDay'].dt.strftime('%Y-%m-%d')

How to find the End Date using the column Date2, Please suggest.

A: You can use %b%Y for match months first 3 letters with years in YYYY, so then only need to add pandas.tseries.offsets.MonthEnd:
df['StartDay'] = pd.to_datetime(df['Date1'], errors='coerce', format='%b%Y')
df['EndDay'] = (pd.to_datetime(df['Date2'], errors='coerce', format='%b%Y') +
                pd.offsets.MonthEnd(1))
print (df)
     Date1    Date2   StartDay     EndDay
0  Apr2020  Dec2020 2020-04-01 2020-12-31
1  Nov2020  Feb2021 2020-11-01 2021-02-28
2  Sep2018  Oct2020 2018-09-01 2020-10-31
3  Jan2020  Nov2020 2020-01-01 2020-11-30
4  Mar2018  Sep2020 2018-03-01 2020-09-30


text:
Q: Fastest and cleanest way to update an environment variable for the new Bash instances? I am trying to create / update an environment variable for every bash instances.
Basically I would like the result of export MSBuildSDKsPath=/opt/dotnet/sdk/$(dotnet --version)/Sdks
to be applicable to every bash instance.
The only solution I found is a bit dirty is to put it at the end of the .bashrc file in my home folder but I am not sure this is the right way of doing.
I read in other places that sometimes it should be put in .profile or .bash_profile but if those files are changed within the same user session and then I start a new bash instance, $MSBuildSDKsPath is not updated accordingly.

A: The next comment exists in ~/.profile file by default:
# ~/.profile: executed by the command interpreter for login shells.
# This file is not read by bash(1), if ~/.bash_profile or ~/.bash_login
# exists.
# see /usr/share/doc/bash/examples/startup-files for examples.
# the files are located in the bash-doc package.

That's why it was not work for you.
Additionally, .profile contain next code by default
# if running bash
if [ -n "$BASH_VERSION" ]; then
    # include .bashrc if it exists
    if [ -f "$HOME/.bashrc" ]; then
    . "$HOME/.bashrc"
    fi
fi

This code invoke your ~/.bashrc if it exists.
For your purposes, adding variable export to the end of .bashrc file, I think, is a best solution.


text:
Q: Using statsmodels.seasonal_decompose() without DatetimeIndex but with Known Frequency I have a time-series signal I would like to decompose in Python, so I turned to statsmodels.seasonal_decompose(). My data has frequency of 48 (half-hourly). I was getting the same error as this questioner, where the solution was to change from an Int index to a DatetimeIndex. But I don't know the actual dates/times my data is from.
In this github thread, one of the statsmodels contributors says that

"In 0.8, you should be able to specify freq as keyword argument to
  override the index."

But this seems not to be the case for me. Here is a minimal code example illustrating my issue:
import statsmodels.api as sm
dta = pd.Series([x%3 for x in range(100)])
decomposed = sm.tsa.seasonal_decompose(dta, freq=3)

AttributeError: 'RangeIndex' object has no attribute 'inferred_freq'

Version info:
import statsmodels
print(statsmodels.__version__)
0.8.0

Is there a way to decompose a time-series in statsmodels with a specified frequency but without a DatetimeIndex?
If not, is there a preferred alternative for doing this in Python? I checked out the Seasonal package, but its github lists 0 downloads/month, one contributor, and last commit 9 months ago, so I'm not sure I want to rely on that for my project.

A: Thanks to josef-pkt for answering this on github. There is a bug in statsmodels 0.8.0 where it always attempts to calculate an inferred frequency based on a DatetimeIndex, if passed a Pandas object.
The workaround when using Pandas series is to pass their values in a numpy array to seasonal_decompose(). For example:
import statsmodels.api as sm

my_pandas_series = pd.Series([x%3 for x in range(100)])
decomposed = sm.tsa.seasonal_decompose(my_pandas_series.values, freq=3)

(no errors)


text:
Q: OOP in JS, how does this.init.apply work with OOP I'm learning OOP in Javascript and I came across one of the first examples and I'm unclear as to what the third line does ==> this.init.apply(this, arguments);
var Class = function(arguments){
    var klass = function(){
        this.init.apply(this, arguments);
    };
    klass.prototype.init = function(){};
    return klass;
};

And anyone mind explaining the whole thing? I understand most of it but I just want to feel like I'm thinking about this the right way.

A: Javascript has prototype inheritance.
The code you pasted has a method called init declared as
klass.prototype.init = ...
Is like a public method of any copy of klass object.
In Javascript every object is linked to a special object named "prototype". Everything you put inside that special object will be accesible to new instances of the original object.
Example:
var Human = function(n){
    this.name = n;
};
Human.prototype.getName = function(){
   return this.name;
};

//instance of Human
var pedro = new Human("Pedro");

Now pedro has access to Human.prototype objects...
pedro.getName();
//return "Pedro"

pedro prototype "inherits" from Human.prototype, and Human.prototype "inherits" from Object.prototype.
Lets get back to your example:
Each copy of klass will be linked with klass prototype besides having its own prototype. So every copy of klass (in this case: every object returned by Class) will be able to use the functions defined in the original klass prototype.
klass is an object (functions are objects in js) encapsulated inside the definition of another object/function named Class.
Class generate instances of klass because that is what Class function return.
This code ilustrates a way of defining a pseudo class "Class", with a method called init, accesible from any object returned by the function Class
That way you could do:
var myClass = new Class(anArrayWithArguments);
In the context of the function klass: "this" inside Class means the klass object, and this can call init as well as myClass can do it like new instances returned by Class function.
init can.be considered like a constructor in your example.
apply called from init allow to invoke init with an array of arguments over the object this (the new object to be returned by Class)


text:
Q: Can Resque Cleaner be expanded to store >1000 failed jobs? I have Resque Cleaner set up with Redis and a Ruby on Rails framework. I noticed the cleaner fills with failed jobs up until the 1000 mark. I've been trying to find a way to increase the 1000 threshold with no luck yet, is there a way to do this that I'm missing?

A: Looks like this is covered in the readme here: https://github.com/ono/resque-cleaner
Add this to a resque-web config file:
# [app_dir]/config/resque-web.rb
require 'resque-cleaner'
module Resque::Plugins
  ResqueCleaner::Limiter.default_maximum = 10_000
end

Then pass the file when you start resque-web
$ resque-web [app_dir]/config/resque-web.rb


text:
Q: Difference between isinstance and type in python I was looking at some code on the web, and I saw some code I'm not used to. The one that most called my attention was:
if not isinstance(string, str):
    #dosomething

What would be the difference if I did instead:
if type(string)!=str:
    #dosomething

A: First check out all the great answers here.
type() simply returns the type of an object.  Whereas, isinstance():
Returns true if the object argument is an instance of the classinfo argument, or of a (direct, indirect or virtual) subclass thereof.
Example:
class MyString(str):
    pass

my_str = MyString()
if type(my_str) == 'str':
    print 'I hope this prints'
else:
    print 'cannot check subclasses'
if isinstance(my_str, str):
    print 'definitely prints'

Prints:
cannot check subclasses
definitely prints


text:
Q: How do I sort a 2D array using a Listbox which displays the first row of the array?
*

*I'm working in VBA (not in the excel IDE but I have its object library as a
reference) and I have a userform with a listbox which displays all
the worksheets within an excel workbook.

*when one of these listbox items(worksheets) is selected, a specific
range of    cells within the selected worksheet is put into a 2D
array and the items from the top row (column headers) in each column
are then used to populate a 2nd listbox.

*I have 2 command buttons which allow me to move the individual items
up or down within the 2nd listbox(depending on if the item can move
up or down from its position in the listbox).

*What I am trying to achieve now is, after I have reordered the items
in the 2nd listbox, I want the 2D array to be sorted to match the
arrangement of the listbox items so that when I loop through the
array I can manipulate its data in this specific order.

I'm not sure precisely how I go about it, my first thought would be loop through the items in the listbox starting at 0, use string comparison of selected item against each value in the top row of the array, if a match is found, move that entire column into a new array, repeat until at the end of all listbox items.
I'm entirely sure that's the best way to approach it so I'm looking for thoughts on how best to achieve this.
Thanks


text:
Q: How can I create an Ember object to send Google Drive API requests? Basically, I need to create an Ember wrapper for the Google Drive API JavaScript client library.

A: Pulling information for various sources, here is a Gist with some information that hopefully will help others:
https://gist.github.com/monocle/9539722
It's not perfect, but it get's the job done for now. This will make creating an Ember Data Adapter for Google Drive files easier.


text:
Q: creating a text box field in Cakephp of array type Can anyone help me that as i am new to CakePHP
i want to create a an input box of array type.
my code is
<?php echo $this->Form->input('txt', array('type' => 'text','label' => 'Field 1')); ?>

output for this is :
<input type="text" id="AddmoreTxt" multiple="multiple" name="data[Addmore][txt]">

but i want the output like
<input type="text" id="AddmoreTxt" multiple="multiple" name="data[Addmore][txt][]">

A: Put dot after your fieldName like below mentioned in code. I have checked this code.
CakePHP Code
<?php echo $this->Form->input('txt.', array('type' => 'text','label' => 'Field 1')); ?>

Output
<input type="text" id="AddmoreTxt" multiple="multiple" name="data[Addmore][txt][]">

A: Finally i find the answer. Let me know if it is not exactly correct thank you
<?php echo $this->Form->input('txt', array('type' => 'text','label' => 'Field 1','name'=>'data[Addmore][txt][]')); ?>

A: I believe this will work better:
In your input, put '.' (dot) after field name.
<?php echo $this->Form->input('txt.', array('type' => 'text','label' => 'Field 1'); ?>


text:
Q: i don't know why 'runtime error' message occurs These are my code. I practice algorithm about 'The little prince'. The algorithm 's contents are that if you input starting point and destination point, you should find how many you cross the planet's range. I submitted my code below to receive score. But I received 'runtime error' message. I couldn't find the solution. Please advise about my code. I think answer itself about algorithm is correct.
import java.util.LinkedList;
import java.util.Scanner;
class Planet
{
    int cx;
    int cy;
    int r;
}
public class Main {
    public static void main(String[] args) {
        Scanner scanner=new Scanner(System.in);
        int testCase=Integer.parseInt(scanner.nextLine());//input test case
        int answer[]=new int[testCase];
        String str[]=scanner.nextLine().split(" ");//input start and dest point
        int x1=Integer.parseInt(str[0]);
        int y1=Integer.parseInt(str[1]);
        int x2=Integer.parseInt(str[2]);
        int y2=Integer.parseInt(str[3]);
        if(x1!=y1&&x2!=y2)
        {
            for(int i=0;i<testCase;i++)
            {
                int count=0;
                int planetNum=Integer.parseInt(scanner.nextLine());//input planet counts
                LinkedList<Planet> planetList=new LinkedList<>();
                for(int j=0;j<planetNum;j++)
                {
                    String inputPlanet[]=scanner.nextLine().split(" ");//each planet's (x,y) and radius
                    Planet planet=new Planet();
                    planet.cx=Integer.parseInt(inputPlanet[0]);
                    planet.cy=Integer.parseInt(inputPlanet[1]);
                    planet.r=Integer.parseInt(inputPlanet[2]);
                    planetList.add(planet);
                }
                for(int j=0;j<planetList.size();j++)
                {
                    double startDistance=Math.sqrt((planetList.get(j).cx-x1)*(planetList.get(j).cx-x1)
                            +(planetList.get(j).cy-y1)*(planetList.get(j).cy-y1));
                    double destDistance=Math.sqrt((planetList.get(j).cx-x2)*(planetList.get(j).cx-x2)
                            +(planetList.get(j).cy-y2)*(planetList.get(j).cy-y2));

                    if(startDistance<planetList.get(j).r||destDistance<planetList.get(j).r)
                        count++;
                }
                answer[i]=count;
            }
        }
        else
        {
            for(int i=0;i<testCase;i++)
                answer[i]=0;
        }
        for(int i=0;i<testCase;i++)
            System.out.println(answer[i]);

    }
}

input

2
-5 1 12 1
7
1 1 8
-3 -1 1
2 2 2
5 5 1
-4 5 1
12 1 1
12 1 2
1
0 0 2
output

3
0

A: Where is your problem? I copied your code. Changed scanner.nextLine() to inputArray[inputIndex++] and filled it (inputArray) with your displayed input. I received zero exceptions. Without the exception-  it's wasting our time. We still want to help. Show us your Exception with stacktrace.
class Planet // I put everything under the Planet class.
{
    int cx;
    int cy;
    int r;

    // These two simulate user input
    static int inputIndex = 0;
    static String[] inputArray =  {
       "2",
       "-5 1 12 1",
       "7",
       "1 1 8",
       "-3 -1 1",
       "2 2 2",
       "5 5 1",
       "-4 5 1",
       "12 1 1",
       "12 1 2",
       "1",
       "0 0 2"};

public static void main(String[] args) {
    int testCase=Integer.parseInt(inputArray[inputIndex++]);//input test case
    int answer[]=new int[testCase];
    String str[]=inputArray[inputIndex++].split(" ");//input start and dest point
    int x1=Integer.parseInt(str[0]);
    int y1=Integer.parseInt(str[1]);
    int x2=Integer.parseInt(str[2]);
    int y2=Integer.parseInt(str[3]);
    if(x1!=y1&&x2!=y2)
    {
        for(int i=0;i<testCase;i++)
        {
            int count=0;
            int planetNum=Integer.parseInt(inputArray[inputIndex++]);//input planet counts
            LinkedList<Planet> planetList=new LinkedList<>();
            for(int j=0;j<planetNum;j++)
            {
                String inputPlanet[]=inputArray[inputIndex++].split(" ");//each planet's (x,y) and radius
                Planet planet=new Planet();
                planet.cx=Integer.parseInt(inputPlanet[0]);
                planet.cy=Integer.parseInt(inputPlanet[1]);
                planet.r=Integer.parseInt(inputPlanet[2]);
                planetList.add(planet);
            }
            for(int j=0;j<planetList.size();j++)
            {
                double startDistance=Math.sqrt((planetList.get(j).cx-x1)*(planetList.get(j).cx-x1)
                        +(planetList.get(j).cy-y1)*(planetList.get(j).cy-y1));
                double destDistance=Math.sqrt((planetList.get(j).cx-x2)*(planetList.get(j).cx-x2)
                        +(planetList.get(j).cy-y2)*(planetList.get(j).cy-y2));

                if(startDistance<planetList.get(j).r||destDistance<planetList.get(j).r)
                    count++;
            }
            answer[i]=count;
        }
    }
    else
    {
        for(int i=0;i<testCase;i++)
            answer[i]=0;
    }
    for(int i=0;i<testCase;i++)
        System.out.println(answer[i]);

}
}


text:
Q: How to remove a system which was created with quicklisp quickproject?
*

*I made a project with quickproject:make-project in directory "~/projects/{name}/".

*I wasn't happy how it turned out and wanted to start over, so I renamed the directory to "~/projects/{name}-old/" and made a new project with quickproject:make-project in the initial directory "~/projects/{name}/".

*If I try to load my project with ql:quickload, quicklisp tries to load the old project.
How do I remove the old system, while keeping the old project files where they are?
What should I have done, instead of renaming the directory in step 2.?

A: There was a bug in ASDF that caused a problem like this. You might be able to recover by using (asdf:clear-system "<name>"). If that doesn't work, things should work fine if you restart.

A: Angus is right, in my file ~/.config/common-lisp/source-registry.conf.d/projects.conf there is this entry,
(:tree (:home "projects/"))

and the wrong project gets picked first. To prevent asdf from loading the wrong project I had to rename the asd file. Just changing the package or system definition in the project, like I tried at first, didn't help.


text:
Q: Scale results in paraview The results I get in paraview through the generated .vtu files are too small (eg magnitude of ^-18) this is because I run an analysis through a scaled down model.
I would like to give the results in a exagerated form so that deflection and stresses are very visible. So I need to multiply my results with a factor.
Can I do this in the paraview interface or should I find a way to write the .vtu files with a magnification factor.
A method to do either would be much appreciated.
Thanks

A: The Calculator filter (http://daac.hpc.mil/software/ParaView/ParaView_Calculator.html) can be use to multiply an array by a value. "Result Array Name" should be set to a new, unique name.


text:
Q: Delete the Range of Columns in Excel VBA I am trying to delete the range of columns but getting error "Application Defined or object defined error". In the below code wks is the worksheet and colStart and colEnd are variables with values.
Dim colDelete As String

colDelete = wks.Range(wks.Cells(1, colStart), wks.Cells(1, colEnd)).EntireColumn.Delete

A: Declare your variables. Always.
dim colStart as long
dim colEnd as long
dim wks as Worksheet

It should work this way.

A:
Yes vacip the colStart and colEnd has integer values as you can see in watch screen of my image. And also wks is properly assigned worksheet object.


text:
Q: Update the value at a certain position for every two rows an array I have a n-by-m matrix with zeros and my row number is always even. For the first and second row, I want to update the first element to be 1, 3rd and 4th the second element to be 1 etc.
So if my original matrix is
 [0,0,0
  0,0,0
  0,0,0
  0,0,0
  0,0,0
  0,0,0]

I would like my resulting matrix to be:
 [1,0,0
  1,0,0
  0,1,0
  0,1,0
  0,0,1
  0,0,1]

A: Another solution using indexing:
m=6;
n=3;
A = zeros(m,n);
A(1:m+2:end)=1;
A(2:m+2:end)=1;

Result:
A =

   1   0   0
   1   0   0
   0   1   0
   0   1   0
   0   0   1
   0   0   1

A: Your question can have two possible interpretations. The simpler one is just to get the second matrix. It is a diagonal matrix with each row repeated twice. This can be done easily with kron:
x = kron(eye(3), [2, 1])

If you want to find the pattern of indices that results in the correct assignment of ones, you can just use the above expression to generate a boolean mask, then apply it to an arbitrary input (in your case zeros(6, 3)):
x = zeros(6, 3);
mask = kron(eye(3, 'logical'), [2, 1]);
x(mask) = 1

A: This works even if n does not equal 2*m
x = zeros(6,4); % example with n=6, m = 4
[n, m] = size(x);
m = min(m,n/2);
x(bsxfun(@plus, 1:n, n*floor(0:.5:m-.5))) = 1;

gives
x =
     1     0     0     0
     1     0     0     0
     0     1     0     0
     0     1     0     0
     0     0     1     0
     0     0     1     0

A: sortrows([eye(3);eye(3)],'descend')

ans =

     1     0     0
     1     0     0
     0     1     0
     0     1     0
     0     0     1
     0     0     1

Or, if you already have your matrix:
A = zeros(6,3);
a = 1; % Or whatever arbitrary number.
jj=1;
for ii = 1:2:size(A,1)
    A(ii:ii+1,jj)=[a;a];
    jj=jj+1;
end


text:
Q: Lazy evaluation of function I want to conditionally lazy evaluate a function with some heavy computations:
def fun(a):
    yield a + 1
    yield a * 2

Is it possible to write this exact function but with 1 line in the function body? Something like this:
def fun(a):
    yield from (a+1, a*2)

But in the code snippet above I think the tuple will be evaluated eagerly? I only want to evaluate a*2 if necessary.

A: Sure, you can separate simple statements on a single line by a semicolon:
def fun(a):
    yield a + 1; yield a * 2

But why do you care how many lines it takes? Just go with your original version, that is the most Pythonic one. At the very least, the above is against PEP-8 style guidelines

A: You can try this
def fun(*args):
    a= yield from  (x+ 1 for x in args);yield a *2

b=fun(12,2,1,2,3,4)
next(b) # (12 +1)
next(b) # (2 +1)

However, if you want to directly use a* 2 with the next value
b.send(next(b)) #(1 *2)

A: This is possible, but I think I like your original multi-line answer better:
Here foo() is your expensive part of your original fun() calculation base on inputs that might be provided say in a loop by fun().
It was not clear from my original example what the distinction between foo() and fun() was as my fun() included the original a+1 "expensive" calculation.
I hope to make this more clear by passing (a, 1) into foo() as paramters where foo() performs the expensive part in a lazy manner.
import time

def foo(a, i):
    # this is expensive
    time.sleep(5)
    return a + i

def fun(a):
    yield from (foo(*x) for x in [(a,1), (a,2)])

for x in fun(10):
    print(x)

This is lazy on foo()


text:
Q: Estimate the body surface area This is a question back when I was in the third year of my (junior) middle school. However I still do not know an elegant answer to it. The question is composed of a single line.

Measure the body surface area of a person, listing necessary steps in the procedure and briefly explain how it works.

Wikipedia does have the page body surface area and it provides a formula for the estimation. However I don't see how that formula would fit into a question designed for middle school students using only textbook knowledge.
So I would know what the expected answer may be to the original question. Any help will be appreciated. I believe the measurement does not need to be very accurate.

This is a closely related question: How to (safely) measure the surface area of a human body?
The statement of that question is basically the same as this one, but the requirement is different. In the referred question, it is required the measurement be safe only. Some of the methods mentioned there (e.g. using a 3D imaging device) are clearly out of the scope of this question. In the highest voted answer there, honey is used to coat the person being measured. I think that method should work but just like my attempted answer of wrapping the person in latex, this renders the person being measured uncomfortable for quite a while, which is the part I find not elegant enough. I expect there is some simple and smart ways that will render the person measured no more uncomfortable than measuring the height or the weight, and only uses the middle school textbook knowledge.
I believe somewhere in the book I saw this question from I also saw the statement that this information may be important to a surgeon dealing with a person who got injured from fire. However of course in that latter case we may just as well use the formula from the Wikipedia.


text:
Q: Bluetooth Beacons - Azure IoT Hub - Android App I want to develop an IT system where my bluetooth beacons send data to an Azure IoT Hub. Then, I want to make an Android app to stream/pull the data from the Azure cloud. I am still new to Azure, so I do not know where to get started.
Any help (with links or example projects) would be really appreciated. I am familiar with Android App Development(currently enrolled in a college) . I am also familiar with consuming REST APIs in Android. The only help I need is how to interact with the data that is in my Azure IoT Hub?

A: IoT Hub is an Azure service that enables you to ingest high volumes of telemetry from your IoT devices into the cloud for storage or processing.
We have a MS Doc to send data from device to IoT Hub
Also, we can send events from IoT hub to different end points, we can filter the data as well before sending to our endpoints. This documentation will help us in understanding to send the telemetry from CLI and send the data using different SDK's
This .py file will help us to integrate with smart devices into your solutions without any manual configuration
Can refer to Azure SDK for Python to check the exact information


text:
Q: Remove dict element from list of dicts using lambda New to python here:
I'm trying to create a new list where every dict from initial list has an element removed, it exists:
arraylist = [{"x":1, "y":2}, {"x":3, "y":2}, {"x":5, "y":2}, {"x":33, "y":2}, {"x":1, "y":8}]
arraylist = map(lambda d: del d["y"] if "y" in d, arraylist)

I know I can do it using for, using del. But I'm looking to learn something new.

A: Use a list comprehension:
In [26]: [{x:d[x] for x in d if x != 'y'} for d in arraylist]
Out[26]: [{'x': 1}, {'x': 3}, {'x': 5}, {'x': 33}, {'x': 1}]

A: You can use filter like this
arraylist = [{"x":1, "y":2}, {"x":3, "y":2}, {"x":5, "y":2}, {"x":33, "y":2}, {"x":1, "y":8}]
arraylist = map(lambda d: dict(filter(lambda (k,v): k != "y", d.iteritems())), arraylist)

A: You can't use del in a lambda function because del is a statement and a lambda's body can only be a single expression. You can't put a statement inside an expression. You could make it work with an ordinary function:
def delete_y(d):
    if "y" in d:
        del d['y']
    return d

Note that using del like this modifies the dictionary d in place. This means that returning the modified dictionary (and using the return value to build a new list) is sort of redundant. The original data structure the dictionary came from will already have the modified version.

A: Maybe its not the shortest way, but it is definitely a convenient way to remove
items from a list:
arraylist = [{"x":1, "y":2}, {"x":3, "y":2}, {"x":5, "y":2}, {"x":33, "y":2}, {"x":1, "y":8}]

print arraylist

def containsY(d):
    if 'y' in d.keys():
        del d['y']
        return True
    return False

filter(containsY, arraylist)

print arraylist

output:
[{'y': 2, 'x': 1}, {'y': 2, 'x': 3}, {'y': 2, 'x': 5}, {'y': 2, 'x': 33}, {'y': 8, 'x': 1}]
[{'x': 1}, {'x': 3}, {'x': 5}, {'x': 33}, {'x': 1}]


text:
Q: SQL: How to perform this query over each group I am using SQLite3 and I have the following setup. I have a table which is organised as follows:
ID   k  count
1    a     1
1    b     2
1    c     5
2    a     3
2    b     4
3    a     2

What I want to do is compute the element wise product-sum between the count column for each ID where they share a k.
So, for example, between 1 and 2, the element wise sum is SUM (1*3 + 2*4) as they share the a and b key. Similarly, between 2 and 3, it will be SUM(3*2) as they only share the 'a' key.
It is because I have to create this for every ID pair i.e. (1, 2), (2, 3), (1, 3), I am not sure how to do this in SQL.

A: You can use INNER JOIN to find all matching pairs:
SELECT t1.ID AS t1ID, t2.ID AS t2ID,
       SUM(t1.count*t2.count) AS s
FROM mytable AS t1
INNER JOIN mytable AS t2
  ON t1.ID < t2.ID AND t1.k = t2.k
GROUP BY t1.ID, t2.ID

Using GROUP BY t1.ID, t2.ID we can easily calculate element wise sum for each pair.
Demo here

A: @Luca instead of Generating as pairs((1,2),(2,3),(1,3)) ,you can generate as(1,2,3...) .You can use subquery inorder to find the appropriate condition and produce the desired output.


text:
Q: How to make Laravel run MQTT listener or subscribe Currently I am running using command php arisan start.listening.mqtt.
However, it will be killed if no more active on the screen.
So can any one suggest a better way for 2 objective

*

*Run the MQTT listener as background process through Laravel code

*When the server reboot, it is started automatically.

Currenly I am using AWS Ubuntu server to run Mosquitto


text:
Q: Accessing values in textboxes dynamically created by jQuery I dynamically created textboxes using jQuery which are filled with random numbers. I am not sure how to access the values inside the dynamically created textboxes.
I want to access the textbox values so I can test them for duplicate numbers or to check if they are nonnumeric since the user can change and enter any character into the textboxes
after they are created. I probably cannot use an array to access them since I won't be able to test the values using the jQuery Validate plugin (or can I?) before they are inserted
into MySQL using PHP. Also, I would like access to the textbox values so they can be inserted into MySQL using PHP. Does anyone have any idea how I can access the textbox values of
these dynamically created textboxes so they can be referred to using PHP for insertion into MySQL? Thanks much for any help.
This is the main code which creates the dynamic textboxes and inputs the random numbers.
    // Fill the textboxes with the generated numbers
    var parentForm = $(this).closest(".form");
    for (var n in random_numbers)
    parentForm.find(".inputs input:eq(" + n + ")").val(random_numbers[n]);
}

$(document).ready(function() {
    $('#dropdownadd').change(function() {

        var dropDownDiv = $('#dropdowndiv');

        dropDownDiv.html("");

        $loopcount = $(this).val();

        for (var i = 1; i <= $loopcount; i++) {
            var setHtml = "";

            setHtml = '
<form id="frm' + i + '">';
            setHtml += 'Number Set #' + i + '';
            setHtml += '
<input type="button" class="button" id="btn' + i + '" value="Generate Numbers" />
';
            setHtml += '
';
            for (var t = 0; t < 3; t++) {
                setHtml += '<input type="text" name="num' + t + '" id="num' + t + '" class="input" />';
            }
            setHtml += '
';
            setHtml += '
';
            dropDownDiv.append(setHtml);

            $("#btn" + i).bind('randomize', getRandomNumbers).click(function(e) {
                $(this).trigger('randomize');
            });
        }

A: When you dynamically create the textboxes give them both an unique id tag and a name tag (same values)
For example TB1 TB2 TB3....
You'll then be able to access them from JS with
$('#TB' + n).val()

where n is the text box number you want to access.
As they are in a form, the values will be posted to the speciefied form url in the tag action and will be available for processing with PHP

A: Based on demo I created here is how I am receiving form currently in php:
print_r( $_GET);

results in:
Array
(
    [num_1_0] => 385122
    [num_1_1] => 719388
    [num_1_2] => 865862
    [num_2_0] => 205449
    [num_2_1] => 819047
    [num_2_2] => 870961
)

Can easily manipulate this array into any other format. First digit in field name is row, second is index in row
EDIT : To visualize this output set form method to "GET" , set action to process-form.php. In process-form.php put following:
echo '
';
print_r( $_GET);

Now submit form


text:
Q: Flex .swc build using org.sonatype.flexmojos is failing I am trying to create and build a flex library project (.swc) using maven 2 firsttime.
I am able to create directory structure but build is failing.
My maven settings are :
Maven version : apache-maven-3.0.2

*

*mvn  archetype:generate
-DarchetypeGroupId=org.sonatype.flexmojos
-DarchetypeArtifactId=flexmojos-archetypes-library
-DarchetypeVersion=3.8
-DgroupId=com.test
-DartifactId=sampleflexproject2 –e

This created the basic project skeleton as per my need.

*

*mvn clean install –e –X

I get below exception while executing this command.
[ERROR] Failed to execute goal org.sonatype.flexmojos:flexmojos-maven-plugin:4.0-pre-alpha-1:compile-swc (default-compile-swc) on project sampleflexproject2: The parameters 'output' for goal org.sonatype.flexmojos:flexmojos-maven-plugin:4.0-pre-alpha-1:compile-swc are missing or invalid -> [Help 1]
org.apache.maven.lifecycle.LifecycleExecutionException:
Failed to execute goal org.sonatype.flexmojos:flexmojos-maven-plugin:4.0-pre-alpha-1:compile-swc (default-compile-swc) on project sampleflexproject2: The parameters 'output' for goal org.sonatype.flexmojos:flexmojos-maven-plugin:4.0-pre-alpha-1:compile-swc are missing or invalid
       at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:221)
       at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:153)
       at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:145)
       at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:84)
       at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:59)
       at org.apache.maven.lifecycle.internal.LifecycleStarter.singleThreadedBuild(LifecycleStarter.java:183)
       at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:161)
       at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:319)
       at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:156)
       at org.apache.maven.cli.MavenCli.execute(MavenCli.java:534)
       at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:196)
       at org.apache.maven.cli.MavenCli.main(MavenCli.java:141)
       at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
       at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
       at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
       at java.lang.reflect.Method.invoke(Method.java:585)
       at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:290)
       at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:230)
       at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:409)
       at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:352) Caused by: org.apache.maven.plugin.PluginParameterException:
The parameters 'out put' for goal org.sonatype.flexmojos:flexmojos-maven-plugin:4.0-pre-alpha-1:compile-swc are missing or invalid
       at org.apache.maven.plugin.internal.DefaultMavenPluginManager.validateParameters(DefaultMavenPluginManager.java:688)
       at org.apache.maven.plugin.internal.DefaultMavenPluginManager.populatePluginFields(DefaultMavenPluginManager.java:580)
       at org.apache.maven.plugin.internal.DefaultMavenPluginManager.getConfiguredMojo(DefaultMavenPluginManager.java:525)
       at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:98)
       at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:209)

Do you foresee any obvious  issue in this ?

A: Please post a simplified version of the POM.
The issue seems to be though that you are missing some configuration for the flexmojos-maven-plugin.  It is complaining that the goal default-compile-swc has no output property defined.
Take a look at your plugin definition:
<plugin>
   <groupId>org.sonatype.flexmojos</groupId>
    <artifactId>flexmojos-maven-plugin</artifactId>
    <version>4.0-pre-alpha-1</version>
    <configuration>
      <output>${basedir}/target/sampleflexproject2.swf</output>
    </configuration>
</plugin>

That though alone will probably not be sufficient for a successful build.
Take a look https://repository.sonatype.org/content/sites/maven-sites/flexmojos/4.0-RC1/compile-swc-mojo.html for more information on what should be set in the configuration block.


text:
Q: CPU Upgrade from Intel Core i3-2120 to Intel Core i5-2400 I am currently using an older Acer Aspire AM3970 computer with an Intel Core i3-2120 and I was wondering if it would be possible to upgrade the CPU to an Intel Core i5-2400?
My hardware building experience consists of RAM upgrades and that is it. I have some friends who can help me perform the upgrade, I am just wondering if it is possible to upgrade before I purchase the CPU.
Thank you!

A: Other than cooling issues between the 65w tdp of the i3-2120 and the i5-2400 at 95wTDP. The issue would be if the motherboard bios supports the larger core chip. You may want to look into the i5-2400S which has the lower operating temp of 65w TDP and matches the designed cooling for your chassis.


text:
Q: phpMyAdmin error while installing I can not access phpMyAdmin
Through my website. When I open https://my-ip-is.com/phpmyadmin or localhost/phpmyadmin
Not Found
The requested URL /phpmyadmin was not found on this server.
Apache/2.4.7 (Ubuntu)


text:
Q: Form Data is not being sent to server The form created shows the data being sent within the URL when the submit is clicked however the only part which is sent to the server is the username/$un. All of form inputs are being ignored.
HTML Form:
<form action="CharacterAdd.php">
<legend>Add Character</legend>
Character Name:

<input type="text" name="Name" >

Gender:

<input type="text" name="Gender" >

Age:

<input type="text" name="Age" >

Hobbies:

<input type="text" name="Hobby" >

Home:

<input type="text" name="Home" >

Job:

<input type="text" name="Job" >

<input type="submit" value="Submit">

</form>

PHP Code:
$un = $_SESSION["gatekeeper"];

$a = htmlentities($_POST['Name']);
$b = htmlentities($_POST['Gender']);
$c = htmlentities($_POST['Age']);
$d = htmlentities($_POST['Hobby']);
$e = htmlentities($_POST['Home']);
$f = htmlentities($_POST['Job']);
$g = htmlentities($_POST['$un']);

{
    $statement = $conn->prepare("INSERT INTO Characters(Name,Gender,Age,Hobby,Home,Job,username) VALUES (?,?,?,?,?,?,?)");
    $statement->bindParam(1,$a);
    $statement->bindParam(2,$b);
    $statement->bindParam(3,$c);
    $statement->bindParam(4,$d);
    $statement->bindParam(5,$e);
    $statement->bindParam(6,$f);
    $statement->bindParam(7,$un);
    $statement->execute();
    $conn->query ($charac);

A: If you want to send the form with POST, change the method, as the default is GET
<form action="CharacterAdd.php" method="POST">

or you could check the $_GET superglobal instead
$a = htmlentities($_GET['Name']);
$b = htmlentities($_GET['Gender']);

A: please declare method="POST" in form tag.

A: You might be wrapping your PHP code like:
if(isset($_POST['submit'])){
  ...
}

Which is a common mistake among developers, because in order for that to work, you need to name your submit button as submit like <input name="submit" value="Submit form">.
Also, you need to set some form attributes, such as the method and action. The default method is get. If you want your values hidden from the browser address bar, make sure you set your method to post like <form method="post">. You also need to specify a file that will be called usingaction`. If not set, the file within which the form is is taken as the action.


text:
Q: Guidelines for calling controller methods in helper modules? Few questions:

*

*Is it possible to call a controller method in a helper module (e.g., application helper)?

*If so, how does the helper handle the rendering of views?  Ignore it?

*In what instances would you want to call a controller method from a helper? Is it bad practice?

*Do you have any sample code where you're calling controller methods in helper?

A: You generally don't call controller-methods from helpers. That is: if you mean a method that collects data and then renders a view (any other method that needs to be called should probably not be in a controller).
It is definitely bad practice and breaks MVC.
It is, however, perfectly possible to make controller-methods available in the views, a great example is for instance the current_user method.
To make a controller method available in the views, as a helper method, just do
private

def current_user
  # do something sensible here
  @current_user ||= session[:user]
end
helper_method :current_user

Such a method is best defined in the private section, or it could be available as an action (if you a wildcard in your routing).

A: Declare your methods on the corresponding controller
private
def method_name1
...
end

def method_name2
...
end

In the head of the controller declare
helper_method :method_name1, :method_name2

You may want to declare those methods under private state
And that's it, now you can use your method on a helper

A: Calling a controller from a helper violates the MVC pattern. IMO if you need to call a controller from a Rails view helper (like application_helper) then there is something about the design that could be improved. The intention is that helpers "help" views, and therefore only talk to models.
I'm not going to defend MVC itself here (there are a  ton of references on the web), but this SO thread about calling the controller from a view should get you started.
Calling controller from view? (note, this is an ASP.NET thread, so only the high level principles are relevant).


text:
Q: Replace a line in a file I have a very large text file, and my iPad program needs to occasionally replace a single line of data (newline: '\n'). How can I do this efficiently? Writing the entire file at once is not an option.
I've been looking into NSFileHandle, and it looks like it will do what I want; right now I'm having trouble figuring out how to find line X, and then replace it with the data from a string. I think after that's done, all I need to do is call synchronizeFile, right?
I appreciate your help!

A: You cannot really do this without writing the whole file. You could seek to the beginning of the line and then write the new line. But first you'd have to find out the offset of that line. If you don't already have that this means reading the file from the beginning to that line. Then you could write the new line, but only if it is exactly the same length as the original line. If it is longer it will overwrite the next line - there is no way to insert data into a file. If the new line is shorter than the old one the end of the old line will remain. The same length requirement is also tricky. This means the same length in bytes. Depending on the character encoding some characters might require more bytes than others.
If you really need to do this and have it work for about every case you'd have to use those steps:

*

*Read the entire file to find out the offset of the line you're interested in

*Seek to the offset of the line

*Write the new line

*Write out the rest of the file you read in step 1.

This algorithm will work, no matter how long or short the lines are or how they are encoded. But this will probably be more expensive than just writing out the whole file, especially if you have it in memory anyways.
Have you actually verified that it is not acceptable to write out the whole file or are you doing premature optimization here? If your text file is really that big you should be considering a database, like SQLite, or to use Core Data.


text:
Q: Iterating with my object stopped working for some reason this code throws an error
// map<int, AnItem> roomlist;
// map<string, long> rinventory

map<int, AnItem>::iterator it;

for ( it = roomlist[roomno].rinventory.beg/in(); it != roomlist[roomno].rinventory.end(); it++ )    {

        if( (*it).second.name == "Stock" )
            tmpitem.append( strmug );
    }

The if statment throws the error.  It's really not that complex and I would think I could handle this.  So... roomlist is a map, roomno is an integer and rinventory is a map
class AnThing   {

public:
    AnThing();              // constructor
    string name;                // name reference
    int gtid;               // Thing ID
    string lcname;              // name in lowercase
    string m_name;
};

class AnItem : public AnThing   {

public:

    ItemType m_type;
    int imin;
    int imax;
    int ispeed;
    long unsigned iprice;
    unsigned int ecoin;
    GAttributes m_attributes;

    AnItem(); //Constructs an item with "invalid" values

    int& Min(); // Returns the min attribute
    int& Max(); // Returns the max attribute
    int& Speed(); // Returns the speed attribute

};

Thanks in advance!  I will append the errors I get below (there are two of them)

c:\ucdhb2\gaia\logonserver\v6\gaiaserver.cpp(812) : error C2679:
  binary '=' : no operator found which takes a right-hand operand of
  type 'std::_Tree<_Traits>::iterator' (or there is no acceptable
  conversion) 1>        with 1>        [ 1>
  _Traits=std::_Tmap_traits,std::allocator>,false> 1>        ] 1>        c:\program
  files\microsoft visual studio 9.0\vc\include\xtree(498): could be
  'std::_Tree<_Traits>::iterator
  &std::_Tree<_Traits>::iterator::operator =(const
  std::_Tree<_Traits>::iterator &)' 1>        with 1>        [ 1>
  _Traits=std::_Tmap_traits,std::allocator>,false> 1>        ] 1>        while trying to match the
  argument list '(std::_Tree<_Traits>::iterator,
  std::_Tree<_Traits>::iterator)' 1>        with 1>        [ 1>
  _Traits=std::_Tmap_traits,std::allocator>,false> 1>        ] 1>        and 1>        [ 1>
  _Traits=std::_Tmap_traits,std::allocator>,false> 1>        ]
  1>c:\ucdhb2\gaia\logonserver\v6\gaiaserver.cpp(812) : error C2678:
  binary '!=' : no operator found which takes a left-hand operand of
  type 'std::_Tree<_Traits>::iterator' (or there is no acceptable
  conversion) 1>        with 1>        [ 1>
  _Traits=std::_Tmap_traits,std::allocator>,false> 1>        ] 1>        c:\program files\microsoft
  sdks\windows\v6.0a\include\guiddef.h(197): could be 'int operator
  !=(const GUID &,const GUID &)' 1>        c:\program files\microsoft
  visual studio 9.0\vc\include\xtree(314): or       'bool
  std::_Tree<_Traits>::const_iterator::operator !=(const
  std::_Tree<_Traits>::const_iterator &) const' 1>        with 1>
  [ 1>
  _Traits=std::_Tmap_traits,std::allocator>,false> 1>        ] 1>        while trying to match the
  argument list '(std::_Tree<_Traits>::iterator,
  std::_Tree<_Traits>::iterator)' 1>        with 1>        [ 1>
  _Traits=std::_Tmap_traits,std::allocator>,false> 1>        ] 1>        and 1>        [ 1>
  _Traits=std::_Tmap_traits,std::allocator>,false> 1>        ]

A: Your iterator
map<int, AnItem>::iterator it;

needs to be of type
map<string, long>::iterator it;

based on your comment (i.e. you are iterating over rinventory, not roomlist).


text:
Q: Runtime Error in C# I have installed Async-CTP-v3 for using new feature of C# 5 but when I tried to run a console application using async keyword/await expression this error appeared:
"A Project with an output type of Class Library cannot be started directly.
In order to debug this project, add an executable project to this solution which references the library project.  Set the executable project as the startup project."
Is there anyone can help me?
Thanks.

A: Your project's output type is almost certainly set to "Class Library".
You can change the Project's Output type by right-clicking on your project in Solution Explorer and selecting properties in the context menu.
Here you can choose the Output type from a drop-down menu. Change your project's output type from "Class Library" to "Console Application"
If that does not work, double check your startup project and make sure it's the project you think it is (and should be).


text:
Q: Why does Mjolnir fall down in Age of Ultron but not in Endgame? In a scene in Avengers: Age of Ultron, we saw Quicksilver trying to take Mjolnir during its flight and suddenly the hammer fell, taking with it Quicksilver to the ground.

But in Avengers: Endgame,

 Spider-Man grabs the hammer in flight with his web and the hammer continue its flight without falling.

Is he worthy? Is it because he didn't really touch the hammer? Or is it the will of Thor which maintains the hammer in flight? Or anything else?!

A: Spider-Man does not grab the hammer in flight. He webs it as it flies by, and it pulls him along. He isn't physically trying to wield it (by grabbing the handle).
It can be seen quickly here:

Without an actual screen cap from the movie, I present you with this video.

A: No.
Take note, Quicksilver was running so fast he basically stopped time. He didn't catch Mjolnir mid-air, but rather tried to hold and wield it.
Spider-Man, on the other hand, was in the same time frame as Mjolnir, and just got brought along for the ride.

A: The enchantment placed on Mjolnir by Odin is as follows:

Whosoever holds this hammer, if he be worthy, shall possess the power of Thor.
Thor

Quicksilver tries to wield Mjolnir and seeing as he isn't worthy, at least at this moment in time (he probably is later when he sacrifices himself), it starts to fall to the floor and due to how fast both are travelling he is thrown to the ground and away from it.
It's also worth noting, as Xantec mentions in a comment, that Mjolnir has a similar affect on Hulk in The Avengers to Quicksilver when he grabs onto it. Just Hulk is stronger and manages to keep hold as it falls to the floor.

Spider-Man on the other hand never tried to wield or even touch Mjolnir, he just webs onto it. Therefore, the enchantment's effects don't kick in on him.


text:
Q: coefficients in the expansion of multivariable expression Consider the expansion of the following $N$ variable expression
$$ D_N(z_1,\ldots,z_N)=\prod_{1\leq j<k\leq N}\left(1-\frac{z_j}{z_k}\right)\left( 1-\frac{z_k}{z_j} \right) $$
For example, in the case of $N=3$ we have
$$
\begin{align*}
D_3(z_1,z_2,z_3) & = \left(1-\frac{z_1}{z_2}\right)\left( 1-\frac{z_2}{z_1} \right)  \left(1-\frac{z_2}{z_3}\right)\left( 1-\frac{z_3}{z_2} \right) \left(1-\frac{z_3}{z_1}\right)\left( 1-\frac{z_1}{z_3} \right) = \\
& = 6 -2\frac{z_1}{z_2}-2\frac{z_2}{z_1} -2\frac{z_2}{z_3}-2\frac{z_3}{z_2} -2\frac{z_3}{z_1}-2\frac{z_1}{z_3} + \\
& +2\frac{z_1z_2}{z_3^2} +2\frac{z_3^2}{z_1z_2} +2\frac{z_2z_3}{z_1^2} +2\frac{z_1^2}{z_2z_3} +2\frac{z_3z_1}{z_2^2} +2\frac{z_2^2}{z_3z_1} - \\
& -\frac{z_1^2}{z_2^2} -\frac{z_2^2}{z_1^2} -\frac{z_2^2}{z_3^2} -\frac{z_3^2}{z_2^2} -\frac{z_3^2}{z_1^2} -\frac{z_1^2}{z_3^2}
\end{align*}
$$
It is known that the constant term of $D_N$ is $N!$ (this can be proved using the formula for the Dyson integral). I am interested in finding out if there are any patterns that describe the coefficients of the other (non-constant) terms in the expansion of $D_N$ ?
As an analogy for what I'm hoping to obtain, in the case of the well-kown multinomial expansion
$$ (z_1+z_2+\ldots+z_M)^N $$
the coefficient of any term $z_1^{k_1}z_2^{k_2}\ldots z_M^{k_M}$ can be simply expressed as
$$ \frac{N!}{k_1! k_2!\ldots k_M!} $$

A: Sills and Zeilberger have a paper, Disturbing the Dyson Conjecture (in a GOOD Way), where they talk about precisely what happens when you want to describe other coefficients in your product, other than the constant term. The bad news is that the formulas seem to get very complicated very fast, which makes it unlikely to hope for an elegant uniform formula. The good news is that these coefficients will always satisfy a recurrence relation (exploited by Good in one of the original proofs of Dyson's conjecture) and this can be used to guess and prove a formula for specific coefficient in the product.
As an illustration of this, in the paper Two Coefficients of the Dyson Product, Lv, Xin, and Zhou give formulas for the coefficient of $x_r^2/x_s^2$ and $x_r^2/x_sx_t$.

A: You may play with this method and find formulae for many coefficients. To be more concrete, below I prove using it that the coefficient of $(z_p/z_q)^c$ equals $-(N-c) (N-2)!$ and the coefficient of $z_1^c(z_2\dots z_{c+1})^{-1} $ equals $(-1)^c c! (N-c)!$ for all $c=1,2,\dots,N-1$.
Assume without loss of generality that $c_1\geqslant c_2\geqslant \ldots \geqslant c_N$, $\sum c_i=0$, and we look for $M:=[\prod z_i^{c_i}]\prod_{i<j} (1-z_i/z_j)(1-z_j/z_i)$. We have $$M=\left[z_1^{N-1+c_1}z_2^{N-1+c_2}\ldots z_N^{N-1+c_N}\right]F,\quad F=\prod_{i<j} (z_j-z_i)(z_i-z_j-\lambda_{ij}),$$
for any constants $\lambda_{ij}$.
Denote $A_i=[0,1,\dots,N-1+c_i]$. Look how can it happen that $z_i\in A_i$ and $F\ne 0$. At first, all $z_i's$ must be distinct. Choose all $\lambda_{ij}=1$. Consider the set $Z=\{z_1,\dots,z_N\}\subset A_1$. It consists of several segments of consecutive integer points, and in each segment the indices of corresponding $z_i$'s must increase (else some bracket $z_i-z_j-1$, with $i<j$, does vanish).
If all $c_i$'s are equal to 0, this already implies that $z_i=i-1$, so the RHS of CN formula has unique summand and we get $N!$ formula for the constant term. If $c_1=c>0$, $c_{N}=c_{N-1}=\dots =c_{N-c+1}=-1$, the same choice of $\lambda$'s gives you unique non-zero value, that yields the aforementioned answer $(-1)^c c! (N-c)! $.
Now consider, say, $c_1=c>0$, $c_2=\dots=c_{N-1}=0$, $c_N=-c$, as I said in the beginning. (This includes, in particular, the case $c_1=2,c_{N}=-2$ mentioned in the answer of Gjergji Zaimi.)
It makes sense to change $\lambda$'s: take $\lambda_{iN}=1$ for $i=1,\dots,N-1$; $\lambda_{1j}=c$ for $j=2,3,\dots,N-1$, other $\lambda$'s are equal to 0. We have $z_{N}\leqslant N-1-c$. It implies that $z_{N}+1\notin Z$. Therefore $Z=\{0,1,\dots,N-1\}\cup z_1\setminus (z_N+1)$ and $z_1\in \{N,N+1,\dots,N+c-1\}$. But $z_1-c\notin \{z_2,z_3,\dots,z_{N-1}\}$. It may happen only if $z_1-c=z_N$ or $z_1-c=z_N+1$. But $z_1-c\geqslant N-c\geqslant z_N+1$, thus we must have $z_N=N-1-c$, $z_1=N$, other $z_i$'s form a permutation of $\{0,1,\dots,N-1\}\setminus \{N-c\}$. All permutations give the same contribution to the CN formula, and after careful but straightforward cancellation we get the above answer.


text:
Q: Google App Script + Google Sheet + HTML modal dialog input form - Get values and build email Another Sheets question.
I have an image on my Google Sheet, which runs a script which brings up a modal dialog built on HMTL:
function HomePageFurtherHelp(){

  var ui = SpreadsheetApp.getUi();
  //
  //Call the HTML file and set the width and height
  var html = HtmlService.createHtmlOutputFromFile("Home Page - Further Help")
    .setWidth(1200)
    .setHeight(1400);
  //Display the dialog
  var dialog = ui.showModalDialog(html, " ");
}

My HTML modal dialog window holds a few fields for user input: it's basically a contact information form and there is a "send" button. I have added 'id' parameters to each of my input fields in HTML. The form is just a free to use version that I've added id's into.
My question is: how can I fetch the users' inputted data and then pass it to the send button and send out an email to a preset email address? I have added an 'onclick' parameter to my Send button, I assume I call a function for the email itself inside 'onclick' but I don't know how to build it.

      <input class="w3-input w3-border" name="first" type="text" placeholder="Your Name" id="userName">

      <input class="w3-input w3-border" name="last" type="text" placeholder="Department" id="departmentName">

      <input class="w3-input w3-border" name="email" type="text" placeholder="Email" id="userEmail">

      <input class="w3-input w3-border" name="phone" type="text" placeholder="Project?" id="projectName">

      <input class="w3-input w3-border" name="message" type="text" placeholder="Message" id="userMessage">

<button class="w3-button w3-block w3-section w3-blue w3-ripple w3-padding" onclick="contactSendEmail()">Send</button>

I did find this post: Apps Script: How to Email Google Sheet file to Email Specified in HTML Service Input? but I am getting a bit confused breaking it apart, I am stuck on 'formObj' and using it.
Helping me understand it would be appreciated.
Thanks,

A: I figured this out using formObj, and calling my name parameters as keys - this was the bit I was missing.
This can be closed etc.