text:
Q: Compare two values in a single column SQL Server I have a SQL Server database in which I ran a query that collects the data about two different tournamnets and the number of people enrolled in the tournament.  So for instance the output is:
Name of Tourney    People enrolled
Tourney 1 ----------- 7
Tourney 2 ----------- 8

After getting these two values, I want to be able to compare them and only show the information for the tournmanet that contains the highest number of people enrolled. Should all be in one query...how can I do this?

A: On MS SQL Server, this should do the trick:
select top 1 ...
from ...
where ...
order by "people enrolled" desc

This sorts your results DESC so that the row with the largest number of people enrolled is first. Then returns the TOP 1 record - that is, the first row, thus the row with the largest number of people enrolled.


text:
Q: What parts of an assembly does the strong name signing verify It is my understanding that strong name signing an assembly uses some kind of hash of the assembly contents, and signs it so that if the assembly is changed after the signing then it shouldn't work anymore. However I just created a small utility to add extra win32 resources to an app after its built, and as far as I can tell it doesn't cause the strong name signed assembly to stop functioning at all.
I created a small test app, which just outputs its assembly name, strong name signed it and then added extra icons to it. Below is the program:
class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("My name is " + Assembly.GetExecutingAssembly().GetName());
    }
}

After I modify the assembly I can still run it, and it prints out its assembly name with my public key token with no problems:
My name is TestApp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=cd4a03be895200fa

Now, my question is, does the strong name signing only check some parts of the assembly, i.e. does it not hash the win32 resources, or am I completely misunderstanding how strong name signing works? If my assembly has been changed after signing, shouldn't it stop working?

A:
A strong name consists of the assembly's identity—its simple text name, version number, and culture information (if provided)—plus a public key and a digital signature. It is generated from an assembly file (the file that contains the assembly manifest, which in turn contains the names and hashes of all the files that make up the assembly), using the corresponding private key.

From Strong Named Assemblies documentation
So if you sign your assembly with the same key and if you don't change its name, version number and culture it will be loaded without any problems.
Hashes are used to prevent the assembly file from being modified, so if you modify a compiled dll (using, let's say, HEX editor) it won't be loaded (as hash will not match).
But as soon as hashes match and the assembly has a correct signature - it has a green light.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I get a button element for a sliding navigation panel to rotate with HTML and CSS? Basically, I have an html page where I have set up a sliding panel when you click the square. How do I get the square to rotate 180 degrees when I click it? I can only manage to have the button trigger the div sliding or the the button spinning, but not both at the same time. I noticed it has something to do with how I'm placing the input tag. If it's inside the label, the button rotates but there is no effect on the panel. If it's outside of the label, pressing the square triggers the side panel. Been going at this all day but can't seem to figure it out. Ideally, I would have liked to get a arrow in place of the square but I wouldn't know where to start...
-sliding div:
https://codepen.io/yung_terminal/pen/oWrZZj
HTML:

 <input id="slide-sidebar" type="checkbox" role="button" />

CSS:
.sidebar {
background-color: white;
width: 300px;
position: absolute;
top: 0;
left: 0;
bottom: 0;
}
#navpan {
position: absolute;
right: 120px;
bottom: 740px;
}
.sidebar li{
color: black;
font-weight: bold;
font-size: 25px;
text-decoration: none;
list-style: none;
}
.content {
background-color: red;
position: absolute;
top: 0;
left: 190px;
right: 0;
bottom: 0;
-moz-transition: left 0.5s ease;
transition: left 0.5s ease;
}

input[type=checkbox] {
display: none;
}

input:checked ~ .content{
left: 0;
}

input:checked ~ label {
left: 0;
}

label {
z-index: 2;
position: absolute;
top: 50%;
left: 190px;
background-color: 0;
font-size:60px;
-moz-transition: left 0.5s ease;
transition: left 0.5s ease;
}

.tab {
width: 100px;
height: 100px;
background-color: white;
transition: all 0.75s 0.25s;
transform: rotate(0);
}

#slide-sidebar:checked + .tab{
transform: rotate(180deg);
}

A: I updated your code. Please check it. DEMO. I added onclick function to that box and created rotated class. Using css I rotate that box with 90degree.

$(document).ready(function() {
  $('#rotate').click(function(){
    $(this).toggleClass('rotated');
});
});
.rotated {
    -webkit-transform: rotate(90deg);
    -moz-transform: rotate(90deg);
    -o-transform: rotate(90deg);
    -ms-transform: rotate(90deg);
    transform: rotate(90deg);
}
.sidebar {
    background-color: white;
    width: 300px;
    position: absolute;
    top: 0;
    left: 0;
    bottom: 0;
}
#navpan {
  position: absolute;
  right: 120px;
  bottom: 740px;
}
.sidebar li{
    color: black;
    font-weight: bold;
    font-size: 25px;
    text-decoration: none;
    list-style: none;
}
.content {
    background-color: red;
    position: absolute;
    top: 0;
    left: 190px;
    right: 0;
    bottom: 0;
    -moz-transition: left 0.5s ease;
    transition: left 0.5s ease;
}
input[type=checkbox] {
   display: none;
}
input:checked ~ .content{
    left: 0;
}
input:checked ~ label {
    left: 0;
}
label {
    z-index: 2;
    position: absolute;
    top: 50%;
    left: 190px;
    background-color: 0;
    font-size:60px;
    -moz-transition: left 0.5s ease;
    transition: left 0.5s ease;
}
.tab {
    width: 100px;
    height: 100px;
    background-color: white;
    transition: all 0.75s 0.25s;
}
#slide-sidebar:checked + .tab{
  transform: rotate(180deg);
}

      <input id="slide-sidebar" type="checkbox" role="button" />

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Doloremque nulla accusamus illo a dolorum quo, maxime fuga ea nam quae ab deserunt quas distinctio culpa recusandae assumenda quisquam repellendus, perferendis!

A: You are close, but not quite there.
You need to change : #slide-sidebar:checked + .tab
To: #slide-sidebar:checked + label>.tab
In your initial selector, you are expecting .tab to be a sibling of the checkbox. The label is the sibling with .tab being a child of label.

.rotated {
    -webkit-transform: rotate(90deg);
    -moz-transform: rotate(90deg);
    -o-transform: rotate(90deg);
    -ms-transform: rotate(90deg);
    transform: rotate(90deg);
}
.sidebar {
    background-color: white;
    width: 300px;
    position: absolute;
    top: 0;
    left: 0;
    bottom: 0;
}
#navpan {
  position: absolute;
  right: 120px;
  bottom: 740px;
}
.sidebar li{
    color: black;
    font-weight: bold;
    font-size: 25px;
    text-decoration: none;
    list-style: none;
}
.content {
    background-color: red;
    position: absolute;
    top: 0;
    left: 190px;
    right: 0;
    bottom: 0;
    -moz-transition: left 0.5s ease;
    transition: left 0.5s ease;
}
input[type=checkbox] {
   display: none;
}
input:checked ~ .content{
    left: 0;
}
input:checked ~ label {
    left: 0;
}
label {
    z-index: 2;
    position: absolute;
    top: 50%;
    left: 190px;
    background-color: 0;
    font-size:60px;
    -moz-transition: left 0.5s ease;
    transition: left 0.5s ease;
}
.tab {
    width: 100px;
    height: 100px;
    background-color: white;
    transition: all 0.75s 0.25s;
}
#slide-sidebar:checked + label>.tab{
  transform: rotate(180deg);
}

      <input id="slide-sidebar" type="checkbox" role="button" />

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Doloremque nulla accusamus illo a dolorum quo, maxime fuga ea nam quae ab deserunt quas distinctio culpa recusandae assumenda quisquam repellendus, perferendis!

A: + denotes an immediate sibling, which .tab is not but label wrapping .tab is. So change
#slide-sidebar:checked + .tab{
   transform: rotate(180deg);
}

to
#slide-sidebar:checked + label .tab{
   transform: rotate(180deg);
}


text: Q: homology of finitely generated group The homology groups of every finite group are finite and those of $\mathbb{Z}^n$ with coefficients in $\mathbb{Z}$ are finitely generated. I was wondering whether for some finitely generated group there is a homology group $H^n(G,\mathbb{Z})$ for some $n\in\mathbb{N}$ which is not finitely generated. This of course can not take place for any group $G$ whose classifying space is compact as the homology groups will be finitely generated in this case.


text:
Q: ExpressJs - Getting Server Sub-routes to work with Angular factory svcs For easy maintenance, I would like to compartmentalize my server routes:
server.js (start app):
require('./routes/allRoutes')(app);

allRoutes.js:
module.exports = function(app){
  //don't I need to pass (app) below? This will not work as is
  var Group1 = require('../routes/Group1/groupRoutes')(app),
      Group2 = require('../routes/Group2/groupRoutes')(app);

  app.use('/group1', Group1);
  app.use('/group2', Group2);
}

groupRoutes.js: (in Group1 Folder)
module.exports = function(app){
  //don't I need to pass (app) below? This will not work as is
  var SubGroup1 = require('../routes/Group1/subGroup1Route')(app);
      .....
  app.use('/subgroup1', SubGroup1);
}

subGroup1Routes.js: (in Group1 Folder)
var FooCrtl = require('../../controllers/Group1/subGroup1/FooCtrl');

module.exports = function(app){
   app.get('/api/foo', FooCtrl.get);
   app.post('/api/foo', FooCtrl.post);
}

