text:
Q: Memory issue in objective c My application is attempting to use a zombie instance of something, though i have no idea where the problem is. the exception consistently occurs when invoking (IBAction)addTag:sender.
my stack trace is below:
2012-03-12 17:06:45.935 FavoriteTwitterSearches[3636:f803] -[__NSCFString addTag:]: unrecognized selector sent to instance 0x6a30d90
2012-03-12 17:06:45.943 FavoriteTwitterSearches[3636:f803] CRASH: -[__NSCFString addTag:]: unrecognized selector sent to instance 0x6a30d90
2012-03-12 17:06:45.947 FavoriteTwitterSearches[3636:f803] Stack Trace: (
    0   CoreFoundation                      0x013bc06e __exceptionPreprocess + 206
    1   libobjc.A.dylib                     0x0154dd0a objc_exception_throw + 44
    2   CoreFoundation                      0x013bdced -[NSObject doesNotRecognizeSelector:] + 253
    3   CoreFoundation                      0x01322f00 ___forwarding___ + 432
    4   CoreFoundation                      0x01322ce2 _CF_forwarding_prep_0 + 50
    5   CoreFoundation                      0x013bdec9 -[NSObject performSelector:withObject:withObject:] + 73
    6   UIKit                               0x000165c2 -[UIApplication sendAction:to:from:forEvent:] + 96
    7   UIKit                               0x0001655a -[UIApplication sendAction:toTarget:fromSender:forEvent:] + 61
    8   UIKit                               0x000bbb76 -[UIControl sendAction:to:forEvent:] + 66
    9   UIKit                               0x000bc03f -[UIControl(Internal) _sendActionsForEvents:withEvent:] + 503
    10  UIKit                               0x000bb2fe -[UIControl touchesEnded:withEvent:] + 549
    11  UIKit                               0x0003ba30 -[UIWindow _sendTouchesForEvent:] + 513
    12  UIKit                               0x0003bc56 -[UIWindow sendEvent:] + 273
    13  UIKit                               0x00022384 -[UIApplication sendEvent:] + 464
    14  UIKit                               0x00015aa9 _UIApplicationHandleEvent + 8196
    15  GraphicsServices                    0x012a6fa9 PurpleEventCallback + 1274
    16  CoreFoundation                      0x013901c5 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__ + 53
    17  CoreFoundation                      0x012f5022 __CFRunLoopDoSource1 + 146
    18  CoreFoundation                      0x012f390a __CFRunLoopRun + 2218
    19  CoreFoundation                      0x012f2db4 CFRunLoopRunSpecific + 212
    20  CoreFoundation                      0x012f2ccb CFRunLoopRunInMode + 123
    21  GraphicsServices                    0x012a5879 GSEventRunModal + 207
    22  GraphicsServices                    0x012a593e GSEventRun + 114
    23  UIKit                               0x00013a9b UIApplicationMain + 1175
    24  FavoriteTwitterSearches             0x00001fab main + 187
    25  FavoriteTwitterSearches             0x00001ee5 start + 53
    26  ???                                 0x00000001 0x0 + 1
)
objc[3636]: EXCEPTIONS: finishing handler

Support Files/Main.m:
#import <UIKit/UIKit.h>

#import "AppDelegate.h"
void uncaughtExceptionHandler(NSException *exception);

int main(int argc, char *argv[])
{
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

    int retVal;
    @try {
    retVal = UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
    }
    @catch (NSException *exception) {
        NSLog(@"CRASH: %@", exception);
        NSLog(@"Stack Trace: %@", [exception callStackSymbols]);
    }
    @finally {
        [pool release];
    }
    return retVal;
}

Controller.m
#import "Controller.h"

@implementation Controller
- (id)init
{
    if (self != nil)
    {
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *dir = [paths objectAtIndex:0];
        filePath = [[NSString alloc] initWithString:[dir stringByAppendingPathComponent:@"tagsIndex.plist"]];
        NSFileManager *fileManager = [NSFileManager defaultManager];

        if ([fileManager fileExistsAtPath:filePath] == NO)
        {
            tags = [[NSMutableDictionary alloc] init];
        }
        else
        {
            tags = [[NSMutableDictionary alloc] initWithContentsOfFile:filePath];
        }

        buttons = [[NSMutableArray alloc] init];
        infoButtons = [[NSMutableArray alloc] init];
    }
    return self;
}

- (void)awakeFromNib
{
    for (NSString *title in tags)
        [self addNewButtonWithTitle:title];
}

- (void)refreshList
{
    for (UIButton *button in scrollView.subviews)
        [button removeFromSuperview];

    [infoButtons removeAllObjects];

    float buttonOffset = BUTTON_SPACING;

    for (UIButton *button in buttons)
    {
        CGRect buttonFrame = button.frame;
        buttonFrame.origin.x = BUTTON_SPACING;
        buttonFrame.origin.y = buttonOffset;
        buttonFrame.size.width = scrollView.frame.size.width - BUTTON_SPACING - BUTTON_HEIGHT;
        buttonFrame.size.height = BUTTON_HEIGHT;
        button.frame = buttonFrame;

        UIButton *infobutton = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
        [infoButtons addObject:infobutton];

        buttonFrame = infobutton.frame;
        buttonFrame.origin.x = scrollView.frame.size.width - BUTTON_SPACING - SCROLLBAR_WIDTH;
        buttonFrame.origin.y = buttonOffset;
        infobutton.frame = buttonFrame;

        [infobutton
         addTarget:self action:@selector(infoButtonTouched:)
         forControlEvents:UIControlEventTouchUpInside];
        [scrollView addSubview:infobutton];

        buttonOffset += BUTTON_HEIGHT + BUTTON_SPACING;
    }
}

- (void)infoButtonTouched:sender
{
    int index = [infoButtons indexOfObject:sender];

    NSString *key = [[buttons objectAtIndex:index] titleLabel].text;
    tagField.text = key;

    NSString *value = [tags valueForKey:key];
    queryField.text = value;
}

- (IBAction)addTag:sender
{
    [tagField resignFirstResponder];
    [queryField resignFirstResponder];

    NSString *key = tagField.text;
    NSString *value = queryField.text;

    if (value.length == 0 || key.length == 0) return;

    if ([tags valueForKey:key] == nil)
        [self addNewButtonWithTitle:key];

    [tags setValue:value forKey:key];

    tagField.text = nil;
    queryField.text = nil;

    [tags writeToFile:filePath atomically:NO];
}

- (IBAction)clearTags:sender
{
    [tags removeAllObjects];
    [tags writeToFile:filePath atomically:NO];
    [buttons removeAllObjects];
    [self refreshList];
}

- (void)addNewButtonWithTitle:(NSString *)title
{
    UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [button setTitle:title forState:UIControlStateNormal];
    [button
     addTarget:self action:@selector(buttonTouched:)
     forControlEvents:UIControlEventTouchUpInside];
    [buttons addObject:button];

    [buttons sortUsingSelector:@selector(compareButtonTitles:)];
    [self refreshList];

    CGSize contentSize = CGSizeMake(
                                scrollView.frame.size.width,
                                buttons.count * (BUTTON_HEIGHT + BUTTON_SPACING) + BUTTON_SPACING);
    [scrollView setContentSize:contentSize];
}

- (void)buttonTouched:sender
{
    NSString *key = [sender titleLabel].text;
    NSString *search = [[tags valueForKey:key]
                        stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSString *urlString = [NSString stringWithFormat:
                           @"http://search.twitter.com/search?q=%@", search];
    NSURL *url = [NSURL URLWithString:urlString];
    [[UIApplication sharedApplication] openURL:url];
}
- (void)dealloc
{
    [filePath release];
    [tags release];
    [infoButtons release];
    [buttons release];
    [super dealloc];
}
@end

@implementation UIButton (sorting)
- (NSComparisonResult)compareButtonTitles:(UIButton *)button
{
    return [self.titleLabel.text caseInsensitiveCompare:button.titleLabel.text];
}
@end

A: [__NSCFString addTag:]: unrecognized selector sent to instance says thay you are calling method addTag: on an instance of type NSString.
Check to what object and how is your IBAction connected in your xib. If everything is okey, try to clean your project, reset your simulator, and then try it again.
EDIT: please, add a NSLog into your dealloc to check if your controller has not been deallocated.

A: It sounds like most likely a Controller object is getting deallocated prematurely. It's not possible from the code you've posted to tell where it's happening, but you should be able to track it down with Instruments (zombies and malloc stack logging in particular). Or, if Controller isn't used in a lot of places†, it might be quicker just to look there and see if you're mistakenly autoreleasing it.
†For an object called something like "Controller", I wouldn't bet on it, but it's worth mentioning and being able to easily track the life cycle of objects is a great incentive to reduce coupling in your program designs.


text:
Q: All css style rules are stripped from one div element but no other elements I am trying to create a header for a website where the title of the site is displayed over an image. I set it up to use a div class element with a background image. However, I can't figure out why the background image in this div class element I created is not displaying.
After inspection I've found out that the css style rules associated with the div class element are being stripped of the element when I render it (in Firefox and Chrome, haven't tried IE).
I have the css setup like this:
.text-over-image {
   width: 960px;
   height: 100px;
   background-image: url("http://www.lupenet.org/wp-content/themes/Lupenet/images/header.jpg");
   margin-left: auto ;
   margin-right: auto ;
}

h8 {
   position: absolute;
   top: 20px;
   left: 400px;
   width: 960px;
}

h8 span {
   color: black;
   font: bold 24px/45px Helvetica, Sans-Serif;
   letter-spacing: -1px;
   padding: 10px;
}

h8 span.spacer1 {
   padding:0 5px;
}

And the html looks like this:

   <h8>La Unión Del Pueblo Entero

"Celebrando el Pasado y Viendo Hacia el Futuro"</h8>

After realizing there was a problem, I set the height and width attributes of the element .text-over-image in case the div was just being rendered too small to view the image, but the background image still didn't display. When I inspected the element using firebug, I found out the div element .text-over-image does not show any background image attribution at all. In fact, all css style rules are stripped from that div element.
I even tried copying the css and html of another website that does exactly what I'm trying to do, but when I do it, the same thing happens (style rules are stripped from that div element). However, the css style rules are not stripped from the other elements.

A: Remove the ; from your class:

It should be just

jsFiddle example

A: I read your css and after that I just came to this point! There is no legal h8 element in HTML.
So I guess the issue is the usage of h8, try replacing it with h6.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Get table data not in pivot table The problem I wish to solve
I have three tables: notification, user, user_viewed_notification. notification and user have a many to many relationship. How do I get the fresh notifications for a particular user:
-- mock sql to explain
select * from notification where user = 1 and viewed = false

Desired Result
Empty as webuser_id = 1 is inside user_viewed_notification table

notification_id
title
content

SQL fiddle
select version();

version()

5.7.39

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
START TRANSACTION;
SET time_zone = "+00:00";

/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;

--
-- Database: `*****`
--

-- --------------------------------------------------------

--
-- Table structure for table `notification`
--

