text:
Q: Merge and save results after selections using loop I want to merge shapefiles after selection inside a loop and then save results to excel files. However, the codes could save the last result to excel files and can not save each merge file.
import arcpy
arcpy.env.workspace = "D:/STAR/GISpro.gdb"
arcpy.env.overwriteOutput = True #overwrite the exsiting files
selection1 = '"gridcode"<=14.3'
selection2 =  '"gridcode">14.3 AND "gridcode"<=28.6'
selection3 =  '"gridcode">28.6 AND "gridcode"<=42.9'
selection4 =  '"gridcode">42.9 AND "gridcode"<=57.2'
selection5 =  '"gridcode">57.2 AND "gridcode"<=71.5'
selection6 =  '"gridcode">71.5 AND "gridcode"<=85.8'
selection7 =  '"gridcode">85.8 AND "gridcode"<=100'

selections = [selection1, selection2, selection3, selection4,
          selection5, selection6, selection7]
layers = ["wqi_Conshp_clip27171","wqi_south8shp_clip27171"]

fc = "wqi_north8shp_clip27171"

list = []

rows = arcpy.SearchCursor(fc)
for row in rows:
pop = row.getValue("Shape_Area")
list.append(pop)

Sum_Area27171 = sum(list)

for layer in layers:

arcpy.MakeFeatureLayer_management(layer,layer)

count = 0
statisticstables = []
selectionmerge = layer + "_Merge" # UPDATE THIS

for selection in selections:
    count = count + 1
    selectionname = layer + "level" + str(count)

    statisticstables.append(selectionname)
    arcpy.SelectLayerByAttribute_management(layer,'NEW_SELECTION',selection)
    arcpy.Statistics_analysis(layer,selectionname,[["Shape_Area","sum"]])
    arcpy.AddField_management(selectionname,'rate','DOUBLE')
    arcpy.CalculateField_management(selectionname,'rate','!SUM_Shape_Area!/{}'.format(Sum_Area27171),'PYTHON_9.3')
    print selectionname

try:
arcpy.Merge_management(statisticstables, selectionmerge) #move this line out of the loop.
print selectionmerge
except ExecuteError as e:
print(e)
print(arcpy.GetMessages())

outpath = "D:\\STAR\\info_data_test_results"
outresult = outpath + "\\" + layer + "_Merge" + ".xls"
arcpy.TableToExcel_conversion(selectionmerge,outresult)

As you can see, I use "merge_management" to merge all results from selection loop but could just save the last result as an excel file. Could anyone provide some suggestions about this problem?

A: This is somewhat guessing since your code snippet doesn't include some of the details, however: it looks like you may be trying to merge a dataset with a dataset that doesn't exist already. The first time you go through the loop, the table you've named "selecationmerge" doesn't exist; in fact it's assigned to an empty string. Additionally it's awkward (and, likely slower) to repeatedly merge.
Two options:

*

*build a list of the tables to merge and then merge all at once

*Append the second (and subsequent) tables after the first table is created. Note that this would change the input layer, so if you want to keep the output separate initially it's not the best option.

Modifying your code from the question for the first option (merge after loop is finished):
# set your environment settings if you haven't done so already
arcpy.env.workspace = r"path_to_workspace"
count = 0
statisticstables = []
selectionmerge = r"path_to_output_table" # UPDATE THIS
for selection in selections:
    count = count + 1
    selectionname = "stats27171wqi_Conlevel" + str(count)
    print selectionname
    statisticstables.append(selectionname)
    arcpy.SelectLayerByAttribute_management('wqi_Conshp_clip27171','NEW_SELECTION',selection)
    arcpy.Statistics_analysis('wqi_Conshp_clip27171',selectionname,[["Shape_Area","sum"]])
    arcpy.AddField_management(selectionname,'rate','DOUBLE')
    arcpy.CalculateField_management(selectionname,'rate','!SUM_Shape_Area!/{}'.format(Sum_Area27171),'PYTHON_9.3')

try:
    arcpy.Merge_management(statisticstables, selectionmerge) #move this line out of the loop.
    print(arcpy.GetMessages())
except ExecuteError as e:
    print(e)
    print(arcpy.GetMessages())

Additional resources:
Merge: http://desktop.arcgis.com/en/arcmap/10.3/tools/data-management-toolbox/merge.htm#GUID-7D7965A6-8486-4AF1-AAFD-C0168DFD1124
Append: http://desktop.arcgis.com/en/arcmap/10.3/tools/data-management-toolbox/append.htm#C_GUID-FA9BFB50-2B63-4355-929C-E22B915A9103

A: It has been a while since I post this question. The script has been updated since then and I post my answer in the following part for other users.
list = []
rows = arcpy.SearchCursor(bufferclip)
SumArea = bufferclip + "Area"

for row in rows:
   area = row.getValue("Shape_Area")
   list.append(area)
   SumArea = sum(list)
print SumArea

arcpy.MakeFeatureLayer_management(bufferclip,bufferclip)

count = 0 #define a number for the name of selected name
statisticstables = []
selectionmerge = bufferclip + "_Merge"

for selection in selections:
    count = count + 1
    selectionname = bufferclip + "level" + str(count)
    statisticstables.append(selectionname)
    ratename = "rate" + str(point)
    arcpy.SelectLayerByAttribute_management(bufferclip,'NEW_SELECTION',selection)
    arcpy.Statistics_analysis(bufferclip,selectionname,[["Shape_Area","sum"]])

    fields = ['FREQUENCY','Sum_Shape_Area'] #do not set OBJECTID
    if int(arcpy.GetCount_management(selectionname).getOutput(0)) == 0:
       icur = arcpy.da.InsertCursor(selectionname,fields)
       icur.insertRow([0,0])
       del icur
    arcpy.AddField_management(selectionname,ratename,'DOUBLE') #add a new field
    arcpy.CalculateField_management(selectionname,ratename,'!SUM_Shape_Area!/{}'.format(SumArea),'PYTHON_9.3')
    print selectionname
    arcpy.Merge_management(statisticstables, selectionmerge)
pathname = "scenairo" + str(i)
outpath = "D:\\WQResults\\25miles\\" + pathname
outresult = outpath + "\\" + selectionmerge + ".xls"
arcpy.TableToExcel_conversion(selectionmerge,outresult)


text:
Q: How do I tell DataMapper to use "timestamp with time zone" for DateTime properties? By default, DataMapper creates DateTime properties of type timestamp without time zone in PostgreSQL.  I'd like to change that default for my project to timestamp with time zone.  How can this be done?

A: Just set ENV['TZ'] = 'your timezone'

A: just in case some jruby users pass by:
you need to set ENV['TZ'] = 'your timezone' and
org.joda.time.DateTimeZone.setDefault(org.joda.time.DateTimeZone.forID('your timezone'))

'UTC' works fine for me. for other timezone you might need to dig into joda-time.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Test rational singularities after forming invariants Let $R$ be a normal local domain of dimension $2$ and odd residue characteristic endowed with the action of the finite group $G \cong \mathbb{Z}/2\mathbb{Z}$. Suppose that the ring of invariants $R^G$ has rational singularities. Does this mean that $R$ also have rational singularities?
Of course, one could pose the question more generally where $G$ is finite of order invertible on $R$ (and $R$ is $2$-dimensional). I am not really interested in $R$ of residue characteristic $0$, but if there already are such counterexamples, then they are of course welcome. Also, I recall that if $R$ has rational singularities, then so does $R^G$ (as long as the order of $G$ is invertible in $R$).
My guess is that the answer is 'no', but I don't have a counterexample. A 'yes' would be great, even if one needs to assume additional hypotheses for that.
For context, let me recall that a normal surface singularity like above is rational if some (equivalently, any) desingularization $X \rightarrow \mathrm{Spec}(R)$ with $X$ regular obtained by successively blowing up closed points satisfies $H^1(X, \mathcal{O}_X) = 0$.


text:
Q: Pomodoro Clock's time doesn't work I am currently working on Pomodoro Clock project, everything seems working on plus/minus buttons in both Session and Break but time itself is not working (in blue circle area), something is little missing, please see below.
var time = document.querySelector(".time");
var timerBody = document.querySelector(".timerBody");
var currentWork = document.querySelector(".currentWork");

var sessionLength = document.querySelector(".sessionLength");
var minusSessionLength = document.querySelector(".minus-sessionLength");
var plusSessionLength = document.querySelector(".plus-sessionLength");

var breakLength = document.querySelector(".breakLength");
var minusBreakLength = document.querySelector(".minus-breakLength");
var plusBreakLength = document.querySelector(".plus-breakLength");

var isLoop = false;
var isSession = true;

var Sound = new Audio('http://www.oringz.com/oringz-uploads/sounds-917-communication-channel.mp3');

function GetTime(timeString){
  timeString = timeString.split(':');
  var seconds = parseInt(timeString[0]) * 60 + parseInt(timeString[1]);
  return seconds;
}

// Errors here
function setTime(seconds) {
  var timeString = [];
  timeString.push(Math.floor(seconds/60));
  timeString.push((seconds % 60 < 10) ? '0' + (seconds % 60).toString() : (seconds % 60));
  return timeString.join(':')
}

var currentTime = GetTime(time.innerHTML);

minusSessionLength.addEventListener('click', function(event){
  if(!isLoop) {
    var STime = parseInt(sessionLength.innerHTML);
    if(STime - 1 >= 1)
      STime--;
    sessionLength.innerHTML = STime;
    if(isSession) {
      time.innerHTML = STime + ':00';
      currentTime = GetTime(time.innerHTML);
    }
  }
});

plusSessionLength.addEventListener('click', function(event){
  if(!isLoop) {
    var STime = parseInt(sessionLength.innerHTML);
    sessionLength.innerHTML = ++STime;

    if(isSession){
      time.innerHTML = STime + ':00';
      currentTime = GetTime(time.innerHTML);
    }
  }
});

minusBreakLength.addEventListener('click', function(event){
  if(!isLoop) {
    var BTime = parseInt(breakLength.innerHTML);
    if(BTime - 1 >= 1) {
      BTime--;
      breakLength.innerHTML = BTime;
    }

    if(!isSession) {
      time.innerHTML = BTime + ':00';
      currentTime = GetTime(time.innerHTML);
    }
  }
});

plusBreakLength.addEventListener('click', function(event){
  if(!isLoop) {
    var BTime = parseInt(breakLength.innerHTML);
    breakLength.innerHTML = ++BTime;

    if(!isSession) {
      time.innerHTML = BTime + ':00';
      currentTime = GetTime(time.innerHTML);
    }
  }
});

var loop;

  timerBody.addEventListener('click', function(event){
    if(isLoop) {
      clearInterval(loop);
      currentWork.innerHTML = 'Paused';
      isLoop = !isLoop;
    }
    else {
      currentWork.innerHTML = isSession ? 'Session' : 'Break';

      loop = setInterval(function() {
        time.innerHTML = SetTime(--currentTime);
        if(currentTime < 1) {
          if(isSession) {
            currentWork.innerHTML = 'Break';
            time.innerHTML = breakLength.innerHTML + ':00';
            currentTime = GetTime(time.innerHTML);
            timerBody.style.borderColor = "#80FF80";
            Sound.play();

            var isBreakTitle = true;
            var changeTitle = setInterval(function(){
              document.title = isBreakTitle ? '***Break!***' : '************';
              isBreakTitle = !isBreakTitle;
            }, 100);

            setTimeout(function() {
              clearInterval(changeTitle);
              document.title = 'Pomodoro clock';
            }, 5000);
            isSession = !isSession;
          }
          else {
            currentWork.innerHTML = 'Session';
            time.innerHTML = sessionLength.innerHTML + ':00';
            currentTime = GetTime(time.innerHTML);
            timerBody.style.borderColor = "#F64141";
            Sound.play();

            var isSessionTitle = false;
            var changeTitle = setInterval(function() {
              document.title = isSessionTitle ? '***Session!****' : '************';
              isSessionTitle = !isSessionTitle;
            }, 100);

            setTimeout(function() {
              clearInterval(changeTitle);
              document.title = 'Pomodoro clock';
            }, 5000);
            isSession = !isSession;
          }
        }
      }, 1000);
      isLoop = !isLoop;
    }

  });