AngularJs FooSvcs:
....
   return {
        getFoo: function(){
            return $http({
                method: 'GET',

                url: '/group1/subgroup1/api/foo', <--- NOT WORKING

            });
        },

Two-Fold issues:

*

*On the server side do I not need to pass the "app" as a parameter down the routes tree? I tried but recv'd an error.

*In the scenario above, what is the correct url for my angular factory as I what have does not work.

A: OK, this was a tough one but I finally solved it.

*

*My desire to compartmentalize my route structure on the server side to mirror my module structure on the client [angular] side is the right approach.

*Where I erred was in thinking I needed to create a tree structure [<-- WRONG] for my server routes and that is NOT the case.
The Example:
Client [angular] side:

public
 ---- app
    ---- module A folder
    ---- module B folder
    ---- module C folder

Server [express] side structure:

server
 ---- routes
    ---- route A folder
        --- foo apis
        --- bar apis
    ---- route B folder
    ---- route C folder

foo api on server side structure:

var express = require('express'),
FooCtl = require('../../controllers/foo/FooCtl');

module.exports = function(app){
   app.get('/api/foo', FooCtl.get);
....
}

I do not need to create a "parent route" to collect on my routes in that folder.
Instead, using "npm install --save wrench" in my root, server.js:

var express = require('express'),
    path = require('path'),
    wrench = require('wrench');

wrench.readdirRecursive("routes", function (error, files) {
       if(files != null){
       files.forEach(function (file) {
               if (file.indexOf('.js') > -1 && file != undefined) {
                   fullPath = ('./routes/' + file);
                   console.log(fullPath);
                   require(fullPath)(app);
               }
       })} });

And everything works!


text:
Q: Sending fax via RingCentral API I am using RingCentral PHP SDK for sending request. I tried some methods, they were working. But when I try to send fax with $rcsdk->createMultipartBuilder() method, I get response "Bad request" message, nothing else specified.
This code return Bad Request:
    $request = $this->ringcentral->createMultipartBuilder()
            ->setBody(array(
                'to' => array(
                    array('phoneNumber' => '1267***0722')),
                'faxResolution' => 'High',
            ))
            ->add(fopen($file->path, 'r'))
            ->request("/account/~/extension/~/fax");

While this work fine and fax is sent
    $request = $this->ringcentral->createMultipartBuilder()
            ->setBody(array(
                'to' => array(
                    array('phoneNumber' => '1267***0722')),
                'faxResolution' => 'High',
            ))
            ->add('Plain Text', 'file.txt')
            ->request("/account/~/extension/~/fax");

Also I tried to send cURL, it also returns Bad Request
curl --request POST --url 'https://platform.devtest.ringcentral.com/restapi/v1.0/account/~/extension/~/fax' --header 'accept: application/json' --header 'authorization: Bearer '<mycode>' --header 'content-type: multipart/form-data' --data '{"attachment":"data:text/plain;name= test.txt;base64,VGVzdCBtZXNzYWdl","to":["1201***0654"]}'

A: Since the fax api support attachments as data. 400 error is caused due to wrong content or mime type: multipart/mixed
The API allows sending a fax message with a multipart request, incorporating two or more parts.
ref: https://developers.ringcentral.com/api-reference#
Have you checked this, the curl command included mime type as multipart/mixed:
https://forums.developers.ringcentral.com/questions/614/switching-to-f-form-option-for-posting-multipartmi.html?page=2&pageSize=10&sort=oldest
and this:
https://forums.developers.ringcentral.com/questions/221/sandbox-fax-send-400-bad-request.html


text:
Q: Почему возникает ошибка при подключению к сервису? Я пытаюсь подключиться по api к сервису: https://fedresurs.ru/. Для работы использую SDK: https://github.com/Smolevich/fedresurs-sdk.
При подключении возникает ошибка:

Uncaught SoapFault: looks like we got no XML document in /phpro/soap-client/src/Phpro/SoapClient/Soap/Driver/ExtSoap/ExtSoapDecoder.php:33

Пожалуйста, подскажите, как исправить ошибку?
Вот мой код:
require_once __DIR__ . '/vendor/autoload.php';

use Fedresurs\WebService\Type\GetDebtorsByLastPublicationPeriod;
use Fedresurs\WebService\Type\GetTradeMessages;
use Http\Adapter\Guzzle6\Client;
use Phpro\SoapClient\Soap\Handler\HttPlugHandle;
use Fedresurs\WebService\WebServiceClientFactory;
use \Fedresurs\WebService\Type\GetTradeMessageContent;

$config = json_decode(file_get_contents(__DIR__ . '/config/credentials.json'), true);

if (empty($config)) {
    throw new Exception('Empty config');
}

$handler = HttPlugHandle::createForClient(
    Client::createWithConfig([
        'headers' => ['User-Agent' => 'testing/1.0'],
        'auth' => [$config['username'], $config['password'], 'digest']
    ])
);

$client = WebServiceClientFactory::factory(__DIR__ . '/schema/schema.wsdl', $handler);
$startDate = new DateTime('-10 day');
$endDate = new DateTime('now');
// Fatal Error
$response = $client->getDebtorsByLastPublicationPeriod(new GetDebtorsByLastPublicationPeriod($startDate,$endDate));


text:
Q: Grunwald fractional derivative I came across this maths statement
\begin{align*}
f(t+h) &= f(t) + h\frac{d}{dt}f(t) + \frac{h^2}{2!}\frac{d^2}{dt^2}f(t) + \frac{h^3}{3!}\frac{d^3}{dt^3}f(t) + \cdots \\
&= f(t) + hDf(t) + \frac{h^2}{2!}D^2f(t) + \frac{h^3}{3!}D^3f(t) + \cdots   \\
&= \left(1 + hD + \frac{h^2}{2!}D^2 + \frac{h^3}{3!}D^3 + \cdots \right)f(t) \\
&= e^{hD}f(t).
\end{align*}
I doubt this is a correct thing since I cannot understand the meaning of $e^{hD}f(t)$ where $D=\dfrac{d}{dt}$ is a differential operator. As an extra information, I found this info when reading something related to Grunwald fractional derivative.
Edit: My question is, can we actually factorise the operator $D$ and take a Taylor series for it as done above? This is because, I imagine that, if $t+h$ is a value on the x-axis, then $f(t+h)$ is a value on the y-axis. On the other hand, $e^{hD}f(t) = e^{h\frac{d}{dt}}f(t)$ is not a value, thus how can $f(t+h)$ be equivalent to $e^{h\frac{d}{dt}}f(t)$?


text:
Q: Application. Received Google message received: Violation of Usage of Android Advertising I have thé application on google play over 2 years this morning i received à mail from Google that tell me that application is deleted
I only use Google admob sdk i have no autorization on manifest file here is the mail i received from Google
Hi developers at ***** 2018,
After review, Listening Prep 2/3 – TOEIC® Test, com.toeic.***i.listening.part2, has been removed from Google Play due to a policy violation. This app won't be available to users until you submit a compliant update.
Issue: Violation of Usage of Android Advertising ID policy and section 4.8 of the Developer Distribution Agreement
Google Play requires developers to provide a valid privacy policy when the app requests or handles sensitive user or device information. We've identified that your app collects and transmits the Android advertising identifier, which is subject to a privacy policy requirement. If your app collects the Android advertising ID, you must provide a valid privacy policy in both the designated field in the Play Console, and from within the app.
Next steps: Submit your app for another review
Read through the Usage of Android Advertising ID and User Data policies, as well as the Developer Distribution Agreement, and make appropriate changes to your app. If you decide to collect sensitive user information, be sure to abide by the above policies, and include a link to a valid privacy policy on your app's store listing page and within your app.
Make sure that your app is compliant with all other Developer Program Policies. Additional enforcement could occur if there are further policy violations.
Sign in to your Play Console and submit the update to your app.
How can i résolve this problèm Please ?


text:
Q: Если приложение удалено, будут ли деньги сниматься за подписку? Если приложение удалено, будут ли деньги сниматься за подписку? Что-то нигде в доках не могу этого найти.

A: Да.
Когда пользователь попытается удалить приложение, он получит предупреждение, что имеется активная подписка. Если он проигнорирует предупреждение и продолжит удаление, то подписка останется активной.
Соус:

App uninstallation
When the user uninstalls an app that includes purchased subscriptions, the Play Store app will notify the user that there are active subscriptions. If the user chooses to continue with the uninstallation, the app is removed and the subscriptions remain active and recurring billing continues. The user can return to cancel the associated subscriptions at any time in the My Apps screen of the Play Store app. If the user chooses to cancel the uninstallation, the app and subscriptions remain as they were.
https://developer.android.com/google/play/billing/billing_subscriptions.html


text:
Q: Update only some fields in a Microsoft Dynamics entity I'm developing a software in C# language that interacts with Microsoft Dynamics through calls to Organization service.
I need to update only some fields of the entity, but when I call the Update operation, Microsoft Dynamics launches a massive update of all the fields of the entity.
I don't want this massive update, I need to update only 2 or 3 fields.
This is my code:
//reading account
Entity account = <reading entity with a call to organizationService>
//update fields
account["fieldName1"] = newValue;
account["fieldName2"] = newValue2;
//call to update entity
organizationService.Update(account);

How I can solve this problem?

A: We use early binding here and we also accept the entire object will be updated,  but from memory:
try this
var accountToBeSentToDynamics = new Entity("account");
accountToBeSentToDynamics.Id = accountToBeUpdated.Id;
accountToBeSentToDynamics["name"] = "Only This Field will be updated";

We also add these to a list of inserts or updates and flush them in batches of size 1000 or less to speed performance

A: This is your problem.
Entity account = <reading entity with a call to organizationService>;

Any attributes retrieved within the call to the org service will be present on your "account" object and subsequently resent to CRM in the update message.
Try something like this:
Entity retrieved = <reading entity with a call to organizationService>;
Entity account = new Entity("account", retrieved.Id);
//update fields
account["fieldName1"] = newValue;
account["fieldName2"] = newValue2;
//call to update entity
organizationService.Update(account);

This way you are guaranteed that only the attributes you've added to the object are updated in CRM.
Lastly, its best practice to only retrieve attributes necessary to perform your business logic when doing a Retrieve or RetrieveMultiple. More attributes will reduce the performance of the query.


text:
Q: Mongodb data is not returned to nodejs api I am able to connect to mongodb through my nodejs api but for some reason data is not returned. When i query mongodb from console , here is what i get :
MongoDB Enterprise > db.patients.find();
{ "_id" : ObjectId("58c9a5dd1eb8c7c1c68778ca"), "FName" : "n", "LName" : "ri", "Email" : "abc@yahoo.com", "phone" : "1234567890" }

here is the code from nodejs:
app.get('/api/patients',function(req,res){
    Patient.getPatients(function(err,patients){
        if(err){
            throw err;
        }
        console.log(patients.length);
        res.json(patients);

    });
});

and this is getPatients method:
var Patient = module.exports = mongoose.model('patient',patientSchema);

// get patients

module.exports.getPatients = function(callback,limit){

    Patient.find(callback);
}

But the browser always shows "[]" and no data. When i look at length of array ( console.log(patients.length)) in API , i get 0. Not sure why data is not returned.
Can someone pls point me what may be the issue ?
Update
Based on suggestions, I did following changes. I created 2 collections just to make sure that the collection exists. So i have patient and patients collections.
MongoDB Enterprise > db.patient.find();
{ "_id" : ObjectId("58cfe4551eb8c7c1c68778cc"), "FName" : "V", "LName" : "K", "Email" : "abc@yahoo.com", "phone" : "1234567890" }
{ "_id" : ObjectId("58cfe4601eb8c7c1c68778cd"), "FName" : "V1", "LName" : "K1", "Email" : "abc@yahoo.com", "phone" : "1234567890" }
MongoDB Enterprise > db.patients.find();
{ "_id" : ObjectId("58cfe42d1eb8c7c1c68778cb"), "FName" : "V", "LName" : "K", "Email" : "abc@yahoo.com", "phone" : "1234567890" }

Here is the code from nodejs file:
var mongoose = require('mongoose');

var patientSchema = mongoose.Schema({
    FName: {
        type : String
     },
     LName: {
        type : String
     },

     Email: {
        type : String
     },
     phone: {
        type : String
     },

},
{collection : 'patient'});

var Patient = module.exports = mongoose.model('patient',patientSchema);

// get patients

module.exports.getPatients = function(callback,limit){
console.log('test2');
 Patient.find({}, function(err, patients) {
  if (err) throw err;

  // object of all the users
  console.log(patients.length);
});
}

when i run this code, it prints 'test2' and '0' for me but not actual results. Can someone help with this ?

A: Are you sure you defined your schemas well and its exported very well... If yes then do something like this from your nodejs scripts
//get the model
var Patient = mongoose.model('patient',patientSchema);
// get all the patients
Patient.find({}, function(err, patients) {
  if (err) throw err;

  // object of all the users
  console.log(patients);
});

I believe this should work

A: The answer above, while executing the find on the Patient model correctly, will not get the results back to your api response. I think if you change your getPatients code to this:
var Patient = module.exports = mongoose.model('patient',patientSchema);

module.exports.getPatients = function(callback) {
    Patient.find({},
        function(err, data) {
            callback(err,data);
        }
    );
}

It will work. If that doesn't work, I'd want to see the entire code file to make sure the app.get can access the getPatients function - but you would get an error if that wasn't the case. So, I think this will work.

A: I figured my code was correct but connection string was incorrect.
Incorrect Connection string :
mongoose.connect('mongodb://localhost:27017/');
Correct connection string:
mongoose.connect('mongodb://localhost:27017/patients');


text:
Q: Mail Server Storage Backend: Filesystem VS Database I am trying to compare mail server software to decide which to use at the ISP where I work. I'm confused mainly about which storage backend is better for such use (again, at an ISP, i.e expected large number of users and possible heavy load).
My question is: What are the advantages/disadvantages of each of the two main storage backends?

*

*Filesystem: generally speaking, since I think formats don't make significant differences, correct me if I'm wrong please.

*Database: generally speaking, regardless of the engine.
I tried to search with many search terms without success, any explanation would be much appreciated.

A: With mail server software, as with all software, you need to take a look under the hood and learn how the software works.
For example Cyrus IMAPd uses Maildir format (at least by default), but in addition to that it has cyrus.{header,index,cache} files which it uses for improving performance. Thanks to those data files, it can return mail headers and other common stuff to mail client without scanning through every mail file, which improves performance quite a lot.
With database based software, you need to find out which database server works best with your mail server, and you probably need a competent DBA to keep everything running smoothly. Also make sure that the mail server software choice of yours does generate sensible SQL queries.
If you want to sleep your nights peacefully, this is just a start. You also need to take into account the scalability of your system (for example, with Cyrus you can use Cyrus Murder or put Perdition in front of Cyrus to scale up to multiple servers), availability of your system (does it matter if one server node goes down or not), and of course maintainability of your system. How easy it would be to recover a single mailbox? Or the whole system? How to backup a potentially huge amount of mail? How to manage user accounts?


text:
Q: Error in Xcode 8.3 - "object has changed without an appropriate KVO notification being sent" I'm suffering from an issue which appears with Xcode 8.3 (sample works fine in version 8.2.1)
I created a NSTextField and connect the value binding to ViewController self.myDict.String
The button calls "change"
When I start the app the string "Initial String" is displayed in the Textfield.
When I click on the button I get an exception

Cannot update for observer  for
  the key path "myDict.String" from , most likely because the value for the key "myDict"
  has changed without an appropriate KVO notification being sent. Check
  the KVO-compliance of the exceptiontest.ViewController class.

The issue first appeared in the latest Xcode 8.3 and works fine on older versions.
Could this be a bug or do I have some kind of design error?
import Cocoa

class ViewController: NSViewController {

    dynamic var myDict = ["String":"Initial String"]

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    @IBAction func change(_ sender: Any) {
        self.willChangeValue(forKey: "myDict")
        myDict["String"] = "New String"
        self.didChangeValue(forKey: "myDict")
    }

}

Thank you!


text:
Q: Redirecting to routes programatically using route names I have the following routes:
ReactDOM.render(
        React.createElement(ReactRouter.Router, {history: ReactRouter.hashHistory},
            React.createElement(ReactRouter.Route, {path: '/', component: AppController}),
            React.createElement(ReactRouter.Route, {component: LayoutController},
                React.createElement(ReactRouter.Route, {path: '/dashboard', component: DashboardController}),
                React.createElement(ReactRouter.Route, {path: '/signout', component: UserSignoutController})
            )
        )
    , document.getElementById('content'));

This is how I redirect the application flow:
ReactRouter.browserHistory.push('/dashboard');

It works, but if I open my application on another machine with a different url structure, and I have to change url paths, I also have to change every push argument.
Is there a way to redirect using route names instead of paths?

A: In older versions it was possible to navigate by name, but AFAIK it is no longer working. In my opinion what you should do is to configure the basename of the history for your different servers, i.e. the prefix of the route. Take into account that the final part of the URL, the one that is configured by react-router is fixed.
In order to specify the basename, you should pass a custom history to the router.
useRouterHistory(createBrowserHistory)({ basename })


text:
Q: Static compilation in the .NET world I'll be writing a small desktop app for a client that has WinXP machines and they won't be installing the .NET framework (at least not for me).
So my choices are limited to either C++ or VB6, neither of which sound great.
I remember reading back in the day that Mono came up with a static compiler, but recently the only thing I could find is Miguel de Icaza's entry on static compilation for a game engine for the purposes of running the app on the iPhone - not what I had in mind.
Are there any products out there, free or commercial that will allow me to statically compile my .net 3.5 winform app?
Thanks

A: Mono has vastly improved its support for Ahead of Time compilation (AOT) to the point where, assuming you are willing/able to target Mono rather than the .Net runtime, it should be possible to statically compile virtually any CIL application.
Whether or not that is a good idea overall depends entirely on the application and your constraints.
For example, Novell now ships MonoTouch, a CLI implementation which is fully AOT compiled and linked to allow .Net applications (not just games) to run on the iPhone against the CocoaTouch framework.
Those same AOT techniques can be used to compile a Winforms application which would not require either the .Net or Mono runtime as prerequisites. There are a lot of performance tradeoffs (both positive and negative) related to AOT, so I would not move forward without due diligence.

Edit:
In response to John Saunders' question regarding "why not just install it for them?". That actually brings up one reason why you might need AOT compilation.. Bootstrappers.
In order to install anything, you have to run an executable. You can either distribute an MSI (which will launch msiexec.exe implicitly) or you can distribute an exe. MSI, while functional, is a pretty terrible developer experience. So you could build your bootstrapper using .NET (AOT compiled eliminate the runtime dependency) which installs whatever prerequisites are necessary (such as .NET) before installing your app.
Additionally, some companies may need to ship downloadable executables that don't require users to install anything (silently or otherwise).
Yet another: Installing .NET requires administrative privileges. AOT may allow you to get around that requirement for your application.
Again, whether any of that is a good idea depends entirely on the application and on your constraints.

A: You can try to use Remotesoft Salamander.
It does exactly what you want.


text:
Q: How to bind celery application with Task class? I want to override the Task class of Celery. I could override on_success and on_failure methods, but the run method is not that easy for me.I tried to use the bind method. My code is as below:
class MyTask(Task):
    def on_success(self, retval, task_id, args, kwargs):
        print("success")

    def on_failure(self, exc, task_id, args, kwargs, einfo):
        print("failed")

    def bind(self, app):
        return super(self.__class__, self).bind(app)

    def run(self, *args, **kwargs):
        x = kwargs.get('data', None)
        x = x**2

if __name__=="__main__":
     mytask = MyTask()
     app = Celery('mytask', backend='redis', broker='redis://localhost')
     mytask.bind(app)
     job = mytask.apply_async(data = 1)

but when i run the code i get the following error:
Received unregistered task of type None.
The message has been ignored and discarded.

Did you remember to import the module containing this task?
Or maybe you're using relative imports?

Please see
http://docs.celeryq.org/en/latest/internals/protocol.html
for more information.

The full contents of the message body was:
b'[[], {}, {"callbacks": null, "errbacks": null, "chain": null, "chord": null}]' (77b)
Traceback (most recent call last):
  File "/home/ayandeh/anaconda3/lib/python3.6/site-packages/celery/worker/consumer/consumer.py", line 559, in on_task_received
    strategy = strategies[type_]
KeyError: None

I have searched a lot but I got no result. How should I register the task?

A: Explicitly binding app is not necessary as celery task will auto-bind to current_app when calling apply_async.
If you would like explicitly binding, two ways available:
1. task.bind(app)
2. create Task class from app.Task. By inheriting app.Task, this app will be bound.
Your issue is not about binding. It's about task registry. Correct it as below:
from celery import Celery, Task

class MyTask(Task):
    name = 'mytask'

    def on_success(self, retval, task_id, args, kwargs):
        print("success")

    def on_failure(self, exc, task_id, args, kwargs, einfo):
        print("failed")

    def run(self, *args, **kwargs):
        x = kwargs.get('data', None)
        print(x**2)

if __name__ == "__main__":
    app = Celery('mytask', backend='redis', broker='redis://localhost')
    MyTask.bind(app)
    app.tasks.register(MyTask)
    app.worker_main()

Hope it helpful.


text:
Q: Sometimes imagebutton click event not fired I have a method that add's an onclick event too an imagebutton.
But sometimes you have to press the button multiple times before the "pop-up" window opens.
Any idea why this happens?
this is my code were I add the event to my imagebutton:
private void AddProjectDetails()
    {
        ImageButton imgBtn;
        HiddenField hfld;
        String ProjectNumber;
        for (int i = 0; i < GridViewProperties.Rows.Count; i++)
        {
            hfld = GridViewProperties.Rows[i].FindControl("HiddenProjId") as HiddenField;
            imgBtn = GridViewProperties.Rows[i].FindControl("ibtnShowExtra") as ImageButton;
            ProjectNumber = hfld.Value;
            imgBtn.Attributes.Add("onclick", "window.open('ProjectDetails.aspx?ProjectNumber=" + Server.UrlEncode(ProjectNumber) + "','Graph','height=590,width=600,left=50,top=50,scrollbars=yes'); return true;");
        }
    }

A: Try returning false from the javascript. This will prevent postback. Some times the postback can be faster then the windows.open, and in this case I don't think you want it.
Another solution is using an image instead of the imagebutton

A: Why are you using return true inside you java-script function.

Do you need postback on your page.
If not use return false.
I will also suggest you to write a javascript function and call it as follows
function OpenPopUp(projectNumber)
{
      window.open("ProjectDetails.aspx?ProjectNumber="+ projectNumber
                      ,'Graph','height=590,width=600,left=50,top=50,scrollbars=yes');
      return false;
};

and call it inside your c# code
imgBtn.Attributes.Add("onclick", "return OpenPopUp('"+Server.UrlEncode(ProjectNumber)+"');");

A: Like Stefano and Shekhar said, you must not use return true for LinkButtons, Imagebuttons, unless you want the page post back.
You can also use this way:
<asp:ImageButton ID="ButtonOpenProject" runat="server" ImageUrl="~/Images/OpenProject.png"  OnClientClick="return OpenProject('"<%# ProjectNumber %>"');" />

And in your JavaScript script you do something like this:
function OpenProject(ProjectNumber){
    window.open('ProjectDetails.aspx?ProjectNumber=' + ProjectNumber + ','Graph','height=590,width=600,left=50,top=50,scrollbars=yes');
    return false;
}

Hope this help.


text:
Q: Trying to create a database with the server ID name in Node.JS gives error I'm trying to create a database with the server ID as the name of the db on the event "guildCreate".
This is my code.
client.on("guildCreate", guild => {
  console.log(`Joined server: ${guild.name} (ID: ${guild.id}). The server has: ${guild.memberCount} members!`);
  client.user.setActivity(`${client.guilds.size} servers!`, { type: 'WATCHING' });
  console.log("Status: Database created!");
  sql1 = "CREATE DATABASE IF NOT EXISTS "+ guild.id +"";
  con.query(sql1);
});

And this is my console output: https://i.imgur.com/OsgRai5.png
EDIT: I did try just now to execute the query without the guild.id variable.
sql1 = "CREATE DATABASE IF NOT EXISTS 154987646546464"; - Works
sql1 = "CREATE DATABASE IF NOT EXISTS "+ guild.id +""; - Does not work.

The query with the variable gives me an error, the one without a variable works.

A: Try to wrap that id in single quotes
sql1 = "CREATE DATABASE IF NOT EXISTS '"+ guild.id +"'";

A: Solved: You just need to put tilt keys before and after the guild id.
Ex:
sql1 = "CREATE DATABASE IF NOT EXISTS `"+ guild.id +"`";

or
sql1 = "CREATE DATABASE IF NOT EXISTS `479846468464654654`";


text:
Q: Would love some help determining where to start with the Node.JS app file provided with BlueMix I've been reading tutorials for JS and I've got a good idea of the syntax and methodology, now I'm looking to figure out how to use Node.JS to build an app with BlueMix. I'm pretty fluent with Java, but I'm absolutely new to web programming so I'm pretty lost as to how to start. Forgive my current state of being an absolute beginner, but I'm just really stuck. Here's the file they give you to build off of.
/*eslint-env node*/

//--------------------------------------------------------------------------
// node.js starter application for Bluemix
//--------------------------------------------------------------------------

// This application uses express as its web server
// for more info, see: http://expressjs.com
var express = require('express');

// cfenv provides access to your Cloud Foundry environment
// for more info, see: https://www.npmjs.com/package/cfenv
var cfenv = require('cfenv');

// create a new express server
var app = express();

// serve the files out of ./public as our main files
app.use(express.static(__dirname + '/public'));

// get the app environment from Cloud Foundry
var appEnv = cfenv.getAppEnv();

// start server on the specified port and binding host
app.listen(appEnv.port, '0.0.0.0', function() {

// print a message when the server starts listening
  console.log("server starting on " + appEnv.url);
});

To clarify, I get the general purpose of the code - it's commented pretty well, but I just don't know how to start // test on the BlueMix platform. I tried doing things like adding print statements, but nothing really changes.
To give a little insight on what I'm trying to do: Just create a webpage where a user can input a string and I can post a string in response. I'm just trying to learn BlueMix, so I need to do it on this platform, and in Node JS.

A: I suggest you to take a look at this tutorial: IBM Bluemix DevOps Services - Develop and deploy a Node.js app. It is useful to get started with DevOps Services (reading your comments it seems that you are using it to deploy from the Web IDE to Bluemix) to get a "Hello World" Node.js Web application on Bluemix. It also shows how to apply some changes and re-push them directly on Bluemix.
Just to answer to your questions, assuming that you have already deployed the starter application (as in your example):

*

*Consider that the starter application uses Express.js, that is an application server framework that helps you to manage the incoming requests. Now let's say that you want to send the string "Hello, World!" in HTTP response when the server receives an HTTP GET request (let's say /printhello). Using express you'll have something like:

app.get('/printhello', function (req, res) {
    res.send('Hello, World!');
  });

*Now you just need to do the HTTP GET /printhello from a web page (for example the index page under the public folder of the starter application). You could for example use an onclick event to send the request to the server. You will see that the server receives it and sends the response to the browser, that will show the string "Hello, World!".

*The reason why you can't see the "starting server" log is that console.log prints in the Node.js console, not into the HTTP response, so you can't see that from the client. To see that output you can use cf logs (please refer to this blog post).

Finally, I invite you to take a look at the Bluemix - Node.js SDK documentation, it is really simple and clear.
I hope this can give you some starting points.

A: Check out https://github.com/IBM-Bluemix/bluemix-hello-node.  It provides a pretty good starting place for node.  There are somethings you need to code around for Node to work for Bluemix.  The biggest is binding to the correct port, the port is given through process.env.PORT.  I have pasted a super simple Node.app below (the rest of the code is at the GitHub link above).
var express = require("express"),
    app = express();

var port = process.env.PORT || 8080;

app.use(express.static(__dirname + '/public'));

app.get("/hello", function (request, response) {
    response.writeHead(200, {"Content-Type": "text/plain"})
    response.end("Hello World!\n");
});

app.listen(port);


text:
Q: getActionBar() is undefined I want to add a ActionBar to my Fragment class, but I keep getting errors. This is my class:
public class TaskDetailFragment extends Fragment {

    public static final String ARG_ITEM_ID = "item_id";

    MyTasks.taskItem mItem;

    public TaskDetailFragment() {

    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (getArguments().containsKey(ARG_ITEM_ID)) {
            mItem = MyTasks.ITEM_MAP.get(getArguments().getString(ARG_ITEM_ID));
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.fragment_task_detail,
                container, false);

        ActionBar actionBar = getActionBar();
        actionBar.show();

        if (mItem != null) {
            //Add TexViews
            ((TextView) rootView.findViewById(R.id.in_Name))
                    .setText(MyTasks.customers[(Integer.parseInt(mItem.id))][1]);
            ((TextView) rootView.findViewById(R.id.in_Address))
                    .setText(MyTasks.customers[(Integer.parseInt(mItem.id))][3] + "  " + MyTasks.customers[(Integer.parseInt(mItem.id))][2]);

        }
        return rootView;
    }
}

This is my error:

The method getActionBar() is undefined for the type TaskDetailFragment

A: As far as I know, you need to ask the Activity (to which the Fragment has been attached) for the ActionBar:
ActionBar actionBar = getActivity().getActionBar();

Or if you're using the support library and/or ActionBarSherlock:
ActionBar actionBar = getFragmentActivity().getSupportActionBar();

Fragments don't define a getActionBar() method, hence the error message.

A: ensure that the getActionBar() is defined in the TaskDetailFragment or other superclasses or sometimes android emulataor can add "protected" to the defining of the method

A: If a fragment wants to use ActionBar, it has to call setHasOptionsMenu(true) , usually from onCreate().


text:
Q: How do I change active tab text color? I have made a tab using JS but I'm unable to add active tab text color. So I want an active tab text color.
I have added the hover color already but I don't seem to achieve active text color. Please note that I'm only looking for active text not the whole tab color to be changed.
Can anyone help me how can I achieve it?
Regards,
Bill

/* Grid View on Search Page */
$("#grid").click(function() {
  $("#grid-view").show();
  $("#map-view").hide();
});

/* Map View on Search Page */
$("#map").click(function() {
  $("#grid-view").hide();
  $("#map-view").show();
});

$("#grid").trigger("click");

/* More Filters Button Toggle */
$("#more-filters").click(function(e) {
  e.preventDefault();
  e.stopPropagation();
  $("#moreoptions").collapse("show");
  $("#more-filters").hide();
  $("#more-filters").parent().parent().hide();
});

/* Reset All Filters on Search Sidebar */
$("#reset_filter").click(function(e) {
  e.preventDefault();
  e.stopPropagation();
  $("#reset_vehicle_form")[0].reset();
});
.view-btn {
  background: #FFF;
  color: #989898;
  font-family: 'Source Sans Pro', sans-serif;
  font-size: 13px;
  font-weight: 600;
  margin: -13px 0px 2px 1px;
  padding: 4px 10px 4px 9px;
}

.filter-btn:active, .view-btn:active {
 color: rgb(0,0,0,.7);
 text-decoration: none;
}

.filter-btn:hover,
.view-btn:hover {
  color: rgb(0, 0, 0, .7);
  text-decoration: none;
}

.view-btn:focus,
.filter-btn:focus {
  box-shadow: none;
  outline: 0!important;
  -webkit-box-shadow: none;
}

.gridView {
  display: none;
}

.mapView {
  display: none;
}

  <button id="grid" class="btn view-btn"> Grid View</button>
  <button id="map" class="btn view-btn active">  Map View</button>

    Hello 1

    Map view

A: You just needed to add and remove an 'active' class as well at the same time as you are showing and hiding the divs #grid and #map.
And also add an .active CSS class with a background colour (i have set it to background-color: red, but you can change it to whatever style you would like)

/* Grid View on Search Page */
$("#grid").click(function() {
  $("#grid-view").show();
  $("#map-view").hide();
  $("#grid").addClass('active');
  $("#map").removeClass('active');
});

/* Map View on Search Page */
$("#map").click(function() {
  $("#grid-view").hide();
  $("#map-view").show();
  $("#map").addClass('active');
  $("#grid").removeClass('active');
});

$("#grid").trigger("click");

/* More Filters Button Toggle */
$("#more-filters").click(function(e) {
  e.preventDefault();
  e.stopPropagation();
  $("#moreoptions").collapse("show");
  $("#more-filters").hide();
  $("#more-filters").parent().parent().hide();
});

/* Reset All Filters on Search Sidebar */
$("#reset_filter").click(function(e) {
  e.preventDefault();
  e.stopPropagation();
  $("#reset_vehicle_form")[0].reset();
});
.view-btn {
  background: #FFF;
  color: #989898;
  font-family: 'Source Sans Pro', sans-serif;
  font-size: 13px;
  font-weight: 600;
  margin: -13px 0px 2px 1px;
  padding: 4px 10px 4px 9px;
}

.view-btn.active {
  background-color: red;
  color: white;
}

.filter-btn:hover,
.view-btn:hover {
  color: rgb(0, 0, 0, .7);
  text-decoration: none;
}

.view-btn:focus,
.filter-btn:focus {
  box-shadow: none;
  outline: 0!important;
  -webkit-box-shadow: none;
}

.gridView {
  display: none;
}

.mapView {
  display: none;
}

  <button id="grid" class="btn view-btn"> Grid View</button>
  <button id="map" class="btn view-btn active">  Map View</button>

    Hello 1

    Map view


text:
Q: How to open multiple instances of the bash Terminal? Under Ubuntu 10 I could easily open as many Terminal instances as I needed, and I often need 6 or more.  How can I do that in Ubuntu 12?  When are they going to fix the bug that restricts me to only one?

A: There is absolutely nothing in Ubuntu that restricts you to opening only one terminal window. At the moment I have anout 30 terminal windows open :)

