text:
Q: Webapp does not find controller I've been trying to figure out something which has been vexing me for a the whole day. I'm trying to run a very simple SpringMVC but the webapp doesn't seem to pick up any of the controllers i've set up. Any help would be great
Web.xml
<web-app version="2.4"
  xmlns="http://java.sun.com/xml/ns/j2ee"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
  http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

  <servlet>
    <servlet-name>mvc-dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>mvc-dispatcher</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>

  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>

  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/mvc-dispatcher-servlet.xml, /WEB-INF/application-context.xml</param-value>
  </context-param>

</web-app>

mvc-dispatcher-servlet.xml
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="
    http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-4.0.xsd">

    <context:component-scan base-package="com.thehit.*" />

    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix">
            <value>/WEB-INF/pages/</value>
        </property>
        <property name="suffix">
            <value>.jsp</value>
        </property>
    </bean>
</beans>

application-context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-4.0.xsd
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx-4.0.xsd"
    default-autowire="byType">

    <context:annotation-config/>
    <context:component-scan base-package="com.thehit.*" />

    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3307/thehit"/>
        <property name="username" value="root"/>
        <property name="password" value="Password01"/>
    </bean>

</beans>

HelloWorldController.java
package com.thehit.controllers;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
@RequestMapping("/welcome")
public class HelloWorldController {

    @RequestMapping(value="/hello", method = RequestMethod.GET)
    public String printWelcome(ModelMap model) {
        model.addAttribute("message", "Spring 3 MVC Hello World. This is HelloControllerClass.");
        return "hello";
    }
}

The jsp file is located in WEB-INF/pages
When I navigate to the following addresses "http://localhost:8080/TheHitWebProject/welcome" or "http://localhost:8080/TheHitWebProject/hello" I get the following error:
HTTP Status 404 -

type Status report

message

description The requested resource is not available.

Apache Tomcat/7.0.53

I know i am missing something basic here but i've been at it for hours and can't figure it out. Any help will be really appreciated
Thanks

A: You're missing mvc:annotation-driven:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

    <mvc:annotation-driven/>

</beans>

Also remember that @RequestMapping from @Controller is added before @RequestMapping from method so url will be:
http://localhost:8080/TheHitWebProject/welcome/hello


text:
Q: fwrite doesn't fail when disk is full? here is a test program I wrote
int main( int argc, const char* argv[] )
{
  const char name[1024] = "/dev/shm/test_file";
  off_t len = atol(argv[argc - 1]);
  char buf[1024];
  FILE * f = fopen(name, "w");
  for (int i = 0; i < len; i++) {
    int ret = fwrite(buf, 1024, 1, f);
    if (ret != 1) {
      printf("disk full\n");
    }
  }
  if ( fclose(f) != 0)
    printf("failed to close\n");
  return 0;
}

I tried to fill the /dev/shm to almost full
tmpfs            36G   36G   92K 100% /dev/shm

and ran
$ ./a.out 93
failed to close

my glibc
$ /lib/libc.so.6
GNU C Library stable release version 2.12, by Roland McGrath et al.

the kernel version is 2.6.32-642.13.1.el6.x86_64
I understand that this behavior is caused by fwrite try to cache the data in memory. (I tried setvbuf(NULL...) and fwrite immediately return failure). But this seems a little different from the definition

The fwrite() function shall return the number of elements successfully
  written, which may be less than nitems if a write error is
  encountered. If size or nitems is 0, fwrite() shall return 0 and the
  state of the stream remains unchanged. Otherwise, if a write error
  occurs, the error indicator for the stream shall be set, [CX] [Option
  Start]  and errno shall be set to indicate the error. [Option End]

The data was not successfully written to disk however its return value is 1. no errno set.
In this test case, the fclose catch the failure. But it could be caught by even a ftell function which is quite confusing.
I am wondering if this happens to all versions of glibc and would this be consider a bug.

A:
The data was not successfully written to disk

The standard doesn't talk about the disk. It talks about data being successfully written to the stream (which it has been).

I am wondering if this happens to all versions of glibc

Most likely.

and would this be consider a bug.

It's a bug in your interpretation of the requirements on fwrite.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Segmentation Fault : 11 in Xcode 10 so i just update the latest Xcode version. at the 9.4.1, it seems fine. But after i upgrade it to 10, i got an error that says "Segmentation Fault : 11". Here's the log:

*

*While emitting SIL for 'insertOrUpdateChannel(activity:channel:user:completion:)' at /Users/wmotionmac/Project/Wmotion/WWF Content Manager/WWF Content Manager/Model/Api/Api.swift:273:5

*While silgen emitFunction SIL function "@$S19WWF_Content_Manager17DetailActivityApiV21insertOrUpdateChannel8activity7channel4user10completionyAA0E0C_AA0J0CAA4UserCySbctFZ".
  for 'insertOrUpdateChannel(activity:channel:user:completion:)' at /Users/wmotionmac/Project/Wmotion/WWF Content Manager/WWF Content Manager/Model/Api/Api.swift:273:5
  error: Segmentation fault: 11

Here's the code for insertOrUpdateChannel
//TODO:- Create or Update Channel
static func insertOrUpdateChannel(activity: Activity, channel: Channel, user: User, completion: @escaping(Bool)->()) {
    let url = URL(string: Base.api + "/channelactivitypage?calendarId=\(activity.id)")
    var request = URLRequest(url: url!)
    if channel.id.elementsEqual("") {
        request.httpMethod = "POST"
    } else {
        request.httpMethod = "PUT"
    }
    request.setValue("application/json", forHTTPHeaderField: "Content-Type")

    var tema = [String : Int]()
    var themes = [[String : Int]]()
    var assets = [[String : Any]]()
    let email = ["ID": String(describing: "2c53ea1f-6ebe-e811-a977-000d3aa00fc2"), "Name": String(describing: "TV Broadcast"), "List_EmailListModels": nil]

    for theme in channel.themes {
        if !theme.elementsEqual("") {
            tema = ["Value" : Int(theme)!]
            themes.append(tema)
        } else {
            tema = ["Value" : -1]
            themes.append(tema)
        }
    }

    if channel.digitalAsset.count > 0 {
        for asset in channel.digitalAsset {
            let media = ["ID" : asset.id, SerializationKeys.name : asset.name, SerializationKeys.description : asset.description, SerializationKeys.copyRightCredit : asset.copyRightCredit, SerializationKeys.location : asset.location]
            assets.append(media)
        }
    } else {
        let media = [SerializationKeys.name : "", SerializationKeys.description : "", SerializationKeys.copyRightCredit : "", SerializationKeys.location : ""]
        assets.append(media)
    }

    let parameters = [["ID" : channel.id, SerializationKeys.name : activity.activityName, SerializationKeys.channelType : channel.channelType, SerializationKeys.publish_date : "2018-09-21T01:00:00Z", "Headline" : channel.headline, SerializationKeys.content : channel.content, SerializationKeys.emailSubject : channel.emailSubject, SerializationKeys.emailURL : channel.emailURL, SerializationKeys.mention : channel.mention, "PostLink" : channel.postLink, SerializationKeys.channelMobileId : channel.mobileId, "Hastag" : nil, SerializationKeys.tema : themes, SerializationKeys.emailGroup : [email], "ApprovalStatus" : channel.channelStatus, SerializationKeys.rubric : channel.rubric, "ApprovalNote" : channel.note, "DigitalAsset" : assets, "ApprovalEmployeeId" : user.id, "ApprovalEmployeeLevel" : user.level]] as [[String : Any]]
    request.httpBody = try! JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted)

    Alamofire.request(request).responseJSON { (response) in
        switch response.result {
        case .success:
            let json = JSON(response.result.value!)
            if !json["Message"].stringValue.elementsEqual("") {
                completion(false)
            } else {
                 completion(true)
            }
        case .failure(_):
            completion(false)
        }
    }
}

Here's the code for DetailActivity
DetailActivityApi.insertOrUpdateChannel(activity: self.activity!, channel: channel, user: self.user!) { (isSuccess) in
                            if isSuccess {
                                DetailActivityApi.updateDetailActivity(activity: self.activity!, user: self.user!) { (error) in
                                    if error != nil {
                                        print(error!)
                                        Message.connectionFailed()
                                        Loading.hide()
                                    } else {

                                    }
                                }
                                self.db.deleteChannelData(id: id, completion: { (isSucceed) in
                                    if isSucceed {
                                        if let digitalAsset = data {
                                            self.db.deleteAsset(id: digitalAsset[self.db.ID]) { (_) in

                                            }
                                        }

                                        self.navigationController?.popViewController(animated: true)
                                        self.dismiss(animated: true, completion: nil)
                                        Message.custom(title: "Submit", body: "Send activity to server", type: .success)
                                    } else {

                                    }
                                })
                            }
                        }
                        Loading.hide()

A: Ok so finally, i find the solution by the help of my friend. there's a bug on my code and after changing, here's the result
static func insertOrUpdateChannel(activity: Activity, channel: Channel, user: User, completion: @escaping(Bool)->()) {
    let url = URL(string: Base.api + "/channelactivitypage?calendarId=\(activity.id)")
    var parameters: [[String : Any?]] = []
    var request = URLRequest(url: url!)
    if channel.id.elementsEqual("") {
        request.httpMethod = "POST"
    } else {
        request.httpMethod = "PUT"
    }
    request.setValue("application/json", forHTTPHeaderField: "Content-Type")

    var tema = [String : Int]()
    var themes = [[String : Int]]()
    var assets = [[String : Any]]()
    let email = ["ID": String(describing: "2c53ea1f-6ebe-e811-a977-000d3aa00fc2"), "Name": String(describing: "TV Broadcast"), "List_EmailListModels": nil]

    for theme in channel.themes {
        if !theme.elementsEqual("") {
            tema = ["Value" : Int(theme)!]
            themes.append(tema)
        } else {
            tema = ["Value" : -1]
            themes.append(tema)
        }
    }

    if channel.digitalAsset.count > 0 {
        for asset in channel.digitalAsset {
            let media = ["ID" : asset.id, SerializationKeys.name : asset.name, SerializationKeys.description : asset.description, SerializationKeys.copyRightCredit : asset.copyRightCredit, SerializationKeys.location : asset.location]
            assets.append(media)
        }
    } else {
        let media = [SerializationKeys.name : "", SerializationKeys.description : "", SerializationKeys.copyRightCredit : "", SerializationKeys.location : ""]
        assets.append(media)
    }
    let params = ["ID" : channel.id, SerializationKeys.name : activity.activityName, SerializationKeys.channelType : channel.channelType, SerializationKeys.publish_date : "2018-09-21T01:00:00Z", "Headline" : channel.headline, SerializationKeys.content : channel.content, SerializationKeys.emailSubject : channel.emailSubject, SerializationKeys.emailURL : channel.emailURL, SerializationKeys.mention : channel.mention, "PostLink" : channel.postLink, SerializationKeys.channelMobileId : channel.mobileId, "Hastag" : nil, SerializationKeys.tema : themes, SerializationKeys.emailGroup : [email], "ApprovalStatus" : channel.channelStatus, SerializationKeys.rubric : channel.rubric, "ApprovalNote" : channel.note, "DigitalAsset" : assets, "ApprovalEmployeeId" : user.id, "ApprovalEmployeeLevel" : user.level] as [String : Any?]

    parameters.append(params)
    request.httpBody = try! JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted)

    Alamofire.request(request).responseJSON { (response) in
        switch response.result {
        case .success:
            let json = JSON(response.result.value!)
            if !json["Message"].stringValue.elementsEqual("") {
                completion(false)
            } else {
                 completion(true)
            }
        case .failure(_):
            completion(false)
        }
    }
}


