text:
Q: What is the most efficient way to get a list of featureclasses from a large ArcSDE database? I have a SDE DB which consists of 40 feature datasets and around 300 featureclasses.  I need to get the full list of all featureclasses whose name does not contain "ARCHIVE". It takes several minutes using the script below. It will be unacceptable if I publish this as a geoprocessing service. How can this be improved?
import arcpy,os
import json
from arcpy import env

env.workspace=r"C:\ysde\lcimrl.sde"
arcpy.AddMessage("--------get resource dataset \n")

resourceFeatureList=[]
lodFeatureList=[]
dsList = arcpy.ListDatasets("*","Feature")
for ds in dsList:
    dsDesc = arcpy.Describe(ds)
    dsName=dsDesc.name.upper()
    arcpy.AddMessage("--------get feature class list from "+dsName+" \n")

    fcList = arcpy.ListFeatureClasses("*","",ds)
    print fcList
    for fc in fcList:
        desc = arcpy.Describe(fc)
        fcName=desc.name.upper()
        #print dsName+"_"+fcName
        if   "ARCHIVE" not in fcName:
            if dsName!="SDE.ALTERNATIVES":
                resourceFeatureList.append(fc)
            else:
                lodFeatureList.append(fc)
print resourceFeatureList
print lodFeatureList

A: Just from running a quick test it seems like the arcpy.descibe method might be the source of your slow-down.  Since all you are using it for is returning the name of your feature class, it is redundant, as you get the name when you use ListFeatureClasses.  Try this and see if it speeds up your process:
import arcpy,os
import json
from arcpy import env

env.workspace=r"C:\ysde\lcimrl.sde"
arcpy.AddMessage("--------get resource dataset \n")

resourceFeatureList=[]
lodFeatureList=[]
dsList = arcpy.ListDatasets("*","Feature")
for ds in dsList:
    arcpy.AddMessage("--------get feature class list from "+ds+" \n")

    fcList = arcpy.ListFeatureClasses("*","",ds)
    print fcList
    for fc in fcList:
        if   "ARCHIVE" not in fc.upper():
            if ds.upper() !="SDE.ALTERNATIVES":
                resourceFeatureList.append(fc)
            else:
                lodFeatureList.append(fc)
print resourceFeatureList
print lodFeatureList


text:
Q: Collapse bootstrap nav bar on click in nav-items. in mobile viewport I'm a noob in bootstrap.
In simple bootstrap nav bar, I wanted it to collapse when the user clicks on the nav-item as well. so I made changes given below.

      <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navbar-collapse-1">
        Toggle navigation

      </button>
        RAHUL SONI

About

Survey

It worked as I wanted. But data-toggle="collapse" data-target="#navbar-collapse-1" that i have added in anchor tag also come in action when my nav-bar is in normal state.

My code snippet

Please give suggestions.

A: now see your data does not toggles  is this you wanted:

       <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

      <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navbar-collapse-1">
        Toggle navigation

      </button>
        RAHUL SONI

About

Survey

redpajama_set_name: RedPajamaStackExchange


text:
Q: can delegates called on instance methods? Can a delegate be called only on static methods.  I ran below code and got error as Method name expected at lines

NuOp nuopAdd = new NuOp   (x.Addition(324324, 4324324));
NuOp nuopMultiply = new NuOp(x.Multiplication(4324, 24234));

namespace DelegateEtAl
{
    public delegate double NuOp(double a, double b);

    class Program
    {
        static void Main(string[] args)
        {
            Mop x = new Mop();
            NuOp nuopAdd = new NuOp   (x.Addition(324324, 4324324));
            NuOp nuopMultiply = new NuOp(x.Multiplication(4324, 24234));

            Console.Out.WriteLine(nuopAdd);
            Console.Out.WriteLine(nuopMultiply);
        }
    }

    public class Mop
    {
        public double Addition(double opA, double opB)
        {
            return opA + opB;
        }

        public double Multiplication(double opA, double opB)
        {
            return opA + opB;
        }
    }
}

When googled all the examples i found were dealing with only static methods.  but the below link states
https://msdn.microsoft.com/en-us/library/aa288459(v=vs.71).aspx

For static methods, a delegate object encapsulates the method to be
called. For instance methods, a delegate object encapsulates both an
instance and a method on the instance.

Thanks.

A: You can call a delegate in either a static or not static method. There isn't any such a restriction. However, you have to do it as below:
NuOp nuopAdd = x.Addition;
NuOp nuopMultiply = x.Multiplication;

Console.Out.WriteLine(nuopAdd(324324, 4324324));
Console.Out.WriteLine(nuopMultiply(4324, 24234));

The problem with the way you used your delegates is the fact that you didn't initialized them correctly. This is clear if you read the definition of a delegate here:

A delegate is a type that represents references to methods with a
  particular parameter list and return type. When you instantiate a
  delegate, you can associate its instance with any method with a
  compatible signature and return type. You can invoke (or call) the
  method through the delegate instance.

For further info in how we use a delegate please have a look here.
In a few words, the delegate NuOp can point to any method, which takes two parameters of type double and return a double. In order you instatiate you delegate NuOp you just jave to assign the signature of such a method in NuOp like above.


text:
Q: Virtually adjusting screen size and position I'm working on a display piece which is an LCD monitor that is partially covered and needs to be running an application in full screen in the uncovered portion of the screen.
I have tried xvidtune on linux which gives me mode errors and switchresx on macosx which only seems to change resolution but not reposition nor resize (it stretches to full screen anyways).
I'm wondering if there's anyway to do this? Practically, I have access to any OS.

A: The way I ended up doing this was by converting the visuals to video and using processing.org to write up a quick player to resize, position and play it. Unfortunately performance for HD playback was significantly less than VLC and there was no audio, but it worked.


text:
Q: Setting PyDev "Search" to case insensitive by default I know this sounds like a newbie question, but I've been using PyDev for years and never run into this till now. I've searched Google for hours to no available. I feel like I'm overlooking something really simple, but...
In PyDev, when I search (ctrl-H), the dialog box always has "Case Sensitive" checked when it first comes up. I'm 99.5% sure this didn't use to be the case for me. However, I cannot seem to locate the setting that turns off Case Sensitive by default.
Thanks,
Matt

A: Well, this doesn't seem to happen to me... when I do Ctrl+H the case-sensitive is unchecked. Which PyDev/Eclipse versions are you using? Which OS? Do you have some error in your error log? (see http://pydev.org/faq.html for how to get it)
p.s.: Note that in an existing search it'll reload the configuration you used last for it.


text:
Q: Banach fixed point theorem application for continuous functions on [0,1] The question asks to show there exists a unique f(x) on [0,1] such that this equation holds:

We define psi as such to show psi is a contraction and conclude it has a fixed point f(x), which is unique.
I get stuck with the algebra following the distance between the distance between two functions, f and g, under psi.
Thanks,

A: The set $X=C([0,1])$ of continuous functions on $[0,1]$ with the metric
$$
d(f,g)=\sup_{0\le x\le1}|f(x)-g(x)|
$$
is a complete metric space. If $f\in X$, then $\psi\,f$ is a continuous function and $\psi\,f\in X$. Let $f,g\in X$. Then
$$\begin{align}
|(\psi\,f)(x)-(\psi\,g)(x)|&\le\int_0^1|f(x\,t)-g(x\,t)|\,t^2\,dt+\frac12|\cos f(x)-\cos g(x)|\\
&\le d(f,g)\int_0^1t^2\,dt+\frac12\,d(f,g)\\
&=\Bigl(\frac13+\frac12\Bigr)\,d(f,g).
\end{align}$$
We have shown
$$
d(\psi\,f,\psi\,g)\le\frac56\,d(f,g).
$$


text:
Q: How to know the number of queries per user in Bigquery? I want to know:

*

*how to get the number of queries a user makes per month in BigQuery?

*how many queries a specific user makes, how many per year.

I found the command
bq ls -j

with that bring the number of jobs and with the comand bq show get the detail, but it does not bring me all the elements that I need, I would like to know if someone knows another way to achieve this.

A: You need to enable Audit Logs, and create a Sink for Bigquery.
Then you can write a query that uses for protoPayload.methodName column one of the google.cloud.bigquery.v2.JobService.Query values
Example: Bytes processed per user identity

This query shows the total bytes billed for query jobs per user, in
terabytes.

 #standardSQL
  WITH data as
  (
    SELECT
      protopayload_auditlog.authenticationInfo.principalEmail as principalEmail,
      protopayload_auditlog.metadataJson AS metadataJson,
      CAST(JSON_EXTRACT_SCALAR(protopayload_auditlog.metadataJson,
          "$.jobChange.job.jobStats.queryStats.totalBilledBytes") AS INT64) AS totalBilledBytes,
    FROM
      `MYPROJECTID.MYDATASETID.cloudaudit_googleapis_com_data_access_*`
  )
  SELECT
    principalEmail,
    FORMAT('%9.2f',SUM(totalBilledBytes)/POWER(2, 40)) AS Billed_TB
  FROM
    data
  WHERE
    JSON_EXTRACT_SCALAR(metadataJson, "$.jobChange.job.jobConfig.type") = "QUERY"
  GROUP BY principalEmail
  ORDER BY Billed_TB DESC


text:
Q: Laravel + Docker Доступ к БД вне контейнера Собственно вопрос заключается из САБЖА.
Имеется развернутый контейнер с приложением Laravel
Также контейнер с Nginx.
Однако одно из основных условий, необходимо подключаться к Базе Данных которая находиться НЕ В ДОКЕРЕ, а просто стоит на этом же сервере.
Как это можно сделать ?
Примеры файлов:
app.dockerfile
FROM php:7-fpm
RUN apt-get update && apt-get install -y libmcrypt-dev mysql-client \
    && docker-php-ext-install pdo_mysql \
    && pecl install mcrypt-1.0.1 docker-php-ext-enable mcrypt
WORKDIR /var/www/main_project/s_crm

web.dockerfile
   FROM nginx:1.10
ADD ./vhost.conf /etc/nginx/conf.d/default.conf
WORKDIR /var/www/main_project/s_crm

docker-compose.yml
    version: '2'

services:
    web:
      build:
        context: ./
        dockerfile: web.dockerfile
      volumes:
        - ./:/var/www/main_project/s_crm
      ports:
        - "8080:80"
      links:
        - app
    app:
      build:
        context: ./
        dockerfile: app.dockerfile
      volumes:
        - ./:/var/www/main_project/s_crm

vhost.conf
server {
    listen 80;
    index index.php index.html;
    root /var/www/main_project/s_crm/public;

    location / {
        try_files $uri /index.php?$args;
    }

    location ~ \.php$ {
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_pass app:9000;
        fastcgi_index index.php;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_param PATH_INFO $fastcgi_path_info;
    }
}

A: Простейший способ указать для каждого сервиса:
network_mode: "host"