A: Difference between Gnome 2 and the "new" Unity
I think you are referring to the behavior of the panel on the left side of screen which is now similar to a mac. When you click on an icon, the application is started. If, however, the application is running already, you will switch to its window.
For users of good old Gnome 2, this may be irritating. There, starters were for starting applications. No matter how often you click them and no matter what is already running, they start a new window. Switching between windows was done via a separate panel which lists all running application.
In Unity, the panel takes over both tasks. Launching and switching to applications. It assumes that the typical use case is to have one instance of an application open and maybe use its built-in tab support.
Multiple Windows in Unity
However, there is a possibility to open multiple windows by using just the mouse. Just right click on the element and select New Terminal. A more convenient way involving also the keyboard is holding Shift and left clicking on the application icon.
A third possibility to start the terminal (which is the one I prefer) is using the shorcut Ctrl+Alt+T.
Choose what you like most.
As you can see, its not a bug, its just a big change on the user interface.

A: bash is just the shell. You can open as many as you like. Terminal on the other hand is the application that emulates a terminal.
So there are several ways.
The text way:
Ctrl+Alt+F1 -Ctrl+Alt+F6 (by deafult)
The old school way
Using screen or bashes background job support More info
Or in gnome
Which is what I suspect you want. Just lauch gnome terminal several times. There's the File-> New Terminal option, and if all else fails you can always start several terminals from terminal.
gnome-terminal --window --window --window --window --window --window
which will spawn 6 new terminal windows.
I do not know of a bug that restricts you to one terminal. I frequently use 4 or more for rails development.