text:
Q: How to set precision of numpy float array when converting from string array? I am using the following link to convert a array of string to array of float
Convert String to float array
The data that I am getting is in a weird format
535.    535.    535.    534.68  534.68  534.68

Although numpy is able to convert the string array to float but some other is failing when data is in the format 535.
Is there a way to convert all 535. to 535.00 in one go.
I am using the following code for conversions
import numpy as np
strarray = ["535.","535.","534.68"]
floatarray = np.array(filter(None,strarray),dtype='|S10').astype(np.float)
print floatarray

A: Convert the the strings to float128.
Try this:
import numpy as np
strarray = ["535.","535.","534.68"]
floatarray = np.array(filter(None,strarray),dtype='|S10').astype(np.float128)
print floatarray

Output:
[ 535.0  535.0  534.68]

Or use the recommended longdouble:
import numpy as np
strarray = ["535.","535.","534.68"]
floatarray = np.array(filter(None,strarray),dtype='|S10').astype(np.longdouble)
print floatarray

Output:
[ 535.0  535.0  534.68]


text:
Q: Custom Dimension Report and Sorting by Value I've setup a custom dimension in Google Analytics called 'Publication' to track which publication an article has been sourced from. The data appears to be tracking, but I'm unable to sort via the value.
Here's an example of the tracking code on one page:
 ga('create', 'UA-XXX', 'auto');
 var dimensionValue = 'News Site';
 ga('set', 'dimension1', dimensionValue);
 ga('send', 'pageview');

And here's one on another, each is sending a different dimensionValue string.
 ga('create', 'UA-XXX', 'auto');
 var dimensionValue = 'Game Site';
 ga('set', 'dimension1', dimensionValue);
 ga('send', 'pageview');

If I look in Google Analytics though and create a custom report, the articles appear in the list, but I cannot sort via the value of the dimensionValue variable. I can't seem to find it in any of the drop-down menus. Ideally I want to see how many page views News Site gets vs Game Site. Does it take time for the values to appear? For some reason it shows a bunch of page info instead.

Any help or insight would be greatly appreciated.


text:
Q: Show time depending on timezone on wordpress with js and php I have a plugin that offer the user time_slots to be booked. The problem is that it doesnt matter where in the world you are you will see the hours in utc-4. I want client to see the time reflected by their timezone
im a huge js/php newb, but i guess i would need a small function that translate $slot to the user time before printing it with
while (strtotime($date_from) < strtotime($end_date))
         {
             $cdiv++;

             $day_num_of_week = date('N', strtotime($date_from));

             ?>

<?php echo date('l, j F, Y', strtotime($date_from))?> - <?php echo  $day_num_of_week?>

              ?>

              <div class="bup-time-slots-divisor" id="bup-time-sl-div-<?php echo $cdiv?>">

             <?php  //get available slots for this date

             $time_slots = $this->get_time_slot_public_for_staff($day_num_of_week,  $staff_id, $b_category, $time_format);

 $cdiv_range = 0 ;

 foreach($time_slots as $slot)
             {
                  $cdiv_range++;
                 ?>

                <li id="bup-time-slot-hour-range-<?php echo $cdiv?>-<?php echo $cdiv_range?>">

                  <?php echo $slot['from'].' – '.$slot['to']?>
                1 time slot available

                <button class="new-appt bup-button bup-btn-book-app" bup-data-date="<?php echo date('Y-m-d', strtotime($date_from))?>" bup-data-timeslot="<?php echo $b_category.'-'.$staff_id?>">

                <?php _e('Book Appointment','bookingup')?></button>

<?php  } //end for each time slots ?>

<?php
 //increase date
 $date_from = date ("Y-m-d", strtotime("+1 day", strtotime($date_from)));

  }

?>

i want the user to see the timeslot depending on their timezone,
ej in australia its a day later, or in x city its 2h earlier
any help would be amazing!!

A: You can do that like this :
var today = new Date();
var date = today.getFullYear()+'-'+(today.getMonth()+1)+'-'+today.getDate();
var time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
var dateTime = date+' '+time;

and put the variable dateTime into the tag HTML that you want like this :
document.getElementById('idElement').innerHTML = dateTime;

and your tag HTML is like that :

Here you will find your input (time)


text:
Q: 'py.test' is not recognized as the name of a cmdlet, function, script file, or operable program Hi I am trying to run my tests using "py.test" command in the Pycharm terminal but every time is am getting this error message:
py.test : The term 'py.test' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify
that the path is correct and try again.
At line:1 char:1

*

*py.test

*
  + CategoryInfo          : ObjectNotFound: (py.test:String) [], CommandNotFoundException
  + FullyQualifiedErrorId : CommandNotFoundException

A: First anwser:
check if python -m pytest or just pytest works for you, if it is - maybe you have installed pytest in a different env/global env, what makes pytest libary unavailable/unreachable in your environment. if the command does not work for you - make sure you have installed pytest libary pip insall pytest
Second anwser:
Try to change the default shell inside Pycharm to use CMD (i think you are using powershell ?) then restart pycharm, make sure you are using cmd as your default shell inside pycharm terminal.


text:
Q: What's your suggested mail server configuration for a FreeBSD server? What would be your suggestion if installing a FreeBSD 7 (7.2, actually) email server?
I am interested in:

*

*SMTP agent

*Imap/Pop backend

*Authentication (OS users, OpenLDAP)

*Anti-Spam server side tools

*WebMail frontend

Thanks a lot in advance.

A: There are so many different possibilities here.  What you're really talking about is an email "stack" (much like web-server/web-app "stacks").

*

*SMTP Agent a.k.a. MTA (Mail Transfer Agent)

There are several, including Sendmail, Exim, Qmail, Postfix, and Courier.  Sendmail has had most of its "issues" resolved, Exim is small and stable, Qmail is fast, and Postfix is "flexible", sturdy, and fairly easy to configure.  I guess it's a function of which one makes the most sense to you.

*

*IMAP/POP Backend

There are also several, including UW-IMAP (don't), and Dovecot (does POP3/IMAP, supports SSL).  Courier also has POP/IMAP services.

*

*Authentication
Where to start?  OpenLDAP is possible, but you can also get away with Kerberos, or even SASL.

*Anti-Spam Tools
Amavisd-new is a Perl script that hooks into SpamAssassin.  Be sure to get the newest version(s) of both (the newer SpamAssassin supports detecting image spam via OCR).

*Web Mail
SquirrelMail has made the rounds, but Courier I believe also provides this.
...and...

*

*Anti-Viral Tools
Clam is free and has a very good detection rate.  If you use it with Amavis, it will act as a "backup" scanner.  I have seen Clam detect things that commercial scanners won't (probably because the signatures are updated frequently).

My personal preference:
Postfix MTA, Amavis spam/virus filter,  ClamAV scanner, Dovecot supplies IMAP over SSL, and SquirrelMail for a web interface.
I do have to admit that I don't run FreeBSD, sorry.  However, I did take the time to check the BSD ports to see if all these package are available, and they are.  So choose what you like. :)

A: If I may throw my own $0.2 I'd recommend DSpam as an anti-spam tool. If you're not afraid of using greylisting (like postgrey) it's worth giving a try. I personally just love OpenBSD's spamd and I can see there's a FreeBSD fork in mail/spamd.


text:
Q: How do I map a palette from www.materialpalette.com to an Angular 2 theme? Download link on otherwise excellent www.materialpalette.com doesn't support Angular 2. Downloading e.g. sass gives:
$primary-color-dark
$primary-color
$primary-color-light
$primary-color-text
$accent-color
$primary-text-color
$secondary-text-color
$divider-color

Looking for advise on exactly how to map these to Angular 2:
$app-primary: mat-palette(…);
$app-accent: mat-palette(…);
$app-warn: mat-palette(…);

A: Use http://mcg.mbitson.com/#!/ to generate a palette based on the colors provided by materialpalette so finally you get the file containing your colors e.g /assets/your-palette.scss:
$mat-your-palette: (
    50 : #e8eaf6,
    100 : #c5cbe9,
    200 : #9fa8da,
    300 : #7985cb,
    400 : #5c6bc0,
    500 : #3f51b5,
    600 : #394aae,
    700 : #3140a5,
    800 : #29379d,
    900 : #1b278d,
    A100 : #c6cbff,
    A200 : #939dff,
    A400 : #606eff,
    A700 : #4757ff,
    contrast: (
        50 : #000000,
        100 : #000000,
        200 : #000000,
        300 : #000000,
        400 : #ffffff,
        500 : #ffffff,
        600 : #ffffff,
        700 : #ffffff,
        800 : #ffffff,
        900 : #ffffff,
        A100 : #000000,
        A200 : #000000,
        A400 : #ffffff,
        A700 : #ffffff,
    )
);

Then based on the file above you have to create a theme e.g /assets/theme.scss:
@import '~@angular/material/_theming.scss';
@import './your-palette.scss';
@include mat-core();
$primary: mat-palette($mat-your-palette, 500);
$accent:  mat-palette($mat-your-palette, A100);
$warn:    mat-palette($mat-your-palette, A200);
$theme: mat-light-theme($primary, $accent, $warn);
@include angular-material-theme($theme);

Then import your theme @import '/assets/theme'; in styles.scss and you are done.
Also check the docs for more info on how to theme your app
UPDATE:
To figure out the colors for your custom theme could be a bit tricky. Currently to build material2 theme you only need to provide 3 colors $primary, $accent and $warn As per Theming Guide:

*

*A primary palette: colors most widely used across all screens and
components.

*An accent palette: colors used for the floating action
button and interactive elements.

*A warn palette: colors used to
convey error state.


text:
Q: [Android]NumberPicker selected item change color Is it possible to change color of the selected item in numberpicker so each time a new center child TextView appear change its color to whatever I like I did not find any style or API expose about this ?

A: I tried to follow many answers and all of them were setting the whole number's color.
I figured out how to change color only for selected number.  set OnTouchListener in your NumberPicker.
numberPicker.setOnTouchListener(new OnTouchListener() {
                    @Override
                    public boolean onTouch(final View v, MotionEvent event) {
                        currentTouchAction = event.getAction();
                        if (currentTouchAction == MotionEvent.ACTION_UP) {
                            new Handler().postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    if (currentTouchAction == MotionEvent.ACTION_UP) {
                                        setSelectedTextColor((NumberPicker)v, selectedColorRes);
                                    }
                                }
                            }, 300);
                        }
                        return false;
                    }
                });