Here's mispelling mistake which should be "SetTime"
function SetTime(seconds) {
  var timeString = [];
  timeString.push(Math.floor(seconds/60));
  timeString.push((seconds % 60 < 10) ? '0' + (seconds % 60).toString() : (seconds % 60));
  return timeString.join(':')
}

Hope that helps to your future issues.


text:
Q: Number of different basis in linear space. Let be $\mathbb{F}_{q}^{n}$ is field of dimension - $q^n$. Let $C$ be linear code of $dimC = k$.
We have three questions :
1) Number of basises in $C$ ($k$ - dimensional linear subspace)?
2) Number of different linear codes in $\mathbb{F}_q^n$?
3) Number of different generator matrices for code of $dim = k$ in $\mathbb{F}_q^n$?
My attempt :
1) Let $C$ be a linear code in $\mathbb{F}_q^n$ with $dim = k$. Then number of basises in $C$ is $(q^k-1)\dots(q^k - q^{k-1})$.
2) Number of linear codes is number of different $k-$dimensional subspaces in $\mathbb{F}_q^n$. It should be $\dfrac{(q^n-1)\dots (q^n-q^{k-1})}{(q^k-1)\dots(q^k - q^{k-1})}$.
3) Number of generator matrices is $(q^n-1) \dots (q^n - q^{k-1})$.
Am I right?

A: For $1)$, you're counting different orders of choosing the basis as different. Since a basis defined as a set, not a tuple, you need to divide by $k!$.
Your result for $2)$ is correct, since you've divided the number of "basis $k$-tuples" in $\mathbb F_q^n$ by the one within the resulting subspaces, so the factors of $k!$ cancel in this case.
In $3)$, the question is unclear; it could be read to ask for the number of different generator matrices for a particular code of dimension $k$ in $\mathbb F_q^n$, or for any such code. Your result is correct for the latter interpretation.


text:
Q: UISearchBar in Xcode 5 I implemented the UISearchBar option in my Json data table. However, whenever I am trying to search it, the program crashes. Highly appreciate help on this.
my table view controller's header and implementation files are given below
Header file.
#import <UIKit/UIKit.h>

@interface byTitleViewController : UITableViewController

@property (nonatomic, strong) NSMutableArray * jsonArray;
@property (nonatomic, strong) NSMutableArray * songsArray;
@property (strong, nonatomic) NSMutableArray* filteredTableData;

- (void) retriveData;

@property (weak, nonatomic) IBOutlet UISearchBar *searchBar;
@property (nonatomic, assign) bool isFiltered;

@end

Implementation file
#import "byTitleViewController.h"
#import "songs.h"

#define getDataURL @"http://fetchpin.com/byTitle.php"

@interface byTitleViewController ()

@end

@implementation byTitleViewController

@synthesize jsonArray, songsArray, filteredTableData, searchBar, isFiltered;

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.title = @"By Title";

    searchBar.delegate = (id)self;

    [self retriveData];
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSUInteger rowCount;

    if(self.isFiltered)
        rowCount = filteredTableData.count;
    else
        rowCount = songsArray.count;

    return rowCount;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];

    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
    }

    songs* songlist;

    if (isFiltered) {
        songlist = [filteredTableData objectAtIndex:indexPath.row];

    }else{
        songlist = [songsArray objectAtIndex:indexPath.row];
    }

    cell.textLabel.text = songlist.songTitle;

    return cell;

    // Configure the cell...

    /*songs * songObject;

    songObject = [songsArray objectAtIndex:indexPath.row];

    cell.textLabel.text = songObject.songTitle;

    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;

    return cell;
        */
}

// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    return YES;
}

- (void) retriveData{

    NSURL * url = [NSURL URLWithString:@"http://fetchpin.com/byTitle.php"];
    NSData * data = [NSData dataWithContentsOfURL:url];

    jsonArray = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];

    songsArray = [[NSMutableArray alloc] init];

    for (int i = 0; i < jsonArray.count; i++) {
        NSString * sId = [[jsonArray objectAtIndex:i] objectForKey:@"id"];
        NSString * sTitle = [[jsonArray objectAtIndex:i] objectForKey:@"title"];

        [songsArray addObject:[[songs alloc]initWithSongTitle: sTitle andSongID: sId]];

    }

    //[self.tableView reloadData];
}

//search bar ...

-(void)searchBar:(UISearchBar*)searchBar textDidChange:(NSString*)text
{
    if(text.length == 0)
    {
        isFiltered = FALSE;
    }
    else
    {
        isFiltered = true;
        filteredTableData = [[NSMutableArray alloc] init];

        for (songs * sTitle in songsArray)
        {
            NSRange titleRange = [sTitle.songTitle rangeOfString:text options:NSCaseInsensitiveSearch];

            if(titleRange.location != NSNotFound)
            {
                [filteredTableData addObject:sTitle];
            }
        }
    }

    [self.tableView reloadData];
}

@end

A: It looks like the problem is that some of the objects you are loading from the JSON have a title that is not an NSString, but an NSNull. Adding a check for NSNull in the textDidChange: method should solve the problem:
if(![sTitle.name isKindOfClass:[NSNull class]])
{
    NSRange titleRange = [sTitle.name rangeOfString:text options:NSCaseInsensitiveSearch];

    if(titleRange.location != NSNotFound)
    {
        [filteredTableData addObject:sTitle];
    }
}

Alternately, you could filter out songs with an NSNull title in your retrieveData method.


text:
Q: XAML array issue I am using the following arrays as parameters to my value converter.  I can't figure why "params2" is passed as an ArrayExtension and "params1" is passed as a simple TextBlock[] array.
<Window.Resources>
    <x:Array Type="TextBlock" x:Key="params1">
        <TextBlock Text="{x:Static local:Constants.MyDir}"></TextBlock>
        <TextBlock>25</TextBlock>
    </x:Array>
</Window.Resources>

<TabItem.Resources>
    <x:Array Type="TextBlock" x:Key="params2">
        <TextBlock Text="{x:Static local:Constants.MyDir}"></TextBlock>
        <TextBlock>55</TextBlock>
    </x:Array>
</TabItem.Resources>

Image Viewer XAML:
<Window x:Class="TotalViewer.ImageViewerWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:TotalViewer"
    Title="ImageViewerWindow" Name="ImageViewerWindow1">

    <Window.Resources>
        <x:Array Type="TextBlock" x:Key="params1">
            <TextBlock Text="{x:Static local:Constants.MyDir}"></TextBlock>
            <TextBlock>25</TextBlock>
        </x:Array>
   </Window.Resources>

    <Grid>
        <Image Source="{Binding ElementName=ImageViewerWindow1, Path=ImagePath,
            Converter={StaticResource ImageConverter},
            ConverterParameter={StaticResource params1}}"/>
    </Grid>
</Window>

A: Well, I kinda gave up for the moment because I need to get this part working.   In the converter, I test if the parameter is either ArrayExtension or TextBlock[].  If it's ArrayExtension, it will get converted to TextBlock[].


text:
Q: Swift - disable accessibility voiceover? I was curious if there was a way to disable the voiceover accessibility (or any other type of accessibility feature for that matter - like hear aids, captioning, etc.) in swift?
Essentially, I'm trying to build an application that has a very high likelihood of being used by people with visual impairments and I've tailored my entire application for such people.
But given that this target group may have the voiceover accessibility feature on, can I disable that only within my application?

I see that on xcode 7, underneath the identity inspector, there is a section for accessibility (picture below) and I tried unchecking that box but it seems like voiceover and the highlighting focus feature are still in effect. Let me know if you have any suggestions or comments, thanks.

A: You can set
element.accessibilityTraits = UIAccessibilityTraitAllowsDirectInteraction

on any elements that you want to provide custom audio/interactions for.

A: This can also be accomplished in storyboard (See photo).
I came across this thread because I was trying to do this for on a game scene tucked inside of a view container.  To get it to work, I was able to set
.accessibilityTraits = UIAccessibilityTraitAllowsDirectInteraction
on each SKNode that had custom accessibility created for it, and then was able to select the proper options (again see screenshot) on the SKView -> View in Storyboard to allow the game screen to work.


text:
Q: Delete Row Result SQL Query I am new in PHP. I am android developer and does not know PHP enough. I have developed one function which provide me numbers from MySQL database. I want delete that numbers instant as soon as it pass me. I am currently doing it like below
function getAllNumbers() {
    require_once("includes/conf.php");
    global $conn;
    $sql = "SELECT number from number_list WHERE server=1";
    $result = $conn->query($sql);
    $data = array();
    if($result) {
        while($row = $result->fetch_row()) {
        array_push($data, $row[0]);
        $delete = "DELETE number from number_list WHERE server=1";
        $result = $conn->query($delete);

        }
    }
    $response["data"] = $data;
    return $response;
}

My Table Structure is like below
id  int(11) NO  PRI NULL    auto_increment
name    varchar(50) NO      NULL
number  varchar(50) NO      NULL
server  int(10) NO      0
status  int(1)  NO      -1
last_act    timestamp   NO      CURRENT_TIMESTAMP
user_id int(11) NO  MUL NULL
created_at  timestamp   NO      CURRENT_TIMESTAMP
disable int(11) NO      0
notify  int(1)  NO      1
fcm varchar(500)    NO      NULL

But I am feeling that if there any new number arrive in database between number select query and delete query it will delete it without select number in first query. So I am looking to delete only rows which get selected in first query. Let me know if there anything I need to change in my codes.
Thanks a lot :)

A: So if you select the id in the first query as that is the unique key you can use that to delete just this row
function getAllNumbers() {
    require_once("includes/conf.php");
    global $conn;
    $sql = "SELECT number,id from number_list WHERE server=1";
    $result = $conn->query($sql);
    $data = array();
    if($result) {
        while($row = $result->fetch_row()) {
            $data[] = $row[0];
            $id = $row[1];
            $delete = "DELETE number from number_list WHERE id = $id";
            $result = $conn->query($delete);
        }
    }
    $response["data"] = $data;
    return $response;
}


text:
Q: Cannot seem to get the value of this input field. What is wrong? Whenever I run this code in my browser and when I click on one of the buttons I can't seem to get the alert to display the value. It just says undefined. But I don't see what I'm doing wrong here.
Here is the code:

Optelmachine in Javascript

     <form id="calculator">
        <textarea name="field" id="field" cols="32" rows="3"></textarea>

        <input  type="button"   class="waarde"  name="waarde"   value="1"  onclick="getInputValue()">
        <input  type="button"   class="waarde"  name="waarde"   value="2"  onclick="getInputValue()">
        <input  type="button"   class="waarde"  name="waarde"   value="3"  onclick="getInputValue()">

        <input  type="button"   class="waarde"  name="waarde"   value="4"  onclick="getInputValue()">
        <input  type="button"   class="waarde"  name="waarde"   value="5"  onclick="getInputValue()">
        <input  type="button"   class="waarde"  name="waarde"   value="6"  onclick="getInputValue()">

        <input  type="button"   class="waarde"  name="waarde"   value="7"  onclick="getInputValue()">
        <input  type="button"   class="waarde"  name="waarde"   value="8"  onclick="getInputValue()">
        <input  type="button"   class="waarde"  name="waarde"   value="9"  onclick="getInputValue()">

        <input  type="button"   class="waarde"  name="waarde"   value="0"  onclick="getInputValue()">
        <input  type="button"  class="waarde1" name="reset"    value="Clear" onclick="addition()">
     </form>

A: Try this
<input  type="button"   class="waarde"  name="waarde"   value="0"  onclick="getInputValue(event)">
     </form>


text: Q: Range Bar Chart in Android I want to create below chart in android and I know about MpChart and AnyChart lib for chart implementation but how to start with this chart I don't know which chart i need to customize! Can anybody help me regarding this it will be very grateful for me.


text:
Q: Code Joomla Template with Twitter Bootstrap I am trying to learn how I can build a Joomla template based on Twitter Bootstrap. I am quite familiar in building within Joomla 2.5 and I have written a template using HTML5, but just wanted to clarify a few questions for my understanding.
I have written my HTML/CSS based on a 960px width but not sure how I would change this to use the row/span classes within Bootstrap.
As Bootstrap is based on a 12 grid layout, would I build 2 blank span 2 classes at the start and at the end to have a layout of 8 grids within the middle?
Or am i going about this the wrong way?
In regards to the modules, I am quite familiar in how I can add this, but just wanted to familiarise myself with the layout first before adding in the rest of the data within the site.
My HTML:
    <!DOCTYPE html>

    <title>Joomla Layout</title>
    <link href="styles.css" rel="stylesheet" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

home

home

home

home

home

home

home

My SideBar

This is my section1

This is my section2

This is my footer

My CSS:
    * {
    margin: 0px;
    padding: 0px;
}

body {
    background:#FFF;
}

.container {
    margin: 0px auto 0px auto;
    height: 1020px;
    width:960px;
    border:1px solid #CCC;
}

header  {
    text-align:center;
    height:16.27450980392157%;
    width:100%;
}

nav {
    float:left;
    height:6.372549019607843%;
    width:100%;
    text-align:center;
    background:#fe6b01;
}

.banners {
    float:left;
    height:24.80392156862745%;
    width:100%;
    background:#01AEF0;
    text-align:center;
}

.sidebar {
    height:600px;
    width:32.29166666666667%;
    background:#ec8400;
    float:left;
    text-align:center;
}

.content {
    height:300px;
    width:67.70833333333333%;
    background:#CCC;
    float:right;
    text-align:center;
}

.list {
    height:300px;
    width:67.70833333333333%;
    background:#01AEEF;
    float:right;
    text-align:center;
}

footer {
    text-align:center;
    font-weight:bold;
    height:16.37254901960784%;
    width:100%;
    background:#efefef;
    text-align:center;
    margin-top:-80px;
}

ul li {
    display:inline;
    text-align:left;
    margin:30px;
}

a {
    text-decoration:none;
    color:#fff;
    font-size:16px;
    font-weight:bold;
    font-family:Arial, Helvetica, sans-serif;
}

