Q: How do i break a number down into a percentage (0 - 100%)? Details inside I am using a JS progress bar that is set using a percentage: 0 to 100 (percent). I need the progress bar to reach 100% when 160,000 people have signed a certain form. I have the total number of signers set in a PHP variable but am lost on how to do the math to convert that into a percentage that fits within 1 - 100 (so that the progress bar actually reflects the goal of 160,000).
I may be missing something obvious here (i suck at anything number-related) so does anyone here have a clue as to how to do this?

A: Percentage calculation is basic mathematics:
$total = 160000;
$current = 12345;
$percentage = $current/$total * 100;

A: Just
percentage = number/160000 * 100

A: If N is the goal, and X is the number of people that have signed so far, then the percentage is (X/N)*100.

A: ...you can't convert a number to a percentage?
$percent = ($currentNumber / 160000) * 100;

If you don't want a float answer you can just cast or round it however you'd like.

A: 160,000/160,000 = 1 = 100%
160,000/2 = 0.5 = 50%
Given this, the calculation should be easy. The numerator is the number completed and the denominator is the "goal" -- the total to complete.
So once you are 80,000 you'd be 50% complete and your progress bar would render as such.
If you need to work with smaller numbers, divide everything by 100 or 1000 and you can reduce the size of the numbers in a relevant manor.
160,000 / 1000 = 160  160 would be your denominator.  So than 50% would be 80/160. Does this make sense?

A: Do it Microsoft style:
current = 12345
percentage = 100*(1-exp(-current/100000))


Q: Multitenancy and Partitaioning HI There,
i have to make my application SAAS compliant .For achieving multi tenancy , i was thing of partitioning the data , and each partition will be for a tenant. and this partitioning will be done dynamically .
has anybody done something like this ?
what do you think the better approach be ?
i am using SQL 2005
Regards
DEE

A: There is a limit of 1000 partitions per partition scheme and you can only partition on a single field, so if you intend to multi-tenant beyond 1000 instances you are going to have to jump through a lot more hoops. You can extend the limit by using a partitioned view on top of multiple partitioned tables, but this increases the management overhead. You can use the DMVs and create your own automated system that generates new partitions per client / tenant and manages the problem but it will be specific to your application and not generic.
At present there is no automatic dynamic partitioning in SQL Server, it was mentioned at the PDC09 in relation to the SQL Azure future roadmap, but I did not hear of it for SQL Server.
Your alternative choices are a database or SQL Instance per client, there are benefits to this approach in that you give yourself far more opportunity to scale out if the needed arises, and if you start looking at a larger data centre, you can start balancing the SQL Instances across a farm of servers etc. If you automatically have all the data in a single database.
Other things to take into consideration:
Security: Whilst you have the data in a single database with partitioning, you have no data protection. You risk exposing one client's data to another very trivially with any single bug in the code.
Upgrading: If all the clients access the same database, then the upgrades will be an all or nothing approach - you will not be able to easily migrate some users to a new version whilst leaving the others as they were.
Backups: You can make each partition occupy a separate file group and try manage the situation. Out of the box so to speak, every client's backups are mingled together. If a single client asks for a rollback to a given data you have to plan carefully in advance how that could be executed without affecting the other users of the system.


Q: Using pwelch to a set of signals: some questions (Matlab) I would like to use pwelch on a set of signals and I have some questions.
First, let's say that we have 32 (EEG) signals of 30 seconds duration. The sampling frequency is fs=256 samples/sec, and thus each signal has length 7680. I would like to use pwelch in order to estimate the power spectral density (PSD) of those signals.
Question 1:
Based on the pwelch's documentation,

pxx = pwelch(x) returns the power spectral density (PSD) estimate, pxx, of the input signal, x, found using Welch's overlapped segment averaging estimator. When x is a vector, it is treated as a single channel. When x is a matrix, the PSD is computed independently for each column and stored in the corresponding column of pxx.

However, if call pwelch as follows
% ch_signals: 7680x32; one channel signal per each column
[pxx,f] = pwelch(ch_signals);

the resulting pxx is of size 1025x1, not 1025x32 as I would expect, since the documentation states that if x is a matrix the PSD is computed independently for each column and stored in the corresponding column of pxx.
Question 2:
Let's say that I overcome this problem, and I compute the PSD of each signal independently (by applying pwelch to each column of ch_signals), I would like to know what is the best way of doing so. Granted that the signal is a 30-second signal in time with sampling frequency fs=256, how should I call pwelch (with what arguments?) such that the PSD is meaningful?
Question 3: If I need to split each of my 32 signals into windows and apply pwech to each one of those windows, what would be the best approach? Let's say that I would like to split each of my 30-second signals into windows of 3 seconds with an overlap of 2 seconds. How should I call pwelch for each one of those windows?

A: Here is an example, just like your case,
The results show that the algorithm indicates the signal frequencies just right.
Each column of matrix, y is a sinusoidal to check how it works.
The windows are 3 seconds with 2 seconds of overlapping,
Fs = 256;
T = 1/Fs;
t = (0:30*Fs-1)*T;
y = sin(2 * pi * repmat(linspace(1,100,32)',1,length(t)).*repmat(t,32,1))';
for i = 1 : 32
[pxx(:,i), freq] = pwelch(y(:,i),3*Fs,2*Fs,[],Fs); %#ok
end
plot(freq,pxx);
xlabel('Frequency (Hz)');
ylabel('Spectral Density (Hz^{-1})');


Q: Logging for Custom Code Written in Spark We are writing Scala code for Apache Spark and running the process in Yarn Mode (Yarn Client Mode) in cloudera 5.5. Spark version is 1.5
I need to do logging for this code and want to move logs in Specific Directory for Spark ,outside of noise in spark logs
We are using plain log4j. Dont have time for logging trait for now.
I have changed the default log4j file in ${spark_home} like this
# Set everything to be logged to the console
log4j.rootLogger=ERROR, console
log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.target=System.err
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=%d{yy/MM/dd HH:mm:ss} %p %c{1}: %m%n

# Spark Logs

log4j.appender.aAppender=org.apache.log4j.RollingFileAppender
log4j.appender.aAppender.File=/var/log/aLogger.log
log4j.appender.aAppender.layout=org.apache.log4j.PatternLayout
log4j.appender.aAppender.layout.ConversionPattern=[%p] %d %c %M - %m%n
log4j.appender.aAppender.maxFileSize=50MB
log4j.appender.aAppender.maxBackupIndex=5
log4j.appender.aAppender.encoding=UTF-8

# My custom logging goes to another file
log4j.logger.fsaLogger=ERROR, fsaAppender

This is my Code in scala
This is inside main method
val logger =LogManager.getLogger("aLogger")
 val jobName = "AData"
 logger.warn("jobName ::" +jobName +" Started at ::" +
+Calendar.getInstance().getTime())

  val sc = new SparkContext(conf)
  val sqlContext = new org.apache.spark.sql.hive.HiveContext(sc)
  val sourceDF = sqlContext.read
    .format("com.databricks.spark.avro")
    .load(pathToFiles)

 finalCSMDF.map { row =>
//To remove Serilizable Exception
 var loggers = org.apache.log4j.LogManager.getLogger("aLogger")
 loggers.error("Test Log")
 row
 }

logger.warn("jobName ::" +jobName +" completed at ::" +
+Calendar.getInstance().getTime())

My problem here is that when ever i run this in yarn mode , i find the lines jobName ::" +jobName started" etc in /var/log/aLogger.log but not the  loggers.error("Test Log") which is inside the closure. Basically everything in driver is going in closure but not the exceutioners closures
Please help


Q: Migrating from mongodb to firebase My app currently uses mongodb and I'm looking forward to migrating it to firebase instead.
How easy is it to do and are there things I have to watch out for.

A: Isn't Firebase stores all its data in MongoDB?
Update May 2016
Apparently a page where Firebase was mentioned in MongoDB's site was removed (http://www.mongodb.org/about/production-deployments/)
After some search on their site I've found another page in their blog
https://www.mongodb.com/post/45270275688/mongodbs-growing-ecosystem (mirror)
where they say:

it’s great to see so many companies building on MongoDB. Here are just a few:

*

*Modulus. A Node.js platform as a service (PaaS) offering, Modulus includes MongoDB as its default data store. This follows related offerings from Meteor and Firebase.

An alternative to MongoDB would be RethinkDB and recently the team behind RethinkDB released Horizon, an open-source backend platform on NodeJS and that is kind of a locally hosted Firebase. Here's a nice talk about Horizon.

A: Given that both MongoDB and Firebase are non-relational in nature, most of your data should map to Firebase cleanly. The Firebase REST endpoints support regular JSON, so getting your data in (and, back out if you choose) should also be easy. The main areas you need to keep watch for are:

*

*The Firebase API is realtime/asynchronous in nature; specifically, when clients are reading data. Migrating your backend request/response code to the client and using this approach will probably be the biggest area with regard to level of effort.

*There will also be a disparity in the feature set that MongoDB and Firebase provide; notable areas include Mongo's support for doing things like MapReduce, Cursors, and free-text queries (Firebase doesn't currently support these areas).

The other thing to keep in mind is that Firebase isn't an all-or-nothing type of undertaking. Apps can definitely take advantage of the realtime, scaling, and platform features piecemeal.

A: Not specifically answering the question, but if you find Firebase lacking a few features which you you are used to with Mongo -
I found a node package which will allow you to run both with Firebase as the master DB.
Firebase

*

*Security/Authentication

*Sockets

MongoDB

*

*querying

*indexing

*aggregation

https://www.npmjs.org/package/mongofb


Q: AngularJS : $watch vs. $observe when newValue === oldValue If this is already explained or discussed somewhere, I am very sorry, but I couldn't find this exact problem discussed anywhere.
So I have an angular directive with one data binding 'myvar' (= or @ makes no difference). The value from the data binding is used in the directive: scope.myvarStr = scope.myvar + 'somestring'. Then I bind myvarStr in the template.
Because scope.myvarStr must be modified when scope.myvar changes, I used $watch('myvar', function(...)) to watch the value and update scope.myVarStr when needed. In the watch function I put the classic if (newValue === oldValue) return;
The problems started the very first time $watch fired and the two values were equal; then the view was not updated. I could easily see that from console.log(scope.myvar) on the first line in the link function that scope.myvar was undefined (or '' dependent on binding type) to begin with and that the value had changed to something else when I did a console.log in the $watch.
I googled for an hour or so, and found this: https://github.com/angular/angular.js/issues/11565
However, this issue wasn't discussed anywhere else, so I looked googled more and  came across $observe AngularJS : Difference between the $observe and $watch methods
When I changed from $watch to $observe, all my problems went away and I can still use if(newValue === oldValue) return;.
(function(directives) {
'use strict';

directives.directive('someDir', [function() {
    return {
        restrict: 'E',
        scope: {
            myvar: '=' //or @ didn't matter at the time...
        },
        template: '
{{myvarStr}}
',
        link: function(scope, el, attrs) {

            function toString() {
                if (scope.myvar < 1000) {
                    scope.myvarStr = scope.myvar;
                } else {
                    scope.myvarStr = scope.myvar/1000 + 'k';
                }
            }
            toString();

            scope.$watch('myvar', function(newValue, oldValue) {
                console.log("changed", newValue, oldValue)
                if (newValue == oldValue) return;
                toString();
            },true);

            // When changing to $observe it works :)
            //attrs.$observe('myvar', function(newValue, oldValue) {
            //    console.log("changed", newValue, oldValue)
            //    if (newValue == oldValue) return;
            //    toString();
            //},true);

        }
    };
}]);
}(angular.module('myApp.directives')));

Suggestion: As far as I understand this issue occurs with $watch because the scope value is never changed. It takes a while for the directive to pick up the value, until then the binding is just an empty string or something and when the value is detected the $watch fires but the actual scope value has not changed (or as explained in the first link; the first watch fires when the value 'appears' in the directive).

A: I don't quite understand your suggestion/explanation, but I feel like things are much simpler than you make it appear.
You don't need the newValue === oldValue test, because your watch-action is idempotent and cheap. But even if you do, it only means you need to initialize the value yourself (e.g. by calling toString() manually), which you seem to be doing and thus your directive should work as expected. (In fact, I couldn't reproduce the problem you mention with your code.)
Anyway, here is a (much simpler) working version:
.directive('test', function testDirective() {
  return {
    restrict: 'E',
    template: '
{{ strVal }}
',
    scope: {
      val: '='
    },
    link: function testPostLink(scope) {
      scope.$watch('val', function prettify(newVal) {
        scope.strVal = (!newVal || (newVal < 1000)) ?
            newVal :
            (newVal / 1000) + 'K';
      });
    }
  };
})