DROP TABLE IF EXISTS `notification`;
CREATE TABLE IF NOT EXISTS `notification` (
  `notification_id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT,
  `title` varchar(255) NOT NULL,
  `content` varchar(255) NOT NULL,
  PRIMARY KEY (`notification_id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4;

--
-- Dumping data for table `notification`
--

INSERT INTO `notification` (`notification_id`, `title`, `content`) VALUES
(1, 'Test', 'This is a test notification');

-- --------------------------------------------------------

--
-- Table structure for table `webuser`
--

DROP TABLE IF EXISTS `webuser`;
CREATE TABLE IF NOT EXISTS `webuser` (
  `webuser_id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT,
  `name` varchar(255) NOT NULL,
  `tel` varchar(255) DEFAULT NULL,
  `address` varchar(255) DEFAULT NULL,
  `email` varchar(255) NOT NULL,
  `password` varchar(255) NOT NULL,
  `role` int(11) NOT NULL,
  `login_attempts` int(11) NOT NULL DEFAULT '0',
  PRIMARY KEY (`webuser_id`),
  UNIQUE KEY `webuser_email_unique` (`email`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4;

--
-- Dumping data for table `webuser`
--

INSERT INTO `webuser` (`webuser_id`, `name`, `tel`, `address`, `email`, `password`, `role`, `login_attempts`) VALUES
(1, 'John', '123', 'Street', '...', '****', 69, 0),
(3, 'Johny', '123', 'Street', '.f..', '****', 61, 0);

-- --------------------------------------------------------

--
-- Table structure for table `webuser_viewed_notifications`
--

DROP TABLE IF EXISTS `webuser_viewed_notifications`;
CREATE TABLE IF NOT EXISTS `webuser_viewed_notifications` (
  `webuser_webuser_id` int(10) UNSIGNED NOT NULL,
  `notification_notification_id` int(10) UNSIGNED NOT NULL,
  PRIMARY KEY (`webuser_webuser_id`,`notification_notification_id`),
  KEY `webuser_viewed_notifications_webuser_webuser_id_index` (`webuser_webuser_id`),
  KEY `webuser_viewed_notifications_notification_notification_id_index` (`notification_notification_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

--
-- Dumping data for table `webuser_viewed_notifications`
--

INSERT INTO `webuser_viewed_notifications` (`webuser_webuser_id`, `notification_notification_id`) VALUES
(1, 1);

--
-- Constraints for dumped tables
--

--
-- Constraints for table `webuser_viewed_notifications`
--
ALTER TABLE `webuser_viewed_notifications`
  ADD CONSTRAINT `webuser_viewed_notifications_notification_notific_e0da5_foreign` FOREIGN KEY (`notification_notification_id`) REFERENCES `notification` (`notification_id`) ON DELETE CASCADE ON UPDATE CASCADE,
  ADD CONSTRAINT `webuser_viewed_notifications_webuser_webuser_id_foreign` FOREIGN KEY (`webuser_webuser_id`) REFERENCES `webuser` (`webuser_id`) ON DELETE CASCADE ON UPDATE CASCADE;
COMMIT;

/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;

Records: 2  Duplicates: 0  Warnings: 0

Records: 1  Duplicates: 0  Warnings: 0

SELECT * FROM `webuser_viewed_notifications`

webuser_webuser_id
notification_notification_id

1
1

SELECT * FROM `notification`

notification_id
title
content

1
Test
This is a test notification

SELECT * FROM `webuser`

webuser_id
name
tel
address
email
password
role
login_attempts

1
John
123
Street
...
****
69
0

3
Johny
123
Street
.f..
****
61
0

fiddle

A: This can be done using NOT EXISTS.
select n.*
from notification n
where not exists (select 1
                 from webuser_viewed_notifications wvn
                 where wvn.notification_notification_id=n.notification_id
                 and wvn.webuser_webuser_id = 1 )    ;

https://dbfiddle.uk/DWW7t6yG

*

*NOT EXISTS performs in most straightforward way: just checks equality and returns TRUE or FALSE on the first hit / miss.

*LEFT JOIN / IS NULL either makes an additional table lookup or does not return on the first match and performs more poorly.


text:
Q: android XmlPullParser parse xml to Listview i have listgender.xml store in asset folder like this:
<gender>
        <sex>male</sex>
        <sex>female</sex>
</gender>

this is class gender :
 public class ClassGender {
    private String sex;
    public String getSex() {
        return sex;
    }
    public void setSex(String sex) {
        this.sex = sex;
    }
}

this is list_data for listview:
<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/tv_gender"
android:textColor="#ff0004"
android:textSize="14sp" />

I use XmlPullParser parse xml to Listview:
ListView lv;

static final String KEY_GENDER = "sex";

List<ClassGender> spList = null;

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

    lv = (ListView) findViewById(R.id.listview_t4);
    try {
        XmlPullParserSpinner parser_Emp = new XmlPullParserSpinner();
        spList = parser_Emp.parse(getAssets().open("listgender.xml"));

        ArrayAdapter<ClassGender> adapter = new ArrayAdapter<ClassGender>(this,
                R.layout.list_data, spList);

        lv.setAdapter(adapter);

    }
    catch (Exception e){
        e.printStackTrace();
    }

}

public class XmlPullParserSpinner {

    private ClassGender c_g;
    private String text;

    public XmlPullParserSpinner() {
        spList = new ArrayList<ClassGender>();
    }

    public List<ClassGender> parse(InputStream is) {
        XmlPullParserFactory factory = null;
        XmlPullParser parser = null;
        try {
            factory = XmlPullParserFactory.newInstance();
            factory.setNamespaceAware(true);
            parser = factory.newPullParser();
            parser.setInput(is, null);
            int eventType = parser.getEventType();
            while (eventType != XmlPullParser.END_DOCUMENT) {
                String tagname = parser.getName();
                switch (eventType) {
                    case XmlPullParser.START_TAG:
                        if (tagname.equalsIgnoreCase(KEY_GENDER)) {
                            c_g = new ClassGender();
                        }
                        break;
                    case XmlPullParser.TEXT:
                        text = parser.getText();
                        break;
                    case XmlPullParser.END_TAG:
                        if (tagname.equalsIgnoreCase(KEY_GENDER)) {
                            spList.add(c_g);
                            c_g.setSex(text);
                        }
                        break;
                    default:
                        break;
                }
                eventType = parser.next();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return spList;
    }
}

my listView can get data from xml, but it not show value is male or female,

it show value is jame.test.ClassGender@5355eddc and
  jame.test.ClassGender@5355ee54.

how to fix it ?

A: If you will see the code of ArrayAdapter
public class ArrayAdapter<T> extends BaseAdapter implements Filterable, ThemedSpinnerAdapter {

  //Some code

public View getView(int position, View convertView, ViewGroup parent) {
        return createViewFromResource(mInflater, position, convertView, parent, mResource);
    }

    private View createViewFromResource(LayoutInflater inflater, int position, View convertView,
            ViewGroup parent, int resource) {
        View view;
        TextView text;

        if (convertView == null) {
            view = inflater.inflate(resource, parent, false);
        } else {
            view = convertView;
        }

        try {
            if (mFieldId == 0) {
                //  If no custom field is assigned, assume the whole resource is a TextView
                text = (TextView) view;
            } else {
                //  Otherwise, find the TextView field within the layout
                text = (TextView) view.findViewById(mFieldId);
            }
        } catch (ClassCastException e) {
            Log.e("ArrayAdapter", "You must supply a resource ID for a TextView");
            throw new IllegalStateException(
                    "ArrayAdapter requires the resource ID to be a TextView", e);
        }

        T item = getItem(position);
        if (item instanceof CharSequence) {
            text.setText((CharSequence)item);
        } else {
            text.setText(item.toString());
        }

        return view;
    }

  //Some code

}

The line
        text.setText(item.toString());

uses the toString() method of the item. So, instead of passing a List of ClassGender you need to pass a List of String otherwise what you can do is override toString() in your class ClassGender which will return the sex object value.


text:
Q: Connection Pooling in flask using couchbase as database I am a newbie to flask. I need to implement connection pooling in flask, the following is my software stack:
1. Flask - 0.12.2
2. Python version - 3.4.3
3. Python couchbase driver version - 2.2.1
4. Couchbase version - 4.5.0-2601 Community Edition (build-2601)
My requirement is - at server startup - repeatedly run 3-4 processes after every 'n' seconds i.e. some process runs every 1 second, some run every 5 seconds etc. I used the "threading" module in python to execute running these parallel processes.
I did not want to create & close connection for above processes, so I create required connections to couchbase buckets at flask start up as below:
(The following lines of code are in "app.py" file)
 cbBkt1Conn = Couchbase.connect(host=<host_name>,
 bucket=<bucket1>, password=<bucket1Password>)
 cbBkt2Conn = Couchbase.connect(host=<host_name>,
 bucket=<bucket3>, password=<bucket3Password>)
 cbBkt3Conn = Couchbase.connect(host=<host_name>,
 bucket=<bucket3>, password=<bucket3Password>)

etc
But, when flask starts after a 3-4 runs I get the following exception:
 File "/usr/local/lib/python3.4/dist-packages/couchbase/n1ql.py", line 384,
 in __iter__
  self._start()
 File "/usr/local/lib/python3.4/dist-packages/couchbase/n1ql.py", line 297,
 in _start
 cross_bucket=self._params.cross_bucket)

 couchbase.exceptions.ObjectThreadError: <Couldn't lock. If LOCKMODE_WAIT
 was passed, then this means that something has gone wrong internally.
 Otherwise, this means you are using the Connection object from multiple
 threads. This is not allowed (without an explicit lockmode=LOCKMODE_WAIT
 constructor argument, C Source=(src/oputil.c,428)>

On further investigation I found that since I am using the same connection object across multiple threads, this was not permitted (as per above error trace & links below):
http://docs.couchbase.com/sdk-api/couchbase-python-client-2.2.1/api/threads.html
The links suggest to use "threading" with "LOCKMODE_WAIT" option, but this defeats the entire purpose.
I also came across SQLALCHEMY, but this does not supports couchbase
Query:
1) How do I implement connection pooling in Flask?
Please guide me to an example / reference to implement this.
Thanks,
Sachin Vyas.

A: You're better off creating new connections in a threading environment. (And maybe think about why you don't want to share to begin with).
It is best to think of connections like an old-style house lines. If one person picks up and dials in the living room, then anyone who wants to make a call on the same line will receive the same conversation. If he picks up the phone and starts calling for pizza, then the people that are using the phone will be interrupted and he won't get his pizza.
There are two options: either the second person who wants to use the house will need to wait until the line is free, or open a new connection for each person in the house.


text:
Q: PHP upgrade from 7.2.0 to 7.2.1 I have a directory where is PHP 7.2.0 : C:/Program Files (x86)/PHP 7.2/
Apache was configured to run this version of PHP.
Then, I have created the directory C:/Program Files (x86)/php-7.2.1/ on my system to upgrade to PHP 7.2.1
I changed my Apache 2.4 conf file to :
LoadModule php7_module "C:/Program Files (x86)/php-7.2.1/php7apache2_4.dll"
PHPIniDir "C:/Program Files (x86)/php-7.2.1/php.ini"

Then, when I run phpinfo(); I keep getting :
PHP Version 7.2.0

But, still, in settings, I can see :
Loaded Configuration File   C:\Program Files (x86)\php-7.2.1\php.ini

Any idea on what I am missing ?


text:
Q: How to start IPython kernel and connect using ZMQ sockets? I am working on a frontend to IPython in C++ (Qt).
I managed to embed Python in my application and retrieve plots and show these in my GUI. Now I want to start an IPython kernel and connect to it through ZMQ sockets.
I found a description for the communication protocol with IPython kernels. However, it doesn't say anywhere which ports to connect to. So it's nice and dandy to have a communication protocol, but totally useless if I don't know which ports to use.
The documentation mentions 'kernel specs' and tells me to use the jupyter kernelspec list command. This indeed shows me one directory, which only contains two files: logo-32x32.png and logo-64x64.png ...
How do I find the ports I need to connect to, to communicate with my IPython kernels?
I start my IPython kernel by running the following Python code from my C++ Qt app:
import IPython
IPython.start_kernel(argv=[])

A: It turns out Thomas K was right. The right approach to start an IPython/Jupyter kernel in a different process is: (with python3 as example)
import jupyter_client
kernel_manager, kernel_client = jupyter_client.start_new_kernel(kernel_name='python3')

When I initially tried this, I got a permission error. This was fixed by installing the python3 kernel spec (apparently Jupyter does not do this automatically...):
python3 -m ipykernel install --user

And then you can get the ports by
print(kernel_manager.get_connection_info())

It should be possible to use these ports to connect to the kernel via zero-mq. However, the kernel_client exposes a few methods to communicated with the kernel, so it may be easier to use that approach...


text:
Q: SFTP user can't edit or create files Server: Ubuntu 12.04 LTS
I am using openSSH and have created an SFTP user called bob who belongs to group sftponly. I have chrooted bob to his home directory which is /usr/share/nginx/www/bob/.
bob is able to SFTP onto the server and view is home directory, however he is unable to edit the files in his directory. I have run chown -R bob /usr/share/nginx/www/bob/* to make bob the owner of his files yet he is still unable to edit them.
Why would this be?

A: To properly chroot an sftponly group member, you need to set this options in /etc/ssh/sshd_config:

Subsystem       sftp    internal-sftp
Match Group sftponly
        ChrootDirectory /srv/chroot/%u
        ForceCommand internal-sftp

It is a requirement that the home directory, and the directories all the way up to the root of the system, of chrooted users must belong to root:root
Given the following values for a user:

$ id user001
uid=1003(user001) gid=1003(user001) groups=1006(sftponly)
$ grep user001 /etc/passwd
user001:x:1003:1003::/input:/sbin/nologin

You need a directory structure like this one:

$ tree /srv/chroot
/srv/chroot
├── user001
│   └── input

Because user001's HOME directory is evaluated after the chroot call, he/she lands in the input directory, where write permissions are valid:

$ ls -lrtd /srv/chroot/user001/input
drwxrwx--- 2 user001 sftponly 4.0K Apr 07 17:55 /srv/chroot/user001/input


text:
Q: How do i get google calendar descriptions to show in fullcalendar I would like to pull the description and location of my event from google calendar into fullCalendar. Ive got the time and title working fine, but I cant find anything to help me figure out how to show this other data. I've searched stackoverflow, but all related questions and answers are super old (like 2011).
If anyone could point me in the direct of a demo, or some documentation, or a question the solution to which still works I would be really grateful.


text:
Q: SQLite, Don't want to get max _id, I want to get the "next" _id Let's say I make 5 entries in a sqlite db.
_id | Name
1    Tom
2    Oskar
3    Matt
4    Mike
5    Ed

If I delete number 4 and 5, I only have 1-3. I then do a max _id query then I get number 3. But, of course I want the next auto incremented _id. What would be the method to do to get the number "6" in this example?

A: If your _id column has type INTEGER PRIMARY KEY AUTOINCREMENT, you can read the current sequence value from the sqlite_sequence table, and thus determine the next one:
SELECT seq + 1 FROM main.sqlite_sequence WHERE name = 'mytablename'


text:
Q: Can the function registered by then get its own resolve method just like Promise Constructor? Would the function that is registered/executed by the then method be able to catch hold of its own resolve?
A promise when its constructed is able to inject its resolve method like:
new Promise(function(resolve, reject){ async(resolve();})

However the action registered by then normally is triggered in resolve method like (at least in some examples I have seen):
resolve = function(value){
  self.value = value;
  self.state = "resolved";
  deferred.resolve(deferred.transform(self.value));
}

There is no real means to inject deferred.resolve into deferred.transform method. It almost as if the then doesn't expect the function it would execute to be asynchronous unlike like a Promise Constructor and hence it isn't isomorphic?
In Javascript Promise Sequence you actually create 8 Promises for a job that should ideally be done in 4 Promises. Can't this be solved if the transformation function registered by then can get hold of its own resolve which is the deferred.resolve? The transformation function can be ansychronous and it can resolve it when it's done.

A:
Would the function that is registered/executed by the then method be able to catch hold of its own resolve?

No.
Or at least not without returning a thenable that intercepts its callback, but that doesn't really make sense.

It almost as if the then doesn't expect the function it would execute to be asynchronous

Oh, it does. Your misunderstanding seems to be based on thinking that asynchronous functions are those that take callbacks. They aren't. Asynchronous functions are those that return promises! And then is totally capable dealing with them.

…unlike the Promise Constructor

It's the other way round. The Promise constructor is the odd one out here. Its only purpose is to transform old-style callback-taking functions to promises. You're expected to deal with fully promisified functions only these days, and new APIs will return promises right away.


text:
Q: Bloomed as an Adjective A "thick-trunked tree" means a tree with a thick trunk. Likewise, can we say "fragrant-bloomed tree" to say that the tree gives out fragrant blooms?

A: I don't know of any hard and fast rule against the usage you suggest, but I can't find any actual examples of the hyphenated form. Googling does throw up the occasional unhyphenated, "fragrant bloomed".
To test the basic structure, I did try "late" instead of "fragrant", and "late-bloomed" does appear in several places. However, what was obvious was that far more common is "late-blooming".
Conclusion: based on everyday usage, while "fragrant-bloomed tree" is probably acceptable, you might want to consider, "fragrant-blooming tree" as a safer alternative.

A: Generically yes, but this usage is rare at best for many possible combinations of adjective and noun.
The specific construct of taking a noun phrase with a single adjective and single noun, hyphenating it, and then adding 'ed' to the end to form an adjective is not linguistically productive (that is, it does not work for any arbitrary noun phrase that happens to fit the required structure), but it is recognized and understandable to most native speakers.
The complicating factor is that this type of adjective formation, even for the 'common' cases, is actually not all that common. There are a couple of idiomatic cases where the hyphenated form is preferred (such as 'thick-headed' or 'hard-headed' as synonyms for 'stubborn'), but these are very much the exception and not the rule. For other cases, you can often come up with specific sentences that utilize the hyphenated form, but most possible usage can be rephrased to avoid it, and those forms are more common in cases where they are valid. For example, 'a thick-trunked tree' can be trivially rephrased as 'a tree with a thick trunk', and that second form is usually the preferred one. Similarly with 'a fragrant-bloomed tree' and 'a tree with fragrant blooms'.
This particular case is also interesting though because 'bloom' is also a verb, and can be used to describe something trees do, so if the tree is blooming, you could also say 'a fragrantly-blooming tree' (the hyphen is optional here, I would not normally include it though).

A: That's a bit weird, only because it's rare.
It's probably going to be easier for your readers to parse "blossomed" at a glance instead (because we use "blossom" in the context of trees a lot more than "bloom").
"Blossomed" also sounds like a more acceptable adjective than "bloomed". This could be for all sorts of reasons, perhaps only because it has a more established usage (Google Ngrams provides cursory evidence that blossomed is more common than bloomed as an adjective), maybe because of some phonological reason (e.g. "blossomed" matches the trochaic stress pattern observed in most English adjectives, so it might naturally lend itself to being used as one), or a lexical one (conjecture: "bloom" is a state that the flower is in until it wilts, therefore a live flower can only be "blooming").
Feel free to use whichever one you want, there's no right answer - least of all in poetry. Use the one that captures the effect you want. At least to me: "bloomed" is about vitality, birth, flowers lens flares, and is in-your-face; "blossomed" is poignant, romantic, serene, multitudinous, dreamlike, promising, and timeless.


text:
Q: how to use Windows Cambria font on TexLive on Linux? This MWE
\documentclass{article}
\usepackage{unicode-math}
\setmainfont{Cambria}
\setmathfont{Cambria Math}
\begin{document}
$\sin(x)=0$
\end{document}

Compiles with no error using MikTeX 2.9 and lualatex on windows 10 since it finds the fonts on windows. But on Linux (Ubuntu) subsystem under same windows 10 PC running TeXLive 2019 it fails.
The question is: Since I own the same PC, and bought windows 10 professional, I'd like to ask if it possible to copy the fonts to my Linux disk from windows and use them and if this will work.
Using miktex:
>lualatex foo.tex
This is LuaTeX, Version 1.10.0 (MiKTeX 2.9.7000 64-bit)
 restricted system commands enabled.
(./foo.tex
LaTeX2e <2018-12-01>

luaotfload | main : initialization completed in 0.725 seconds
("C:/Users/me/AppData/Local/Programs/MiKTeX 2.9/tex/latex/base/article.cls"
Document Class: article 2018/09/03 v1.4i Standard LaTeX document class
("C:/Users/me/AppData/Local/Programs/MiKTeX 2.9/tex/latex/base/size10.clo"))
("C:/Users/me/AppData/Local/Programs/MiKTeX 2.9/tex/latex/unicode-math/unicode-
math.sty"
("C:/Users/me/AppData/Local/Programs/MiKTeX 2.9/tex/latex/l3kernel/expl3.sty"
("C:/Users/me/AppData/Local/Programs/MiKTeX 2.9/tex/latex/l3kernel/expl3-code.t
ex")
("C:/Users/me/AppData/Local/Programs/MiKTeX 2.9/tex/latex/l3kernel/l3pdfmode.de
f"))
("C:/Users/me/AppData/Local/Programs/MiKTeX 2.9/tex/latex/unicode-math/unicode-
math-luatex.sty"
("C:/Users/me/AppData/Local/Programs/MiKTeX 2.9/tex/latex/l3packages/xparse/xpa
rse.sty")
("C:/Users/me/AppData/Local/Programs/MiKTeX 2.9/tex/latex/l3packages/l3keys2e/l
3keys2e.sty")
("C:/Users/me/AppData/Local/Programs/MiKTeX 2.9/tex/latex/fontspec/fontspec.sty
"
("C:/Users/me/AppData/Local/Programs/MiKTeX 2.9/tex/latex/fontspec/fontspec-lua
tex.sty"
("C:/Users/me/AppData/Local/Programs/MiKTeX 2.9/tex/latex/base/fontenc.sty"
("C:/Users/me/AppData/Local/Programs/MiKTeX 2.9/tex/latex/base/tuenc.def"))
("C:/Users/me/AppData/Local/Programs/MiKTeX 2.9/tex/latex/fontspec/fontspec.cfg
")))
("C:/Users/me/AppData/Local/Programs/MiKTeX 2.9/tex/latex/filehook/filehook.sty
") ("C:/Users/me/AppData/Local/Programs/MiKTeX 2.9/tex/latex/base/fix-cm.sty"
("C:/Users/me/AppData/Local/Programs/MiKTeX 2.9/tex/latex/base/ts1enc.def"))
("C:/Users/me/AppData/Local/Programs/MiKTeX 2.9/tex/lualatex/lualatex-math/lual
atex-math.sty"
("C:/Users/me/AppData/Local/Programs/MiKTeX 2.9/tex/latex/etoolbox/etoolbox.sty
"))
("C:/Users/me/AppData/Local/Programs/MiKTeX 2.9/tex/latex/unicode-math/unicode-
math-table.tex"))) (./foo.aux) [1{C:/Users/me/AppData/Local/MiKTeX/2.9/pdftex/c
onfig/pdftex.map}] (./foo.aux))
 419 words of node memory still in use:
   3 hlist, 1 vlist, 1 rule, 2 glue, 3 kern, 1 glyph, 6 attribute, 49 glue_spec
, 6 attribute_list, 1 write nodes
   avail lists: 1:1,2:23,3:19,4:1,5:33,6:2,7:78,8:15,9:15,11:1
<C:/WINDOWS/Fonts/cambria.ttc><C:/WINDOWS/Fonts/cambria.ttc><C:/WINDOWS/Fonts/c
ambria.ttc>
Output written on foo.pdf (1 page, 86448 bytes).
Transcript written on foo.log.

Using TeXLive 2019
>lualatex foo.tex
This is LuaTeX, Version 1.10.0 (TeX Live 2019)
 restricted system commands enabled.
(./foo.tex
LaTeX2e <2018-12-01>

luaotfload | main : initialization completed in 0.105 seconds
(/usr/local/texlive/2019/texmf-dist/tex/latex/base/article.cls
Document Class: article 2018/09/03 v1.4i Standard LaTeX document class
(/usr/local/texlive/2019/texmf-dist/tex/latex/base/size10.clo))
(/usr/local/texlive/2019/texmf-dist/tex/latex/unicode-math/unicode-math.sty
(/usr/local/texlive/2019/texmf-dist/tex/latex/l3kernel/expl3.sty
(/usr/local/texlive/2019/texmf-dist/tex/latex/l3kernel/expl3-code.tex)
(/usr/local/texlive/2019/texmf-dist/tex/latex/l3kernel/l3pdfmode.def))
(/usr/local/texlive/2019/texmf-dist/tex/latex/unicode-math/unicode-math-luatex.
sty (/usr/local/texlive/2019/texmf-dist/tex/latex/l3packages/xparse/xparse.sty)
 (/usr/local/texlive/2019/texmf-dist/tex/latex/l3packages/l3keys2e/l3keys2e.sty
) (/usr/local/texlive/2019/texmf-dist/tex/latex/fontspec/fontspec.sty
(/usr/local/texlive/2019/texmf-dist/tex/latex/fontspec/fontspec-luatex.sty
(/usr/local/texlive/2019/texmf-dist/tex/latex/base/fontenc.sty
(/usr/local/texlive/2019/texmf-dist/tex/latex/base/tuenc.def))
(/usr/local/texlive/2019/texmf-dist/tex/latex/fontspec/fontspec.cfg)))
(/usr/local/texlive/2019/texmf-dist/tex/latex/filehook/filehook.sty)
(/usr/local/texlive/2019/texmf-dist/tex/latex/base/fix-cm.sty
(/usr/local/texlive/2019/texmf-dist/tex/latex/base/ts1enc.def))
(/usr/local/texlive/2019/texmf-dist/tex/lualatex/lualatex-math/lualatex-math.st
y (/usr/local/texlive/2019/texmf-dist/tex/latex/etoolbox/etoolbox.sty))
(/usr/local/texlive/2019/texmf-dist/tex/latex/unicode-math/unicode-math-table.t
ex)))
luaotfload | db : Reload initiated (formats: otf,ttf,ttc); reason: "Font Cambria not found.".
luaotfload | resolve : sequence of 3 lookups yielded nothing appropriate.

! Package fontspec Error: The font "Cambria" cannot be found.

For immediate help type H <return>.
 ...

l.5 \setmathfont
              {Cambria Math}
?

I use only lualatex.  The following is what I see under windows
>dir C:\WINDOWS\Fonts\cambria*

09/15/2018  02:28 AM         1,792,664 cambria.ttc
09/15/2018  02:28 AM           841,440 cambriab.ttf
09/15/2018  02:28 AM           892,620 cambriai.ttf
09/15/2018  02:28 AM           856,672 cambriaz.ttf
               4 File(s)      4,383,396 bytes

If it is possible to copy the above files as is to Linux and use them in TL, please provide exact instructions on how to do this and where to put them in Linux and any other commands or configuration needed to make the file compiles OK on Linux under TL 2019. Will copying them to texmf-local/fonts/ for example work and be enough? Are these files independent of operating system?


text:
Q: No matching signature for operator < for argument types: STRING, INT64 SELECT
CAST(CONCAT(TRIM(SUBSTR(Date, 6,5)),"-",IF(SUBSTR(Date, 1,1)<10,0,""),SUBSTR(Date, 1,1),"-",SUBSTR(Date, 3,2))AS DATE)
FROM XXXXX LIMIT 1000
hello, Guys I have problems with "IF" because I want to put a condition for the month. Someone can help me, please?
thank you for your time


text:
Q: Multer fileFilter is not getting called and req.body is empty for some reason the fileFilter on multer is not getting called.
here is my Controller (i am using express routers)
const express = require('express');
const router = express.Router();
const UploadController = require('../controllers/UploadController');

router.route('/upload').post(UploadController.upload);

module.exports = router;

and this is the controller
const multer = require('multer');
const fs = require('fs');

module.exports = {
    upload: function (req, res) {
        let storage = multer.diskStorage({
            destination: function (req, file, cb) {
                console.log('here');
                const filesDir = './uploads/' + req.body.ref;
                if (!fs.existsSync(filesDir)) {
                    fs.mkdirSync(filesDir);
                }
                cb(null, filesDir);
            },
            filename: function (req, file, cb) {
                let extArray = file.mimetype.split("/");
                let extension = extArray[extArray.length - 1];
                cb(null, req.body.type + '-' + Date.now() + '.' + extension);
            },
            fileFilter : function (req, file, cb) {
                if (!file.originalname.match(/\.(jpg|jpeg|png|gif)$/)) {
                    return cb(new Error('Only image files are allowed!'), false);
                }
                cb(null, true);
            }
        })
        const upload = multer({ storage: storage }).single('file');

        upload(req, res, function (err) {
            if (err instanceof multer.MulterError) {
                res.send({
                    error: err
                });
            } else if (err) {
                res.send({
                    error: err
                });
            }else{
                res.send({
                    file: req.file,
                    body: req.body
                });
            }

        });
    }
}

I have following issues:

*

*The fileFilter function is not even called so its not validating files

*the req.body on the upload function (upload: function (req, res)) is empty it is only available in diskStorage and last upload function (upload(req, res, function (err)) so i cannot validate  the body data also.

A: I had the same problem. the fileFilter function has to be defined inside multer, not inside the diskStorage function.
To make it a bit more readable I defined the storage and filter in variables instead of making everything inside the multer call.
// storage settings
const multerStorage = multer.diskStorage({
    destination: function(req, file, next) {
        next(null, './public/files');
    },
    filename: function(req, file, next) {
        const sanitizedName = file.originalname
            .replace('/[^a-z0-9\./gi', '-')
            .replace('/-{2,}/g', '-')
            .toLowerCase();
         const name = Date.now() + '-' + sanitizedName;

         // sending the file name to be stored in the database
         req.body.filename = name;

         next(null, name);
     },
     limits: {
         fileSize: 25000000
     }
 });

 // filter function
 const multerFilter = function(req, file, cb) {
     const ext = path.extname(file.originalname).toLowerCase();

     if (ext !== '.pdf') {
         cb(new Error('File must be in PDF format.'));
     }

     cb(null, true);
 }

And then applying the storage settings and filter function to multer:
const upload = multer({
    storage: multerStorage,
    fileFilter: multerFilter
});


text:
Q: Why does clearRect not work on html5 canvas I have tried a simple animation of text on canvas. However it does not clear the canvas whenever i press animate again. clearRect() function is not working properly.
here is the code:
document.getElementById('click').onclick = function() {

 var startTime = new Date().getTime();
 var interval = setInterval(function() {
    if (new Date().getTime() - startTime > 2000) {
      clearInterval(interval);
    }
    ctx.clearRect(0, 0, canvas.width, canvas.width);

    animateText();
  }, 33);

}

Here is the fiddle
Should animate from beginning(the first instance) everytime I click animate button.

A: Your screen is being cleared, its just that you didn't reset any value, like distance and speed. Also, keep in mind that you are creating a new interval every time you click the button (since you are using var ).
So, you'll need to reset the values every click, and remove var.
Additionally, your clearInterval(interval); seems to be slightly delayed... So try that every button click.
document.getElementById('click').onclick = function() {

 var startTime = new Date().getTime();
 clearInterval(interval); //clearinterval
 distance = 0; //reset values
 speed = 15; //reset values
 interval = setInterval(function() {
    if (new Date().getTime() - startTime > 2000) {
      clearInterval(interval);
    }
    ctx.clearRect(0, 0, canvas.width, canvas.width);

    animateText();
  }, 33);

}


text:
Q: Bower: Installing legacy bootstrap (2.3.2) with bower I have an open source webapp using bootstrap 2.3.2 and which Currently I can't move to bootstrap 3 (completely different grid system) - I'm trying to move the webapp to use bower to handle dependencies but bower install bootstrap#2.3.2 fetches something that looks as the raw code repo not built, for example no css folder, just the seperate less files, no one minified bootstrap.min.js but multiple different plugins (not concatenated) etc..
Is this fixable? should I install differently?

A: You are doing everything correct.  Take a look at the README for v2.3.2 on github

Bootstrap includes a makefile with convenient methods for working with
  the framework. Before getting started, be sure to install the
  necessary local dependencies:
$ npm install When completed, you'll be able to run the various make
  commands provided:
build - make
Runs the recess compiler to rebuild the /less files and compiles the
  docs. Requires recess and uglify-js.
test - make test
Runs jshint and qunit tests headlessly in phantomjs (used for ci).
  Depends on having phantomjs installed.
watch - make watch

A: The solution I ended up with: forked bootstrap repo, cleaned up(other branches etc..) git reset --hard to the v2.3.2 tag - checked it into another branch and pushe it to github. more cleanup (removing the old master branch, higher tags). run the build processes and setup an "updated" dist folder for the v2.3.2 tag. changed the bower package and published it as bootstrap2.3.2 package.
Now I (and everyone else) can install with bower install from this repo. The results are here if someone want to use it.

A: I just ran into this and was basically setting up my own fork of Bootstrap 2.3.2 (before I noticed your answer). As I dove in, I noticed that Bootstrap 2.3.2 actually does come with pre-built assets you can use in your project. While it's not as obvious as the dist/ directory in Bootstrap 3, you can find the location of the prebuilt assets in the project's bower.json:
"main": ["./docs/assets/js/bootstrap.js", "./docs/assets/css/bootstrap.css"],

So there you go. Add {"bootstrap": "~2.3.2"} to your bower.json dependencies like you normally would, then use it like this:
<link href="bower_components/bootstrap/docs/assets/css/bootstrap.css" rel="stylesheet">
<script src="bower_components/bootstrap/docs/assets/js/bootstrap.js"></script>

No build step required.


text:
Q: How to disable keyboard in TimePickerDialog android? I am using timepicker and datepicker in my app. i want to disable keyboard in both these. i am able to disable keyboard in date picker with below code.
datePickerDialog.getDatePicker().setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);

but not getting how to disable keyboard in timepickerdialog.
i tried below popular example but still no use
public class TimePickerFragment extends DialogFragment implements TimePickerDialog.OnTimeSetListener
{
    private TimePickerDialog timePickerDialog;

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState)
    {
        //Default 6:00
        timePickerDialog = new TimePickerDialog(getActivity(), this, 6, 0, android.text.format.DateFormat.is24HourFormat(getActivity()));

        return timePickerDialog;
    }

    @Override
    public void onStart()
    {
        super.onStart();

        final View hourView = timePickerDialog.findViewById(Resources.getSystem().getIdentifier("hour", "id", "android"));
        final View minuteView = timePickerDialog.findViewById(Resources.getSystem().getIdentifier("minute", "id", "android"));

        if (hourView != null && hourView instanceof NumberPicker)
        {
            ((NumberPicker) hourView).setDescendantFocusability(TimePicker.FOCUS_BLOCK_DESCENDANTS);
        }

        if (minuteView != null && minuteView instanceof NumberPicker)
        {
            ((NumberPicker) minuteView).setDescendantFocusability(TimePicker.FOCUS_BLOCK_DESCENDANTS);
        }
    }

    @Override
    public void onTimeSet(TimePicker view, int hourOfDay, int minute)
    {
        ((MenuEditActivity) getActivity()).setRecipeTime(hourOfDay, minute);
    }

    @Override
    public void onCancel(DialogInterface dialog)
    {
        super.onCancel(dialog);
    }
}

any help?

A: Solved the issue by creating custom Dialog and extending TimePickerDialogClass
public class CustomTimePickerDialog extends TimePickerDialog {

private int currentHour = 0;
private int currentMinute = 0;

private Calendar calendar = Calendar.getInstance();
private DateFormat dateFormat;

public RangeTimePickerDialog(Context context, OnTimeSetListener callBack, int hourOfDay, int minute, boolean is24HourView) {
    super(context, callBack, hourOfDay, minute, is24HourView);
    currentHour = hourOfDay;
    currentMinute = minute;
    dateFormat = DateFormat.getTimeInstance(DateFormat.SHORT);

    try {
        Class<?> superclass = getClass().getSuperclass();
        Field mTimePickerField = superclass.getDeclaredField("mTimePicker");
        mTimePickerField.setAccessible(true);
        TimePicker mTimePicker = (TimePicker) mTimePickerField.get(this);
        mTimePicker.setOnTimeChangedListener(this);
    } catch (NoSuchFieldException e) {
    } catch (IllegalArgumentException e) {
    } catch (IllegalAccessException e) {
    }

    fixSpinner(context, hourOfDay, minute, is24HourView);
}

@Override
public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {

    updateTime(currentHour, currentMinute);
    updateDialogTitle(view, currentHour, currentMinute);
}

private void updateDialogTitle(TimePicker timePicker, int hourOfDay, int minute) {
    calendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
    calendar.set(Calendar.MINUTE, minute);
    String title = dateFormat.format(calendar.getTime());
    setTitle(title);
}

private void fixSpinner(Context context, int hourOfDay, int minute, boolean is24HourView) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { // android:timePickerMode spinner and clock began in Lollipop
        try {
            // Get the theme's android:timePickerMode
            final int MODE_SPINNER = 2;
            Class<?> styleableClass = Class.forName("com.android.internal.R$styleable");
            Field timePickerStyleableField = styleableClass.getField("TimePicker");
            int[] timePickerStyleable = (int[]) timePickerStyleableField.get(null);
            final TypedArray a = context.obtainStyledAttributes(null, timePickerStyleable, android.R.attr.timePickerStyle, 0);
            Field timePickerModeStyleableField = styleableClass.getField("TimePicker_timePickerMode");
            int timePickerModeStyleable = timePickerModeStyleableField.getInt(null);
            final int mode = a.getInt(timePickerModeStyleable, MODE_SPINNER);
            a.recycle();
            if (mode == MODE_SPINNER) {
                TimePicker timePicker = (TimePicker) findField(TimePickerDialog.class, TimePicker.class, "mTimePicker").get(this);
                Class<?> delegateClass = Class.forName("android.widget.TimePicker$TimePickerDelegate");
                Field delegateField = findField(TimePicker.class, delegateClass, "mDelegate");
                Object delegate = delegateField.get(timePicker);
                Class<?> spinnerDelegateClass;
                if (Build.VERSION.SDK_INT != Build.VERSION_CODES.LOLLIPOP) {
                    spinnerDelegateClass = Class.forName("android.widget.TimePickerSpinnerDelegate");
                } else {
                    // TimePickerSpinnerDelegate was initially misnamed TimePickerClockDelegate in API 21!
                    spinnerDelegateClass = Class.forName("android.widget.TimePickerClockDelegate");
                }
                // In 7.0 Nougat for some reason the timePickerMode is ignored and the delegate is TimePickerClockDelegate
                if (delegate.getClass() != spinnerDelegateClass) {
                    delegateField.set(timePicker, null); // throw out the TimePickerClockDelegate!
                    timePicker.removeAllViews(); // remove the TimePickerClockDelegate views
                    Constructor spinnerDelegateConstructor = spinnerDelegateClass.getConstructor(TimePicker.class, Context.class, AttributeSet.class, int.class, int.class);
                    spinnerDelegateConstructor.setAccessible(true);
                    // Instantiate a TimePickerSpinnerDelegate
                    delegate = spinnerDelegateConstructor.newInstance(timePicker, context, null, android.R.attr.timePickerStyle, 0);
                    delegateField.set(timePicker, delegate); // set the TimePicker.mDelegate to the spinner delegate
                    // Set up the TimePicker again, with the TimePickerSpinnerDelegate
                    timePicker.setIs24HourView(is24HourView);
                    timePicker.setCurrentHour(hourOfDay);
                    timePicker.setCurrentMinute(minute);
                    timePicker.setOnTimeChangedListener(this);

timePicker.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

private static Field findField(Class objectClass, Class fieldClass, String expectedName) {
    try {
        Field field = objectClass.getDeclaredField(expectedName);
        field.setAccessible(true);
        return field;
    } catch (NoSuchFieldException e) {} // ignore
    // search for it if it wasn't found under the expected ivar name
    for (Field searchField : objectClass.getDeclaredFields()) {
        if (searchField.getType() == fieldClass) {
            searchField.setAccessible(true);

            return searchField;
        }
    }
    return null;
}

}
Added the following code in fixSpinner() function
timePicker.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS)
And use it as
 CustomTimePickerDialog timePickerDialog;
 timePickerDialog=new CustomTimePickerDialog (context,
                            timePickerListener, hour, minute,false);

 timePickerDialog.show();
 private TimePickerDialog.OnTimeSetListener timePickerListener =
        new TimePickerDialog.OnTimeSetListener() {
            public void onTimeSet(TimePicker view, int selectedHour,
                                  int selectedMinute) {
                hour = selectedHour;
                minute = selectedMinute;

            }
        };

A: I use TimePickerDialog like this
dialog = new TimePickerDialog(getActivity(), android.R.style.Theme_Holo_Light_Dialog_NoActionBar, listener, hour, minute);

The keyboard is disabled when android:descendantFocusability is blocksDescendants.
so I change android:descendantFocusability  in android:timePickerStyle
<style name="Theme.MyApp.TimePicker" parent="android:Widget.Material.TimePicker">
    <item name="android:timePickerMode">spinner</item>
    <item name="android:descendantFocusability">blocksDescendants</item>
</style>
<style name="Theme.MyApp.Picker" parent="android:Theme.Holo.Light.Dialog.NoActionBar">
    <item name="android:timePickerStyle">@style/Theme.MyApp.TimePicker</item>
</style>

dialog = new TimePickerDialog(getActivity(), R.style.Theme_MyApp_Picker, listener, hour, minute);

I don`t know what style you put in 'this' part
@Override
public Dialog onCreateDialog(Bundle savedInstanceState)
{
    //Default 6:00
    timePickerDialog = new TimePickerDialog(getActivity(), this, 6, 0, android.text.format.DateFormat.is24HourFormat(getActivity()));

    return timePickerDialog;
}

A: try this
public void ADDHideSoftKeyboard() {
        InputMethodManager lIMM;
        try {
            lIMM = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            lIMM.hideSoftInputFromWindow(pView.getWindowToken(), 0);
        }
    }

A: use this for time picker
public static class TimePickerFragment extends DialogFragment implements TimePickerDialog.OnTimeSetListener {
            TextView lTextViewTime;

            public TimePickerFragment(TextView pTextViewTime) {
                lTextViewTime = pTextViewTime;
            }

            @Override
            public Dialog onCreateDialog(Bundle savedInstanceState) {
                final Calendar lCal = Calendar.getInstance();
                int lHour, lMinute;
                lHour = lCal.get(Calendar.HOUR_OF_DAY);
                lMinute = lCal.get(Calendar.MINUTE);
                return new TimePickerDialog(getActivity(), this, lHour, lMinute, DateFormat.is24HourFormat(getActivity()));
            }

            @Override
            public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                lTextViewTime.setText(((hourOfDay < 10) ? ("0" + hourOfDay) : (hourOfDay)) + ":" + ((minute < 10) ? ("0" + minute) : (minute)));
            }
        }


text:
Q: Cannot find library with simple C++ example I am building a C++ library called alpha in Ubuntu with cmake, which contains one source file:
cmake_minimum_required(VERSION 2.8)

project(Alpha)

add_library (alpha alpha.cpp)

This creates a file called libalpha.a, which I now want to link to. So, I copy it into the source directory of another C++ projected called beta, which also contains one source file:
cmake_minimum_required(VERSION 2.8)

project(Beta)

add_executable(beta beta.cpp)

target_link_libraries(beta alpha)

However, I get the following error:
/usr/bin/ld: cannot find -lalpha

The same thing happens if I use the line:
target_link_libraries(beta libalpha.a)

Why can beta not find the alpha library?

A: If you wish to build the library and the program completely separately, you have to use imported targets. When you try to link your executable against a "completely unknown" library, CMake build system automatically passes the task of locating the library to the linker, simply adding -lalpha option. When the linker encounters the option it attempts to locate libalpha.so in one of the standard library locations (i.e. /usr/lib/, /usr/local/lib etc) and expectedly fails. You can use an absolute path to the libalpha.a: target_link_libraries(beta /path/to/libalpha.a).
However if you can build things together, this greatly simplifies the task. Consider
<project>/CMakeLists.txt:
cmake_minimum_required(VERSION 2.8)

Project(Test)

add_subdirectory(alpha)
add_subdirectory(beta)

<project>/alpha/CMakeLists.txt
cmake_minimum_required(VERSION 2.8.11)

project(alpha)

set(SOURCES alpha.c)

add_library(alpha ${SOURCES})
target_include_directories(
  alpha INTERFACE
  "$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}>"
  "$<BUILD_INTERFACE:${CMAKE_CURRENT_BINARY_DIR}>"
)

target_include_directories() with the complex expression within is required to automatically add libalpha include directories to all components which later are linked against libalpha.
<project>/beta/CMakeLists.txt
project(beta)

set(SOURCES beta.c)

add_executable(beta ${SOURCES})
target_link_libraries(beta alpha)

A: Add this line with the path to alpha-library.
link_directories( <library path> )


text:
Q: Tint is inverting colors in swift I'm trying out this code to tint color a UIImage but it seems to be inverting the colors - coloring the background and turning the black stroke to white.
How do I have it color the black stroke lines of an image and leave the white background alone?  Here's a playground sample where I try one technique as well as another one suggested by the first answer.
Playground Code
 extension UIImage {

    func tint(color: UIColor, blendMode: CGBlendMode = CGBlendMode.Normal) -> UIImage
    {
        UIGraphicsBeginImageContextWithOptions(self.size, false, self.scale);
        let context = UIGraphicsGetCurrentContext();
        CGContextTranslateCTM(context, 0, self.size.height);
        CGContextScaleCTM(context, 1.0, -1.0);
        CGContextSetBlendMode(context, blendMode);
        let rect = CGRectMake(0, 0, self.size.width, self.size.height);
        CGContextClipToMask(context, rect, self.CGImage);
        color.setFill()
        CGContextFillRect(context, rect);
        let newImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        return newImage;
    }

    func tint2(color: UIColor, blendMode: CGBlendMode) -> UIImage
    {
        let drawRect = CGRectMake(0.0, 0.0, size.width, size.height)
        UIGraphicsBeginImageContextWithOptions(size, false, scale)
        let context = UIGraphicsGetCurrentContext()
        CGContextClipToMask(context, drawRect, CGImage)
        color.setFill()
        UIRectFill(drawRect)
        drawInRect(drawRect, blendMode: blendMode, alpha: 1.0)
        let tintedImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return tintedImage
    }

}

let stringUrl = "https://s3.amazonaws.com/neighbor-chat-assets/icons/avatar1000.png"

let url = NSURL(string: stringUrl)

let data = NSData(contentsOfURL: url!)

var originalimage = UIImage(data: data!)

var image = originalimage!.imageWithRenderingMode(.AlwaysTemplate).tint(UIColor.blueColor(), blendMode:.Normal)
var image2 = originalimage!.imageWithRenderingMode(.AlwaysTemplate).tint2(UIColor.blueColor(), blendMode:.Normal)

A: This should work, I just tested it with a png and transparent background
func tint(color: UIColor, blendMode: CGBlendMode = CGBlendMode.Normal) -> UIImage
{
    UIGraphicsBeginImageContextWithOptions(self.size, false, self.scale);
    let context = UIGraphicsGetCurrentContext();
    CGContextTranslateCTM(context, 0, self.size.height);
    CGContextScaleCTM(context, 1.0, -1.0);
    CGContextSetBlendMode(context, blendMode);
    let rect = CGRectMake(0, 0, self.size.width, self.size.height);
    CGContextClipToMask(context, rect, self.CGImage);
    color.setFill()
    CGContextFillRect(context, rect);
    let newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}

Also see this post for further information. The alternative would be to wrap your image in a UIImageView with UIImageRenderingMode.AlwaysTemplate rendering mode, and then set the tintColor property.
EDIT
So this is the function you can use to first mask out certain colors if you don't have an alpha channel in an image
func tint(color: UIColor, blendMode: CGBlendMode = CGBlendMode.Normal, colorToMask: UIColor = UIColor.blackColor()) -> UIImage
{
    var fRed : CGFloat = 0
    var fGreen : CGFloat = 0
    var fBlue : CGFloat = 0
    var fAlpha: CGFloat = 0
    colorToMask.getRed(&fRed, green: &fGreen, blue: &fBlue, alpha: &fAlpha)

    let rect = CGRectMake(0, 0, self.size.width, self.size.height);
    var colorMasking : [CGFloat] = [fRed,fRed,fGreen,fGreen,fBlue,fBlue]
    let newImageRef = CGImageCreateWithMaskingColors(self.CGImage!, &colorMasking)

    UIGraphicsBeginImageContextWithOptions(self.size, false, self.scale);
    let context = UIGraphicsGetCurrentContext();

    CGContextTranslateCTM(context, 0, self.size.height);
    CGContextScaleCTM(context, 1.0, -1.0);
    CGContextSetBlendMode(context, blendMode);
    CGContextClipToMask(context, rect, newImageRef!);
    color.setFill()
    CGContextFillRect(context, rect);

    let newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return newImage;
}

This function first creates a mask depending on the specified color, and clips the context to this mask.
EDIT #2
As stated in the comments, I also didn't manage to mask out the white color, I tried UInt8 values (i.e. 255) and float values (i.e. 1.0), but it still didn't work. So the only solution I could come up with was to invert the image. Here is the function:
func negativeImage() -> UIImage {

    let coreImage = MYImage(CGImage: self.CGImage!)
    let filter = CIFilter(name: "CIColorInvert", withInputParameters: ["inputImage" : coreImage])!
    let result = filter.outputImage!
    let context = CIContext(options:nil)
    let cgimg : CGImageRef = context.createCGImage(result, fromRect: result.extent)

    let bmpcontext = CGBitmapContextCreate(nil, Int(self.size.width), Int(self.size.height), 8, Int(self.size.width)*4, CGColorSpaceCreateDeviceRGB(),CGImageAlphaInfo.NoneSkipLast.rawValue)
    CGContextDrawImage(bmpcontext, CGRectMake(0, 0, self.size.width, self.size.height), cgimg)
    let newImgRef = CGBitmapContextCreateImage(bmpcontext)!
    return UIImage(CGImage: newImgRef)
}

You can use it like this
var image : UIImage = ...
image = image.negativeImage()
image = image.tint(UIColor.redColor())

Here are some general notes

*

*CGImageCreateWithMaskingColors requires a CGImage with NO alpha channel, that's why I use the flag CGImageAlphaInfo.NoneSkipLast in the negativeImage function in order to remove the alpha channel again

*There is absolutely no error checking included in this, you should at least check whether there is an alpha channel included within the tint function using CGImageGetAlphaInfo

*You can either have the masked out parts (white in our example) transparent (by setting false in the UIGraphicsBeginImageContextWithOptions command within the tint function), or a specific color by setting true, which is black by default (you would need to paint before clipping to the mask).


text:
Q: what does this mean in native Android java.? i am newbie in Android native development.while tracing code i found this code,but unable to understand what that does ..
My doubt in these is ,
1.)if we are using a interface methods in Activity.java ,shouldnt i make Activity.java to use implement keyword to implement those methods mentioned in Icommand Interface.
2.)If not then What is it doing here.is Variable onsuccess is an object or instance of interface?
please could anyone help me to understand this.
In Icommand.java
 public interface ICommand<T, S> {
public T execute(S params) throws Exception;
     }

In Activity.java
public class Activity extends BaseActivity {
 private ICommand<Void, String> onSuccess = new ICommand<Void, String>() {
    @Override
    public Void execute(String params) throws Exception {
        Activity.this.setPreferenceValue(Constants.PREF_PHONENUMBER, params);

        Activity.this.setPreferenceValue(Constants.PREF_HASPHONENUMBER, "true");
       Activity.this.finish();
        return null;
    }
};

}

A: yes, you have to implement to your Interface, and Override methods you have there, thats the function.
It works as a Callback, so for example you start a new Thread, you can you the CallBack and pass to your Thread or AsyncTask and then in that new Class call the interface method. this automatically  will call the activity method that you Override from your Interface. Very usefull to update some UI after some tasks.
Of course you can too use an internal class Callback Listener, but this is not recommendable. Code is more readable using implement and Overriding functions as well.
Hope thats help.
Regards.


text:
Q: How can I clear a write("message") Basically, I have a button that write("message"+myVar).
Then I want to press a button that will delete the written message, but not mess with the variable at all.
I am very new to coding. I code on Code.org which is powered by javascript.
Much thanks

A: Welcome to SO. Always try to share your code so anyone can help you better. As much as I understand there are lots of ways to achieve this. The most straightforward one could be to create a textLabel with an empty string and then modify it with the setText property of code.org. Like so;
var myVar = "something";
textLabel("messageId","");

button("createButton", "create");
onEvent("createButton", "click", function( ) {
  setText("messageId", "message" + myVar);
});

button("deleteButton", "delete");
onEvent("deleteButton", "click", function( ) {
  setText("messageId",myVar);
});


text:
Q: Canvas: Path with negative and large positive numbers With my Android App I have a view that can be zoomed and panned. On that view I want to draw a line for the following points. But the path is not shown at all. I wonder if this has anything to do with the negative or large numbers in the list of points.
{"x":-317,"y":-744},
{"x":50,"y":-702},
{"x":394,"y":-663},
{"x":718,"y":-626},
{"x":1023,"y":-592},
{"x":1310,"y":-560},
{"x":1581,"y":-529},
{"x":1837,"y":-500},
{"x":2079,"y":-472},
{"x":2951,"y":198},
{"x":5997,"y":4780},
{"x":4064,"y":4143},
{"x":2686,"y":3689},
{"x":1654,"y":3348},
{"x":852,"y":3084},
{"x":211,"y":2873},
{"x":-312,"y":2700},
{"x":-748,"y":2556},
{"x":-895,"y":2213},
{"x":-574,"y":569},
{"x":-317,"y":-744}]}
Here's the code snippet.
private final Paint paintStrokeArea = new Paint(Paint.ANTI_ALIAS_FLAG);
private Point[] viewArea = ...

public MyView(Context context, AttributeSet attributeSet) {
    super(context, attributeSet);

    paintStrokeArea.setColor(Color.WHITE);
    paintStrokeArea.setStyle(Style.STROKE);
    paintStrokeArea.setStrokeWidth(4.5f);
    paintStrokeArea.setStrokeJoin(Join.MITER);
    paintStrokeArea.setPathEffect(null);
}

public onDraw(Canvas) {
    if (viewArea != null)
        renderViewArea(viewArea, canvas, paintStroke);
}

public static void renderViewArea(Point[] area, Canvas canvas, Paint paint) {
    if (area == null || canvas == null || paint == null)
        return;

    boolean first = true;
    Path path = new Path();
    Point last = new Point();

    for (Point current : area) {
        if (first) {
            first = false;
        } else {
            path.moveTo(last.x, last.y);
            path.lineTo(current.x, current.y);
        }

        last.set(current.x, current.y);
    }

    if (!first)
        canvas.drawPath(path, paint);
}

A: The same problem was described in this post. According to the answers, the problem occurs because drawPath is done in CPU by rendering it into a bitmap that is than transferred into the GPU. Because my path was too large, the bitmap could not be rendered (send to) the GPU. Better use drawLines because it uses the GPU directly. Here's a helper class that I encapsulated.
package eu.level12.tools;

import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Point;

/**
 * Provides several static methods for drawing onto Android's canvas.
 * Hardware-accelerated methods are named with the prefix render while others
 * begin with draw.
 *
 * @author Matthias Heise
 *
 */
public final class DrawingTools {

    /**
     * Draws the line specified by the given path using hardware-accelerated
     * method Canvas.drawLines. Has no effect if either argument is null or if
     * the line consists of less than two points.
     *
     * @param path
     *            A path of points that specifies the line.
     * @param canvas
     *            The canvas onto which the line should be drawn.
     * @param paint
     *            The paint argument that specifies how the line is drawn.
     */
    public static void renderLine(Point[] path, Canvas canvas, Paint paint) {

        if (path == null || canvas == null || paint == null || path.length <= 1)
            return;

        final float[] lines = new float[(path.length - 1) * 4];
        int index = 0;
        final Point last = new Point();
        boolean first = true;

        for (Point current : path) {
            if (first) {
                first = false;
            } else {

                // start point
                lines[index] = last.x;
                lines[index + 1] = last.y;

                // end point
                lines[index + 2] = current.x;
                lines[index + 3] = current.y;

                index += 4;
            }

            last.set(current.x, current.y);
        }

        if (!first)
            canvas.drawLines(lines, paint);
    }
}


text:
Q: How to pass jenkins credentials into docker build command? My Jenkins pipeline code successfully checks out my private git repo from bitbucket using
checkout([$class: 'GitSCM',
            userRemoteConfigs: [[credentialsId: 'cicd-user', url:'ssh://git@bitbucket.myorg.co:7999/A/software.git']]

in same software.git I have a Dockerfile that I want to use to build various build targets present in software.git on Kubernetes and I am trying the below to pass jenkins credentials into a docker container that I want to build and run.
So in the same jenkins pipeline when I checked out software.git (above code), I try to do the following to get the docker container built
  withCredentials([sshUserPrivateKey(credentialsId: 'cicd-user', keyFileVariable: 'FILE')]) {
           sh "cd ${WORKSPACE} && docker build -t ${some-name} --build-arg USERNAME=cicd-user --build-arg  PRIV_KEY_FILE=$FILE --network=host -f software/tools/jenkins/${some-name}/Dockerfile ."
        }

in Dockerfile I do
RUN echo "$PRIV_KEY_FILE" > /home/"$USERNAME"/.ssh/id_rsa && \
 chmod 700 /home/"$USERNAME"/.ssh/id_rsa

RUN echo "Host bitbucket.myorg.co\n\tStrictHostKeyChecking no\n" >> ~/.ssh/config
But still from my Docker container I am  not able to successfully checkout my private repo(s). What am I missing ? Any comments, suggestions ? Thanks.

A: Please read about Groovy String Interpolation.
In your expression
sh "cd ${WORKSPACE} && docker build -t ${some-name} \
--build-arg USERNAME=cicd-user \
--build-arg  PRIV_KEY_FILE=$FILE --network=host \
-f software/tools/jenkins/${some-name}/Dockerfile ."

you use double quotes so Groovy interpolates all the variables in the string. This includes $FILE so Groovy replaces that with the value of Groovy variable named FILE. You don't have any Groovy variable with that name (but rather bash variable which is different from Groovy) so this gets replaced with an empty string.
To prevent interpolating that particular variable, you need to hint Groovy not to interpolate this particular one, by escaping this $ with \:
sh "cd ${WORKSPACE} && docker build -t ${some-name}\
 --build-arg USERNAME=cicd-user \
 --build-arg  PRIV_KEY_FILE=\$FILE --network=host \
 -f software/tools/jenkins/${some-name}/Dockerfile ."


text:
Q: Amazon S3 as a mount on Heroku I am new to Heroku , just wanted to understand if there is a way to have an Amazon S3 Bucket as a mount on heroku for my Liferay application to use.
I already have my liferay app deployed on heroku which is also connected to postgres.
My aim is to keep certain static configuration files on S3 and write into LOG files on S3.


text:
Q: Getting rid of if/else In Java, I've to set a POJO class with values. However to decide which setter function to be used, I've to depend on if condition. My current code looks as follow:
// Code written in a function which is called within a loop, while parsing xml file.
if (name.equals("dim1")) {
    line.setDim1Code(Integer.parseInt(value));
} else if (name.equals("dim2")) {
    line.setDim2Code(Integer.parseInt(value));
} else if (name.equals("debitcredit")) {
    line.setDebitOrCredit(value);
} else if (name.equals("basevalue")) {
    line.setBasevalue(Integer.parseInt(value));
} else if (name.equals("rate")) {
    line.setRate(Integer.parseInt(value));
} else if (name.equals("value")) {
    line.setValue(Integer.parseInt(value));
} else if (name.equals("description")) {
    line.setDescription(value);
} else if (name.equals("vatbasetotal")) {
    line.setVatBaseTotal(value);
} else if (name.equals("vattotal")) {
    line.setVatTotal(value);
}

This is just an example but I've 70+ such properties to be set. My code is working but I wonder if it is right way of doing things?
AFAIK, such code is against coding best practices. How can we optimise this code in Java? What is Java best practice to deal with such code?

A: It is actually something, which should be done automatically based on annotations by some library like Jackson 2.0+ or something similar (I am parsing only JSON so far)
Then the object looks like this :
@XmlAccessorType(XmlAccessType.FIELD)
    public class Employee
    {
        @XmlAttribute
        @XmlID
        protected String id;

        @XmlAttribute
        protected String name;

        @XmlIDREF
        protected Employee manager;

        @XmlElement(name="report")
        @XmlIDREF
        protected List<Employee> reports;

        public Employee() {
            reports = new ArrayList<Employee>();
        }
    }

A: You can try Java Architecture for XML Binding (JAXB), here you have a tutorial.
i.e:
    File file = new File("C:\\file.xml");
    JAXBContext jaxbContext = JAXBContext.newInstance(Pojo.class);

    Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
    Pojo pojo= (Pojo) jaxbUnmarshaller.unmarshal(file);

A: What you are probably looking to do is write a dynamic Getter/Setter. A quick Google search will give you a large number of options and approaches, but here is a couple I found quickly.
How to define dynamic setter and getter using reflection?
Invoking setter method using java reflection
I personally like the look of BeanUtils. Simple and easy to understand.

A: Rather than having a separate field and setter for each property, create a dictionary to hold all of your properties. Borrowing code from How do you create a dictionary?:
private Map<String, String> properties;

// Constructor
public MyClass() {
    properties = new HashMap<String, String>();
}

// Setter
public string setProperty(String name, String value) {
    properties.put(name, value);
}

// Getter
public string getProperty(String name) {
    return properties.get(name); // May return null. You may want to handle that.
}

Now all 70+ of your properties have only one getter and setter. No giant if-else or switch block.
With a dictionary, you lose some of the contracts that properties provide. For example, I could add a property to the dictionary that shouldn't exist. You can enforce these restrictions yourself (for example, by creating a list of allowed property names and refusing to set any property that is not in the list).


text:
Q: Python parse int from django url parameter I'd like to parse a date from incoming URL parameters in my django application. I came up with:
def month_transactions(request, month, year):
    current_month = calculate_current_month(month, year)
    next_month = calculate_next_month(current_month)
    debit_transactions = Transaction.objects.filter(is_credit=False,
                                                    due_date__range=(current_month, next_month))
    credit_transactions = Transaction.objects.filter(is_credit=True,
                                                     due_date__range=(current_month, next_month))
    return render(request, 'finances/index.html', {
        'debits': debit_transactions,
        'credits': credit_transactions,
    })
def calculate_current_month(month, year):
    current_month = re.match('\d{2}', month)
    current_year = re.match('\d{4}', year)
    return_month = datetime.date(
        int(current_year.group()), int(current_month.group()), 1)
    return return_month

Where my URL.conf looks like:
url(r'^transactions/(?P<month>\d{2})/(?P<year>\d{4}/$)', views.month_transactions, name='index',),

Since 'month' and 'year' come in to month_transactions as unicode strings (year comes with a trailing /) I kept getting Type exceptions when creating a new date from the raw variables.
Is there a better approach; something built into Python or Django that I missed?
Thanks,

A: You're making things much more complicated than they need to be. month and year are passed as strings, so you can just call int(month) and int(year) - no need for all that strangeness with the regexes.
Year only comes in with a trailing slash because your close paren is in the wrong place in the urlconf regex - it should be directly after the }, as you have for month.


text:
Q: Server returns 201 but promise routes to error I have a service called AuthService that makes a post request to login
the server response with a 201 but the second function in then() is executed and not the first
 AuthService.login(credentials)
    .then(function(data){
        console.log("Login success====")
        console.log(data);
        //if its successful
        $rootScope.$broadcast(AUTH_EVENTS.loginSuccess);
        $scope.setCurrentUser(user);

        $state.go('dashboard.account');
    }, function(error){  // THIS IS EXECUTED ONCE SERVER RESPONDS
        console.log("Login error====")
        //$rootScope.$broadcast(AUTH_EVENTS.loginFailed);
        console.log('Error: ' + error);
     });

So I get "Login error===" instead of success. I'm not sure why I'm following this guide
https://medium.com/opinionated-angularjs/techniques-for-authentication-in-angularjs-applications-7bbf0346acec
I thought that 201 are successful
Error contains
Error: TypeError: Cannot read property 'id' of undefined

//Session is a service that stores user data
.factory('AuthService', function ($http, Session) {
   var authService = {};

   authService.login = function (credentials) {
     return $http
     .post('/login', credentials)
     .then(function (res) {
        Session.create(res.data.id, res.data.user.id,
                   res.data.user.role);
        return res.data.user;
   });
};


text:
Q: My header file seems to be correct but it is throwing a lot of errors I am writing an interface program and I am using classes to write the interface as well as some of the other options within the program. This is what I have written so far:
#ifndef INTERFACE_H
#define INTERFACE_H

#include <iostream>
#include <vector>
#include <string>

class Interface
{
private:
    typedef vector<string> programType;
    programType programCode;

public:
    void startInterface()
    {
        char q, input;
        do
        {
            cout << "PySUB Interpreter 1.0 on Windows (September 2020)" << endl;
            cout << "Enter program lines or read(<filename>.py) at command line interface" << endl;
            cout << "Type 'help' for more information or 'quit' to exit" << endl;
        } while (input != q);
    }

    void quit();
    void help();
    void show();
    void clear();
};

#endif

The errors that I am getting are:
Build started...
1>------ Build started: Project: pysub1, Configuration: Debug x64 ------
1>interface.cpp
1>C:\Users\Johnathon\source\repos\pysub1\pysub1\interface.h(11,16): error C2143: syntax error: missing ';' before '<'
1>C:\Users\Johnathon\source\repos\pysub1\pysub1\interface.h(11,16): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1>C:\Users\Johnathon\source\repos\pysub1\pysub1\interface.h(11,36): error C2238: unexpected token(s) preceding ';'
1>C:\Users\Johnathon\source\repos\pysub1\pysub1\interface.h(12,14): error C3646: 'programCode': unknown override specifier
1>C:\Users\Johnathon\source\repos\pysub1\pysub1\interface.h(12,25): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1>C:\Users\Johnathon\source\repos\pysub1\pysub1\interface.h(21,72): error C2065: 'endl': undeclared identifier
1>C:\Users\Johnathon\source\repos\pysub1\pysub1\interface.h(22,91): error C2065: 'endl': undeclared identifier
1>C:\Users\Johnathon\source\repos\pysub1\pysub1\interface.h(23,73): error C2065: 'endl': undeclared identifier
1>Done building project "pysub1.vcxproj" -- FAILED.
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

How do I resolve this?

A: The problem here is that you don't specify the namespace of cout, endl, etc. You should either change them them to std::cout and so on, or write using namespace std at the top of your file (which is generally considered bad practice, but will do just fine in your example).


text:
Q: Problems with passing a hashmap from activity to fragment Im having problems I've followed a few examples but none of them seems to work.
I'm trying to send the HashMap to a fragment so that i can retrieve the values and place them onto text-views.
I'm calling the method(SendInfoToFragment) to pass the hashmap to the fragment inside the method(splitStringBuilder) where we split the JSONObject. I try to retrieve it the bundle i send on the OnAttachmethod inside the fragment. However i keep getting "java.io.Serializable android.os.Bundle.getSerializable(java.lang.String)' on a null object reference"
This is my main Activity.
public class WeatherActivity extends MenuActivity {

    public JSONObject splitStringBuilder(String builder) throws JSONException {
        String Info = (builder);
        JSONObject obj = new JSONObject(Info);
        JSONObject obj2 = new JSONObject(Info);
        JSONArray weatherObj = obj.getJSONArray("consolidated_weather");
        System.out.println(obj.get("title"));

        for(int x = 0; x < 6; x ++ )
        {
            WeatherForeCast weatherObject = new WeatherForeCast();
            obj = weatherObj.getJSONObject(x);

            int temperature = obj.getInt("the_temp");
            int wind_speed = obj.getInt("wind_speed");
            int air_pressure = obj.getInt("air_pressure");
            int humidity = obj.getInt("humidity");
            String weather_state = obj.getString("weather_state_name");
            String date = obj.getString("applicable_date");

            weatherObject.setTemperature(temperature);
            weatherObject.setWindSpeed(wind_speed);
            weatherObject.setAirPressure(air_pressure);
            weatherObject.setHumidity(humidity);
            weatherObject.setWeatherState(weather_state);
            weatherObject.setDate(date);
            String counter = String.valueOf(x);
            HashMapWeatherInformation.put(counter,weatherObject);

        }
        SendInfoToFragment(HashMapWeatherInformation);
        return obj2;
    }

    private class WeatherAsyncTask extends AsyncTask<String, Void , Void> {
        @Override
        protected Void doInBackground(String... strings) {
            try {
                weatherInfo = callApi();
                jsWeatherInfo = splitStringBuilder(weatherInfo);

            } catch (IOException | JSONException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);

        }
    }
    public void SendInfoToFragment(HashMap hashMap) {
        FragmentTransaction fm = getSupportFragmentManager().beginTransaction();
        DisplayWeatherFrag weatherFrag = new DisplayWeatherFrag();
        Bundle bundle = new Bundle();
        bundle.putSerializable("hashmap", hashMap);
        weatherFrag.setArguments(bundle);
                fm.add(R.id.fragment ,weatherFrag);
                        fm.commit();

    }
    public void runtheDamnThing(String string) {
        WeatherAsyncTask weatherAsyncTask = new WeatherAsyncTask();
        weatherAsyncTask.execute(string);
    }

    }

This is my fragment
/**
 * A simple {@link Fragment} subclass.
 */
public class DisplayWeatherFrag extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_display_weather, container, false);

        return view;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        HashMap<String, WeatherForeCast>HashMapWeatherInfo = null;
        Bundle b;
        b = getArguments();
        HashMapWeatherInfo = (HashMap<String, WeatherForeCast>) b.getSerializable("hashmap");

    }

}

This is the error code that i'm getting
2019-03-19 17:32:31.762 17365-17365/com.fan4.outdoorplus E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.fan4.outdoorplus, PID: 17365
    java.lang.NullPointerException: Attempt to invoke virtual method 'java.io.Serializable android.os.Bundle.getSerializable(java.lang.String)' on a null object reference
        at com.fan4.outdoorplus.WeatherFragments.DisplayWeatherFrag.onActivityCreated(DisplayWeatherFrag.java:68)
        at android.support.v4.app.Fragment.performActivityCreated(Fragment.java:2460)
        at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1483)
        at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1784)
        at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1852)
        at android.support.v4.app.FragmentManagerImpl.dispatchStateChange(FragmentManager.java:3269)
        at android.support.v4.app.FragmentManagerImpl.dispatchActivityCreated(FragmentManager.java:3229)
        at android.support.v4.app.FragmentController.dispatchActivityCreated(FragmentController.java:201)
        at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:620)
        at android.support.v7.app.AppCompatActivity.onStart(AppCompatActivity.java:178)
        at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1391)
        at android.app.Activity.performStart(Activity.java:7157)
        at android.app.ActivityThread.handleStartActivity(ActivityThread.java:2937)
        at android.app.servertransaction.TransactionExecutor.performLifecycleSequence(TransactionExecutor.java:180)
        at android.app.servertransaction.TransactionExecutor.cycleToPath(TransactionExecutor.java:165)
        at android.app.servertransaction.TransactionExecutor.executeLifecycleState(TransactionExecutor.java:142)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:70)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:193)
        at android.app.ActivityThread.main(ActivityThread.java:6669)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