and below code is for changing the selected number color. You might have to use 'performClick()'
to dynamically apply the color.
And if you do that, the picker would immediately stop. So that's why I put postDelayed(300) above. User might drag number picker several times to select the profit number. If you put above postDelay() and wait for several milliseconds, it can be scrolled smoothly.
public void setSelectedTextColor(NumberPicker np, int colorRes) {
    final int count = np.getChildCount();
    for(int i = 0; i < count; i++){
        View child = np.getChildAt(i);
        if(child instanceof EditText){
            try{
                Field selectorWheelPaintField = np.getClass().getDeclaredField("mSelectorWheelPaint");
                selectorWheelPaintField.setAccessible(true);
                ((EditText) child).setTextColor(mContext.getResources().getColor(colorRes));
                np.performClick();
            }
            catch(NoSuchFieldException e){
            }
            catch(IllegalArgumentException e){
            }
        }
    }
}

A: I think you can use a NumberPicker.OnValueChangeListener using the method setOnValueChangedListener(...)of the widget.
In the callback you get the picker and can change the style the way you want.

A: You can try using below code. Just pass only your NumberPicker and color in this parameters. Hope this solves your issue
import java.lang.reflect.Field;

public static void changeNumberPickerTextColor(NumberPicker numberPicker, int color)
{

    try{
        Field selectorWheelPaintField = numberPicker.getClass()
            .getDeclaredField("mSelectorWheelPaint");
        selectorWheelPaintField.setAccessible(true);
        ((Paint)selectorWheelPaintField.get(numberPicker)).setColor(color);
    }
    catch(NoSuchFieldException e){
        Log.w("setNumberPickerTextColor", e);
    }
    catch(IllegalAccessException e){
        Log.w("setNumberPickerTextColor", e);
    }
    catch(IllegalArgumentException e){
        Log.w("setNumberPickerTextColor", e);
    }

    final int count = numberPicker.getChildCount();
    for(int i = 0; i < count; i++){
        View child = numberPicker.getChildAt(i);
        if(child instanceof EditText)
            ((EditText)child).setTextColor(color);
    }
    numberPicker.invalidate();
}

A: By design is not possible to change only the center color. If you check the NumberPicker's source code, specifically in the onDraw method, then you will see that the widget makes no difference between the center item and the rest of the items when rendering. All the texts are rendered using the same color.
Source code link. Check the onDraw method starting at the comment "//draw the selector wheel": https://android.googlesource.com/platform/frameworks/base/+/0e2d281/core/java/android/widget/NumberPicker.java
In addition, when editing, it places an EditText control on top of the NumberPicker center area. Changing such EditText control will not solve the problem, even if you perform some tricks such as doing a programmatic click to set the EditText into focus, because as soon as you scroll again or set the focus to a different View in your layout, the EditText will be hidden, and you will loose such color effect.
The only solution is to create a new NumberPicker control. For example you could use the actual NumberPicker source code, and adapt it to your needs. You will need to make the adjustments in the onDraw method.


text:
Q: the contract reflected all the tiny details? "Matt's job was to make sure the contract reflected all the tiny details."
What does "reflect" in this sentence mean?  contain?
What other synonyms that have the same meaning ?

A: It is a metaphoric usage from the core meaning that you would use with a mirror: "The mirror reflects the image in front of it". The implication is that one entity is a parallel of another: I have two eyes - and my mirror image has two eyes that look remarkably similar. There is a big nose on my face - and there is one in the mirror as well.
In your sentence, the intended meaning is that all the tiny details that exist in reality are also represented in the contract.
A possible near-synonymous replacement, for all the same reasons, would be "Matt's job was to make sure all the tiny details were [faithfully] reproduced in the contract."


text:
Q: Array display without key I am trying to display an array without key item. Just want to display array values without key.
Here is my sample code I tried
$myList = array(
        0 =>array(
                "product_id"=> 8085
            ),
         1 =>array(
                "product_id"=> 8087
            ),
          2 =>array(
                "product_id"=> 8086
            ),
           3 =>array(
                "product_id"=> 8042
            ),
        );

  $newList = array();
foreach($myList as $listItem) {
    $newList[] = $listItem['product_id'];
}
$a=array();
$a= array_values($newList);
print_r($a);

I want my array like this
$productIds = array(8085,8087,8086,8042);

Here is my sample code link

A: print_r function will output the keys. even if you use array_values the array still have indexes as keys.
Just output the the array manually using echo and implode (implode will join array values into a single string using the first parameter character):
echo implode(',', $newList);

A: You're looking for array_column (which is available as of PHP 5.5):
$productIds = array_column($myList, 'product_id');

This gives you:
var_export($productIds);

array (
  0 => 8085,
  1 => 8087,
  2 => 8086,
  3 => 8042,
)

Which is exactly what you want:
var_dump($productIds === array(8085,8087,8086,8042)); // bool(true)

A: Arrays will always have keys. If you want an array, you can get all the values, turn them into one comma separated string, and place that into an array:
$productIds = [implode(',', array_column($myList, 'product_id'))];
var_dump($productIds);

// RESULT:
// array (size=1)
//   0 => string '8085,8087,8086,8042' (length=19)


text:
Q: Unable to execute WorkManager from Xposed Injected code I have a couple of classes that are loaded and executed inside third party apps using Xposed hooks.
One of the methods takes a lot of resources and crashes the App where it runs. I figured out I would run it using the WorkManager so the load will be automatically handled by the system.
The classes injected are not part of a normal Android App (Manifest doesn't have the application tag, and even if it did It wouldn't run as a normal App). Rather the classes are compiled and loaded inside the third party app then executed directly inside.
Since WorkManager relies on the Application to create an instance, I figured out that maybe I could just create the instance manually.
So somewhere in the code I called:
WorkManager.initialize(context, new Configuration.Builder().build());

Then in my method I used something like :
WorkManager mWorkManager = WorkManager.getInstance();
mWorkManager.enqueue(OneTimeWorkRequest.from(MyWorker.class));

However during the initialization I get the following error:
Resources$NotFoundException: Resource ID #0x7f020002 type #0x3 is not valid

I'm not sure what resources the WorkManager is looking for, as I mentioned before I just have couple classes, no res folder
I'm open to other suggestions to replace the WorkManager

A: WorkManager does look for resources to determine if it needs to enable / disable Scheduler's based on API level. Here is the actual file in question (https://android.googlesource.com/platform/frameworks/support/+/androidx-master-dev/work/workmanager/src/main/res/values/values.xml).
I don't know why these resources are not getting merged correctly.


text:
Q: Derivation of Birthday Paradox formula with unknown n I have been trying to derive the formula for the upper bound probability of the birthday paradox for any number of occurrences $n$.
Assuming we want to find the number of occurrences $k$ such that there is >50% probability they share a property, I am given it to be:
$exp(-k(k-1)/2n)$
Now given the fact that P[share a property] = $\frac{1}{2}$ = $exp(-k(k-1)/2n)$, I would like to find the formula for $k$, so I can just plug in any $n$, to see the number of occurrences required with different values of $n$. This is only an approximation, so I need the formula to be in the form k ≈ ...
I have tried solving for $k$, but got stuck after getting rid of the exponential, which I'm not sure I even did correctly, as it gave me: $2n\ ln(2) < k^2-k$
I managed to find an answer to this online which said that $k ≈ 1.18\sqrt{n}$, but I have no idea how to get to that answer.

A: Since we are finding an approximation for $k$, we should have equality in $2n\ln2<k^2-k$, not just an inequality. The approximation comes after the quadratic formula.
$$k^2-k-2n\ln2=0$$
$$k=\frac{1+\sqrt{1+8n\ln2}}2\approx\sqrt{2n\ln2}=\sqrt{2\ln2}\sqrt n$$
and $\sqrt{2\ln2}=1.17741\dots$


text:
Q: could not find function MXSymbolGetAtomicSymbolName I am getting "could not find function MXSymbolGetAtomicSymbolName" error in windows 10 on Julia command prompt when I enter:
julia> using MXNet
What should I do to fix this error

A: Tested with Julia 0.6.2 and the issue is no longer present.


text:
Q: Django - Foreign Keys in Fixtures I have a fixture of "User" objects (just the default Django auth ones), and am trying to create a fixture of "Profile" objects.  Each profile has a one-to-one relation to a user object, and defines some more custom stuff for that user.
As far as I can tell, the normal way of dealing with foreign keys in a fixture is to just hardcode the primary key of the foreign object into the fixture.  Is there a way to avoid doing that?
Basically, I'm trying to have something like '"user":username' in the fixture rather than '"user":pk'.
Is there any way to do this?

A: What you are trying to do is serializing with natural keys, explained here.
You basically need to define how to get the object from other fields in these special manager and model methods.
Just realized that this question has been asked 9 years ago, what? Why did it appear in the feed at the top?


text:
Q: Continuously changing Big Data and C# I have a dataset with {A LOT OF} rows containing continuously correcting data of 50000 assets of 150 customers for well over a decade and a half.
I want to achieve the following:

*

*Storing data and changing data should be done at a reasonable speed

*Getting data must be super fast

*The customer should be able to retrieve data of day/month/quarter/annual time range for up to 10000 assets at a time

All I need is the best way to implement a data storage solution for this dataset.
I have tried SQL Server - it's slow; Azure Table storage getting data for 10K assets results in 10K queries .. so no good.
Google big data have the same problem.
Any help appreciated


