text:
Q: Output State of comparator circuit for AC signal when open? I am trying to design a circuit which would interface AC signals from pick-up coils.
Below is the circuit.

R4, R3 are for DC bias, and R2 is for feeding that bias to inverting input of the OP amp.
R5 and R8 is for hysteresis regarding noise immunity.
V2 is the input signal.
V1 is power rail.
My question is that how should I determine the state of Vout(18V or 0V) when V2 is open?
I simulated it on CircuitLab. and below is the result
V+ = 8.946 V
V- = 8.955 V
Vout = 1.783 mV
My concern is that V- is higher than V+ only by  9 mV, which I believe is leading Vout to near negative rail(0V).
Can I rely on current circuit for the output to be low always?
Or should I add some kind of pull-up or pull-down resistor for circuit stabilization?
I tried adding pull-up or pull-down resistors to V+ or V- but it prevents the signal from making Vout with 18V peak to Peak.
Below is the link to the circuit i made public
https://www.circuitlab.com/circuit/74bt8h/comparator/

A: To start, eliminate V2, C1, R2 and R5. Then the junction of R3 and R4 will have a Thevenin equivalent voltage of 9 volts, and a resistance of 5k. Adding R5 provides a hysteresis of $$ \Delta v = 18\times \frac{6k}{1.006 M} = .107\text{ volts} =  9 +/- .053\text{ volts} $$ this will also provide a hysteresis at the R2/R3 junction of  $$ \Delta v = 18\times \frac{5k}{1.005 M} = .089\text{ volts}=  9 +/- .045\text{ volts} $$   With V2 still unconnected, the - input will be forced to the value of the R2/R3 junction. Since this is undetermined, the output voltage is undetermined.
Effectively, with V2 disconnected the comparator can be in either state, and there is no a priori way to determine which state that will be.


text:
Q: How to send events to GA4 without any code I am working on a chatbot software where I used this code TestWSC.ga(event, interm_conversion, Greeting_New_User,) to send events to Universal aalytics. But after switching to GA4 this doesnt works anymore. Do any of you have experienced the same? And how to do it with GA4?
I used this code but it didn't worked
gtag('event', 'login', { 'method': 'Google' });

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to set the input tag as enabled?

var startat = 5;
function disableRegBtn(bdisable){
    document.getElementById('regBtn').disabled=bdisable;
}

function showTime(){
    if(startat == 0){
        clearInterval(timeId);
        document.getElementById("p1").innerHTML = "please register now";
        disableRegBtn("enabled");
        return;
        }
    document.getElementById("p1").innerHTML = "please register in  " + startat + "  second(s)";
    startat--;
}
window.onload=function(){
    document.getElementById('taid').readOnly=true;
    disableRegBtn(true);
    timeId=setInterval("showTime()",1000);
}

<textarea id="taid" cols="30" rows="5">Registration Agreement:
1.xxxxxx
2.xxxxxx
3.xxxxxx
</textarea>
<input id="regBtn" type="button" value="register" />

I want to make people read the registration agreement at least 5 seconds before they submit their registration,when 5 second is over,please register now can show in webpage,how to make  <input id="regBtn" type="button" value="register" /> work?
I make some tries for disableRegBtn() in showTime function.
disableRegBtn(false)
disableRegBtn("false")
disableRegBtn("disabled")
disableRegBtn("enabled")

None of them can take effect.

A: your button deleted while doing document.getElementById("p1").innerHTML = "please register in... just add the button again after timeout

var startat = 5;

function disableRegBtn(bdisable) {
  document.getElementById('regBtn').disabled = bdisable;
}

function showTime() {
  if (startat == 0) {
    clearInterval(timeId);
    document.getElementById("p1").innerHTML = '<input id="regBtn" type="button" value="register" />';
    return;
  }
  document.getElementById("p1").innerHTML = "please register in  " + startat + "  second(s)";
  startat--;
}
window.onload = function() {
  document.getElementById('taid').readOnly = true;
  disableRegBtn(true);
  timeId = setInterval("showTime()", 1000);
}
<textarea id="taid" cols="30" rows="5">Registration Agreement:
1.xxxxxx
2.xxxxxx
3.xxxxxx
</textarea>

<input id="regBtn" type="button" value="register" />

A: You do not need to create the button again as it is already in the DOM.
You can use variables to hold the elements so that you can use them when you need them. This will ensure that your code is more clean and robust.
Instead of passing enabled, you can pass flase when the counter is 0. I will also suggest you to use textContent instead of innerHTML when dealing with text only content as it is more faster an predictable.

var startat = 5;
var buttonEl = document.getElementById('regBtn');
var pEl = document.getElementById("p1");
function disableRegBtn(bdisable){
  buttonEl.disabled = bdisable;
  pEl.textContent = '';
  pEl.prepend(buttonEl);
}

function showTime(){
  if(startat == 0){
    clearInterval(timeId);
    pEl.textContent = "please register now";
    disableRegBtn(false);
    return;
  }

  pEl.textContent = "please register in  " + startat + "  second(s)";
  startat--;
}
window.onload=function(){
  document.getElementById('taid').readOnly=true;
  disableRegBtn(true);
  timeId=setInterval("showTime()",1000);
}
<textarea id="taid" cols="30" rows="5">Registration Agreement:
1.xxxxxx
2.xxxxxx
3.xxxxxx
</textarea>
<input id="regBtn" type="button" value="register" />


text:
Q: Line too long in PGI 16.9. How to solve? USe the following dummy code to replicate the issue.
program pp
  implicit none
  real*8,dimension(45) :: refPoints
  refPoints(:) = (/ -1.0 , 1.0 , 1.0 , -1.0 , -1.0 , 1.0 , 1.0 , -1.0 , 0.0 , 1.0 , 0.0 , -1.0 , 0.0 , 1.0 , 0.0 , -1.0 , -1.0 , 1.0 , 1.0 , -1.0 , 0.0 , 1.0 , 0.0 ,-1.0 , 0.0 , 0.0 , 0.0 , 0.0 , 0.0 , 1.0, 1.0, 2.0 , 3.0, 34.0, 35.0, 25.0, 1.0, 50.0, 5.0, 55.0 , 1.0 , 2.0, 3.0, 4.0, 5.0/)

end program pp

PGF90-S-0285-Source line too long (pp.f90: 6)
PGF90-S-0023-Syntax error - unbalanced parentheses (pp.f90: 6)
  0 inform,   0 warnings,   2 severes, 0 fatal for pp

A: 132 columns is limit the F90 standard and going beyond this limit is undefined behavior. While a pain, you'll be better off in the long run by getting your code into compliance by adding continuations.


text:
Q: Scanning log file using ForEach-Object and replacing text is taking a very long time I have a Powershell script that scans log files and replaces text when a match is found. The list is currently 500 lines, and I plan to double/triple this. the log files can range from 400KB to 800MB in size.
Currently, when using the below, a 42MB file takes 29mins, and I'm looking for help if anyone can see any way to make this faster?
I tried changing ForEach-Object with ForEach-ObjectFast but it's causing the script to take sufficiently longer. also tried changing the first ForEach-Object to a forloop but still took ~29 mins.
$lookupTable= @{
'aaa:bbb:123'='WORDA:WORDB:NUMBER1'
'bbb:ccc:456'='WORDB:WORDBC:NUMBER456'
}

Get-Content -Path $inputfile | ForEach-Object {
   $line=$_
   $lookupTable.GetEnumerator() | ForEach-Object {
       if ($line-match$_.Key)
        {
           $line=$line-replace$_.Key,$_.Value
        }
    }
  $line
}|Set-Content -Path $outputfile

A: Since you say your input file could be 800MB in size, reading and updating the entire content in memory could potentially not fit.
The way to go then is to use a fast line-by-line method and the fastest I know of is switch
# hardcoded here for demo purposes.
# In real life you get/construct these from the Get-ChildItem
# cmdlet you use to iterate the log files in the root folder..
$inputfile  = 'D:\Test\test.txt'
$outputfile = 'D:\Test\test_new.txt'  # absolute full file path because we use .Net here

# because we are going to Append to the output file, make sure it doesn't exist yet
if (Test-Path -Path $outputfile -PathType Leaf) { Remove-Item -Path $outputfile -Force }

$lookupTable= @{
    'aaa:bbb:123'='WORDA:WORDB:NUMBER1'
}

# create a regex string from the Keys of your lookup table,
# merging the strings with a pipe symbol (the regex 'OR').
# your Keys could contain characters that have special meaning in regex, so we need to escape those
$regexLookup  = '({0})' -f (($lookupTable.Keys | ForEach-Object { [regex]::Escape($_) }) -join '|')

# create a StreamWriter object to write the lines to the new output file
# Note: use an ABSOLUTE full file path for this
$streamWriter = [System.IO.StreamWriter]::new($outputfile, $true)  # $true for Append

switch -Regex -File $inputfile {
    $regexLookup {
        # do the replacement using the value in the lookup table.
        # because in one line there may be multiple matches to replace
        # get a System.Text.RegularExpressions.Match object to loop through all matches
        $line  = $_
        $match = [regex]::Match($line, $regexLookup)
        while ($match.Success) {
            # because we escaped the keys, to find the correct entry we now need to unescape
            $line  = $line -replace $match.Value, $lookupTable[[regex]::Unescape($match.Value)]
            $match = $match.NextMatch()
        }
        $streamWriter.WriteLine($line)
    }
    default { $streamWriter.WriteLine($_) }  # write unchanged
}

# dispose of the StreamWriter object
$streamWriter.Dispose()


text:
Q: enable & disable a link depending on an event jquery I have a link on the page that i would like to disable when the page loads, when the user clicks on the radio button i would like to enable the link. How would i do so.
Add

<input type="radio" id="enableLink" name="selection" onclick="">

A:     Add

    $('#enableLink').live('click', function() {
       $('#add_link').html('Add');
    });

A: $(function(){
    var isEnabled=false;
    $("#goTo").click(function(e){
       if(!isEnabled)
       {
          e.preventDefault();
       }
    });
    $("#enableLink").click(function(){
        isEnabled=true;
    });
});

Sample : http://jsfiddle.net/HyKL9/2/


text:
Q: Create join model record with accepts_nested_attributes_for I have following models
class User < ActiveRecord::Base
   has_many :project_users, dependent: :destroy
   has_many :projects, through: :project_users
end

class ProjectUser < ActiveRecord::Base
   belongs_to :user
   belongs_to :project
   has_many :participants
   has_many :tasks, through: :participants
end

class Task < ActiveRecord::Base
   belongs_to :project
   has_many :participants
   has_many :project_users, through: :participants
   accepts_nested_attributes_for :participants
end

class Participant < ActiveRecord::Base
   belongs_to :project_user
   belongs_to :task
 end

So the flow should go like this:
1. User creates the project
2. User adds users to project via the join model ProjectUser
3. User creates a task for the project and selects those users from ProjectUsers, who will participate in the task. So I put an accepts_nested_attributes_for method and tried to build the nested form.
In my controller:
 def new
    @task = Task.new
    @task.participants.build
 end

 def task_params
    params.require(:task).permit(:project_id, :project_phase_id, :priority_id, :title,     :due_date, :estimation, :responsible_id, :description, :participant_ids => [])#, :participants_attributes => [:project_user_id, :task_id])
 end