*

*Spork

*Autotest

*Guard (long story)

*The Rails console

If you need a more in depth example my autotest script runs (please excuse the poor formating the site did):

!/bin/bash
  source /home/coteyr/.bash_profile
gnome-terminal --working-directory="$1" --profile=rails --tab --title="DRB" --command=/home/coteyr/.bin/spork.sh --tab --title="Testing" --command=/home/coteyr/.bin/auto-test.sh --tab --title="Reload" --command=/home/coteyr/.bin/reload.sh

A: This applies to Unity
sumpfomat mentioned Ctrl+Alt+T will open a new terminal window. You can repeat that as many times as you like and open new terminals. But there is another possibilty: in an already open terminal Ctrl+Shift+T will add a new tab to the already open terminal. From the terminals menu this is File -> Open Tab.
You can open as many tabs as you like. To navigate between them you can use Alt+[1,2,3,..]
This is really handy if you need to run processes in the foreground that don't need much direct input (watchers for things like sass, continuous testing etc). Everything is contained in one terminal process so Alt+Tabing is not a mess, but you can easily switch between your tabs as well.


text:
Q: Describe $\mathbb{Z}[\omega] / (2)$ $$\Bbb Z[ω] = \{\;a + bω: a, b\in\Bbb Z\;\}\;,\;\; ω = e^{2πi / 3} = -\frac12 +\frac{\sqrt3}2i$$
Describe $\;\Bbb Z[ω]/(2)\;$ where $\;(2)\;$ is an ideal.
I already described it as a ring, and am now looking to describe it as:
x̅1, ..., x̅r for some specific x1, ..., xr where x̅i are in the ideal.