BTW, since you are only trying to "format" some value for display, it seems like a filter is more appropriate (and clear imo), than a $watch (see the above demo):
.filter('prettyNum', prettyNumFilter)
.directive('test', testDirective)

function prettyNumFilter() {
  return function prettyNum(input) {
    return (!input || (input < 1000)) ? input : (input / 1000) + 'K';
  };
}

function testDirective() {
  return {
    template: '
{{ val | prettyNum }}
',
    scope: {val: '='}
  };
}


Q: Responsive dataTable is not working with Bootstrap 4.3.1 I have an issue with the responsive DataTable Plugin and Boostrap 4.3.1 in this specific scenario:
I have an extra large modal which display a table, this table have 3 collapsed columns with some contact information this work as expected:

However in mobile display the table dont collapse the other columns as I would expect, and the table is not wraped inside the modal:

I used the following example at Datatables.net and loaded basically the same files with the exception of Bootstrap which is the version 4.3.1 and not the 4.1.3.
My HTML:

Opciones:

                <button type="button" class="close" data-dismiss="modal">×</button>

                            id
                            Nombre
                            Apellido
                            Departamento
                            Puesto
                            Fecha Creado
                            Extension
                            Telefono
                            Celular
                            Email

                            id
                            Nombre
                            Apellido
                            Departamento
                            Puesto
                            Fecha Creado
                            Extension
                            Telefono
                            Celular
                            Email

                <button type="button" class="btn btn-outline-dark" data-dismiss="modal">Cerrar</button>

My Javascript:
$('#opciones-list').on('click', 'a' ,(e) => {
            $('#modalOpciones').modal('show');
            var tablaEditar=$('#tablaDirectorio').DataTable({
                "destroy": true,
                "responsive":/*{
                    "details": {
                        renderer: function ( api, rowIdx, columns ) {
                            var data = $.map( columns, function ( col, i ) {
                                return col.hidden ?
                                '
'+
                                ''+col.title+':'+'	 '+
                                ''+col.data+'	'+
                                '
' :
                                '';
                            } ).join('');

                            return data ?$('
').append( data ) :false;
                        }
                    }
                }*/true,
                "autoWidth": false,
                "ajax": {
                    "url": 'controller/controller.php',
                    "method": 'POST',
                    data:{accion:'getTabla'}
                },
                "columns": [
                    {"data": "directorio"},
                    {"data": "nombres"},
                    {"data": "apellidos"},
                    {"data": "departamento_nombre"},
                    {"data": "puesto"},
                    {"data": "fechacreado"},
                    {"data": "Extension"},
                    {"data": "Telefono"},
                    {"data": "Celular"},
                    {"data": "Email"}
                ],
                "language":idioma_spanol,
                "columnDefs": [
                    {"className": "dt-center", "targets": "_all"}
                ]
            });
        })

Hope someone can help me on this one !!
Thanks in advice

A: CAUSE
Your table is hidden initially which prevents jQuery DataTables from initializing the table correctly.
SOLUTION
Use the code below to recalculate column widths of all visible tables once modal becomes visible by using a combination of columns.adjust() and responsive.recalc() API methods.
$('#modal').on('shown.bs.modal', function(e){
   $($.fn.dataTable.tables(true)).DataTable()
      .columns.adjust()
      .responsive.recalc();
});

You can also adjust single table by using table ID, for example:
$('#modal').on('shown.bs.modal', function(e){
   $('#example').DataTable()
      .columns.adjust()
      .responsive.recalc();
});

LINKS

*

*jQuery DataTables: Column width issues with Bootstrap tabs - Responsive extension – Incorrect breakpoints.

*Datatable jquery - table header width not aligned with body width

A: Try to wrap the table inside a divand then give it the attribute overflow:auto;


Q: ImageMagick code neeeds to be edited..please CHECK OUT please check my imagemagick code where iam trying to add "size" variable ,but not getting where exactly we need to add size variable just like "color" ,"string"...
$animation = new Imagick();
$animation->setFormat( "gif" );
$color = new ImagickPixel( "blue" );
$color->setColor( "red" );
     $string = "kothi!";
$draw = new ImagickDraw();
$draw->setFont( "arial.ttf" );
for ( $i =0; $i <= 0; $i++ )
{
$part = substr( $string,100, $i);

$animation->newImage( 100, 50, $color);

$animation->annotateImage( $draw, 100, 100, 100, $part );
$animation->setImageDelay( 30 );
}
$draw->setFont( "arial.ttf" );
$animation->newImage( 100, 50, $color);
$animation->annotateImage( $draw, 10, 10, 0, $string );
$animation->setImageDelay( 120 );
header( "Content-Type: image/gif" );
echo $animation->getImagesBlob();

A: bool Imagick::setSize ( int $columns , int $rows )

Sets the size of the Imagick object. Set it before you read a raw image format such as RGB, GRAY, or CMYK.
--php.net


Q: How to pass variable from stimulus-js to view file of Rails? Facing problem
The order of things I want to do is

*

*Open modal from @posts partial

*Enter the posting deadline in the form on modal

*POST the contents of the form to rails action that updates the posting flag to true

When opening the modal in item 1 of above, it will be lost track of the partial post record information, so I'm getting the partial post.id with the stimulus getter, but I'm having trouble embedding that id in the url specified in the form.
Development Env
ruby 3.1.2
rails 7.0.3
importmap-rails 1.1.2
tailwindcss-rails 2.0.10
stimulus-rail 1.0.4
Related source code
_post.html.erb
 <button data-action="click->modal#open" data-modal-id-param=<%= post.id %> class="flex justify-center ml-1 py-2 px-4">
 </button>

modal_controller.js
import { Controller } from "@hotwired/stimulus"

export default class extends Controller {
  static targets = ["modal", "form"]

  open(event) {
    event.preventDefault();

    this.modalTarget.showModal();

    this.modalTarget.addEventListener('click', (e) => this.backdropClick(e));

    this.idValue = event.params

    console.log(this.idValue)

  }

  backdropClick(event) {
    event.target === this.modalTarget && this.close(event)
  }

  close(event) {
    event.preventDefault();

    this.modalTarget.close();

    if (this.hasFormTarget) {
      this.formTarget.reset();
    }
  }
}

_publish_limit_form.html.erb
<dialog class="bg-white shadow-xl w-4/5 md:w-2/5 backdrop:bg-gray-700 backdrop:bg-opacity-50 open:animate-fade-in open:backdrop:animate-fade-in" data-modal2-target="modal">
  <button type="button" data-action="modal#close" class="float-right">
    <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
    </svg>
  </button>
  <%= form_with url: start_to_publish_admin_post_path(????), method: :patch, data: { modal2_target: 'form2'} do |f| %>
// <- Above, I want to embed the id in the specified url by extracting post.id from stimulus.  advice please! ! ->

<%= t('.please_set_publish_limit')%>

      <%= f.datetime_select :publish_limit, { min: Time.zone.now, minute_step: 30, discard_year: true, discard_second: true, start_minite: 30, start_second: 0 }, { class: "leading-none rounded mt-2" } %>
      <%= t('.until') %>

    <%= f.hidden_field :publish_status, value: 'is_publishing' %>

      <%= f.submit 'OK', class: "mt-3 font-bold leading-normal text-white py-4 px-10 bg-blue-700 rounded hover:bg-blue-600 focus:ring-2 focus:ring-offset-2 focus:ring-blue-700 focus:outline-none" %>

  <% end %>
</dialog>

Any advice on what to do would be greatly appreciated.


Q: How do I have the serial monitor of the Arduino show a string a value but only the value is changing? I already have my code to work, I'm just trying to make it look nicer now. Just to give a really short summary on what my device does: Smart parking system that detects cars going in and out of a parking lot and displays how many vacant spots are available or not at the entrance. Right now the output looks like this:
Vacant Spots: 1
Vacant Spots: 1
Vacant Spots: 1
Vacant Spots: 1
Vacant Spots: 0
.
.
.
.
.