participants_attributes is commented
In my view:
= f.association :participants, as: :select

Actual HTML generated:
 <input name="task[participant_ids][]" type="hidden" value="">
 <select class="select optional form-control" id="task_participant_ids" multiple="multiple" name="task[participant_ids][]">
   <option value="57">AlexandeR MazeiN</option>
   <option value="59">Firenze</option>
   <option value="58">Vasily Strekotkin</option>
 </select>

I add options via ajax, value = ProjectUser.id
I Have to do it like so, because I dont know which ProjectUsers there will be unless a concrete project for a task is selected.
Error I am getting:

Started POST "/tasks" for 127.0.0.1 at 2014-04-11 13:18:24 +0300
  User Load (0.7ms)  SELECT "users".* FROM "users" WHERE "users"."id" = 6 ORDER BY "users"."id" ASC LIMIT 1
Processing by TasksController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"aXuk9ZuDvFZce+sbIQLRhWZlVjitMvySaJ7CwWfdmaQ=", "task"=>{"project_id"=>"20", "priority_id"=>"4", "project_phase_id"=>"40", "title"=>"Skepta", "due_date"=>"", "estimation"=>"8", "responsible_id"=>"6", "participant_ids"=>["", "57", "58"], "description"=>""}, "commit"=>"Create Task"}
  Team Load (0.4ms)  SELECT "teams".* FROM "teams" WHERE "teams"."id" = $1 LIMIT 1  [["id", 3]]
  Participant Load (0.5ms)  SELECT "participants".* FROM "participants" WHERE "participants"."id" IN (57, 58)
Completed 404 Not Found in 7ms

ActiveRecord::RecordNotFound - Couldn't find all Participants with IDs (57, 58) (found 0 results, but was looking for 2):

A: Your param hash has the IDs from ProjectUser as participant_ids, so when it queries the database it is looking for Participant models with these IDs. You need to set these as project_user_id inside of a list of participants, something like this:
participants: [ { project_user_id: 57 }, { project_user_id: 58 } ]

I'm not super familiar with build, but something along these lines should allow AR to properly construct the associations.


text:
Q: Cannot create docker images I try to create a Docker image in the developerWorks organization for an article. Instead of proceeding, or asking me for a container namespace, I get this error:

BXNUI0517E: The attempt to retrieve the container namespace of the org failed because of an internal error with incident ID 238-1457636351.976-5559997. Try again later. If this problem continues, go to Support. For other help options, see the Bluemix Docs.

It has been doing it consistently for three days now. How do I use Docker on Bluemix?

A: In this case you should engage the IBM Containers team to investigate your space. I suggest you to open a support request using one of the following methods:

*

*Use the Support Widget. It is available from the user avatar in the
   upper right corner of the main Bluemix UI.  After opening the support
   widget panel, select Get Help > Get In Touch , select the type of
   assistance you need, and then fill out the support form.

*Use the Support Site 'Get Help' form. This form is available on a separate site that is made available for ticket submission when you cannot log into Bluemix and access the Support Widget.  Go to http://ibm.biz/bluemixsupport and fill in the support request form.

A: Can you check namespace by running the command - "cf ic namespace get"
Also container creation in US/UK regions was not working from March 8. Refer to
https://developer.ibm.com/bluemix/support/#status
RESOLVED: Possible issues with creating IBM Containers on US South and United Kingdom regions
Some users are currently experiencing issues when creating IBM Containers from the Bluemix UI in both US South and United Kingdom regions.
The UI will return a "catalog:createContainer_errorWithIncidentId" error.
The operations team is aware of the issue and is currently working to resolve it.
The IBM Containers CLI is unaffected and can be used as workaround.
Update March 9th 3:30 PM UTC (9:30AM EST): the issue has been addressed and successfully resolved.
Updated:    Mar 9, 2016 9:05 PM UTC+0530
Starts: Mar 8, 2016 4:30 AM UTC+0530
Category:   IBM Containers
Region(s):  eu-gb
us-south

A: if this is the first time that you are using container before creating a container you need to create a namespace in a specific space. I suggest you to create the first container using UI\dashboard and then use that space in Command line plugin (cf ic).
login to bluemix:
- cf api https://api.[REGION].bluemix.net
- cf login  -u your_email -o your_org -s yourspace_where_you_created_first_container
- cf ic login

you can retrieve the namespace for the space issue: cf ic namespace get


text:
Q: Parse error: syntax error, unexpected T_VARIABLE, expecting T_FUNCTION Could someone tell me what I'm doing wrong?
I want to display the users online on specific rooms only.
the code below is the function that calls my online.php this is under my chat.php
when I load the page this function also loads.
function whos_online() {
  if ( window.XMLHttpRequest ) {
    xmlhttp = new XMLHttpRequest();
  } else {
    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
  }
  xmlhttp.open("GET", "online.php?room=<?php $_SESSION['room']?>", false);
  xmlhttp.send();
  document.getElementById("whos_online").innerHTML = xmlhttp.responseText;
}

ONLINE.PHP
this is the content of my online.php
<link rel="stylesheet" type="text/css" href="style.css" />
<?php

    session_start();
    include 'db.inc.php';

    class WhosOnline{
        $rn = $_GET['room'];
        protected $get_status_query = "SELECT * FROM `online_users` WHERE `room` = '{$rn}'";
        public function DisplayUsers(){
            $get_current_status = mysql_query( $this->get_status_query );
            if( mysql_num_rows( $get_current_status ) != 0 ) {
                while( $row_status = mysql_fetch_array( $get_current_status ) ) {
                    if( $_SESSION['username'] == true ) {
                        echo "

                                ".base64_decode($row_status['username'])."

";
                    }
                }
            }
        }
    }

    $Online = new WhosOnline;
    $Online->DisplayUsers();
?>

Any help?

A:
$rn = $_GET['room'];
protected $get_status_query = "SELECT * FROM `online_users` WHERE `room` =     '{$rn}'";

This is a bad habit that you need to break RIGHT NOW.
protected function get_status_query($rn) {
  return "SELECT * FROM `online_users` WHERE `room` =     '". sanitize($rn) . "'";
};

Implementation of sanitize() is left to the reader.

A: you could not initialized any variable directly in class , try this
public $rn;
protected $get_status_query;

public __construct(){
      $this->rn = $_GET['room'];
      $this->get_status_query = "SELECT * FROM `online_users` WHERE `room` = '{$this->rn}'";
}

A: Ok, even this gives an error:
class WhosOnline{
    public $rn = $_GET['room'];
}

This also gives an error:
$v = "Hi there";
class WhosOnline{
    public $rn = $v;
}

The error is because you're trying to set a variable based on another variable in the class definition. You could do this in the constructor. Or you can set class members based on CONSTANTS (as you were doing with the query string). But why not rewrite your WhosOnline method like this:
public function DisplayUsers(){
    $get_current_status = mysql_query(
        "SELECT * FROM `online_users` WHERE `room` = '"
            . mysql_real_escape_string($_GET['room']) . "'");
    if(mysql_num_rows($get_current_status)!=0){
        while($row_status = mysql_fetch_array($get_current_status)){
            if($_SESSION['username']==true){
                echo "
   ".base64_decode($row_status['username'])."

";
            }
        }
    }
}

This will also remove any potential errors you might have with $this-> references missing.


text:
Q: Past and present perfect tense in scientific articles There are various questions about this, but none that I found provided me with a satisfying answer. My problem lies mainly in the part of the paper were I introduce the necessary background, and in particular explain what papers have introduced what ideas. Consider the sentence:
John and Doe have introduced an algorithm to do X in [47], which has been substantially improved in [11].
Should I use present perfect or past tense here? I am confused, because many style guides (e.g., this one or this) advise using the past tense; on the other hand, I've been taught in school something about if action is still ongoing or just completed, if the time is unspecified, and if the result is relevant. Based on the latter aspect, I'd say sure, the introduction of the algorithm in [47] and its improvements in [11] are highly relevant to what I write, so I'd use the present perfect. Am I right or wrong in this?

A: Those style guides are written for scientists in general, not for people with a sophisticated understanding of English grammar. I find it highly unlikely that, by prescribing the use of the past tense to describe past events, they mean to require the simple past and prohibit the present perfect.
Neither of them even mention the present perfect (or use the phrase "simple past" specifically), and it would be extremely unusual for a style guide to recommend against the usage of the present perfect in general, much less to do so without explicitly stating as much. I suspect that they would just lump it in with the past tense.
Assuming you follow the usual rules about when the present perfect is appropriate, there is no reason to avoid it in a scientific paper.

A: As the poster writes, style guides differ, and practice differs between fields. As a biological scientist who later in his academic career moved into bioinformatics I was surprised at what seems to me the bizarre way many computing sciences articles use the present tense where I have always used the past tense.
My advice — which editors and referees in other fields may reject — is to do what people in my field do. I would say that, wouldn't I? But the simple justification is that this is the form used in normal English. Normal English will be comprehensible to the reader, and the purpose of a scientific communication is to present results or ideas in a way that can be understood.
So:

John and Doe introduced (note 1) an algorithm to do X  (note 3)
[47], which has been (note 2) substantially improved by Jack and
Jill (note 4) [11].

Notes:
1, 2. Both papers referred to were published in the past. The past tense is therefore appropriate. However, with one published before the other I think it better (and normal English usage) to employ the simple present for the original and the perfect tense for the more recent publication.
3,4. I have changed the citation by removing the word 'in'. This was not a response to the question, but if we are talking about scientific writing stye… Why? It is unnecessary in the first case, and sounds odd read out loud. In the second case, for consistency,  I would prefer to include the names of the authors of the improvement (or use 'they' if the same as the original). Alternatively just put '[11]' directly after the word 'improved', without an intervening space.


text:
Q: Doubts in MVVM implementation This is the architecture I have implemented.

Basically I want to select "cells" in View 2 and "locations" will be populated from the selected cell. Then I have combo box with "systems" and I want upon system selection, to populate different set of cells. For that I am using IOC to access different view-model.
Doubt is that whether I have implemented according to MVVM pattern. The part with UpdateModel looks not so nice to me. I would appreciate if somebody could review architecture and tell me what I could have done better. Also is it right to have model instances in view-model or I should use data service pattern, like in mvvm-light boilerplate?
Question: can I implement response to system change without calling UpdateModel function but using mvvm-light's native mechanisms to update ViewModel2?
Below some key parts of the code.
ViewModel2:
    public List<string> LocationList
    {
        get
        {
            var cells = _wList.GetCells(currentSystemNumber);
            var cell = cells[_selectedCellItem.Key];
            return cell.Locations;
        }
    }

    private KeyValuePair<int, string> _selectedCellItem;
    public KeyValuePair<int, string> SelectedCellItem
    {
        get
        {
            return _selectedCellItem;
        }

        set
        {
            Set(ref _selectedCellItem, value);
            RaisePropertyChanged("LocationList");
        }
    }

    public ObservableCollection<KeyValuePair<int, string>> CellList
    {
        get
        {
            int count = _wList.GetCells(currentSystemNumber).Count;
            ObservableCollection<KeyValuePair<int, string>> cells = new ObservableCollection<KeyValuePair<int, string>>();
            for(int i = 0; i < count; i++)
                cells.Add(new KeyValuePair<int, string>(i, string.Format("Cell {0}/{1}", i, currentSystemNumber+1)));
            return cells;
        }
    }

    public void UpdateModel(int system)
    {
        currentSystemNumber = system;

        RaisePropertyChanged("CellList");
        RaisePropertyChanged("LocationList");
    }