A: Not sure this is what you expect, but your question isn't very clear.
As $\mathbf Z[\omega]\simeq \mathbf Z[x]/(x^2+x+1)$ we have:
$$\mathbf Z[\omega]/(2)\simeq \mathbf Z/2\mathbf Z[x]/(x^2+x+1)$$
The polynomial $x^2+x+1$ is irreducible over $\mathbf Z/2\mathbf Z=\mathbf F_2$, hence this quotient is a quadratic extension of $\mathbf F_2$ (there's only, up to isomorphism), i.e. it is isomorphic to $\mathbf F_4$.

A: Notice that $2$ and $2\omega$ are both in the ideal $(2)$. This means you can reduce any element $a+b\omega$ to one of these equivalence classes: $$\{0, 1, \omega, 1+\omega\}.$$ Now you can describe the ring structure by writing out a table for addition and a table for multiplication (keeping in mind that $1+1 = 0$ and $\omega^2 = \omega + 1$).
There aren't so many possibilities though; for instance, the multiplicative group of nonzero elements can only be a cyclic group of order three.


text:
Q: LUIS issues with special characters (TEXT) is converted to ( TEXT ) in LUIS when we identify an entity name.
Issues with special characters.
Refer the image in below:

Here monthly iq dashboard hospitalists is converted to reportname --> "monthly iq dashboard ( hospitalists )" in Entities. So when we use this entity in bot framework we are facing issues while comparing to actual report name stored in Metadata (database).

A:
(TEXT) is converted to ( TEXT ) in LUIS when we identify an entity name. Issues with special characters.

The issue you reported seems be that whitespace is added when some special characters are using, I reproduced the issue on my side, and I find similar issues are reported by others:

*

*LUIS inserts whitespace in utterances when punctuation present causing entity getting incorrectly parsed

*LUIS cannot take care of special characters

when we use this entity in bot framework we are facing issues while comparing to actual report name stored in Metadata (database)

To solve it, as Nicolas R and NiteLordz mentioned in comments, you can try to handle that in your code. And to remove whitespace from ( hospitalists ), the following regex would be helpful.
Regex regex = new Regex(@"\(\s\w*\s\)");

input = Regex.Replace(input, regex.ToString(), c => c.Value.Replace(" ", ""));

Note: can reproduce the issue, and same issue will appear when we process something like URL that contains / and . etc


text:
Q: Where are scanner drivers located, and what (file) form do they take? I'm attempting to make use of this scanner (Dymo Cardscan 800):

It has no generic or publicly available drivers for any version of MacOS (or Windows, for that matter). The makers intend for you to use their software... and yesterday I stumbled across a copy (demo, I get 100 scans before it locks me out). I tested it on Sierra, and it works.
In the dotapp bundle, I see several executables. Only one is executable from the command line. That one just launches the application, gui and all.
However, in the Frameworks folder, there is one named "Alpha.framework". And within that, I have another Resource bundle for it named "alpha.drv.bundle". It's just a resource bundle, but in it are a bunch of .string files, which have error messages you might expect out of a scanner driver.
I was wondering if this was some internal driver that could maybe be extracted and used generally. But I have no clue where scanner drivers are in the OS, or what form they take.
Using the proprietary software (even were I to buy a license) would be miserable... it doesn't save the scans. It OCRs them immediately, deletes the image file, and that's it (found where it puts the image file... I see it flicker into existence and then it's gone before you can click). Hoping for a minor miracle.

A: Scanner drivers are located in /Library/Image Capture/Devices/ as Tetsujin so helpfully points out.
These scanner drivers are App bundles, but quite a bit different than regular applications. An executable binary is inside Contents/MacOS, along with the obligatory plists, Resources, etc. Even so, they're typically quite a bit more barren than an actual Application bundle.
If Tetsujin wants to include an answer here, please upvote his rather than mine since mine is basically just repeating information that I got from him.


text:
Q: Electron error Function must be called on an object of type NativeImage I am working with electron and reactjs and rendering the view with electron js, I am facing an Error: Illegal invocation: Function must be called on an object of type NativeImage after electron version upgrade. I can't downgrade the electron version as some functionality is not working in surface machines.
We have the functionality to capture screenshots but after the package upgrade facing an error while screenshot capture. I am using webview to render view in the electron application.
Here is the code how I am using to load view in webview.
const webview = <webview src="path" class="webview__3kBDE" style="width: 768px; height: 576px; margin-top: 0px; margin-left: auto; margin-right: auto;"></webview>

const rawImage = await webview.capturePage()
const URL = rawImage.toPNG()

When I am printing the rawImage I am getting blank object so while rawImage.toPNG() I am facing an error. If anyone has any idea how to fix this error that would be a great help. Thank you.

A: The Electron 10 release had major changes and if you are using the Electron 10 > the remote module is now disabled by default. To use the remote module, enableRemoteModule: true must be specified in WebPreferences:
const w = new BrowserWindow({
    webPreferences: {
    enableRemoteModule: true
   }
})

For more details check here https://www.electronjs.org/docs/latest/breaking-changes#default-changed-enableremotemodule-defaults-to-false


text:
Q: How to restore GRUB after windows XP installation? After I've installed windows xp for dual booting, I need to restore grub of my archlinux installation. I did it a lot of times with windows 7, but this time heavens decided to torture me.
I have opensuse liveKDE usb drive inserted into my laptop. My currect drive is /dev/sda with /dev/sda1 -> archlinux /; /dev/sda2 -> /home; /dev/sda3 -> windows xp.
In liveKDE konsole I mount my /dev/sda1 to /mnt/arch, chroot /mnt/arch /bin/bash and run grub.
Trying root (hdX,Y) I get "selected disk does not exist". So I try grub-install /dev/sda, which gives me "Not found or not a block device". I have tried other variants like grub-install.unsupported /dev/sda, which gave me "/dev/loop0 does not have any corresponding BIOS drive", arrrr!
I'm out of options here, does anybody have an idea of some competent liveCD to start with. I tried Super Grub Disk, didn't work cause it froze all the time. Tried Rescatux but it does not have grub available in terminal.

A: Finally, I did it.
from liveCD (Archbang in my case) under root:

*

*mkdir /mnt/root

*mount -t ext4 /dev/sdaX /mnt/root

*mount -t proc none /mnt/root/proc

*mount -o bind /dev /mnt/root/dev

*chroot /mnt/root /bin/bash

*grub

*find /boot/grub/stage1

*root (hdX,Y)

*setup (hdX)

*quit

*reboot

This should work. Archlinux wiki has an article which explains the process in more detail.

A: I have tried this once,And it worked for me..I installed windows xp dual boot with Ubuntu.
Same problem occured to me, i followed the steps below hope it can work with you...
Using Ubuntu live dvd..
The graphical way
1: Insert your Ubuntu CD, reboot your computer and set it to boot from CD in the BIOS and boot into a live session. You can also use a LiveUSB if you have created one in the past.
2: Install and run Boot-Repair
3: Click "Recommended Repair".
4: Now reboot your system. The usual GRUB boot menu should appear. If it does not, hold Left Shift while booting. You will be able to choose between Ubuntu and Windows.


text:
Q: Seasonal Decomposition plots won't show despite pandas recognizing DateTime Index I loaded the data as follows
og_data=pd.read_excel(r'C:\Users\hp\Downloads\dataframe.xlsx',index_col='DateTime')

And it looks like this:
DateTime             A
2019-02-04 10:37:54  0
2019-02-04 10:47:54  1
2019-02-04 10:57:54  2
2019-02-04 11:07:54  3
2019-02-04 11:17:54  4

Problem is, I'm trying to set the data to a frequency, but there are NaN values that I have to drop, and even if I don't, it seems to be an irregular frequency. I've got pandas to recognize the DateTime to the index:
og_data.index

DatetimeIndex
dtype='datetime64[ns]', name='DateTime', length=15536, freq=None)

but when I try doing this:
og_data.index.freq = '10T'

That should mean 10min, right?
But I get the following error instead:
ValueError: Inferred frequency None from passed values does not conform to passed frequency 10T

Even if I set the frequency to days:
og_data.index.freq = 'D'

I get a similar error.
The goal is to get a seasonal decomposition plots because I want to forecast the data. But I get the following error when I try to do so:
result=seasonal_decompose(og_data['A'],model='add')
result.plot();

ValueError: You must specify a period or x must be a pandas object with a DatetimeIndex with a freq not set to None

Which makes sense, I can't set the datetime index to a specified frequency. I need it to be every 10min, please advise.


text:
Q: FQL like, share, comment count accuracy Often it seems fql number for a given url like, share, comment, total counts seem to be off.
For example this url
http://www.france24.com/en/20140112-reporters-crimean-tatars-unending-exile-identity-ethnic-minority-muslims-central-asia-ukraine
FQL shows:
share_count: 18377
like_count: 16215
comment_count: 8840
total_count: 43432

The graph api shows very different numbers, and if you check facebook widget count on the url itself it has a totally different count.
Anyone knows what is going on and how to get accurate numbers.

A: When querying link_stat with url you supplied we see the following:
select comment_count, like_count, share_count, total_count
  from link_stat where url = 'http://www.france24.com/en/20140112-reporters-crimean-tatars-unending-exile-identity-ethnic-minority-muslims-central-asia-ukraine/'

{
  "data": [
    {
      "comment_count": 10,
      "like_count": 55,
      "share_count": 18,
      "total_count": 83
    }
  ]
}

But when querying link_stat with parent url of site france24.com we see exactly your numbers (weel slightly changed of course, but almost the same). So check you query - maybe you cut the url somehow in you request?
select comment_count, like_count, share_count, total_count
  from link_stat where url = 'http://www.france24.com/'

{
  "data": [
    {
      "comment_count": 8840,
      "like_count": 16415,
      "share_count": 18377,
      "total_count": 43632
    }
  ]
}

A: Perhaps my initial question was not clear, the issue was with 2 forms of the same url returning radically different results in fql, web facebook widget etc. the urls in question are
http://www.france24.com/en/20140112-reporters-crimean-tatars-unending-exile-identity-ethnic-minority-muslims-central-asia-ukraine
and
http://www.france24.com/en/20140112-reporters-crimean-tatars-unending-exile-identity-ethnic-minority-muslims-central-asia-ukraine/
The URLs are identical except the ending /

A: The facebook sees the url as a string. Is case sensitive and it matters how you pass it for url. So, for facebook, there are really two different urls :/ The same happens if someone writes Ukraine with "U".
http://www.france24.com/en/20140112-reporters-crimean-tatars-unending-exile-identity-ethnic-minority-muslims-central-asia-Ukraine


text:
Q: Selecting all the items in UICollectionView iOS, even the cells that are not visible I am in the middle of creating an application where I have a button on a tool bar which selects all the items inside a collection view.
But the problem that I am facing is, when I tap on the button it selects only those items that are visible on the screen. This is due to the CELL REUSE functionality.
Is there any way that I can select all the cells, even those which are not currently visible to the user?
Thanks
J

A: I struggled thro the same problem where I wanted to display photos and allow the user to select multiple photos, with select-all and deselct-all options.
It turned out that [self.collectionView selectItemAtIndexPath:] does not work for selecting all cells.
So I ended up in maintaining a separate state flag along with the data source. In my case, each cell displayed a photo, so I had to maintain a separate BOOL array, where each element represents the current selection state of the corresponding photo in the data source array.
Please see the code below:
(Source: http://heliumapps.weebly.com/blog/uicollectionview-and-cell-selection)
@interface PhotosViewController() {
    BOOL *selectedStates; //cell selection states boolean array [C-language array]
    /* Let us assume that we have an array for data source, named  "myDataSourceArray".
       For each element in the array, the correspomding element in selectedStates represents
       the selection state of the cell.
   */
}

//load data source
-(void)loadDataSource {
       //init the data source array (myDataSourceArray) and populate it with data

      //free up the previously allocated memory for selecteStates, if any (in case you reuse this view controller)
      if(selectedStates) {
        free(selectedStates);
        selectedStates = nil;
      }

       //initilaize the selection states of all cells to NO
       selectedStates = malloc(myDataSourceArray.count*sizeof(BOOL));
            for(NSUInteger i = 0; i < self.myDataSourceArray.count; i++) {
                selectedStates[i] = NO;
            }
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView
                  cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    PhotoViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:self.reuseIdentifier
                                                                            forIndexPath:indexPath];
    //populate cell with required data & images to display
    [cell setPhoto:myDataSourceArray[indexPath.item]];

    //configure cell for selection state
    [cell configureCellForSelectionState:selectedStates[indexPath.item]];

    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
        [self toggleSelectionOfCellAtIndex:indexPath];
}

- (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(nonnull NSIndexPath *)indexPath {
        [self toggleSelectionOfCellAtIndex:indexPath];
}

-(void)toggleSelectionOfCellAtIndex:(NSIndexPath*)indexPath{
    MyCollectionViewCell *cell = [self.collectionView cellForItemAtIndexPath:indexPath];
    selectedStates[indexPath.item] = !selectedStates[indexPath.item];
    [cell configureForSelectionState];
}

//method to select/deselect all photos
- (void) setStateForAllPhotos:(BOOL)flag {
    for(NSUInteger i = 0; i < self.myDataSourceArray.count; i++) {
        selectedStates[i] = flag;
    }
    [self.collectionView reloadData];  //on main thread
}

/* below method in the cell's implementation  */
-(void) configureForSelectionState:(BOOL)flag {
       if(flag) {
                  //configure cell for selected state
                  [cell.layer setBorderColor:[UIColor greenColor].CGColor];
                  [cell.layer setBorderWidth:2];
    } else {
               //configure cell for deselected state
    }
}

A: Updated for Swift 3
updated Gasper Kolenc answer to swift 3 , for future use if anyone looking for this in swift 3 then..
  for row in 0..<self.collectionView!.numberOfItems(inSection: 0) {
    self.collectionView!.selectItem(at: IndexPath(row: row, section: 0), animated: false, scrollPosition: .none)
}

A: It is not possible to have all cells selected when using cell reuse.
Due to cell reuse the number of actual cells which exist at any moment is a couple more than the number of cells currently visible.
i.e. 6 cells visible is about 8 cells existing.
You are able to find out how many visible cells there are with
NSArray *visiblePaths = [self.collectionView indexPathsForVisibleItems];

The solution is to have the selected value stored within the UICollectionView datasource and use that value for when you customise a cell inside cellForItemAtIndexPath

A: I've created a simple extension on UICollectionView for selecting and deselecting:
extension UICollectionView {

    /// Iterates through all sections & items and selects them.
    func selectAll(animated: Bool) {
        (0..<numberOfSections).flatMap { (section) -> [IndexPath]? in
            return (0..<numberOfItems(inSection: section)).flatMap({ (item) -> IndexPath? in
                return IndexPath(item: item, section: section)
            })
        }.flatMap { $0 }.forEach { (indexPath) in
            selectItem(at: indexPath, animated: true, scrollPosition: [])
        }

    }

    /// Deselects all selected cells.
    func deselectAll(animated: Bool) {
        indexPathsForSelectedItems?.forEach({ (indexPath) in
            deselectItem(at: indexPath, animated: animated)
        })
    }

}

A: This is possible even with cell reuse. You can select all cells in the first section through:
for (NSInteger row = 0; row < [self.collectionView numberOfItemsInSection:0]; row++) {
    [self.collectionView selectItemAtIndexPath:[NSIndexPath indexPathForRow:row inSection:0] animated:NO scrollPosition:UICollectionViewScrollPositionNone];
}

If you have more than 1 section, just use another nested for loop to loop through all the sections.

A: Swift 3 solution:
stride(from: 0, to: collectionView.numberOfItems(inSection: yourSectionIndex), by: 1)
        .forEach{ collectionView.selectItem(at: IndexPath(row: $0, section: yourSectionIndex), animated: true, scrollPosition: []) }


text:
Q: How can I stop a hash key from overwriting duplicates in ruby I'm making a madlib; in the paragraph it finds words that look like this: [noun], [verb] or [adjective]. It does that fine but when I prompt the user for the desired word they want for that position it keeps overwriting the key with the already existing key (I'm guessing because they have the same name). But I don't know how to stop it from overwriting it; I've tried merging but I can't get it to work.
Here is the code:
class MadLib
  def initialize(input)
    p @input_string = read_file(input)
    p @parsed_inputs = parse(@input_string)
    p @hashed_input_values = {}
  end

  def take_input
    @parsed_inputs.each do |key|
      parse_key = key.match(/:/)

      if parse_key
        print "Enter #{parse_key.post_match} :"
        value = STDIN.gets.chomp
        @hashed_input_values["[#{key}]"] = value
        @hashed_input_values["[#{parse_key.pre_match}]"] = value
        @parsed_inputs.delete(parse_key.pre_match)
      else
        print "Enter #{key} :"
        @hashed_input_values["[#{key}]"] = STDIN.gets.chomp
      end
    end

    @hashed_input_values
  end

  def print_output
    @input_string.gsub(/\[(\w*:*\w)]/i, @hashed_input_values)
  end

  def parse(input)
    # f = File.open(input)
    input.scan(/\[(\w*:*\w)]/i).flatten
  end

  def read_file(file_name)
    file = File.read(file_name)
  end

  private :parse
end

madlib = MadLib.new(ARGV[0])

# test = "Story1.txt"
# madlib = MadLib.new(test)
madlib.take_input
puts "#{madlib.print_output}"

And here is the text file I've been using:
Everyone was so [adjective] to [verb] all of the [adjective] animals. The star of the show was a [adjective] [noun] named Bobo.

A: If you need to write only first value for given key - use ||=
hash = {}
hash[:a] ||= 1 # => { a: 1 }
hash[:a] ||= 2 # => { a: 1 }

A: The hash's behavior of replacing the value for a given key with a new value is the intended behavior of a hash.  We expect and need hashes to behave that way.
As previously said by others, you need to give each key a unique name. You could name the adjectives adjective1, adjective2, etc.  If you want to hide the numbers from the user, you could easily remove them in the string that you display.  It might not be so bad to even leave them in.
It might seem that implementing each part of speech as an array so that you'd have adjectives[0], etc., is a better design, but for the MadLibs use case, I don't think so.  The adjectives don't really have anything more in common with each other than they do with instances of other parts of speech.


text:
Q: Angular-UI - Transitioning to same state updates URL but back button broken I have the following code in my Ui-router setup
.state('contacts.list', {
    url: "",
    templateUrl: "templates/contactsList.tpl.html",
    controller: "ContactsListCtrl"  contactsFilter: "all"
    }
})
.state('contacts.list.paginated', {
    url: "/page/{pageNumber}",
    templateUrl: "templates/contactsList.tpl.html",
    controller: "ContactsListCtrl"
})