2019-03-19 17:32:31.849 1932-2013/system_process E/InputDispatcher: channel '9ab1457 PopupWindow:1c45845 (server)' ~ Channel is unrecoverably broken and will be disposed!
2019-03-19 17:32:31.850 1932-2013/system_process E/InputDispatcher: channel '8221b13 com.fan4.outdoorplus/com.fan4.outdoorplus.MainActivity (server)' ~ Channel is unrecoverably broken and will be disposed!
2019-03-19 17:32:32.061 2592-2866/com.google.android.googlequicksearchbox:search E/eglCodecCommon: glUtilsParamSize: unknow param 0x000082da
2019-03-19 17:32:32.061 2592-2866/com.google.android.googlequicksearchbox:search E/eglCodecCommon: glUtilsParamSize: unknow param 0x000082da

A: A better way to do it would be to have the Hashmap(or any other object) inside the activity with a getter. Then you can get it directly from there.
In Fragment just do:
hashmap = ((WeatherActivity) getActivity()).getMyHashMap()

And make sure you have the getMyHashMap() method in your WeatherActivity.


text:
Q: Programming device in vivado using tcl I am trying out programming my digilent FPGA through the vivado command line.  After opening the hardware server I can program my device as follows...
program_hw_devices [get_hw_devices xc7a100t_0]