View2:
<Grid>
    <ListBox x:Name="listBox" HorizontalAlignment="Left" Height="104" Margin="121,32,0,0" VerticalAlignment="Top" Width="144" ItemsSource="{Binding LocationList}"/>
    <ListBox x:Name="listBox1" HorizontalAlignment="Left" Height="104" Margin="10,32,0,0" VerticalAlignment="Top" Width="102" ItemsSource="{Binding CellList}" SelectedItem="{Binding SelectedCellItem}" DisplayMemberPath="Value"/>
    <Label x:Name="label" Content="Cells" HorizontalAlignment="Left" Margin="10,1,0,0" VerticalAlignment="Top"/>
    <Label x:Name="label1" Content="Locations" HorizontalAlignment="Left" Margin="121,1,0,0" VerticalAlignment="Top"/>
</Grid>

ViewModel1:
    private ObservableCollection<KeyValuePair<int, string>> _systems = new ObservableCollection<KeyValuePair<int, string>>();
    public ObservableCollection<KeyValuePair<int, string>> Systems
    {
        get
        {
            return _systems;
        }
    }

    private KeyValuePair<int, string> _selectedSystemItem;
    public KeyValuePair<int, string> SelectedSystemItem
    {
        get
        {
            return _selectedSystemItem;
        }
        set
        {
            Set(ref _selectedSystemItem, value);
            var locator = (ViewModelLocator)Application.Current.Resources["Locator"];
            var vm = locator.DASrvPageVM;
            vm.UpdateModel(value.Key);
        }
    }

A: Partial answer here to address some code smells and doubts you have with your architecture:

*

*ViewModels shouldn't know about other ViewModels so ViewModel1 shouldn't call into ViewModel2.

*ServiceLocator shouldn't be used if at all possible. ViewModelLocator should only be used by the framework and not called directly. If you fix issue 1, that will remove this issue as well.

*Models can implement INotifyPropertyChanged as well as the ViewModels. This way you could put properties for SelectedSystem, SelectedCell, and SelectedLocation on a model and have those fire the PropertyChanged event.

*Use your ViewModel to pull your Models out of some type of repository. This way the state of the Model is persisted when the ViewModels update their properties. ViewModels may or may not keep state based on how the ViewModelLocator is working internally. Use Models and/or Repositories to ensure the state lasts beyond the life of the ViewModel.

*Use ObservableCollections for nearly all collection types in ViewModels and Models so the Views can bind to these without having to perform so much logic on the getters. Rule of thumb, if you want to see any value or collection on the View, make sure they are Observable. This will allow the full power of MVVM bindings to be used and removes tons of boilerplate code trying to keep the View updated.


text:
Q: Multiple form submission 1 submit javascript half working I have 2 forms in 1 page that need submitting i seem to be limited because it is for a hotspot by mikrotik.
The login.html in mikrotic router is

<title>...</title>

$(if chap-id)

JavaScript required. Enable JavaScript to continue.

$(endif)
If you are not redirected in a few seconds, click 'continue' below

<form name="redirect" action="http://domain.name/login.php" method="post">
<input type="hidden" name="mac" value="$(mac)">
<input type="hidden" name="ip" value="$(ip)">
<input type="hidden" name="username" value="$(username)">
<input type="hidden" name="link-login" value="$(link-login)">
<input type="hidden" name="link-orig" value="$(link-orig)">
<input type="hidden" name="error" value="$(error)">
<input type="hidden" name="chap-id" value="$(chap-id)">
<input type="hidden" name="chap-challenge" value="$(chap-challenge)">
<input type="hidden" name="link-login-only" value="$(link-login-only)">
<input type="hidden" name="link-orig-esc" value="$(link-orig-esc)">
<input type="hidden" name="mac-esc" value="$(mac-esc)">
<input type="submit" value="continue">
</form>

so then my login.php is this
<?php
   $mac=$_POST['mac'];
   $ip=$_POST['ip'];
   $username=$_POST['username'];
   $linklogin=$_POST['link-login'];
   $linkorig=$_POST['link-orig'];
   $error=$_POST['error'];
   $chapid=$_POST['chap-id'];
   $chapchallenge=$_POST['chap-challenge'];
   $linkloginonly=$_POST['link-login-only'];
   $linkorigesc=$_POST['link-orig-esc'];
   $macesc=$_POST['mac-esc'];
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<title>mikrotik hotspot > login</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta http-equiv="pragma" content="no-cache" />
<meta http-equiv="expires" content="-1" />

    <form name="sendin" action="<?php echo $linkloginonly; ?>" method="post"          id="form1">
    <input type="hidden" name="username" />
    <input type="hidden" name="password" />
    <input type="hidden" name="dst" value="<?php echo $linkorig; ?>" />
    <input type="hidden" name="popup" value="true" />
</form>

    <a href="<?php echo $linkloginonly; ?>?target=lv&dst=<?php echo $linkorigesc; ?>">Hotspot

Please log on to use the mikrotik hotspot service

    <form method="POST" action="signin.php" id="form2">
   First Name
<input type="text" name="firstname" size="30">

    Surname
<input type="text" name="lastname" size="30">

Email address  (required)
<input type="text"  name="email" size="30">

    <input type="submit" value="submit" onclick="javascript:fnSubmit();"/>
 </form>
  <form name="login" id="form3 action="<?php echo $linkloginonly; ?>" method="post" onSubmit="return doLogin()" >
        <input type="hidden" name="dst" value="<?php echo $linkorig; ?>" />
        <input type="hidden" name="popup" value="true" />

            <input type="hidden" style="width: 80px" name="username" type="text" value="user2"/>

            <input type="hidden" style="width: 80px" name="password" type="password" value="user2"/>

    </form>

<?php echo $error; ?>

as you can see im trying to auto submit the username and password
so that the user only inputs his email address, to do this i want to store the email in
a database
with signin.php
which is this
<?php
ini_set('display_errors', 'On');
 // Receiving variables
@$pfw_ip= $_SERVER['REMOTE_ADDR'];
@$firstname = addslashes($_POST['firstname']);
@$lastname = addslashes($_POST['lastname']);
@$email = addslashes($_POST['email']);
@$date = addslashes($_POST['date']);

// Validation
if (! ereg('[A-Za-z0-9_-]+\@[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+', $email))
{
die("
Please enter a valid    email
");
}

if (strlen($email) == 0 )
{
die("
Please enter a valid email
");
}

            /* adding user information to the userinfo table */
                        @$pfw_strQuery = "INSERT INTO userinfo (firstname, lastname, email, creationdate) values ".
                "('$firstname', '$lastname', '$email', NOW())";

@$pfw_host = "localhost";
@$pfw_user = "dbusername";
@$pfw_pw = "dbpassword";
@$pfw_db = "database";

$pfw_link = mysql_connect($pfw_host, $pfw_user, $pfw_pw);
if (!$pfw_link) {
 die('Could not connect: ' . mysql_error());
}
$pfw_db_selected = mysql_select_db($pfw_db, $pfw_link);
if (!$pfw_db_selected) {
die ('Can not use $pfw_db : ' . mysql_error());
}

//insert new record
$pfw_result = mysql_query($pfw_strQuery);
if (!$pfw_result) {
 die('Invalid query: ' . mysql_error());
}
mysql_close($pfw_link);

header('Location: http://www.google.co.uk');

?>

what happens is that the email address is stored in the mysql table
but the form which stores the username and password, does not pass through, and i end up at the login page
what am i missing?
Thanks all

A: Ok the answer was to eliminate all the javascript in login.php and use a simple form with the signin.php passing through the username and password using pap login. All working and happy a happy bunny


text:
Q: Java How to make sure that a shared data write affects multiple readers I am trying to code a processor intensive task, so I would like to use multithreading and share the calculation between the available processor cores.
Let's say I have thousands of iterations and all iterations have two phases:

*

*Some working threads that scans through hundreds of thousands of options
while they have to read data from a shared array (or some other data structure), while there is no modification of the data.

*One thread that collects the results from all the working threads (while
they are waiting) and makes modifications on the shared array

The phases are in sequence, so that there is no overlap (no concurrent writing and reading of the data). My problem is: How would I be sure that the data (cache) is updated for the working threads before the next phase, Phase 1, starts.
I am assuming that when people speak about cache or caching in this context, they mean the processor cache (fix me if I'm wrong).
As I understood, volatile can be used for nonreference types only, while there is no point to use synchronized, because the working threads will block each other at reading (there can be thousands of reads when processing an option).
What else can I use in this case?
Right now I have a few ideas, but I have no idea how costly they are (most probably they are):

*

*create new working threads for all iterations

*in a synchronized block make a copy of the array (can be up to 195kB in size) for each threads before a new iteration begins

*I red about ReentrantReadWriteLock, but I can't understand how is it related to caching. Can a read lock acquire force the reader's cache to update?

A: The thing I was searching for was mentioned in the "Java Tutorial on Concurrence" I just had to look deeper. In this case it was the AtomicIntegerArray class. Unfortunately it is not efficient enough for my needs. I run some tests, maybe it worth to share.
I approximated the cost of different memory access methods, by running them many times and averaged the elapsed times, broke everything down to one average read or write.
I used a size of 50000 integer array, and repeated every test methods 100 times, then averaged the results. The read tests are performing 50000 random(ish) reads. The results shows the approximated time of one read/write access. Still, this can't be stated as exact measurement, but I believe it gives a good sense of the time costs of the different access methods. However on different processors or with different numbers these results may be completely different regarding to the different cache sizes, and clock speeds.
So the results are:

*

*Fill time with set is: 15.922673ns

*Fill time with lazySet is: 4.5303152ns

*Atomic read time is: 9.146553ns

*Synchronized read time is: 57.858261399999996ns

*Single threaded fill time is: 0.2879112ns

*Single threaded read time is: 0.3152002ns

*Immutable copy time is: 0.2920892ns

*Immutable read time is: 0.650578ns

Points 1 and 2 shows the write result on an AtomicIntegerArray, with sequential writes. In some article I red about the good efficiency of the lazySet() mehtod so I wanted to test it. It is usually over perform the set() method by about 4 times, however different array sizes show different results.
Points 3 and 4 shows the difference between the "atomic" access and synchronized access (a synchronized getter) to one item of the array via random(ish) reads by four different threads simultaneously. This clearly indicates the benefits of the "atomic" access.
Since the first four value looked shockingly high, I really wanted to measure the access times without multithreading, so I got the reslults of points 5 and 6. I tried to copy and modify methods from the previous tests, to make the code as close as it is possible. Of course there can be optimizations I can't affect.
Then just out of curiosity I come up with points 7. and 8. which imitates the immutable access. Here one thread creates the array (by sequential writes) and passes it's reference to an another thread which does the random(ish) read accesses on it.
The results are heavily vary, if the parameters are changed, like the size of the array or the count of the methods running.
The conclusion:
If an algorithm is extremely memory intensive (lots of reads from the same small array, interrupted by short calculations - which is my case), multithreading can slow down the calculation instead of speeding it up. But if it has many many reads, compared to the size of the array, it may be helpful to use an immutable copy of the array, and use multiple threads.


text:
Q: How to select * from DataTable Where... using Linq I'm trying to filter a datatable with linq, I have tried doing this..
string strFind = "Road";
var query = from a in res.AsEnumerable()
             where (a.Field<string>("Last Name") == strFind ||
             a.Field<string>("First Name") == strFind ||
             a.Field<string>("Address") == strFind)
             select a;

I have about 5 other columns that I got to filter out as well, this is testing code right now to see if it would work, and it doesn't.
I tried putting the datatable to a list and filtering by using .Contains(strFind) but that didn't work out for me either.

A: A LINQ query doesn't actually do anything to the list you're querying.  That query gives you a list of results.  If you want the user to see those results then you have to actually show them those results, e.g. call ToArray or ToList or, in this case, CopyToDataTable and then bind that result to a grid or whatever.

A: It also works :
   var query = res.AsEnumerable()
         where (a.Field<string>("Last Name") .CustomContains(strFind,StringComparison.OrdinalIgnoreCase) ||
         a.Field<string>("First Name") .CustomContains(strFind,StringComparison.OrdinalIgnoreCase) ||
         a.Field<string>("Address") .CustomContains(strFind,StringComparison.OrdinalIgnoreCase)
         ).ToList()

Use the below Extension Method to solve the Case sensitivity in strFind
 public static bool CustomContains(this string source, string toCheck, StringComparison compare)
    {
        return source.IndexOf(toCheck, compare) >= 0;

    }


text:
Q: Log transformation in CART analysis I'm working as a liaison between a researcher and a stats team at a university.  I'm a database admin who is working on using business intelligence tools to offer the option of (as of right now) offer CART analyses in .PDF form over the internet.  I'm using Microsoft Business Intelligence Development Studio to do this.  Recently I received an email saying that the measure (or independent variable I guess it should be called here) was highly skewed and the original CART analysis didn't make sense.  Fair enough, I know that sometimes these things don't work out like you had hoped.  Then, another analysis was done with a log transformation.  Can someone point me to a good quick and dirty resource so I can read up on this?  I'm not a complete stats novice, but ANOVAs and logistic regressions are about as far as my knowledge extends.

A: Taking the log of a predictor (independent) variable should have no effect, as CART is invariant to monotonic transformations of the predictors.
See this example where I fit a CART with Age (named fit1) and log(Age) (named fit2). The split points are the same for both trees (only that the split points in fit2 are on the log scale, e.g., $4.706 \approx \ln(111)$), the predictions and nodes are exactly the same.
R> library(rpart)
R> fit <- rpart(Kyphosis ~ Age + Number + Start, data=kyphosis)
R> fit2 <- rpart(Kyphosis ~ log(Age) + Number + Start, data=kyphosis)
R> fit
n= 81

node), split, n, loss, yval, (yprob)
      * denotes terminal node

 1) root 81 17 absent (0.79012 0.20988)
   2) Start>=8.5 62  6 absent (0.90323 0.09677)
     4) Start>=14.5 29  0 absent (1.00000 0.00000) *
     5) Start< 14.5 33  6 absent (0.81818 0.18182)
      10) Age< 55 12  0 absent (1.00000 0.00000) *
      11) Age>=55 21  6 absent (0.71429 0.28571)
        22) Age>=111 14  2 absent (0.85714 0.14286) *
        23) Age< 111 7  3 present (0.42857 0.57143) *
   3) Start< 8.5 19  8 present (0.42105 0.57895) *