Then I have an Angular-ui pagination control which calls this function when the page is changed
$scope.pageChanged = function(pageNumber){

    $state.go("contacts.list.paginated", {pageNumber: pageNumber});

    $scope.listParams.offset = (pageNumber -1) * $scope.itemsPerPage;

    updateList(); // Reloads the data for the new page from the server */

};

This kind of works. When you click from page 1 to page 2 it gets the next page of data from the server, puts it on the page and changes the URL in the address bar to /2. Also, presumably because the two states share the same controller, the controller is not re-executed, this is what I want because I want it to continue executing my $scope.pageChanged() function, which it does.
So far so good. URL updating, data updating.
The problem is that when I click the back button, nothing happens. If hit page 2, 3, then 4 and then hit the back button the URL changes back to /page3 as expected, but the controller code is not executed and the pagination control is not updated and no call is made to the sever to get the correct data.
Also, if you are already in this view, manually typing /page/2 or /page/3 into the address bar causes no code to be executed, presumably because it's just a change of params.
I need to find a way of either getting it to re-execute the controller code when you use the back/forward button, or listening out for the change in state/location so that I can refresh the data when this happens (but not run it twice when you hit the page for the first time).
I have scoured SO and the rest of the web but cannot find any clues.

A: Try injecting the $rootScope into your controller and listening for the $stateChangeSuccess even like so:
$rootScope.$on('$stateChangeSuccess', function() {
    $scope.listParams.offset = (pageNumber -1) * $scope.itemsPerPage;
    updateList(); // Reloads the data for the new page from the server */
});

A: OK, I think I have a solution.
The solution to getting the back button to work was to do this...
$scope.$watchCollection('$stateParams', function(){

    ... calculate page number and offet here...

    updateList();

});

This triggers every time you use $state.go() AND every time you use the browser back and forward button, as opposed to putting it in your controller code which is not re-executed when you hit the back button.
The problem I had initially with this approach was that sometimes I was updating my results separately and the state was changing so my watch was getting triggered and my AJAX code was being called twice. The key was to never update the list of results outside of this watch and make sure every time you want them to update you change the state or the state params first.


text:
Q: Download certain user's files from SharePoint online My company has buisness account and domain like \<company>.sharepoint.com
So each employee has his own OneDrive space like
\<company>-my.sharepoint.com
We have special account to manage our documents that are stored on it's own onedrive like this
files stored on emploee onedrive
I tried SharePoint CSOM, Microsoft Graph API and SharePointAPI. Using any of it i can get file-related data like name, last change date etc.
But when I try to download it using something like this:
var file = clientContext.Web.GetFileByUrl(<url to file>);
var fileStream = file.OpenBinaryStream();
clientContext.ExecuteQuery();

I have exception

File Not Found