This is in the case of when a car is entering so it's decrementing by 1 and it increments when a car leaves since there's a added vacant spot available. What I'm trying to do is have the output look like this:
"
Vacant Spots: 1
"
The only thing I want to change is the numerical value. I don't want a continuous stream of
" Vacant Spots: 1 "s to show at the LCD display for the parking user to see. Is there a way to just clear the serial monitor after the loop ends without having it output a new value below it continuously? I've provided the code for the program. I have 3 xbees (1 coordinator and 2 routers). The two routers dont have code on them and are just sending data to the coordinator. The coordinator is where it receives the data. This is the code for the coordinator:
int readValue = 0;
void setup()
{
  Serial.begin(9600);
}
int vslots = 1;

void loop()
{

  if(Serial.available()>21)
  {
        if(Serial.read() == 0x7E)
        {
          for(int i=0;i<19;i++)
          {
          byte discard = Serial.read(); //Next 18 bytes, it's discarded
          }
          readValue = Serial.read();

            bool flagTrue = false;
            bool flagFalse = false;

            if((readValue == 0) && flagTrue == false ) //EXIT
              {
                flagTrue = true;
                flagFalse = false;
                Serial.print("Vacant Spots: ");
                Serial.println(vslots);
              }
              else if((readValue == 16 && flagFalse == false) && vslots >= 1)
//DECREMENT (CAR ENTERING)
              {
                flagTrue = false;
                flagFalse = true;
                vslots -= 1;
                Serial.print("Vacant Spots: ");
                Serial.println(vslots);
              }

             if((readValue == 18) && flagTrue == false )
              {
                flagTrue = true;
                flagFalse = false;
                Serial.print("Vacant Spots: ");
                Serial.println(vslots);
              }
               else if((readValue == 19 && flagFalse == false) && vslots <= 10)
//INCREMENT (CAR EXITING)
              {
                flagTrue = false;
                flagFalse = true;
                vslots += 1;
                Serial.print("Vacant Spots: ");
                Serial.println(vslots);
               }

         }
   }
}

A: First, you need to understand that Arduino serial terminal is not like a real terminal software It does not support a command sent on UART. So to achieve what you want you will require real terminal software such as putty. Which allows you to make changes by sending character bytes using UART communication.
//ADD these lines before printing on a serial terminal
  Serial.write(27);       // 27 is an ESC command for terminal
  Serial.print("[2J");    // this will clear screen
  Serial.write(27);       // 27 is an ESC command for terminal
  Serial.print("[H");     // move cursor to home
//now print what you want...
  Serial.print("Vacant Spots: ");
  Serial.println(vslots);

For more info and methods you can check this post here. But had tried everything and suggesting to go with putty.

A: The ln suffix in println stands for new line. That means println will "print" the value and a newline.
So as an initial solution you could change from using println to plain print:
Serial.print("Vacant Spots: ");
Serial.print(vslots);  // Note: not println

Then we have to solve the problem of going back to the beginning of the line. to overwrite the old text. This is typically done with the carriate-return character '\r'. If we add it to the beginning of the printout:
Serial.print("\rVacant Spots: ");  // Note initial cariage-return
Serial.print(vslots);  // Note: not println

Then each printout should go back to the beginning of the line, and overwrite the previous content on that line.
To make sure that each line is equally long, you could use e.g. sprintf to format the string first, and then write it to the serial port:
char buffer[32];
// - for left justification,
// 5 for width of value (padded with spaces)
sprintf(buffer, "\rVacant Spots: %-5d", vslots);
Serial.print(buffer);


Q: Can I develop a desktop app in VS2008 that can also run on Mac? What approach? Can I develop a desktop app in VS2008 that can also run on Mac?  What approach?
That is, if I am developing an application (thick client) that runs on a Windows XP/Vista PC, is there an approach to do this such that I could also run it on a Mac?  (e.g. silverlight?)
The kind of things my winforms type app needs includes:

*

*HttpWebRequest / HTTP calls

*Access to underlying Sqlite database (via ADO.net)

*Windows / Dialogs

*System Tray Presence

I'm currently working in VS2008 and using WinForms, so I'm not really across WPF / Silverlight etc.
Thanks

A: I would suggest using Mono for this project, since you're already in Windows Forms.  You'll have difficulty with the database requirement using Silverlight, and WPF will not work at all.

A: Agreed on the Mono front.  I would definitely check out Mono Develop - it's the cross platform Mono IDE.  It's been released for Mac so that may help you port your app (or even develop it!)

A: I would suggest looking into Silverlight 4.0. Beta version is already available. I expect to see release at Mix 2010 (which is March 15-17th).
From what you requested it already supports

*

*HttpWebRequest / HTTP calls

*Windows / Dialogs (kind of)

*System Tray Presence

As for access to underlying Sqlite database (via ADO.net) this can be achieved through RIA Services.
Silverlight supports out of browser mode, and runs both on Window and Mac. IDE is VS 2010, and (probably) Eclipse.


Q: Custom Calendar for sales data aggregated by weeks and months I am struggling with creating Custom Calendar that would allow me to use time intelligence function on data that is already aggregated by weeks and months. The original table with transactions contains over 20M rows, so for performance and space saving reasons the grouping is necessary and I perform it while querying the database in SQL Server. I want to create:

*

*Month vs Same Month Last Year

*Week vs Same Week Last Year

*Year-To-Date vs Last Year Year-To-Date (by Months)

*Year-To-Date vs Last Year Year-To-Date (by Weeks)
My idea was to assign some dummy dates to each row of data, and then create custom calendar that would have each of these dummy dates along with other details. I just cannot figure out the key (how to create dummy date having Year number Month number and Week number - please keep in mind that for example Week 5 of 2020 is  partially in January and partially in February)
Is it possible? Maybe I have to create 2 separate Calendars, one for Weeks and one for Months?

A: Add calculated table:
Calendar =
GENERATE (
    CALENDAR (
        DATE ( 2016,  1,  1 ),
        DATE ( 2020, 12, 31 )
    ),
    VAR VarDates = [Date]
    VAR VarDay = DAY ( VarDates )
    VAR VarMonth =  MONTH ( VarDates )
    VAR VarYear = YEAR ( VarDates )
    VAR YM_text = FORMAT ( [Date], "yyyy-MM" )
    VAR Y_week = YEAR ( VarDates ) & "." & WEEKNUM(VarDates)

    RETURN
        ROW (
            "day"     , VarDay,
            "month"   , VarMonth,
            "year"    , VarYear,
            "YM_text" , YM_text,
            "Y_week"  , Y_week
        )
)

You can customize it. In relation pane connect your Date field of FactTable (which is by week, as you say. This table can have missing dates and duplicate dates, to be precise) to the field Date of the Calendar table (which has unique Date, by day). Then, in all your visuals or measures always use the the Date field of the Calendar table. It is a good practice to hide the field Date in your FactTable.
More explanations here https://stackoverflow.com/a/54980662/1903793


Q: the result weka j48 classifyinstance is not correct I already build a tree to classify the instance. In my tree, there are 14 attributes. Each attribute is discretize by supervised discrete. When I created a new instance, I put the value in this instance and classify it in my tree, and I found the result is wrong. So I debug my program, and I found the value of the instance is not divided into the interval correctly. For example:
value of the instance:0.26879699248120303 is divided into '(-inf-0]'.
Why?

A: Problem solved.I didn't discretize the instance that was to be tested so that the weka didn't know the format of my instance.add the following code:
discretize.input(instance);//discretize is a filter
instance = discretize.output();


Q: Unit test custom IActionResult.ExecuteResultAsync(ActionContext) in ASP.NET Core 2.0 Having the below class
/// <summary>
/// An unsuccessful HTTP result.
/// </summary>
public class UnsuccessfulActionResult : IActionResult, IHttpStatusCodeResult, IErrors
{
    /// <inheritdoc />
    /// <summary>
    /// The HTTP status code.
    /// </summary>
    public HttpStatusCode StatusCode { get; }

    /// <summary>
    /// The corresponding error messages, if any.
    /// </summary>
    public IReadOnlyCollection<string> Errors { get; }

    /// <summary>
    /// The request Transaction ID.
    /// </summary>
    public string TransactionId { get; }

    /// <summary>
    /// Default ctor.
    /// </summary>
    /// <param name="transactionId">The request Transaction ID.</param>
    /// <param name="errors">The corresponding error messages, if any.</param>
    /// <param name="httpStatusCode"></param>
    public UnsuccessfulActionResult(
        string transactionId,
        HttpStatusCode httpStatusCode,
        IReadOnlyCollection<string> errors = null)
    {
        TransactionId = transactionId;
        StatusCode = httpStatusCode;
        Errors = errors ?? new List<string>();
    }

    /// <summary>
    /// Convenient method to create an unsuccessful response model.
    /// </summary>
    /// <param name="statusCode"></param>
    /// <returns></returns>
    protected UnsuccessfulResponseModel CreateResponseModel(int statusCode)
    {
        return new UnsuccessfulResponseModel(TransactionId, statusCode, Errors);
    }

    /// <inheritdoc />
    public virtual Task ExecuteResultAsync(ActionContext context)
    {
        var objectResult = new ObjectResult(CreateResponseModel((int)StatusCode))
        {
            StatusCode = (int)StatusCode
        };

        return objectResult.ExecuteResultAsync(context);
    }
}

I need to test this class to make sure that ActionContext has the response provided in overridden ExecuteResultAsync.
Just started going deep into ASP.NET Core 2.0 and missing some parts, in Web API 2 I would just check the HttpResponseMessage returned in the equivalent method of IHttpActionResult.
Task<HttpResponseMessage> ExecuteAsync(
    CancellationToken cancellationToken
)


Q: I have error while building the angular application Please help me solve this error. I have seen some solutions on stack overflow, but they are not working for me.

*

*Here is the error code
ERROR in ./src/app/remedies/Remedy.model.ts
Module build failed: Error: /Volumes/Prince/MyApp/Angular/health/src/app/remedies/Remedy.model.ts is missing from the TypeScript compilation. Please make sure it is in your tsconfig via the 'files' or 'include' property.
    at AngularCompilerPlugin.getCompiledFile (/Volumes/Prince/MyApp/Angular/health/node_modules/@ngtools/webpack/src/angular_compiler_plugin.js:674:23)
    at plugin.done.then (/Volumes/Prince/MyApp/Angular/health/node_modules/@ngtools/webpack/src/loader.js:467:39)
    at <anonymous>

*

*links that I have tried but not working