Это заставит их использовать не интерфейс по-умолчанию который создается docker-compose автоматически, а интерфейсы самой машины. А значит у тебя будет доступ к loopback интерфейсу (localhost) и всем приложениям что на нем запущены.

A: Проблему решили.
Доступ был организован на БД на другой машине - на ней создали пользователя и дали права на доступ к этой БД от этого юзера с адреса приложения


text:
Q: Narrowing down error type in catch For this piece of code
try {
  throw new CustomError();
}
catch (err) {
  console.log(err.aPropThatDoesNotExistInCustomError);
}

err is any and doesn't trigger type errors. How can it be narrowed down to the type that error is expected to be?

A: You need to perform a check yourself to narrow inside a catch block. The compiler does not know or believe that err will definitely be a CustomError:
try {
  throw new CustomError();
}
catch (err) {
  console.log('bing');
  if (err instanceof CustomError) {
    console.log(err.aPropThatIndeedExistsInCustomError); //works
    console.log(err.aPropThatDoesNotExistInCustomError); //error as expected
  } else {
    console.log(err); // this could still happen
  }
}

For example, here's my evil implementation of CustomError:
class CustomError extends Error {
  constructor() {
    super()
    throw new Error('Not so fast!');  // The evil part is here
  }
  aPropThatIndeedExistsInCustomError: string;
}

In this case err will not be a CustomError.  I know, that's probably not going to happen, but the point is that the compiler won't do this narrowing automatically for you.  If you are absolutely sure of the type, you can assign to another variable:
try {
  throw new CustomError();
}
catch (_err) {
  const err: CustomError = _err;
  console.log(err.aPropThatDoesNotExistInCustomError); // errors as desired
}

but remember that you could possibly run into trouble at runtime if you're mistaken about the type.
Good luck!
P.S.: See TypeScript issues #8677 and #9999 for more information.


text:
Q: Haskell - list traversing I want to traverse list of lists and check every element if its equal a char or not. How can I do this? I get an error even when I write if statement. I would be glad if you can help.
example list that I want to traverse:
maze = [ ['E','#','#','#'],
       [' ','#',' ',' '],
       [' ',' ',' ',' '],
       ['#','#','#','S'] ]

If statement:
checkElement :: Char -> Bool
checkElement x = if x == '#'
  then False
  else True

A: The simplest way to do this is with the map function:
map :: (a -> b) -> [a] -> [b]
map _ []     = []
map f (x:xs) = f x : map f xs

When you want to map over a nested list, you can use (map . map) :: (a -> b) -> [[a]] -> [[b]]:
λ (map . map) checkElement mazes
[ [ False, True , True , True  ]
, [ False, True , False, False ]
, [ False, False, False, False ]
, [ True , True , True , False ] ]

It's also worth noting that if x then False else True can be replaced with not x:
checkElement :: Char -> Bool
checkElement x = not $ x == '#'


text:
Q: Not being able to store a variant in a pointer in c++ My groupmate and I are doing a school assignment and we are having some trouble trying to save a value.
I am 100% aware that some of the things done in the code is not the normal way of doing, and that there are better ways, but part of the assignment is to use the concepts taught in class.
Problem:
I have a Train class which I would like to assign to a platform, such that I know if there is a train on the platform.
template<typename T>
class Train
{
public:
    //Some constructors, getters and other stuff
private:
    std::string reg_nr_;
}

Because the Train is a template there are different template argument classes so it is possible to give it a type
struct IC3{};

struct IC4{};

To instantiate a Train it is done in main in the following way, as is the way it is intended to be used.
Train<IC3> tester_train("testing_train");
Train<IC4> some_other_tester_train("some_other_tester_train");

Platform pl;
pl.train_arriving(tester_train);
pl.train_leaving(tester_train);
pl.train_arriving(some_other_tester_train);

class Platform
{
public:
    using Trains = std::variant<TrainWrapper<Train<Arriva>>, TrainWrapper<Train<IC3>>, TrainWrapper<Train<IC4>>>;

    template<typename U>
    void train_arriving(U& t)
    {
        train_ = TrainWrapper<U>{ u };
    }

    void train_leaving()
    {
        train_ = ???????; //Should be set to nothing
    }
private:
    Trains train_;
}

template<typename T>
struct TrainWrapper
{
    T& t;
};

Now for the real part of the problem.
I have a Train template class which takes an argument and transform the Train in different types which are not compatible. This presents a problem of being able to pass these different train types into the platform and saving them.
To solve the problem of different passing in different types a std::variant has been used. This presented a new problem of not being able to retrieve the data easily, which is why the TrainWrapper is used, such that the Train is stored in a common type.
Tinkering around with the variant (and finally asking our teacher) my groupmate and I arrived Trains expression seen in Platform. We know for a fact (using a local variable) that we are able to save a TrainWrapper in a Trains object. Our problem however is that we would like to be able to change the Train on the Platform. We therefore thought a pointer would be the way forward, but doing this we run into conversion errors like: Error    C2440   '=': cannot convert from 'TrainWrapper<Train<Arriva>>' to 'Platform::Trains *'. We have tried a bunch of different pointer variations, but it is always the same conversion error.
So our question more or less is: How are we able to save Train on the platform so we are able to remove it again?

A: You might use std::monostate to signal empty:
class Platform
{
public:
    using Trains = std::variant<std::monostate,
                                TrainWrapper<Train<Arriva>>,
                                TrainWrapper<Train<IC3>>,
                                TrainWrapper<Train<IC4>>>;

    template<typename U>
    void train_arriving(U& t)
    {
        train_ = TrainWrapper<U>{ u };
    }

    template<typename U>
    void train_leaving(U& )
    {
        train_ = std::monostate{};
    }
private:
    Trains train_;
};

Demo


text:
Q: judge if it's open or not (1)for $(x,y,z) \in \, \mathbb{R}^3, \quad x ^2 + y ^2 < 1, \quad z =0$
judge if this is open, closed, and bounded or not. and give proofs.
I'm not sure whether it's open or not. I think it's open, not closed and bounded. Because whatever neighbouhood you choose, it would certainly contain other points since z is always 0.then if you choose a open ball centered at any point, it would
be 3 dimensional and go beyond the 2-d shape.
(2) judge whether a finite set is bounded, closed, open or not.Is finite set just some finite points?
I'm not sure about the answer either.
What do you guys think?