Even using https://developer.microsoft.com/en-us/graph/graph-explorer i can't reach my files
also using SharePoint CSOM I can download file from
<company>.sharepoint.com/Shared%20Documents/Forms/AllItems.aspx
Is there a way to download files directly from employee documents library, or it's forbbiden and i should move all files to SharePoint 'Communication site' documents?

A: I solwed the problem by using Azure Active Directory App like in this tutorial
https://learn.microsoft.com/en-us/graph/auth-v2-service


text:
Q: Possible event bug in Node.js? I think I've been suffering from a very strange bug. There might be something systematically broken with EventEmitter. Ever since I started using the once function things seem off.
The following lines of console output demonstrate what's happening:
var EventEmitter = require('events').EventEmitter;
a = new EventEmitter();
a.on("bla", function() { console.log("perm");});
a.once("bla", function() { console.log("this is temp"); });
a.emit('bla');

You would expect both events to be called, but on my console the output is:
> a.emit("bla")
perm
perm
true

What's going on??
I've also tried using the code in a script and that seemed to work but I'm getting the feeling that the once function is somehow responsible for the weird glitches on my server.
Anyone ever encountered this?
[Tested on versions 0.5.1 and 0.5.3]

A: Works for me on 0.5.10. I'm pretty sure you typed something else than what you posted here - where could the second "perm" come from? Try it again.
$ node
> var EventEmitter = require('events').EventEmitter;
> a = new EventEmitter();
{}
> a.on("bla", function() { console.log("perm");});
{ _events: { bla: [Function] } }
> a.once("bla", function() { console.log("this is temp"); });
{ _events: { bla: [ [Function], [Object] ] } }
> a.emit('bla');
perm
this is temp
true
>


text:
Q: Rails 3 - select data from 3 tables I have these 3 models:
class Car < ActiveRecord::Base
  belongs_to :user
  has_many :car_styles
  has_many :styles, :through => :car_styles
end

class CarStyle < ActiveRecord::Base
  belongs_to :car
  belongs_to :style
end

class UserStyle < ActiveRecord::Base
  belongs_to :style
  belongs_to :user
end

class User < ActiveRecord::Base
  has_many :cars

  has_many :car_styles
  has_many :styles, :through => :car_styles

end
I have logged-in a user (current_user). I am trying to select all cars, where car style_id are the same like user style_id -- how can I do that?
Thanks for help in advance
EDIT: schema:
cars
-id
-user_id

car_styles
-car_id
-style_id

user_styles
-user_id
-style_id

Every user has saved favorite styles - doesn't matter how much (but approximately ±5). Every photo has added a styles as well - and again doesn't matter how much.
And I would like to select all cars from table Cars, which have the same styles, as the current_user has added.

A: I think what you're saying here is you have three main models:
Car, User and Style
CarStyle and UserStyle are joins right?
If so, you should be able to say:
Car.joins(:styles => [:users]).where(:users => {:id => current_user.id })

If not, could you update the question with your schema?


text:
Q: Proof that if T is Transitive Tournament T Has Unique Hamiltonian Path A few of us have been looking to prove this but we've been struggling. We've found some proofs online that prove in the wrong direction (if T has unique path then T is transitive).
If you could point us in the right direction or just give us something to work with that would be great just we're completely stumped.
Thanks everyone.

A: By the comments, you're satisfied that $T$ has a Hamiltonian path; you just don't know that it's unique.
Suppose $T$ has multiple distinct Hamiltonian paths; label the vertices so there are two paths $H_1=p_1\dots p_n$, $H_2=p_{\pi(1)}\dots p_{\pi(n)}$ where $\pi$ is a non-identity permutation.
Since $T$ is transitive, there is an arc from $p_i$ to $p_j$ whenever $j > i$. Since  $\pi$ is a non-identity permutation, there must be some $i, j$ such that $j > i$ but $\pi(i) > \pi(j)$. Can you obtain a contradiction?


text:
Q: Delete all but header and first visible row I've been tasked with removing duplicates from a dataset, but in a specific way; I need to apply a filter with two criteria, then remove all visible rows except the first one, which I will be editted on the fly.
I'm sure the solution rests with a loop filtering each criteria and deleting the relevant rows. However, I'm not sure how to go about it. Using offset is no good; setting and offsetting a range from used & visible cells doesn't seem to work; it always offsets from row 1, not the visible rows.
The range Dive is from the sheet WS, not the "Compilation Sheet" where the autofilter and duplication removal is taking place.
    Sub Dupe_killer()

Dim List As Worksheet
Dim Dive As Range
Dim Hit As Range
Set List = Sheets.Add
Dim aRow As Range
Dim fRow As Range
Dim lRow As Range
Dim r As Range
Dim Rng As Range
Dim FilterRange As Range

With Application
    .ScreenUpdating = False
    .EnableEvents = False
    .Calculation = xlCalculationManual
    .DisplayAlerts = False
End With

Worksheets("Compilation Sheet").Activate

If ActiveSheet.FilterMode = False Then
    ActiveSheet.Range("A1:bc1").AutoFilter
End If

ActiveWorkbook.Worksheets("Compilation Sheet").AutoFilter.Sort.SortFields.Clear
ActiveSheet.Range("$A$1:$BC$11188").AutoFilter Field:=2, Criteria1:=RGB(255 _
    , 0, 255), Operator:=xlFilterCellColor

List.Range("A:A").Value = Worksheets("Compilation Sheet").Range("B:B").Value
List.Range("A:A").RemoveDuplicates Columns:=Array(1)

Set r = List.Range("A2")
Set Dive = Range(r, r.End(xlDown))

For Each Hit In Dive
    With Worksheets("Compilation Sheet")
    .Range("A1:BC1").AutoFilter Field:=2, Criteria1:=Hit
    .Range("A1:BC1").AutoFilter Field:=10, Criteria1:="*", Criteria2:="*,*", Operator:=xlAnd
    End With
    Set FilterRange = ActiveSheet.UsedRange.Offset(2, 0) _
    .SpecialCells(xlCellTypeVisible)
    FilterRange.Select
Next Hit

With Application
    .ScreenUpdating = True
    .EnableEvents = True
    .Calculation = xlCalculationAutomatic
    .DisplayAlerts = True
End With

End Sub

A: You want to set the range in Dive to be only the visible rows.
Google the syntax for
.SpecialCells(xlCellTypeVisible)

A: I think i've cracked it. Found a nifty bit of code for selecting the first visible cell. I could then hide that row and delete all visible.
Range("A2", Cells(Rows.Count, "A").End(xlUp)).SpecialCells(xlCellTypeVisible).Cells(1, 1).Select
ActiveCell.EntireRow.Hidden = True
ActiveSheet.UsedRange.SpecialCells(xlCellTypeVisible).Delete


text:
Q: How can i match a file and get its path and date in cygwin ls -R "all.xml"  //host1//dw/fold
i am trying to use this command to find all.xml file in the fold directory and its subsequent directories but i am getting all the files present in that directory and its sub directories , is there any way i can find and list all the all.xml file with timestamp and its path using ls command

A: On bash, leverage globstar for recursive directory traversal with glob pattern **:
shopt -s globstar
ls -l /path/to/fold/**/all.xml

Disable globstar (shopt -u globstar) or run the above in a subshell, if you want:
( shopt -s globstar && ls -l /path/to/fold/**/all.xml )

Or use find with -ls action to list the file attributes:
find /path/to/fold/ -type f -name all.xml -ls

A: As you on cygwin make sure that you are able to apply bash's find command instead of Windows find command:
find //host1//dw/fold -type f -name "all.xml" -printf "%p\t%t\n"

*

*%p - File's name

*%t - File's last modification time in the format returned by the C ctime function


text:
Q: Nested `mdframed` environments and footnotes Suppose that you have two mdframed environments, one nested inside the other, and a footnote in the first mdframed environment but not in the second.  See the MWE example below.

\documentclass{article}

\usepackage{mdframed}

\begin{document}

\begin{mdframed}
Test frame\footnote{Test footnote}
\begin{mdframed}
Test nested frame
\end{mdframed}
\end{mdframed}

\end{document}

And here is what the same example looks like without the \footnote command.

There are (at least) two problems here.  The first of course is that, with the footnote, the nested mdframed environment is too large and goes outside the right margin.  The second problem is that, as the footnote appears in the first mdframed environment, it should be appearing at the end of the first mdframed environment, not the second.  I suspect these problems are related (it's probably worth noting that if you move the footnote command into the second mdframed environment, everything is the correct size).
Any idea what's going on here or how to fix it?

A: Use tcolorbox instead of mdframed:

\documentclass{article}
\usepackage{tcolorbox}
\begin{document}
\begin{tcolorbox}[arc=0mm,boxrule=1pt,colback=white]
Test frame\footnote{Test footnote}
\begin{tcolorbox}[arc=0mm,boxrule=1pt,colback=white]
Test nested frame
\end{tcolorbox}
\end{tcolorbox}
\end{document}


text:
Q: Audio MP2 encoding and decoding producing half data C++ and FFMPEG I have 16 bit PCM data with stereo setup which I grab from a microphone.
Once I get the data I encode it using the following encoder settings
AVCodec* audio_codec = avcodec_find_encoder(AV_CODEC_ID_MP2);

AVCodecContext* audio_codec_ctx = avcodec_alloc_context3(audio_codec);
audio_codec_ctx->bit_rate = 64000;
audio_codec_ctx->channels = 2;
audio_codec_ctx->channel_layout = AV_CH_LAYOUT_STEREO;
audio_codec_ctx->sample_rate = 44100;
audio_codec_ctx->sample_fmt = AV_SAMPLE_FMT_S16;

When I pass the audio data into the encoder I see that it takes 4608 bytes of data each time and encodes it correctly to MP2 data.  PCM data grabbed by the microphone is 88320 bytes and the encoder takes 4608 bytes each time and compresses it.
If I take each 4608 byte section that has been encoded and pass it through a decoder with the same settings as above but with a decoder.
AVCodecID audio_codec_id = AV_CODEC_ID_MP2;
AVCodec * audio_decodec = avcodec_find_decoder(audio_codec_id);

audio_decodecContext = avcodec_alloc_context3(audio_decodec);
audio_decodecContext->bit_rate = 64000;
audio_decodecContext->channels = 2;
audio_decodecContext->channel_layout = AV_CH_LAYOUT_STEREO;
audio_decodecContext->sample_rate = 44100;
audio_decodecContext->sample_fmt = AV_SAMPLE_FMT_S16;

The decoding works and is successful but when I look at the data size it is exactly half 2034 of what was encoded.  I dont understand why that would be.  I would of imagined I would get 4608 considering the encoder and decoder are the same.
Can anyone shed some light into why this would be happening.  Anything I should be setting?

A: The requested decoder sample format should be set using audio_decodecContext->request_sample_fmt. sample_fmt is set by the decoder itself, and may be different, in which case you should use libswresample to convert between sample formats.


text:
Q: conditional mutate by dplyr I want to create a new column in my dataset that: i) drop the last 1 character if the word itself starts with "vi"; and ii) drop the last 2 characters if the word itself does not start with "vi". I know how to work on that in R, like below:
iris$Species <- as.character(iris$Species)
iris$Species_mod <- substr(iris$Species,
                           1,
                           ifelse(grepl('^vi',iris$Species),
                                  nchar(iris$Species)-1,
                                  nchar(iris$Species)-2))

But I have a hard time in deciphering the mutate, if_else and matches in dplyr. Can anyone enlighten me? Thanks!