*

*Module build failed: Error: index.ts is missing from the TypeScript compilation

*main-aot is missing from the typeScript compilation


Q: How to use GIT in web development team I am trying to implement GIT in my company for web development.
Our current workflow is:

*

*Implementing and testing features on a test server in our environment

*Copy/Paste the files on the production server.

Now I am trying to figure out how I would do this with GIT.
My idea is that the developers should push changes on the local(test) server and when the project is finished the production server will pull the updates.
My question is how the test server will see the git files?
Do you have any recommendations for this approach?

A: I don't think it is a good idea to push to the test server. Since shared repository is usually a bare repository.
It would be best to keep the shared repository somewhere on a third server.
Everyone can push to this server, and you can maintain several branches there if you wish.
The test server pulls the changes before running the test.
Or for a more complete test - it would clone the entire repository fresh each time before test.

A: There are really plenty of approaches to this problem, you should consider read more about "Auto deployment", "GIT + deploy" etc.
Personally I'm using special script to export all the files between specific tags in GIT repository and upload them directly on the server.

A: Take a look on the git workflow(s) modal.
https://www.atlassian.com/git/tutorials/comparing-workflows/
http://nvie.com/posts/a-successful-git-branching-model/
You simply have to figure out which workflow suits you the best and you can grab the most suitable one.
If you choose to use nvie gitworkflow you can customize it to your own needs by modifing teh scripts


Q: Comparing field values using reflection I am trying to compare the field values of two different objects in a generic way. I have a function (seen below) that takes in two Objects and then gets the fields and then compares the fields in a loop and adds the fields to a list if they are not the same - is this the proper way to do this?
public void compareFields(Object qa, Object qa4) throws FieldsNotEqualException
{

  Field[] qaFields = qa.getClass().getFields();
  Field[] qa4Fields = qa4.getClass().getFields();

  for(Field f:qaFields)
  {

    for(Field f4:qa4Fields)
    {
       if(f4.equals(f))
       {
           found = true;
           break;
       }
       else
       {
           continue;
       }
    }
  }

 if(!found)
 {
    report.add(/*some_formatted_string*/) //some global list
    throw new FieldsNotEqualException();
 }
}

I was googling and I saw that C# had like a PropertyInfo Class - does Java have anything like that?
ALSO, is there a way to do like f.getFieldValue() -I know there is no method like this but maybe there is another way???

A: Libraries like commons-beanutils can help you if you want to compare bean properties (values returned by getters) instead of comparing field values.
However, if you want to stick with plain reflection, you should:

*

*Use Class.getDeclaredFields() instead of Class.getFields(), as the latter only returns the public fields.

*Since fields only depend on their class, you should cache the result and keep the fields in a static / instance variable rather than invoking getDeclaredFields() for each comparison.

*Once you have an object of that class (say o), in order to get the value of some field f for that particular object, you need to call: f.get(o).

A: You might check out org.apache.commons.lang.builder.EqualsBuilder which will save you a lot of this hassle if you're wanting to do a field by field comparison.
org.apache.commons.lang.builder.EqualsBuilder.reflectionEquals(Object, Object)

If you're wanting to compare fields yourself, check out java.lang.Class.getDeclaredFields() which will give you all the fields including non-public fields.
To compare the value of the fields use f.get(qa).equals(f.get(qa4))  Currently, you are actually comparing the field instances and not the values.

A: // If you want to have some fields, not all field then use this.
  public boolean compareObject(Object object) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException
{

 String[] compareFields = { "fieldx", "fieldy","fieldz", "field15",
        "field19"}; // list of all we need
for(String s : compareFields) {
Field field = DcrAttribute.class.getDeclaredField(s); // get a list of all fields for this class
    field.setAccessible(true);
    if(!field.get(this).equals(field.get(object))){  //if values are not equal
    return true;
    }

    }

    return false;
}


Q: Usability: How do I provide & easily deploy a (preferably node.js + MongoDB based) server backend for my users? I'm currently planing an application (brainstorming, more or less), designed to be used in small organizations. The app will require syncronization w/ a backend-server, e.g. for user management and some advanced, centralized functionality. This server has to be hosted locally and should be able to run on Linux, Mac and Windows. I haven't decided how I'm going to realize this, mainly I simply don't know which would be the smartest approach.
Technically speaking, a very interessting approach seemed to be node.js + mongoose, connecting to a local MongoDB. But this is where I'm struggeling: How do I ensure that it's easy and convienient for a organization's IT to set this up?
Installing node.js + MongoDB is tedious work and far from standartized and easy. I don't have the ressources to provide a detailled walthrough for every major OS and configuration or do take over the setup myself. Ideally, the local administrator should run some sort of setup on the machine used as server (a "regular" PC running 24/7 should suffice) and have the system up and running, similar to the way some games provide executables for hosting small game-servers for a couple friends (Minecraft, for instance).
I also thought about Java EE, though I haven't dug into an details here. I'm unsure about whether this is really an option.
Many people suggest to outsource the backend (BaaS), e.g. to parse.com or similar services. This is not an option, since it's mandatory that the backend will be hosted locally.
I'm sorry if this question is too unspecific, but unfortunately, I really don't know where to start.

A: I can give you advice both from the sysadmin's side and the developers side.
Sysadmin
Setting up node.js is not a big task. Setting up a MongoDB correctly is. But that is not your business as an application vendor, especially not when you are a one man show FOSS project, as I assume. It is an administrators task to set up a database, so let him do it. Just tell them what you need, maybe point out security concerns and any capable sysadmin will do his job and set up the environment.
There are some things you underestimate, however.
Applications, especially useful ones, tend to get used. MongoDB has many benefits, but being polite about resources isn't exactly one of them. So running on a surplus PC may work in a software development company or visual effects company, where every workstation has big mem, but in an accountant company your application will lack resources quite fast. Do not make promises like "will run on your surplus desktop" until you are absolutely, positively sure about it because you did extensive load tests to make sure you are right. Any sensible sysadmin will monitor the application anyway and scale resources up when necessary. But when you make such promises and you break them, you loose the single most important factor for software: the users trust. Once you loose it, it is very hard to get it back.
Developer
You really have to decide whether MongoDB is the right tool for the job. As soon as you have relations between your documents, in which the change of of document has to be reflected in others, you have to be really careful. Ask yourself if your decision is based on a rational, educated basis. I have seen some projects been implemented with NoSQL databases which would have been way better of with a relational database, just because NoSQL is some sort of everybody's darling.
It is a FAR way from node.js to Java EE. The concepts of Java EE are not necessarily easy to grasp, especially if you have little experience in application development in general and Java.
The Problem
Without knowing anything about the application, it is very hard to make a suggestion or give you advice. Why exactly has the mongodb to be local? Can't it be done with a VPC? Is it a webapp, desktop app or server app? Can the source ode be disclosed or not? How many concurrent users per installation can be expected? Do you want a modular or monolithic app? What are your communication needs? What is your experience in programming languages? It is all about what you want to accomplish and which services you want to provide with the app.

A: Simple and to the point: Chef (chef solo for vagrant) + Vagrant.
Vagrant provides a uniform environment that can be as closed to production as you want and Chef provides provisioning for those environments.
This repository is very close to what you want: https://github.com/TryGhost/Ghost-Vagrant
There are hundreds of thousands of chef recipes to install and configure pretty much anything in the market.


Q: Sending FILE to a External API REST from Django I'm trying to send a file from a DJANGO FORM to an API REST service, if i send only the text it works but i need to send a file an i tried all that i found but i doesn't work.
This is my form:
class Publicacion(forms.Form):

publicacion = forms.CharField(label=False,  widget=forms.Textarea(attrs={'rows': '3', 'cols': '40'}))
imagen = forms.FileField(required=False)

This is the html of that form:
            <form name="publicion" enctype="multipart/form-data" id="publicacion" method="POST">{% csrf_token %}
            <div class="post post_form" style="padding:0;">
                {{ formpublicar|crispy }}
                <button class="post_form_extra"></button>
                <input value=" " type="submit" class="post_form_submit" name="publicar"/>
            </div>

            </form>

and this is my views.py method:
def sesionactiva(request):
if 'token' in request.session:
    token = request.session['token']
    crearpublicacion = Publicacion(request.POST or None, request.FILES or None)
    if 'publicar' in request.POST and request.POST['publicar']:
        if crearpublicacion.is_valid():
            publicacion_data = crearpublicacion.cleaned_data
            publicaciontexto = publicacion_data.get("publicacion")
            imgpublicacion = request.FILES['imagen']
            apipublicar = 'http://localhost/apiSocial/publicacion/createPublication'
            payloadpublicacion = {'token': token, 'texto': publicaciontexto, 'imagen': imgpublicacion}
            responsepublicacion = requests.post(apipublicar, data=payloadpublicacion)
            crearpublicacion = Publicacion()

A: You should use requests as such:
requests.post(url, files=files, data=data)


Q: how to remove uiview with animation I added an UIView with some animation by using the following code:
CGRect a = CGRectMake(10,10,295,460);
UIView *customView = [[UIView alloc]initWithFrame:a];
customView.tag=10;
[self.tableView addSubview:customView];

[UIView animateWithDuration:1.0
                 animations:
 ^{
     customView.transform = CGAffineTransformMakeScale(1.0f, 1.0f);
 }
 ];

When I try to remove the UIView with animation, the animation seems not working. The view is just getting removed without any animation.
Here is what I have to remove the UIView with animation:
UIView *removeView=[self.tableView viewWithTag:10] ;

        removeView .transform = CGAffineTransformMakeScale(1.0f, 1.0f);

        [removeView removeFromSuperview];

[UIView animateWithDuration:1.5
                 animations:
 ^{
     removeView .transform = CGAffineTransformMakeScale(0.0f, 0.0f);
 }
 ];