text:
Q: dijkstra algorithm incorrect conditional I am working on a dijkstra algorithm using priority queues. I have been doing a lot of research, and I thought my code was following the algorithm, but I cannot get into the conditional when comparing for the shortest paths
    void dijkstra( int startingID ) {

        priority_queue<Vertex*, vector<Vertex*>, PathWeightComparer> dijkstra_queue{};
        vector<Vertex*> vert;
        vert = _vertices;
        int n = vert.size();
        vector< double > dis(n);

        for (int i = 0; i < n; i++)
        {
            dis[i] = std::numeric_limits< double >::infinity();
        }
        vert[startingID]->setPathWeight(startingID);
        dis[startingID] = 0;
        Vertex* temp = vert[startingID];
        dijkstra_queue.push(temp);

        while (!dijkstra_queue.empty())
        {
            double dist = dijkstra_queue.top()->getPathWeight();
            double u = dijkstra_queue.top()->getId();
            dijkstra_queue.pop();

            for (auto i : vert)
            {
                double v = i->getId();
                double weight = i->getPathWeight();
                double distance_total = dist + weight;
                cout << "distance_total " << distance_total << " dis[v] " << dis[v] << endl;
                if (distance_total < dis[v]) //PROBLEM
                {
                    dis[v] = distance_total;
                    Vertex* temp2 = i;
                    temp2->setPathWeight(dis[v]);
                    dijkstra_queue.push(temp2);
                }
            }
        }
    }
};