A: Your argument shows that in case $(1)$, the set is not open. It isn't closed, either (since the boundary is $x^2+y^2=1,z=0$), but it is bounded.
A finite point set is closed (since it has no limit points) and bounded (since the points' distances from the origin have a maximum), and isn't open unless it's empty.

A: $S$ is bounded, not open in $\mathbb{R}^3$. It is only relative open.
See here
http://en.wikipedia.org/wiki/Relative_interior
for definition of relative interior.


text:
Q: Laravel join table with json using MariaDB PHP 7.2
MariaDB 10.3.11
Laravel 5.5.45
https://github.com/beyondcode/laravel-vouchers/issues/10
I am using this package. Inside the vouchers table have a field data
which is store array / json data.
The vouchers table inside the data field type is TEXT.
https://github.com/beyondcode/laravel-vouchers/blob/master/database/migrations/create_vouchers_table.php.stub
E.g
{"customer_id":1,"customer_name":"Shiro","message":"Birthday Voucher"}
Voucher Table:-
+-----+-----------+-----------------+----------+--------------------------------------------------------------------------+---------------------+---------------------+---------------------+
| id  | code      | model_type      | model_id | data                                                                     | expires_at          | created_at          | updated_at          |
+-----+-----------+-----------------+----------+--------------------------------------------------------------------------+---------------------+---------------------+---------------------+
| 170 | 1111-1112 | App\VoucherType |        2 | {"customer_id":"1","customer_name":"Shiro","message":"Birthday Voucher"} | 2019-04-30 23:59:59 | 2019-03-20 04:58:12 | 2019-03-20 04:58:12 |
+-----+-----------+-----------------+----------+--------------------------------------------------------------------------+---------------------+---------------------+---------------------+

Customer Table
+------+----------------------------------------------+----------------------+
| id   | user_name                                    | email                |
+------+----------------------------------------------+----------------------+
| 1    | AMAZON BEAUTY SUPPLY - BEAUTIFUL LADYGAGA HA | beautifyfu@gmail.com |
+------+----------------------------------------------+----------------------+

I would like to join with my customers table.
I tried https://github.com/ybr-nx/laravel-mariadb , but still can't directly join the table.
Any idea how to join two table and one of the table using json field?


text:
Q: Ubuntu Server 16.04 LTS internet not working at all I am running Ubuntu Server 16.04 LTS. anything network related doesn't seem to work. sudo apt-get update says temporary failure to resolve host. curl and ping both just hang when I run them. there is no output at all. I think this started happening when I got a new router.
EDIT:
ping -c4 8.8.4.4
PING 8.8.4.4 (8.8.4.4) 56(84) bytes of data.

--- 8.8.4.4 ping statistics ---
4 packets transmitted, 0 received, 100% packet loss, time 3023ms

ifconfig
Returns
enp2s8    Link encap:Ethernet  HWaddr 00:0c:f1:b3:b6:b0
          inet addr:192.168.2.208  Bcast:192.168.2.255  Mask:255.255.255.0
          inet6 addr: fe80::20c:f1ff:feb3:b6b0/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:478724 errors:0 dropped:0 overruns:0 frame:0
          TX packets:225770 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:54169875 (54.1 MB)  TX bytes:17520767 (17.5 MB)

lo        Link encap:Local Loopback
          inet addr:127.0.0.1  Mask:255.0.0.0
          inet6 addr: ::1/128 Scope:Host
          UP LOOPBACK RUNNING  MTU:65536  Metric:1
          RX packets:203 errors:0 dropped:0 overruns:0 frame:0
          TX packets:203 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1
          RX bytes:15524 (15.5 KB)  TX bytes:15524 (15.5 KB)

tun0      Link encap:UNSPEC  HWaddr 00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00
          inet addr:10.8.0.1  P-t-P:10.8.0.2  Mask:255.255.255.255
          UP POINTOPOINT RUNNING NOARP MULTICAST  MTU:1500  Metric:1
          RX packets:0 errors:0 dropped:0 overruns:0 frame:0
          TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:100
          RX bytes:0 (0.0 B)  TX bytes:0 (0.0 B)

sudo cat /etc/network/interfaces
Returns
# This file describes the network interfaces available on your system
# and how to activate them. For more information, see interfaces(5).

source /etc/network/interfaces.d/*

# The loopback network interface
auto lo
iface lo inet loopback

# The primary network interface
auto enp2s8
iface enp2s8 inet dhcp

The computer is connected with an ethernet cable, and I am running ubuntu server as said in the title meaning I don't have a GUI.
sudo dhclient enp2s8
Returns nothing.
I hope this helps!

A: Connect the pc to the router on an ethernet cable. This eliminates the wireless layer as a source of trouble.
Use that to find out if your router works at all. If it is not getting to the outside world, you will see the trouble like you describe--nothing works.
If ethernet is working on the wire, then problem is wireless driver configuration.
You don't mention which desktop you are using, but most have the Network Manager applet.  That has some GUI configuration.
Also, if you want to understand better what is going wrong, the most general advice is to open a terminal and run "dmesg" to summarize all the system level errors.


text:
Q: Detail disclosure button not appearing on mapkit callout I'm not sure why the detail disclosure button is not appearing on the mapkit callout. Here's my code:
I made sure to include  in the .h file
and then the following methods. The callout works and appears right after the map loads. I also made sure to hook up the delegate in the Xib file.
   - (MKAnnotationView *)mapView:(MKMapView *)map viewForAnnotation:(id <MKAnnotation>)annotation
{
    MKPinAnnotationView *mapPin = nil;
    if(annotation != map.userLocation)
    {
        static NSString *defaultPinID = @"defaultPin";
        mapPin = (MKPinAnnotationView *)[map dequeueReusableAnnotationViewWithIdentifier:defaultPinID];
        if (mapPin == nil )
        {
            mapPin = [[MKPinAnnotationView alloc] initWithAnnotation:annotation
                                                     reuseIdentifier:defaultPinID];
            mapPin.canShowCallout = YES;

            UIButton *disclosureButton = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
            [disclosureButton addTarget:self action:@selector(clDetails:) forControlEvents:UIControlEventTouchUpInside];

            mapPin.rightCalloutAccessoryView = disclosureButton;

        }
        else
            mapPin.annotation = annotation;

    }
    return mapPin;
}

  - (void)mapView:(MKMapView *)mapView didAddAnnotationViews:(NSArray *)views
{
    id<MKAnnotation> myAnnotation = [self.mapView.annotations objectAtIndex:0];
    [self.mapView selectAnnotation:myAnnotation animated:YES];
}

thanks for any help.

A: I had this line of code in viewDidLoad that was  throwing off the MKAnnotation method.
mapView = [[MKMapView alloc]initWithFrame:self.view.bounds];

:)

A: - (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation

{
    // if it's the user location, just return nil.
    if ([annotation isKindOfClass:[MKUserLocation class]])
        return nil;
// try to dequeue an existing pin view first
static NSString* AnnotationIdentifier = @"AnnotationIdentifier";
MKPinAnnotationView* pinView = [[[MKPinAnnotationView alloc]
                                 initWithAnnotation:annotation reuseIdentifier:AnnotationIdentifier] autorelease];
pinView.animatesDrop = YES;
pinView.canShowCallout = YES;
pinView.draggable = NO;
pinView.annotation = annotation;
pinView.draggable = YES;
pinView.enabled = YES;
pinView.exclusiveTouch = YES;
pinView.highlighted = YES;
pinView.multipleTouchEnabled = YES;
pinView.pinColor = MKPinAnnotationColorPurple;
pinView.userInteractionEnabled = YES;

//button on the right for popup for pins
UIButton* rightButton = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
[rightButton setTitle:annotation.title forState:UIControlStateNormal];
[rightButton addTarget:self
                action:@selector(showDetails:)
      forControlEvents:UIControlEventTouchUpInside];
pinView.rightCalloutAccessoryView = rightButton;

 //Create and add the right button to the callout
 rightCalloutButton = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
[pinView setRightCalloutAccessoryView:rightButton];

    [self updateAnnotation];

    [self crawlViews];

//zoom button on the left of popup for pins
UIButton* leftButton = [UIButton buttonWithType:UIButtonTypeContactAdd];
[leftButton setTitle:annotation.title forState:UIControlStateNormal];
[leftButton addTarget:self
               action:@selector(zoomToLocation:) forControlEvents:UIControlEventTouchUpInside];
pinView.leftCalloutAccessoryView = leftButton;

UIImageView *profileIconView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"profile.png"]];
pinView.leftCalloutAccessoryView = profileIconView;
[profileIconView release];

return pinView;

}


text:
Q: Getting variable value from external JavaScript file in jQuery $(document).ready(function(){}); I have defined on external JavaSsript file which contains one variable such as the following
var demo='Hello'".

I want to use this variable's value in jQuery's $(document).ready() event. How can I accomplish this?

A: All you have to do is put the external file above your main script:
<script src="external.js"></script>
<script>
     // "demo" is accessible here
</script>

Script tags load synchronously, so once the second script tag executes, you can be sure the first one has already loaded.
Edit
Per the comment, this script works for me:
<html>
    <script src="global.js"></script>
    <script type="text/javascript" src="http://code.jquery.com/jquery-2.0.3.js"></script>
    <script type="text/javascript">
        $(document).ready(function() { var x=abc(); alert('hello'+x); });
    </script>
</html>

Where global.js is just:
function abc() { var valu='hello'; return valu; }

A: If you have defined that file before the file with the ready event, it should be available providing the scope is correct. ie:
<script type="text/javascript" src="scriptwithvalue.js"></script>
<script type="text/javascript" src="scriptthatwantsthevalue.js"></script>

When I'm passing variables between files, I tend to wrap the logic up in a getter and setter, ie:
File One
var name = "Dave";

function getName()
{
    return name;
}

File Two
var name = getName();

 Edit
As above, if your Javascript is already in the HTML file, then simply importing the script with the value in it is enough.


text:
Q: Name of an inversion-like function for permutations Let $\pi\in S_n$ be a permutation. Define $m_k=|\{i: \ i\leq k, \ \pi(i)>k\}|$. For example, if $\pi=(597216384)$, then it's $m$ vector is $m(\pi):=(m_1,m_2,\ldots,m_{n-1})=(1,2,3,3,2,2,1,1)$. Is there some commonly associated name for $m_k$? In particular, for the sum $M:=\sum_{k=1}^{n-1}m_k$? This function came out of a paper related to reduced words. Quoting the paper, starting from the identity permutation, convert this permutation to $\pi$ by means of adjacent transpositions. Then one can interpret $m_k$ as the least number of times one needs to apply an adjacent swap $(k,k+1)\rightarrow (k+1,k)$.
Also, is there some nice relation between $M,m_k$ and the number of inversions in a permutation: $L(\pi):=\sum_{k=1}^{n-1}L_k(\pi),$ where $L_k(\pi)=\{i:\ i\geq k, \ \pi(k)>\pi(i)\}$? In other words, is there a connection between $m$ vectors and Lehmer codes? If there are no obvious connections between $m_k$ and inversions, are there some crude bounds that one can deduce between $L$and $M$? It seems to me that if one starts with the identity, $M=L$ for the sequence of the first few adjacent transpositions and then they begin to differ.
My inspiration for the latter question is based on the known bijection between major index and inversions.

A: I doubt that this has a name.  I like to refer to a nice table page 388 in Kitaev's book.  If it's not there, it's unlikely this has been widely studied.
S. Kitaev, Patterns in permutations and words, Springer, 2011.


text:
Q: WebApi OData: $filter 'any' or 'all' query not working First, using the ASP.NET WebApi tutorials I've created a basic ApiController that exposes an Entity Framework model through OData. The service works to return json for OData $filter queries.
When I perform OData $filter queries that include "any" or "all" queryies on a multi-value property it throws an ODataException
Here's the OData query I'm trying to use
~/api/Blogs?$filter=any(Tags,Name+eq+'csharp')
My ApiController looks like this:
public class BlogController : ApiController
{
    public BlogsController()
    {
        this.Entities = new BlogEntities();
    }

    public ContactEntities Entities { get; set; }

    [Queryable(PageSize = 25, AllowedQueryOptions = AllowedQueryOptions.All)]
    public IQueryable<Blog> Get()
    {
        return this.Entities.Blogs;
    }
}

The Blog entity has this contract
public Blog {
    public Guid ID { get; set; }
    public string Title { get; set; }
    public Tag Tags { get; set; }
}

public Tag {
    public Guid ID { get; set; }
    public string Name { get; set; }
}

The exception thrown
ODataException: Type 'Blog' does not have a property 'Name'

As you can see, I have nothing out of the ordinary in my code and everything should work fine. Is it possible that "any" and "all" queryies aren't supported yet in Microsoft ASP.NET Web API OData?

A: Your any needs to be changed a bit. Try something like this:
~/api/Blogs?$filter=Tags/any(tag: tag/Name eq 'csharp')

This is assuming Tags actually returns a collection of Tags, not just a single Tag like you have above.
$inlinecount is only supported out of the box for the OData format. I wrote extensively about it here:
Web API OData Inlinecount not working
The short answer is that you can get it working for other formats with code that looks like this:
public PageResult<Customer> Get(ODataQueryOptions<Customer> queryOptions)
{
    IQueryable results = queryOptions.ApplyTo(_customers.AsQueryable());
    return new PageResult<Customer>(results as IEnumerable<Customer>, Request.GetNextPageLink(), Request.GetInlineCount());
}


text:
Q: JavaFX: Get line height of TextArea I have a window/stage and a TextArea which will be resized dependent on the length of the text inside the TextArea (the text is wrapped). This means, the window is smaller, the less the text is inside the TextArea. The width of the TextArea is given. To calculate the height of the TextArea I use the length of the text, the given width of the TextArea and the line height. For example:

double height=textwidth/agreement.getWidth()*18;

In this case the line-height is defined by a static value. But the line height have to be variable dependent on the definitions in the css-file, because the line height changes if the definition of the font size changes. Consequently I need to determine the line height of the TextArea to use it instead of using a static value. So, how can I get the line height of a TextArea?

A: You can find the exact dimensions of the text rendered in the text area, once the stage is shown:
@Override
public void start(Stage primaryStage) {
    TextArea area = new TextArea("This is some random very long text");
    area.setWrapText(true);
    area.setPrefWidth(200);
    area.setMaxWidth(200);
    area.setStyle("-fx-font: 18pt Arial");
    StackPane root = new StackPane(area);

    Scene scene = new Scene(root, 300, 250);

    primaryStage.setScene(scene);
    primaryStage.show();

    Text t = (Text)area.lookup(".text");
    System.out.println("LayoutX "+t.getLayoutX());
    System.out.println("LayoutY "+t.getLayoutY());
    System.out.println("Width: "+t.getBoundsInLocal().getWidth());
    System.out.println("Height: "+t.getBoundsInLocal().getHeight());
}

Based on those dimensions, you can perform your calculations.
EDIT
You can get the dimensions before showing the stage, but for that you need to apply CSS styling to the root and children and force a layout on the scene:
    Scene scene = new Scene(root, 300, 250);

    root.applyCss();
    root.layout();

    Text t = (Text)root.lookup(".text");
    System.out.println("LayoutX "+t.getLayoutX());
    System.out.println("LayoutY "+t.getLayoutY());
    System.out.println("Width: "+t.getBoundsInLocal().getWidth());
    System.out.println("Height: "+t.getBoundsInLocal().getHeight());

    // Now calculations can be performed

    primaryStage.setScene(scene);
    primaryStage.show();


text:
Q: Парсинг json android Во всех примерах в начале стоит вот такого вида конструкция {data:[{....}..
Как парсить такой JSON?
[
{"id":"99111772",
"name":"Иванов Иван Иванович",
"position":"Депутат ГД",
"isCurrent":true,
"factions":[
{"id":"72100004",
"name":"Фракция Политической партии \"Коммунистическая партия Российской Федерации    \"",
"startDate":"2011-12-04",
"endDate":"2017-01-03"}]},

{"id":"99112284",
"name":"Петров Петр Петрович",
"position":"Депутат ГД",
"isCurrent":true,
"factions":[
{"id":"72100024",
"name":"Фракция Всероссийской политической партии \"ЕДИНАЯ РОССИЯ\"",
"startDate":"2013-03-06",
"endDate":"2017-01-03"}]}]

Делаю вот так:
                    deputies = new ArrayList<String>();

                    try {
                        JSONArray data = json.getJSONArray(null);
                        for (int i = 0; i < data.length(); i++) {
                            JSONObject name = data.getJSONObject(i);
                            String n = name.getString("name");
                            deputies.add(n);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

Что мне писать в это строчке кода, null, как я понял, не катит? Или проблема не только в этой строчке? объясните пожалуйста)
JSONArray data = json.getJSONArray(null)

A: Знак [] - означает что это массив. По сути у вас такие Java классы
public class Member {
   String id;
   String name;
   String position;
   boolean isCurrent;
   ArrayList<Fraction> fractions;
}

public class Fraction {
   String id;
   String name;
   Date startDate;
   Date endDate;
}

Чтобы распарсить вам надо использовать Google Gson и вызвать примерно такой код:
Type memberType = new TypeToken<ArrayList<Member>>(){}.getClass();
Gson gson = new Gson();
ArrayList<Member> members = gson.fromJson(jsonString, memberType);

members и будет содержать нужный массив объектов
A: Вот здесь посмотрите, из строки показан перевод в объект и массив json.

Для чтения json ответов от сервера, необходимо импортировать org.json. библиотеку.
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

Метод принимает входящий параметр строку формата json, далее создается объект, из него массив. Имя "data" - есть именем json-массива пришедшего с сервера. Далее в нужные нам места вытягиваем значение элементов по идентификаторам, к примеру как "flag".
public void JSONURL(String result) {

    try {
        JSONObject json = new JSONObject(result);
        final JSONArray urls = json.getJSONArray("data");
        FLAG = urls.getJSONObject(0).getString("flag").toString();
    } catch (JSONException e) {
        Log.e("log_tag", "Error parsing data " + e.toString());
    }
}


text:
Q: Azure Application Gateway HTTP Settings Backend Port Resets to 80 In the Azure Portal, I have created the following Application Gateway with the Backend Pools, Rules, Listeners, and HTTP Settings below.  I want the HTTP Settings to be configured with the backend ports below and have placed the settings in the backend port fields numerous times.  However, when I save the setting, Azure resets the port to 80.  Has anyone run into this issue before?  Please provide any guidance that you may have on how to resolve the issue.
AppGateway
Backend Pools

*

*Pool1 - 2 servers listening on port 80

*Pool2 - 1 server listening on port 8080

*Pool3 - 1 server listening on port 8777

Rules

*

*Rule1 - Listener1 - HTTP1

*Rule2 - Listener2 - HTTP2

*Rule3 - Listener3 - HTTP3

Listeners

*

*Listener1 - multisite - port 80 - domain #1

*Listener2 - multisite - port 80 - domain #2

*Listener3 - multisite - port 80 - domain #3

HTTP Settings

*

*HTTP1 - port 80 - backend port 80

*HTTP2 - port 8080 - backend port 8080

*HTTP3 - port 8777 - backend port 8777

A: Yes I ran into this issue with the portal a couple of weeks ago - going into the edit panel displays the port field value to 80, even though the underlying stored value is different.
If this goes unnoticed when editing a different field, it will update the http settings with the potentially incorrect '80' default.
Therefore if you specify your desired value either in the portal, Az PS, CLI or ARM deployment it will use the port you set.  It's just that edit panel doesn't seem to display the underlying value.


text:
Q: How to write "No file ends with" a user-defined extension I was wondering if there was a way to tell the user that no file in a directory they specified has the file extension they are looking for. The only way I could think of uses an if/else, but would be tripped up if any other file extension exists in the directory. I was able to find something but it was bash: Listing files in a directory that do not end with vXXX and not exactly what I was looking for.
Here is an example of a directory:

out-30000000.txt.processed
out-31000000.txt.processed
out-32000000.txt.processed
out-33000000.txt.processed
out-34000000.txt.processed
nope.csv

If I use the following code:
def folder_location():
    location = raw_input("What is the folder containing the data you like processed located? ")
    #location = "C:/Code/Samples/Dates/2015-06-07/Large-Scale Data Parsing/Data Files"
    if os.path.exists(location) == True: #Tests to see if user entered a valid path
        print "You entered:",location
        if raw_input("Is this correct? Use 'Y' or 'N' to answer. ") == "Y":
            print ""
            file_extension(location)
        else:
            folder_location()
    else:
        print "I'm sorry, but the file location you have entered does not exist. Please try again."
        folder_location()

def file_extension(location):
    file_extension = raw_input("What is the file type (.txt for example)? ")
    print "You entered:", file_extension
    if raw_input("Is this correct? Use 'Y' or 'N' to answer. ") == "Y":
        print ""
        each_file(location, file_extension)
    else:
        file_extension(location)

def each_file(location, file_extension):
    try:
        column = (raw_input("Please enter column name you want to analyze: ")) #Using smcn
        print "You entered:",column
        if raw_input("Is this correct? Use 'Y' and 'N' to answer. ") == "Y":
            print ""
            sort_by(location,file_extension,column)
        else:
            each_file(location,file_extension)
    except TypeError:
        print "That is not a valid column name. Please try again."
        each_file(location,file_extension)

def sort_by(location, file_extension, column):
    content = os.listdir(location)
    for item in content:
        if item.endswith(file_extension):
            data = csv.reader(open(os.path.join(location,item)),delimiter=',')
            col_position = get_columnposition(data.next(),column)
            to_count = sorted(data, key=operator.itemgetter(col_position))
            count_date(to_count, location)
        else:
            print "No file in this directory ends with " + file_extension

I get:
No file in this directory ends with .processed

and then the rest of my output (code not posted here).
Is there a way for me to say (I'm going to put it in a code block just to show how it works in my mind):
def file_extension(location):
    file_extension = raw_input("What is the file type (.txt for example)? ")
    print "You entered:", file_extension
    if raw_input("Is this correct? Use 'Y' or 'N' to answer. ") == "Y":
        print ""
        each_file(location, file_extension)
    else:
        file_extension(location)

def each_file(location, file_extension):
    try:
        column = (raw_input("Please enter column name you want to analyze: ")) #Using smcn
        print "You entered:",column
        if raw_input("Is this correct? Use 'Y' and 'N' to answer. ") == "Y":
            print ""
            sort_by(location,file_extension,column)
        else:
            each_file(location,file_extension)
    except TypeError:
        print "That is not a valid column name. Please try again."
        each_file(location,file_extension)

def sort_by(location, file_extension, column):
    content = os.listdir(location)
    for item in content:
        if item.endswith(file_extension):
            data = csv.reader(open(os.path.join(location,item)),delimiter=',')
            col_position = get_columnposition(data.next(),column)
            to_count = sorted(data, key=operator.itemgetter(col_position))
            count_date(to_count, location)
        if no item.endswith(file_extension):
            print "No file in this directory ends with " + file_extension

Any help would be greatly appreciated. If it would help, I could edit in the rest of my code I have at the moment.
Thanks!

A: Your logic should be the following:

*

*Ask for the directory

*Ask for the extension

*Check if any file ends with that extension

*If there is at least one file, then ask for the column

To make all this easier, use csv and glob:
import glob
import csv
import os

directory = input('Please enter the directory: ')
extension = input('Please enter the extension (.txt, .csv): ')
files = list(glob.glob(os.path.join(directory, extension)))
if not files:
   print('Sorry, no files match your extension {} in the directory {}'.
         format(extension, directory))
else:
    for file_name in files:
        col = input('Enter the column number for {}'.format(file_name))
        with open(file_name, 'r') as thefile:
            reader = csv.reader(thefile, delimiter=',')
            for row in reader:
                try:
                    do_something(row[col])
                except IndexError:
                    print('Column {} does not exist'.format(col))


text:
Q: JDBC DatabaseMetaData method not implemented by JDBC(T4SQLMX) driver I am setting up a Spring-boot application to connect to HP NonStop Tandem's SQL/MX. First I achieved this connection by hard-coding the jdbc parameters like dataSource, URL, etc in the service section of the application and it worked (I was able to access tables by executing query).
Now I am trying to remove the hard coded part and have my database related info in application.properties file, but now I am getting the following error
org.springframework.jdbc.support.MetaDataAccessException: JDBC DatabaseMetaData method not implemented by JDBC driver - upgrade your driver; nested exception is java.lang.AbstractMethodError: Method com/tandem/t4jdbc/SQLMXConnection.isValid(I)Z is abstract
Can someone help me understand the root cause? The same driver jar is being used when hard-coding the datasource details and it worked but not working when having the data source properties in application.properties and needs an upgrade to the jar.

A: I encountered the same exception when using Spring Data JPA in a Spring Boot application, the JTDS driver and the Hikari connection pool. In my case I discovered that the following fixed the problem:
Examining the class com.zaxxer.hikari.pool.PoolBase, the following can be observed:
this.isUseJdbc4Validation = config.getConnectionTestQuery() == null;

Thus JDBC 4 validation will not be attempted if there is a connection test query configured. In a Spring Boot application, this can be accomplished like this:
spring.datasource.hikari.connection-test-query=select 1;

Regretfully I do not have any experience with the T4SQLMX driver but nevertheless hope this can be of some use.

A: I recently fought through the same issue, for me I was using a JDBC type 3 driver; but my spring implementation only supported a type 4 driver, thus when the method you linked above was attempted to be called, it caused the error.
I suggest you look for a type 4 driver for your particular database and see if that resolves your issue.


text:
Q: userManagerAddToRole(User,Role) : System.InvalidOperationException:RoleDoes"Random Role Id string" not exist I am new to Entity Framework and ASP.NET MVC. In my project, I am trying to assign a role to a user. when I am trying to assign a role to the user, this error gets generated. Even though I tried to see in debugger, I get the Role Id and user id perfectly which I am expecting but when those id are passed to userManager.AddToRole(User,Role) it says role does not exist.
Here is my seed method where I am creating role. Those roles are getting created in AspNetRoles table.
internal sealed class Configuration : DbMigrationsConfiguration<VacationProjectV2.Models.ApplicationDbContext>
{
    private RoleManagement roleManager;
    private ApplicationDbContext dbContext;
    public Configuration()
    {
        AutomaticMigrationsEnabled = false;
        dbContext = new ApplicationDbContext();
        roleManager = new RoleManagement(dbContext);
    }

    protected override void Seed(VacationProjectV2.Models.ApplicationDbContext context)
    {
        //  This method will be called after migrating to the latest version.C:\Users\brahm\source\repos\VacationProjectV2\VacationProjectV2\App_Start\
        //  You can use the DbSet<T>.AddOrUpdate() helper extension method
        //  to avoid creating duplicate seed data.
        roleManager.CreateRole("Admin")   //.ToString().ToUpper();
        roleManager.CreateRole("ProjectManager")  //.ToString().ToUpper();
        roleManager.CreateRole("Developer") //.ToString().ToUpper();
    }
}

Here is my AdminController where I am trying to assign it.
public class AdminsController : Controller
{
    ApplicationDbContext db = new ApplicationDbContext();
    UserManager<ApplicationUser> userManager;
    RoleManager<IdentityRole> roleManager;

    public AdminsController()
    {
        roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(db));
        userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(db));
    }
    // GET: Admins

    public ActionResult AssignRole()
    {
        ViewBag.Users = new SelectList(db.Users, "Id", "UserName");
        ViewBag.Roles = new SelectList(db.Roles, "Id", "Name");
        return View();
    }

    [HttpPost]
    public ActionResult AssignRole(string Users,String Roles)
    {
        userManager.AddToRole(Users, Roles);
        ViewBag.Users = new SelectList(db.Users, "Id", "UserName");
        ViewBag.Roles = new SelectList(db.Roles, "Id", "Name");
        return View();
    }
    public ActionResult Index()
    {
        return View();
    }
}

And here the View code
@{
    ViewBag.Title = "AssignRoles";
}

AssignRoles

@using (Html.BeginForm())
{
    @Html.DropDownList("Users", "Select User");
    @Html.DropDownList("Roles","Select Role")
    <input type="Submit" value="Add Role"/>
}

So I wanted to see UserId and RoleId in AspNetUserRoles table. I don't know where I am making mistake. I tried to create roles in seed method using .Tostrong().ToUpper() by seeing another post with the same issue but it didn't work for me. Please let me know where I am making a mistake.

A: Sorry Guys It was my bad I did not check the method required parameters correctly. The mistake was userManager.AddToRole(). Requires the roleName not the roleId as a parameter.
 public ActionResult AssignRoles()
        {
            ViewBag.Users = new SelectList(db.Users, "Id", "UserName");
            ViewBag.Roles = new SelectList(db.Roles, "Name", "Name"); // Here I was Passing the Id insted Of Role Name.
            return View();
        }
        [HttpPost]
        public ActionResult AssignRoles(string Users,string Roles)
        {
            usersManager.AddToRole(Users, Roles);
            ViewBag.Users = new SelectList(db.Users, "Id", "UserName");
            ViewBag.Roles = new SelectList(db.Roles, "Name", "Name");
            return View();
        }


text:
Q: Display Camera View With Custom UI Good day android geniuses! I am creating an application that allows the user to use the their android phone as speedometer. Imagine the phone posted to the top of your windshield. The phone should be using the camera view without any of the stock UI with a speedometer in the right hand corner. I am currently using intents to display the camera but this displays a camera with all the stock UI. How can i display the camera view with a custom UI overlay?

A: some quick googling shows this result here http://android-er.blogspot.com/2010/12/add-overlay-on-camera-preview.html  This example is older, but its the concept that matters here..
you cannot start your camera with an intent if you want a custom ui, you have to create the custom ui and initialize the camera all yourself.


text:
Q: C++ Win32 Radio button background color So first i'm using the windows API, no special libraries.
I've created a radio button with this code:
g_hRadioButton = CreateWindowEx(0, "BUTTON", "Radio Button",
    WS_CHILD | WS_VISIBLE | BS_RADIOBUTTON,
    10, 55, 120, 25, hWnd, (HMENU)RADIOBUTTON, GetModuleHandle(NULL), NULL);

Now I have a black background for the main window, so I would like the text to be white, and the background to be transparent.
I've tried checking both the WM_CTLCOLORBTN and WM_CTLCOLORSTATIC messages.
Here's my code:
case WM_CTLCOLORBTN:
    SetTextColor((HDC)wParam, 0xffffff);
    SetBkMode((HDC)wParam, TRANSPARENT);
    return (LRESULT)GetStockObject(BLACK_BRUSH);

case WM_CTLCOLORSTATIC:
    SetTextColor((HDC)wParam, 0xffffff);
    SetBkMode((HDC)wParam, TRANSPARENT);
    return (LRESULT)GetStockObject(NULL_BRUSH);

This doesn't work, the backgrounds still white and the text is black.
Also i've enabled visual styles by linking to ComCtl32.lib, creating the manifest and all that.
EDIT:
Trying to process the NM_CUSTOMDRAW message now instead.
Here's my code but it's having no effect, and i'm pretty sure im doing something wrong.
case WM_NOTIFY:
{
    if (((LPNMHDR)lParam)->code == NM_CUSTOMDRAW)
    {
        LPNMCUSTOMDRAW nmCD = (LPNMCUSTOMDRAW)lParam;
        switch(nmCD->dwDrawStage)
        {
            case CDDS_PREPAINT:
                return CDRF_NOTIFYITEMDRAW;

            case CDDS_ITEMPREPAINT:
                SetTextColor(nmCD->hdc, 0xffffff);
                SetBkColor(nmCD->hdc, 0x000000);
                return CDRF_DODEFAULT;
        }
    }

    break;
}

Could someone at least point me in the right direction?

A: Perhaps as soon as your application is running with visual styles, you will be better off handling NM_CUSTOMDRAW notification for button control. Originally, these were for common controls only, but quite a few versions are already extending button behavior the same way too.


text:
Q: how to make learning curve plot I am trying to plot learning curves to determine if my model is undercutting or overfitting, but cannot get learning curves like

or

Not sure what I did is wrong. I have several stupid simple questions:
(1) Does that mean, for each chosen number of training dataset, we train a model? Suppose m (total training data size) = 100000, n (test data size) = 20000. We build model for training dataset size = 0.1m, 0.2m, 0.3m,.... until m, and then for each model, we evaluate training errors using training dataset with 0.1m, 0.2m,... and test errors (always using n=2000 test dataset)?
(2) What does the error mean here? For regression problems, is it the total errors or mean errors?
(3) For classification model, I saw many people use accuracy as error to make plot. Can we use the cross entropy instead?

A: *

*First, divide your data into training data and test data. Then you construct these kinds of learning curves by training models on data of different sizes, such as 10 samples, 100 samples, 1000 samples. (For most models, you won't use all of your training data.) For each model, estimate the out-of-sample error on your entire test set.

*Mean error probably makes the most sense, since each experiment has a different size of training data.

*It's up to you to decide which metric is most interesting for your purposes.


text:
Q: use the sensor accelerometer and mp3 player I would create a small app that uses the accelerometer sensor to start the mp3 player. Basically my idea is this:
1) start the application
2) Turn off the screen of your smartphone
3) shake the cell
4) start the mp3 player, with a song by default
I'm not expert in programming in Android, I hope in your help

A: Look at my sample for shaking device at this link
For mediaPlayer:
public static void playMusic(Context context, int beepType) {
        try {

            mMediaPlayer = MediaPlayer.create(context, R.raw.mymusic);

            mMediaPlayer.setLooping(false);
            mMediaPlayer.start();
            mMediaPlayer.setOnCompletionListener(new
                    OnCompletionListener() {
                        public void onCompletion(MediaPlayer arg0) {
                            // if (mMediaPlayer != null) {
                            // mMediaPlayer.release();
                            // mMediaPlayer = null;
                            // }
                        }
                    });
        } catch (Exception e) {
            if (mMediaPlayer != null) {
                mMediaPlayer.release();
                mMediaPlayer = null;
            }
        }
    }


text:
Q: How can I save multiple ViewModels in ASP.NET MVC 4? I followed the instructions of the article http://www.codeproject.com/Tips/850816/Dynamically-Populate-Dependent-Dropdown-List-in-MV for an own project. It works fine. I can dynamically populate dependent dropdownlists in this way.
The code in "5.4 Update Index View" of the article above unifies the ViewModels CityViewModel, StateProvinceViewModel and CountryViewModel. Every ViewModel contains the information for its own dropdownlist.
My question is now:
How can I save the current selections in all three dropdownlists after the selections were made? (I want to save the currently selected values in the dropdownlists in a database). Can someone give me a hint, please?
I know how to handle one ViewModel (maybe with three different DataModels), but I don't know where to start if multiple ViewModels are used.
I use C# and Razor (but I'm also able to read VB and to translate VB into C#). As far as I know, I can only save one ViewModel, or am I wrong?

A:
How can I save the current selections in all three dropdownlists after the selections were made?

Sounds like you may need a Ajax callback to a controller action after each dropdown change event?  In effect (to demonstrate the basics)
Have a look at this MVC Fiddle
https://dotnetfiddle.net/JCwltD
Assuming we have a bunch of dropDown lists on a page:
<form id="theForm">
    @Html.DropDownListFor(m => m.DropDown1, new SelectList(this.Model.DropDown1Items), new { @class="ddl"} )
    @Html.DropDownListFor(m => m.DropDown2, new SelectList(this.Model.DropDown2Items), new { @class="ddl"} )
    @Html.DropDownListFor(m => m.DropDown3, new SelectList(this.Model.DropDown3Items), new { @class="ddl"} )
</form>

How you select the values to save can be dependent on a JQuery selector (in this case the css class .ddl
$(document).ready(function()
            {
                $(".ddl").change(function()
                {
                    $.post('@Url.Action("Save", "Home")',
                        $(".ddl").serialize(), function(c)
                        {
                            alert(c);
                        });

                });
            });

Just make sure you have an action method to collect this information, and ensure the parameter names of the action method match the field names what will be within the HTTP Post.  (Fiddler or Firebug of Chrome developer tools can show you these if they are not clear)
[HttpPost]
public JsonResult Save(string dropDown1, string dropDown2, string dropDown3)
{
    // do save logic here
    return Json("Saved: " + dropDown1 + " " + dropDown2 + " " + dropDown3);
}


text:
Q: Django Model Form not saving I have a Django model form which when I use the following, isn't saving
if request.method == 'POST':
    form = AbsenceForm(request.POST, instance=request.user)
    if form.is_valid():
        form.save()

forms.py
class DateInput(forms.DateInput):
    input_type = 'date'

class AbsenceForm(forms.ModelForm):
    class Meta:
        model = NotWorking
        exclude = ['user']
        widgets = {
            'date': DateInput()
        }

Can you help please.

A: You're using instance wrong.
instance on a model form is supposed to be of the same class as the model you're referring to. It is used in UpdateViews to bind the form to an existing instance instead of creating a new instance up on save.
Example from the documentation:
# Create a form to edit an existing Article, but use
# POST data to populate the form.
>>> a = Article.objects.get(pk=1)
>>> f = ArticleForm(request.POST, instance=a)
>>> f.save()

In order to attach the user instance to the form you should set it on the form instead of providing it as an instance argument like detailed in this question.
if request.method == 'POST':
    form = AbsenceForm(request.POST)
    form
    if form.is_valid():
        instance = form.save(commit=False)
        instance.user = request.user
        instance.save()


text:
Q: How to fetch the required content from a shell command output that is stored in a Register in Ansible? I'm trying to find a way to store the content of the NSLOOKUP command that i run in Ansible to find a CNAME associated with an application. The CNAME changes accordingly with application to application.
I performed nslookup in shell and registered the output.
- name: Shell Command to perform NSLOOKUP
  shell: nslookup abc.xyz.com
  register: result
- debug: var=result

The Output of NSLOOKUP :
    "stdout_lines": [
        "Server:\t\t10.10.10.10",
        "Address:\t10.10.10.11#53",
        "",
        "abc.xyz.com\tcanonical name = abc.web.xyz.com.",
        "Name:\tabc.web.xyz.com",
        "Address: 10.210.120.111"
    ]

Basically i need to fetch the output of the Value of Name , this value change dynamically from application to application . So i can't use stdout_lines[5] this won't work for each scenario.

A: The task below reports the value(s) of Name(s)
- debug:
    msg: "{{ item.split('\t').1 }}"
  loop: "{{ result.stdout_lines }}"
  when: item is match('^Name:*')

and the next task creates a list of the Name(s') value(s)
- set_fact:
    names: "{{ names|default([]) + [ item.split('\t').1 ] }}"
  loop: "{{ result.stdout_lines }}"
  when: item is match('^Name:*')
- debug:
    var: names

Preferred option should be Ansible native dig – query DNS using the dnspython library.


text:
Q: Python pymySQL sending a string with quotes I'm trying to insert a string to a mySQL database like this:
cur.execute('UPDATE connections SET cmd = "' + command + '", client_new = 1 where ip = "' + ip + '"')

When I set command to be echo "hello", I get this error:
Traceback (most recent call last):
  File "C:/Users/Owner/Desktop/master.py", line 111, in <module>
    main ()
  File "C:/Users/Owner/Desktop/master.py", line 80, in main
    print(""); command(); print("")
  File "C:/Users/Owner/Desktop/master.py", line 29, in command
    cur.execute('UPDATE connections SET cmd = "' + command + '", client_new = 1 where ip = "' + ip + '"')
  File "M:\Python34\lib\site-packages\pymysql\cursors.py", line 146, in execute
    result = self._query(query)
  File "M:\Python34\lib\site-packages\pymysql\cursors.py", line 296, in _query
    conn.query(q)
  File "M:\Python34\lib\site-packages\pymysql\connections.py", line 781, in query
    self._affected_rows = self._read_query_result(unbuffered=unbuffered)
  File "M:\Python34\lib\site-packages\pymysql\connections.py", line 942, in _read_query_result
    result.read()
  File "M:\Python34\lib\site-packages\pymysql\connections.py", line 1138, in read
    first_packet = self.connection._read_packet()
  File "M:\Python34\lib\site-packages\pymysql\connections.py", line 906, in _read_packet
    packet.check_error()
  File "M:\Python34\lib\site-packages\pymysql\connections.py", line 367, in check_error
    err.raise_mysql_exception(self._data)
  File "M:\Python34\lib\site-packages\pymysql\err.py", line 120, in raise_mysql_exception
    _check_mysql_exception(errinfo)
  File "M:\Python34\lib\site-packages\pymysql\err.py", line 112, in _check_mysql_exception
    raise errorclass(errno, errorvalue)
pymysql.err.ProgrammingError: (1064, 'You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near \'hello"", client_new = 1 where ip = "123.456.789.012"\' at line 1')

I understand that there is a problem with how I'm passing the data to the database, but how do I do it properly?

A: You could use placeholders, in that case mysql driver escapes your query:
cur.execute('UPDATE connections SET cmd=%s, client_new=1 where ip=%s', (command, ip))

A: You are surrounding your SQL string literals with double quotes.  SQL requires string literals to have single quotes.
In SQL, double quotes normally signify identifier names, e.g. if you had a column name with a space in it, you would use double quotes then.


text:
Q: Optional values with Esper Is there any support in Esper for properties with Optional values?
I'm building a POC with Esper, using Scala, and I have the EPL query working with non-optional values. I have a simple object that I'm using to test with:
case class EsperEvent(@BeanProperty id: Int, @BeanProperty eventtype: Int)

And can get my expected results with the following query:
select * from EsperEvent
 match_recognize (
   measures A as event1, B as event2
   pattern (A B)
   define
     A as A.eventtype = 2,
     B as B.eventtype = 3
 )

However, when I change my model to the following, I can't seem to get any output from Esper:
case class EsperEvent(@BeanProperty id: Int, @BeanProperty eventtype: Option[Int])

I've tried with the above query and also using dynamic properties as follows:
select * from EsperEvent
  match_recognize (
   measures A as event1, B as event2
   pattern (A B)
   define
     A as A.eventtype? = 2,
     B as B.eventtype? = 3
  )

A: The type of the property would be "java.util.Optional" if I'm not mistaken. You could use "A.eventtype.get()" which returns an Object and would need to be casted for example "cast(A.eventtype.get(), int)". It would be simpler if the event type is just boxed "Integer" for nullable values. EPL adheres to SQL92 standards and they sure don't have "optional".


text:
Q: MagicMock @patch not working as I expected (Python 2.6)
I am missing something in MagicMock patching
Given the following production code:
class MyQueue(object):
    def send(self, message):
        pass

class MessageSender(object):
    def send_all(self, messages):
        queue = MyQueue()
        for message in messages:
            queue.send(message)

I have the following test:
class MessageSenderTest(TestCase):
    @patch('path.to.MyQueue')
    def test_can_send_all_messages(self, queue):
        messages = ['foo', 'bar', 'baz']
        sender = MessageSender()
        sender.send_all(messages)
        queue.send.assert_has_calls([call(message) for message in messages])

Which gives me:
AssertionError: Calls not found.
Expected: [call('foo'), call('bar'), call('baz')]
Actual: []

I thought that the mock produced by sender would allow me to make an assertion.

A: Notice that you are not using the patched queue instance you are receiving in your test method for  anything, because it is instantiated by your MessageSender class. This leads to the mocked MyQueue being instantiated each time the send method is called. In fact, you can modify your assertion a bit and get the following list of calls:
expected = [call()] + [call().send(message) for message in messages]
self.assertEquals(queue.mock_calls, expected)

In this form, the test passes. However, I think it would be more natural for the MessageSender class to receive the MyQueue in its constructor method, so that it can be mocked in the test. See this alternative implementation:
# file: main.py

class MyQueue(object):

    def send(self, message):
        pass

class MessageSender(object):

    def __init__(self, queue):
        self.queue = queue

    def send_all(self, messages):
        for message in messages:
            self.queue.send(message)

Using this, the test reads much more natural:
# file: test.py

import unittest

from mock import patch, call

import main

class MessageSenderTest(unittest.TestCase):

    @patch('main.MyQueue')
    def test_can_send_all_messages(self, queue):
        messages = ['foo', 'bar', 'baz']
        sender = main.MessageSender(queue)  # <-- here is where you do use `queue`
        sender.send_all(messages)
        queue.send.assert_has_calls([call.send(message) for message in messages])

if __name__ == '__main__':
    unittest.main()


text:
Q: React Native drawer navigator to stack navigator missing transition animation I have a functional Drawer navigator that holds a Stack navigator as shown below:
function DrawerNavigator() {
    return (
        <Drawer.Navigator>
            <Drawer.Screen
                name="Categories"
                component={CategoriesScreen}
                ... />
                    ),
                }}
            />
            <Drawer.Screen
                ...
        </Drawer.Navigator>
    );
}
...
return (
        <>
           ...
                <NavigationContainer onReady={onLayoutRootView}>
                    ...
                        <Stack.Screen
                            name="MealCategories"
                            component={DrawerNavigator}
                            options={{ headerShown: false }}
                        />

While in the 'Favorites' screen, which is registered under the Drawer Navigator, when attempting to navigate to 'Categories' page which is registered under Stack navigator (but pointed to using Drawer navigator) using navigation.navigate(), there's no navigation animation.
const buttonPressHandler = () => {
        navigation.navigate("Categories");
    };

A: Yup it seems the drawer navigator has no support for screen animation.  So it all looks great when using the drawer to navigate.  But if navigating through links in the page or actions, theres no navigation animation between screens.  Been hunting for hours now and I think its simply not implemented.


text:
Q: AngularJS, is this way of using service good? i've this HTML:

Hello {{name}}

and the controller is:
function myCtrl(scope, service) {
    scope.name = service.getUsername(); // service.getUsername() return "World!"
}
myCtrl.$inject = ['$scope', 'originalService'];

The service works fine, so i don't paste the code here...
In this case the result is "Hello world!"
I changed the HTML in this way:

Hello {{service.getUsername()}}

But this does not work.
I changed the controller:
function myCtrl(scope, service) {
    scope.ser = service;
}
myCtrl.$inject = ['$scope', 'originalService'];

and then the HTML

Hello {{ser.getUsername();}}

This works!
So my question is:
Is this the only way to use the functions of a service directly in the HTML, or i'm missing something?

A: AngularJS templates can only invoke functions that are available on a scope. So, whatever approach you take you need to have your function on a scope.
If you want your service's functions to be directly invokable from a template you've got several options:
The one you've tried - that is, expose the whole service on a scope:
$scope.service = service;

and then in a template:

Hello {{service.getUsername();}}

This is one-liner in a controller and makes all the service methods available on a scope and thus to templates.
Expose methods one by one
to have precise control over what gets exposed:
$scope.getUsername = service.getUsername;

and then in a template:

Hello {{getUsername();}}

This requires more work exposing methods but gives you fine-grained control over what gets exposed.
Expose proxing methods:
$scope.getMyUsername = function() {
   //pre/post processing if needed
   return service.getUsername();
};

You can use any of those methods or mix and combine them but at the end of the day a function must end up on a scope (either directly or through another object exposed on a scope).

A: Another way to do it:
Expose the service on $rootScope:
$rootScope.service = service;

and then in a template:

Hello {{service.getUsername();}}

You can do this on app.run, and you will get the service in all the views of your app. You could use this method for Authentication services.

A: Another way to expose your service within your $scope would be to add a function pointer to your service method/data object.
scope.serviceData = service.data;
// Or
scope.getServiceData = service.getData;

Within your view you can then invoke it by using parentheses.
<input ng-model="serviceData().key" />
// Or
<input ng-model="getServiceData().key" />
// Or
{{getServiceData().key}}

I personally like this approach and i am currently using it in order to keep multiple views in sync with the same data. It does bring up some issues though as explained here:
AngularJS. Best practice concerning proper two way data binding from a service
As to exposing to much data i am currently trying to do something like this.
// Within your view.
{{getServiceDataByKey('key')}}

// In your controller.
scope.getServiceDataByKey = service.getServiceDataByKey;

// In your service.
getServiceDataByKey : function (key) {
   return dataObject[key];
}

The reason why i am doing this is that we want to keep the controllers as clean as possible and have all our data in one centralized place. Also most data within the service should be exposed.


text:
Q: Filter Dictionary using key and Value in list in Python I am new to python and trying to filter a dictionary from list using  value and key. I am using python 3
[{'ctime': 1459426422, 'accesskey': 'xxxxxx', 'secretkey': 'xxxx', 'id': 4, 'fsname': '/mnt/cdrom1', 'name': '/mnt/cdrom1:test1'}, {'ctime': 1459326975, 'accesskey': 'xxxx', 'secretkey': 'xxxx', 'id': 1, 'fsname': '/mnt/cdrom2', 'name': '/mnt/cdrom2:test2'}]

From above output, I need to filter a dictionary with key value as 'name':'/mnt/cdrom2:test2' so I get fitered dictionary as
{'ctime': 1459326975, 'accesskey': 'xxxx', 'secretkey': 'xxxx', 'id': 1, 'fsname': '/mnt/cdrom2', 'name': '/mnt/cdrom2:test2'}

I can then later extract  keys and values as needed.
Thanks.

A: If your above list is in a variable named "my_list"
Python 2.7.x Version
for d in my_list:
    if d['name'] == '/mnt/cdrom2:test2':
        print d['name'] # or do whatever you want here

Python 3 Version
for d in my_list:
    if d['name'] == '/mnt/cdrom2:test2':
        print(d['name']) # or do whatever you want here


text:
Q: get data from node-sqlite using Promises Can somebody show some good way using Promises with node-sqlite?
For example I'm trying to rewrite such code to avoid callback-hell
and get empty variables
tableRows = []
columns = []

db.all(`... query`, params, (err, medics) => {
   medics.forEach((medic) => {
        db.all(`some other query`, {$id: medic.id}, (err, amounts) => {
              tableRows.push(amounts)
            })
        }
   }).all(`another query`, (err, result) => {
        columns = result
   })

console.log(tableRows, columns)

Can somebody help?
Only node-sqlite please, no ORM or sqlite-based libs.

A: If you can transpile your code or if you are using Node 7.6+, you can use async/await
(async function() {

   tableRows = []
    columns = []

    try {

        const medics = await db.all(`... query`, params);
        medics.forEach((medic) => {
            const amounts = await db.all(`some other query`, {$id: medic.id});
            tableRows.push(amounts);
        });

       const result = db.all(`another query`);
       columns = result;
       console.log(tableRows, columns);
   }

   catch(err) {
       console.log(err);
   }
})();


text:
Q: Regex paterns to remove word formatting I am having a problem using regex patterns to replace items in HTML markup. The values that I am trying to replace are these:

and
class="MsoNormal"

I am not the best at using Regex the patterns that I have come up with so far are:

*

*

*class=\"msonormal\"

*class=\"MsoNormal\"
Item 1 removes anything that starts with  but it only does it once it doesn't remove all instances.
I don't think items 2 and 3 are working at all.
I found some of this information for the patterns here:
is there a Way to strip all Unnecessary MS Word Formatting from FCKEditor
The full listing of text that I want to remove is this:

<title>Blank</title>


text:
Q: Use GETPIVOTDATA for grouped data I have a PivotTable where the rows are values from a field called ID, which is a number, two columns: Light and Humidity, and a set of values Temp. I want to find the max value for Temp over a grouping of IDs. I grouped the IDs from number 1- 100, which encompasses all IDs in the PivotTable, leaving me a PivotTable with a single row of data. In each column I now have the maximum Temp value at a given Light and Humidity value. This is all looking good, until I try to use these max values.
I am trying to use a function like so:
=GETPIVOTDATA("Temp", Controls!$A$15, "Light", 50, "Humidity", 10)

As well as:
=GETPIVOTDATA("Temp", Controls!$A$15, "Light", 50, "Humidity", 10, "ID", "1-100")

But this gives a #REF error.
Prior to grouping the IDs into a single group, I could use a function like:
=GETPIVOTDATA("Temp", Controls!$A$15, "Light", 50, "Humidity", 10, "ID", 1)

And this would correctly return the "Temp" value for ID 1 where the column values match those given in the function.
How can I modify this query to successfully get the value by a grouping of numbers?

A: In my test it seems that the first number of the group can be used in the GetPivotTable formula, so if the group starts with 4, this formula will return the correct result:
=GETPIVOTDATA("temp",$H$3,"light",50,"humidity",10,"id",4)

As an alternative, you could add a helper column to your source data and use a formula that returns the group for each respective ID.
In the screenshot the upper pivot table uses the "Group" functionality and it is not possible to get a GetPivotData of that. The lower pivot table, however, uses the same grouping, which is achieved by the helper formula in column F.
="group "&CEILING([@id]/3,1)

This allows a single value to cover the group and that single value can be used in GetPivotData.
=GETPIVOTDATA("temp",$H$10,"light",50,"humidity",10,"group","group 2")


text:
Q: str_replace not working for two words in different lines I have this code:
<?php
$string = "

Hello
";
$string = str_replace('

','text',$string);
echo $string;
?>

this is not working..
but this works.
<?php
$string = "

Hello
";
$string = str_replace('

','text',$string);
echo $string;
?>

this is not my real code but i could replicate my problem with this code.I need a solution which will work even if there is no line break. please help me.

A: You can do that with preg_replace() and the multi-line operator m after your regex pattern.
$string = preg_replace('/(

){,2}/m', 'text', $string);

A: In your first code, you two tags
are separated by an invisible character (\n), it's why your regex (generated by str_replace) doesn't work
This doesn't work
<?php
    $string = "

    Hello
    ";
    $string = str_replace('

','text',$string);
    echo $string;
?>

But this code will :
<?php
    $string = "
".
    "

    Hello
    ";
    $string = str_replace('

','text',$string);
    echo $string;
?>

A: It's because of "space" characters, remove them using rtrim :
$string = str_replace('

','text',rtrim($string));

Note that it will remove ALL the spaces and line breaks, so it will also remove the line break before Hello. See what you need to do from it.

A: Because there is no '' in the first code. There is  . It will look at exact words to change. It means if you had a blank in your str_replace('

' code, it would work.
<?php
$string = "

Hello
";
$string = str_replace('

','text',$string);
echo $string;
?>

A: Create an array for breaks and check it with string .
$breaks = array("\r\n", "\n", "\r");
$newtext = str_replace($breaks, "", $string);`


text:
Q: CSS inverted trapezium when width will differ I need to make the shape below, which will contain some text.  Sometimes the text will be longer, sometimes shorter so I can use any fixed widths.
**********
 *      *
  ******

This the is code I have - I'm wondering if there's a way I can tag an image on to the beginning and the end of the span.  The height won't change so that would probably be the best in terms of cross browser solutions...

A: One Wrapper Only Needed (IE8+)
This fiddle demonstrates that only a single wrapper is needed. It uses a single pseudo-element to get the angles. The wrapper must either be floated or an inline-block. Here's the code:
HTML

   Test text

CSS
.trapizium {
    position: relative;
    float: left; /* wrap the text */
    clear: left; /* for demo */
    margin: 10px 20px; /* left/right margin will be diagonal width */
    /* needs some set height */
    font-size: 1em;
    line-height: 1em;
    padding: .2em 0;
    background-color: cyan;
}