I tried by placing the [UIView animateWithDuration:1.5 ... block before and after the [removeView removeFromSuperview], but none gave me the animation. Kindly help me out in this.

A: [UIView animateWithDuration:1.5 animations:^ {
     removeView.transform = CGAffineTransformMakeScale(0.0f, 0.0f);
} completion:^(BOOL finished) {
     [removeView removeFromSuperview];
}];

A: Some changes:
UIView *removeView=[self.tableView viewWithTag:10] ;

    removeView .transform = CGAffineTransformMakeScale(1.0f, 1.0f);

    [removeView performSelector:@selector(removeFromSuperview) withObject:nil afterDelay:1.5];

    [UIView animateWithDuration:1.5
                     animations:
     ^{
         removeView .transform = CGAffineTransformMakeScale(0.01f, 0.01f);
     }
     ];

Try setting your final transform to something small but nonzero.

A: Try waiting to remove the view until the animation is over:
    [removeView performSelector:@selector(removeFromSuperview) withObject:nil afterDelay:2.0];

A: Try this one, it's worked for me:
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:1.5f];
removeView.transform = CGAffineTransformMakeTranslation(removeView.frame.origin.x,1000.0f + (removeView.frame.size.height/2));
aview.alpha = 0;
[UIView commitAnimations];

A: Refer the following sample from Apple.
[UIView transitionWithView:containerView
           duration:0.2
           options:UIViewAnimationOptionTransitionFlipFromLeft
           animations:^{ [fromView removeFromSuperview]; [containerView addSubview:toView]; }
           completion:NULL];

The above code creates a flip transition for the specified container view. At the appropriate point in the transition, one subview is removed and another is added to the container view. This makes it look as if a new view was flipped into place with the new subview, but really it is just the same view animated back into place with a new configuration.
May be the animation type you need to manage.
Refer:-
https://developer.apple.com/documentation/uikit/uiview/1622574-transition


Q: Express Routes params to define react page components I am learning Express.js, this is my case, i have 2 urls
/security/1

/security/2

The answer to that request will be the following, depending on the answer, the "/security/{id}" will return a Web page that will show and enable a certain number of "elements".
app.get('/security/:id', (req, res) => {
  setTimeout(
    () =>
      res.send({
        access: req.params.id === '1' ? ['EDIT', 'DELETE', 'VIEW', 'ADD'] : ['VIEW'],
      }),
    Math.floor(Math.random() * 2000 + 100)
  );
});

My question is now that i have flagged the elements based on the request parameter, how can i render my react page ( for example index.js ) flagging these elements
I would appreciate any example or code answer helping me to figure it out the approach

A: I did not fully understand your question but you can make request from your frontend React page and based on the result you can render whatever you want.


Q: How do I read in a series of numbers using "Textscan" in MATLAB if the file is mostly text? I have a text file that have a string of 3 numbers that I need to read into MATLAB.
For Example:
#######################
#
#
#    Text Text Text
#
#
#######################

Blah blah blah = ####
Blah blah blah = ####
Blah blah blah = ####
Blah blah blah = ####
Blah blah blah = ####
Blah blah blah = ####

I_NEED_THIS_STRING =  1234.5 6789.0 1234.5 !Comment blah blah blah

I need to read in those 3 numbers into an array.
PLEASE HELP.
Thanks

A: If most of the file is irrelevant to your application, I suggest preprocessing with your favorite scripting language or command line tool to find the relevant lines and use textscan() on that.
e.g., from a shell prompt:
grep ^I_NEED_THIS_STRING infile > outfile

in matlab:
fid = fopen('outfile');
C = textscan(fid, 'I_NEED_THIS_STRING = %f %f %f')
fclose(fid)

See the textscan documentation for more details.

A: An alternative is to use IMPORTDATA to read the entire file into a cell array of strings (with one line per cell), then use STRMATCH to find the cell that contains the string 'I_NEED_THIS_STRING', then use SSCANF to extract the 3 values from that cell:
>> data = importdata('mostly_useless_text.txt','\n');  %# Load the data
>> index = strmatch('I_NEED_THIS_STRING',data);  %# Find the index of the cell
                                                 %#   containing the string
>> values = sscanf(data{index},'I_NEED_THIS_STRING = %f %f %f')  %# Read values

values =

  1.0e+003 *

    1.2345
    6.7890
    1.2345

If the file potentially has a lot of useless text before or after the line you are interested in, then you may use up a lot of memory in MATLAB by loading it all into a variable. You can avoid this by loading and parsing one line at a time using a loop and the function FGETS:
fid = fopen('mostly_useless_text.txt','r');  %# Open the file
newLine = fgets(fid);                        %# Get the first line
while newLine ~= -1                          %# While EOF hasn't been reached
  if strmatch('I_NEED_THIS_STRING',newLine)  %# Test for a match
    values = sscanf(newLine,'I_NEED_THIS_STRING = %f %f %f');  %# Read values
    break                                    %# Exit the loop
  end
  newLine = fgets(fid);                      %# Get the next line
end
fclose(fid);                                 %# Close the file


Q: Finding text width in jquery I am trying to to calculate text width in px.
I will take a string from html, this string may contain some special characters as well (in this example just a hyphen), and make this string an html content of a div, and calculate string width.
But I am getting strange results.
If there is an better way to get text width, cross-browser!, please let me know.
I have made a fiddle:
http://jsfiddle.net/YaPcP/39/
Thank you!

A: <div> elements are set to span the width of their parent element, so changing the font size will have no effect on its actual width.  Changing your <div> to a <span> should give you what you're looking for.

A: Add float: left; to #holder
#holder which is the test container for width, is defaulting to width: auto;. In other words, it is spanning 100% of the browser window and giving you the mixed results.
You might consider adding white-space: nowrap; as well to #holder should it ever exceed the width of it's container.
Updated fiddle

A: It may look nasty but gives you the width:
http://jsfiddle.net/adaz/YaPcP/43/


Q: Is there any way to get smart sheet rows based on column value I want to use smart sheet api to read sheet data. my sheet has changedtm column. I want to fetch rows which are greater than certain date. is there any way to do this using smart sheet API

A: You can't do this kind of filtering via the Smartsheet API exactly. One approach would be you could do a GET Sheet request and use the columnIds query string parameter to provide the id number of the specific column you are looking to review. Then you would get back a response that only contained data for that specific column. The filtering based on the date values would then have to be done by you in your code.
If you will need other data in the rows I would then just do the GET Sheet request to get all of the data in the sheet and do the filtering of the response in your code.


Q: How does node.js handle simultaneous http requests? I am learning node.js, and I am not managing to find a direct  answer to this question. How does node.js deal with HTTP incoming requests, if they come in virtually at the same time? Let's say that one HTTP request comes in at a given time. As a result, the value of a global variable might change. However, at virtually the same time, another request comes in. In order to service the new request, the value of that one global variable is needed, but the code for the first request is still executing. How does node react to this?

A: Node.js processes the request one after the other. There is only one thread.
However, if you for example query the database for some information and pass a callback, while the query is executed, node.js can process new requests. Once the database query is completed, node.js calls the callback and finishes processing the first request.
EDIT:
Simple server example:
var http = require('http');
var numresponses = 0;
http.createServer(function (request, response) {
     res.writeHead(200, {'Content-Type': 'text/plain'});
     res.end('This is response #' + (++numresponses));
}).listen(80);

this server will always print out the number of the request even if two requests happen simultaneously, node will choose one that gets processed first, and both will have different numbers.


Q: LSL Wrapper for pygame Newbie to Python and gaming. Is there an LSL (lab streaming layer) wrapper for pygame? I want to create a game using EEG signals to create a brain computer interface application. Any help will be deeply appreciated. thanks! :)

A: There is a LSL module for Python called pylsl. You should be able to incorporate this into your game loop.
The following code was adapted from this example:
from pylsl import StreamInlet, resolve_stream
import pygame

# first resolve an EEG stream on the lab network
streams = resolve_stream('type', 'EEG')

# create a new inlet to read from the stream
inlet = StreamInlet(streams[0])

# Pygame setup
pygame.init()
size = width, height = 320, 240

screen = pygame.display.set_mode(size)

samples = []
while True:
    # get a new sample (you can also omit the timestamp part if you're not
    # interested in it)

    # Get a sample from the inlet stream
    sample, timestamp = inlet.pull_sample()
    samples.push(sample)

    #TODO: interpolate streamed samples and update game objects accordingly.
    # You'll probably need to keep a few samples to interpolate this data.

    #TODO: draw game
    ...
    pygame.display.flip()

A: Adding another possibility: engineers from the Foundation Campus Biotech Geneva have created a library using LSL for an online paradigm using EEG, called NeuroDecode.
It relies on pylsl and offers a higher-level implementation.
On my fork version, I dropped the (old) decoding functionalities in favor of improvements to the low-level functionalities, e.g. signal acquisition/visualization.
https://github.com/mscheltienne/NeuroDecode


Q: com.google.cloud.datastore.DatastoreException: Unauthenticated. objectify java I have set up objectify v6 and when I try to save an entity I get this exception

com.google.cloud.datastore.DatastoreException: Unauthenticated.
Caused by:
  com.google.datastore.v1.client.DatastoreException: Unauthenticated., code=UNAUTHENTICATED

NOTE: I am only trying to save this entity on localhost.
Here is my code to save entity using objectify:
        Subscriber subscriber = new Subscriber(phone);
        ofy().save().entity(subscriber).now();


Q: SQLPLus Decode if value is not null I have a sqlplus script and if a variable is not null then I want to execute a script and pass the value. If it is null then I want to execute a different script. I have the following:
col scr new_value script
set term off
select decode('&partitions', 'true', 'CreateTablesPartitions', 'CreateTables') scr from   dual;
set term on
@@&script &partitions

Which checks if the variable partitions is true then execute CreateTablePartitions. How do I check if the variable partitions is null?

A: just add null and the value to decode to in your decode string.
select decode('&partitions', 'true', 'CreateTablesPartitions',
              null, 'itsnull', 'CreateTables') scr
from   dual;

so if its null, then the result will be itsnull

A: You can just include null as a recognised value in your decode:
col scr new_value script
set term off
set verify off
select decode('&partitions', null, 'CreateTables',
    'CreateTablesPartitions') as scr from dual;
set term on
@@&script &partitions

... which will run CreateTables if the entered partitions value is null.
But, because you have termout off, you won't see the prompt for the value. You might want to use positional variables (&1 etc.) depending on how you're intending to call this, but assuming you do want to be prompted at run-time, you can either leave termout on and add noprint to the column command (col scr new_value script noprint), which will give some blank lines in the output; or set partitions earlier. You can't use define though because that won't like a null value.
The cleanest approach may be to use accept with its own prompt:
accept partitions prompt "Enter partitions: "

col scr new_value script noprint
set verify off
set term off
select decode('&partitions', null, 'CreateTables',
    'CreateTablesPartitions') as scr from dual;
set term on
@@&script &partitions