R> fit2
n= 81

node), split, n, loss, yval, (yprob)
      * denotes terminal node

 1) root 81 17 absent (0.79012 0.20988)
   2) Start>=8.5 62  6 absent (0.90323 0.09677)
     4) Start>=14.5 29  0 absent (1.00000 0.00000) *
     5) Start< 14.5 33  6 absent (0.81818 0.18182)
      10) log(Age)< 4.005 12  0 absent (1.00000 0.00000) *
      11) log(Age)>=4.005 21  6 absent (0.71429 0.28571)
        22) log(Age)>=4.706 14  2 absent (0.85714 0.14286) *
        23) log(Age)< 4.706 7  3 present (0.42857 0.57143) *
   3) Start< 8.5 19  8 present (0.42105 0.57895) *


text:
Q: Used the reactjs in vscode was report an error use "jsx" grammar in visual studio code.
visual studio code report an error

Please help me.
Thanks!!!

A: The symbol "<" should appear in the same line with the tag name.
For example,
instead of doing that:
   return (     <
      button className="square"> {/*TODO*/} <
      /button>
   )

Do that:
  return(
    <button className="square">
         {/*TODO*/}
    </button>
)

If you want to split the tag to multiple lines,
you can do it like that:
      return (
        <button
          className="square"
          id="id"
          onClick={someFunc}
        >
             {/*TODO*/}
        </button>
       )

A: There is a button in the lower-right side of the VScode window (yours says "Javascript Standard Style"). If you click that you can select a different language mode. You want to select the one that works with React. You may also be able to select "Auto-detect" from the menu list.
For example, mine says "Javascript React"

The language mode can also be selected from the command-palette (CMD-Shift-p on Mac, not sure what it it is on other OS's, but you can also reach it from toolbar > View)..


text:
Q: How to connect two players over turn based api game center? I am trying to make a turn based game with turn based game center api but I have this problem. I have two iPhones, and when I try to connect over game center view, every time it creates new match for iphone 1 and new match for iphone 2. But when I try the real game api then match connect those two iphones as it should. On turn based version, when starting, it says "Starting game..." but in the real game it says "finding players..." first.
How to solve that?
I'm learning and trying from example (spinningyarn - turn based game center) which was in iOS 5 turorials which I bought on ray wenderlich site.


text:
Q: SQL Query to list all friends who bought exactly same three items from REF table I want to list down all friends who bought exactly ItemID's 1,2,3
CREATE TABLE #FRIENDS
(
    PERSONID int,
    ITEMID int
)

insert into #FRIENDS VALUES (1, 1)
insert into #FRIENDS VALUES (1, 2)
insert into #FRIENDS VALUES (1, 3)
insert into #FRIENDS VALUES (1, 6)
insert into #FRIENDS VALUES (2, 1)
insert into #FRIENDS VALUES (3, 1)
insert into #FRIENDS VALUES (2, 8)
insert into #FRIENDS VALUES (5, 1)
insert into #FRIENDS VALUES (4, 1)
insert into #FRIENDS VALUES (7, 1)
insert into #FRIENDS VALUES (8, 1)
insert into #FRIENDS VALUES (8, 2)
insert into #FRIENDS VALUES (8, 3)
insert into #FRIENDS VALUES (9, 3)
insert into #FRIENDS VALUES (9, 2)
insert into #FRIENDS VALUES (9, 1)

sample O/P
PERSONID
1
8
9

I want to get list who bought all the three items NOT any one of the item.

A: This is an example of a "set-within-sets" query.  I like to approach this using group by and having, because this method is very flexible in terms of the rules for matching the sets.
select personid
from #friends f
group by personid
having count(distinct item) = 3 and
       count(distinct (case when item in (1, 2, 3) then item end)) = 3;

That is, each person bought three items.  And, each person bought three items in the set you care about.  Voila!  Exactly those three items, no more, no less.
EDIT:
The text says "who brought exactly Item 1,2,3", which is what the above does.  You seem to want person 1, so you want people who bought 1, 2, 3 and perhaps other things.  Easily done:
select personid
from #friends f
where item in (1, 2, 3)
group by personid
having count(distinct item) = 3;

A: You can use the INTERSECT set operator for this:
Fiddle: http://sqlfiddle.com/#!3/a9a80/2/0
select personid
  from friends
 where itemid = 1
intersect
select personid
  from friends
 where itemid = 2
intersect
select personid
  from friends
 where itemid = 3


text:
Q: How to receive Messages in chat App using signalR in Android hello i am new in signalR i am making one chating app with using signalR i take reference from SignalR integration in android studio here with the help of this i able to send the messages to the chat group but i am not able to receive messages i read lots of Q&A here but i am not able to solve this problem i paste here my code and please anyone tell me how do i receive message from the server.following is my code.
Activity main
   package myapp.chatapp;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.Toast;

import com.google.gson.JsonElement;

import java.util.ArrayList;

import microsoft.aspnet.signalr.client.MessageReceivedHandler;
import microsoft.aspnet.signalr.client.Platform;
import microsoft.aspnet.signalr.client.http.android.AndroidPlatformComponent;
import microsoft.aspnet.signalr.client.hubs.HubConnection;
import microsoft.aspnet.signalr.client.hubs.HubProxy;
import microsoft.aspnet.signalr.client.hubs.SubscriptionHandler2;
import microsoft.aspnet.signalr.client.transport.ClientTransport;
import microsoft.aspnet.signalr.client.transport.LongPollingTransport;

public class MainActivity extends AppCompatActivity implements SignalRService.Something {

    private StringBuilder mLog;

    private ListView mTestCaseList;

    private Spinner mTestGroupSpinner;

    private HubConnection mHubConnection;
    private HubProxy mHubProxy;

    private final Context mContext = this;
    private SignalRService mService;
    private SignalRService mMessageResive;
    private boolean mBound = false;

    ListView list_item;
    EditText editText;

    ArrayList<String> listItems;
    ArrayAdapter<String> adapter;

    ClientTransport transport;

    private Handler mHandler; // to display Toast message

    private Thread t;

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        // don't restart the activity. Just process the configuration change
        super.onConfigurationChanged(newConfig);
    }

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

        Intent intent = new Intent();
        intent.setClass(mContext, SignalRService.class);
        bindService(intent, mConnection, Context.BIND_AUTO_CREATE);

        editText = (EditText)findViewById(R.id.edit_message);
        ImageButton btn = (ImageButton)findViewById(R.id.btn);
        list_item = (ListView)findViewById(R.id.list_item);
        listItems = new ArrayList<String>();
        /*listItems.add("First Item - added on Activity Create");*/
       /* adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1, listItems);*/

        adapter = new ArrayAdapter<String>(mContext,R.layout.custom_list, R.id.textView,listItems);
        list_item.setAdapter(adapter);

        final Handler handler = new Handler();
        handler.postDelayed( new Runnable() {

            @Override
            public void run() {
                adapter.notifyDataSetChanged();
                handler.postDelayed( this, 1000 );
            }
        }, 1000 );

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                listItems.add(editText.getText().toString());
                adapter.notifyDataSetChanged();
                sendMessage(view);
            }
        });

    }

    @Override
    protected void onStop() {
        // Unbind from the service
        if (mBound) {
            unbindService(mConnection);
            mBound = false;
        }
        super.onStop();
    }

    public void sendMessage(View view) {
        if (mBound) {

            String message = editText.getText().toString();
            String email = "kn@yopmail.com";
            String name = "Kunal From Android";
            String group ="1";
            mService.sendMessage(name,email,group,message);
            editText.setText("");
            // Call a method from the SignalRService.
            // However, if this call were something that might hang, then this request should
            // occur in a separate thread to avoid slowing down the activity performance.
            /*EditText editText = (EditText) findViewById(R.id.edit_message);
            if (editText != null && editText.getText().length() > 0) {

            }*/
        }
    }

    public void setmMessageResive(JsonElement jsonElement)
    {

        listItems.add(10, String.valueOf(jsonElement));

    }

    /**
     * Defines callbacks for service binding, passed to bindService()
     */
    private final ServiceConnection mConnection = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            // We've bound to SignalRService, cast the IBinder and get SignalRService instance
            SignalRService.LocalBinder binder = (SignalRService.LocalBinder) iBinder;
            mService = binder.getService();
            mBound = true;
        }

        @Override
        public void onServiceDisconnected(ComponentName arg0) {
            mBound = false;
        }
    };

    @Override
    public void doSomething(String msg) {

        listItems.add(msg);

    }
}