.trapizium:before {
    content: '';
    height: 0;
    width: 100%;
    position: absolute;
    top: 0;
    left: -20px; /* stick out into margined area */
    z-index: -1; /* make it the background */
    border: 20px solid transparent; /* left/right diagonals */
    border-top: 1.4em solid cyan;
    border-bottom: 0px solid transparent;
}

A: Fiddle
#trapizium {
    border-top: 100px solid blue;
    border-left: 50px solid transparent;
    border-right: 50px solid transparent;
    height: 0;
    width: 100px;
}

You may have to absolute position your text into your shapes. This uses borders to make the shape, and has no height.


text:
Q: Wrap certain types of lines to different text widths? I have text set to wrap at 80 characters.
Is it possible to have text wrapped to, say, 50 characters when editing a certain type of line?
For example, I program Ruby and I want Ruby comments to be wrapped to 50 characters whilst everything else stays at 80.
Is it possible?

A: Wrapping is controlled by the 'textwidth' option. :help 'textwidth' shows that it's local to buffer, so different values can be set, for example manually via
:setlocal textwidth=50

To make this automatically apply to all Ruby files, you can use Vim's built-in filetype detection and filetype plugins. Put the above command into ~/.vim/after/ftplugin/ruby.vim. (This requires that you have :filetype plugin on; use of the after directory allows you to override any default filetype settings done by $VIMRUNTIME/ftplugin/ruby.vim.) Alternatively, you could define an :autocmd FileType ruby ... directly in your ~/.vimrc, but this tends to become unwieldy once you have many customizations.
The built-in functionality stops there, at buffer scope. To apply the different textwidth only to comments (or any other syntax element), dynamic adaptation is needed. This can be implemented using :autocmd, hooking into the CursorMoved event. My OnSyntaxChange plugin provides utility functions to simplify the setup (again placed in ~/.vim/after/ftplugin/ruby.vim):
call OnSyntaxChange#Install('Comment', '^Comment$', 1, 'a')
autocmd User SyntaxCommentEnterA setlocal textwidth=50
autocmd User SyntaxCommentLeaveA setlocal textwidth=80


