text:
Q: How can you pipe a readable stream to gulp.dest()? I've got the following sample code which attempts to pipe a stream to gulp.dest():
  var gulp = require('gulp');
  var stream = require('stream');

  var readable = new stream.Readable;
  readable.push('Hello, world!');
  readable.push(null);
  readable
  .pipe(gulp.dest('./test.txt'));

This code produces the following error:
path.js:146
      throw new TypeError('Arguments to path.resolve must be strings');
      ^
TypeError: Arguments to path.resolve must be strings
    at Object.win32.resolve (path.js:146:13)
    at DestroyableTransform.saveFile [as _transform] (C:\paylocity\expense\node_modules\gulp\node_modules\vinyl-fs\lib\dest\index.js:36:26)
    at DestroyableTransform.Transform._read (C:\paylocity\expense\node_modules\gulp\node_modules\vinyl-fs\node_modules\through2\node_modules\readable-stream\lib\_stream_transform.js:184:10)
    at DestroyableTransform.Transform._write (C:\paylocity\expense\node_modules\gulp\node_modules\vinyl-fs\node_modules\through2\node_modules\readable-stream\lib\_stream_transform.js:172:12)
    at doWrite (C:\paylocity\expense\node_modules\gulp\node_modules\vinyl-fs\node_modules\through2\node_modules\readable-stream\lib\_stream_writable.js:237:10)
    at writeOrBuffer (C:\paylocity\expense\node_modules\gulp\node_modules\vinyl-fs\node_modules\through2\node_modules\readable-stream\lib\_stream_writable.js:227:5)
    at DestroyableTransform.Writable.write (C:\paylocity\expense\node_modules\gulp\node_modules\vinyl-fs\node_modules\through2\node_modules\readable-stream\lib\_stream_writable.js:194:11)
    at Readable.ondata (_stream_readable.js:540:20)
    at Readable.emit (events.js:107:17)
    at Readable.read (_stream_readable.js:373:10)

I can't, however, see what exactly is wrong with the code.  If I replace gulp.dest() with process.stdout then it works and the gulp.dest() works within the context of other calls.  What is a viable way of doing this?

A: Gulp works with Vinyl streams:
var gulp   = require('gulp'),
    stream = require('stream'),
    source = require('vinyl-source-stream');

var readable = new stream.Readable;
readable.push('Hello, world!');
readable.push(null);

readable
    .pipe(source('test.txt'))
    .pipe(gulp.dest('.'));

A Gulp stream normally begins with some file or files as source, so you need to wrap that readable stream into a Vinyl stream allowing Gulp and any gulp-plugin getting info from it like filename (obviously faked), avoiding that error of yours.
So, Gulp streams are streams of files, just check the source...


text:
Q: qooxdoo : Layout of a Menu Strip In qooxdoo using qx.Desktop, I made a menu strip which looks like this:

how to modify the qx.ui.window.Window layout like this ? (I work it out in CSS)

Current qooxdoo source:
qx.Class.define("my_project.gameui.MainGameMenu",
{
  extend : qx.ui.window.Window,

    construct : function()
    {
      this.base(arguments, "MainGameMenu");
      // hide the window buttons
      this.setShowClose(false);
      this.setShowMaximize(false);
      this.setShowMinimize(false);
      // adjust size
      this.setWidth(400);
      this.setHeight(80);

      this.getChildControl("captionbar").setVisibility("excluded");

      var layout = new qx.ui.layout.Grid(0,0);
      this.setLayout(layout);
      var toolbar = new qx.ui.toolbar.ToolBar();
      this.add(toolbar, {row: 0, column: 0});

      var btn_status    = new qx.ui.toolbar.Button("STATUS");
      var btn_backpack  = new qx.ui.toolbar.Button("BACKPACK");
      var btn_crew      = new qx.ui.toolbar.Button("CREW");
      var btn_social    = new qx.ui.toolbar.Button("SOCIAL");
      var btn_mission   = new qx.ui.toolbar.Button("MISSION");
      var btn_system    = new qx.ui.toolbar.Button("SYSTEM");
      btn_status.setWidth(80);
      btn_status.setHeight(80);
      toolbar.add(btn_status);
      toolbar.add(btn_backpack);
      toolbar.add(btn_crew);
      toolbar.add(btn_social);
      toolbar.add(btn_mission);
      toolbar.add(btn_system);
    }
});

Seems I am still far from complete. I need to remove the default layout for this menu strip and add my own style. How can I do it?

A: This should resemble your screenshot and give you a good starting point for further adaptions:
Edit your Appearance.js like this:
qx.Theme.define("my_project.theme.Appearance",
{
  extend : qx.theme.modern.Appearance,

  appearances :
  {
    "mywindow":
    {
      style : function(states)
      {
        return {
          paddingRight: 15,
          paddingLeft: 15,
          decorator: "horizontalrule"
        };
      }
    },

    "mybutton":
    {
      style : function(states)
      {
        return {
          padding: 10,
          marginBottom: 1,
          textColor: "blue",
          decorator: "redbox"
        };
      }
    }
  }
});

Then edit your Decoration.js like this:
qx.Theme.define("my_project.theme.Decoration",
{
  extend : qx.theme.modern.Decoration,

  decorations :
  {
    "horizontalrule":
    {
        decorator : [
          qx.ui.decoration.MSingleBorder
        ],

        style:
        {
          widthBottom: 1,
          colorBottom: "black"
        }
    },

    "redbox":
    {
        decorator : [
          qx.ui.decoration.MSingleBorder
        ],

        style:
        {
          width: 1,
          color: "red"
        }
    }
  }
});