Service code
    package myapp.chatapp;

import android.app.Service;
import android.bluetooth.BluetoothClass;
import android.content.Intent;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.util.Log;
import android.widget.Toast;

import com.google.gson.JsonElement;

import java.util.ArrayList;
import java.util.concurrent.ExecutionException;
import java.util.logging.Logger;

import microsoft.aspnet.signalr.client.Action;
import microsoft.aspnet.signalr.client.Credentials;
import microsoft.aspnet.signalr.client.LogLevel;
import microsoft.aspnet.signalr.client.MessageReceivedHandler;
import microsoft.aspnet.signalr.client.Platform;
import microsoft.aspnet.signalr.client.SignalRFuture;
import microsoft.aspnet.signalr.client.http.Request;
import microsoft.aspnet.signalr.client.http.android.AndroidPlatformComponent;
import microsoft.aspnet.signalr.client.hubs.HubConnection;
import microsoft.aspnet.signalr.client.hubs.HubProxy;
import microsoft.aspnet.signalr.client.hubs.SubscriptionHandler1;
import microsoft.aspnet.signalr.client.hubs.SubscriptionHandler2;
import microsoft.aspnet.signalr.client.hubs.SubscriptionHandler4;
import microsoft.aspnet.signalr.client.transport.ClientTransport;
import microsoft.aspnet.signalr.client.transport.LongPollingTransport;
import microsoft.aspnet.signalr.client.transport.ServerSentEventsTransport;

/**
 * Created by NULLPLEX7 on 11/28/2017.
 */

public class SignalRService extends Service {
    private HubConnection mHubConnection;
    private HubProxy mHubProxy;
    private Handler mHandler; // to display Toast message
    private final IBinder mBinder = new LocalBinder(); // Binder given to clients

    ClientTransport transport;

    registerListener registerListener;

    private MainActivity setmMessageResive;

    public  Something list;

    public SignalRService() {
    }

    @Override
    public void onCreate() {
        super.onCreate();
        mHandler = new Handler(Looper.getMainLooper());
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        int result = super.onStartCommand(intent, flags, startId);
        startSignalR();
        return result;
    }

    @Override
    public void onDestroy() {
        mHubConnection.stop();
        super.onDestroy();
    }

    @Override
    public IBinder onBind(Intent intent) {
        // Return the communication channel to the service.
        startSignalR();
        return mBinder;
    }

    /**
     * Class used for the client Binder.  Because we know this service always
     * runs in the same process as its clients, we don't need to deal with IPC.
     */
    public class LocalBinder extends Binder {
        public SignalRService getService() {
            // Return this instance of SignalRService so clients can call public methods
            return SignalRService.this;
        }
    }

    /**
     * method for clients (activities)
     */
    public void sendMessage(String name, String email, String group, String msg ) {
        String SERVER_METHOD_SEND = "BroadCastMessage";
        mHubProxy.invoke(SERVER_METHOD_SEND, name,email,group,msg);
    }

    private void startSignalR() {
        Platform.loadPlatformComponent(new AndroidPlatformComponent());

        Credentials credentials = new Credentials() {
            @Override
            public void prepareRequest(Request request) {
                request.addHeader("User-Name", "BNK");
            }
        };

        String serverUrl = "myurlhere";
        mHubConnection = new HubConnection(serverUrl);
        mHubConnection.setCredentials(credentials);
        String SERVER_HUB_CHAT = "ChatHub";
        mHubProxy = mHubConnection.createHubProxy(SERVER_HUB_CHAT);
        ClientTransport clientTransport = new ServerSentEventsTransport(mHubConnection.getLogger());
        SignalRFuture<Void> signalRFuture = mHubConnection.start(clientTransport);

        mHubProxy.subscribe(this);

        transport = new LongPollingTransport(mHubConnection.getLogger());

        mHubConnection.start(transport);

          /* ****new codes here**** */
        /* ****seems useless but should be here!**** */
        mHubProxy.subscribe(new Object() {
            @SuppressWarnings("unused")
            public void newMessage(final String message, final String messageId, final String chatId,
                                   final String senderUserId, final String fileUrl, final String replyToMessageId) {

            }
        });

        try {

            signalRFuture.get();

        }catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
            return;
        }

        mHubProxy.on("receiveGroupMessage",
                new SubscriptionHandler4<String, String, String, String>() {
                    @Override
                    public void run(final String name,final String msg ,final String avtar,final String date ) {
                        final String finalMsg = name + " says " + msg;
                        /*final String finalMsg =  msg;*/
                        // display Toast message
                        mHandler.post(new Runnable() {
                            @Override
                            public void run() {

                                list.doSomething(msg);

                            }
                        });
                    }
                }
                , String.class,String.class,String.class,String.class);

             mHubConnection.received(new MessageReceivedHandler() {

            @Override
            public void onMessageReceived(final JsonElement json) {
                Log.e("receiveGroupMessage ", json.toString());
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getApplicationContext(), ""+json, Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });

    }
    public interface Something
    {
        void doSomething(String msg);
    }

}

i read on stack overflow that in onMessageReceived i get the server responses but i did not get any response here . I want  when any one send message  in group from web i want that message in my chat app  someone suggest me that i need to create Event listener but i don't no how to create it . please tell me how do i get messages in my chat app.
   mHubProxy.on("receiveGroupMessage",
                new SubscriptionHandler4<String, String, String, String>() {
                    @Override
                    public void run(final String name,final String msg ,final String avtar,final String date ) {
                        final String finalMsg = name + " says " + msg;
                        /*final String finalMsg =  msg;*/
                        // display Toast message
                        mHandler.post(new Runnable() {
                            @Override
                            public void run() {

                                list.doSomething(msg);

                            }
                        });
                    }
                }
                , String.class,String.class,String.class,String.class);

i thought that i got messages here but execution not go inside the Run.
Any Help is Welcome


text:
Q: Email forwarding - iOS Someone sent me an email with an image attached. I want to review the image and forward it to someone else.
How do I do that?

A: Using the application Mail click on your mail. Then click in the bottom bar the 4th icon that is an arrow. Press Forward. If it asks if you want to include attachments from original message, press Include. Then just fill the information depending on who do you want to send it to.