text:
Q: OData paging with expand issue I'm using OData v5/Web API 2.2 to create an endpoint that will return a list of employees from each company.
My problem occurs when I try to implement server-side paging while also using the OData $expand property. When I try to make a call to
http://localhost:60067/Companies?$expand=Employees
I get an error that says "Could not find a property named 'Employees' on type 'System.Web.OData.Query.Expressions.SelectAllAndExpand_1OfCompanyApiModel'"
However, when I removed the EnableQuery attribute the call to the endpoint or when I didn't expand it works as expected. Does anyone have an idea of what I am doing wrong? I've been googling this for a while but haven't found anything.
Here are some code snippets -
Data Models:
public class CompanyApiModel
{
    [Key]
    public Guid CompanyGuid { get; set; }
    [Required]
    public string Name { get; set; }
    // other properties
    public List<EmployeeApiModel> Employees { get; set; }
}

public class EmployeeApiModel
{
    [Key]
    public Guid EmployeeGuid { get; set; }
    [Required]
    public string Name { get; set; }
    // other properties
}

CompaniesController.cs:
[EnableQuery(PageSize = 10)] // If I comment this out everything works
//[EnableQuery] // This fails as well
public IHttpActionResult Get(ODataQueryOptions<CompanyApiModel> queryOptions)
{
    var companies = GetCompanies(queryOptions);
    return Ok(companies);
    // return Ok(companies.AsQueryable()); // This doesn't work either
}