With simple dummy scripts to call, e.g. CreateTables.sql:
prompt In CreateTables

... and CreateTablesPartitions:
prompt In CreateTablesPartitions with passed value "&1"

... this gives:
Enter partitions:
In CreateTables

... and:
Enter partitions: Test
In CreateTablesPartitions with passed value "Test"


Q: Eliminate zeroed values in an array with dataweave function In this array of a list of devices, you would need to delete from the array when any item was zeroed out

[
    {
        "valueTotal": "6.50"
    },
    {
        "bread": "001",
        "value": "3.00"
    },
    {
        "milk": "002",
        "value": "3.50"
    },
    {
        "coffe": "003",
        "value": "0.00"
    }
]

A: Assuming you intend to remove the items in the input, whose "value" field is 0 and then get the totalValue. Here is a quick one I have come up with(could be improved).
%dw 2.0
output application/json

//filter the items whose value is zero
var filteredPayload= ((payload [-1 to 1] map (item1, index1) ->
{
      (if (item1.value as Number != 0)  (item1) else null)
}) filter  ($ != {}))

// get the totalValue from the filteredPayload
var totalFilteredPayload = filteredPayload reduce ($.value + $$.value)

---
// simply add both the arrays
filteredPayload ++ [{  "valueTotal": totalFilteredPayload as String }]

A: If by "zeroed out" you mean value = 0 it is just a basic filter operation
payload filter ($.valueTotal? or ($.value as Number != 0))

The condition $.valueTotal? is to make the object with valueTotal pass the check. And the other one is for the value itself.


Q: Background Image Quality Android Development help please.
Can somone tell me how I might increase the quality of background images in my app? I have been using Photoshop where the images look great, then I save for the web as a png...then add it to my app... Then on the phone the image looks a little blurred.
Whats the best way to increase my image quality?

A: I would make sure you're saving it at an adequate resolution. I'm will to bet that "save for web" reduces the resolution to 72 dpi which may not be enough for an android handset.  In photoshop, try bumping the resolution of the final png to something like 300 dpi and see if that makes a difference.  From there you can experiment with different resolutions to figure out what's the smallest value you can use and still have a crisp image.  Alternatively, you could just look for the documented resolution requirements.

A: The apparent quality of your images may also depend in the type of device you are displaying the images on.  For example, if your image is saved as 72px x 72px in your image editor, then displayed with a size defined using 72 scaled pixels (sp) in android on a high pixel-density device, then the OS will stretch the image before display.  As such, the pixel density of the display device can affect the apparent image quality.
You can provide different resolution images for different pixel densities by using the hdpi, mdpi and ldpi folders for drawables.  See these links for more info:

*

*Screens support

*Icon design


Q: Cast arraylist in recyclerview firebase I have an array of data which I am retrieving from firebase. I am using a recyclerview to display the data but my adapter is not working correctly.I tried adding the arraylist in the adapter but this is not working.
It is saying the adapter is not attached and I am having a blank activity.
Any help on this ?
Here are my details.
Modal Class
public class Order {
    private String ProductId;
    private String ProductName;
    private String Quantity;

    public Order() {
    }

    public String getProductId() {
        return ProductId;
    }

    public void setProductId(String productId) {
        ProductId = productId;
    }

    public String getProductName() {
        return ProductName;
    }

    public void setProductName(String productName) {
        ProductName = productName;
    }

    public String getQuantity() {
        return Quantity;
    }

    public void setQuantity(String quantity) {
        Quantity = quantity;
    }

    public Order(String productId, String productName, String quantity) {
        ProductId = productId;
        ProductName = productName;
        Quantity = quantity;
    }

}

Adapter
public class AllOrdersAdapter extends RecyclerView.Adapter<AllOrdersViewHolder> {

    List<Order> myfoods;

    public AllOrdersAdapter(List<Order> myfoods) {
        this.myfoods = myfoods;
    }

    @NonNull
    @Override
    public AllOrdersViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.allorders_layout,parent,false);
        return new AllOrdersViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(@NonNull AllOrdersViewHolder holder, int position) {
        holder.foodname.setText(myfoods.get(position).getProductName());
        holder.foodquantity.setText(myfoods.get(position).getQuantity());
        holder.foodId.setText(myfoods.get(position).getProductId());
    }

    @Override
    public int getItemCount() {
        return myfoods.size();
    }

}

Test Class
public class Test extends AppCompatActivity {

    FirebaseDatabase db;
    DatabaseReference requests;
    RecyclerView lstFoods;
    RecyclerView.LayoutManager layoutManager;
    TextView food_id,food_quan,food_name;
//    List foods = new ArrayList<>();
//    RecyclerView.Adapter<AllOrder> adapter;
//    List<String> myOrders = new ArrayList<String>();

//    ArrayList<String> foods=new ArrayList<>();
    List<String> myfoods = new ArrayList<String>();
    AllOrdersAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test);
        //firebase
        db = FirebaseDatabase.getInstance();
        requests= db.getReference().child("Requests");

        lstFoods = (RecyclerView)findViewById(R.id.lstAllFoods);
        lstFoods.setHasFixedSize(true);
        layoutManager = new LinearLayoutManager(this);
        lstFoods.setLayoutManager(layoutManager);

        loadOrderss();

    }
    private void loadOrderss() {

        requests.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
                    if (postSnapshot.getValue() != null) {
//                        List ingredients = new ArrayList<>();
                        for (DataSnapshot ing : postSnapshot.child("foods").getChildren()) {
//                            String data = String.valueOf(postSnapshot.getValue(Order.class));
                            myfoods.add(ing.child("quantity").getValue(String.class));
                            myfoods.add(ing.child("productName").getValue(String.class));
                            myfoods.add(ing.child("productId").getValue(String.class));
//                            myfoods.add(String.valueOf(Order.class));
                            System.out.println("Gained data: " + ing.child("productName").getValue(String.class));

                        }

                    }
                }
                adapter = new AllOrdersAdapter((ArrayList<String>) myfoods);
                lstFoods.setAdapter(adapter);
               adapter.notifyDataSetChanged();
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        });
            }

A: There seems to be a couple things wrong with the code. As it is posted I would be surprised if it compiles.
In your Adapter you have:
List<Order> myfoods;

and
public AllOrdersAdapter(List<Order> myfoods) {
    this.myfoods = myfoods;
}

but in your activity code you pass:
adapter = new AllOrdersAdapter((ArrayList<String>) myfoods);

one is a ArrayList of String the other of Order !
You also need to change your adapter class to something like:
public class AllOrdersAdapter extends RecyclerView.Adapter<AllOrdersAdapter.AllOrdersViewHolder> {
    private static final String TAG = AllOrdersAdapter.class.getSimpleName();

    private ArrayList<Order> mData;

    public class AllOrdersViewHolder extends RecyclerView.ViewHolder {
        public TextView mTvFoodname;
        public TextView mTvFoodQuantity;
        public TextView mTvFoodId;

        public AllOrdersViewHolder(View v){
            super(v);
            // TODO:  You need to assign the appropriate View Id's instead of the placeholders ????
            mTvFoodQuantity = v.findViewById(R.id.????);
            mTvFoodname = v.findViewById(R.id.????);
            mTvFoodId = v.findViewById(R.id.????);
        }
    }

    public AllOrdersAdapter(ArrayList<Order> data){
        this.mData = data;
    }

    @Override
    public AllOrdersViewHolder onCreateViewHolder(ViewGroup parent, int viewType){
        View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.business_list_card_view, parent, false);
        return new AllOrdersViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(final AllOrdersViewHolder holder, final int position){
        //TODO: You need to decide whether you want to pass a string or order object
        Order data = mData.get(position);

        final String name = data.getProductName();
        final String quantity = data.getQuantity();
        final String id = data.getProductId();

        holder.mTvFoodname.setText(name);
        holder.mTvFoodQuantity.setText(quantity );
        holder.mTvFoodId.setText(id)
    }

    @Override
    public int getItemCount(){
        return mData.size();
    }
}

Note: That since I can not know, whether an ArrayList of String or of Order should be used the parameters in either the Activity or Adapter will need to be changed. Also how you assign the data to the RecyclerView will be affected in the onBindViewHolder method.
You should also follow the advice given by Frank.

EDIT
Change your onDataChange() method to this:
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
    for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
        if (postSnapshot.getValue() != null) {
            List ingredients = new ArrayList<>();
            for (DataSnapshot ing : postSnapshot.child("foods").getChildren()) {
                String name = ing.child("productName").getValue(String.class);
                String quantity = ing.child("quantity").getValue(String.class);
                String productId = ing.child("productId").getValue(String.class);
                // Using your overloaded class constructor to populate the Order data
                Order order = new Order(productId, name, quantity);

                // here we are adding the order to the ArrayList
                myfoods.add(order);
                Log.e(TAG, "Gained data: " + name)
            }
        }
    }
    adapter.notifyDataSetChanged();
}

In your Activity you will need to change the ArrayList class variable "myfoods" to this:
ArrayList(Order) myfoods = new ArrayList<>();
and in your onCreate() method you can now change:
adapter = new AllOrdersAdapter((ArrayList<String>) myfoods);

to simply this:
adapter = new AllOrdersAdapter(myfoods);

Also notice that I have made some changes in my original code above.

A: You'll want to create the adapter, and attach it to the view, straight in onCreate:
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_test);
    //firebase
    db = FirebaseDatabase.getInstance();
    requests= db.getReference().child("Requests");

    lstFoods = (RecyclerView)findViewById(R.id.lstAllFoods);
    lstFoods.setHasFixedSize(true);
    layoutManager = new LinearLayoutManager(this);
    lstFoods.setLayoutManager(layoutManager);

    adapter = new AllOrdersAdapter((ArrayList<String>) myfoods);
    lstFoods.setAdapter(adapter);

    loadOrders();
}

This also means you should declare myfoods as a ArrayList<String>, which saves you from having to downcast it. Something like:
ArrayList<String> myfoods = new ArrayList<String>();

Now in loadOrders you simple add the items to the list, and then notify the adapter that its data has changed (so that it repaints the view):
private void loadOrders() {
    requests.child("foods").addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
                for (DataSnapshot ing: postSnapshot.getChildren()) {
                    myfoods.add(ing.child("quantity").getValue(String.class));
                    myfoods.add(ing.child("productName").getValue(String.class));
                    myfoods.add(ing.child("productId").getValue(String.class));
                }
            }
           adapter.notifyDataSetChanged();
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {
            throw databaseError.toException(); // don't ignore errors
        }
    });
  }