text:
Q: How come stored procedure will not create table with IF statement USE [WORKFILES]
GO
/****** Object:  StoredProcedure [dbo].[MLINT]    Script Date: 05/04/2015 16:49:38 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[MLINT]

AS

IF OBJECT_ID('WORKFILES.dbo.MLINT05', 'U') IS NULL

BEGIN
        --CREATE CMPDTE TABLE
CREATE TABLE WORKFILES.dbo.MLINT05
(DTSTAMP DATETIME NOT NULL)
END

BEGIN
        --INSERT TIMESTAMP
INSERT INTO WORKFILES.dbo.MLINT05
SELECT (getdate())
END

BEGIN
SELECT CONVERT(varchar(20), DTSTAMP)
FROM [WORKFILES].[dbo].[MLINT05]
END

I added a go to my SP
USE [WORKFILES]
GO
/****** Object:  StoredProcedure [dbo].[MLINT]    Script Date: 05/04/2015 16:49:38 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[MLINT]

AS

IF OBJECT_ID('WORKFILES.dbo.MLINT05') IS NULL
GO

BEGIN
        --CREATE CMPDTE TABLE
CREATE TABLE WORKFILES.dbo.MLINT05
(DTSTAMP DATETIME NOT NULL)
END

BEGIN
        --INSERT TIMESTAMP
INSERT INTO WORKFILES.dbo.MLINT05
SELECT (getdate())
END

BEGIN
SELECT CONVERT(varchar(20), DTSTAMP)
FROM [WORKFILES].[dbo].[MLINT05]
END

A: The go keyword is used by the Management Studio client to separate batches.  You can't use it in stored procedures.  In fact, if you use go in a stored procedure definition in SSMS, the go will mark the end of the procedure.
Your procedure works fine in SQL Server 2012.  Perhaps older versions give an error when they see a create table for a table that already exists.  If this is true, you can work around that with dynamic SQL:
IF OBJECT_ID('WORKFILES.dbo.MLINT05', 'U') IS NULL
    BEGIN
    EXEC (N'CREATE TABLE WORKFILES.dbo.MLINT05 (DTSTAMP DATETIME NOT NULL)')
    END


text:
Q: Derivation of the expectation of an exponential I would like to demonstrate the formula which states that if
$X$ is a random variable such that
$\forall \lambda >0, E[e^{-\lambda^2.\frac{X}{2}}] = e^{-\lambda.b}$
Where $b$ is a positive constant.
Then by derivation regardng $\lambda^2$ and taking $\lambda = 0$.
Once can calculate $E[X]$
In order to demonstrate this statement, I thought of using whole series to demonstrate such a purpose. However this lead me nowhere...
Can you please advise?!!
Thank you

A: The hypothesis can be written as $Ee^{-tX}=e^{-\sqrt {2t} b}$ for all $t>0$. Differentiating  w.r.t. $t$ (from the right) and setting $t=0$ we get $EX=\infty$.


text:
Q: Gmail search with API and access token I am trying to fetch Gmail search results from Gmail API using an access token.
The following code works and returns an array of my email IDs:
fetch(`https://www.googleapis.com/gmail/v1/users/${userId}/messages?access_token=${accessToken}`)

I then try to append a search query following the Gmail API documentation guidelines
fetch(`https://www.googleapis.com/gmail/v1/users/${userId}/messages?access_token=${accessToken}?q=${text}`)

and it brings this error code: 401, message: 'Invalid Credentials'
Authentication scope is set to https://mail.google.com/ which assumes full control of the email. I tried swapping access_token and q parameters, as well as removing the access_token parameter but still no success. What am I doing wrong?

A:
`https://www.googleapis.com/gmail/v1/users/${userId}/messages?access_token=${accessToken}?q=${text}

you are preforming a HTTP GET in this call.  Additional parameters are tacked on using a & only the first one starts with a ?
try this:

`https://www.googleapis.com/gmail/v1/users/${userId}/messages?access_token=${accessToken}&q=${text}


text:
Q: swift closure equivalent java lambda I have to pass this swift closure to a lambda java and java < 8 (in java I have the same method loginUsingPost generate by swagger).
It's my first time with both languages so I don't know how to handle this.
LoginRestControllerAPI.loginUsingPOST(user: user) { (tokenWrapper, error) in
                // code
                completion(auth, nsError)
            }


text:
Q: JSON deserialize is coming null When I'm testing I just Tested this code, When I'm running this JSON not assigning to the variables it is coming NUll.
String requestString='{"terms":{"customerCode":"sadasd","customerName":"sadasd","incoterm":"EXW","paymentTerms":"T30JFDM","paymentTermsDescriptionEn":"Transfer 30 days end of month the 20th","paymentTermsDescriptionFr":"Virement 30 jours Fin de Mois le 20","creditLimit":"asdasdsa"}}';
              system.debug('string json'+requestString);
System.debug(
    system.JSON.deserialize(requestString,terms.class));

terms quoweb=(terms)JSON.deserialize(requestString,terms.class);
              //quoteData quoweb=(quoteData)JSON.deserialize(json,quoteData.class);

              integer i=0;
Try{
              System.debug('web serivice size JSO'+quoweb);
             // for(i=0;i<quoweb.terms.size();i++){

               //   System.debug('web serivice JSON checking size and detailes'+quoweb.terms.size()+'Detailes'+quoweb.terms[i].paymentTerms);

              //}
}catch(exception e) {

    System.debug('excdsdf'+e);

}

public class terms{
        public String customerCode{get;set;}
        public String customerName{get;set;}
        public String incoterm{get;set;}
        public String paymentTerms{get;set;}
        public String paymentTermsDescriptionEn{get;set;}
        public String paymentTermsDescriptionFr{get;set;}
        public String creditLimit{get;set;}
}

What I'm Getting:
USER_DEBUG [5]|DEBUG|terms:[creditLimit=null, customerCode=null, customerName=null, incoterm=null, paymentTerms=null, paymentTermsDescriptionEn=null, paymentTermsDescriptionFr=null]

A: Your input JSON should not include the outer object with the "terms" property... change it to:
String requestString='{"customerCode":"sadasd","customerName":"sadasd","incoterm":"EXW","paymentTerms":"T30JFDM","paymentTermsDescriptionEn":"Transfer 30 days end of month the 20th","paymentTermsDescriptionFr":"Virement 30 jours Fin de Mois le 20","creditLimit":"asdasdsa"}';

A: The issue is that your JSON isn't just a {<terms object>} as your code assumes. There's an extra layer of object in there that you haven't captured. It's really a {<property name> : <terms object>}.
Removing the outer layer of object, as Phil W suggests, is one way to going about fixing this. That approach isn't always practical (especially if you're getting the JSON from some external third party).
You could simply do an untyped deserialization, but probably the easiest way to handle this in most real applications would be to add another class so that you have an accurate representation of your JSON's structure.
In this case, the extra class is pretty easy.
public class OuterObject{
    // Using the name of a property as the class name isn't ideal.
    // This will, however, work
    Terms terms;
}

You'd then be using OuterObject in the deserialization in place of Terms, and accessing the data inside of the Terms object would be done in the normal way (e.g. myOuterObject.terms.customerCode)


text:
Q: What is the fastest way to read a data frame in R compared to Stata? I have this data set with 57000 rows and 5500 columns. They are both numeric and character variables. I originally downloaded the data in .dta format and it is quite quick for Stata to read it. It takes .13 scones to do it, when I time it using the timer command.
Now, I have been using R and from I have read, it is supposed to be much more efficient. I exported my data to csv from Stata and even following the recommendations I read on stack exchange, the results are not convincing.
Here is the best solution I came across with:
library(data.table)
system.time(fread("~/Data/GSS/GSS.csv", stringsAsFactors=FALSE, header=T, na.strings=paste0(".",letters), data.table=FALSE)

)
I get:
Read 57061 rows and 5548 (of 5548) columns from 1.053 GB file in 00:00:46
  user  system elapsed
  52.000   1.492  53.470

I also get a lot of warnings regarding the missing values, although I have declared them. The Warnings:
Bumped column XXXX to type character on data row XXXX, field contains '.n'.

I think it has to do with R not recognizing these missing values in numeric columns
Any suggestions on how to improve this? As a side note, I tried sqldf but it just did not work on my computer, even upgrading the package to the most recent version.
Here is the data I am working with:
http://www3.norc.org/GSS+Website/Download/

A: I find read.dta13 from readstata13 package to be the best in reading Stata files in general.
The main advantage of read.dta13 is its ability to read Stata's labelled data correctly into a factor format and keeps the order, which I find it extremely important. It also reads any version of Stata, including Stata 15 files.
I could not do this using haven and foreign packages.


text:
Q: jQuery checking each element against each other element in a class (ty putvande and shanet for pointing out the wrong ')' which now is removed, I had however to repost the question as it only got answers related to that little mistake and not the main question)
I'm having a lot of difficulties constructing the following in javascript:
FOR every element with Assemble_station class
CHECK whether it overlaps with each other element with Assemble_station class
IF it does: CHECK which element has biggest left position of the two, move the element with the biggest left position to another location to avoid collision
Here's what I've written
$(".Assemble_station").each(function (i, firstobj) {
    $(".Assemble_station").each(function (i, secondobj) {
        if ($(firstobj).overlaps($(".Assemble_station").not(firstobj), secondobj)) {
            if ($(firstobj).css("left") >= $(secondobj).css("left")) {
                $(secondobj).css("top", "98px");
            }
        }
    });
});

Here's a jsfiddle that uses the code at the back: http://jsfiddle.net/NxWxU/6/
To sum up the question, I'm trying to find the best practice method for doing what I described above. And so far I don't get why my current code isn't even working. >.<
You can see that some of the elements clearly overlap if you break my code in jsfiddle and watch their positions before the are moved to same vertical position.
Ty for taking the time to try help

A: Suggestions to improve your coding and debugging skills
Your updated code (in which you resolved the lack of the overlaps function) is failing because jQuery plugins are not supposed to be used in that way. Please consider reading about creating jQuery plugins, and as much as you can about javascript debugging before trying to resolve this kind of problem.
Try to develop your debugging abilities by doing all of the following in the console after setting breakpoints (or using the debugger statement in your code):

*

*Play the relevant code step by step

*Check variables values

*Go thru the stacktrace

*Put commands in the console to see how the code behaves in that context

For instance, to resolve this problem I used some jQuery into the console:
> $(".Assemble_station") // this returned elements with [visibility:hidden] so I tried:
> $(".Assemble_station:visible") // but I got the same results, so I ended up using:
> $(".taskNameItem").remove() // then I checked again:
> $(".Assemble_station") // and now the results are different :)

And all these were done in the console without having to change the code. So you can really learn a lot by putting commands in the console while your code is in a breakpoint. But in jsFiddle, remember to change from the <top frame> to the result frame using the dropdown at the bottom of the console.
The actual problems in your code
The problem with changing overlaps into a jQuery plugin, is that jQuery plugins can be called on many items at the same time. So it would be difficult to adapt it as a plugin to work properly, and you are better off using the original version.
But the problem with using the original function is that it works with normal HTML elements, but your elements are not so simple (because you hidden parts, and the containers have the positions while the contents the have the sizes). So I had to hack into the getPosition function inside overlaps to make it work with your weird HTML:
var overlaps = (function () {
    function getPositions( elem ) {
        var obj = $( elem );
        var pos = obj.position();
        //HACK: weird HTML force me to use its first child's dimensions
        var child = obj.children(":first-child");
        var width = child.width();
        var height = child.height();
        return [ [ pos.left, pos.left + width ], [ pos.top, pos.top + height ] ];
    }

Take a look at this new code on how to use the overlaps function (in the second each, I've removed not only the firstobj, but also every other object already tested in previous loops by using i1 + 1 as starting point):
var stations = $('.Assemble_station');
stations.each(function(i1, firstobj) {
    stations.slice(i1 + 1).each(function(i2, secondobj) {
        if(overlaps(firstobj, secondobj)) {
            var obj1 = $(firstobj);
            var obj2 = $(secondobj);
            var objToMove = obj1.position().left >= obj2.position().left ? obj1 : obj2;
            var newTop = objToMove.position().top + 18;
            objToMove.css("top", newTop + 'px');
        }
    });
});

Your other problem is that several elements on your page are sharing IDs. If you give an element an id, it should be the only element with that id in the whole page. jQuery won't work as expected if you don't comply with this basic HTML assumption. I fixed this by removing (instead of hiding) the titles and the yellow bar (and doing it before getting the objects by id), so they won't interfere with the collision detection.
The full solution
You can play with my jsFiddle here: http://jsfiddle.net/protron/NxWxU/8/


text:
Q: facebook connect for ios question authentication application id and secret perhaps a stupid question, yet...
We're using the "new" ios facebook connect sdk (https://github.com/facebook/facebook-ios-sdk) and a few questions come to mind.
In the old sdk, you would have to pass a "secret key" (known only to you) in order to obtain a session so that you could use the facebook api, this made sense.
With the new sdk, all you need to pass is "Application Id" and then the user logs in, then he is able to post any message and it will appear as if my application (the facebook application identified by the application id) posted it.
This makes little sense to us, if someone obtains our application id (not mentioned to be a secret anywhere), he/she will (without any problem) have the ability to post as if he was the owner of our facebook application.
Can someone explain this and how this is prevented using this new SDK?
a few more issues we're unclear about are:

*

*in the facebook application
settings, there is a choice between
"Native application" and "HTML5 /
mobile web" currently ours is set to
HTML5/Mobile web (which is the
default) what's the deal here?
perhaps this correlates to the
previous issue?

*there are two more settings: "iOS Bundle ID" and
    "iTunes App Store ID" it is again
    unclear what these are used for.
    Currently none of these 2 are set in
    our app and we're able to submit to
    user walls without a problem using
    the "application id" only in our
    iPhone app.

Any tips and hints appreciated!
thanx,
-tzurs

A: iOS Bundle ID is used to prevent that from happening. You specify the bundle id in your info.plst (e.g., com.your_company.your_app) so Facebook knows that your iPhone app is authorized to use your Facebook appication.
iTunes App Store ID is used to create a link from your Facebook application's page to your iPhone app on the app store.


text:
Q: Reduced density operator of a maximally entangled state Is the reduced density operator of a maximally entangled pure state always maximally mixed (trace being half)?
I test it on 4 bell state and this claim is true. I wonder why and can the degree of entanglement of pure state be revealed by the trace of the reduced density operator?

A: Yes and no (for bipartite systems).
For your first question, if you don't take it as a definiton (which is often done), you can prove it by noting that a maximally entangled (pure) state has the Schmidt decomposition $\sum_{i=1}^d 1/\sqrt{d} |i\rangle\otimes |i\rangle$ is an appropriate basis. The partial trace is the identity.
Your second question is trivial, because the reduced density matrix must have unit trace for normalized density matrices by the definition of the partial trace. In other words: Reduced density matrices are always states! If you just want to take the reduced density matrix and ask whether we can define a measure by comparing it to the identity matrix, this is indeed possible via majorization (see here for an article exploring a bit about majorization). A special case is the idea behind the so-called von Neumann entropy measure for entanglement.
For multipartite system, the answer is completely different, because the notion of a "maximally entangled state" is problematic, as there are different classes of entanglement each with their own maximally entangled set.


text:
Q: beginner's c# class question public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void txtTestPrime_Click(object sender, EventArgs e)
        {
            TestPrime myNumber = new TestPrime();
            lblAnswer.Text =
                myNumber.TestPrime(ToInt16(txtTestPrime.Text)) ? "it is prime!" : "it is NOT prime!";
        }

    }
    public class TestPrime(int number)
    {
        bool prime;

    }

it doesnt like this line:
public class TestPrime(int number)

i am getting this error: invalid token '(' in class, struct, or interface member declaration
also getting expect { and ; on that line
also on this line:
myNumber.TestPrime(ToInt16(txtTestPrime.Text)) ? "it is prime!" : "it is NOT prime!";

im getting Error    4   'WindowsFormsApplication1.TestPrime' does not contain a definition for 'TestPrime' and no extension method 'TestPrime' accepting a first argument of type 'WindowsFormsApplication1.TestPrime' could be found (are you missing a using directive or an assembly reference?)
perhaps it is one main thing that i am doing wrong. please help!

A: Is TestPrime supposed to be a class?  It sounds more like a function (also called "method").
Try changing that line to
public static bool TestPrime(int number)

A: You are trying to create a class and a method on the same line at the same time, that just don't make any sense.
If you want a method to check the number, do the following:
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void txtTestPrime_Click(object sender, EventArgs e)
    {
        // this instantiate a new class, which now is not needed
        //TestPrime myNumber = new TestPrime();
        lblAnswer.Text = TestPrime(Int16.Parse(txtTestPrime.Text)) ? "it is prime!" : "it is NOT prime!";
    }

    public bool TestPrime(short number)
    {
        /* your logic */
        /* this method expects a boolean as the return type */
    }
}