WebApiConfig.cs:
public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;

        var routingConventions = ODataRoutingConventions.CreateDefault();
        routingConventions.Insert(0, new OptionsRoutingConvention());
        config.MapODataServiceRoute("odata", null, GetEdmModel(), new DefaultODataPathHandler(), routingConventions);

        // below code allows endpoints to respond with either XML or JSON, depending on accept header preferences sent from client
        // (default in absence of accept header is JSON)
        var odataFormatters = ODataMediaTypeFormatters.Create();
        config.Formatters.InsertRange(0, odataFormatters);

        config.EnsureInitialized();

    }

    public static IEdmModel GetEdmModel()
    {
        ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
        builder.Namespace = "Demos";
        builder.ContainerName = "DefaultContainer";

        builder.EntitySet<CompanyApiModel>("Companies");
        builder.EntitySet<EmployeeApiModel>("Employees");

        var edmModel = builder.GetEdmModel();
        return edmModel;
    }
}

A: Figured out the problem. We were overriding the EnableQuery attribute somewhere in our code and calling it EnableMappedQuery and applying it to the controller. Thus instead of having [EnableQuery(PageSize = 10)] I should have had [EnableMappedQuery(PageSize = 10)].

A: EnableQuery Attribute do many works,
1. it will validate the queryoption for you.
2. it will apply the queryoption for you.
3. it can add some querysettings like PageSize.