Finally you have to set the appearances on the widgets:
qx.Class.define("my_project.gameui.MainGameMenu",
{
  extend : qx.ui.window.Window,

    construct : function()
    {
      this.base(arguments, "MainGameMenu");

      ...
      // reset appearance
      // (could also be done by defining an additional appearance like before)
      toolbar.setAppearance("");
      ...
      btn_status.setAppearance("mybutton");
      btn_backpack.setAppearance("mybutton");
      btn_crew.setAppearance("mybutton");
      btn_social.setAppearance("mybutton");
      btn_mission.setAppearance("mybutton");
      btn_system.setAppearance("mybutton");
      ...
      this.setAppearance("mywindow");
      ...

Some notes:

*

*mywindow, mybutton, horizontalrule, redbox are of course arbitrary strings

*instead of "black" you could also write "#000" or even a string from the Color.js of the currently used theme [1]

*this is just a starting point because we now have overwritten all states (hovered, pressed, disabled ...) for the toolbar buttons. Copy the originally framework code of the style function from [2] over in your Appearance.js, merge it with your own return statement and adapt it to your needs.

Dive deeper in the code/manual:

*

*[1] https://github.com/qooxdoo/qooxdoo/blob/master/framework/source/class/qx/theme/modern/Color.js

*[2] https://github.com/qooxdoo/qooxdoo/blob/master/framework/source/class/qx/theme/modern/Appearance.js#L1441
Theming in general:

*

*http://manual.qooxdoo.org/current/pages/desktop/ui_theming.html

*http://manual.qooxdoo.org/current/pages/desktop/ui_custom_themes.html
More specific:

*

*http://manual.qooxdoo.org/current/pages/desktop/ui_decorators.html

*http://manual.qooxdoo.org/current/pages/desktop/ui_appearance.html

redpajama_set_name: RedPajamaStackExchange


text:
Q: Extending the Charme Interpreter I need to extend the Charme interpreter (described here) by adding a primitive procedure <= to the global environment. I know that to do this I also need to define a procedure that implements the primitive, and modify initializeGlobalEnvironment to install the primitive.
This is what I have for initializeGlobalEnvironment --
def initializeGlobalEnvironment():
    global globalEnvironment
    globalEnvironment = Environment(None)
    globalEnvironment.addVariable('true', True)
    globalEnvironment.addVariable('false', False)
    globalEnvironment.addVariable('+', primitivePlus)
    globalEnvironment.addVariable('-', primitiveMinus)
    globalEnvironment.addVariable('*', primitiveTimes)
    globalEnvironment.addVariable('=', primitiveEquals)
    globalEnvironment.addVariable('zero?', primitiveZero)
    globalEnvironment.addVariable('>', primitiveGreater)
    globalEnvironment.addVariable('<', primitiveLessThan)

A: I am not sure about the exact syntax for charme, but the approximate scheme-y code would be
primitiveLessThanEqualTo = '(lambda (x y) (if (= x y) (true) (if (< x y) (true) (false))))'
globalEnvironment.addVariable('<=', primitiveLessThanEqualTo)


text:
Q: Making A Meteor Subdocument Reactive I have a collection of Items that can be marked as "read" by my users.
In order to mark a collection as "read", a subdocument is added:
"readby": [
    {
      "action": "read",
      "owner": "w5XzMrCCJJfDxCn6d"
    }
  ]

I then use the following helper to set up an array and push any "read" entries that match the current owner. If the array has a length bigger than 0, the helper returns "true" and we know the logged in user has read this item:
itemHasBeenRead() {
    var subscribers = [];
    var readItems = this.readby;

    if(!readItems) {
        return false;
    }

    var readiness = readItems.forEach(function(currentSubscriber) {
      // loop over current users expenses
      var newSubscriber = { owner: currentSubscriber.owner };

      if (currentSubscriber.owner == Meteor.userid()) {
            subscribers.push(newSubscriber);
      }
    });

    return subscribers && subscribers.length > 0
}

This all works perfectly BUT as I understand it, subdocuments aren't reactive in Meteor, so the code doesn't pick up changes reactively. Refresh the page and it works fine.
Is there a way to do this reactively, rather than just on page load?
--
Edits as requested:
--
Template code:
{{#each playlists}}

{{playlistName}}{{numberOfSubscribers}} enrolled{{#unless isPlaylistOwner}}{{#unless userIsSubscribed}}Enrol{{/unless}}{{#if userIsSubscribed}}Enrolled{{/if}}{{/unless}}

        0/6 items marked complete

        {{#if isPlaylistOwner}}Delete{{/if}}

      {{playlistPrivacyType}} collection by {{playlistOwnerName}}

          {{#if isPlaylistOwner}}

+

          {{/if}}

          {{#each playlistItems this._id}}

            {{#if isPlaylistItemOwner}}

{{/if}}

              "{{itemDescription}}"

            {{#unless itemHasBeenRead}}

            {{/unless}}
            {{#if itemHasBeenRead}}

            {{/if}}
          {{#if hasPrice}}

{{/if}}

{{itemTitle}}

{{itemDescription}}...

          {{/each}}

      {{/each}}

Publication code:
Meteor.publish('UserPlaylists', function() {
  var loggedinuser = Meteor.user();
  // Reveal ALL expenses if it's an admin who's logged in
  return Playlists.find({
    owner: loggedinuser._id
  });
});

// Publish public playlists, as long as they're both public and from the same company
Meteor.publish('PublicPlaylists', function() {
  var loggedinuser = Meteor.user();
  var companyid = loggedinuser.userofcompanyid;
  // Reveal ALL expenses if it's an admin who's logged in
  return Playlists.find({
    companyid: companyid,
    published: true
  });
});

// Publishes absolutely all expenses for superadmins
Meteor.publish('Playlists', function() {
  var loggedinuser = Meteor.user();
  if (loggedinuser.issuperadmin) {
    return Playlists.find({});
  }

});

Subscribing to the publications in the template js:
Template.Playlists.onCreated(function playlistsOnCreated() {
  var self = this;
  self.autorun(function() {
    self.subscribe('UserPlaylists');
    self.subscribe('PublicPlaylists');
    self.subscribe('UserPlaylistItems');
    self.subscribe('PublicPlaylistItems');
  });
});

The playlists helper:
  playlists() {
    return Playlists.find({}, {
      sort: {
        timestamp: -1
      }
    });
  },

The playlistItems helper:
  playlistItems(playlistid) {
    return PlaylistItems.find({
      playlistid: playlistid
    }, {
      sort: {
        timestamp: -1
      }
    });
  },


text:
Q: How do I return a set of rows when a condition is true on one or more rows within the set? How do I return a set of multiple rows when a condition is true on one or more rows within the set?
RECORD  VERSION INDICATOR AREA
1234    01  A     CA
1234    02  B     CA
1234    03  C     CA
5678    01  D     CO
5678    02  L     CO
5678    03  F     CO

For example, I would like to return all rows within a record set if a B indicator is present within the set.
I can query for that condition, but it simply returns the one row where the condition is true.
SELECT
record,
version,
indicator,
area

FROM vista
WHERE indicator = 'B';

Expected results:
RECORD  VERSION INDICATOR AREA
1234    01  A     CA
1234    02  B     CA
1234    03  C     CA

A: You can use EXISTS and a correlated subquery that checks for a record with a 'B' indicator.
SELECT v1.record,
       v1.version,
       v1.indicator,
       v1.area
       FROM vista v1
       WHERE EXISTS (SELECT *
                            FROM vista v2
                            WHERE v2.record = v1.record
                                  AND v2.indicator = 'B');

A: Since the common field is Area, you want two subsets that match on that field.
SELECT va.record, va.version, va.indicator, va.area
FROM vista va
WHERE va.Area = 'CA' AND EXISTS (
  SELECT * FROM vista WHERE Area = va.Area and vi.indicator = 'B'
)

A: select record, version, indicator, area
from vista
where area IN
 (
 select area
 from vista
 where indicator = "B"
 )


text:
Q: is this the proper way to use initialization? Right so I always initialize with a function, but I'm new to this swift initialization so is this way that I initialized this 2d array proper.
var board = [[UIButton]](){
   init(array:UIButton){
       board = [
          [b0,b1,b2],
          [b3,b4,b5],
          [b6,b7,b8]

    ]
  }
}

A: Your board variable must be initialised with an array of buttons, so in the class that contains your board, you specify an init(boardButtons:) initializer that initializes the board variable:
class ClassThatContainsBoard {

    var board: [[UIButton]]

    init(boardButtons: [UIButton]) {
        let b = boardButtons
        board = [
            [b[0], b[1], b[2]],
            [b[3], b[4], b[5]],
            [b[6], b[7], b[8]]
        ]
    }
}

If your class itself knows what buttons should comprise the board, you needn't specify an initializer that takes the buttons as a parameter. Variables can take a closure to initialize themselves to a default value:
class ClassThatContainsBoard {

    var board: [[UIButton]] = {
        var numRows = 3
        var numCols = 3
        var newBoard = [[UIButton]]()

        for row in 0..<numRows {
            var boardRow = [UIButton]()

            for col in 0..<numCols {
                let buttonNumber = (row + 1) * (col + 1)
                let button = UIButton(type: .Custom)
                button.setTitle("\(buttonNumber)", forState: .Normal)
                boardRow.append(button)
            }

            newBoard.append(boardRow)
        }

        return newBoard
    }()
}

So above, when an instance of ClassThatContainsBoard is initialized, the closure will be executed and return the default value for board. Here, it's just initialised to a 3x3 array of buttons, with each button's title set to the numbered position on the board.


text:
Q: How to Use Angular Routing from Child Component Using Angular Material I am trying to set up routing on a toolbar component that I created. The toolbar component is called in my app.component and that's how it is added to the DOM. I have a menu with 3 buttons on that toolbar and I would like to make them route to different links.
I tried importing AngularRouting into my child component (toolbar) but I am not sure what I'm doing anymore lol.
./toolbar/toolbar.ts:
     <button mat-menu-item>
       <mat-icon>home</mat-icon>
       Home
     </button>
     <button mat-menu-item>
       <mat-icon>assignment</mat-icon>
       About
     </button>
     <button mat-menu-item>
       <mat-icon>help</mat-icon>
       Help
     </button>
   </mat-menu>

How do I setup routing on the child component that uses angular material?

A: This can be achieved in several ways.

*

*using routerLink
<button routerLink='/home' mat-menu-item>
   <mat-icon>home</mat-icon>
   Home
 </button>

2 using .ts file
HTML
     <button (click)="navigateToHome()" mat-menu-item>
       <mat-icon>home</mat-icon>
       Home
     </button>

TS
constructor(private router:Router){}

navigateToHome(){
this.router.navigateByUrl('/home');
}

using Angular material doesn't change the way you navigate.
Hope it helps!


text:
Q: self.view not properly aligned on window So what I am really doing is... I have a login page, when proper login session took place, Its navigating to another view. It contains Tab bar. So what I did is, I made a separate class for customizing 'UITabbarController'. And now I see a white screen on the top and below is the view of that class.
Can anybody help me out?

A: Are you subclassing UITTabBarController?  It is not something you would normally want to do.
A better option is to create your second viewcontroller and add a normal UITabBarController onto that viewcontroller's view.


text:
Q: Help to bypass password for sample projects of excel I am doing project in EXCEL VBA.
i am taking refernce of some projects made in excel vba.
But when I trid to open that excel sample projects, it ask me for password.
so how can bypass password for that excel project  so i can take refrence so that i can take refrence of sample.
Please help....

A: the password was likely put in place to prevent copying of code. I would try Google for code that is freely available on the web relating to the sample project you are trying to recreate. Or ask a specific question here and see what you get.


text:
Q: Error while executing gem...Permission Denied I am attempting to install taps from my Heroku app folder. When I type "gem install taps," I get the following error:

ERROR:  While executing gem ... (Errno::EACCES)
      Permission denied - /Users/jacob/.rvm/gems/ruby-1.9.3-p194/gems/taps-0.3.24/bin/taps

I attempted to remove the taps-0.3.24 folder using rm -r and got this question: override rwxr-xr-x  root/staff for /Users/jacob/.rvm/gems/ruby-1.9.3-p194/gems/taps-0.3.24//bin/schema?
Upon typing yes, it tells me permission denied. Here is the whole exchange:

Jacob-MacBook-Pro:furious-ocean-6122012 jacob$ rm -r /Users/jacob/.rvm/gems/ruby-1.9.3-p194/gems/taps-0.3.24/
  override rwxr-xr-x  root/staff for /Users/jacob/.rvm/gems/ruby-1.9.3-p194/gems/taps-0.3.24//bin/schema? yes
  rm: /Users/jacob/.rvm/gems/ruby-1.9.3-p194/gems/taps-0.3.24//bin/schema: Permission denied
  override rw-r--r--  root/staff for /Users/jacob/.rvm/gems/ruby-1.9.3-p194/gems/taps-0.3.24//bin/schema.cmd?

Any thoughts on how to resolve this issue would be appreciated. Thanks!

A: I just ran into this when trying to get the Heroku Toolbelt running. I was able to remove the old version with sudo rm -rf /path/to/gems/taps-x.x.x and then re-install (without sudo).

A: You should add "sudo" before "gem...."


text:
Q: How to convert api JSON output to a dataframe? I am working on pulling weather data from NOAA API using a SDK. Below is the sample code:
import requests, json
import pandas as pd
from pandas.io.json import json_normalize

from noaa_sdk import noaa
n = noaa.NOAA()
n.points_forecast(40.7314, -73.8656, hourly=False)

The sample output is below:
{'@context':
['https://raw.githubusercontent.com/geojson/geojson-ld/master/contexts/geojson-base.jsonld',
{'wx': 'https://api.weather.gov/ontology#',    'geo':
'http://www.opengis.net/ont/geosparql#',    'unit':
'http://codes.wmo.int/common/unit/',    '@vocab':
'https://api.weather.gov/ontology#'}],  'type': 'Feature',
'geometry': {'type': 'GeometryCollection',   'geometries': [{'type':
'Point', 'coordinates': [-73.8610332, 40.7408918]},    {'type':
'Polygon',
    'coordinates': [[[-73.8730892, 40.7534295],
      [-73.8775823, 40.7317593],
      [-73.8489801, 40.7283524],
      [-73.84448110000001, 40.7500224],
      [-73.8730892, 40.7534295]]]}]},  'properties': {'updated': '2020-04-03T09:30:44+00:00',   'units': 'us',   'forecastGenerator':
'BaselineForecastGenerator',   'generatedAt':
'2020-04-03T14:18:55+00:00',   'updateTime':
'2020-04-03T09:30:44+00:00',   'validTimes':
'2020-04-03T03:00:00+00:00/P7DT4H',   'elevation': {'value': 14.9352,
'unitCode': 'unit:m'},   'periods': [{'number': 1,
    'name': 'Today',
    'startTime': '2020-04-03T10:00:00-04:00',
    'endTime': '2020-04-03T18:00:00-04:00',
    'isDaytime': True,
    'temperature': 53,
    'temperatureUnit': 'F',
    'temperatureTrend': 'falling',
    'windSpeed': '18 mph',
    'windDirection': 'N',
    'icon': 'https://api.weather.gov/icons/land/day/rain,50?size=medium',
    'shortForecast': 'Chance Light Rain',
    'detailedForecast': 'A chance of rain. Cloudy. High near 53, with temperatures falling to around 50 in the afternoon. North wind around
18 mph, with gusts as high as 29 mph. Chance of precipitation is
50%.'}

I need to convert above JSON output to a data frame so that I can export it as a CSV file. How to achieve that?
I need the dataframe to have the below columns
    'name': 'Today',
    'startTime': '2020-04-03T10:00:00-04:00',
    'endTime': '2020-04-03T18:00:00-04:00',
    'isDaytime': True,
    'temperature': 53,
    'temperatureUnit': 'F',
    'temperatureTrend': 'falling',
    'windSpeed': '18 mph',
    'windDirection': 'N',
    'icon': 'https://api.weather.gov/icons/land/day/rain,50?size=medium',
    'shortForecast': 'Chance Light Rain',
    'detailedForecast': 'A chance of rain. Cloudy. High near 53, with temperatures falling to around 50 in the afternoon. North wind around
18 mph, with gusts as high as 29 mph. Chance of precipitation is
50%.'

A: Ok, it is easier that we could have thought first. All the relevant fields are in the same dict in a list. This is a native entry for a DataFrame.
Assuming you have loaded the json in a data variable, you can just do:
df = pd.DataFrame(data['properties']['periods'],
          columns= ['name', 'startTime', 'endTime', 'isDaytime', 'temperature',
            'temperatureUnit', 'temperatureTrend', 'windSpeed', 'windDirection',
            'icon', 'shortForecast', 'detailedForecast'])

It will give:
    name                  startTime                    endTime  isDaytime  temperature temperatureUnit temperatureTrend windSpeed windDirection                                               icon      shortForecast                                   detailedForecast
0  Today  2020-04-03T10:00:00-04:00  2020-04-03T18:00:00-04:00       True           53               F          falling    18 mph             N  https://api.weather.gov/icons/land/day/rain,50...  Chance Light Rain  A chance of rain. Cloudy. High near 53, with t...


text:
Q: AdView type in interface declaration I was trying to create an interface that uses property of type AdView. I tried the following code, but the AdView is unresolved. Not sure why, but I gotta feeling I did something stupid. How exactly does one use AdView in interfaces?
import com.google.android.gms.ads.AdView;
public interface ActionResolver {

    public void showInterstitial();
    public void loadInterstitial();
    public AdView getBanner(); /// doesn't recognize AdView
}

A: Check if you have added the dependency correctly. There should not be anything special to use a class in an interface.
build.gradle (excerpt)
...
dependencies {
        compile fileTree(dir: 'libs', include: ['*.jar'])
        compile 'com.android.support:appcompat-v7:22.2.0'
        compile 'com.google.android.gms:play-services-ads:8.3.0'
    }
...


text:
Q: InflateException in custom ImageView I'm making an example that rotate an image like this post.
I've extends ImageView then override the OnDraw and put in MainActivity. But It fired "InflateException".
Here is my example code:
MImageView
public class MImageView extends ImageView {

    public MImageView(Context context) {
        super(context);
        // TODO Auto-generated constructor stub
    }

    @Override
    protected void onDraw(Canvas canvas) {
        // TODO Auto-generated method stub
        canvas.save();
        canvas.rotate(45, 0, 0);
        super.onDraw(canvas);
        canvas.restore();
    }
}

MainActivity
public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        MImageView mImageView = (MImageView) findViewById(R.id.imageView1);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

}

main_activity.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <com.example.rotatetest.MImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_launcher" />

</RelativeLayout>

Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.rotatetest"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.rotatetest.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Logcat
08-16 10:21:31.820: D/AndroidRuntime(5135): Shutting down VM
08-16 10:21:31.820: W/dalvikvm(5135): threadid=1: thread exiting with uncaught exception (group=0x40ab4210)
08-16 10:21:31.820: E/AndroidRuntime(5135): FATAL EXCEPTION: main
08-16 10:21:31.820: E/AndroidRuntime(5135): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.rotatetest/com.example.rotatetest.MainActivity}: android.view.InflateException: Binary XML file line #13: Error inflating class com.example.rotatetest.MImageView
08-16 10:21:31.820: E/AndroidRuntime(5135):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2049)
08-16 10:21:31.820: E/AndroidRuntime(5135):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2083)
08-16 10:21:31.820: E/AndroidRuntime(5135):     at android.app.ActivityThread.access$600(ActivityThread.java:134)
08-16 10:21:31.820: E/AndroidRuntime(5135):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1233)
08-16 10:21:31.820: E/AndroidRuntime(5135):     at android.os.Handler.dispatchMessage(Handler.java:99)
08-16 10:21:31.820: E/AndroidRuntime(5135):     at android.os.Looper.loop(Looper.java:137)
08-16 10:21:31.820: E/AndroidRuntime(5135):     at android.app.ActivityThread.main(ActivityThread.java:4697)
08-16 10:21:31.820: E/AndroidRuntime(5135):     at java.lang.reflect.Method.invokeNative(Native Method)
08-16 10:21:31.820: E/AndroidRuntime(5135):     at java.lang.reflect.Method.invoke(Method.java:511)
08-16 10:21:31.820: E/AndroidRuntime(5135):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:787)
08-16 10:21:31.820: E/AndroidRuntime(5135):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:554)
08-16 10:21:31.820: E/AndroidRuntime(5135):     at dalvik.system.NativeStart.main(Native Method)
08-16 10:21:31.820: E/AndroidRuntime(5135): Caused by: android.view.InflateException: Binary XML file line #13: Error inflating class com.example.rotatetest.MImageView
08-16 10:21:31.820: E/AndroidRuntime(5135):     at android.view.LayoutInflater.createView(LayoutInflater.java:589)
08-16 10:21:31.820: E/AndroidRuntime(5135):     at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:680)
08-16 10:21:31.820: E/AndroidRuntime(5135):     at android.view.LayoutInflater.rInflate(LayoutInflater.java:739)
08-16 10:21:31.820: E/AndroidRuntime(5135):     at android.view.LayoutInflater.inflate(LayoutInflater.java:489)
08-16 10:21:31.820: E/AndroidRuntime(5135):     at android.view.LayoutInflater.inflate(LayoutInflater.java:396)
08-16 10:21:31.820: E/AndroidRuntime(5135):     at android.view.LayoutInflater.inflate(LayoutInflater.java:352)
08-16 10:21:31.820: E/AndroidRuntime(5135):     at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:255)
08-16 10:21:31.820: E/AndroidRuntime(5135):     at android.app.Activity.setContentView(Activity.java:1879)
08-16 10:21:31.820: E/AndroidRuntime(5135):     at com.example.rotatetest.MainActivity.onCreate(MainActivity.java:15)
08-16 10:21:31.820: E/AndroidRuntime(5135):     at android.app.Activity.performCreate(Activity.java:4539)
08-16 10:21:31.820: E/AndroidRuntime(5135):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
08-16 10:21:31.820: E/AndroidRuntime(5135):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2013)
08-16 10:21:31.820: E/AndroidRuntime(5135):     ... 11 more
08-16 10:21:31.820: E/AndroidRuntime(5135): Caused by: java.lang.NoSuchMethodException: <init> [class android.content.Context, interface android.util.AttributeSet]
08-16 10:21:31.820: E/AndroidRuntime(5135):     at java.lang.Class.getConstructorOrMethod(Class.java:460)
08-16 10:21:31.820: E/AndroidRuntime(5135):     at java.lang.Class.getConstructor(Class.java:431)
08-16 10:21:31.820: E/AndroidRuntime(5135):     at android.view.LayoutInflater.createView(LayoutInflater.java:561)
08-16 10:21:31.820: E/AndroidRuntime(5135):     ... 22 more

Did I do something wrong?

A: You have not implemented constructor with (class android.content.Context, interface android.util.AttributeSet) signature.

A: You're missing the constructor for MImageView(Context, Attributeset). Just add it and the error will be gone :)


text:
Q: Disable all options selected in other elements I am trying to disable an option if it has been selected in any of the other select elements, and re-enable it if it gets unselected.
This function isn't working properly when I preselect options (selected="selected"), and only works for one option at a time amongst all the select elements. How can I modify it to work with preselected options and for all of the options amongst all the elements?
I posted a fiddle of the function without any preselected options here: http://jsfiddle.net/dZqEu/927/
JS
$('.rank_options').change(function() {
    $('#priority1, #priority2, #priority3, #priority4, #priority5').not(this)
    .children('option[value=' + this.value + ']')
    .attr('disabled', true)
    .siblings().removeAttr('disabled');
});

HTML

<select name=priority1 id="priority1" class="rank_options" >
    <option selected="selected" value="Test 1">Test 1</option>
    <option value="Test 2">Test 2</option>
    <option value="Test 3">Test 3</option>
    <option value="Test 4">Test 4</option>
    <option value="Test 5">Test 5</option></select>

<select name=priority2 id="priority2" class="rank_options" >
    <option value="Test 1">Test 1</option>
    <option selected="selected" value="Test 2">Test 2</option>
    <option value="Test 3">Test 3</option>
    <option value="Test 4">Test 4</option>
    <option value="Test 5">Test 5</option></select>

<select name=priority3 id="priority3" class="rank_options" >
    <option value="Test 1">Test 1</option>
    <option value="Test 2">Test 2</option>
    <option selected="selected" value="Test 3">Test 3</option>
    <option value="Test 4">Test 4</option>
    <option value="Test 5">Test 5</option></select>

<select name=priority4 id="priority4" class="rank_options" >
    <option value="Test 1">Test 1</option>
    <option value="Test 2">Test 2</option>
    <option value="Test 3">Test 3</option>
    <option selected="selected" value="Test 4">Test 4</option>
    <option value="Test 5">Test 5</option></select>

<select name=priority5 id="priority5" class="rank_options" >
    <option value="Test 1">Test 1</option>
    <option value="Test 2">Test 2</option>
    <option value="Test 3">Test 3</option>
    <option value="Test 4">Test 4</option>
    <option selected="selected" value="Test 5">Test 5</option></select>

A: Something like this?
$(document).ready(function(){
$('select option[value="Test 1"]').attr('disabled',true);
});
$('.rank_options').change(function () {
  $('#priority1, #priority2, #priority3, #priority4, #priority5').
  find('option:selected').each(function(){
   $("#priority1, #priority2, #priority3, #priority4, #priority5").find("option[value="+this.value+"]").attr('disabled', true);
   });
});

DEMO VIEW


text:
Q: How to answer a call programmatically How to answer a call programatically.
I have tried to implement the below code using TelephonyManager.
TelephonyManager tm = (TelephonyManager) mContext
        .getSystemService(Context.TELEPHONY_SERVICE);

if (tm == null) {
    // whether you want to handle this is up to you really
    throw new NullPointerException("tm == null");
}
tm.answerRingingCall();

But, It is not working. Is there any other ways to do the same.


text:
Q: Does everyone in Door's family have the same power as her? In Neverwhere, the character Door has a magical ability with doors - either opening existing ones without needing a key, or (apparently) creating portals of her own such as when she first finds Richard. It's mentioned a few times that this ability is something to do with her family, and other family members, such as her father Lord Portico, also have door-related names.
Does everyone in Door's family have the same power as her? Or is it only some of them? Or do some of them have other magical abilities instead?

A: To add to the existing answers, all current members of the Portico family at the start of Neverwhere are Openers.  The book does not state whether all previous (or future - thanks @Valorum!) members of the family have the ability.
Also per @Valorum's quotes, it is an ability which requires some level of practise to learn, and possibly assistance from others.  The book does not state whether people who join the family can be taught or otherwise "given" the ability, nor whether Portico's family are the only Openers.  However since Door has a father and mother who are both Openers, we can infer that one of those must be the case (unless the Portico family practise sibling marriage).
Some characters in the book do indeed have more than one "knack".  Croup and Vandemar are notable examples - they do not age, do not bleed, and are apparently able to move from place to place without transition (or at least quicker than can be seen).  The book does not state whether a "knack" is learnt or innate, and it also does not state whether people with a "knack" are actually human or just choose to look human-ish (as is the case with Islington, of course).

A: Yes, the whole family has the ability. This is made pretty clear in the book (not so sure about the TV series/radio series/comics).
For example, Portico's "house" consist of a series of rooms spread out all over the world, linked in a way that only a member of his family could go from one to the other. The Marquis comments in astonishment upon this as an excellent security setup, and can't figure out how Croup and Vandemar managed to defeat it (which we never do find out exactly).
Door also mentions casually to Richard that her family has a certain gift with doors.
If I recall correctly, there's also a bit towards the end where the heroes are informed that they can kill Door at need because they still have Door's little brother. Although I believe that turned out to be a lie, the implication is that they have another person able to open doors at need.
I think there is also a bit near the beginning where Door is being chased and tries to calm herself by going through exercises that her father taught her in order to Open.
It's also symbolic with her father having plans to unite London Above and London Below. That he would be the one to open the door to doing so.
I think the Earl also comments at one point about Portico's family all having that funny thing with doors.

A: It would appear that being an "opener" is restricted to the Portico family.

Door said, patiently, "And the quick way is?"
"No, no. Need to be an opener to use it. Only good for Portico's
  family." He rested a huge hand on her shoulder. Then his hand slid up
  to her cheek. "Better off staying here with me. Keep an old man warm
  at night, eh?" He leered at her, and touched her tangle of hair with
  his old fingers. Hunter took a step toward Door. Door gestured with
  her hand: No. Not yet.

It's not clear whether the Lady Door has other extant relatives with the same capacity but when she talks about it, she always refers to her family, not just her father.

Door smiled, suddenly; her face seemed to be illuminated. For a
  moment, her elfin face became beautiful. "Richard," she said. "My
  family. We're openers. It's our Talent. Look . . ." She reached out a
  grubby hand, touched the door.

We see her and her brother practicing their 'opening' skills.

She holds it in her hand, feeling the cold metal, feeling the weight
  of the lock in her hands. Something is bothering her. There is
  something she has to know. Door learned to open some time after she
  learned to walk. She remembers her mother holding her tightly, opening
  a door from Door's bedroom to the playroom, remembers watching her
  brother Arch separating linked silver rings, joining them back
  together.
She tries to open the padlock. She fumbles at it with her fingers, and
  with her mind. Nothing happens. She throws the padlock down onto the
  floor and begins to cry. Her father reaches down and picks up the
  padlock, puts it back into her hand. His long finger brushes away a
  tear from her cheek.


text:
Q: Science Fiction Stories - included story about miniature civilization on brink of extinction Read a book called "Science Fiction Stories" as a kid in the early 80's. It was anthology of short stories, roughly 8x11 in size, paperback cover, and I don't remember much else from the cover other than the title.
I remember one story that stuck with me in particular - about a kid who stumbled onto to a miniature civilization that seemed doomed to extinction. The kid tried to save it after making friends with a member of the miniatures. But the story ended sadly when the miniature friend died in the final paragraph...
Would love to know if anyone knows the book I'm talking about. Thanks!

A: P.S. Oops, I just noticed that The Random House Book of Science Fiction Stories was published in 1997 and you read your book in the early 80's. I guess this is a wrong answer then. Sorry about that!
You may be thinking of The Random House Book of Science Fiction Stories; a 5.5" by 8.5" trade paperback, it was the American edition of Space Stories, edited by Mike Ashley. If so, the closest story in that book to your description is "Status Extinct" by Eric Brown.
The "kid" is a woman space explorer:

Jessica Ball sneezed as her ship came in to land.
She blew her nose and dropped the tissue in the waste chute. She could not believe it. Modern science had developed starships to send her to the edge of the galaxy in search of intelligent life, and yet there was still no cure for the common cold.

The "miniature" aliens stand a meter tall:

The creatures were not animals—but men. They were tiny, perhaps a meter high and impossibly slim, their arms and legs as thin and gray as gun barrels. Jessica counted twenty of the tiny extraterrestrials. They moved slowly down the slope, as if wary of the strange creature lying at the bottom.
I don't believe it, she said to herself. Aliens—real, live humanoid aliens . . . She decided to call them Thinnies.

However, she is not trying to save the aliens. On the contrary, the aliens save her life after she breaks her leg, giving her first aid and hauling her back to her spaceship:

The aliens dragged the sled up the ship's ramp and left her at the top. Jessica sat up, stared at the beings who had saved her life. She raised her hand, and the Thinnies, responding to her gesture, raised their hands also before walking down the ramp and away from the ship.

The aliens were in no danger of extinction until Jessica came along:

For she had brought death to these innocent people; she had spread disease amongst them in the form of the influenza virus, a virus new to them and against which, therefore, they had no protection.
"I'm sorry," she whispered. "I'm so sorry."
She pulled the St. Christopher medallion from her pouch and dropped it into the hand of the dead alien.

The final paragraph:

She readied the ship for lift-off.
As the engines fired, she entered computer's exploration files. She typed in the information:
Planet: WINTERWORLD
Native Fauna: HUMANOID ALIENS—INTELLIGENT
Status: . . .
Jessica hesitated, tears rolling down her cheeks.
At last she typed:
Status: EXTINCT
Then the ship lifted, carrying Jessica Ball away from Winterworld forever.

The short story "Status Extinct" was identified previously as part of the answer to this question. The anthology it's in was also identified in answers to this question and this one; perhaps you will recognize the descriptions of some of the other stories.


text:
Q: Formatar uma duração "hora:minuto" para o formato ISO 8601 Estou tentando transformar a string 05:25 para PT05M25S.
Consegui chegar até aqui, altera o : pelo M. Mas não consegui inserir o restante que ficou faltando.
$date = "05:25";

$date = preg_replace('/[:\/]/', 'M', $date);

echo $date;

A: Fiz desse jeito:
$duration   = 05:25;

$duration   = preg_replace('/[:\/]/', 'M', $duration);

echo 'PT' . $duration . 'S';

Resultado: PT05M25S

A: O problema com seu código é que as barras no início e fim são delimitadores da regex. Por isso, quando uma outra barra é encontrada no meio da expressão, o PHP acha que a regex já terminou e dá erro. Uma forma de resolver é a que você fez: escapar a barra com \.
Outra opção é usar um caractere diferente como delimitador, já que há vários outros caracteres que podem ser usados além da barra. De preferência, escolha um que não está sendo usado na regex, assim você não precisa se preocupar com o escape:
// usando # como delimitador
$duration = preg_replace('#[:/]#', 'M', $duration);

Mas neste caso, não sei se precisa de regex, afinal você só quer trocar o caractere : por M, então um simples str_replace já resolveria:
$duration = "05:25";
echo "PT". str_replace(':', 'M', $duration). "S";

Mas como você está trabalhando com durações (quantidades de tempo), talvez seja interessante usar um DateInterval:
$duration = "05:25";
$partes = explode(':', $duration);
$d = DateInterval::createFromDateString("{$partes[0]} minutes + {$partes[1]} seconds");
$formatado = "PT";
if ($d->i > 0) {
    $formatado .= "{$d->i}M";
}
if ($d->s > 0) {
    $formatado .= "{$d->s}S";
}

echo $formatado; // PT5M25S

Pode parecer "pior" só porque o código ficou maior, mas creio que fica um pouco mais robusto, pois se a string não tiver números (por exemplo, se for "ab:xy"), ocorrerá um erro ao criar o DateInterval. Neste caso, bastaria verificar se ele foi criado mesmo:
$duration = "ab:xy"; // string inválida
$partes = explode(':', $duration);
$d = DateInterval::createFromDateString("{$partes[0]} minutes + {$partes[1]} seconds");
if ($d) {
    // $d foi criado corretamente, formatar o valor usando o código acima
} else {
    echo "erro ao criar o intervalo";
}

Já usando replace, não é feita nenhuma verificação, e ele aceita qualquer string que vier.
Eu incluí uma verificação para não colocar o valor na string quando este for zero, então se a string for "00:25" o resultado será PT25S. A norma ISO 8601 (que define este formato para durações) diz que não há problema em ter valores zerados, mas que estes podem ser omitidos caso sejam zero. Fica a seu critério decidir se vai incluir ou não.

Obviamente dá para melhorar, pois eu não verifiquei se o array retornado por explode possui duas posições, etc. Também não está claro se o formato sempre é "minutos:segundos". Se for, outra opção é usar format:
$duration = "05:25";
$partes = explode(':', $duration);
$d = DateInterval::createFromDateString("{$partes[0]} minutes + {$partes[1]} seconds");
echo $d->format('PT%iM%sS'); // PT5M25S

A diferença para o código anterior é que mesmo quando os valores forem zero eles serão incluídos na string. Por exemplo, para "00:25" o resultado será PT0M25S.


text:
Q: Why does React.js sometimes not let me use `debugger` Sometimes I can put debugger; statements in my React components and it works, and sometimes it doesn't.  For instance, I am calling my react component like this:
<script type="text/javascript">
    debugger;
    var nav = React.createElement(SubLocationSelector, {instanceID: @Model.InstanceID, locationID: @Model.LocationID, OnSublocationSelected: function(id, fullPath) {alert("ID: " + id + "; FullPath: " + fullPath);}}, null);
    ReactDOM.render(nav, document.getElementById("drill-down-nav"));
</script>

and its debugger point gets hit.  However inside the React component:
class SubLocationSelector extends React.Component{
    constructor(props) {
        debugger;
        super(props);
        this.model = new SubLocationSelectorViewModel();
        this.model.loadSubLocations(this.props.locationID);
    }
    componentWillReceiveProps(nextProps) {
        debugger;
        if(nextProps.locationID != this.props.locationID){
            this.model.loadSubLocations(nextProps.locationID)
        }
    }
    render() {
        debugger;
        return (
            <ViewModelBinder model={this.model}>
                <SublocationSelectorDisplay model={this.model}
                                            OnSublocationSelected={this.props.OnSublocationSelected} />
            </ViewModelBinder>
        )
    }
}

none of these debugger points get hit if I run the code in Chrome with devtools open.  I haven't yet isolated why some of my react components work with debugger and some don't, but I'm pretty confident it has to do with React.
Furthermore: is there a way to fix this behavior?
EDIT:
It's been suggested that this may be a culprit of a babel plugin such as remove-debugger.  Here are the babel plugins listed by npm ls:

I don't have a .babelrc file or a package.json.
Searching for remove-debugger in my entire solution gets no results.
EDIT2:
There are two different package.jsons that might be used by babel:
{
  "_args": [
    [
      {
        "raw": "babel-runtime@^6.20.0",
        "scope": null,
        "escapedName": "babel-runtime",
        "name": "babel-runtime",
        "rawSpec": "^6.20.0",
        "spec": ">=6.20.0 <7.0.0",
        "type": "range"
      },
      "C:\\develop\\trakref\\node_modules\\babel-traverse"
    ]
  ],
  "_from": "babel-runtime@>=6.20.0 <7.0.0",
  "_id": "babel-runtime@6.20.0",
  "_inCache": true,
  "_location": "/babel-runtime",
  "_nodeVersion": "6.9.0",
  "_npmOperationalInternal": {
    "host": "packages-12-west.internal.npmjs.com",
    "tmp": "tmp/babel-runtime-6.20.0.tgz_1481239547266_0.8724558432586491"
  },
  "_npmUser": {
    "name": "hzoo",
    "email": "hi@henryzoo.com"
  },
  "_npmVersion": "3.10.8",
  "_phantomChildren": {},
  "_requested": {
    "raw": "babel-runtime@^6.20.0",
    "scope": null,
    "escapedName": "babel-runtime",
    "name": "babel-runtime",
    "rawSpec": "^6.20.0",
    "spec": ">=6.20.0 <7.0.0",
    "type": "range"
  },
  "_requiredBy": [
    "/babel-messages",
    "/babel-traverse",
    "/babel-types"
  ],
  "_resolved": "https://registry.npmjs.org/babel-runtime/-/babel-runtime-6.20.0.tgz",
  "_shasum": "87300bdcf4cd770f09bf0048c64204e17806d16f",
  "_shrinkwrap": null,
  "_spec": "babel-runtime@^6.20.0",
  "_where": "C:\\develop\\trakref\\node_modules\\babel-traverse",
  "author": {
    "name": "Sebastian McKenzie",
    "email": "sebmck@gmail.com"
  },
  "dependencies": {
    "core-js": "^2.4.0",
    "regenerator-runtime": "^0.10.0"
  },
  "description": "babel selfContained runtime",
  "devDependencies": {
    "babel-helpers": "^6.6.0",
    "babel-plugin-transform-runtime": "^6.9.0"
  },
  "directories": {},
  "dist": {
    "shasum": "87300bdcf4cd770f09bf0048c64204e17806d16f",
    "tarball": "https://registry.npmjs.org/babel-runtime/-/babel-runtime-6.20.0.tgz"
  },
  "license": "MIT",
  "maintainers": [
    {
      "name": "amasad",
      "email": "amjad.masad@gmail.com"
    },
    {
      "name": "hzoo",
      "email": "hi@henryzoo.com"
    },
    {
      "name": "jmm",
      "email": "npm-public@jessemccarthy.net"
    },
    {
      "name": "loganfsmyth",
      "email": "loganfsmyth@gmail.com"
    },
    {
      "name": "sebmck",
      "email": "sebmck@gmail.com"
    }
  ],
  "name": "babel-runtime",
  "optionalDependencies": {},
  "readme": "ERROR: No README data found!",
  "repository": {
    "type": "git",
    "url": "https://github.com/babel/babel/tree/master/packages/babel-runtime"
  },
  "scripts": {},
  "version": "6.20.0"
}

and this one:
{
  "_args": [
    [
      {
        "raw": "core-js@^2.4.0",
        "scope": null,
        "escapedName": "core-js",
        "name": "core-js",
        "rawSpec": "^2.4.0",
        "spec": ">=2.4.0 <3.0.0",
        "type": "range"
      },
      "C:\\develop\\trakref\\node_modules\\babel-runtime"
    ]
  ],
  "_from": "core-js@>=2.4.0 <3.0.0",
  "_id": "core-js@2.4.1",
  "_inCache": true,
  "_location": "/babel-runtime/core-js",
  "_nodeVersion": "6.2.2",
  "_npmOperationalInternal": {
    "host": "packages-16-east.internal.npmjs.com",
    "tmp": "tmp/core-js-2.4.1.tgz_1468791807265_0.5941079026088119"
  },
  "_npmUser": {
    "name": "zloirock",
    "email": "zloirock@zloirock.ru"
  },
  "_npmVersion": "3.9.5",
  "_phantomChildren": {},
  "_requested": {
    "raw": "core-js@^2.4.0",
    "scope": null,
    "escapedName": "core-js",
    "name": "core-js",
    "rawSpec": "^2.4.0",
    "spec": ">=2.4.0 <3.0.0",
    "type": "range"
  },
  "_requiredBy": [
    "/babel-runtime"
  ],
  "_resolved": "https://registry.npmjs.org/core-js/-/core-js-2.4.1.tgz",
  "_shasum": "4de911e667b0eae9124e34254b53aea6fc618d3e",
  "_shrinkwrap": null,
  "_spec": "core-js@^2.4.0",
  "_where": "C:\\develop\\trakref\\node_modules\\babel-runtime",
  "bugs": {
    "url": "https://github.com/zloirock/core-js/issues"
  },
  "dependencies": {},
  "description": "Standard library",
  "devDependencies": {
    "LiveScript": "1.3.x",
    "es-observable-tests": "0.2.x",
    "eslint": "3.1.x",
    "grunt": "1.0.x",
    "grunt-cli": "1.2.x",
    "grunt-contrib-clean": "1.0.x",
    "grunt-contrib-copy": "1.0.x",
    "grunt-contrib-uglify": "1.0.x",
    "grunt-contrib-watch": "1.0.x",
    "grunt-karma": "2.0.x",
    "grunt-livescript": "0.6.x",
    "karma": "1.1.x",
    "karma-chrome-launcher": "1.0.x",
    "karma-firefox-launcher": "1.0.x",
    "karma-ie-launcher": "1.0.x",
    "karma-phantomjs-launcher": "1.0.x",
    "karma-qunit": "1.1.x",
    "phantomjs-prebuilt": "2.1.x",
    "promises-aplus-tests": "2.1.x",
    "qunitjs": "2.0.x",
    "temp": "0.8.x",
    "webpack": "1.13.x"
  },
  "directories": {},
  "dist": {
    "shasum": "4de911e667b0eae9124e34254b53aea6fc618d3e",
    "tarball": "https://registry.npmjs.org/core-js/-/core-js-2.4.1.tgz"
  },
  "gitHead": "5e106f64c726edf2849f0babc9096ce6664b7368",
  "homepage": "https://github.com/zloirock/core-js#readme",
  "keywords": [
    "ES3",
    "ECMAScript 3",
    "ES5",
    "ECMAScript 5",
    "ES6",
    "ES2015",
    "ECMAScript 6",
    "ECMAScript 2015",
    "ES7",
    "ES2016",
    "ECMAScript 7",
    "ECMAScript 2016",
    "Harmony",
    "Strawman",
    "Map",
    "Set",
    "WeakMap",
    "WeakSet",
    "Promise",
    "Symbol",
    "TypedArray",
    "setImmediate",
    "Dict",
    "polyfill",
    "shim"
  ],
  "license": "MIT",
  "main": "index.js",
  "maintainers": [
    {
      "name": "zloirock",
      "email": "zloirock@zloirock.ru"
    }
  ],
  "name": "core-js",
  "optionalDependencies": {},
  "readme": "ERROR: No README data found!",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/zloirock/core-js.git"
  },
  "scripts": {
    "grunt": "grunt",
    "lint": "eslint es5 es6 es7 stage web core fn modules",
    "observables-tests": "node tests/observables/adapter && node tests/observables/adapter-library",
    "promises-tests": "promises-aplus-tests tests/promises-aplus/adapter",
    "test": "npm run lint && npm run grunt livescript client karma:default && npm run grunt library karma:library && npm run promises-tests && npm run observables-tests && lsc tests/commonjs"
  },
  "version": "2.4.1"
}

A: Try to replace debugger with eval('debugger'), babel will not transform the string value.


text:
Q: How to show sql results under titles on python / pymysql? def selectTopNactors(n):

# Create a new connection
con=connection()

# Create a cursor on the connection
cur=con.cursor()
#execute query
sql ="""SELECT g.genre_name AS 'genreName', a.actor_id AS 'actorId', COUNT(*) AS 'number_of_movies'
FROM actor AS a, role AS r, movie AS m, genre AS g, movie_has_genre AS mg
WHERE a.actor_id = r.actor_id AND m.movie_id = r.movie_id
    AND m.movie_id = mg.movie_id AND g.genre_id = mg.genre_id
    AND (g.genre_id , m.movie_id) IN (SELECT g.genre_id, m.movie_id
                                        FROM movie AS m, genre AS g, movie_has_genre AS mg
                                        WHERE m.movie_id = mg.movie_id AND mg.genre_id = g.genre_id
                                        ORDER BY g.genre_id)
GROUP BY a.actor_id,g.genre_name

ORDER BY g.genre_name,number_of_movies DESC LIMIT 5 """

cur.execute(sql,)
results = cur.fetchall()
for row in cur:
     #genre_name = row[0]
     #actor_id = row[1]
     #number_of_movies = row[2]
     print(row["g.genre_id"])
     print(row["a.actor_id"])
     print(row["number_of_movies"])

print (n)
con.commit()
return [("genreName ", "actorId ", "numberOfMovies"),results]

When I try this I get something like this :

But I want every result to be showed in each column, for example actorid's in column of actorid and genre names in the column of genreName etc.


text:
Q: how to turn tar file object to string I have a tarfile object with a few files in it, one of them is called ffb.json. I tried the following to extract that json string,
with tarfile.open(mode="r:gz", fileobj=StringIO.StringIO(p.results)) as tar:
    for tarinfo in tar:
        print tarinfo.name
        if tarinfo.name == './ffb.json':
            print tarinfo.tobuf()

However, the print tarinfo.tobuf() doesn't print what I expected: ./ffb.json0000644000000000000000000000054313070524150012600 0ustar  rootroot00000000000000
If I extract the ffb.json by hand, it indeed has legitimate json string in it.

A: As noted in the documentation for tarfile, TarInfo only contains file metadata - "It does not contain the file's data itself."
Fortunately, you can pass that TarInfo object back into TarFile.extractfile(member) in order to get the file's contents as a file-like object (which you can subsequently .read() to get the raw contents). For example: print tar.extractfile(tarinfo).read().
Alternatively, you could just skip the foreach loop and call TarFile.extractfile(member) with the filename directly (e.g. print tar.extractfile("./ffb.json").read()).


text:
Q: android app stopped running on emulator and real device I am search for the reason why my app is not running on emulator (after apk build) and real device. It runs when I am in debug mode.
I have the logcat here, which is a long file, can anyone have a look and see what I miss?
Here is the file: logcat file

A: Read through the logCat. Seems this is the caused of the error.
Caused by: com.google.android.apps.gsa.shared.exception.GsaIOException: Error
code: 393238

Check this out and see if it helps. related Thread


text:
Q: How do you pass parameters which are not associated with a serializer field in Django Rest Framework? I have a form with fields which are not associated with a model.  I assume to implement the equivalent using a REST API (django-rest-framework), I would have to pass those additional fields, which are not associated with a Serializer?  How do I do that?
Let's say the additional field is number_of_pages.  I use that for some calculation.  How do I allow that to be passed in my REST call?

A: if you are using ModelSerializer from DjangoRestFramework, just add a field.
by default only model fields are added, but nothing limits you to add more, the only thing that may be problematic (but I've not tested it) - you may have too many fields while creating or updating model - in such a case, you will need to remove those fields in create() and update() methods before calling save().
class MyModelSerializer(serializers.ModelSerializer):
    number_of_pages = fields.IntegerField()

    # this I'm not sure if needed
    def create(self, validated_data):
        validated_data.pop('number_of_pages')
        return super(MyModelSerializer, self).create(validated_data)

    def update(self,instance, validated_data):
        validated_data.pop('number_of_pages')
        return super(MyModelSerializer, self).update(instance, validated_data)
    # end

    class Meta:
        fields = ('mymodelfield_1', 'mymodelfield_2', 'number_of_pages')
        model = MyModel

A: If, you are using django-rest-framework, then you can use SerializerMethodField() to pass additional fields in Api. Below I give an example.
class UserGroupSerializer(serializers.ModelSerializer):
"""
    This Serializer pass additionl field count. by using SerializerMethodField()
"""
count = serializers.SerializerMethodField()

class Meta:
    model = UserGroup

def get_count(self,obj):
    """return length of group"""
    return Groupmember.objects.filter(user_group=obj.id).count()

and use
serializer_class = UserGroupSerializer

in view.
I think it can help you.
Thanks


text:
Q: Returning values in Java I'm having some trouble understanding pretty basic Java code, I can't figure out how in the end of compiling x=2. Because through my logic it should be 4. The code itself:
public class eksami_harjutused {

public static int x=2;
   public static int y=2;

   public static void main(String[] args) {
     foo(bar(foo(x)));
     System.out.println("main x,y: "+x+" "+y);
   }

   public static int foo(int x) {
     x++;
     y++;
     System.out.println("foo x,y: "+x+" "+y);
     return x;
   }

   public static int bar(int x) {
     int z=0, y=10, u=0;
     --y;
     for(y=1; y<(x*x); y++) {
       for(z=1; z<x; z++) {
         u++;
       }
     }
     System.out.println("bar x,y: "+x+" "+y);
     return z;
   }
}

It prints out:
foo x,y: 3 3
bar x,y: 3 9
foo x,y: 4 4
main x,y: 2 4

A: Well, x is passed by value - since it is int type, so any modification to x in the callee functions will not affect x in the caller function. You can think of giving a copy of value in x to the callee, and the callee can do whatever with it without affecting the x in the scope of the caller.
Passing by value is done for all the primitive types in Java. And passing by reference is done for the rest (Object - note that array is Object).
Another thing is the effect of variable shadowing in foo and bar methods: x is declared as parameter to foo and bar, so the class member x is shadowed. Any access to x in foo and bar methods will refer to the argument passed in, not the class member x.
The value of x printed in the main method is from the class member x, which is never touched during the execution of the program.
In contrast, you can see the variable y modified twice in 2 calls to the foo method, since y in foo method will refer to the class member y. The y in bar method, however, refer to the local variable y declared in the bar method.

A: Because int is passed by value, you would not expect x to be incremented in foo(). You can try org.apache.commons.lang.mutable.MutableInt since Integer class is also immutable.


text:
Q: Is correcting several minor spelling mistakes considered a substantial edit? I was about to edit the answer Christian Kuetbach gave in: Does force close of a Java application cause Database connection leakage
The answer and its style were not bad, having only minor mistakes/slips, but in sum more than the needed six characters to make an edit. That would be:

*

*"withiin" (additional i)

*"ressources" (French spelling instead of English)

*twice a comma before "because"

*"Database" (capital letter in the middle of the sentence)

*"bonnection" (instead of connection)

I wouldn't have considered an edit for the first four points. But "bonnection" just leaps to the eye. So I don't know if I'm here just nitpicking or if those tiny one-letter corrections altogether justify an edit.
As Cody Gray pointed out in his answer, there isn't a really good answer to this question. So I'm rather asking for the gut feeling of the community how should I handle such (rather rare) cases in the future.

A: The six character limit is there to prevent trivial edits from unnecessarily taking up reviewers' time.  If you are changing enough legitimate errors to exceed 6 characters, then you have met that metric, and your suggested edit can therefore be thrown into the lion's den... er, review queue, for evaluation.
Fixing spelling and grammatical errors is a perfectly legitimate use of the edit system.  Remember, the audience for SE questions is the entire internet (or at least those folks interested in the subject matter), not just script kiddies who believe that txtspk is a legitimate form of the English language.  It is therefore  in our best interest to make questions and answers look professional.


text:
Q: I get the following error "E/Sync: java.text.ParseException: Unparseable date: "" (at offset 0)" I get the following error
 "E/Sync: java.text.ParseException: Unparseable date: "" (at offset 0)"
I have gone through many solutions in stack overflow. But unable to get the appropriate solution
Following is the code:
  public void execute() {
    if (mTableName.contentEquals("removed")) {
        String query = "Select * from removed";
        Cursor cursor = LODatabaseUtility.getInstance().cursorFromQuery(
                query);
        List<String> tableName = LODatabaseUtility.getInstance()
                .dataListfromCursor(cursor, "table_name");
        cursor = LODatabaseUtility.getInstance().cursorFromQuery(query);
        List<String> number = LODatabaseUtility.getInstance()
                .dataListfromCursor(cursor, "number");
        cursor = LODatabaseUtility.getInstance().cursorFromQuery(query);
        List<String> removedTimestamp = LODatabaseUtility.getInstance()
                .dataListfromCursor(cursor, "timestamp");
        if (number.size() == 0 || tableName.size() == 0) {
            cursor.close();
        }
        for (int i = 0; i < tableName.size(); ++i) {
            query = "Select timestamp from " + tableName.get(i) + " where "
                    + tableName.get(i) + "_id = " + number.get(i);
            cursor = LODatabaseUtility.getInstance().cursorFromQuery(query);
            String tableTimestamp = LODatabaseUtility.getInstance()
                    .dataStringfromCursor(cursor);
            try {

                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
                Date removedDate, tableDate;
                removedDate = df.parse(removedTimestamp.get(i));
                tableDate = df.parse(tableTimestamp);

                if (removedDate.compareTo(tableDate) > 0) {
                    query = "Delete from " + tableName.get(i) + " where "
                            + tableName.get(i) + "_id = " + number.get(i);
                    LODatabaseUtility.getInstance().getDatabase()
                            .execSQL(query);
                }
            } catch (ParseException e) {
                Log.e("Sync", "" + e);
                e.printStackTrace();
            }
        }
        cursor.close();
    }
    getSyncTimeFromServer(mTableName);
}

I get the error pointing to the following line of code:
tableDate = df.parse(tableTimestamp);

Only for a particular table the timestamp value is giving the error. For the rest of the tables that I have the timestamp value, the value is inserted properly. Any help would be useful


text:
Q: libxml constants are accessible, yet don't register as defined constants According to the PHP documentation, there are a number of constants defined when the libxml extension is enabled.
These are accessible in the code, so something like
var_dump(LIBXML_DTDLOAD);

will return a value of int(4) (no problem so far, that's exactly what I expect to see)
What puzzles me is if I do
echo var_dump(defined(LIBXML_DTDLOAD));

I get a bool(false) returned....
So how can I access the constant and see its value if it isn't (apparently) defined? Or why does defined() return a false for a constant that clearly is defined?
Demo

A: You didn't quote the constant name
var_dump(defined('LIBXML_DTDLOAD')); // bool(true)


text:
Q: Java Random seed I need to test out a Java program 20 times and need to set the random seed so that the tests can be repeated. If I were to set the initial seed as 0 and then increment by 1 at each run (i.e. 1,2,3 etc), would this method still ensure complete randomness, even though the seeds are not far apart?
Thank you

A: Any seed will provide the same level of randomness as any other seed for a standard PRNG like the one included with Java. So it's fine to use an incrementing seed for tests.
You might want to consider using a better random number generator though. The one included with Java yields noticeable repeating patterns if you render the values as an image (I can't find a reference offhand, but I recall it being apparent). I'd recommend the Mersenne Twister (there are Java versions) as an alternative that's fast and has a very long period so you won't easily see patterns.

A: If you use a seed of 0 the sequence of random numbers will be repeatable from that point.  You would only need to use a different random seed if you wanted a different sequence.  i.e. you should be able to set the seed once per test.

A: Why not just use the current time as the seed? ie, System.currentTimeMillis() ?

A: Do you need a number or a string? I use  UUID.randomUUID().toString() to get a UUID for my tests when I need strings, but if you need a number then you can use System.nanoTime().


text:
Q: How do I use the additional line breakpoint markers in Chrome Dev Tools? I have the following line selected for a breakpoint within Chrome Dev Tools

I don't know what the additional markers mean, nor do I know how to use them.
Do these only appear for multiple arrow functions on the same line? Is it possible to stop the code's execution on these markers? If so, how?
Any help is appreciated!

A: In javascript you're able to just run everything on one line, as long as each line is separated by a ; (wherever a ; would typically be used that is).
What chrome is doing here is it's showing that you can breakpoint at those "lines" as well, all you have to do is click on the indicators to enable them.
They will appear anywhere as long as it's something that could be considered its own line.


text:
Q: How to view/edit extended properties of SQL Table in SharePoint 2010
Possible Duplicate:
 Edit SQL Extended Properties in SharePoint 2010

Hi everyone,
I know how to view/edit table data from an external SQL (non SharePoint) database from my SharePoint 2010 web front end.
However, I also want to view/edit the extended properties (metadata) as well.
How can I do this?
Thanks!

A: You don't make clear if you are wanting to access a SharePoint Database (not supported as NLV say) or a.n.other database via SharePoint.
I am assuming the latter.
There are lots of table viewer/editor web parts but I don't know of any that let you work with metadata so you're probably going to have to develop your own - this guide and this one are for a viewer but should give you a head start.


text:
Q: water-damaged 3DS, some buttons are now non-functional, any ideas? so about 3 months ago I got my Nintendo 3DS wet. I tore it down, cleaned it up with isopropyl alcohol (of highest possible purity) and let it dry off.
unfortunately for me, there are some buttons that are non-functional, these are HOME, SELECT, X. Y works with some input lag. as the PCB is designed, well, SMD way I can't figure out how I could possibly repair the device so it would work as intended. what's interesting and probably obvious, everytime after I clean the PCB with isopropyl alcohol, these buttons work but for a short period of time, then it's the same - they simply don't work. my guess is that isopropyl alcohol improves the conductance of (as I assume) rusty circut paths. I could kind of re-solder the paths by using high temperature, but I've got no idea what is the MAXIMUM temperature I could use for doing that (and that's because I don't know exact parameters of SMD elements that are put on the circuit board, e.g. maximum temperature that cap can be exposed to etc.).
so, have you got ANY knowledge in this field, or maybe any other ideas or experience in this field?

A: My success on keyboards used liberal (half bottle) amounts of isoprop with drainage until solvent flux contaminants are dissolved and drained then vaccum & blow dry for 24hr ( or filtered compressed air )


text:
Q: BotFramework: Can you branch off to several possible dialogs from the mainDialog? I'm making a multi dialog chatbot with the MS Bot framework in c# and visual studio.
I have a main dialog file that should branch off to two possible further dialog files depending on what the user enters.

However I can't seem to be able to branch off successfully to both dialogs and now I'm doubting whether it's possible?
Here is my code , note that I use the BeginDialogAsync Method to switch between files. It works for the first dialog (vpn), but not the second (sauvegarde).
I am thinking it is because you have to go from one dialog to another and cannot do multiple branches from one class? I can't find any explanation in the documentation.
private async Task<DialogTurnResult> MiddleStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
{
    if (((string)stepContext.Result).ToLower().Contains("vpn"))
    {
        await stepContext.Context.SendActivityAsync(MessageFactory.Text($"Ah d'accord", InputHints.ExpectingInput)); //tr: oh ok

        await stepContext.Context.SendActivityAsync(MessageFactory.Text($"{(string)stepContext.Result} ? Il me semble que votre problème est lié a votre vpn..."), cancellationToken); // it seems your problem is linked with your vpn

        await stepContext.Context.SendActivityAsync(MessageFactory.Text($"Vous n'arrivez pas à vous connecter à distance? Je vais vous poser quelques questions afin de mieux vous aider à résoudre ce problème."), cancellationToken); // tr: i will ask you some questions
        return await stepContext.BeginDialogAsync((nameof(VPNDialog)), null, cancellationToken);

    }
    else if (((string)stepContext.Result).ToLower().Contains("sauvegard"))
    {
        await stepContext.Context.SendActivityAsync(MessageFactory.Text($"{(string)stepContext.Result} ? Il me semble que votre problème est lié a la sauvegarde de vos données..."), cancellationToken); // oh it seems your problem is to do with saving your data

        return await stepContext.BeginDialogAsync((nameof(SauvegardeDialog)), null, cancellationToken);
    }
    else
    {
        await stepContext.Context.SendActivityAsync(MessageFactory.Text($"Je ne crois pas pouvoir règler ce problème, entrer n'importe quoi pour revenir au menu principale où vous pourriez reformulez votre demande. ", InputHints.ExpectingInput)); //I don't think I can solve your problem sorry
        return await stepContext.CancelAllDialogsAsync(cancellationToken);
    }
}

I have also added the dialogs like so at the top of the main dialog class
AddDialog(new SauvegardeDialog(userState));
AddDialog(new VPNDialog(userState));

Is there some little part that I'm missing somewhere??
here are some sample conversations:
Success:

Fail:

I would appreciate any help! thanks in advance!

A: It worked after I changed the namespace in the SauvgardeDialog file from
namespace MultiTurnPromptDialog.Dialogs

to
namespace Microsoft.Dialogs

I don't really understand why


text:
Q: How to get a custom image content type to show up in the Ephox editor? Using Percussion CM System, I have a custom content type for images, actually using the PSOImageEditor imedImage type.  How do I get Images of that type to show up in the Content Browser selection list when users click the insert CMS Image icon in Edit Live?  I've scanned through the docs and config files but nothing is jumping out at me.

A: You need to edit the sys_inline_image slot in workbench under Assembly Design and add the content type/template pair you want to add.
Most slots you are adding a snippet template as the allowed template but for sys_inline_link and sys_inline_variant you add the binary template(s),  this is because the system just generates the link to the item based on its published location scheme for these slots.
You can add more than one template for the same type if you have more than one image field on the type you may have a binary template for each.


text:
Q: Why object changes into proxy object in vue? I have have object problem is when I assign object to data property it converts into proxy object .
Here is what I am doing
 data() {
    return {
      msg: "",
      notifications: {},

    };
  },
  this.notifications =  TokenService.getUserInfo().unread_notifications;

Thats how I am receiving object
Proxy {0: {…}, 1: {…}, 2: {…}, 3: {…}, 4: {…}}
[[Handler]]: Object
[[Target]]: Array(5)
[[IsRevoked]]: false

What is the reason?

A: Reason is Vue 3 is using ES6 Proxy to make an objects reactive. You can study how that works in depth or you can just ignore it and work with objects as normal (Proxy is transparent wrapper and works everywhere as your original object)


text:
Q: Call controller methods inside View I have a View and want to execute some controller methods inside of it.

First method adds options inside select tag;
Second method bound to the button executes process i need;

I tried a lot of options from google, but it does not let me even try them. It shows me Unterminated string literal. no matter what i try to do with it.
how looks the error
Simply it looks like this:
<!DOCTYPE html>

    <title>Choose language to upload .html files</title>

    <form">

Choose language to upload .html files

        <select>
            /*After page is loaded, method from a controller will add options*/
        </select>

    <button>Start</button> /*Another method from a controller will be bound to this button*/
    </form>

A: Rename your file extension from .html to .cshtml. Currently, what you're seeing is VS Code's JavaScript error for a regular html file. Once you change the file extension it will recognize that your file is a Razor view.
Another option is to set the language based settings of the file in VS Code to the appropriate language. You can do this by opening the pub.cshtml_virtual.html file and the language setting will be at the bottom right of VS Code.
Currently, the pub.cshtml_virtual.html file will be set to HTML:

click HTML to change it to aspnetcorerazor (might need an extension to get the option):

A: Okay, so you need to understand the MVC architecture and how you want to implement different scenarios based on your requirement. Each View is rendered by its associated Controller. You can either a create a View without an associated Model and handle all your data on the View using front-end scripting technqiues such as JavaScript and AJAX.
Another technique which I prefer is Model-View bindining in which you would design the appropriate Model for your View and bind them using the Controller. Now based on your requirement, you can prepopulate your Model in your Controller and render your View with those values. Or you could use a strongly Model typed binding on your View to set your form data and then send it to associated method for processing using Form tag. Please note that this method will process your data and then return the appropriate View.
Now moving on to your case, the error that is being displayed is because of incorrect string literal in your action onclick. You may use this on your button event:
onclick="@("window.location.href='" + @Url.Action("Start", "Default") + "'");"

On the button click, you would be taken to Start action method of the Default controller.


text:
Q: how is it that $\int_0^x 2\pi r\ dr$ is equal to the area of a circle I'm studying calculus and I'm having some basic questions, this one is regarding the area of a circle. we know, from some guy, that the circumference of a circle is $2 \pi r$ and the area can be seen as the sum of all the circumferences from $0$ to $r$ which is the same as the integral, which leads us to $\pi r^2$.
my question is how is it that $$\int_0^R 2\pi r\ dr = \text{Area}\ \ ?$$

A: Here is a proof with few words. Note that the line is the graph of $y=t$ with $t$ being the horizontal axis and that the integral
$$\int_0^x t\,dt$$ represents the area of a triangle with both base and height equal to $x$.
But for more general functions, one needs the Riemann Sum as indicated by GeorgSaliba.

A: $$\int_0^R xdx\ne\sum_0^Ri$$
You are adding small areas of circumference equal to $2\pi r$  and thickness $\Delta r$ over a span of $r=0$ to $R$. So you have to partition this interval into $n$ subdivisions, each subdivision is $R/n$ thick. This means that each radius to be added can be expressed like this $$r={i\times R\over n}\qquad i=0,1,2,\dots,n$$and $$\Delta r=\frac Rn$$
When $n$ is "infinitely large" you get an "infinitely precise" sum, which is then: $$\int_0^R2\pi rdr=\lim_{n\rightarrow\infty}2\pi\frac Rn\sum_0^n\frac{Ri}{n}=\lim_{n\rightarrow\infty}2\pi\frac{R^2}{n^2}\frac {n(n+1)}{2}=\lim_{n\rightarrow\infty}2\pi\frac{R^2}{n^2}\frac {n\times n}{2}=\pi R^2$$
This is called a Riemann Sum


text:
Q: How do I add an action or outlet to a class in Xcode 4.3.1? I'm following a slightly outdated the guide from cocoalab.com (Become An Xcoder) to learn the basics of cocoa, but I'm stuck on one of the instructions.
On page 45 (section 08:9) in the section titled "Creating connections", it tells me to select the instance of my new class, and from the identity inspector, to add two actions and an outlet.
I'm using Xcode 4.3.1 which is obviously a bit different to the version that this tutorial was written for, but I can't figure out how to do the equivalent in this newer version.
Can anyone please help by giving me step by step instructions of how to add these to my object.

A: Open the Assistant Editor (red rectangle in the screenshot). Then, from Interface Builder, press the ctrl key and drag the mouse from the button (or an other control in you view) to the .h file.

You will be prompted to choose the type of the connection to create as in the screenshot below:

A: I would suggest to follow the nice and easy tutorial on developer.apple.com - search for "Your First iOS App".
This explains how to add an outlet, and an action - all using the latest version of XCode. Won't take you long to do, but will get you up to speed with all the features you need.
Hope this helps :)


text:
Q: Returning json array/object of nested data I have a postgres database of jobs, locations and countries, where jobs <=> locations is many-to-many, jobs <=> countries is many-to-many, and locations <= countries is one-to-many. A job can belong to a country through 2 different paths:
jobs <=> jobs_locations <=> locations <=> countries
jobs <=> jobs_countries <=> countries

This is my current query:
select
  jobs.*,
  COALESCE(json_agg(locations) filter (where locations.id IS NOT NULL), '[]') as locations,
  COALESCE(json_agg(countries) filter (where countries.id IS NOT NULL), '[]') as countries
from jobs
left join jobs_locations on jobs.id = jobs_locations.job_id
left join locations on jobs_locations.location_id = locations.id
left join countries loc_country on locations.country_id = loc_country.id
left join jobs_countries on jobs.id = jobs_countries.job_id
left join countries on jobs_countries.country_id = countries.id
where loc_country.id = 2 OR countries.id = 2
group by jobs.id;

I'm currently getting the data in this format:
{
  id: 1,
  ...
  locations: [
    {
      id: 10,
      name: "Paris",
      country_id: 100
    }
  ]
}

I want to get a job in this format:
{
  id: 1,
  ...
  locations: [
    {
      id: 10,
      name: "Paris",
      country: {
        id: 100,
        name: "France"
      }
    }
  ]
}

How can I do this? It seems like a simple query but I've been trying for hours to get this data in the right format, what am I missing here?

A: Many ways lead to Rome.
This returns all jobs, and only appends locations and/or countries for country_id = 2. Should be among the fastest ways:
SELECT j.*
     , coalesce(l.locations, '[]') AS locations
     , coalesce(c.countries, '[]') AS countries
FROM   jobs j
LEFT   JOIN (
   SELECT jl.job_id AS id
        , jsonb_agg(l) - 'country_id' AS locations  -- !!!
   FROM   jobs_locations jl
   JOIN  (
      SELECT l.*, to_jsonb(c) AS country            -- subquery to prepare row !!!
      FROM   locations l
      JOIN   countries c ON c.id = l.country_id
      WHERE  l.country_id = 2
      ) l ON l.id = jl.location_id
   GROUP  BY 1
   ) l USING (id)
LEFT   JOIN (
   SELECT jc.job_id AS id
        , jsonb_agg(c) AS countries
   FROM   jobs_countries jc
   JOIN   countries c ON c.id = jc.country_id
   WHERE  jc.country_id = 2
   GROUP  BY 1
   ) c USING (id);

First of, your original seems incorrect to begin with. Multiple uncorrelated LEFT JOIN instances result in multiplication of rows. See:

*

*Two SQL LEFT JOINS produce incorrect result
And then you add a WHERE condition on "right" tables, which counteracts all the LEFT JOIN clauses ... See:

*

*Postgres LEFT JOIN with WHERE condition
I fixed that before adding an answer to your question. Note how I use jsonb instead of json to allow convenient operators. Details for that solution:

*

*Return multiple columns of the same row as JSON array of objects

*How to select sub-object with given keys from JSONB?
One side-effect: keys appear in jsonb-specific sort order.
Only get jobs with countries and/or locations
At least one of the of the joins must find a row. (That's how I understand your comment.)
You could simply append your (adapted) original WHERE clause in the outer SELECT:
...
WHERE 2 IN (l.id, c.id);

But try this more elegant rewrite with a FULL JOIN between locations and countries, followed by a JOIN to jobs. If the subqueries are selective (like it seems), that should be (much) faster because it can filter jobs right away, during the join on the PK column id:
SELECT j.*
     , coalesce(l.locations, '[]') AS locations
     , coalesce(c.countries, '[]') AS countries
FROM  (
   SELECT jl.job_id AS id
        , jsonb_agg(l) - 'country_id' AS locations
   FROM   jobs_locations jl
   JOIN  (
      SELECT l.*, to_jsonb(c) AS country
      FROM   locations l
      JOIN   countries c ON c.id = l.country_id
      WHERE  l.country_id = 2
      ) l ON l.id = jl.location_id
   GROUP  BY 1
   ) l
FULL   JOIN (
   SELECT jc.job_id AS id
        , jsonb_agg(c) AS countries
   FROM   jobs_countries jc
   JOIN   countries c ON c.id = jc.country_id
   WHERE  jc.country_id = 2
   GROUP  BY 1
   ) c USING (id)
JOIN   jobs j USING (id);

You should be comfortable with all join clauses and NULL handling to understand subtleties. In particular, matching column aliases (id) and the USING clause in the FULL [OUTER] JOIN are essential to produce the single, combined id column for the subsequent [INNER] JOIN. This is one of the rare cases where the USING clause is essential.
(Well, we could spell out JOIN jobs j ON j.id = COALESCE(l.id, c.id) but that's far less elegant.)


text:
Q: How to draw a titration curve? I'm trying to draw acid-base titration curve as it's shown here in this picture:

I've drawn the curve, but I didn't know how to draw the tangents and \frac{\dd pH}{\dd V_b}, and here's my attempt to draw the curve :
\begin{center}
\begin{tikzpicture}[ultra thick,scale=1]
\begin{axis}[ axis x line=bottom,axis y line = left, smooth,  minor  tick num=4,ymin=0,ymax=12,ultra thick, xlabel={$V_{B}$ ml},ylabel={pH }]
\addplot[smooth, black] coordinates {
(0,2) (2,2.1) (4,2.2) (6,2.3) (8,2.4) (10,2.5) (12,2.6) (14,2.7) (16,2.9) (18,3.3) (18.5,3.45)(19,3.6)
(19.5,4.2)(20,7)(20.5,9.3)(21,10)(21.5,10.3)(22,10.5)(24,10.9)(26,11)(28,11.1)(30,11.2)};
\end{axis}
\end{tikzpicture}
\end{center}

Is there any method to draw the two tangents, the bisector, and also the function g(V_b)?

A: Just in case you want a smoother titration curve, you can check my answer using tikz. An angle of 35° works well as tangent.
\documentclass[border=5pt]{standalone}

\usepackage{tikz}
\usetikzlibrary{intersections}

\tikzset{%
    every pin/.style={font=\small, pin distance=5mm, inner sep=0pt},
    every pin edge/.style={draw=black, line width=0.5*\pgflinewidth},
    small dot/.style={fill=black, circle, scale=0.25}
}

\begin{document}
    \begin{tikzpicture}

%draw grid and axix with ticks

        \draw[help lines, gray!25!white] (0,0) grid[step=0.5] (15,6);
        \draw[-stealth] (0,0) -- (0,6.5) node[above] {pH};
        \draw[-stealth] (0,0) -- (15.5,0) node[right] {$\mathrm{V_B~/~mL}$};

        \foreach [evaluate=\i as \n using (\i)*2] \i in {0,2.5,5,...,15} {
            \draw (\i,0) -- (\i,-0.125) node[below] {\n};
        }
        \foreach [evaluate=\i as \n using (\i)*2] \i in {0,1,...,6} {
            \draw (0,\i) -- (-0.125,\i) node[left] {\n};
        }

% draw titration curve

%       \draw [gray!50]  (0,1) -- (2,1.5) -- (8,2) -- (9,5) -- (15,6);
        \draw [black, name path=a] plot [smooth, tension=0.5] coordinates {(0,1) (2,1.5) (8,2) (9,5) (15,6)};

% draw second function g(VB)

%       \draw [gray!50]  (7,0) -- (8.25,0.1) -- (8.5,1) -- (8.75,0.1) -- (10,0);
        \draw [black, name path=b] plot [smooth, tension=0.5] coordinates {(7,0) (8.25,0.1) (8.5,1) (8.75,0.1) (10,0)};

% draw linear funktion with 35° slope which points through (9,5); (8.5,3.5); (8,2)

        \draw[domain=6:10, smooth, variable=\x] plot ({\x, \x*0.47381472+0.735667516});
        \draw[domain=6.5:10.5, smooth, variable=\x] plot ({\x, \x*0.47381472-0.527425124});
        \draw[domain=7:11, smooth, variable=\x] plot ({\x, \x*0.47381472-1.790517763});

% draw linear function perpendicular to the upper ones (m1*m2=-1) which penetrates (9.75 and y value of first liea function)

        \draw[domain=9.75:10.73, smooth, variable=\x] plot ({\x, \x*-2.1105296+25.9330248});

% draw equiv point

        \draw[densely dashed] (0,3.5) node[left] {$\mathrm{{pH}_{equiv}}$} -- (8.5,3.5) node[above left] {$\mathrm{E}$} -- (8.5,0) node[below] {$\mathrm{V_{equiv}}$};

% label functions

        \path[name path=c] (0,5) -- (15,5);
        \path[name intersections={of=c and a},];
        \coordinate (P1)  at (intersection-1);

        \path[name path=d] (0,0.75) -- (15,0.75);
        \path[name intersections={of=d and b},];
        \coordinate (P2)  at (intersection-2);

        \node[small dot, pin={above left:$\mathrm{pH=f(V_B)}$},] at (P1) {};
        \node[small dot, pin={above right:$\mathrm{\frac{d(pH)}{d(V_B)}=g(V_B)}$},] at (P2) {};
    \end{tikzpicture}
\end{document}

A: A straightforward solution using tkz-euclide.

I decided to draw on the left, since your the curvation is really close to the right of the picture. You can adapt the code to any tangent, because the points coordinates are on them.
\documentclass[tikz,border=3.14mm]{standalone}
\usepackage{pgfplots,tkz-euclide}

\begin{document}
    \begin{tikzpicture}[ultra thick,scale=1]

        \begin{axis}[ axis x line=bottom,axis y line = left, smooth,  minor  tick num=4,ymin=0,ymax=12,ultra thick, xlabel={$V_{B}$ ml},ylabel={pH }]
        \addplot[smooth, black] coordinates {
        (0,2) (2,2.1) (4,2.2) (6,2.3) (8,2.4) (10,2.5) (12,2.6) (14,2.7) (16,2.9) (18,3.3) (18.5,3.45)(19,3.6)
        (19.5,4.2)(20,7)(20.5,9.3)(21,10)(21.5,10.3)(22,10.5)(24,10.9)(26,11)(28,11.1)(30,11.2)};

        % Tangent lines
        \addplot[domain=5:27, samples=100,thin]{0.2*x+6.2} coordinate[pos=0.1] (A) coordinate[pos=0.9] (A');
        \addplot[domain=10:30, samples=100,thin]{0.2*x-0.4} coordinate[pos=0.1] (C) coordinate[pos=0.9] (D);

        \end{axis}

        \begin{scope}[line width=.75pt]

            \tkzDefLine[perpendicular=through A](D,C) \tkzGetPoint{A'}
            \tkzInterLL(A,A')(C,D) \tkzGetPoint{B}
            \tkzDefMidPoint(A,B)\tkzGetPoint{M}
            \tkzDefLine[parallel=through M](C,D) \tkzGetPoint{N}
            \tkzDrawLine[add=0.1 and 0.1](M,N)
            \tkzDrawSegment(A,B)
            \tkzMarkSegments[mark=s||](A,M M,B)

            \path (M) -- (N) node[pos=0.65] (e) {};
            \pgfgetlastxy{\xe}{\ye}
            \draw[dashed] (\xe,0) |- (0,\ye);
            \node[above left] at (e) {E};

        \end{scope}

    \end{tikzpicture}
\end{document}


text:
Q: JUNK Character in text pad for foreign language in HADOOP mapreduce I have and application where i have to read HBase and write into files in text format .
Everything work fine but requirement from the client is that they need to have files in UTF-8-BOM encoding format .
I have not mentioned any encoding format explicitly and by default it comes as UTF-8 format .
Is there anyway to to write into the files in UTF-8-BOM format .
Please consider that i am doing all these in mapreduce .
I have tried with below changes in the driver code but then also it comes out as UTF-8 format .
hbaseConf.set("mapreduce.child.java.opts", "-Xmx6553m -Dfile.encoding=UTF-8-BOM");

Thanks in advance ..

A: No extra encoding is required to mention in the config .
I have solved it by Appending "\uFEFF" in the first row and it worked fine for me .No extra character in the output file also .All good now


text:
Q: How do I check how many wisps are left in an area? I would like to check which areas I still have uncollected wisps in. I know the game tells me how many wisps are left after I collect a wisp, but I can't remember which areas I've cleared.
How do I check how many wisps are left in an area?

A: Go to Jubilife Village and talk to Vessa, the child who gave you the Wisp collecting quest. Select "How many wisps are left?" and she will say how many wisps are left in each area.


text:
Q: Receiving full date time in node API instead of receiving date only I am trying to get only date pate part from timestamp value using DATE() in MySQL its showing result correct in MySQL but in node js its showing full-time stamp instead of date.
Example : -
SELECT DATE("2020-04-12T18:30:00.000Z");

Generating 2020-04-12 in MySQL but in node js while fetching through my own API it's giving "2020-04-12T18:30:00.000Z" this.
Help me to Solve this.

A: You can use in the query SQL this:
SELECT ...,(DATE_FORMAT("2017-06-15", "%Y-%m-%d") as finalDate) FROM ...

And now in your API, when you call to MySQL with the previous query you should have 2017-06-15 in finalDate. The type DATE in MySQL is a Date Object, so if you want only date in string, you need to cast it in MySQL with the previous code or in your API with parsing date to string with methods or Date


text:
Q: $\frac{1}{n}-\sin(\frac{1}{n})\sim\frac{1}{6n^3}$? I saw this approximation posted in a different thread
Convergence of the series $\sum_{n=1}^{\infty}((1/n)-\sin(1/n))$..?.
I am very curious as to how one would come up with this approximation. My intuition tells me it has something to do with power series, but I cannot find a way to show this. I would like to learn more about how to get this result so I can apply it to the other trigonometric functions.

A: By Taylor series, you know that
$$\sin(x) = \sum_{n=0}^m (-1)^{n}\frac{x^{2n+1}}{(2n+1)!} +\mathtt o(x^{2m+2})$$
as $x \to 0$. The notation $\mathtt o(x^{2m+2})$ means that there exists a function $q$ that is infinitesimal as $x \to 0$ such that
$$\sin(x) = S_m(x) + x^{2m+2}q(x), $$
where $S_m(x)$ is the $(2m+1)$-th (and $(2m+2)$-th) Taylor polynomial of $\sin$, which we wrote in the first equation.
The sequence $1/n$ converges to $0$, so this is the expansion you are interested in; we get, for $m = 1$,
$$\sin\left(\frac 1 n \right) = \frac 1 n - \frac{1}{3! n^3} + \mathtt o\left(\frac 1 {n^4}\right)$$
so
$$\frac 1 n - \sin\left(\frac 1 n \right) = \frac{1}{3! n^3} + \mathtt o\left(\frac 1 {n^4}\right), $$
as we wanted.


text:
Q: Why do different methods for solving Xc=y in python give different solution when they should not? I was trying to solve a linear system Xc=y that was square. The methods I know to solve this are:

*

*using inverse c=<X^-1,y>

*using Gaussian elimination

*using the pseudo-inverse

It seems as far as I can tell that these don't match what I thought would be the ground truth.

*

*First generate the truth parameters by fitting a polynomial of degree 30 to a cosine with frequency 5. So I have y_truth = X*c_truth.

*Then I check if the above three methods match the truth

I tried it but the methods don't seem to match and I don't see why that should be the case.
I produced fully runnable reproducible code:
import numpy as np
from sklearn.preprocessing import PolynomialFeatures

## some parameters
degree_target = 25
N_train = degree_target+1
lb,ub = -2000,2000
x = np.linspace(lb,ub,N_train)
## generate target polynomial model
freq_cos = 5
y_cos = np.cos(2*np.pi*freq_cos*x)
c_polyfit = np.polyfit(x,y_cos,degree_target)[::-1] ## needs to me reverse to get highest power last
## generate kernel matrix
poly_feat = PolynomialFeatures(degree=degree_target)
K = poly_feat.fit_transform(x.reshape(N_train,1)) # generates degree 0 first
## get target samples of the function
y = np.dot(K,c_polyfit)
## get pinv approximation of c_polyfit
c_pinv = np.dot( np.linalg.pinv(K), y)
## get Gaussian-Elminiation approximation of c_polyfit
c_GE = np.linalg.solve(K,y)
## get inverse matrix approximation of c_polyfit
i = np.linalg.inv(K)
c_mdl_i = np.dot(i,y)
## check rank to see if its truly invertible
print('rank(K) = {}'.format( np.linalg.matrix_rank(K) ))
## comapre parameters
print('--c_polyfit')
print('||c_polyfit-c_GE||^2 = {}'.format( np.linalg.norm(c_polyfit-c_GE) ))
print('||c_polyfit-c_pinv||^2 = {}'.format( np.linalg.norm(c_polyfit-c_pinv) ))
print('||c_polyfit-c_mdl_i||^2 = {}'.format( np.linalg.norm(c_polyfit-c_mdl_i) ))
print('||c_polyfit-c_polyfit||^2 = {}'.format( np.linalg.norm(c_polyfit-c_polyfit) ))
##
print('--c_GE')
print('||c_GE-c_GE||^2 = {}'.format( np.linalg.norm(c_GE-c_GE) ))
print('||c_GE-c_pinv||^2 = {}'.format( np.linalg.norm(c_GE-c_pinv) ))
print('||c_GE-c_mdl_i||^2 = {}'.format( np.linalg.norm(c_GE-c_mdl_i) ))
print('||c_GE-c_polyfit||^2 = {}'.format( np.linalg.norm(c_GE-c_polyfit) ))
##
print('--c_pinv')
print('||c_pinv-c_GE||^2 = {}'.format( np.linalg.norm(c_pinv-c_GE) ))
print('||c_pinv-c_pinv||^2 = {}'.format( np.linalg.norm(c_pinv-c_pinv) ))
print('||c_pinv-c_mdl_i||^2 = {}'.format( np.linalg.norm(c_pinv-c_mdl_i) ))
print('||c_pinv-c_polyfit||^2 = {}'.format( np.linalg.norm(c_pinv-c_polyfit) ))
##
print('--c_mdl_i')
print('||c_mdl_i-c_GE||^2 = {}'.format( np.linalg.norm(c_mdl_i-c_GE) ))
print('||c_mdl_i-c_pinv||^2 = {}'.format( np.linalg.norm(c_mdl_i-c_pinv) ))
print('||c_mdl_i-c_mdl_i||^2 = {}'.format( np.linalg.norm(c_mdl_i-c_mdl_i) ))
print('||c_mdl_i-c_polyfit||^2 = {}'.format( np.linalg.norm(c_mdl_i-c_polyfit) ))

and I get the result:
rank(K) = 4
--c_polyfit
||c_polyfit-c_GE||^2 = 4.44089220304006e-16
||c_polyfit-c_pinv||^2 = 1.000000000000001
||c_polyfit-c_mdl_i||^2 = 1.1316233165135605e-06
||c_polyfit-c_polyfit||^2 = 0.0
--c_GE
||c_GE-c_GE||^2 = 0.0
||c_GE-c_pinv||^2 = 1.0000000000000007
||c_GE-c_mdl_i||^2 = 1.1316233160694804e-06
||c_GE-c_polyfit||^2 = 4.44089220304006e-16
--c_pinv
||c_pinv-c_GE||^2 = 1.0000000000000007
||c_pinv-c_pinv||^2 = 0.0
||c_pinv-c_mdl_i||^2 = 0.9999988683985006
||c_pinv-c_polyfit||^2 = 1.000000000000001
--c_mdl_i
||c_mdl_i-c_GE||^2 = 1.1316233160694804e-06
||c_mdl_i-c_pinv||^2 = 0.9999988683985006
||c_mdl_i-c_mdl_i||^2 = 0.0
||c_mdl_i-c_polyfit||^2 = 1.1316233165135605e-06

Why is it? Is it a machine precision thing? Or is it because the error accumulates (a lot) when degree is large (greater than 1)? Honestly I don't know but all those hypothesis seem silly to me. If anyone can spot my mistake, feel free to point it out. Otherwise, I might not understand linear algebra or something...which is a lot more worrying.
Also if I can get suggestions for this to work, it would be highly appreciated. Do I:

*

*increase the size of the interval to no be less than 1 (in magnitude)?

*what is the largest polynomial size degree I may use?

*different language...? Or increase the precision?

any suggestions are appreciated!

A: The issue is floating point accuracy. You're raising numbers between zero and one to the 30th power, then adding them together. If you were doing this with infinite precision arithmetic, the methods would recover the inputs. With floating point arithmetic, precision loss means you can't.


text:
Q: connecting another db2 instance in same php file in BlueMix I connect to a db using this code
//parse VCAP_SERVICES Environment variable
$vcap_services = $_ENV["VCAP_SERVICES"];
$services_json = json_decode($vcap_services,true);
$sqldb = $services_json["sqldb"];
if (empty($sqldb)) {
    echo "No sqldb service instance is bound. Please bind a sqldb service instance";
    return;
}

//Get Credentials object (db,host,port,username,password)
$sqldb_config = $services_json["sqldb"][0]["credentials"];

$conn_string = "DRIVER={IBM DB2 ODBC DRIVER};DATABASE=".
   $sqldb_config["db"].
   ";HOSTNAME=".
   $sqldb_config["host"].
   ";PORT=".
   $sqldb_config["port"].
   ";PROTOCOL=TCPIP;UID=".
   $sqldb_config["username"].
   ";PWD=".
   $sqldb_config["password"].
   ";";

then I do "my thing" and close the connection with
db2_close($conn);

then when I try to connect to another instance of the db2 db by using the same connection code but changing the middle argument in this line:
$sqldb_config = $services_json["sqldb"][0]["credentials"];

the connection does not work. The two parts of code work just fine separately. It's when I put the code in the same file in that order that it causes this error.

A: Once you've closed a connection you have to open a new one (using the code you're already using) in order to access to the DB again. It is correct to close the connection after each 'logic' group of queries.