Some useful links:

*

*Introduction to C# Classes

*C# Methods

A: You can't have parameters in a class declaration.
You need to create a constructor taking the desired parameters.
Example:
public class TestPrime
{
        private bool prime;
        private int _number;
        public TestPrime(int number)
        {
           this._number = number;
        }
}


text:
Q: SSRS-2016 Redirect for Specific Traffic Is there a way to redirect SSRS - 2016 to a specific folder depending on the origin URL? For example, if the origin were: http://originsite.com/Reports.aspsx
I would want the report viewer to land on folder: /SpecificFolder and NOT on the Home folder.
For example:  I want all traffic hitting the SSRS machine from a particular URL to direct to a particular folder of my choosing.


text:
Q: Using sympy cxxcode on Heaviside function fails I am using sympy version 1.10.1 and numpy version 1.20.0. Can someone please explain why the following simple code results in an error?
import sympy as sp
from sympy.printing import cxxcode

T = sp.symbols('T', real=True, finite=True)
func = sp.Heaviside(T - 0.01)
func_cxx = cxxcode(func)

The error is
ValueError: All Piecewise expressions must contain an (expr, True) statement to be used as a default condition. Without one, the generated expression may not evaluate to anything under some condition.

I understand that sympy converts Heaviside to a Piecewise function, but I'd imagine the corresponding Piecewise is also defined for all real & finite T:
>>func.rewrite(sp.Piecewise)
>>Piecewise((0, T - 0.01 < 0), (1/2, Eq(T - 0.01, 0)), (1, T - 0.01 > 0))

A: If I were you I would open an issue on SymPy.
To solve your problem you might want to modify the function in order to get cxxcode to work:
func = func.rewrite(Piecewise)
# modify the last argument to insert the True condition
args = list(func.args)
args[-1] = [args[-1][0], True]
# recreate the function
func = Piecewise(*args)
print(cxxcode(func))
# out: '((T - 0.01 < 0) ? (\n   0\n)\n: ((T - 0.01 == 0) ? (\n   1.0/2.0\n)\n: (\n   1\n)))'


text:
Q: In android, i was successful to play a video but media controller is not showing. Further given below Reference:
https://google-developer-training.gitbooks.io/android-developer-advanced-course-practicals/unit-5-advanced-graphics-and-views/lesson-13-media/13-1-p-playing-video-with-videoview/13-1-p-playing-video-with-videoview.html
I was trying to follow the steps in the reference but media player is not showing in the activity. So, how can I get rid of this issue?
onCreate Method:
In here I've tried to add MediaController after getting the VideoView id
mVideoView = findViewById(R.id.video_view);
if (savedInstanceState != null) {
   mCurrentPosition = savedInstanceState.getInt(PLAYBACK_TIME);
}
MediaController mediaController = new MediaController(this);
mediaController.setMediaPlayer(mVideoView);

playing video:

(In here, a method for initializing video, Using corresponded Uri)
private void initializePlayer() {
    Uri videoUri = getMedia(VIDEO_SAMPLE);
    mVideoView.setVideoURI(videoUri);

    if (mCurrentPosition > 0) {
        mVideoView.seekTo(mCurrentPosition);
    } else {
        // Skipping to 1 shows the first frame of the video.
        mVideoView.seekTo(1);
        }
     mVideoView.start();
}

private Uri getMedia(String mediaName) {
   return Uri.parse("android.resource://" + getPackageName() +
                "/raw/" + mediaName);
}

A: You're using it incorrectly :
Use like this,
mVideoView = findViewById(R.id.video_view);
if (savedInstanceState != null) {
   mCurrentPosition = savedInstanceState.getInt(PLAYBACK_TIME);
}
MediaController mediaController = new MediaController(this);
mVideoView.setMediaController(mediaController); // Change in this line.

Checkout reference : VideoView

A: package com.example.sagar.videoplay;

import android.net.Uri;
import android.os.Build;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.MediaController;
import android.widget.VideoView;

public class MainActivity extends AppCompatActivity {

    private static final String VIDEO_SAMPLE = "demo";
    private VideoView mVideoView;
    private int mCurrentPosition = 0;
    private static final String PLAYBACK_TIME = "play_time";

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

        mVideoView = findViewById(R.id.video_view);
        if (savedInstanceState != null) {
            mCurrentPosition = savedInstanceState.getInt(PLAYBACK_TIME);
        }
        MediaController mediaController = new MediaController(this);
        mVideoView.setMediaController(mediaController);
    }

    //its a method which takes string as a input and return a url
    private Uri getMedia(String mediaName) {
        return Uri.parse("android.resource://" + getPackageName() +
                "/raw/" + mediaName);
    }

    private void initializePlayer() {
        Uri videoUri = getMedia(VIDEO_SAMPLE);
        mVideoView.setVideoURI(videoUri);

        if (mCurrentPosition > 0) {
            mVideoView.seekTo(mCurrentPosition);
        } else {
            // Skipping to 1 shows the first frame of the video.
            mVideoView.seekTo(1);
        }
        mVideoView.start();
    }

    private void releasePlayer() {
        mVideoView.stopPlayback();
    }

    @Override
    protected void onStart() {
        super.onStart();
        initializePlayer();
    }

    @Override
    protected void onStop() {
        super.onStop();
        releasePlayer();
    }

    @Override
    protected void onPause() {
        super.onPause();

        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
            mVideoView.pause();
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt(PLAYBACK_TIME, mVideoView.getCurrentPosition());
    }
}


text:
Q: Remove Make goal passed from commandline Before beheading me for abusing make, is it possible to remove a goal passed on the command line?
Something like MAKECMDGOALS := $(wordlist 1,2,$(MAKECMDGOALS)) ?
I've tried this but it still goes on and makes the other rules anyway...

A: From the documentation:

MAKECMDGOALS
The targets given to make on the command line. Setting this variable has no effect on the operation of make.

(Emphasis added.)


text:
Q: PostgreSQL table does not exist drop table Employee;

 CREATE TABLE Employee
    (   EmployeeID integer,
        FirstName varchar(24),
        LastName varchar(24),
        Email varchar(48),
        PhoneNumber varchar(12),
        HotelID integer
        PRIMARY KEY (EmployeeID),
    );

    INSERT INTO Employee VALUES (1, 'James', 'Jenkins', 'jj@gmail.com', '0412181111', 1);
    INSERT INTO Employee VALUES (22, 'Roy', 'Bond', 'jb@gmail.com', '0418246192', 1);
    INSERT INTO Employee VALUES (14, 'Rachel', 'Green', 'rg@gmail.com', '0468129367', 1);
    INSERT INTO Employee VALUES (96, 'Eddard', 'Stark', 'es@gmail.com', '0458192716', 1);
    INSERT INTO Employee VALUES (77, 'Anna', 'Nguyen', 'an@gmail.com' , '0418238694', 1);

Error: "psql:employee:1: ERROR:  table "employee" does not exist"
What is the way that the error can be fixed?
Link to the entire doc if anyone wants to take a look: https://docs.google.com/document/d/1r4E7yz4XJxLmO3rmkH4YBVOGfYN5PkhcDSJUyuy7qxw/edit?usp=sharing

A: Your create statement has a comma(,) missing before declaring the primary key. Therefore the table is not getting created. This this:
CREATE TABLE Employee
(   EmployeeID integer,
FirstName varchar(24),
LastName varchar(24),
Email varchar(48),
PhoneNumber varchar(12),
HotelID integer,
PRIMARY KEY (EmployeeID),
FOREIGN KEY (HotelID) REFERENCES Hotel
);

A: The table Employee might not be already created in your database when you are trying to run above snippet. Always have an IF EXISTS check before dropping a table or stored procedure or function.
Your drop query should be.
drop table if exists `Employee`;