Your scenario not working is because your GetCompanies is already applied the queryoption, so when EnableQuery get the result and apply the queryoption again, it fails, it can't find the expand property, my suggestion is just return original Company and let EnableQuery do the reset of work for you, ODataQueryOption in parameter is also not needed.
If you realy do some custom work in GetCompanies and don't need EnableQuery to apply for you, you can add PageSize in ODataQuerySettings when you call method ODataQueryOptions.ApplyTo(IQueryable, ODataQuerySettings).


text:
Q: How to download mapbox gallery site data? I am trying to make a map of network connections. The MapBox map gallery has some really beautifully laid out maps and I wanted to take the coordinate data to style it for other purposes.
I know this is a long shot, but does anyone know how these maps render data and whether or not the coordinates are accessible after they are made web ready?
i.e. map: http://mapbox.com/tilemill/gallery/#tmcw.rrrr2

A: For this map you're in luck! @tmcw has written about the process of making the map here:
Article
http://macwright.org/2011/07/28/mapping-runs.html
Demo
http://macwright.org/running
Code
https://github.com/tmcw/running


text:
Q: How to convert a PWM signal generated by an M5 Stack Core ESP32 from 3.3 V or 5 V to 12 V and at least 0.8 A? I am working on a project that requires me to convert two PWM signals of 1 kHz frequency that are generated from an M5-Stack Core from either 3.3 V or 5 V to two PWM signals of 12 V and (at least) 0.8 A. Is there any way of doing this without using a low-pass filter?
I have read on other websites that I can use a low-pass filter to convert it to an analog signal and then use an op-amp to convert it again to a higher voltage signal. Also excuse me if my words don't make much sense. I don't have much experience with circuits. If possible please do use simple vocabulary so I can understand it as better as possible.