@media only screen and (max-width: 960px) {

    .container {
    height:816px;
    width:768px;
}

@media only screen and (max-width: 768px) {

    .container {
    height:653px
    width:615px;
}

@media only screen and (max-width: 600px) {

    .container {
    height:510px;
    width:480px;
    }

    .sidebar {
    width:100%;
    float:left;
    }

    .content {
    width:100%;
    float:right;
}

.list {
    width:100%;
    float:right;
}

Any advice would be really appreciated.
Thanks in advance.

A: Firstly you need to load the Framework in with:
// Add JavaScript Frameworks
JHtml::_('bootstrap.framework');

It is built using a 12grid format yes, so you would adjust the spans accordingly to the output you wanted. Your HTML at present has no bootstrap setup.
As a good example, look at the Joomla! Protostar Template this is by default a Bootstrap template.
It is located in:
/Joomla! root/templates/protostar/
And it will give you all the basics you need to get you going!
You might also find blank.vc very useful too!


text:
Q: Determining the points at constant distance $d$ from parabola $y = x^2$ My friends recently learned about Locus and how parabola are the points equdistant from a fixed point (focus) and a straight line (directrix). However, now we're trying to find an equation or set of equations for the points at a constant distance from the parabola of function y = x^2 and cannot be closer/further from any point on the curve than any arbitrary distance (just use variable d).
As they have more experience with derivatives, they've gone with using the equation of the normal to find these equations. I've tried to use the distance formula, but with no success.
It would be awesome if we got some help on this!

A: We have $f(x) = x^2$. A tangent vector at each point $P(x)= (x, f(x))$ is $$
t(x)=(1, f'(x)).
$$
The normal vectors are orthogonal to the tangent vectors which gives
$$
n_i(x) = (\mp f'(x), \pm 1)
$$
and satisfies
$$
t(x) \cdot n_i(x)
= 1 \cdot (\mp f'(x)) + f'(x) \cdot (\pm 1)
= 0.
$$
As we want to specify a distance along a normal, it is easier to use normal vectors with length $1$ (unit vectors):
$$
n_i(x) = \frac{(\mp f'(x), \pm 1)}{\sqrt{1+f'(x)^2}}.
$$
The two cases of sign stand for the normal vector pointing inwards and outwards. Then a point $Q(x)$ with distance $d$ along a normal to $P(x)$ is
$$
Q(x)
= P(x) + d \, n_i(x)
= (x, f(x)) + d \, \frac{(\mp f'(x), \pm 1)}{\sqrt{1+f'(x)^2}}.
$$
In this case
$$
Q(x) = (x, x^2) + d \frac{(\mp 2x, \pm 1)}{\sqrt{1+4x^2}}.
$$


text:
Q: Prove that if $q | 2^{p} - 1$ then $q \mid 2^{q-1} - 1$ and $q = 1+2kp$
Let a prime $p\ge 3$ and let $q$, a prime such that $q \mid 2^p - 1$. prove that $q \mid 2^{q-1} - 1$ and show that it has the form $q = 1+2kp$,  $k\in\mathbb N$.

Note: I have been asked to show first that $q\mid \gcd \left( 2^p - 1, 2^{q-1} -1 \right)$ and to use the lemma:$ \gcd \left( N^a -1 , N^b - 1 \right) = N^{\gcd(a,b)} - 1$
So I followed the hint:
$$\gcd\left( 2^p -1, 2^{q-1}-1 \right) = 2^{\gcd(p,q-1)} - 1$$
Then we have to show that $q\mid 2^{\gcd(p,q-1)}$.
Now, since $p$ is a prime: $\gcd(p,q-1)\in\{1,p\}$.  If $\gcd(p,q-1) = p$ then it works out since $q\mid 2^p - 1$ by definition. But, it may be that $\gcd(p,q-1) = 1$. Isn't it? That would imply $q=1$ - A contradiction to the primality of $q$.
I guess I need to somehow eliminate the option that $\gcd(p,q-1)=1$.
How?

A: You are assuming that $2^p\equiv1\pmod q$. But you know that $2^{q-1}\equiv1\pmod q$. It is easy to see that if $k$ is the smallest natural such that $2^k\equiv1\pmod q$, then every natural $N$ such that $2^N\equiv1\pmod q$ is a multiple of $k$. But, clearly, $k\neq1$. Therefore, since $p$ is prime, $k=p$ and so $p\mid q-1$. In other words, $q=1+Mp$ for some natural number $M$. If $M$ was  odd, $q$ would be even. But the only even prime is $2$ and $2\nmid2^p-1$. Therefore, $q$ is odd and $M=2k$ for some natural $k$.

A: Given that $q | 2^{p} - 1,$ it follows that $q$ is a primitive factor of the $pth$ Mersenne number. Hence, $q$ must be of the form $1 + 2kp$ as all primitive prime divisors of Mersenne numbers of prime index have this form.
Finally, as long as $q$ is greater than $3$ (which is the case here), it must divide $M_{q-1}$; and so, $q | 2^{q-1} - 1.$
Remark: The latter divisibility property is not always true for Lucas sequences in general; for example, in the Fibonacci sequence, $q > 5 $ will divide either F_{q-1} or F_{q+1} but not both.


text:
Q: Chaging innerHTML of DIV changes table properties I have to show dynamically checkboxes in a HTML page and get their value from database.
The trick I used is to create the whole table HTML in java and then using AJAX I do this
var div = document.getElementByID("div").innerHTML = htmlCode;

but issue is
in htmlCode variable, the html is like

       ......

but when I check div.innerHTML it shows like

            <?xml:namespace prefix = ....

Why they become uppercase and why is xml:namaesapce prefix added ?
This causes issue as table is not properly displayed.
Is there any other better way to do this without using innerHTML ?
The code for generation of table is
String html = "
";

for (Iterator it = lookupList.iterator (); it.hasNext ();)
    {
        HashTree lookupElement = (HashTree) it.next ();
        String code = lookupElement.getChildTagValue ("CODE");
        String text = lookupElement.getChildTagValue ("TEXT");

        String labelText = "";

            if(indexLookupElement == 0)
                labelText = "First Checkbox label";

            html = html + "
" +
             +
                    "<input type=\"checkbox\" id=\"item" + code + "\"  />" +
                    "" + text +
                    "" +

            "" +
            "
";

            indexLookupElement += 1;
    }

html = html + "
";

Thanks,
Aiden

A: It's not a best practice to create the HTML code server-side. If you are sure you'll have the table in your document it's better to make it part of the structure of the document and feed only the variables from your Java code. Even if the table is conditional you may consider hide/unhide it with a variable. I believe this approach will solve your problem if the HTML code of your webpage is correct.
Update
Test it like this:
html = html + "
<input type=\"checkbox\" id=\"item" + code + "\" />" + text + "
";

In your code you have missing TD closing tag and I made some changes. See if this will fix your problem.


text:
Q: Bound for covariance using the covariance properties For $a \in \mathbb R^+$ and random variables $X$ and $Y$, are these two inequalities correct?
$$2\operatorname{cov}(X,aY) \leq \operatorname{var}(X)+\operatorname{var}(aY) = \operatorname{var}(X)+a^2\operatorname{var}(Y) \tag{1}$$
$$2\operatorname{cov}(X,aY)=a \times 2\operatorname{cov}(X,Y) \leq a(\operatorname{var}(X)+\operatorname{var}(Y)) \tag{2}$$
Since in my case $0<a<<1$ and $\operatorname{var}(X) \approx\operatorname{var}(Y)$, I guess (2) is clearly better (tighter). I just wanted confirmation, thanks.

A: Let $X_1=X-E(X)$ and $Y_1=Y-E(Y)$.
Then the inequality
$0 \le (X_1-Y_1)^2=X_1^2+Y_1^2-2X_1Y_1$ implies that
$$\text{Cov}(X,Y)=E(X_1 Y_1) \le \frac12  E(X_1^2+Y_1^2)=\frac12 \bigl(\text{Var}(X)+\text{Var}(Y)\bigr)\,.$$
Both inequalities in the question follow, and can be improved by a factor of 2.


text:
Q: Is there anything that can be done in plain JS but not Coffeescript? I was reading a discussion about CoffeeScript today and I saw someone make a claim to the effect of "avoid CoffeeScript, since you will eventually need to work with libraries/features/etc that only work in JS." Is this the case? I've started learning CoffeeScript recently and as far as I can tell there is a 1-1 match between the two languages, but I'm not very familiar with JS so I'm not sure.
I've seen this and I'm not asking for a general discussion of the merits of JS vs CoffeeScript. Also, I don't want to count embedded snippets of JS in CoffeeScript as "getting the job done in CoffeeScript," since that makes the question boring.

A: Nope. You can embed JS in CoffeeScript if you really need to, but as CoffeeScript compiles to (semi-idiomatic) JS, anything a JS library can do, CoffeeScript can do.


text:
Q: WiFi direct Ip address Do the Wifi-Direct Ip_address and Ip address given by any WIFI router to the smart-phone same?
I am below code to get my IP address.
public String getP2PIpAddr() {
   WifiManager wifiManager = (WifiManager) getSystemService(WIFI_P2P_SERVICE);
   WifiInfo wifiInfo = wifiManager.getConnectionInfo();
   int ip = wifiInfo.getIpAddress();

   String ipString = String.format(
   "%d.%d.%d.%d",
   (ip & 0xff),
   (ip >> 8 & 0xff),
   (ip >> 16 & 0xff),
   (ip >> 24 & 0xff));

   return ipString;
}

but its giving me 0.0.0.0 when i am not connected to any wifi router.But it is returning me IP address given by router to phone but not the wifi-direct IPAddress..
Please Help...
Thanks In advance..

A: No the IP addresses are not the same.
You are making mistakes here, getSystemService(WIFI_P2P_SERVICE) returns WifiP2pManager not WifiManager.
Secondly
You use wifiManager.getConnectionInfo() when you are connected to a normal Wifi network i.e. via a router or hotspot. You do not get IP when connected via WifiDirect like this as it is not a normal wifi network. Thus, the reason you are getting IP as 0.0.0.0.
Now the main the question what are the IPs in WifiDirect.
If you are a GroupOwner you have fixed GO_IP = 192.168.43.1. So, in onConnectionInfoAvailable or onGroupInfoAvailable, you can do info.isGroupOwner() and if you are not the groupOwner then the other system is, hence his IP is GO_IP, then this system can communicate to the GO using GO_IP
Now if GO wants to communicate with client, he can get his IP using NetworkInterfaces. Refer this how to get the client IP.
I think this all should solve your problem.


text:
Q: view_as use in Boost Polygon library Can anyone guide me how view_as can be used. Or maybe an example in boost polygon library?
In documentation, it's mentioned that we can type cast from one to another.
http://www.boost.org/doc/libs/1_58_0/libs/polygon/doc/gtl_polygon_90_concept.htm

A: The boost::polygon documentation is not great, but in this area at least it does seem to be fairly clear:

An object that is a model of polygon_90_concept can be viewed as a model of any of its refinements if it is determined at runtime to conform to the restriction of those concepts.  This concept casting is accomplished through the view_as<>() function.

view_as<rectangle_concept>(polygon_90_object)

The return value of view_as<>() can be passed into any interface that expects an object of the conceptual type specified in its template parameter.


text:
Q: How to pass options to column select while extending gird with ? Im trying to pass options form my source file to a custom column grid:
<?php

class Vendor_Module_Model_Source_Order_Way
    extends Mage_Eav_Model_Entity_Attribute_Source_Abstract
{

    /**
     * Retrieve all options array
     *
     * @return array
     */
    public function getAllOptions()
    {
        if (is_null($this->_options)) {
            $this->_options = [
                [
                    "label" => "Website",
                    "value" => 1
                ],
                [
                    "label" => "Phone",
                    "value" => 2
                ],
                [
                    "label" => "Email",
                    "value" => 3
                ],
            ];
        }

        return $this->_options;
    }

    /**
     * Retrieve option array
     *
     * @return array
     */
    public function getOptionArray()
    {
        $_options = [];
        foreach ($this->getAllOptions() as $option) {
            $_options[$option["value"]] = $option["label"];
        }

        return $_options;
    }

    /**
     * Get a text for option value
     *
     * @param string|integer $value
     * @return string
     */
    public function getOptionText($value)
    {
        $options = $this->getAllOptions();
        foreach ($options as $option) {
            if ($option["value"] == $value) {
                return $option["label"];
            }
        }

        return false;
    }

}

And I'm stuck in options tag. I don't know how to pass path to source file and method?
<?xml version="1.0"?>
<layout>
    <sales_order_grid_update_handle>
        <reference name="sales_order.grid">
            <action method="addColumnAfter">
                <columnId>order_way</columnId>
                <arguments>
                    <header>Way Method</header>
                    <index>order_way</index>
                    <type>options</type>
                    <options>...</options>
                </arguments>
                <after>status</after>
            </action>
        </reference>
    </sales_order_grid_update_handle>
    <adminhtml_sales_order_grid>
        <update handle="sales_order_grid_update_handle" />
    </adminhtml_sales_order_grid>
    <adminhtml_sales_order_index>
        <update handle="sales_order_grid_update_handle" />
    </adminhtml_sales_order_index>
</layout>


text:
Q: First use of AVX 256-bit vectors slows down 128-bit vector and AVX scalar ops Originally I was trying to reproduce the effect described in Agner Fog's microarchitecture guide section "Warm-up period for YMM and ZMM vector instructions" where it says that:

The processor turns off the upper parts of the vector execution units when it is not used, in order to save power. Instructions with 256-bit vectors have a throughput that is approximately 4.5 times slower than normal during an initial warm-up period of approximately 56,000 clock cycles or 14 μs.

I got the slowdown, although it seems like it was closer to ~2x instead of 4.5x. But what I've found is on my CPU (Intel i7-9750H Coffee Lake) the slowdown is not only affecting 256-bit operations, but also 128-bit vector ops and scalar floating point ops (and even N number of GPR-only instructions following XMM touching instruction).
Code of the benchmark program:
# Compile and run:
# clang++ ymm-throttle.S && ./a.out

.intel_syntax noprefix

.data
L_F0:
  .asciz "ref cycles = %u\n"

.p2align 5
L_C0:
  .long 1
  .long 2
  .long 3
  .long 4
  .long 1
  .long 2
  .long 3
  .long 4

.text

.set initial_scalar_warmup, 5*1000*1000
.set iteration_count, 30*1000
.set wait_count, 50*1000

.global _main
_main:
  # ---------- Initial warm-up
  # It seems that we enter _main (at least in MacOS 11.2.2) in a "ymm warmed-up" state.
  #
  # Initial warm-up loop below is long enough for the processor to switch back to
  # "ymm cold" state. It also may reduce dynamic-frequency scaling related measurements
  # deviations (hopefully CPU is in full boost by the time we finish initial warmup loop).

  vzeroupper

  push rbp
  mov ecx, initial_scalar_warmup

.p2align 4
_initial_loop:
  add eax, 1
  add edi, 1
  add edx, 1

  dec ecx
  jnz _initial_loop

  # --------- Measure XMM

  # TOUCH YMM.
  # Test to see effect of touching unrelated YMM register
  # on XMM performance.
  # If "vpxor ymm9" below is commented out, then the xmm_loop below
  # runs a lot faster (~2x faster).
  vpxor ymm9, ymm9, ymm9

  mov ecx, iteration_count
  rdtsc
  mov esi, eax

  vpxor xmm0, xmm0, xmm0
  vpxor xmm1, xmm1, xmm1
  vpxor xmm2, xmm2, xmm2
  vmovdqa xmm3, [rip + L_C0]

.p2align 5
_xmm_loop:
  # Here we only do XMM (128-bit) VEX-encoded op. But it is triggering execution throttling.
  vpaddd xmm0, xmm3, xmm3
  add edi, 1
  add eax, 1

  dec ecx
  jnz _xmm_loop

  lfence
  rdtsc
  sub eax, esi
  mov esi, eax  # ESI = ref cycles count

  # ------------- Print results

  lea rdi, [rip + L_F0]
  xor eax, eax
  call _printf

  vzeroupper
  xor eax, eax
  pop rbp
  ret

Question: Is my benchmark correct? Is the description (below) of what's happening seem plausible?
CPU is in AVX-cold state (no 256-bit/512-bit instruction has been executed for ~675 µs) encounters a single instruction with YMM (ZMM) destination register. CPU immediately switches to some sort of "transition to AVX-warm" state. This presumably takes ~100-200 cycles mentioned in Agner's guide. And this "transition" period lasts ~56'000 cycles.
During transition period GPR code may execute normally, but any instruction that has vector destination register (including 128-bit XMM or scalar floating point instructions, even including vmovq xmm0, rax) applies throttling to entire execution pipeline. This affects GPR-only code immediately following such instruction for N-cycles (not sure how many; may be ~dozen cycles worth of instructions).
Perhaps throttling limits number of µops dispatched to execution units (regardless of what those µops are; as long as there is at least one µop with a vector destination register)?

What's new here for me is that I thought that during transition period throttling would be applied only for 256-bit (and 512-bit) instructions, but it seems like any instruction that has vector register destination is affected (as well as ~20-60 of GPR-only immediately following instructions; can't measure more precisely on my system).

Related: "Voltage Only Transitions" section of an article at Travis Downs blog may be describing the same effect. Although the author measured performance of YMM vectors during transition period, the conclusion was that it is not the upper part of the vector that's being split, rather throttling applied to entire pipeline when vector register touching instruction is encountered during transition period. (edit: the blog post did not measure XMM registers during transition period, which is what this post is measuring).

A: The fact that you see throttling even for narrow SIMD instructions is a side-effect of a behavior I call implicit widening.
Basically, on modern Intel, if the upper 128-255 bits are dirty on any register in the range ymm0 to ymm15, any SIMD instruction is internally widened to 256 bits, since the upper bits need to be zeroed and this requires the full 256-bit registers in the register file to be powered and probably the 256-bit ALU path as well. So the instruction acts for the purposes of AVX frequencies as if it was 256-bit wide.
Similarly, if bits 256 to 511 are dirty on any zmm register in the range zmm0 to zmm15, operations are implicitly widened to 512 bits.
For the purposes of light vs heavy instructions, the widened instructions have the same type as they would if they were full width. That is, a 128-bit FMA which gets widened to 512 bits acts as "heavy AVX-512" even though only 128 bits of FMA is occurring.
This applies to all instructions which use the xmm/ymm registers, even scalar FP operations.
Note that this doesn't just apply to this throttling period: it means that if you have dirty uppers, a narrow SIMD instruction (or scalar FP) will cause a transition to the more conservative DVFS states just as a full-width instruction would do.


text:
Q: How do I get a value from an NSURLSession task into an instance variable? I have a tableView which I want to fill with a list of items provided by a web service. The service returns a JSON object with status (success or failure) and shows (an array of strings).
In viewDidLoad I call the custom method getShowsFromService()
func getShowsFromService() {
    // Send user data to server side
    let myURL = NSURL(string: "https://myurl.com/srvc/shows.php")

    // Create session instance
    let session = NSURLSession.sharedSession()

    var json:NSDictionary = [:]

    // Create the task
    let task = session.dataTaskWithURL(myURL!) {  //.dataTaskWithRequest(request) {
        (data, response, error) in

        guard let data = data else {
            print("Error: \(error!.code)")
            print("\(error!.localizedDescription)")
            return
        }

        do {
            json = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions()) as! NSDictionary
        } catch {
            print (error)
        }

        let sts = json["status"] as! NSString
        print("\(sts)")
    }

    // Resume the task so it starts
    task.resume()

    let shows = json["shows"] as! NSArray
    for show in shows {
        let thisshow = show as! String
        showsArray.append(thisshow)
    }

    // Here I get "fatal error: unexpectedly found nil while unwrapping an Optional value"

}

The method receives the JSON object and puts it into a dictionary. Then I want to use that dictionary to call json['shows'] in order to get to the array of shows which I want to store in an instance variable called showsArray. The idea is to use showsArray in tableView(cellForRowAtIndexPath) in order to fill in the data.
The problem is that I can't get the Dictionary into the variable. If I try to do it inside the task, I get an error that says I need to call self.showsArray and if I do, the data doesn't go inside the array. If I do it outside the task I get an error because it says I'm trying to force unwrap a nil value.
How can I get the Dictionary created within the task out into the showsArray var?

A: The dataTaskWithURL method makes an async call, so as soon as you do task.resume() it will jump to the next line, and json["shows"] will return nil as the dictionary is empty at this point.
I would recommend moving that logic to a completion handler somewhere in your class. Something along the lines of:
func getShowsFromService() {
    let myURL = NSURL(string: "https://myurl.com/srvc/shows.php")
    let session = NSURLSession.sharedSession()
    let task = session.dataTaskWithURL(myURL!, completionHandler: handleResult)
    task.resume()
}

//-handle your result
func handleResult(data: NSData?, response: NSURLResponse?, error: NSError?) {
    guard let data = data else {
        print("Error: \(error!.code)")
        print("\(error!.localizedDescription)")
        return
    }

    do {
        if let json = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions()) as! NSDictionary {
            if let shows = json["shows"] as! NSArray {
                //- this is still in a separate thread
                //- lets go back to the main thread!
                dispatch_async(dispatch_get_main_queue(), {
                    //- this happens in the main thread
                    for show in shows {
                        showsArray.append(show as! String)
                    }
                    //- When we've got our data ready, reload the table
                    self.MyTableView.reloadData()
                    self.refreshControl?.endRefreshing()
                });
            }
        }
    } catch {
        print (error)
    }
}

The snippet above should serve as a guide (I dont have access to a playground atm).
Note the following:
as soon as the task completes (asynchronously -> different thread) it will call the new function handleResult which will check for errors and if not, it will use the dispatcher to perform your task on the main thread. I'm assuming showsArrays is a class property.
I hope this helps
EDIT:
As soon as you fetch your data you need to reload the table (updated code above). You can use a refresh control (declare it as a class property).
var refreshControl: UIRefreshControl!

Then when you finish getting your data you can refresh:
self.MyTableView.reloadData()
self.refreshControl?.endRefreshing()

This will call your delegate methods to populate the rows and sections.


text:
Q: Is there a name for practise of avoiding using programing langue types? I try to convince coworkers to stop writing code like this (example in java):
class Person {
    Long id;
    String name;
    String surname;
}

and write code like this:
class Person {
    PersonId id;
    PersonName name;
    PersonSurname surname;
}

Basically, I want to avoid overusing Strings', Longs' and use dedicated types that correspond to a domain. This is not a new concept, methodology or practise (however you call it), so it probably already have a name. There probably are many people who have already written pros and cons of such approach, but I cannot find any, because I do not know what to look for.

A: Yes, the name of that practise is Avoiding Primitive Obsession.
According to this article:

The Smell: Primitive Obsession is using primitive data types to represent domain ideas. For example, we use a String to represent a message, an Integer to represent an amount of money, or a Struct/Dictionary/Hash to represent a specific object.
The Fix: Typically, we introduce a ValueObject in place of the primitive data.
The Tools: Some languages make this easier or harder on you.

In languages like C# and Java it can be painful to create hundred of tiny types just wrapping a simple string or int. For example you will have a lot of classes like this:
class PersonName {
    public String value;
    public PersonName(String value) {
        this.value = value;
    }
}

But in ML languages like F#, it is trivial to create simple wrapper types:
type PersonName = PersonName of string

Some good articles on the topic:

*

*https://refactoring.guru/smells/primitive-obsession

*https://softwareengineering.stackexchange.com/questions/365017/when-is-primitive-obsession-not-a-code-smell

*http://codemonkeyism.com/never-never-never-use-string-in-java-or-at-least-less-often/

*https://fsharpforfunandprofit.com/posts/designing-with-types-single-case-dus/


text:
Q: iOS- Get button on MKAnnotationView to delete pin I have created a MKAnnotationView and do add a UIButton on it. Now I would like that button to remove the pin it is in.
This is how I add the button:
- (MKAnnotationView *)mapView:(MKMapView *)mV viewForAnnotation:(id <MKAnnotation>)annotation
{
    MKPinAnnotationView *pinAnnotation = nil;
    if(annotation != myMapView.userLocation)
    {
        NSString *defaultPinID = [[NSString alloc] initWithFormat:@"pin%d",pinCount];
        pinAnnotation = (MKPinAnnotationView *)[myMapView dequeueReusableAnnotationViewWithIdentifier:defaultPinID];
        if ( pinAnnotation == nil )
            pinAnnotation = [[[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:defaultPinID] autorelease];
        pinAnnotation.canShowCallout = YES;

    //// ADDING MY BUTTON
        UIButton *deleteButton = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
        pinAnnotation.rightCalloutAccessoryView = deleteButton;
    //// ADDING IT'S ACTION
        [deleteButton addTarget:self action:@selector(deletePin) forControlEvents:UIControlEventTouchUpInside];
    }
    pinCount++;
    return pinAnnotation;
}

As you can see there, I set the action to call this method:
-(void)deletePin
{
    //What to put here...?
}

How can I make that action delete it's button's pin?
I figured maybe sending the id thru or something, but am not sure how.

A: With annotation callout accessory views, do not use your own target/action method.
Instead, use the map view's calloutAccessoryControlTapped delegate method which will make this job much easier.
Remove the addTarget line and your custom method.  Then implement the delegate method instead:
- (void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)view
            calloutAccessoryControlTapped:(UIControl *)control
{
    [mapView removeAnnotation:view.annotation];
}

Also, unrelated, but the way you are setting the re-use identifier is wrong and defeats re-usability by assigning a different id to every annotation.  The following is recommended:
- (MKAnnotationView *)mapView:(MKMapView *)mV viewForAnnotation:(id <MKAnnotation>)annotation
{
    MKPinAnnotationView *pinAnnotationView = nil;
    if (annotation != myMapView.userLocation)
    {
        NSString *reuseId = @"StandardPin";
        pinAnnotationView = (MKPinAnnotationView *)[myMapView dequeueReusableAnnotationViewWithIdentifier:reuseId];
        if ( pinAnnotationView == nil )
        {
            pinAnnotationView = [[[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:reuseId] autorelease];
            pinAnnotationView.canShowCallout = YES;

            UIButton *deleteButton = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
            pinAnnotationView.rightCalloutAccessoryView = deleteButton;
        }
        else
            //update annotation property if view is being re-used...
            pinAnnotationView.annotation = annotation;
    }

    return pinAnnotationView;
}

A: Get the sender in your callback
[deleteButton addTarget:self action:@selector(deletePin:) forControlEvents:UIControlEventTouchUpInside];

-(void)deletePin:(id)sender
{
    //What to put here...?
}

Then get the MKAnnotation associated with the MKPinAnnotationView, remove it from the MKMapView's annotations and redraw ([mapView setNeedsDisplay])


text:
Q: Which signature spell is the fastest for generating Flashes of Insight? The Wizard's Arcane Dynamo skill description reads:

When you deal damage with a Signature spell you may gain a Flash of Insight.

The "may" is very vague. What is the actual chance? And more importantly, which skill may ultimately generate Flashes of Insight faster? Also, is there any runes / passives / item selection which will make the generation even faster?

A: Arcane Dynamo has since been changed to

When you cast a Signature Spell, you gain a Flash of Insight.

Now, causing damage with a Signature spell does not grant Flashes of Insight. However, there is a 100% chance of gaining a stack of Flash of Insight on cast. As such, gaining stacks of Flash of Insight now relies entirely on attack speed and whatever Signature spell you choose has absolutely no effect on the efficiency of gaining stacks of Flash of Insight.

A: The spell best suited for this is Shock Pulse with the rune Living Lightning.
The spell has an insane amount of hits/second, however each hit deals low amounts of damage , but it adds up to the same DPS as any other spell doing the same amount of weapon damage percentage.
Combine Living Lightning with items that improve Attack Speed and you will fire an insane amount of attacks per second, with each attack producing lots of hits/second. If you fire off several Living Lightnings, you will regenate 5 Flashes of Insight in a few milliseconds after you've casted your non-signature spell.
The skill: http://eu.battle.net/d3/en/class/wizard/active/shock-pulse
A video showing the skill in action:

They use Shock Pulse and Living Lightning with a rune that reduces cooldowns by 1 second for every critical hit. You gain lots of critical hits with Living Lightning without critical hit gear, imagine what you get if you gear up correctly!
NOTE: I am not sure the above build works anymore, changes were made recently, but Living Lightning was unaffected.

A: How fast you attack with your signature spell is based on your attack speed.
As such, unless one signature spell hitting multiple enemies counts as more than one instance of dealing damage, there is no difference between different spell abilities.
The actual chance is unfortunately not something that can be determined precisely, and even a vague estimate would take quite a bit of dedicated testing to try to establish a percent chance.
In summary, other than increasing your attack speed, there is very little you can do to affect how often this passive is triggered.


text:
Q: Getting text from a specified tkinter label on mouse click books = []
result = db.answer_query(query)
for item in result:
    book = Label(search_page,text=item,font="none 12 bold",pady=2)
    book.grid(row=row_count, column=0, sticky = W)
    books.append(book)
    row_count += 1
for book in books:
    book.bind("<Button-1>", lambda e: BookInfoPage(book.cget("text")))
    book.bind("<Enter>", lambda event, h=book: h.configure(fg="#638cbb"))
    book.bind("<Leave>", lambda event, h=book: h.configure(fg="#000000"))

This is the current code which loads multiple labels and places them on successive rows of each index in a list returned from db.answer_query(query). This function returns a list of string values.
The current issue that I have is that for the "<Button-1>" event, I pass the parameter book.cget("text") into the function BookInfoPage() which is a function that provides information about the clicked book name (provided from the labels). I want to pass text from a specified tkinter label on mouse click into the function BookInfoPage() but currently it passes the text from the last label only, no matter which label is clicked.
This is because book variable is recognised as the last entity in the list from the for loop. Is there any way around this issue?
I want to be able to pass text from a specified tkinter label on mouse click into the function BookInfoPage().
Here is a video (gif) of the current working application: https://imgur.com/a/9sjynxm
See that even though I click on "harry potter" it gives me the result for "the great gasby", the last entry in the list.

A: The event object passed to the callback can tell you which widget you clicked on. Instead of throwing away the event object, use it:
book.bind("<Button-1>", lambda event: BookInfoPage(event.widget.cget("text")))

An arguably better solution is to call a proper function, and use the event object to get the widget that was clicked on. Using a function is easier to write, easier to read, and easier to debug.
def show_book(event):
    book = event.widget
    BookInfoPage(book.cget("text"))

book.bind("<Button-1>", show_book)


text:
Q: Update table row value to a random row value from another table I have 2 MySQL tables.
One table has a column that lists all the states
colStates | column2 | column 3
------------------------------
AK        | stuff   | stuff
AL        | stuff   | stuff
AR        | stuff   | stuff
etc..     | etc..   | etc..

The second table has a column(randomStates) with all NULL values that need to be populated with a randomly selected state abbreviation.
Something like...
UPDATE mytable SET `randomStates`= randomly selected state value WHERE randomStates IS NULL

Can someone help me with this statement. I have looked around at other posts, but I don't understand them.

A: this works for me with trial data in SQLite:
UPDATE mytable
SET randomStates = (SELECT colStates FROM
                        (SELECT * FROM first_table ORDER BY RANDOM())
                    WHERE randomStates IS NULL)

without the first SELECT portion, you end up with the same random value inserted into all the NULL randomStates field. (i.e. if you just do SELECT StateValue FROM counts ORDER BY RANDOM() you don't get what you want).


text:
Q: How do I select for a row using multiple clauses in PACT smart contract language The PACT documentation clearly states how to select for a single condition in the where clause, but it is not so clear on how to select for multiple clauses which seems much more general and important for real world use cases than a single clause example.
Pact-lang select row function link
For instance I was trying to select a set of dice throws across the room name and the current round.
(select 'throws (where (and ('room "somename") ('round 2)))
But this guy didn't resolve and the error was not so clear.  How do I select across multiple conditions in the select function?

A: The first thing we tried was to simply select via a single clause which returns a list:

(select 'throws (where (and ('room "somename")))

A: [object{throw-schema},object{throw-schema}]
And then we applied the list operator "filter" to the result:

(filter (= 'with-read-function' 1) (select 'throws (where (and ('room "somename"))))

Please keep in mind we had a further function that read the round and spit back the round number and we filtered for equality of the round value.
This ended up working but it felt very janky.

A: The second thing we tried was to play around with the and syntax and we eventually found a nice way to express it although not quite so intuitive as we would have liked.   It just took a little elbow grease.
The general syntax is:

(select 'throws (and? (where condition1...) (where condition2...))

In this case the and clause was lazy, hence the ? operator.  We didn't think that we would have to declare where twice, but its much cleaner than the filter method we first tried.

A: The third thing we tried via direction from the Kadena team was a function we had yet to purview:  Fold DB.

(let*  ((qry (lambda (k obj) true)) ;;
(f (lambda(x) [(at 'firstName x), (at 'b x)]))  )  (fold-db people (qry) (f)) )

This actually is the most correct answer but it was not obvious from the initial scan and would be near inscrutable for a new user to put together with no pact experience.
We suggest a simple sentence ->

"For multiple conditions use fold-db function."

In the documentation.
This fooled us because we are so used to using SQL syntax that we didn't imagine that there was a nice function like this lying around and we got stuck in our ways trying to figure out conditional logic.


text:
Q: Adding buttons next to the Close button in dialog title bar I have added two customized buttons on my dialog box, but they are currently just in the middle. How can i move these buttons next to the close button on the title bar, without covering or touching the close button, and also without using anyCSS?
My fiddle: http://jsfiddle.net/ZSk6L/928/

A: If you are happy to use inline styling in the jquery, this gets you what you want (without floats or covering the close button - simply set a left margin to the first custom button:
$('<button>-</button>').appendTo(titlebar).css('margin-left', '35%').click(function() {
Fiddle

A: If you are alright using css within your jQuery then you could add a class to the minus button:
$('<button class="minusButton">-</button>').appendTo(titlebar).click(function() {
    $('#resultId').parents('.ui-dialog').animate({
        height: '40px',
        top: $(window).height() - 90
    }, 50);
});

And then set the margin
$(".minusButton").css("margin-left", "105px");

A: There is absolutely no way to do this without at least using inline CSS, written in through jQuery.
Your best bet is just using a float and a fixed small margin on the + button so it doesn't overlap the closing button. Be aware, that any answer written here is probably going to have a problem when the user resizes the dialog window a lot, and the only way to prevent that is to give the whole dialog window a min-width property.
Here is what you should do:
$('<button>+</button>').appendTo(titlebar).css({'display':'inline-block', 'float':'right', 'margin-right': '10px'}).click...
And for the other button:
$('<button>-</button>').appendTo(titlebar).css({'display':'inline-block', 'float':'right'}).click...
You can see the working Fiddle Here


text:
Q: WPF Sorting an ObservableCollection de-selects a ComboBox I have a ComboBox where a user can select what JobType they are working on.  The ComboBox has a list of AllJobTypes.  The problem stems from when a user adds a new JobType, I add the JobType to the AllJobTypes ObservableCollection, then sort it.  When the sorting happens the ComboBox get's de-selected and not really sure why.  The JobConfig.SelectedJobType.Name never changes in this process.  Is there a way to sort an observable collection where it doesn't break the ComboBox?
public class JobTypeList : ObservableCollection<JobType> {

  public void SortJobTypes() {
    var sortableList = new List<JobType>(this);
    sortableList.Sort((x, y) => x.Name.CompareTo(y.Name));
    //this works but it creates a bug in the select for JobTypes
    for (int i = 0; i < sortableList.Count; i++) {
        this.Move(this.IndexOf(sortableList[i]), i);
    }
  }

And in the XAML
<ComboBox Grid.Column="0" SelectionChanged="JobTypeComboBox_SelectionChanged"
                              Name="JobTypeComboBox"
                              ItemsSource="{Binding Path=AllJobTypes}"
                              DisplayMemberPath="Name"
                              SelectedValuePath="Name"
                              SelectedValue="{Binding
Path=JobConfig.SelectedJobType.Name}" />

A: Instead of sorting the collection in the view model, you should bind the ComboBox's ItemsSource to a CollectionViewSource, where you can specify a SortDescription:
<Window ...
    xmlns:scm="clr-namespace:System.ComponentModel;assembly=WindowsBase"
    ...>
    <Window.Resources>
        <CollectionViewSource x:Key="cvs" Source="{Binding AllJobTypes}">
            <CollectionViewSource.SortDescriptions>
                <scm:SortDescription PropertyName="Name"/>
            </CollectionViewSource.SortDescriptions>
        </CollectionViewSource>
    </Window.Resources>

    ...
    <ComboBox ItemsSource="{Binding Source={StaticResource cvs}}"
              DisplayMemberPath="Name"
              SelectedValuePath="Name"
              SelectedValue="{Binding JobConfig.SelectedJobType.Name}"/>
    ...

</Window>

For further information see How to: Sort and Group Data Using a View in XAML

A: Here's a version using ItemsSource/SelectedItem.  Note that you can add a new item to the list and sort it without losing the currently selected item in the view.
The window
<Window
    x:Class="SortingAList.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:SortingAList"
    mc:Ignorable="d"
    Title="MainWindow"
    Height="350"
    Width="525">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition />
            <RowDefinition />
        </Grid.RowDefinitions>
        <TextBox
            Text="{Binding NewJobType, Delay=1000}"
            HorizontalAlignment="Center"
            VerticalAlignment="Center"
            Width="200" />
        <ComboBox
            Grid.Row="1"
            ItemsSource="{Binding JobTypes}"
            SelectedItem="{Binding SelectedJobType}"
            DisplayMemberPath="Name"
            HorizontalAlignment="Center"
            VerticalAlignment="Center"
            Width="200" />
    </Grid>
</Window>

The code
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        DataContext = new ViewModel();
    }
}

public class Notifier : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    protected void Notify([CallerMemberName]string property = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(property));
    }
}

public class ViewModel : Notifier
{
    private JobType _selectedJobType;
    private string _newJobType;

    public JobTypeList JobTypes { get; private set; }
    public JobType SelectedJobType { get => _selectedJobType; set { _selectedJobType = value; Notify(); } }
    public string NewJobType { get => _newJobType; set { _newJobType = value; Notify(); AddNewJobType(value); } }
    public ViewModel()
    {
        JobTypes = new JobTypeList();
        JobTypes.Add(new JobType { Name = "Butcher" });
        JobTypes.Add(new JobType { Name = "Baker" });
        JobTypes.Add(new JobType { Name = "LED maker" });
    }

    private void AddNewJobType(string name)
    {
        if(JobTypes.Any(x => x.Name == name)) return;
        JobTypes.Add(new JobType { Name = name });
        JobTypes.SortJobTypes();
    }
}
public class JobType : Notifier
{
    private string _name;

    public string Name { get => _name; set { _name = value; Notify(); } }
}

Using your JobTypesList
public class JobTypeList : ObservableCollection<JobType>
{

    public void SortJobTypes()
    {
        var sortableList = new List<JobType>(this);
        sortableList.Sort((x, y) => x.Name.CompareTo(y.Name));
        //this works but it creates a bug in the select for JobTypes
        for(int i = 0; i < sortableList.Count; i++)
        {
            this.Move(this.IndexOf(sortableList[i]), i);
        }
    }
}


text:
Q: Почему при изменении переменной которой присвоен элемент массива, меняется и сам элемент в массиве? JS

'use strict';
const games = [{
        id: 1,
        title: 'Mario'
    },
    {
        id: 2,
        title: 'Zelda'
    },
    {
        id: 3,
        title: 'Donkey Kong'
    }
];

let test = games[0];
test.id = 22222
alert( JSON.stringify(games));
games.splice(0, 1);

alert( JSON.stringify(games));
alert( JSON.stringify(test));

Не могу понять:

*

*Почему когда я меняю значения переменой меняется и значения id в массиве

*Почему тогда когда я удаляю значения в массиве оно не удаляться с переменой??

A: Потому что в данном случае ты работаешь со ссылками на объекты, ты меняешь не переменную, а свойство объекта, а переменная как ссылалась на один объект, так и продолжила ссылаться.
С удалением то же самое. Удалил ссылку из массива, а ссылка в переменной осталась.

'use strict';

const games = [
  { id: 1, title: 'Mario' },
  { id: 2, title: 'Zelda' },
  { id: 3, title: 'Donkey Kong' }
];

let test = Object.assign({}, games[0]);
test.id = 22222;

console.log( JSON.stringify(games) );
games.splice(0, 1);

console.log( JSON.stringify(games) );
console.log( JSON.stringify(test) );


text:
Q: Django Language Switcher Not Showing Check Next to Current Language I have a language switcher where I can't use a form directly.  Here is the code:

    Languages

        {% for lang in LANGUAGES %}

{{ lang.1 }}

        {% endfor %}

Then I have this form:
<form action="/i18n/setlang/" method="post" style="display: none" id="change_language_form">
{% csrf_token %}
    <select type="hidden">
        <option type="hidden" id="language-option" value=""></option>
    </select>
    <input name="next" type="hidden" value="{{ request.path }}" />
    <input type="hidden" value="" name="language" id="language" />
</form>

Then the jQuery form the form:

The code works, and changes the language, but I cannot seem to get the check mark to appear next to the current language once the page reloads.  I tried adding
if ($('.change_language').attr('selected') === 'selected')
{
    $(this).append('');
}

At the bottom of the jQuery I showed earlier, but still it doesn't show the check mark next to the correct language after reload, and it makes it so the other JavaScript doesn't seem to work at all. No check marks appear.
Without that code it does show the correct check mark when I click the the language, and then if I click another it moves the check mark.  But as I said after page reload, the check mark is gone.
What can I do to make it mark the current language?  What am I missing?
Thanks, any help is much appreciated

A: I was able to fix it by adding this under the  jQuery:
$('.current_language').parent().addClass('active');
$('.current_language').append('');

adding this template tag:
{% get_current_language as current_lang %}
and then this to the class of the anchors within the
's in the languages dropdown.
class="change_language{% if current_lang == lang.0 %} current_language {% endif %}"


text:
Q: Error staging application: App staging failed in the buildpack compile phase Failed (python) I am uploading my django application to cloud foundry, here is my manifest.yml file
  applications:
  - name: onlinecourse
    routes:
      - route: madhavatreya.au-syd.cf.appdomain.cloud
    memory: 128M
    buildpack: python_buildpack
  - name: onlinecourse-nginx
    routes:
      - route: madhavatreya.au-syd.cf.appdomain.cloud/static
    memory: 128M
    buildpack: staticfile_buildpack

Procfile
web: gunicorn myproject.wsgi

Allowed_host setting in django setting file is ['*']
How to solve this error (pillow) is not installing.
Running setup.py install for Pillow: started
Running setup.py install for Pillow: finished with status 'error'
error: subprocess-exited-with-error
× Running setup.py install for Pillow did not run successfully.
│ exit code: 1
╰─> [164 lines of output]
running install


text:
Q: How do I copy ACLs on Mac OS X? Most unix derivates can copy ACLs from one file to another with:
getfacl filename1 | setfacl -f - filename2

Unfortunately Mac OS X does not have the getfacl and setfacl commands, as they have rolled ACL handling into chmod. chmod -E accepts a list of ACLs on stdin, but I haven't found a command that will spit out ACLs in a suitable format on stdout. The best I have come up with is:
ls -led filename1 | tail +2 | sed 's/^ *[0-9][0-9]*: *//' | chmod -E filename2

Is there a more robust solution?
Bonus question: is there a nice way to do it in Python, without using any modules that aren't shipped with 10.6?

A: Maybe have a look at https://github.com/jvscode/getfacl.

A: ls -e  Print the Access Control List (ACL) associated with the file, if present, in long (-l) output.
this gives a result such as...
drwxr-xr-x@ 19 localadmin   646B Aug  4 00:21  APPBUNDLE
0: user:localadmin allow add_file,add_subdirectory,writeattr,writeextattr,writesecurity
                   ⬆    ⇧                      ⇶                                     ⬆

Personally, I have "exports" in my ~/.bash_profile
export FILE_ALL="read,write,append,execute,delete,readattr,writeattr,readextattr,writeextattr,readsecurity,writesecurity,chown"
export DIR_ALL="list,search,add_file,add_subdirectory,delete_child,readattr,writeattr,readextattr,writeextattr,readsecurity,writesecurity,chown"

that make such a chmod possible...
sudo chmod +a "allow localadmin $DIR_ALL" /APPBUNDLE
From the chmod man page, there is this bit of info... that hints that it may indeed be possible to do something like you describe..
"ACLs are manipulated using extensions to the symbolic mode grammar.  Each file has one ACL, containing an ordered list of entries.  Each entry refers to a user or group, and grants or denies a set of permissions.  In cases where a user and a group exist with the same name, the user/group name can be prefixed with "user:" or "group:" in order to specqify the type of name."

chmod  -E      Reads the ACL information from stdin, as a sequential list of ACEs, separated by newlines.  If the information parses correctly, the existing information is replaced.

Also, I'll give a shout out to BatchMod, an oldie, but a goodie for ACL's, as well as TinkerToolSystem.

A: https://github.com/ptrrkssn/acltool might be of interrest - it works on MacOS, FreeBSD, Linux & Solaris. I got tired of the different ACL tools on each system so decided to create one that works the same on all...
With it you can do things like:
% acltool list-access  -v .
# file: .
# owner: peter (501)
# group: staff (20)
# type: directory
        group:everyone:-----d--------:-------:deny  # gid=12

% mkdir t

% acltool copy-access -v . t
t: ACL Updated

% acltool edac -v peter:full_set t
t: ACL Updated

% acltool lac t
# file: t
# owner: peter
# group: staff
          user:peter:rwxpDdaARWcCos:-------:allow
      group:everyone:-----d--------:-------:deny

(It has some bugs but mostly works now)

A: You should be able to get stat to format its output in a suitable way.


text:
Q: Accessing Facebook messages (or notifications) on iOS I wish to access the user's unread Facebook messages in my app. I'm using the Accounts framework. Calling accountStore.requestAccessToAccountsWithType:options: requires the permissions be given as part of the options.
I want to access /{user-id}/inbox stated in their Graph API. This states that the read_mailbox permission is required. Reading the permissions page, it states:

This permission is granted to apps building a Facebook-branded client
  on platforms where Facebook is not already available. For example,
  Android and iOS apps will not be approved for this permission. In
  addition, Web, Desktop, in-car and TV apps will not be granted this
  permission.

In other words: This is available to basically nobody.
After such a blow, I feel like I'm pulling at straws here, but I'm wondering if this applies to the Accounts framework login. Their API references the standard Facebook login (with a button and then a permissions screen) and doesn't mention login through the Accounts framework.
So I tried it, and got an iOS UIAlertView asking if I wanted to allow my app to access the given permissions, including the Inbox permission. I tapped "OK", and was granted access. But then calling accountsWithAccountType: returns 0 accounts (I have a Facebook account logged in on device).
I'm wondering if anyone's done any further investigation, or knows any more about this?

A: You should first try testing your app in the explorer https://developers.facebook.com/tools/explorer/ and see what comes up.

Additionally, since you have read the permission page, you will understand that it wouldn't make sense developing the app with this feature unless you are the only using it.


text:
Q: transform an attribute to 0 or 1 I have a dataframe which has an attribute called income as follows:
......  income
......   > 10
......   <= 10
......   > 10

After the transformation, it will look like
    ......  income
    ......   1
    ......   0
    ......   1

I want to transform this column to 1 if it's larger than 10, otherwise 0.
What I am doing currently is getting the last column from the dataframe. Then run if else statement on the last column. After that use cbind to bind first n-1 columns with the last column. I want to know other more efficient solutions.
I just learn how to use R. I really appreciate if you could provide more details for your solutions.

A: In R, the integer values of TRUE and FALSE are 1 and 0, respectively.  Since you want 1 for "yes it's '> 10'" and 0 for "no it's not", we can simply convert the result of a logical comparison to their corresponding integer values.
df$income <- as.integer(df$income == "> 10")

where df is your data.


text:
Q: error while running gradient vector flow i was trying gradient vector field for segmentation from gvf. Code is in examples-gvf_ex.m .I changed the code as
I=rgb2gray(I);
I=im2double(I)

Input image is

actual output is

i'm expecting somewhat like this(without that rectangular portion)

A: The code you are using is designed for greyscale images of type double. You are inputting a rgb-image of type uint8.
Use rgb2gray and im2double to convert.


text:
Q: Codebehind and inline on same page in ASP.NET? In ASP.NET, is it possible to use both code behind and inline on the same page? I want to add some inline code that's related to the UI of the page, the reason to make it inline is to make it easy to modify as it outputs some HTML which is why I don't want to add it in the code behind, is this possible in ASP.NET?
Edit: I'm sorry, obviously my question wasn't very clear, what I meant is using a script block with runat="server", this is what I meant by inline code.
Thanks

A: Yes, you can use inline code just like in classic asp. You can use 'this' or 'me' to get to the code behind fields, methods, etc.

A: Yes, that will work, make sure the code behind class is declared as a partial class, which is the default these days anyway. Don't think it would work in 1 or 1.1


text:
Q: Preg_match sql database connect i was wondering if someone can explain this: i am trying to the php to the SQL and it keeps on failing. Is there something i am missing in the password sector? What should i enter?
define('DB_HOST',"localhost");
define('DB_USER', (preg_match("/url.co.cc/i",$_SERVER["SERVER_NAME"])?"databaseName":"databaseUser"));
define('DB_PASS', (preg_match("/url.co.cc/i",$_SERVER["SERVER_NAME"])?"password":"password"));
define('DB_NAME', (preg_match("/url.co.cc/i",$_SERVER["SERVER_NAME"])?"databaseName":"databaseUser"));

A: I think your doing this wrong, try and implement it like so:
<?php
$username = "your_name";
$password = "your_password";
$hostname = "localhost";

//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password)
  or die("Unable to connect to MySQL");
echo "Connected to MySQL<br>";
?>


text:
Q: How can I detect if I'm in a subshell? I'm trying to write a function to replace the functionality of the exit builtin to prevent myself from exiting the terminal.
I have attempted to use the SHLVL environment variable but it doesn't seem to change within subshells:
$ echo $SHLVL
1
$ ( echo $SHLVL )
1
$ bash -c 'echo $SHLVL'
2

My function is as follows:
exit () {
    if [[ $SHLVL -eq 1 ]]; then
        printf '%s\n' "Nice try!" >&2
    else
        command exit
    fi
}

This won't allow me to use exit within subshells though:
$ exit
Nice try!
$ (exit)
Nice try!

What is a good method to detect whether or not I am in a subshell?

A: How about BASH_SUBSHELL?

BASH_SUBSHELL
        Incremented  by one within each subshell or subshell environment when the shell
        begins executing in that environment.  The initial value is 0.

$ echo $BASH_SUBSHELL
0
$ (echo $BASH_SUBSHELL)
1

A: In bash, you can compare $BASHPID to $$
$ ( if [ "$$" -eq "$BASHPID" ]; then echo not subshell; else echo subshell; fi )
subshell
$   if [ "$$" -eq "$BASHPID" ]; then echo not subshell; else echo subshell; fi
not subshell

If you're not in bash, $$ should remain the same in a subshell, so you'd need some other way of getting your actual process ID.
One way to get your actual pid is sh -c 'echo $PPID'. If you just put that in a plain ( … ) it may appear not to work, as your shell has optimized away the fork. Try extra no-op commands ( : ; sh -c 'echo $PPID'; : ) to make it think the subshell is too complicated to optimize away. Credit goes to John1024 on Stack Overflow for that approach.

A: [this should've been a comment, but my comments tend to be deleted by moderators, so this will stay as an answer that I could use it as a reference even if deleted]
Using BASH_SUBSHELL is completely unreliable as it be only set to 1 in some subshells, not in all subshells.
$ (echo $BASH_SUBSHELL)
1
$ echo $BASH_SUBSHELL | cat
0

Before claiming that the subprocess a pipeline command is run in is not a really real subshell, consider this man bash snippet:

Each  command in a pipeline is executed as a separate process (i.e., in a subshell).

and the practical implications -- it's whether a script fragment is run a subprocess or not which is essential, not some terminology quibble.
The only solution, as already explained in the answers to this question is to check whether $BASHPID equals $$ or, portably but much less efficient:
if [ "$(exec sh -c 'echo "$PPID"')" != "$$" ]; then
    echo you\'re in a subshell
fi


text:
Q: responsive navbar in JS I'm currently working with an JS application and Bootstrap. The index file of my website only includes

and some scripts.
Now I'm wanting to implement an responsive navbar into the app.js with data-toggle but haven't figured it out yet.

    var Navbar = React.createClass({
  displayName: 'Navbar',
  render: function() {
    return el.nav(
      {className: 'navbar navbar-inverse navbar-fixed-top'},
      el.div(
        {className: 'container'},
        el.div(
          {className: 'navbar-header'},
          el.a({className: 'navbar-brand', href:'/'}, config.app_name)

needs to be responsive, by
              <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
            Toggle navigation

          </button>

implemented to it. How to fix this as I don't see a way to fix this currently.

A: <!DOCTYPE html>

<title>Bootstrap Case</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">

  WebSiteName

Home

Page 1

Page 2

Page 3

Inverted Navbar

An inverted navbar is black instead of gray.

use Bootstrap JQuery fonction you don't have to write it on your own


text:
Q: Syntastic not detecting errors I am new to VIM. I have successfully installed pathogen and with the pathogen i install NERDTree, snimate, vim airline, vim snippets etc all are working fine. But when i tried syntastic its not detecting any errors i follow the directions for their github repository. https://github.com/scrooloose/syntastic
Here is my .vimrc for syntastic

:h syntastic is not working but :SyntasticInfo is working

Here is my little ruby script and syntastic is not detecting any errors


text:
Q: Measure Theorem Ellipsoid I want to find the measure of ellipsoid S:
$$S= (x,y,z)\in R: \frac{x^2}{a^2}+\frac{y^2}{b^2}+\frac{z^2}{c^2}<1 $$
I know $\int_{S} 1 = \mu(S)$. I think it's smart to use spherical/ellipsoid coordinates for this, so: $
x = at\sin(\theta)\cos(\phi) \\
y = bt\sin(\theta)\sin(\phi) \\
z = ct\cos(\theta).$
Then I have to find the Jacobian matrix and determinant of $g(t,\theta,\phi)=(at\cos(\theta)\sin(\phi),bt\sin(\theta)\sin(\phi), ct\cos(\theta)) $.
Then I'll find the answer when I do this: $$\int_{S} 1 = \mu(S)= \int_{0}^{\pi}\int_{0}^{2\pi}\int_{0}^{1} Jacobian\ \ dt\ d\phi\ d\theta  $$
But the Jacobian-determinant is not a nice expression, so I think I do something wrong. Maybe in the parameterization with the $t$??
I hope someone wants to help me, thanks in advance!
Edit:
Jacobi-matrix = \begin{array}{cc}
   sin(\theta)cos(\phi) & a\ t\ cos (\theta)cos(\phi) & -a\ t\ sin(\theta)sin(\phi)\\
   sin(\theta)sin(\phi) & b\ t\ cos(\theta)sin(\phi) & b\ t\ sin(\theta)cos(\phi)\\
c\ cos(\theta) & -c\ t\ sin(\theta) & 0\\
  \end{array}
Determinant: $a\cdot b \cdot c \ t^2\  cos(\theta)cos(\phi)sin(\theta)cos(\phi)cos(\theta) \\
a\cdot c\ t^2\ sin(\theta)sin(\phi) sin(\theta)sin(\phi) sin(\theta)+ \\
b\cdot c\ t^2\ sin(\theta)cos(\phi) sin(\theta)cos(\phi)sin(\theta) +\\
a\cdot b \cdot c\ t^2\ sin(\theta)sin(\phi) cos(\theta)sin(\phi) cos(\theta) $
And that's the same as:
$$ Jacobian: t^2\ \left( a\cdot b \cdot c \ cos^2(\theta)cos^2(\phi)sin(\theta)
+ a\cdot c\ sin^3(\theta)sin^2(\phi) +
b\cdot c\ sin^3(\theta)cos^2(\phi) +
a\cdot b \cdot c\ sin(\theta)sin^2(\phi) cos^2(\theta) \right) $$

A: Using reduced coordinates makes your life easier:
Let $x=a X$, $y=b Y$ and $z=c Z$
\begin{align*}
  \iiint_{x^2/a^2+y^2/b^2+z^2/c^2<1} \, dV &=
  abc \iiint_{X^2+Y^2+Z^2<1} \, dX \, dY \, dZ \\
  &=
  abc\int_{-1}^{1}
  \left[
    \int_{-\sqrt{1-X^2}}^{\sqrt{1-X^2}}
    \left( \int_{-\sqrt{1-X^2-Y^2}}^{\sqrt{1-X^2-Y^2}} dZ \right) dY
  \right] dX \\
  &=
  abc\int_{-1}^{1}
  \left[
    \int_{-\sqrt{1-X^2}}^{\sqrt{1-X^2}}
    2\sqrt{1-X^2-Y^2} dY
  \right] dX \\
  &= abc\int_{-1}^{1} \pi (1-X^2) \, dX \\
  &= \frac{4\pi abc}{3}
\end{align*}


text:
Q: How does SQL LIMIT ordering work If you select from a sql database and add a limit, and run it multiple times, the results will vary. However, when you want to select randomly from a database you usually do:
order by random()
limit n

My question is how does sql limit ordering work. If its not random then how are the results being varried?

A: LIMIT doesn't do ordering, period. If you want a specific ordering, use ORDER BY.
If no ORDER BY is specified, then the rows are not returned in any specific order. They may be the same from run to run, but it depends on all sorts of things having to do with retrieval of rows from the underlying data file, or indexes, or join order. Regardless of what might control ordering when no ORDER BY is specified, you should not depend on it.

A: It varies by each vendor's implementation, but generally the entire result set is generated, then the ORDER BY is applied if it exists, and then the server only returns n rows to the client.
Note that LIMIT or TOP without ORDER BY is non-deterministic.  That is, the results are not guaranteed to be consistent between executions.


text:
Q: ruby in 100 minutes good_morning method issue I have been doing the Ruby in 100 minutes  on the JumpStart labs website, and encountered a problem during part 5.
I was asked to create a good_morning method that would print out a greeting such as 'Happy Monday, it's the 130 day of 2013'. Here is my current program:
class PersonalChef

    def good_morning

        today = Date.today.strftime("%A")
        day_of_year = Date.today.yday
        puts "Happy#{today}! It is the #{day_of_year} day of year."
        return self
            end

    def make_toast(color)
        puts " Making your toast #{color}!"
        return self
       end
    def make_milkshake(flavor)
        puts " Making a #{flavor} milkshake!"
        return self
       end

    def make_eggs(quantity)
        puts " Making you #{quantity} eggs!"
        return self
            end
            end

when I try to run the program load on irb( 'personal_chef.rb', frank = PersonalChef.new, frank.make_milkshake('chocolate'), etc, everything works fine until I try to type frank.good_morning into irb, which gives the following error message:
NameError: **uninitialized constant** PersonalChef :: Date
     from personal_chef.rb:5: in good_morning from (irb):3 from /bin/irb:12:in '<main>'

Any help or information to help me solve this issue would be greatly appreciated.
Thanks for your time!

A: The error is because you haven't required the 'date' library.  So when your code executes the good_morning method it doesn't know about Ruby's Date class.  So in that scope it tries to find a PersonalChef::Date class which also doesn't exist.
Add the following to the top of the file and it should work:
require 'date'


text:
Q: Sitecore Lucene indexing - save child field values in parent Lucene doc I have a Sitecore content structure where any single item can have a number of child items that are used to store enumerable content for lists (obviously a fairly standard approach). I am hoping to index these items but store their index data against the parent doc in Lucene. This should hopefully speed up the search bit, by saving time sorting through multiple results which all effectively point to the same URL. Below is some basic code for the custom indexer I will implement.
Can anyone let me know if this is (a) possible and (b) a good idea? The main issues I see are that the Lucene doc already looks like it has been created - do I need to delete it? Also, if the Lucene doc for the parent item does not exist, do I need to create it? And will it be overwritten/lost when the parent item is indexed. Looks like a bit of room of conflict there.
Another option is that I don't index child items, but get their values when I am indexing the parent. Now that I think about it, this seems like the better way to go.. opinions?
public class CustomIndex : Sitecore.Data.Indexing.Index
{
    public CustomIndex(string indexName): base(indexName) {}

    protected override void AddFields(Item item, Document document)
    {
        //is item a sub-item (promo item)
        if (...)
        {
            //delete the sub-item lucene doc
            DeleteDoc(document); //is this possible or needed?

            //get parent item
            Item parentItem = item.Parent;

            //get lucene document for parent item
            Document parentDoc = GetParentDoc();

            //add fields to parent item lucene document
            parentDoc.Add(...);
            parentDoc.Add(...);
        }
        else
        {
            base.AddFields(item, document);
        }
    }
}

A: yes i agree, option #2 is better - index the children when you're at the parent. mainly because you aren't guaranteed what order the traversal will happen in, so the document may get re-created as you said.


text:
Q: v4l2loopback SMPTE color bars in Genymotion I'm running v4l2loopback on a Ubuntu 18.04 machine v4l2-ctl and virtualbox installed.

I use command below to initialize a loopback camera:
sudo modprobe v4l2loopback video_nr=2 card_label="Hello world" exclusive_caps=1 devices=1
v4l2-ctl --device=/dev/video2 --all

and output form the second command above is:
Driver Info (not using libv4l2):
    Driver name   : v4l2 loopback
    Card type     : Hello world
    Bus info      : platform:v4l2loopback-000
    Driver version: 5.3.18
    Capabilities  : 0x85208000
        Video Memory-to-Memory
        Read/Write
        Streaming
        Extended Pix Format
        Device Capabilities
    Device Caps   : 0x05208000
        Video Memory-to-Memory
        Read/Write
        Streaming
        Extended Pix Format
Priority: 0
Format Video Output:
    Width/Height      : 416/720
    Pixel Format      : 'YU12'
    Field             : None
    Bytes per Line    : 416
    Size Image        : 449280
    Colorspace        : sRGB
    Transfer Function : Default (maps to sRGB)
    YCbCr/HSV Encoding: Default (maps to ITU-R 601)
    Quantization      : Default (maps to Limited Range)
    Flags             :
Streaming Parameters Video Capture:
    Frames per second: 30.000 (30/1)
    Read buffers     : 2
Streaming Parameters Video Output:
    Frames per second: 30.000 (30/1)
    Write buffers    : 2

User Controls

                    keep_format 0x0098f900 (bool)   : default=0 value=0
              sustain_framerate 0x0098f901 (bool)   : default=0 value=0
                        timeout 0x0098f902 (int)    : min=0 max=100000 step=1 default=0 value=0
               timeout_image_io 0x0098f903 (bool)   : default=0 value=0

Now I can feed the input from my desktop
sudo ffmpeg -f x11grab -r 25 -s 416x768 -i :0.0+0,0 -vcodec rawvideo -pix_fmt yuv420p -threads 0 -f v4l2 /dev/video2

Or my stream OBS:
ffmpeg -f flv -listen 1 -i rtmp://localhost:1935/live/app -f v4l2 /dev/video2

And both work perfect; because I can view the output using WebRTC, Chrome, Firefox, and ffplay:
ffplay /dev/video2

My machine also has a webcam running on /dev/video0 which works perfect with genymotion.
But when I choose my "Hello world", genymotion exports noise (SMPTE color bars) as result.
Whats wrong with my Genymotion? I found that there are differences between UVC output and v4l2loopback.

A: Can you provide the logs of the Genymotion Emulator, located here ~/.Genymobile/Genymotion/deployed/<yourdevice>/genymotion-player.log, there might be interesting insights in there.