Then if I run puts [get_hw_devices xc7a100t_0] it outputs xc7a100t_0 which leads me to think that I should be able to just do something like program_hw_devices xc7a100t_0.  This however fails and I get the following output.

ERROR: [Common 17-161] Invalid option
  value 'xc7a100t_0' specified for 'hw_device'.

I don't really understand what is wrong with this.  I thought the two commands would be equivalent since I just passed it what was returned by get_hw_devices.  Also I thought the type of everything in tcl was just a string.  Does the output of [get_hw_devices xc7a100t_0] have some special type?

A: Looking at usage patterns, we see that the recommended usage is:
program_hw_devices [lindex [get_hw_devices] 0]

Given the text of the output of get_hw_devices is a "simple" word (no spaces or Tcl metacharacters), I suspect that the device tokens are actually special values that have non-trivial types hanging off the back end of their representation. We don't recommend that approach as it can lead to very weird error messages (such as the one you got), but given that it is so, you need to use exactly the pattern as described above so that you strip exactly one level of list-ness away.

For future reference, the script at that link (which was supposedly working) was:

# Connect to the Digilent Cable on localhost:3121

connect_hw_server -url localhost:3121
current_hw_target [get_hw_targets */xilinx_tcf/Digilent/12345]
open_hw_target

# Program and Refresh the XC7K325T Device