A: Same idea, except you explicitly need to convert your factor to a string
iris = mutate(iris, Species_mod = substr(Species, 1, nchar(as.character(Species)) -
    ifelse(grepl('^vi', Species), 1, 2)))

A: you can try something like:
iris %>%
  mutate(Species = as.character(Species))  %>%
  rowwise() %>%
  mutate(species2 = case_when(
    Species == 'vi%' ~ substr(Species, 0, nchar(Species) - 1),
    Species != 'vi%' ~ substr(Species, 0, nchar(Species) - 2)
  ))


text:
Q: using std::function in a std::map I have a class...
#include <map>
#include <boost/function.hpp>

enum class ECmd { one, two, three };

class C
{
public:

    void Command(ECmd e)
    {
        auto pos = m_fnCmd.find(e);

        if (pos != m_fnCmd.end())
        {
            // call the function
            (pos->second)(this);
         }
        else
        {
            printf("no command!\n");
        }
    }

protected:
    using fnCmd = boost::function<void(C*)>;
    using fnCmdMap = std::map<ECmd, fnCmd>;

    static const fnCmdMap m_fnCmd;

    // the command functions
    void One() { printf("one.\n"); }
    void Two() { printf("Two.\n"); }
    void Three() { printf("Three.\n"); }
};

const C::fnCmdMap C::m_fnCmd =
{
    {std::make_pair(ECmd::one, &C::One)},
    {std::make_pair(ECmd::two, &C::Two)},
    {std::make_pair(ECmd::three, &C::Three)},
};

Which demonstrates a technique i use for processing id based commands. This code works just fine, however when i change the class to use std::function instead of boost::function it fails to compile - does not like initializing C::m_fnCmd.
The error message is:
1>c:\program files (x86)\microsoft visual studio 12.0\vc\include\functional(506): error C2664: 'void std::_Func_class<_Ret,C *>::_Set(std::_Func_base<_Ret,C *> *)' : cannot convert argument 1 from '_Myimpl *' to 'std::_Func_base<_Ret,C *> *'
1>          with
1>          [
1>              _Ret=void
1>          ]
1>          Types pointed to are unrelated; conversion requires reinterpret_cast, C-style cast or function-style cast
1>          c:\program files (x86)\microsoft visual studio 12.0\vc\include\functional(442) : see reference to function template instantiation 'void std::_Func_class<_Ret,C *>::_Do_alloc<_Myimpl,_Fret(__thiscall C::* const &)(void),_Alloc>(_Fty,_Alloc)' being compiled
1>          with
1>          [
1>              _Ret=void
1>  ,            _Fret=void
1>  ,            _Alloc=std::allocator<std::_Func_class<void,C *>>
1>  ,            _Fty=void (__thiscall C::* const &)(void)
1>          ]
1>          c:\program files (x86)\microsoft visual studio 12.0\vc\include\functional(442) : see reference to function template instantiation 'void std::_Func_class<_Ret,C *>::_Do_alloc<_Myimpl,_Fret(__thiscall C::* const &)(void),_Alloc>(_Fty,_Alloc)' being compiled
1>          with
1>          [
1>              _Ret=void
1>  ,            _Fret=void
1>  ,            _Alloc=std::allocator<std::_Func_class<void,C *>>
1>  ,            _Fty=void (__thiscall C::* const &)(void)
1>          ]
1>          c:\program files (x86)\microsoft visual studio 12.0\vc\include\functional(442) : see reference to function template instantiation 'void std::_Func_class<_Ret,C *>::_Reset_alloc<_Fret,C,,std::allocator<std::_Func_class<_Ret,C *>>>(_Fret (__thiscall C::* const )(void),_Alloc)' being compiled
1>          with
1>          [
1>              _Ret=void
1>  ,            _Fret=void
1>  ,            _Alloc=std::allocator<std::_Func_class<void,C *>>
1>          ]
1>          c:\program files (x86)\microsoft visual studio 12.0\vc\include\functional(442) : see reference to function template instantiation 'void std::_Func_class<_Ret,C *>::_Reset_alloc<_Fret,C,,std::allocator<std::_Func_class<_Ret,C *>>>(_Fret (__thiscall C::* const )(void),_Alloc)' being compiled
1>          with
1>          [
1>              _Ret=void
1>  ,            _Fret=void
1>  ,            _Alloc=std::allocator<std::_Func_class<void,C *>>
1>          ]
1>          c:\program files (x86)\microsoft visual studio 12.0\vc\include\functional(671) : see reference to function template instantiation 'void std::_Func_class<_Ret,C *>::_Reset<void,C,>(_Fret (__thiscall C::* const )(void))' being compiled
1>          with
1>          [
1>              _Ret=void
1>  ,            _Fret=void
1>          ]
1>          c:\program files (x86)\microsoft visual studio 12.0\vc\include\functional(671) : see reference to function template instantiation 'void std::_Func_class<_Ret,C *>::_Reset<void,C,>(_Fret (__thiscall C::* const )(void))' being compiled
1>          with
1>          [
1>              _Ret=void
1>  ,            _Fret=void
1>          ]
1>          c:\program files (x86)\microsoft visual studio 12.0\vc\include\utility(157) : see reference to function template instantiation 'std::function<void (C *)>::function<_From>(_Fx &&)' being compiled
1>          with
1>          [
1>              _From=void (__thiscall C::* )(void)
1>  ,            _Fx=void (__thiscall C::* )(void)
1>          ]
1>          c:\program files (x86)\microsoft visual studio 12.0\vc\include\utility(157) : see reference to function template instantiation 'std::function<void (C *)>::function<_From>(_Fx &&)' being compiled
1>          with
1>          [
1>              _From=void (__thiscall C::* )(void)
1>  ,            _Fx=void (__thiscall C::* )(void)
1>          ]
1>          c:\projects\test\fntest\fntest.cpp(60) : see reference to function template instantiation 'std::pair<const _Kty,_Ty>::pair<ECmd,void(__thiscall C::* )(void),void>(std::pair<ECmd,void (__thiscall C::* )(void)> &&)' being compiled
1>          with
1>          [
1>              _Kty=ECmd
1>  ,            _Ty=C::fnCmd
1>          ]
1>          c:\projects\test\fntest\fntest.cpp(60) : see reference to function template instantiation 'std::pair<const _Kty,_Ty>::pair<ECmd,void(__thiscall C::* )(void),void>(std::pair<ECmd,void (__thiscall C::* )(void)> &&)' being compiled
1>          with
1>          [
1>              _Kty=ECmd
1>  ,            _Ty=C::fnCmd
1>          ]
1>

A: It works with GCC and Clang (see Jonathan's comment). To make it work in VS2013, you can add std::mem_fn() around the pointers to the member functions:
const C::fnCmdMap C::m_fnCmd =
{
    {std::make_pair(ECmd::one, std::mem_fn(&C::One))},
    {std::make_pair(ECmd::two, std::mem_fn(&C::Two))},
    {std::make_pair(ECmd::three, std::mem_fn(&C::Three))},
};

See VS2013 std::function with member function


text:
Q: Displaying rotatable 3D plots in IPython or Jupyter Notebook (Mac OSX 10.10.5)
I can reproduce from the matplotlib website mplot3d the example code for a 3D scatter plot scatter3d_demo.py, however the plot renders as a static image. I can not click on the graph and dynamically rotate to view the 3D plotted data.
I have achieved the static 3D plot using the example code - using (a) ipython from within Terminal, (b) ipython notebook from within terminal, and (c) ipython notebook launched from the Anaconda launcher.
I think I am missing some very basic step as assumed knowledge.
In past learning, plotting has opened a GUI Python App which has a graph viewer. (Solution 2 in code shown below opens this.) Perhaps I need to know the code to export the output graph to that display method? (Yes, use %matplotlib (only) as first line without inline or notebook as shown in comments in code block below.)
As an example in ipython notebook:
    # These lines are comments
    # Initial setup from an online python notebook tutorial is below.
    # Note the first line "%matplotlib inline" this is how the tutorial has it.
    # Two solutions 1. use: "%matplotlib notebook" graphs appear dynamic in the notebook.
    #               2. use: "%matplotlib" (only) graphs appear dynamic in separate window.
    #    ( 2. is the best solution for detailed graphs/plots. )

    %matplotlib inline
    import pandas as pd
    import numpy as np
    import matplotlib as mpl
    import matplotlib.pyplot as plt
    from mpl_toolkits.mplot3d import Axes3D

    pd.set_option('html',False)
    pd.set_option('max_columns',30)
    pd.set_option('max_rows',10)

    # What follows is a copy of the 3D plot example code.
    # Data is randomly generated so there is no external data import.

    def randrange(n, vmin, vmax):
        return (vmax-vmin)*np.random.rand(n) + vmin

    fig = plt.figure()
    ax = fig.add_subplot(111, projection='3d')
    n = 100
    for c, m, zl, zh in [('r', 'o', -60, -25), ('b', '^', -30, -5)]:
        xs = randrange(n, 23, 50)
        ys = randrange(n, 0, 100)
        zs = randrange(n, zl, zh)
        ax.scatter(xs, ys, zs, c=c, marker=m)

    ax.set_xlabel('X Label')
    ax.set_ylabel('Y Label')
    ax.set_zlabel('Z Label')

    plt.show()

Can someone identify what I am missing?
Looking at Python 3.3.6 documentation, section 25.1perhaps the tkinter package ...

The tkinter package ("Tk interface") is the standard Python interface to the Tk GUI toolkit. Both Tk and tkinter are available on most Unix platforms, as well as on Windows systems.

I think though, this relates to development of GUI programs so I am not sure this is relevant.  (Correct, this was not needed for the solution.)

A: Use %matplotlib notebook instead of %matplotlib inline to get embedded interactive figures in the IPython notebook – this requires recent versions of matplotlib (1.4+) and IPython (3.0+).

A: For Colab environments, I've found the HTML() function to be the most useful:

from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as plt
from numpy.random import rand
from IPython.display import HTML
from matplotlib import animation

m = rand(3,3) # m is an array of (x,y,z) coordinate triplets

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

for i in range(len(m)): # plot each point + it's index as text above
  x = m[i,0]
  y = m[i,1]
  z = m[i,2]
  label = i
  ax.scatter(x, y, z, color='b')
  ax.text(x, y, z, '%s' % (label), size=20, zorder=1, color='k')

ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z')

def animate(frame):
  ax.view_init(30, frame/4)
  plt.pause(.001)
  return fig

anim = animation.FuncAnimation(fig, animate, frames=200, interval=50)
HTML(anim.to_html5_video())

A: For Windows ( Windows 8.1 for me ), you can use
%matplotlib inline
%matplotlib notebook
%pylab

instead.
Note: You must execute  ALL THREE command together, or You will get a kernal died error and then the notebook will restart automatically.

A: After you add:
%matplotlib inline
%matplotlib notebook
%pylab

and if everything is still in 2D you have to just use this option (in red on second image) to drag and rotate graph around and your 3D image will show up:
Before:

After:

I'm using Windows 10 and Jupyter Notebook 6.0.2.

A: For those with even less familiarity, like myself, quick answer is:
%matplotlib  (above imports)(for interactive graphs in new window)
import matplot... etc.
%matplotlib notebook (for graph interaction within JupyterNotebook itself
import etc...
import etc...

A: On Windows, I can make the plot show up in interactive mode by starting the notebook with:
from matplotlib import use
use("Qt5Agg")
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
...

If needed, shutdown your notebook and restart it.