A: Since your output is supposed to be PWM, there's no point in filtering the PWM to DC to amplify it.
All you really need is a circuit that switches its output high (to 12V) when the input is high, and switches its output to ground when the input is low.  If you use large transistors for the switching, then you can deliver a large current to your load.
Such a circuit could look like this:

(From this answer.)
A simpler way would be to use a half H-bridge motor driver.  Such a motor driver contains the output transistors and some supporting circuitry to make it easier to use and more robust and reliable


text:
Q: What would this Classic asp code look like in asp.net? I have to convert some logic of an old Classic ASP site into an asp.net project.  I am having trouble understanding some function which is responsible for posting data.
Here is the function in Classic ASP:
<%Function PostHTTP(strURL, strBody, strErrTemplate)
ON ERROR RESUME NEXT
Dim objHTTP, strResult

  Set objHTTP = Server.CreateObject("Msxml2.ServerXMLHTTP.3.0")

  If Err.Number <> 0 Then
    strResult = Replace(strErrTemplate, "%1", Err.Number)
    strResult = Replace(strResult, "%2", Err.Description)
    strResult = Replace(strResult, "%3", "Init::" & Err.Source)
    Set objHTTP = Nothing
    PostHTTP = strstrResult
    Exit Function
  End If

  With objHTTP
    .Open "POST", strURL, False
    .setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
    .setTimeouts 30000, 30000, 60000, 240000
    .send strBody

    If Err.Number <> 0 Then
      strResult = Replace(strErrTemplate, "%1", Err.Number)
      strResult = Replace(strResult, "%2", Err.Description)
      strResult = Replace(strResult, "%3", "Post::" & Err.Source)
    Else
      strResult = .responseText
    End If
  End With

' Response.Write "strResult: " & strResult
'Response.End

  If Err.Number > 0 Then
    strResult = Replace(strErrTemplate, "%1", Err.Number)
    strResult = Replace(strResult, "%2", Err.Description)
    strResult = Replace(strResult, "%3", Err.Source)
  ElseIf Len(strResult) = 0 Then
    strResult = Replace(strErrTemplate, "%1", 2000)
    strResult = Replace(strResult, "%2", "No response received from remote server.")
    strResult = Replace(strResult, "%3", "PostHTTP")
  End If

  PostHTTP = strResult
  Set objHTTP = Nothing
End Function

What would this look like in asp.net?
ps: I have tried my own posting function, but clearly missed something, as mine does not work.

A: The main task of POST would be quite simple if you use WebClient class. For example,
// Form URL and POST-DATA
...
using (WebClient wc = new WebClient())
{
    wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
    string strResult = wc.UploadString(strURL, strBody);
}
...

For more granular control, you can use WebRequest class.
EDIT: here's the example code for WebRequest because it appears that you need to specify the timeout value which is not possible with WebClient
var request = WebRequest.Create(strUrl);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.Timeout = 240000; // set timeout
using (var writer = new StreamWriter(request.GetRequestStream()))
{
    // write to the body of the POST request
    writer.Write(strBody);
}


text:
Q: Android SQLite very slow lookup I am trying to create a dictionary application on Android. I have a database of 80000 articles. When user enters a word in an EditText, I want to show suggestions in a ListView, To do that I use the following code:
    public Cursor query(String entry){
             String[] columns = new String[]{"_id", "word"};
             String[] selectionArgs = new String[]{entry + "%"};
             return mDB.query("word", columns, "word LIKE ?", selectionArgs, null, null, null);
    }

and I use SimpleCursorAdapter for the ListView.
The problem is that suggestions appear very late. I think the reason is LIKE in the SQL. I do not know any other way to do that. Is there anything I can do to boost the performance of getting the suggestions?

A: You might find that adding an index on the word column helps a lot. See the documentation.
So you might try this, just after you create the table:
CREATE INDEX word_idx ON word (word);

(Note: I'm not sure if having the table and column both named word will cause syntax issues here. Try it and see!)

A: As a simple alternative, you can limit the suggestions in the arbitrary order with Limit as in this post: Using the LIMIT statement in a SQLite query
mDB.query("word", columns, "word LIKE ?", selectionArgs, null, null, null, "LIMIT 150" );

Since all the results are equally valid suggestions, the order will not matter.
Also you wonT be able to show crazy amount of suggestions anyway so you can simply use some fixed limit count depending on your UI. I gave 150 as an example.
Hope it helps..

A: Aside from the obvious index you should look into using full text search with MATCH rather than like if this is a dictionary. Android should support FTS3.
Check out http://www.sqlite.org/fts3.html and some answers here on SO regarding fts3 on Android.
It seems that the words should start with the string.
Maybe this type of trick could help: SQLite FTS3 simulate LIKE somestring%


text:
Q: Why does Update() call itself more than once? I'm new in Unity and developing a cricket game. I have a screen that shows squad selection. It shows images of 15 players, out of which I have to select any 11.
I keep on adding the clicked (selected) player in a List. But the problem is that when I click the player once, the size of my list becomes 4 or 5 or even more sometimes. My script is as follows:
using UnityEngine;
using System.Collections;

public class bear : MonoBehaviour {

    // Use this for initialization
    void Start () {

    }

    // Update is called once per frame
    void Update () {
        //select ();
        if (Input.touchCount == 1)
        {
            Vector3 wp = Camera.main.ScreenToWorldPoint(Input.GetTouch(0).position);
            Vector2 touchPos = new Vector2(wp.x, wp.y);
            if (collider2D == Physics2D.OverlapPoint(touchPos))
            {
                Material newMat = Resources.Load("New Material", typeof(Material)) as Material;
                gameObject.renderer.material = newMat;
                PlayersManager.objPlayerList.Add(PlayersManager.setPlayerObject("Bear"));
                countausplayer.countteam++;
            }
        }
    }
}

Please guide me where am I going wrong? Why is the List size increasing on its own?

A: Update is called every frame, and you are testing basically every frame if the users finger is over your item and adding items to the list. If you have a long touch you will get more adds.
instead you should test that the touch has ended, you do this with TouchPhase.
The right TouchPhase is TouchPhase.Ended.
This means that a finger was lifted from the screen. This is the final phase of a touch.
Or in your code:
void Update () {
    //select ();
    int i = 0;
    while (i < Input.touchCount) {
        if (Input.GetTouch(i).phase == TouchPhase.Ended)
            Vector3 wp = Camera.main.ScreenToWorldPoint(Input.GetTouch(i).position);
            Vector2 touchPos = new Vector2(wp.x, wp.y);
            if (collider2D == Physics2D.OverlapPoint(touchPos))
            {
                Material newMat = Resources.Load("New Material", typeof(Material)) as Material;
                gameObject.renderer.material = newMat;
                PlayersManager.objPlayerList.Add(PlayersManager.setPlayerObject("Bear"));
                countausplayer.countteam++;
            }
        }
    }
}

A: My previous answer was wrong...
I think you have the solution here:

*

*http://docs.unity3d.com/ScriptReference/Input.GetTouch.html

*https://www.youtube.com/watch?v=zszQA9httVo
You should look for Input.touchCount > 0 && TouchPhase.TheOneYouWant