text:
Q: Yet another evaluating limit question: $\lim_{n\to \infty} \left(1-\frac{1}{n^2-4}\right)^{3n^2+5}$ How do I begin to evaluate this limit: $$\lim_{n\to \infty} \left(1-\frac{1}{n^2-4}\right)^{3n^2+5}$$
Does it equal to $e^{-1}$? (Please don't use ln.)
Thanks a lot.

A: Let $m=n^2-4$, and
$$ \lim_{m\rightarrow\infty}\left(1-\frac1m\right)^{3m+17}=\left[\lim_{m\rightarrow\infty}\left(1-\frac1m\right)^{m}\right]^3=\frac1{e^3}$$

A: Let $v\longrightarrow \infty$
 and $u\longrightarrow
 1$ , then $\lim _{n\rightarrow \infty}u^v\longrightarrow
\exp (\lim_{n\rightarrow \infty} v(u-1))$.
So, we have
 $$\lim_{n\to \infty} \left(1-\frac{1}{n^2-4}\right)^{3n^2+5}=exp(\lim_{n\to \infty} \left(1-\frac{1}{n^2-4}-1\right)({3n^2+5})=exp(\lim_{n\to \infty} \left(-\frac{3n^2+5}{n^2-4}\right))\\
=exp(-3)$$


text:
Q: Request paremeters appear to be null in servlet This is my jsp:
<form method='post' action='/controller'>

         <input class="form-control" type="text" id="name-input-field" pattern="[A-Z][a-z]+([ -][A-Z][a-z]+)*" required >

</form>

This is my servlet:
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
      req.getParameter("name-input-field");//appears null
}

Please Help me find the mistake.

A: The getParameter() method takes in the name attribute of input tag and not the id attribute. It returns the value of value attribute of the input.
Add name="name-input-field" to your input tag to get its value in Servlet.

A: As Yogesh said the req.getParameter uses name, but also you have to know this:
Imagine this scenario:
You have to disable the input option or whatever you could use this in your html:
<input type="text" name="ame-input-field" disabled>

Well Sr you will get a null because a disable input won't be send in your request ;) so be carefull


text:
Q: Using the R forecast package with missing values and/or irregular time series I am impressed by the R forecast package, as well as e.g. the zoo package for irregular time series and interpolation of missing values.
My application is in the area of call center traffic forecasting, so data on weekends is (nearly) always missing, which can be nicely handled by zoo. Also, some discrete points may be missing, I just use R's NA for that.
The thing is: all the nice magic of the forecast package, such as eta(), auto.arima() etc, seem to expect plain ts objects, i.e. equispaced time series not containing any missing data. I think real world applications for equispaced-only time series are definitely existent, but - to my opinion -  v e r y  limited.
The problem of a few discrete NA values can easily be solved by using any of the offered interpolation functions in zoo as well as by forecast::interp. After that, I run the forecast.
My questions:

*

*Does anyone suggest a better solution?

*(my main question) At least in my application domain, call center traffic forecasting (and as far as I can imagine most other problem domains), time series are not equispaced. At least we have recurring "business days" scheme or something. What's the best way to handle that and still use all the cool magic of the forecast package?
Should I just "compress" the time series to fill the weekends, do the forecast, and then "inflate" the data again to re-insert NA values in the weekends? (That would be a shame, I think?)
Are there any plans to make the forecast package fully compatible with irregular time series packages like zoo or its? If yes, when and if no, why not?
I'm quite new to forecasting (and statistics in general), so I might overlook something important.

A: You should be very careful when you apply interpolation before further statistical treatment. The choice you do for your interpolation introduces a bias into your data. This is something you definitely want to avoid, as it could alter the quality of your predictions.
In my opinion for missing values such as those you mentioned, that are regularly spaced in time and that correspond to a stop in the activities, it might be more correct to leave these days out of your model. In the the little world of your call center (the model you are building about it), it might be better to consider that time simply stopped when it is closed instead of inventing measurements of a non-existing activity.
On the other hand the ARIMA model has been statistically built on the assumption that data is equally spaced. As far as I know there is no adaptation of ARIMA to your case. If you are just missing a few measurements on actual working days, you might be forced to use interpolation.

A: I am not an R expert so maybe there is a simpler way but I have come across this before.  What I did before is implement a function that measures the distance (in time units) between the actual dates and saves that in a new column in the existing time series.  So we have something like:
index/date | value | distance
01.01.2011 |  15   |   1
02.01.2011 |  17   |   3
05.01.2011 |  22   |   ..

This way, if your time series is not yet associated with an actual series of points in time (or wrong format or whatever), then you can still work with it.
Next, you write a function that creates a new time series for you, like so:
First, you calculate how many units of time the time series actually would have between the dates of your chosing and create that timeline in zoo or ts or whatever the choice is with empty values.
Second, you take your incomplete time series array and, using a loop, fill the values into the correct timeline, according to the limits of your choosing.  When you come upon a row where the unit distance is not one (days (units) are missing), you fill in interpolated values.
Now, since this is your function, you can actually chose how to interpolate. For example you decide that if the distance is less than two units, you use a standard linear interpolation. If a week is missing, you do something else and if a certain threshold of missing dates is reached, you give out a warning about the data - really whatever you want to imagine.
If the loop reaches the end date you return your new ts.
Advantage of such a function is that you can use different interpolations or handling procedures depending on the lengths of the gap and return a cleanly creates series in the format of your choosing. Once written, it allows you to gain clean and nice ts out of any sort of tabular data. Hope this helps you somehow.

A: I would not interpolate the data before estimating the model on this data, as @Remi noted. It's a bad idea. An extreme example: imagine you have two data points Jan 2013 and Jan 2014. Now interpolate 10 monthly points in between: Feb through Dec 2013, and run regression on the monthly date. In reality it's not going to be this bad, but it's the same idea: you'll be inflating your statistics at best.
The way to go is to use time series methods which handle missing data. For instance, state space methods. Take a look at astsa R package. It comes with an excellent book on time series analysis. This will handle missing data nicely. Matlab now has a similar functionality in ssm package. You have to learn converting your models into state space form, but you have to learn this anyways if you want to step away from auto.arima "magic".


text:
Q: How are docker containers stored in the ram and executed? I would like to know how the Docker containers are managed by the operating system. I could find  some explanations here: https://stackoverflow.com/a/47784145/11377751, but I can not understand well.
I know the basics of the operating system (notions about PCB, ram, CPU, kernel, syscall, etc.).
But I do not understand how the containers are managed by the OS:

*

*Are containers processes or are they "emulated" by the Docker Engine (which would be the only process, with its threads)? How can I represent a container in the ram ?

*If, in my container, I launch a C application that contains "fork();", who makes the call to the kernel: the container or the Docker Engine? Who duplicates the pcb ? Or a "malloc (..);"?

*What is the concept of namespace in the kernel? in the ram? Are these tables that define access rights or something? Why does wikipedia say that this notion is essential for containers, knowing that in schemas Docker Engine is represented between containers and the kernel?

image :
This is an image I found here : https://stackoverflow.com/a/42111368/11377751

thank you very much in advance

A: Preface: this was tested on Arch Linux

*

*Containers are processes. We have dockerd and containerd - each of them only once. Then we have docker and containerd-shim processes for each container, that is running. Notice, that containerd-shim is parent of container. It's purpose is to:

*

*First it allows the runtimes, i.e. runc,to exit after it starts the container.  This way we don't have to have the long running runtime processes for containers.  When you start mysql you should only see the mysql process and the shim.

*Second it keeps the STDIO and other fds open for the container incase containerd and/or docker both die.  If the shim was not running then the parent side of the pipes or the TTY master would be closed and the container would exit.

*Finally it allows the container's exit status to be reported back to a higher level tool like docker without having the be the actual parent of the container's process and do a wait4.
( taken from https://groups.google.com/forum/#!topic/docker-dev/zaZFlvIx1_k )

*Please read 2 good answers about system calls ( https://stackoverflow.com/a/32842491/5247040 ) and roles of docker's parts ( https://stackoverflow.com/a/46650343/5247040 ). Another good read https://medium.com/devopslinks/docker-containerd-standalone-runtimes-heres-what-you-should-know-b834ef155426
EDIT: Quick answer: C application calls fork and malloc => Linux kernel.
I was wrong, Docker Engine doesn't participate in syscalls, all control happens via namespaces / seccomp ( https://stackoverflow.com/a/34871045/5247040 )

*Representations of namespace in ram are quite different, you can check source code for

*

*user namespaces https://elixir.bootlin.com/linux/v5.0.7/source/kernel/user_namespace.c

*pid namespaces https://elixir.bootlin.com/linux/v5.0.7/source/kernel/pid_namespace.c

*net namespaces https://elixir.bootlin.com/linux/v5.0.7/source/net/core/net_namespace.c

*etc.

Why does wikipedia say that this notion is essential for containers

Because "Various container software use Linux namespaces in combination with cgroups to isolate their processes, including Docker[8] and LXC" ( https://en.wikipedia.org/wiki/Linux_namespaces )
Basically namespaces are the instrument, with which Docker Engine controls resources of containers


text:
Q: AWS: ClientError: An error occurred (ValidationException) when calling the CreateTransformJob operation: Could not find model I am new here and am strugling with some basic things.
I am trying to implement a DeepAR model, but maybe due to an update from sagemaker it doesn't find the correct path as it did on the example..
Can someone tell me why is it happening and how o fix it?
Error: ClientError: An error occurred (ValidationException) when calling the CreateTransformJob operation: Could not find model "arn:aws:sagemaker:eu-central-1:900386373554:model/forecasting-deepar-2022-06-21-14-12-51-560".
This is the Batch Transformation I am trying to implement:
-Batch Transform
import boto3
-Create the SageMaker Boto3 client
boto3_sm = boto3.client('sagemaker')
import time
from time import gmtime, strftime
batch_job_name = 'Batch-Transform-' + strftime("%Y-%m-%d-%H-%M-%S", gmtime())
input_location = 's3://sagemaker-eu-central-1-900386373554/deepar-rossmann/input/prediction_input.json'
output_location = 's3://{}/{}/output/{}'.format(bucket, prefix, batch_job_name)
request =
{
"BatchStrategy": "SingleRecord",
"MaxPayloadInMB": 100,
"Environment": {
"DEEPAR_INFERENCE_CONFIG" : "{ "num_samples": 200, "output_types": ["mean"] }"
},
"TransformJobName": batch_job_name,
"ModelName": 'forecasting-deepar-2022-06-21-14-12-51-560',
"TransformOutput": {
"S3OutputPath": output_location,
"Accept": "application/jsonlines",
"AssembleWith": "Line"
},
[...]
I am following this project: https://github.com/CatherineSai/project_sales_prediction_DEEPAR
Notebook 3 of 3 step 49
--> ModelName is copied from the finished training job at aws console
Thanks

A: In order to launch a SageMaker Batch Transform Job you require a SageMaker Model. Kindly confirm that the ModelName you are passing exists in the Models page in the Console (Inference tab  > Models)


text:
Q: $L^{q,\infty}(\mu) \subset L^p(\mu)$ with $1 \leq pLet $\mu$ be a finite measure on a measurable space $(X,\Sigma)$. I want to prove that exists $C > 0$ so that $$ \| f\|_p \leq C \| f \|_{q,\infty}$$ when $1 \leq p < q < \infty$, where $$ \| f \|_{q,\infty} = \sup\limits_{\lambda > 0}\lambda \mu(\{x \in X: |f(x)| > \lambda \} )^{1/q}. $$ I think the key of the proof relies in the fact that $\mu$ is a finite measure, because it's not difficult to show a counterexample when you consider the Lebesgue measure on $\mathbb{R}$.
My best aproach consists of putting $$ \int_X |f|^p d\mu = \int_0^\infty \mu\{ |f| > t\} p t^{p-1} dt = \int_0^\lambda\mu\{ |f| > t\} p t^{p-1} dt  + \int_\lambda^\infty \mu\{ |f| > t\} p t^{p-1} dt,  $$  where $\lambda > 0$. For the first integral it's easy to see that it's $\leq \mu(X) \frac{\lambda^p}{p} = C_1 \lambda^p$, but I'm stuck with the second integral and I don't know how to continue.
Any idea of how to continue the proof? Do yo know any different approach to the solution? Thank you very much.

A: For the second integral, bound $\mu\{ |f| > t\}$ by $t^{-q}\left\lVert f\right\rVert_{q,\infty}^q$ and the integral can be therefore controlled by a constant times $\lambda^{-q+p}$. Then choose $\lambda$ appropriately.