Here is the graph class
class Graph
{
    vector<Vertex*> _vertices;      // All vertices in the graph (vertex id == index)
    int _last_startingID = -1;

And here is the vertex class
class Vertex
{
private:
    int _id;                    // ID (key) of given vertice
    bool _known = false;        // Dijkstra's algorithm "known" flag
    Vertex* _path = nullptr;    // Dijkstra's algorithm parent vertex pointer
        // Weight of path through graph - starts at a true infinity (inf)
    double _path_weight = std::numeric_limits<double>::infinity();

I tried to only include the code that was relavent to only the dijkstra function, but if anything is unclear I can add more.

A: Your implementation of the algorithm is incorrect.
After you pop() vertex u from the queue (because it's distance from the source is the lowest) you should ONLY inspect vertices that are directly reachable from u (i.e. an edge exists from u to that vertex).
Your current implementation seems to be looping through ALL vertices regardless of whether they are directly reachable from u or not, and perhaps as a result, you are doing something strange with the distance calculation that makes no sense. More specifically, distance_total in your implementation seems nonsensical.
The key idea behind Dijkstra's algorithm is:
dis[u] = must be shortest path from source to u since u was popped.
dis[v] = current_known_distance_to_v

Then, for all v where edge exists from u to v:
IF dis[u] + weight(u, v) < dis[v]:
    // going via u is better than the current best known distance to v
    dis[v] = dis[u] + weight(u, v)


text:
Q: Missing type id when trying to resolve subtype Jackson ION desrialization even after registering subtypes I have an interface -
@JsonTypeInfo(use=JsonTypeInfo.Id.NAME, include=JsonTypeInfo.As.PROPERTY, property="type")
interface Base { ... }

I have two derived classes - ClassA and ClassB. I am attempting to serialize and deserialize with Jackson ION to base type as follows -
class TestSerDeSer {
    private static ObjectMapper MAPPER = new IonObjectMapper();

    static {
        MAPPER.registerSubtypes(new NamedType(A.class, "A"));
        MAPPER.registerSubtypes(new NamedType(B.class, "B"));
      }

    public byte[] serialize(Base baseType) {
        try {
            return MAPPER.writeValueAsBytes(baseType);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    }

    public Base deserialize(byte[] bytes) {
        Base base;
        try {
            base = MAPPER.readValue(bytes, Base.class);
            return base;
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    }

}

I am creating an Object of Class A and serializing and desrializing using above functions as
Base baseObj = new ClassA(...);
//serialization works fine
byte[] serializedBytes = serialize(baseObj);

//this line throws exception
Base deserializedBase = deserialize(serializedBytes);

The exception is -
Caused by: com.fasterxml.jackson.databind.exc.InvalidTypeIdException: Missing type id when trying to resolve subtype of [simple type, class mypackage.path.Base]: missing type id property 'type'

I am registering subtypes in ObjectMapper. I also have the annotation for type in base interface. What is it that I am missing here?

A: Your example work with standard JSON with ObjectMapper however it fails when serialization format is switched to Ion with IonObjectMapper. Tested your example with com.fasterxml.jackson.dataformat:jackson-dataformat-ion:2.9.7, fails with the same exception.
There is an open issue [avro] Support @JsonSubTypes in schema generation and serialization #11 which implies that not all binary dataformats support subtypes. Open pull request [Ion] Better support for Ion type annotations. #109 implies that @JsonTypeInfo doesn't work when using Ion yet.


text: Q: What is the problem in proving $\pi$ is transcendental over $\mathbb{Q}$ in purely algebraic method Why can't we prove for the field extension $\mathbb{R}$ over $\mathbb{Q}$ ,$\pi$ is transcendental over $\mathbb{Q}$ in a purely algebraic method? Or is there any prove that proves $\pi$ is transcendental over $\mathbb{Q}$ in a purely algebraic method?


text:
Q: Scrollable 100% height main panel with fixed header and optional breadcrumbs I have a difficult CSS problem to solve. I have an app that always has a header at the top of the page - say 75px in height. On most pages, there will be breadcrumbs too - 45px in height. Of course, the home page has no need to show the breadcrumbs, so the header will occupy less total height than other pages.
What I'd like to do is have the main view under the breadcrumbs occupy the rest of the space on the screen - for all device heights. Moreover, I want this pane to be scrollable, while the header/breadcrumbs are always on top.
This seems to be very tricky to do.
Here is an example describing what I mean:

A: Here's that calc() solution I mentioned in the comments. If you don't care about ie8 and lower it's perfect for your use case. If you care for older ie versions you can look into IE's expressions. Here's the demo:

html, body {
    margin: 0;
    padding: 0;
}

header {
    height: 60px;
    background: orange;
}

.breadcrumbs {
    height: 40px;
    background: yellowgreen;
}

.content {
    background: #BADA55;
    height: calc(100vh - 40px - 60px);
    overflow: auto;
}

    Header

    Breadcrumbs

Content

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Illo ut et sequi harum repudiandae beatae iure quod similique ipsa natus. Ex quia ducimus in molestias maxime consequuntur quos explicabo at quam voluptate aliquid earum nesciunt voluptatum aperiam iure eum maiores obcaecati iste expedita beatae. Velit vitae animi voluptate harum similique dicta suscipit quo nemo molestias maiores quae omnis obcaecati expedita officia rem tempora qui nostrum impedit magnam molestiae repellendus assumenda fugit recusandae quos iusto inventore labore dignissimos. Maxime aspernatur nam assumenda est iure quas ad incidunt porro ea saepe! Ut laborum eligendi nostrum quidem ullam natus nam tempora sequi magnam.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Illo ut et sequi harum repudiandae beatae iure quod similique ipsa natus. Ex quia ducimus in molestias maxime consequuntur quos explicabo at quam voluptate aliquid earum nesciunt voluptatum aperiam iure eum maiores obcaecati iste expedita beatae. Velit vitae animi voluptate harum similique dicta suscipit quo nemo molestias maiores quae omnis obcaecati expedita officia rem tempora qui nostrum impedit magnam molestiae repellendus assumenda fugit recusandae quos iusto inventore labore dignissimos. Maxime aspernatur nam assumenda est iure quas ad incidunt porro ea saepe! Ut laborum eligendi nostrum quidem ullam natus nam tempora sequi magnam.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Illo ut et sequi harum repudiandae beatae iure quod similique ipsa natus. Ex quia ducimus in molestias maxime consequuntur quos explicabo at quam voluptate aliquid earum nesciunt voluptatum aperiam iure eum maiores obcaecati iste expedita beatae. Velit vitae animi voluptate harum similique dicta suscipit quo nemo molestias maiores quae omnis obcaecati expedita officia rem tempora qui nostrum impedit magnam molestiae repellendus assumenda fugit recusandae quos iusto inventore labore dignissimos. Maxime aspernatur nam assumenda est iure quas ad incidunt porro ea saepe! Ut laborum eligendi nostrum quidem ullam natus nam tempora sequi magnam.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Illo ut et sequi harum repudiandae beatae iure quod similique ipsa natus. Ex quia ducimus in molestias maxime consequuntur quos explicabo at quam voluptate aliquid earum nesciunt voluptatum aperiam iure eum maiores obcaecati iste expedita beatae. Velit vitae animi voluptate harum similique dicta suscipit quo nemo molestias maiores quae omnis obcaecati expedita officia rem tempora qui nostrum impedit magnam molestiae repellendus assumenda fugit recusandae quos iusto inventore labore dignissimos. Maxime aspernatur nam assumenda est iure quas ad incidunt porro ea saepe! Ut laborum eligendi nostrum quidem ullam natus nam tempora sequi magnam.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Illo ut et sequi harum repudiandae beatae iure quod similique ipsa natus. Ex quia ducimus in molestias maxime consequuntur quos explicabo at quam voluptate aliquid earum nesciunt voluptatum aperiam iure eum maiores obcaecati iste expedita beatae. Velit vitae animi voluptate harum similique dicta suscipit quo nemo molestias maiores quae omnis obcaecati expedita officia rem tempora qui nostrum impedit magnam molestiae repellendus assumenda fugit recusandae quos iusto inventore labore dignissimos. Maxime aspernatur nam assumenda est iure quas ad incidunt porro ea saepe! Ut laborum eligendi nostrum quidem ullam natus nam tempora sequi magnam.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Illo ut et sequi harum repudiandae beatae iure quod similique ipsa natus. Ex quia ducimus in molestias maxime consequuntur quos explicabo at quam voluptate aliquid earum nesciunt voluptatum aperiam iure eum maiores obcaecati iste expedita beatae. Velit vitae animi voluptate harum similique dicta suscipit quo nemo molestias maiores quae omnis obcaecati expedita officia rem tempora qui nostrum impedit magnam molestiae repellendus assumenda fugit recusandae quos iusto inventore labore dignissimos. Maxime aspernatur nam assumenda est iure quas ad incidunt porro ea saepe! Ut laborum eligendi nostrum quidem ullam natus nam tempora sequi magnam.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Illo ut et sequi harum repudiandae beatae iure quod similique ipsa natus. Ex quia ducimus in molestias maxime consequuntur quos explicabo at quam voluptate aliquid earum nesciunt voluptatum aperiam iure eum maiores obcaecati iste expedita beatae. Velit vitae animi voluptate harum similique dicta suscipit quo nemo molestias maiores quae omnis obcaecati expedita officia rem tempora qui nostrum impedit magnam molestiae repellendus assumenda fugit recusandae quos iusto inventore labore dignissimos. Maxime aspernatur nam assumenda est iure quas ad incidunt porro ea saepe! Ut laborum eligendi nostrum quidem ullam natus nam tempora sequi magnam.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Illo ut et sequi harum repudiandae beatae iure quod similique ipsa natus. Ex quia ducimus in molestias maxime consequuntur quos explicabo at quam voluptate aliquid earum nesciunt voluptatum aperiam iure eum maiores obcaecati iste expedita beatae. Velit vitae animi voluptate harum similique dicta suscipit quo nemo molestias maiores quae omnis obcaecati expedita officia rem tempora qui nostrum impedit magnam molestiae repellendus assumenda fugit recusandae quos iusto inventore labore dignissimos. Maxime aspernatur nam assumenda est iure quas ad incidunt porro ea saepe! Ut laborum eligendi nostrum quidem ullam natus nam tempora sequi magnam.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Illo ut et sequi harum repudiandae beatae iure quod similique ipsa natus. Ex quia ducimus in molestias maxime consequuntur quos explicabo at quam voluptate aliquid earum nesciunt voluptatum aperiam iure eum maiores obcaecati iste expedita beatae. Velit vitae animi voluptate harum similique dicta suscipit quo nemo molestias maiores quae omnis obcaecati expedita officia rem tempora qui nostrum impedit magnam molestiae repellendus assumenda fugit recusandae quos iusto inventore labore dignissimos. Maxime aspernatur nam assumenda est iure quas ad incidunt porro ea saepe! Ut laborum eligendi nostrum quidem ullam natus nam tempora sequi magnam.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Illo ut et sequi harum repudiandae beatae iure quod similique ipsa natus. Ex quia ducimus in molestias maxime consequuntur quos explicabo at quam voluptate aliquid earum nesciunt voluptatum aperiam iure eum maiores obcaecati iste expedita beatae. Velit vitae animi voluptate harum similique dicta suscipit quo nemo molestias maiores quae omnis obcaecati expedita officia rem tempora qui nostrum impedit magnam molestiae repellendus assumenda fugit recusandae quos iusto inventore labore dignissimos. Maxime aspernatur nam assumenda est iure quas ad incidunt porro ea saepe! Ut laborum eligendi nostrum quidem ullam natus nam tempora sequi magnam.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Illo ut et sequi harum repudiandae beatae iure quod similique ipsa natus. Ex quia ducimus in molestias maxime consequuntur quos explicabo at quam voluptate aliquid earum nesciunt voluptatum aperiam iure eum maiores obcaecati iste expedita beatae. Velit vitae animi voluptate harum similique dicta suscipit quo nemo molestias maiores quae omnis obcaecati expedita officia rem tempora qui nostrum impedit magnam molestiae repellendus assumenda fugit recusandae quos iusto inventore labore dignissimos. Maxime aspernatur nam assumenda est iure quas ad incidunt porro ea saepe! Ut laborum eligendi nostrum quidem ullam natus nam tempora sequi magnam.

and when you don't have the breadcrumbs you just add a class to the body (or a container) and use different styles: http://jsfiddle.net/cy83uL28/1/
.container.without-breadcrumbs .content{
    height: calc(100vh - 60px);
}

Here's a link to a jsfiddle demo in case you want to play a little bit with it: http://jsfiddle.net/cy83uL28/

A: What you need to do is use position:fixed on the header and breadcrumbs, so that they float above the other content and always stay on the page. It would allow the functionality you want, without a lot of headache or special methods. Simply add position:fixed top:0 left:0 to your divs css.


text:
Q: Laravel 5.1 Event broadcasting seems to be irresponsive I've been struggling with this for a day - I can't get to work laravel events broadcasting system. I use pusher. I followed the laracasts tutorial step by step several times,
In the pusher web interface I can see than connection is open but it is not able to listen to any of my broadcasting events. Why could this happen?
Step by step what I did:
Fire an event, make it implement ShouldBroadcast interface,
Implement broadcastOn method
Followed the JS code example from pusher docs to listen to this event.
var pusher = new Pusher('3890ebc2a16a21e534d8', {
        encrypted: true
    });

    var channel = pusher.subscribe('pointsGiven.' + this.player.id);

    console.log(channel);
    channel.bind("MK\Events\PlayerWasGivenScores", function(data) {
        console.log(data);
    });

The event name is App\\\Events\\PlayerWasGivenScores.
No mistakes here - checked several times. So what could it be? The docs says that queues should be configured. is sync driver for queues considered as configured queue? I believe yes. Could this be a problem that I'm on homestead?
Any hint would be much appreciated!

A: You are using an incorrect channel name; according to the pusher documentation:

Channel names should only include lower and uppercase letters, numbers and the following punctuation _ - = @ , . ;

Your channel name therefor MK\Events\PlayerWasGivenScores is invalid. The same might be the case for the event names, I'd test this by using simpler channel and event names.

A: Is this local or on a server? If on a server make sure ports are available for Redis and Node.


text:
Q: Обращение к элементам форм, выводимых в цикле Форма комментариев к статьям выводится в цикле php.
Как в js обратиться к каждому элементу форм?
Код формы:
<form class = "comment_form" action = "send.php" action ="POST">
    <input type ="hidden" name ="article_id" value ="<? echo $articles['id']?>" class = "content_id">
    <input type ="text" name ="username" class = "userlogin">
    <textarea name ="comment" class = "comm_cont">
    <input type ="button" name ="submit" class = "submit">
</form>

Форма JS
    $(document).ready(function(){

      $('.submit').on('click', function(e) {
        e.preventDefault();

        var content_id = $('.content_id').val();
        var username = $('.userlogin').val();
        var message = $('.comm_cont').val();
        var url = $('.comment-form').attr('action');

       //e.preventDefault();
        $.ajax({
          url: url,
          type: "POST",
          data: {
            "post_id": content_id,
            "login": username,
            "comment": message,
            "submit": $(".submit").val()
          },
          cache: false,
          dataType: 'json',
          success: function(response){

              $('.comment_text').val('');
              $('.comment_show').append(response.username + response.login + response.comment + response.pubdate);

            }
          });
        });
      });


text:
Q: How to display two not associated models on one page via admin interface? I have two models, not connected by ForeignKey. I would to display them on one page in admin interface, in the way like inlines in Django.
I can't associate PostFile with Post, because uploaded medias should be available to every Post which was and will be created in future. I have no idea what I can do if inlines are unavailable.
class Post(models.Model):

    STATUS_CHOICES = (
        ('draft', 'Draft'),
        ('published', 'Published')
    )

    title = models.CharField(max_length=255)
    slug = models.SlugField(max_length=255, unique_for_date='publish_date', blank=True)
    author = models.ForeignKey(User, related_name='blog_posts', on_delete=models.CASCADE, blank=True)
    content = MarkdownxField()
    publish_date = models.DateTimeField(default=timezone.now)
    creation_date = models.DateTimeField(auto_now_add=True)
    last_update_date = models.DateField(auto_now=True)
    status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft')
    tags = models.ManyToManyField(Tag)
    objects = models.Manager()

    class Meta:
        ordering = [
            '-publish_date'
        ]

    def __str__(self):
        return self.title

    def save(self, *args, **kwargs):
        if not self.slug:
            self.slug = slugify(self.title)
        super(Post, self).save(*args, **kwargs)

    def get_absolute_url(self):
        return reverse('blog:post_detail',
                       args=[
                           self.publish_date.strftime('%Y'),
                           self.publish_date.strftime('%m'),
                           self.publish_date.strftime('%d'),
                           self.slug
                       ])

    #https://github.com/neutronX/django-markdownx/issues/83

    def formatted_markdown(self):
        return markdownify(self.content)

class PostFile(models.Model):

    file_name = models.CharField(max_length=200, blank=True)
    file_object = models.FileField(upload_to='post_files/')
    file_upload_date = models.DateTimeField(auto_now_add=True)

    def save(self, *args, **kwargs):
        if not self.file_name:
            self.file_name = self.file_object.name
        super(PostFile, self).save(*args, **kwargs)

    def file_url(self):
        return self.file_object.url

    def __str__(self):
        return self.file_name

I would to receive in output a Post model admin page, where on the bottom I have listed all PostFile objects. This will give me easy and fast acces to PostFile-object url on media folder. I don't want each time to open new tab, and to go to PostFile model admin page to check url of object.


text:
Q: How can I find all the StackExchange websites that I'm part of? - Queries on Data Explorer How can I find all the StackExchange websites that I'm part of as well as I'm not part of using the Data Explorer..?
In addition, if it's possible, I would like to use this query to do additional data manipulation such as to see avg answer score and fav tag on each website.
Related questions:
Allow cross-site queries in data explorer
Interesting queries on Data Explorer

A: The following multi-database query finds for a given accountid (that is the id of your networkprofile) the sites you participate on. In the second result set you find total sites joined and the total number of sites. I assume you can get from there how many sites you don't have an account on.
declare @sql nvarchar(max)

create table #result (site sysname
                    , displayname nvarchar(150)
                    , id integer
                    , upvotes integer
                    , downvotes integer
                    , q integer
                    , a integer)

select @sql = N'insert into #result' + STRING_AGG(concat(N'
select ''', convert(nvarchar(max),name) ,N''' as site
     , u.displayname
     , u.id
     , u.upvotes
     , u.downvotes
     , sum(case p.posttypeid when 1 then 1 else 0 end) Q
     , sum(case p.posttypeid when 2 then 1 else 0 end) A
from ', convert(nvarchar(max),quotename(name)), N'.dbo.users u
left outer join ', convert(nvarchar(max),quotename(name)), N'.dbo.posts p on
  p.owneruserid = u.id
where accountid = ##accountid##
group by u.displayname, u.id, u.upvotes, u.downvotes
'),N'
union all')
from sys.databases
where database_id > 5
and (name not like '%.Meta' or name = 'StackExchange.Meta')

exec (@sql)

select *
from #result

select (select count(*)
from #result) [sites with account]
, (select count(*)
from sys.databases
where database_id > 5
and (name not like '%.Meta' or name = 'StackExchange.Meta')) [total sites]

When run today for a random account number this is what your result might look like:

Keep in mind SEDE is updated once a week on Sunday.


text:
Q: WCF Service throwing exception as 401 on WCF Test Client and The provided URI scheme 'http' is invalid; expected 'https' during ASP.Net call While working on WCF service I am facing some issue and receiving two different errors
1. While accessing the service through WCFTectClient I am receiving Unauthorized error.
2. While accessing service through ASP.Net application using service reference I am receiving "The provided URI scheme 'http' is invalid; expected 'https'."
On my development environment everything is working perfectly fine however post hosting it is throwing errors.
I tried matching and changing configuration settings in web.config but no use.
Below are my web.configs
1. Service web.config
                <configuration>
              <system.web>
                <compilation debug="true" targetFramework="4.5" />
                <httpRuntime targetFramework="4.5" />
                <authentication mode="Windows" />
               <system.serviceModel>
                <client>
                  <endpoint address="" binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_SomeOtherClient"
                  contract="SomeOtherClient_Contract}" name="BasicHttpBinding_SomeOtherClient" />
                  <endpoint address="" binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_SomeOtherClient1" contract="
               {SomeOtherClient_Contract1}" name="BasicHttpBinding_SomeOtherClient1" />
                </client>
                <bindings>
                  <basicHttpBinding>
                    <binding name="BasicHttpBinding_MyName">
                      <security mode="TransportCredentialOnly">
                        <transport clientCredentialType="Windows" />
                      </security>
                    </binding>
                    </basicHttpBinding>
                </bindings>
                <services>
                  <service behaviorConfiguration="MEX" name="{SERVICE_CONFIGURATION_NAME}">
                    <endpoint address="" binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_MyName"
                    name="BasicHttpBinding_MyName" contract="MyService.Services.InterfaceName">
                      <identity>
                        <dns value="localhost" />
                      </identity>
                    </endpoint>
                    <endpoint address="mex" binding="mexHttpBinding"
                contract="IMetadataExchange" />
                  </service>
                </services>
                <behaviors>
                  <serviceBehaviors>
                    <behavior name="MEX">
                      <serviceMetadata httpGetEnabled="true"  />
                      <serviceDebug includeExceptionDetailInFaults="true" />
                      <serviceCredentials>
                        <clientCertificate>
                          <authentication mapClientCertificateToWindowsAccount="true"
                  />
                        </clientCertificate>
                      </serviceCredentials>
                    </behavior>
                  </serviceBehaviors>
                   </behaviors>
                   <serviceHostingEnvironment aspNetCompatibilityEnabled="true"
                  multipleSiteBindingsEnabled="true" />
                  </system.serviceModel>
                   </configuration>

*Application Web.Config
            <configuration>
              <system.web>
                <browserCaps userAgentCacheKeyLength="256" />
                <compilation debug="true" targetFramework="4.7.2" />
                <authentication mode="Windows" />
                <sessionState mode="InProc" timeout="20" />
                <pages controlRenderingCompatibilityVersion="3.5" clientIDMode="AutoID">
                </pages>
                <customErrors mode="Off" defaultRedirect="~/Error.aspx">
                </customErrors>
                <webServices>
                  <protocols>
                    <add name="HttpGet" />
                    <add name="HttpPost" />
                  </protocols>
                </webServices>
              </system.web>
              <appSettings>
                 <add key="{WCF_SERVICE_URL}" value="http://ServerBaseURl/MyWCF_SERVICE_URL" />

              </appSettings>
              <system.serviceModel>
                <serviceHostingEnvironment aspNetCompatibilityEnabled="false" multipleSiteBindingsEnabled="true" minFreeMemoryPercentageToActivateService="1" />
                <behaviors>
                  <serviceBehaviors>
                    <behavior name="">
                      <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
                      <serviceDebug includeExceptionDetailInFaults="true" />
                    </behavior>
                  </serviceBehaviors>
                </behaviors>
                <bindings>
                  <basicHttpBinding>
                    <binding openTimeout="01:50:00" receiveTimeout="01:50:00" sendTimeout="01:50:00" maxBufferPoolSize="20000000" maxBufferSize="2147483647" maxReceivedMessageSize="2147483647">
                      <readerQuotas maxDepth="128" maxStringContentLength="8388608" maxArrayLength="16384" maxBytesPerRead="4096" maxNameTableCharCount="16384" />
                      <security mode="TransportCredentialOnly">
                        <transport clientCredentialType="Windows" />
                      </security>
                    </binding>

                      <security mode="TransportCredentialOnly">
                        <transport clientCredentialType="Windows" />
                      </security>
                    </binding>
                    <binding name="BasicHttpBinding_Windows" maxReceivedMessageSize="2147483647">
                      <security mode="TransportCredentialOnly">
                        <transport clientCredentialType="Windows" />
                      </security>
                    </binding>
                    <binding name="BasicHttpBinding_MyName" receiveTimeout="00:20:00" sendTimeout="00:20:00" maxReceivedMessageSize="2147483647">
                      <security mode="TransportCredentialOnly">
                        <transport clientCredentialType="Windows" />
                      </security>
                    </binding>

                  </basicHttpBinding>
                </bindings>

            <client>
                    <endpoint address="MyServiceURL"
                  binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_MyName"
                   contract="yService.Services.InterfaceName"
                   name="BasicHttpBinding_MyName" />

                </client>
              </system.serviceModel>
              <devExpress>
                <settings rightToLeft="false" />
                <compression enableHtmlCompression="false" enableCallbackCompression="true" enableResourceCompression="true" enableResourceMerging="true" />
                <themes enableThemesAssembly="true" />
                <errors callbackErrorRedirectUrl="" />
              </devExpress>
            </configuration>

For WCF TestClient Below is the Exception
Error: Cannot obtain Metadata from {MyServiceURL} If this is a Windows (R) Communication Foundation service to which you have access, please check that you have enabled metadata publishing at the specified address. For help enabling metadata publishing, please refer to the MSDN documentation at http://go.microsoft.com/fwlink/?LinkId=65455.WS-Metadata Exchange Error URI: {MyServiceURL} Metadata contains a reference that cannot be resolved: '{MyServiceURL}'. The HTTP request is unauthorized with client authentication scheme 'Anonymous'. The authentication header received from the server was 'Negotiate,NTLM'. The remote server returned an error: (401) Unauthorized.HTTP GET Error URI: {MyServiceURL} There was an error downloading '{MyServiceURL}'. The request failed with HTTP status 401: Unauthorized.
For Application
The provided URI scheme 'http' is invalid; expected 'https'.
Parameter name: via
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.ServiceModel.FaultException`1[[System.ServiceModel.ExceptionDetail, System.ServiceModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]: The provided URI scheme 'http' is invalid; expected 'https'.
Parameter name: via
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[FaultException`1: The provided URI scheme 'http' is invalid; expected 'https'.
Parameter name: via]
   System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg) +14833358
   System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type) +386

A: In the configuration file, the service is created by Basichttpbinding with TransportCredentialOnly security mode. and required client credential is windows. The first point requires that we need to specify an Http base address as a service base address. The second point is that we should specify a windows credential(username/password) when calling the service. this could not be achieved in Wcttestclient, except that we change the clientCredentialType.
<transport clientCredentialType="None"></transport>

As for the errors thrown by your application client. I suggest you generate the client proxy class by re-adding service reference.
Feel free to let me know if the problem still exists.


text:
Q: Optimize Earth Engine script script profiler I created a workflow where I try to apply an algorithm over a selection of transects (line geometry) and images in a ImageCollection. I noticed that processing time goes up very quickly when the amount of transects is increasing and I'd like to explore the possibility to imrpove the script (and processing time). I started looking into the profiler and I am thinking where to start digging and how to approach this issue.
The workflow roughly follows this procedure:

*

*Create an imagecollection (SpectralUnmixing + Billateral filtering on images): for now 1 year of landsat observations (+/- 20 images)

*iterate over all transects (+/- 250 with a length of 30km): break up  the transects in point, reduceRegion for each point and extract pixel values at transect.

*Build Arrays with for each pixel the extract values of Spectal unmixing output

*Do some array calculations such as first/2nd order derivatives for peaks & valleys on the transect

*return the required output.

https://code.earthengine.google.com/8edf8f719c2f8ae01b1d8629bcdf9dde
So I was expecting that most of the computation time would be in the reduceRegion (step2) and billateral filtering (step 1) and not so much in the Array computations (step 4). So when I look at the profiler I see that most computation time is indeed plumbing, loading assets and applying image algorithms to it (related to billateral filtering function I assume). Yet, most of the memory goes to the algorithm array group, which I assume are the steps that fall under number 4.
Does the peak memory below in the image indeed indicate that my array computations can be optimized or is it mainly the image computations that could be improved? And where in the alogrithms is there a possibility to improve computation time spent on overhead/plumbing?
The screen shots are from tests applied to 1 image and 1 transect.

A:
Does the peak memory below in the image indeed indicate that my array computations can be optimized or is it mainly the image computations that could be improved?

Algorithm Array doesn't mean array algorithms in general, but constructing arrays. So it might be large just because it's measuring the inputs to your arrays whereas the other array algorithms are operating on that existing array, not allocating large amounts of memory on their own.

Or does the plumbing time suggest that the overhead is just to large somehow?

Yes, "plumbing" is intended to measure overhead: work that isn't specifically the algorithms you asked for but is necessary to set them up and connect them.
However, keep in mind that computation steps can be reorganized such that the profiler won't necessarily attribute them correctly (the most notable case of this is computing image pixels from a chain of image algorithms), so it may be useful to not just assume the profiler is "blaming" the right thing, but actually try removing/replacing parts of your script and seeing how the numbers change.


text:
Q: Bootstrap DatePicker, how to set the start date for to 15 mins. in the future? Is there any way to have the startDate be 15 minutes from current time, something like this:
var currentDate = new Date();
var fifteenminslater - new Date(currentDate.getTime() + (20*60*1000));

     $( ".datepicker" ).datetimepicker({
         pickTime: true,
         pick12HourFormat: true,
         startDate: fifteenminslater  });

I think startDate only knows date, and not time. Is there something similar to startDate that will allow me to mess with the time?


text:
Q: Installing python-praat-scripts in Ubuntu I want to install the python-praat-scripts package. It says:

Installation
You can install python-praat-scripts through pip via:
pip install python-praat-scripts
Or through downloading this repository and running:
python setup.py install
Once installed, the praatinterface package will be importable.

So I did that. Then it says:

For basic usage, instantiate a PraatLoader object as below:
``` from praatinterface import PraatLoader
pl = PraatLoader(praatpath = '/path/to/praat')
text = pl.run_script('formants.praat', '/path/to/wav/file', 5, 5500)
formants = pl.read_praat_out(text) ```

So I wrote the following:
from praatinterface import PraatLoader

praat_path = '/usr/bin/praat'
pl = PraatLoader(praatpath = praat_path)
for path in ae_paths:
    text = pl.run_script('formants.praat', path, 5, 5500)
    formants = pl.read_praat_out(text)
    print(formants)

here ae_paths is a list with audio paths. The praat path was found by writing in the terminal:

vladimir@vladimir:/usr/bin$ type praat
praat is /usr/bin/praat

However I get an error:

--------------------------------------------------------------------------- PermissionError                           Traceback (most recent call
  last)  in ()
        2
        3 praat_path = '/usr/bin/praat'
  ----> 4 pl = PraatLoader(praatpath = praat_path)
        5 for path in ae_paths:
        6     text = pl.run_script('formants.praat', path, 5, 5500)
/home/vladimir/anaconda3/lib/python3.5/site-packages/praatinterface/Praat.py
  in init(self, **kwargs)
       18             self.script_dir = os.path.join(os.path.dirname(file),'praatScripts')
       19             self.praat = 'praat'
  ---> 20         self.init_scripts()
       21         if self.debug:
       22             self.initlog()
/home/vladimir/anaconda3/lib/python3.5/site-packages/praatinterface/Praat.py
  in init_scripts(self)
       35     def init_scripts(self):
       36         if not os.path.isdir(self.script_dir):
  ---> 37             os.mkdir(self.script_dir)
       38         for s in self.scripts:
       39             sfilename = s
PermissionError: [Errno 13] Permission denied: '/usr/bin/praatScripts'

A: I have another way to run praat scripts.
you can try this way.
First you have to install praat to run python praat scripts
- you can install praat using this   "sudo apt-get install praat"

*

*after that open praat GUI using "./praat" command in CMD.

*there is option run to praat scripts. click on it and select your praat script and execute.


text:
Q: Changing where PHP logs syntax errors How would I go about changing where PHP logs it's syntax errors? I've got multiple people working on the same server, and I want to be able to send my own logs to a custom file so that I'm not looking at every one else's errors.
I can do this:
error_reporting(E_ALL);
ini_set('display_errors','On');
ini_set('error_log','path/to/mylogfile.log');

And that works for some errors, but for actual syntax errors, the logs are still being sent to the master /var/log/httpd/error_log. How do I make the syntax errors get sent to my custom log file?

A: Since the file cannot be correctly parsed, the ini_set function is not executed either and neither is the new error log set. You need to set php_value error_log /path/to/myfile.log in an .htaccess file or the global server config (I'm assuming that you're using Apache).

A: Given that syntax errors prevent PHP from running you will not be able to set log paths via PHP. It's a chicken before the egg situation.
Alternatives would be:

*

*Change the error log at the webserver level

*Enable output of error messages to the browser

I'd suggest the latter.


text:
Q: How to handle form data while switching between multiple frames I have created a swing application in Netbeans environment. This application consists of four frames. Now my requirement is, after filling A frame when user clicks "Next" button then A's data should be buffered somewhere and then go to second form and so on. Finally when user lands in the last form, at this point i want the total data of all forms should be stored in database.
I am not sure how to achieve this. Can anyone suggest some useful resource or idea?

A: Consider having one non-GUI model class, that can be passed into the view (GUI) classes, either via a constructor parameter, or a setter parameter, i.e., public void setModel(Model model). Then all views can have the same Model instance passed into them.
When the first window has its data "submitted", it submits it into the one shared model. If you're using a Model-View-Control structure, then this is usually done by the Control, but if your program is simple, a Model-View is probably all you need. The other windows can be notified by the Model of the changed data, and then change their displays accordingly.

But as an aside, also please ask yourself, how many professional applications do you use that jump from window to window? Not many because it is a very distracting and often unpleasant experience for the user. Most use a single main application window that swaps gui views within this window and with an occasional dialog window popping up when information is needed in a modal fashion. Please have a look at The Use of Multiple JFrames, Good/Bad Practice?


text:
Q: Material UI v0 ListItem Alignment Issue when using Custom Avatar Component Material UI version: v0.20.0
I am trying to assign leftAvatar value via CustomAvatar component but it is not aligning as you can see in attached screenshot. Please help.
CustomAvatar: This component is working on some condition bases like if image is available the its
MemberList/index.js
import React, {Component} from 'react';
import {withRouter} from 'react-router-dom';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import {List, ListItem} from 'material-ui/List';
import IconMenu from 'material-ui/IconMenu';
import MenuItem from 'material-ui/MenuItem';
import CustomAvatar from 'routes/CustomAvatar';

class MemberList extends Component {
    render(){<MuiThemeProvider>
        <List>
            <ListItem
                leftAvatar={<CustomAvatar avatarPic={false}/>}
                primaryText={"Mike Tailor"}
                secondaryText={"This is first text"}
                secondaryTextLines={1}
                rightIconButton={<IconMenu iconButtonElement={iconButtonElement}>
                  <MenuItem>Add friend</MenuItem>
                  <MenuItem>Chat</MenuItem>
                </IconMenu>}/>

            <ListItem
                leftAvatar={<CustomAvatar avatarPic={true}/>}
                primaryText={"Kory Becker"}
                secondaryText={"This is second text"}
                secondaryTextLines={1}
                rightIconButton={<IconMenu iconButtonElement={iconButtonElement}>
                  <MenuItem>Add friend</MenuItem>
                  <MenuItem>Chat</MenuItem>
                </IconMenu>}/>
        </List>
    </MuiThemeProvider>}
}

export default withRouter(MemberList);

CustomAvatar/index.js
import React, {Component} from 'react';
import {withRouter} from 'react-router-dom';
import Avatar from 'material-ui/Avatar';

class CustomAvatar extends Component {
    render(){
        if(this.props.avatarPic){
            return(<Avatar size={40} src={"http://www.example.com/myimage.png"} />)
        }else{
           return(<Avatar size={40}>A</Avatar>)
        }
    }
}

export default withRouter(CustomAvatar);

A: The cause of your problem
Your problem is caused because the material-ui v0 library expects the leftAvatar prop to be an Avatar component, and so relies on internal values of Avatar behind the scenes. Since your CustomAvatar is not directly an Avatar, material-ui does not find these internals and so the styling does not work.
Specifically, if you take a look at the source of ListItem, you'll notice a pushElement function that takes child components like leftAvatar and assigns styling by setting the style prop:
pushElement(children, element, baseStyles, additionalProps) {
  if (element) {
    const styles = Object.assign({}, baseStyles, element.props.style);
    children.push(
      React.cloneElement(element, {
        key: children.length,
        style: styles,
        ...additionalProps,
      })
    );
  }
}

Your CustomAvatar makes no use of this style prop, so you never receive the necessary CSS styling. That's the cause of your layout issues.
You have a couple of options to fix this depending on whether you are willing to upgrade to v1 or not.
Code that fixes it
class CustomAvatar extends Component {
  render() {
    const { showPicture, ...other } = this.props;

    if (showPicture) {
      return (<Avatar size={40} {...other} src={"http://www.example.com/myimage.png"} />);
    } else {
      return (<Avatar size={40} {...other}>A</Avatar>);
    }
  }
}

As discussed above, the pushElement function sets the style prop. Right now, you're not using it, so your Avatars get no styling. The {...other} spreads this prop down into your Avatars so that they get the right styling and your layout works.
But, you should upgrade to v1
v1 should have a stable release in the early quarters of 2018, and it fixes a lot of these kinds of problems. Instead of spending time working through these kinds of issues and working with v0, you should upgrade and learn the new (and, imho, improved) way.

A: I also have faced same problem you could fix this by wrap your custom compoent into PAPER component of material-ui. Please see code below:
import React, {Component} from 'react';
import {withRouter} from 'react-router-dom';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import {List, ListItem} from 'material-ui/List';
import IconMenu from 'material-ui/IconMenu';
import MenuItem from 'material-ui/MenuItem';
import CustomAvatar from 'routes/CustomAvatar';
import Paper from 'material-ui/Paper';

class MemberList extends Component {
    render(){<MuiThemeProvider>
    <List>
        <ListItem
            leftAvatar={<Paper zDepth={2} circle={true}><CustomAvatar avatarPic={false}/></Paper>}
            primaryText={"Mike Tailor"}
            secondaryText={"This is first text"}
            secondaryTextLines={1}
            rightIconButton={<IconMenu iconButtonElement={iconButtonElement}>
              <MenuItem>Add friend</MenuItem>
              <MenuItem>Chat</MenuItem>
            </IconMenu>}/>

        <ListItem
            leftAvatar={<Paper zDepth={2} circle={true}><CustomAvatar avatarPic={true}/></Paper>}
            primaryText={"Kory Becker"}
            secondaryText={"This is second text"}
            secondaryTextLines={1}
            rightIconButton={<IconMenu iconButtonElement={iconButtonElement}>
              <MenuItem>Add friend</MenuItem>
              <MenuItem>Chat</MenuItem>
            </IconMenu>}/>
    </List>
</MuiThemeProvider>}

}
export default withRouter(MemberList);


text:
Q: How to display nearest data point information of a line chart by moving the mouse over the chart area I'm going to draw a chart using c# in Windows Form Application. I need to draw a circle on line chart and show this data point value on a label which is nearest data point from the x-axis of the mouse pointer when mouse is moved over the chart area.
I write a code as follows......
private void Chart1_MouseMove(object sender, MouseEventArgs e)
    {
        HitTestResult result = Chart1.HitTest(e.X, e.Y);

        DataPoint nearestPoint = null;

        if (prevPosition!=null)
        {

            Chart1.Series[0].Points[prevPosition.PointIndex].MarkerStyle = MarkerStyle.None;

        }

        if (result.ChartElementType == ChartElementType.DataPoint)
        {

            string xValue = DateTime.FromOADate(Chart1.Series[0].Points[result.PointIndex].XValue).ToString("yyyy/MM/dd");
            string yValue = Convert.ToString(Chart1.Series[0].Points[result.PointIndex].YValues[0]);

            Chart1.Series[0].Points[result.PointIndex].MarkerStyle = MarkerStyle.Circle;
            Chart1.Series[0].Points[result.PointIndex].MarkerSize = 7;
            Chart1.Series[0].Points[result.PointIndex].MarkerColor = Color.Green;

            label1.Text = "Date:" + xValue;
            label2.Text = "Price:" + yValue;
            prevPosition = result;

        }

But this code shows the value and corresponding circle over line when mouse is moved near to the depicted line. When mouse is far away from line but within chart area it does not show the circle and value. I need to draw the circle over the line point nearest to the X-axis of the mouse pointer and show this data on a label

A: You can find the closest point measuring only the x-values or the y-values or measuring the absolute distances. Or you could simple output the values under the mouse cursor, no matter the points. For this last one see here!
For each of the 1st three options this should help:
Class level variables used to set and reset colors..:
DataPoint dpXaxis = null;
DataPoint dpYaxis = null;
DataPoint dpAbs = null;

And a list of points for keeping the pixel locations of all points:
List<Point> pixPoints = null;

The MouseMove event:
private void chart_MouseMove(object sender, MouseEventArgs e)
{
    ChartArea ca = chart.ChartAreas[0];
    Axis ax = ca.AxisX;
    Axis ay = ca.AxisY;
    Series s = chart.Series[0];

    if (!s.Points.Any()) return; // no data, no action!

    // option 1:
    // the values at the mouse pointer:
    double valx = ax.PixelPositionToValue(e.X);
    double valy = ay.PixelPositionToValue(e.Y);

    // the deltas on the x-axis (with index):
    var ix = s.Points.Select((x, i) => new {delta = Math.Abs(x.XValue - valx), i})
                            .OrderBy(x => x.delta).First().i;
    var dpx = s.Points[ix];

    // option 2:
    // the deltas on the y-axis (with index):
    var iy = s.Points.Select((x, i) =>
                      new {delta = Math.Abs(x.YValues[0] - valy), i })
                     .OrderBy(x => x.delta).First().i;
    var dpy = s.Points[iy];

    // option 3:
    // the absolute distances (with index):
    var ind = pixPoints.Select((x, i) =>
        new { delta = Math.Abs(x.X - e.X) + Math.Abs(x.Y - e.Y), i}).
        OrderBy(x => x.delta).First().i;
    // find index of smallest delta
    var dpca = s.Points[ind];

    // set/reset colors
    if (dpXaxis != null) dpXaxis.Color = s.Color;
    dpXaxis = dpx;
    dpXaxis.Color = Color.LawnGreen;

    // set/reset colors
    if (dpYaxis != null) dpYaxis.Color = s.Color;
    dpYaxis = dpy;
    dpYaxis.Color = Color.Cyan;

    if (dpAbs != null) dpAbs.Color = s.Color;
    dpAbs = dpca;
    dpAbs.Color = Color.Red;
}

To find the point closest in both directions you will need to either include the scales of the axes or, probably easier, create a List<PointF> from the DataPoints that hold the locations of the points in pixels. For this use the reverse axis functions. Then I calculate the deltas in a similar fashion as the Linq above.
The list gets filled/updated like so:
List<Point> getPixPoints(Series s, ChartArea ca)
{
    List<Point> points = new List<Point>();
    foreach (DataPoint dp in s.Points)
    {
        points.Add(new Point(
            (int)ca.AxisX.ValueToPixelPosition(dp.XValue),
            (int)ca.AxisY.ValueToPixelPosition(dp.YValues[0])  ));
    }
    return points;
}

Let's see it at work:


text:
Q: Stripe Payment Link success link to include session id I can't seem to figure out how to include session id into stripe checkout success redirect.
I setup stripe check out payment link (from UI), I don't need anything fancy, just simple subscription. Once payment is successful, I would like to redirect customer to my WebApp, but I do need to include Stripe session id.

Unfortunate redirect includes literal {CHECKOUT_SESSION_ID}, instead of real session id. How can I mend it?
Thanks.


text:
Q: Error while Adding Poster Image to an Audio File in ffmpeg i have installed ffmpeg in ubuntu and tried to do the following:
when i tried to add an image(color2.jpg) to an audio file (sample.mp3) i got an error saying
"Unable to find a suitable output format for 'experimental'
experimental: Invalid argument"

A: If you just wish to include a video stream with your audio, then use the current command with one correction, specify the name of the audio codec :
ffmpeg -loop 1 -i color2.jpg -i sample.mp3 -c:v libx264 -c:a aac -strict experimental -b:a 192k -shortest outputfile.mp4

(If you're using a FFmpeg version from Dec 2015 or later, you don't need -strict experimental)


text:
Q: Mongo chokes with 'login failed' when trying to login with user and pwd The user 'tyuser' has been added to the system.users collection in the admin database:
{user: 'tyuser',
 pwd: 'typwd',
 roles: [{role: 'readWrite', db: 'testy'}]}

mongod is then started with mongod --auth
When trying mongo testy -u tyuser -p typwd
mongo barfs with "exception: login failed"
What is the correct way to access my 'testy' database as an authenticated user?


text:
Q: Rhino mocks: Issue with IEnumerator.MoveNext() when stubbing an IEnumerable interface Our API has an interface inheriting from IEnumerable like this:
public interface IFoos : IEnumerable<IFoo>
{
    // Additional foo-collection-specific methods
}

I'm writing a unit test for a class that depends on IFoos. It has a method that iterates on an IFoos, like this:
public class Bar
{

    public IFoos Foos {get; set;}
    public void FooItUp()
    {
        foreach (IFoo foo in this.Foos)
        {
            foo.JumpAround();
        }
    }
}

In my unit test, I manage to stub out the dependency and return an Enumerator with Rhino Mocks like so:
[Test]
public void FooItUp_JumpsUpJumpsUpAndGetsDown()
{
    // Arrange
    var mocks = new MockRepository();
    var stubFoo1 = mocks.Stub<IFoo>();
    var stubFoo2 = mocks.Stub<IFoo>();
    var stubFoos = mockRepository.Stub<IFoos>().
    var fooEnumerator = new List<IFoo> { stubFoo1, stubFoo2 }.GetEnumerator();
    stubFoos.Stub(x => x.GetEnumerator()).Return(null).WhenCalled(x => x.ReturnValue = fooEnumerator);
    Bar bar = new bar();
    bar.Foos = stubFoos;

    // Act
    bar.FooItUp();

    // Assert
    ...

}

When I try running this test, an exception is thrown:
System.InvalidOperationException : Previous method 'IEnumerator.MoveNext();' requires a return value or an exception to throw.

Looking at the IEnumerable interface, though, the only method I should have to implement or set a return value for is GetEnumerator() which I did above, right?  Why doesn't the foreach loop in Bar.FooItUp() just call MoveNext() on the List enumerator?

A: Durrr.
I wasn't putting my stubs in replay state before acting on them.
Adding the line:
mocks.ReplayAll();

before calling bar.FooItUp() fixed the issue.

A: Try changing:
stubFoos.Stub(x => x.GetEnumerator()).Return(null).WhenCalled(x => x.ReturnValue = fooEnumerator);

To:
stubFoos.Stub(x => x.GetEnumerator()).Return(fooEnumerator);

Edit: interesting info in that question you linked.
Having looked at it, try:
stubFoos.Stub(x => x.GetEnumerator()).Return(null).WhenCalled(x => x.ReturnValue = new List<IFoo> { stubFoo1, stubFoo2 }.GetEnumerator());


text:
Q: Detect if specific R script is running in Windows batch file I have a .bat file that works great to detect if Rscript.exe is running, and if not it will launch a specific Rscript file. Below is the code, which was inspired by this SO Q&A Batch program to to check if process exists:
cd C:\R\Scripts
tasklist | find /i "Rscript.exe" && echo process "Rscript.exe" is running. ||
"C:\Program Files\R\R-3.4.1\bin\x64\Rscript.exe"
"C:\R\Script_1.R"

However, as opposed to simply checking if the Rscript.exe process itself is running, I want to detect if Rscript.exe is running the specific Script_1.R file. This way, I can have individual .bat files for each R script file. I wouldn't want to run all the scripts from one .bat file because I wouldn't want to relaunch all the scripts, just the scripts which aren't currently running.


text:
Q: Magento 2 Payment Module Sample Wanted to check the sample module for online payments from Magento, but noticed that the module is not anymore in Magento Github Repository.
Does anyone have any idea where can it be found?

Broken Link to Github from official documentation

A: Looks like that entire repository was removed, so no more sample apps. Instead I believe they want you to refer to the dev docs as well as existing modules in the code base.
Specifically for payment gateways you'd be looking at Braintree as your example implementation in code and the Payment gateway integration documentation page.

A: The official repo of Magento don't have the modules anymore, but I noticed that Mageplaza has a clone of the repositories.
Anyone interested can access the example modules in this link.
magento2-samples


text:
Q: Oracle package replace is stuck I have this DATA_CAPTURING package I am trying to replace the package body.
The package is called by a scheduled job every 15 minutes. The job can take longer than 15 minutes.
I believe this has to do with locks being held on the package.
I have the following SQL to find potential locks:
SELECT s.sid,
   s.SERIAL#,
   s.STATUS,
   s.STATE,
   s.username,
   l.lock_type,
   l.mode_held,
   l.mode_requested,
   l.lock_id1
FROM   dba_lock_internal l,
   v$session s
WHERE s.sid = l.session_id
AND UPPER(l.lock_id1) LIKE '%DATA_CAPTURING%'
;

This is the output:
12  223 ACTIVE  WAITED SHORT TIME   XXX Cursor Definition Lock  Null    None    SELECT s.sid,        s.SERIAL#,        s.STATUS,        s.STATE,        s.username,        l.lock_type,        l.mode_held,        l.mode_requested,        l.lock_id1     FROM   dba_lock_internal l,        v$session s     WHERE s.sid = l.session_id     AND UPPER(l.lock_id1) LIKE '%DATA_CAPTURING%'
12  223 ACTIVE  WAITED SHORT TIME   XXX Cursor Definition Lock  Null    None    SELECT s.sid,        s.SERIAL#,        s.STATUS,        s.STATE,        s.username,        l.lock_type,        l.mode_held,        l.mode_requested,        l.lock_id1     FROM   dba_lock_internal l,        v$session s     WHERE s.sid = l.session_id     AND UPPER(l.lock_id1) LIKE '%DATA_CAPTURING%'
15  105 KILLED  WAITING XXX Cursor Definition Lock  Null    None    call XXX.DATA_CAPTURING.RUN_EXTRACTION (  )
15  105 KILLED  WAITING XXX Cursor Definition Lock  Null    None    call XXX.DATA_CAPTURING.RUN_EXTRACTION (  )
15  105 KILLED  WAITING XXX Table/Procedure/Type Definition Lock    Null    None    XXX.DATA_CAPTURING
15  105 KILLED  WAITING XXX Body Definition Lock    Null    None    XXX.DATA_CAPTURING
203 489 ACTIVE  WAITING XXX Body Definition Lock    Exclusive   None    XXX.DATA_CAPTURING
15  105 KILLED  WAITING XXX Table/Procedure/Type Definition Pin Share   None    XXX.DATA_CAPTURING
203 489 ACTIVE  WAITING XXX Body Definition Pin None    Exclusive   XXX.DATA_CAPTURING
15  105 KILLED  WAITING XXX Body Definition Pin Share   None    XXX.DATA_CAPTURING

I tried to kill the session 15,105 but as you can see its not gone yet.
For killing, I used alter system kill session 'SID,SERIAL#';
Meanwhile, my database package replace script received a timeout:
create or replace PACKAGE BODY            "DATA_CAPTURING" AS
ERROR at line 1:
ORA-04021: timeout occurred while waiting to lock object

Is there anything else I can do except waiting for that session to kill itself, or restarting the database?
I solved a very similar question with a restart, but I am not happy with this kind of solution.

A: I found the following solution:
exec dbms_scheduler.disable('RUN_EXTRACTION_SIRIUS_1');

This will give an error message about the job currently running.
So I issued the following command:
exec DBMS_SCHEDULER.STOP_JOB ( job_name => 'RUN_EXTRACTION_SIRIUS_1', force => true);

However now the "disable" command still gave an error message. Maybe because the scheduler started a new job right away. So issued the "stop_job" command again.
After that, the "disable" command worked.
I then was able to run the database upgrade script to replace the package body of DATA_CAPTURING.
Finally I issued the command to re-enable the job:
dbms_scheduler.enable('RUN_EXTRACTION_SIRIUS_1');