Q: How to set the default icon for apps in registry using Exe? I created the installer using NSIS. Everything working fine but default
    icon not setting to the particular files.
   WriteRegStr HKCR "Myapp\DefaultIcon" "" "$INSTDIR\Myexe,1"

I need to set default icon by using my Exe not by using icon file

A: You need to provide the full path. If you want the first icon in your .exe then you don't need a icon index:
RequestExecutionLevel Admin

Section
WriteRegStr HKCR ".foo" "" "foofile" ; .foo file extension
WriteRegStr HKCR "foofile\DefaultIcon" "" "$INSTDIR\MyApp.exe"
SectionEnd

Other icons need a icon index:
WriteRegStr HKCR "MyProgId\DefaultIcon" "" "$INSTDIR\MyApp.exe,1"


Q: How to exclude a Java Object Property as part of JSON String? I have a Java POJO. Few properties are there along with a list<>. While converting this object to JSON String, I want to exclude the list property,
So what annotation to use for that?
public class StudentResultSummary {
    private String totMarks;
    private String avgMarks;
    private List<StudentResult> resultList = new ArrayList<StudentResult>();
}

Convert to JSON:
StudentResultSummary resultSummary = new StudentResultSummary();
Json json = new Json();
policySummary = json.encode(resultSummary);

How can I make sure the field resultList is not included as part of the JSON response?

A: From Chris Seline's answer:

Any fields you don't want serialized in general you should use the
  "transient" modifier, and this also applies to json serializers (at
  least it does to a few that I have used, including gson).
If you don't want name to show up in the serialized json give it a
  transient keyword, eg:
private transient String name;

A: If You don't want to that column in response json you can use @JsonIgnore
and if you don't want to that field in table you should use @Transient
 @Transient
    private String password_key_type;

    @JsonIgnore
    public int getUser_id()
    {
    return user_id;
    }


Q: Converting spectral data for given Observer/Illuminant to another Observer/Illuminant I'm working on a simple Measuring Software for HunterLab (Color) instruments (EZ line) (screenshot here) and I hope someone can help out here.
They deliver spectral data from 400nm...700nm by 10nm using a D65 light source and 10° Observer.
I have the observer functions for ASTM D65 which work great and I can reproduce any value from the instrument 1:1, as long as i measure in D65, 10° (converting to XYZ and then CIELab using tristimulus references for perfect reflecting diffuser).
That was done mostly using algorithms from brucelindbloom.com and easyrgb.com, both have some great information!
Now I want to add the ability to convert the spectral data to another observer or another illuminant (or both). But I cant wrap my head around how to do that.
I guess some directions would be enough but I dont know if I would need even more references for that (references for illuminants by wavelength?) or if its done by some other means.

A: OK, here is the answer :)
Spectral data from most spectrophotometers is already corrected in so far that the hardware illuminant and angle dont matter.
What you do is just use the observer functions for every single angle/illuminant, as written in ASTM E308, to convert the spectral data to XYZ instead of only using the table which corresponds to the hardware illuminant/angle.
Thats a lot of reference values but it works perfect.


Q: PageMethods and UpdatePanel I have a page hierarchy as the following

I want to execute a PageMethod if I click the 'SAVE' button, so I coded like the following
On Button Click I called
OnClientClick="return btnSaveAS_Clicked()"

Called the following on PageLoad of the inner user control
private void RegisterJavaScript()
{
    StringBuilder jScript = new StringBuilder();
    jScript.Append("<script type='text/javascript'>");
    jScript.Append(@"function btnSaveAS_Clicked() {
        var txtConditionName = document.getElementById('" + txtConditionName.ClientID + @"').value;
        PageMethods.Combine('hello','world', OnSuccess);
        function onSuccess(result)
        {
            alert(result);
        }
    }");
    jScript.Append("</script>");

    Page.ClientScript.RegisterStartupScript(this.GetType(), "conditions_key", jScript.ToString());
}

Coded page method as
[WebMethod]
public static string Combine(string s1, string s2) {
  return s1 + "," + s2;
}

But it gives the following error...

A: You cannot define page methods in ascx pages. You have to define them in your web form. If you want to have a page method, defined in your user control, you'd have to define a forwarding page method in you aspx page like below (source):
in user control:
[WebMethod]
[ScriptMethod(UseHttpGet = true)]
public static string MyUserControlPageMethod()
{
    return "Hello from MyUserControlPageMethod";
}

in aspx.cs page:
[WebMethod]
[ScriptMethod]
public static string ForwardingToUserControlMethod()
{
    return WebUserControl.MyUserControlMethod();
}

and in aspx page:
 function CallUserControlPageMethod()
 {
     PageMethods.ForwardingToUserControlPageMethod(callbackFunction);
 }

Alternatively, you could use ASMX services and jquery ajax methods (jQuery.ajax, jQuery.get, jQuery.post) to call your methods asynchronously (sample).
Another option would be defining http handlers and call them via jQuery as well (tutorial).


Q: In Google BigQuery, how to get storage size of a partition in time-partitioned table? I can query for storage size of a table in BigQuery using SELECT size_bytes FROM dataset.__TABLES__ WHERE table_id='mytable', but this only works for finding total size of table. How to get size of a specific partition from a time-partitioned table, for example I want to find out how much data is stored in mytable$20180701.
I know I can for example copy that partition to a non-partitioned table and use the method above, but I feel this can't be the right method.

A: You can use dryRun for this - or in UI just type SELECT * FROM mytable$20180701 and see in Validator how much bytes will be processed - this is the size of the table


Q: cv has no member CAP_PROP_POS_FRAMES I'm trying to run a bit of code to add trackbars onto some video, it's from the Learning OpenCV Second Edition book, but I can't compile my code and gives the error "namespace cv has no member CAP_PROP_POS_FRAMES"
Here's the first bit of the code
#include <opencv2\highgui\highgui.hpp>
#include <opencv2\imgproc\imgproc.hpp>
#include <iostream>
#include <fstream>

using namespace std;

int g_slider_position = 0;
int g_run = 1, g_dontset = 0; //start out in a single step mode
cv::VideoCapture g_cap;

void onTrackbarSlide(int pos, void *) {
    g_cap.set(cv::CAP_PROP_POS_FRAMES, pos);
    if(!g_dontset)
        g_run = 1;
    g_dontset = 0;
}

A: It's CV_CAP_PROP_POS_FRAMES (note the S) and it should be brought in by highgui.hpp.  It's an unnamed enum in the global namespace.


Q: Is it possible to sync an azure repo with MWAA (Amazon Workflows for Apache Airflow)? I have set up a private MWAA instance in AWS. It has set up a bucket that stores DAGs in S3.
I've created a private repository in Azure DevOps and have set up a role that can access this bucket.
With Azure-Pipelines is it possible to sync the entire repository to control the DAGs created/modified in that S3 bucket?
I've seen it's possible to create artefacts and push them to the S3 bucket, but what if a dag is deleted? The DAG will still persist in the S3 Bucket and will still be available in MWAA.
Any guidance will be appreciated.

A: If you just want to sync entire repository to S3 bucket,you can use the task Amazon S3 Upload in your azure pipeline.

I'm not sure if that will fully address your problem, though.
If there is any misunderstanding, please feel free to add comments related to your issue.


Q: Xcode skips if else statement my if else statement checks whether some text fields are empty and if so pops an alert. However xcode even if going through everything, moves on to other functions.
There is an if statement which checks the value of a segmented control and accordingly checks some text fields.
@IBAction func calc(_ sender: Any) {

    // Check if dilution text field is empty
    let dilutiontext = self.dilution.text
    if (dilutiontext?.isEmpty ?? true) {
        Alert.showAlert(on: self, with: "Empty Fields", message: "Dilution field is empty")
    }
    if choose.selectedSegmentIndex == 0 {

        if (self.number1.text?.isEmpty) ?? true || self.number2.text?.isEmpty ?? true || self.number3.text?.isEmpty ?? true || self.number4.text?.isEmpty ?? true {
            Alert.showAlert(on: self, with: "Empty Fields", message: "Number 1-4 fields should not be empty")
        } else {
            performSegue(withIdentifier: "turner", sender: self)
        }
    } else {
        if (self.number1.text?.isEmpty) ?? true || self.number2.text?.isEmpty ?? true || self.number3.text?.isEmpty ?? true || self.number4.text?.isEmpty ?? true || self.number5.text?.isEmpty ?? true || self.number6.text?.isEmpty ?? true || self.number7.text?.isEmpty ?? true || self.number8.text?.isEmpty ?? true {
            Alert.showAlert(on: self, with: "Empty Fields", message: "Number 1-8 fields should not be empty")
        } else {
            performSegue(withIdentifier: "turner", sender: self)
        }
    }

}

I have another file alert.swift which controls the alerts:
import Foundation
import UIKit

struct Alert {
    public static func showAlert(on vc: UIViewController, with title: String, message: String) {
        let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
        vc.present(alert, animated: true)
    }
}

EDIT:
Previously self.dilution.text?.isEmpty and now let dilutiontext = self.dilution.text with dilutiontext?isEmpty
I commented out the prepare for segue function and surprisingly the alerts started working. I still need that function and the alerts working though. Here is the function:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

    var vc = segue.destination as! SecondViewController

    if choose.selectedSegmentIndex == 0 {
        vc.n1 = Int(number1.text!)!
        vc.n2 = Int(number2.text!)!
        vc.n3 = Int(number3.text!)!
        vc.n4 = Int(number4.text!)!
        vc.dil = Int(dilution.text!)!
        vc.cn = Int(choose.selectedSegmentIndex)

    } else {
        vc.n1 = Int(number1.text!)!
        vc.n2 = Int(number2.text!)!
        vc.n3 = Int(number3.text!)!
        vc.n4 = Int(number4.text!)!
        vc.n5 = Int(number5.text!)!
        vc.n6 = Int(number6.text!)!
        vc.n7 = Int(number7.text!)!
        vc.n8 = Int(number8.text!)!
        vc.cn = Int(choose.selectedSegmentIndex)
        vc.dil = Int(dilution.text!)!
    }

}

When I run it, instead of showing the alerts (which check if a text field is empty) it continues to the segue function and displays Unexpectedly found nil while unwrapping an Optional value, which is expected