current_hw_device [lindex [get_hw_devices] 0]
refresh_hw_device -update_hw_probes false [lindex [get_hw_devices] 0]
set_property PROGRAM.FILE {C:/design.bit} [lindex [get_hw_devices] 0]
set_property PROBES.FILE {C:/design.ltx} [lindex [get_hw_devices] 0]

program_hw_devices [lindex [get_hw_devices] 0]
refresh_hw_device [lindex [get_hw_devices] 0]

I would have written it more like this myself:
# Connect to the Digilent Cable on localhost:3121
connect_hw_server -url localhost:3121
current_hw_target [get_hw_targets */xilinx_tcf/Digilent/12345]
open_hw_target

# Program and Refresh the XC7K325T Device
set Device [lindex [get_hw_devices] 0]
current_hw_device $Device
refresh_hw_device -update_hw_probes false $Device
set_property PROGRAM.FILE "C:/design.bit" $Device
set_property PROBES.FILE "C:/design.ltx" $Device

program_hw_devices $Device
refresh_hw_device $Device

so that I only do the list extraction once, but that's purely style; if one works, the other should as well.


text:
Q: How can I take two columns in R and flatten them like the below? Before
+---------+------------------------------------+
|  Word   |                Tags                |
+---------+------------------------------------+
| morning | #sunrise #droplets #waterdroplets  |
| morning | #sky #ocean #droplets              |
+---------+------------------------------------+

After
+---------+---------------+
|  Word   |     Tags      |
+---------+---------------+
| morning | sunrise       |
| morning | droplets      |
| morning | waterdroplets |
| morning | sky           |
| morning | ocean         |
| morning | droplets      |
+---------+---------------+

Notice how I want to keep droplets appearing twice. This table is very big, over 5m rows, if this method can be efficient that would be very helpful. Thanks!

A: We can use separate_rows from tidyr.
library(dplyr)
library(tidyr)

dat <- tribble(
  ~Word,   ~Tags,
  "morning", "#sunrise #droplets #waterdroplets",
  "morning", "#sky #ocean #droplets"
)

dat2 <- dat %>%
  separate_rows(Tags, sep = " #") %>%
  mutate(Tags = gsub("#", "", Tags))
dat2
# # A tibble: 6 x 2
#   Word    Tags
#   <chr>   <chr>
# 1 morning sunrise
# 2 morning droplets
# 3 morning waterdroplets
# 4 morning sky
# 5 morning ocean
# 6 morning droplets