A: Obviously neither the "if" nor the "else if" condition are true then. Add
let dilutiontext = self.dilution.text
let celltext = self.cell.text

then set a breakpoint and examine the values.

A: Clearly the alerts were skipped if one of the if conditions in the segue function was true. So if there was something that would initially make the statements false and then after going through the alerts it would make them true, the problem would be solved.
Therefore I made two more functions each for the if and if else statements in the segue func.
func option1() -> Bool {
    if (self.number1.text?.isEmpty) ?? true || self.number2.text?.isEmpty ?? true || self.number3.text?.isEmpty ?? true || self.number4.text?.isEmpty ?? true || self.dilution.text?.isEmpty ?? true || !(self.number5.text?.isEmpty ?? true) || !(self.number6.text?.isEmpty ?? true) || !(self.number7.text?.isEmpty ?? true) || !(self.number8.text?.isEmpty ?? true) {
        return false
    } else {
        return true
    }
}

func option2() -> Bool {
    if (self.number1.text?.isEmpty) ?? true || self.number2.text?.isEmpty ?? true || self.number3.text?.isEmpty ?? true || self.number4.text?.isEmpty ?? true || self.number5.text?.isEmpty ?? true || self.number6.text?.isEmpty ?? true || self.number7.text?.isEmpty ?? true || self.number8.text?.isEmpty ?? true || self.dilution.text?.isEmpty ?? true {
        return false
    } else {
        return true
    }
}

which checked if all the conditions were true and if so returned true, so that the program could move on to the segue func.
The segue would check whether the conditions were true, if not, it would go through the alerts-therefore making the option1() or option2() return true- and so the if conditions in the segue func would be true for the program to continue.
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

    var vc = segue.destination as! SecondViewController

    if option1() == true {
        vc.n1 = Int(number1.text!)!
        vc.n2 = Int(number2.text!)!
        vc.n3 = Int(number3.text!)!
        vc.n4 = Int(number4.text!)!
        vc.dil = Int(dilution.text!)!
        vc.cn = Int(choose.selectedSegmentIndex)

    } else if option2() == true {
        vc.n1 = Int(number1.text!)!
        vc.n2 = Int(number2.text!)!
        vc.n3 = Int(number3.text!)!
        vc.n4 = Int(number4.text!)!
        vc.n5 = Int(number5.text!)!
        vc.n6 = Int(number6.text!)!
        vc.n7 = Int(number7.text!)!
        vc.n8 = Int(number8.text!)!
        vc.cn = Int(choose.selectedSegmentIndex)
        vc.dil = Int(dilution.text!)!
    }

}


Q: Codebehind is not calling through ajax In the below code i have a dropdown in which when i select a value in dropdown it should move to the method in codebehind and perform the operation.In my case it is not moving to the codebehind .My aim is to make dropdown a dependent pls help me to solve the issue.
Code:
<asp:DropDownList ID="cbField" runat="server" onfocus="setFocus()" CausesValidation="true">
             </asp:DropDownList>

Ajax:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js" type="text/javascript"></script>
      <script type ="text/javascript">
          $(document).ready(function () {
              $('#<%=cbField.ClientID %>').click(function () {
                  $.ajax({
                     type: "POST",
                     url: "GmasField.ascx/cbField_Dependent",
                      data: "{}",
                      contentType: "application/json; charset=utf-8",
                    dataType: "json",
                     async: true,
                     cache: false,
                     success: function (msg) {
                         $('#myDiv').text(msg.d);
                    }
               })
               return false;
             });
         });
     </script>

A: You didn't mention it but have you added the WebMethodAttribute to the method you have defined on the code behind?
You seem to have a method in the code-behind called cbField_Dependent()
So just add the attribute like the first line below I think.
[WebMethod]
public void cbField_Dependent() {
  //
}

A: Follow this article, this show step by step method to call web method.
http://www.c-sharpcorner.com/UploadFile/63e78b/call-an-Asp-Net-C-Sharp-method-web-method-using-jquery/


Q: Trouble clearing spinner data android I have a problem with my spinners in my android app. I have two spinners implemented. Both loads contents from json. The first one look as,
    // Code for First spinner
    loc = json.getJSONArray("location");
    for(int i = 0; i < loc.length(); i++){
        JSONObject c = loc.getJSONObject(i);
        //put json obkject on variable
        String l = c.getString("stock_location");
        locationList.add(l);
    // Set Spinner Adapter
    location.setAdapter(new ArrayAdapter<String>OfferedDiesel.this,android.R.layout.simple_spinner_dropdown_item,locationList));
    // Spinner on item click listener
    location.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
    @Override
    public void onItemSelected(AdapterView<?> arg0,View arg1, int position, long arg3) {
        place = locationList.get(position);
        selected = place;
        new LoadProduct().execute();
        product_title.setVisibility(View.VISIBLE);
        product.setVisibility(View.VISIBLE);
    }

    @Override
   public void onNothingSelected(AdapterView<?> arg0) {
         place = null;

   }
   });
   }

//Following is the LoadProduct
private class LoadProduct extends AsyncTask<String, String, JSONObject> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(OfferedDiesel.this);
            pDialog.setMessage("Loading Product ...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
         }
        @Override
        protected JSONObject doInBackground(String... args) {
            UserFunctions userFunction = new UserFunctions();
            JSONObject json = userFunction.getProductFromLocation(selected);
            return json;
        }

        protected void onPostExecute(JSONObject json) {
            if(pDialog.isShowing()){
                pDialog.dismiss();
            }
            // Locate the spinner in activity_main.xml
            /*LOcate site node*/
            try{
                if(json.has("error_msg")){
                    String err = json.getString("error_msg");
                    alert.showAlertDialog(OfferedDiesel.this, "ALert !!", err, null);
                }else{
                    prod = json.getJSONArray("product");

                    for(int i = 0; i < prod.length(); i++){
                        JSONObject d = prod.getJSONObject(i);
                        //put json obkject on variable
                        String k = d.getString("stock_name");
                        productList.add(k);

                        arrayAdapter = new ArrayAdapter<String>(OfferedDiesel.this,android.R.layout.simple_spinner_dropdown_item,productList);
                        // Set Spinner Adapter
                        product.setAdapter(arrayAdapter);
                         // Spinner on item click listener
                        product.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                        @Override
                        public void onItemSelected(AdapterView<?> arg0,View arg1, int position, long arg3) {
                             good = locationList.get(position);

                                  //selected = place;

                                    }

                                    @Override
                                    public void onNothingSelected(AdapterView<?> arg0) {
                                        place = null;

                                    }
                                });
                    }
                }

            }catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }

    }/*End of Spinner Populate*/

Here, whenever I am selecting a new item in above spinner it will execute new LoadProduct().execute(); and on my second spinner I am getting the data but the date are appended. I mean for example if by defalt '1' on my first spiner then at second spinner I will get "First" and when I select '2' (change on first spinner) then I will get "Second" it is appended on 'First' and Hence I get 2 items "First" and "Second" instead of just one i.e'Second'. I now need to clear all the spinner list before loading the new. For both spinners I am using json to load data.
Thanks in advance.

A: I'm going to take a few guesses here about what you are trying to do, because I'm not 100% sure I understood... Here's what I think you are trying to do:

*

*There are two ListViews.

*When you click on the first one, it sets up text in the second one to load.

*It does so via an AsyncTask called LoadProduct.

*selected is used in the LoadProduct to determine what to load.

*You aren't getting quite the results you expect.

Okay, so if I'm right here, I would suggest a few changes.

*

*Pass in the selected value to the AsyncTask.

*Clear the previous adapter from it's values.

*Add the new values.

The AsyncTask should be able to take the input, no problem.

A: You just need to clear array list using clear method before adding new data to array,this would defiantly help you


Q: Read Word ActiveX radio button into vb.net form I'm working on some code to read values in a Word document into a windows form using vb.net.  The word document is designed so that the data to be read in is all contained within content controls.  Here is a sample of my code:
Private Sub ImportWordButton_Click(sender As Object, e As EventArgs) Handles ImportWordButton.Click
    Dim oWord As Microsoft.Office.Interop.Word.Application
    Dim oDoc As Microsoft.Office.Interop.Word.Document
    Dim oCC As Microsoft.Office.Interop.Word.ContentControl

    oWord = CreateObject("Word.Application")
    oDoc = oWord.Documents.Open("C:\Temp\PIFFormTest2.docx", [ReadOnly]:=False)

    For Each oCC In oDoc.ContentControls
        Select Case oCC.Tag
            Case "PIFNo"
                NumberBox.Text = oCC.Range.Text
            Case "PIFTitle"
                TitleBox.Text = oCC.Range.Text
            Case "Initiator"
                InitiatorBox.Text = oCC.Range.Text
            Case "PTHealthSafety"
                HealthSafeCheckBox.Checked = oCC.Checked
            Case "PTRegEnviro"
                RegEnvCheckBox.Checked = oCC.Checked

... it goes on.  Some of the content in the Word file is captured with ActiveX radio buttons rather than content controls.  I can't seem to find the correct object for referring to the radio buttons. I've spent significant time searching the web.  Any help is appreciated.

A: I'm working on this too, and it's a nightmare.
For Each f As Field In oDoc.Fields    'notice fields not content controls
    Console.WriteLine(f.OLEFormat.Object.Name) 'notice properties, not methods...
Next

Here's the MSDN reference


Q: Entity framework relationship issue 'Unable to determine the principal end...' I am having two classes, like below
Class One
{
  ID (PK),
  Property 2;
}

Class Two
{
  ID (PK),
  One_ID (FK),
  Nullable_One_ID (FK)
}

While saving I am getting error ' Unable to determine the principal end of the 'x' relationship. Multiple added entities may have the same primary key.'
I tried many combinations WithOutPrincipal and WithOutDependant etc. But no luck, please guide me to the right relationship.

A: Your question is a bit unclear, and you might want to provide more detail, but I suspect that you want only one foreign key property on your class two. Depending on how you're creating these objects, this may also be happening because you're trying to reference an id that's 0, because the object has not yet been saved to the database, so it has not been assigned an id.

A: If you are trying to have 1 to 0 or 1 relationship between class one and class two then  you need to have  primary key and foriegn key same in class 2 and it should be primary key of class one
Class One { ID (PK), Property 2; }
Class Two { One_ID (PK, FK), Nullable_One_ID (FK) }