Q:

Spring-boot WebMvcTest, why am i getting this NullPointer when i provide a mocked UserDetailsService?

I am trying to create some @WebMvcTest cases in Spring boot. I have a controller under test and i am trying to use @WithUserDetails so that i can test the Authentication object that gets passed to my controller method as a parameter.
I have a custom UserDetails extension named EmployeeDetails.
I mock my UserDetailsService with @MockBean and i make it return a custom EmployeeDetails object using given(userDetailsService.loadUserByUsername(anyString())).willReturn(new EmployeeDetails(employee, account));
However, when i run the test i get the following error:
java.lang.IllegalStateException: Unable to create SecurityContext using @org.springframework.security.test.context.support.WithUserDetails(setupBefore=TEST_METHOD, userDetailsServiceBeanName=userDetailsService, value=someemail@email.com)

    at org.springframework.security.test.context.support.WithSecurityContextTestExecutionListener.createTestSecurityContext(WithSecurityContextTestExecutionListener.java:126)
    at org.springframework.security.test.context.support.WithSecurityContextTestExecutionListener.createTestSecurityContext(WithSecurityContextTestExecutionListener.java:96)
    at org.springframework.security.test.context.support.WithSecurityContextTestExecutionListener.beforeTestMethod(WithSecurityContextTestExecutionListener.java:62)
    at org.springframework.test.context.TestContextManager.beforeTestMethod(TestContextManager.java:289)
    at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:74)
    at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
    at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:251)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
    at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
    at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:230)
    at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:58)
Caused by: java.lang.NullPointerException
    at org.springframework.security.test.context.support.WithUserDetailsSecurityContextFactory.createSecurityContext(WithUserDetailsSecurityContextFactory.java:63)
    at org.springframework.security.test.context.support.WithUserDetailsSecurityContextFactory.createSecurityContext(WithUserDetailsSecurityContextFactory.java:44)
    at org.springframework.security.test.context.support.WithSecurityContextTestExecutionListener.createTestSecurityContext(WithSecurityContextTestExecutionListener.java:123)
    ... 23 more

What is causing this? I don't understand. I am under the impression that the mocked UserDetailsService should return the object that i provide in the given call. Why  am i getting the NullPointer? Can anyone point me in the right direction?
Thanks!
This is my test case:
@RunWith(SpringRunner.class)
@WebMvcTest(PDPController.class)
@AutoConfigureMockMvc(addFilters = false)
public class PDPControllerTests {

    @Autowired
    private MockMvc mvc;

    @Autowired
    private ObjectMapper objectMapper;

    @MockBean
    private PDPService pdpService;

    @MockBean(name = "userDetailsService")
    private MyUserDetailsService userDetailsService;

    //..

    @Test
    @WithUserDetails(value = "someemail@email.com", userDetailsServiceBeanName = "userDetailsService")
    public void testSaveBackground_returns_result_from_service() throws Exception {
        PersonalDevelopmentPlan pdp = new PersonalDevelopmentPlan();
        pdp.setEmployee(EMPLOYEE_ID);
        Account account = new Account();
        Employee employee = new Employee();

        given(pdpService.saveBackground(eq(EMPLOYEE_ID), any(), anyInt())).willReturn(pdp);
        given(userDetailsService.loadUserByUsername(anyString())).willReturn(new EmployeeDetails(employee, account));

        mvc.perform(patch(URL_WITH_ID + "/background").secure(true)
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(pdp)))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.employee", Matchers.is(EMPLOYEE_ID)));
    }

}

A:

Add the following

    @PostConstruct
    public void setup() {
        Account account = new Account();
        Employee employee = new Employee();
        given(userDetailsService.loadUserByUsername(anyString()))
             .willReturn(new EmployeeDetails(employee, account));
    }

And remove the following line from inside the test method

   given(userDetailsService.loadUserByUsername(anyString()))
             .willReturn(new EmployeeDetails(employee, account));


Q:

Merging dataframes using a table

I have a matrix of similarity (which is built as a dataframe):
mat = pd.DataFrame(index = df.a.values,columns = df.a.values)
mat[:] = [[1,0.2,0.3],[0.7,1,0.6],[0,0.4,1]]
    id1     id2     id3
id1 1.0     0.2     0.3
id2 0.7     1.0     0.6
id3 0.0     0.4     1.0

And I would like to create another dataframe which contains the same index but with a single column containing the closest id:
    id      closest
0   id1     id3
1   id2     id1
2   id3     id2

The idea is to look for every row in the similarity matrix for the second highest value (the first will always be 1 on the diagonal), and retrieve the name of the corresponding column.
I know I could set the diagonal to zero, and then use something like this:
def closest(x):
    return np.where(x == x.max())

temp = mat.apply(lambda x: closest(x))
df['closest'] = df.index[[w[0][0] for w in temp.values]].tolist()

But I can't find how to filter the diagonal without reassigning it..
Note: the values in my matrix are all between 0 and 1, and the only 1 are on the diagonal

A:

Subtract the identity matrix, then use DataFrame.idxmax() to find the index of the largest value in each row.
import numpy as np
import pandas as pd

index = ['id1', 'id2', 'id3']
mat = pd.DataFrame([[1, 0.2, 0.3],[0.7, 1, 0.6],[0, 0.4, 1]],
                   index=index, columns=index)

(mat - np.identity(3)).idxmax(axis=1)

Output:
id1    id3
id2    id1
id3    id2
dtype: object


Q:

Angular-Bootstrap UI Tabs: Remove Tab Option

I have a special requirement for my project where I use Angular-UI-Bootstrap to create a tabbed view.
<uib-tab data-ng-repeat="pageTitle in form.pagetitles" heading="{{pageTitle}}">
    // tab content and so on...
</uib-tab>

I want to have a Button next to the Tab-Heading with a linked ng-click function. In this function I want to remove the page (still implemented, no help needed here).
<button data-ng-click='removePage(pageTitle)' class='btn btn-default'></button>

My Problem: I do not have an idea how to get the button next to the heading. Can anyone help me?

A:

Instead of using the attribute "heading" use the tag: <uib-tab-heading>
Something like:
<uib-tab data-ng-repeat="pageTitle in form.pagetitles">
  <uib-tab-heading>

{{pageTitle}}

      <button data-ng-click='removePage(pageTitle)' class='btn btn-default'></button>

  </uib-tab-heading>
  // tab content and so on...
</uib-tab>


Q:

Scout SmartField suggestions from Hibernate

I am working in Scout and need SmartField. For this I need to set up lookup for suggestions.
I see the example with creating Lookup Call and than implement in Lookup Service getConfiguredSqlSelect
but I use Hibernate to work with classes, so my question is how to connect Smart field with Hibernate object filled service?

A:

create a new lookup call according to [1] with the following differences:

don't select AbstractSqlLookupService as a lookup servic super type, but AbstractLookupService
in the associated lookup service you now need to implement getDataByAll, getDataByKey, and getDataByText

to illustrate the following snippet should help:
public class TeamLookupService extends AbstractLookupService<String> implements ITeamLookupService {

  private List<ILookupRow<String>> m_values = new ArrayList<>();

  public TeamLookupService() {
    m_values.add(new LookupRow<String>("CRC", "Costa Rica"));
    m_values.add(new LookupRow<String>("HON", "Honduras"));
    m_values.add(new LookupRow<String>("MEX", "Mexico"));
    m_values.add(new LookupRow<String>("USA", "USA"));
  }

  @Override
  public List<? extends ILookupRow<String>> getDataByAll(ILookupCall<String> call) throws ProcessingException {
    return m_values;
  }

  @Override
  public List<? extends ILookupRow<String>> getDataByKey(ILookupCall<String> call) throws ProcessingException {
    List<ILookupRow<String>> result = new ArrayList<>();

    for (ILookupRow<String> row : m_values) {
      if (row.getKey().equals(call.getKey())) {
        result.add(row);
      }
    }

    return result;
  }
  ...

[1] https://wiki.eclipse.org/Scout/Tutorial/4.0/Minicrm/Lookup_Calls_and_Lookup_Services#Create_Company_Lookup_Call


Q:

Pandas DataFrame.Apply output format

Have questions concerning the output of apply() method in python pandas.DataFrame
Q1 -
Why does this function returns a pandas.DataFrame with the same format as the input (pandas.DataFrame) when apply function returns an array with the same shape as input?.
For instance
foo = pd.DataFrame([[1,2],[3,4]],columns=['a','b'])
foo.apply(lambda x: [np.min(x)/2,np.max(x)/2], axis='index')

code will return:
       a        b
0   min(a)/2   min(b)/2
1   max(a)/2   max(b)/2

Q2 -
For some reason I would like to output a pandaq.Series of arrays instead:
0   [min(a)/2, max(a)/2]
1   [min(b)/2, max(b)/2]
...

I have tried reduce=True without success.
Then, How should I do?
Thank you in advance.

A:

I prefer to avoid apply where numpy operations are possible.
In this case, there are at least a couple of alternatives. Below are examples with benchmarking. As you can see, the closer you move to numpy, the better the results.
import pandas as pd, numpy as np

foo = pd.DataFrame([[1,2],[3,4]],columns=['a','b'])

foo = pd.concat([foo]*10000, ignore_index=True)

def dark(df):
    return df.apply(lambda x: tuple([np.min(x)/2,np.max(x)/2]), axis=1)

def jp1(df):
    return [tuple([np.min(x)/2,np.max(x)/2]) for x in foo[['a', 'b']].values]

def jp2(df):
    arr = foo[['a', 'b']].values
    return list(zip(*(np.min(arr, axis=1)/2, np.max(arr, axis=1)/2)))

%timeit dark(foo)  # 4.95s
%timeit jp1(foo)   # 298ms
%timeit jp2(foo)   # 4.68ms

Of course, dark() returns a pd.Series, but pandas lets you assign via a list.


Q:

Conditions for using mail.css with drupal_mail()

Problem
I'm trying to style an email sent with drupal_mail. Sometimes it works, other times it doesn't and I can't work out why.
I'm running mail system, SMTP and mimemail:
Mail system sets up: SMTP for sending and mimemail for styling.
In the mimemail options include stylesheets is disabled because it's found mail.css in my theme. Mime mail CSS compressor is enabled because people use hotmail and gmail.
Condition 1
User uses form to send email, this works as expected I receive a styled email in gmail.
$message = drupal_mail('module_1', 'notify', $email, language_default(), $params);

function module_1_mail($key, &$message, $params) {
    $title = check_plain($_SESSION['title']);
    $message['headers']['MIME-Version'] = '1.0';
    $message['headers']['Content-Type'] = 'multipart/mixed; text/html; charset=UTF-8; format=flowed;';
    $message['subject'] = t('Email subject plus ').$title;

    $message['body'][] = "Body text goes here";
    $message['params']['attachments'] = $params;
  }

Condition 2
The user uses another form which schedules a rule action which sends an email some time later. This doesn't receive any styling despite seeming identical for all intents and purposes.
$message = drupal_mail('rules_module', 'notify', $user->mail, language_default(), $params);

function rules_module_mail($key, &$message, $params) {
    $message['headers']['MIME-Version'] = '1.0';
    $message['headers']['Content-Type'] = 'multipart/mixed; text/html; charset=UTF-8; format=flowed;';

    $message['subject'] = t('Here is a (@location)', array('@location' => $params['location']));
    $message['body'][] = 'This is some body text';
  }

Could rules somehow affect the calling of a stylesheet? Am I missing something obvious?

A:

The problem in my case was that the email being sent wasn't using the drupal_mail function but php send mail.
I run msmtp on my server to route mail and so rather than passing through drupal, the email was being sent directly through my server with none of the styling.


Q:

Why are screen readers not reading out the label for a select element

If I have a standard select element with a label, like this:
<label for="mySelect">My Select</label>
<select id="mySelect">
  <option>Please select</option>
  <option>One</option>
  <option>Two</option>
</select>

When I am using JAWS or mac voiceover, the screen reader reads the first option and not the label.
Is there some aria-attribute I should be adding to get the screen reader to read the label?

A:

This is unfortunately the expected behavior with Jaws according to Testing Select box labels with Screen Readers when using the Virtual Cursor.
The user has to use the tab key to get the associated label


Q:

Run from solar panel without batteries?

Is it possible to use solar panel(/s) as primary power for an electric bike, HPV or light velomobile (without batteries, mandatory assisted mode only) ?
Are there any limitations or obstacles ?
Example could an "solar backpack", panel 300Wp 1.6x1m size, weight <20kg help to keep at least reasonable constant speed on a flat road. There could be 5x output power difference depending on sun light, season, etc. (home installation webs)
Suppose a single vehicle - no large separate trails, etc.

A:

There is a race, the Sun Trip, for solar-powered bikes (and there have been a few other one-off efforts). Looking at the entrants, there are some that use huge PV roofs to avoid using trailers, but as @Affe points out, those could turn into sails.
Most e-bikes use 250-W motors (if not larger). Depending on the speed you're satisfied with, you could get away with half that power. Weight isn't what will make it hard to maintain a decent speed with these: aerodynamics are vastly more consequential, and a big flat PV array will make it hard to optimize aerodynamics.
Depending on how many hours of the day you're riding the bike, how many hours your PV array is in the sun, and your battery capacity, you may be able to run the bike without ever plugging it into a wall…but you could extend that logic to using a stationary PV array as your power source and running only off batteries—that is, a regular e-bike—when on the road. This might turn out to be more efficient than trying to charge while you ride due to the inefficiencies of having a bike-mounted PV array.
My own take is that solar-powered bikes are possible as interesting experiments, but impractical for day-to-day transportation.

A:

A human produces 100-300 W (100 W is trivial even when exhausted, 300 W can be produced only up intermediate-length hills). Unless you want the bicycle to be unstable up hills, you want the full 300 W up steep hills. Solar power constant is about 1000 W / square meter, when there are no clouds. Of those, common silicon solar panels produce about 200 W / square meter, the rest is losses. You need more than a square meter of panels and continuous sunny weather to get up hills at any reasonable speed.
If multijunction cells are an option (expensive), you get 400 W / square meter perhaps. So, less than a square meter is enough in sunny weather. You however need to handle cloudy weather somehow.
My advice? Use multijunction cells that track the sun and don't ditch the pedals. The pedals come handy when it's cloudy. I would also advise to not ditch the battery. It helps you up hills, so that even 100-150 W average power produced is enough.
A problem is where to mount the cells and how to ensure they track the sun when you turn. If they don't track the sun, you need more cells.
Also, how to ensure that the solar cells don't cause excessive air resistance is a problem. The mount needs to be very sturdy so that they don't fly away in the wind.
I think you'll find that common backpacks rarely have more than 0.2 square meters of area. Multijunction panels that are 0.2 square meters produce only 80 watts when they are perfectly oriented and there are no clouds. A backpack most of the time is not perfectly oriented, and often there are clouds.
A better approach would be to connect the solar panels to electricity grid (then cheap single-junction silicon cells are enough) to produce hydrogen during the daytime. The hydrogen is then compressed. During the nighttime, when you sleep, the battery of the e-bike is charged using fuel cells powered by the compressed hydrogen. With large enough battery, the system might be enough for riding one day at a time.
You can also refine the grid-connected idea by adding wind power to complement the solar power during windy but non-sunny (cloudy) days.


Q:

Is there a way to re-write this query without subqueries?

I've got a table of employees from HR schema (oracle). This is how I completed the task (select employees with minimal salary in their departments, if they belong to any of them)
    SELECT D.employee_id,D.Last_name,D.salary,D.department_id
    FROM [HelpDatabase].[dbo].[Employees] D,
         [HelpDatabase].[dbo].[Employees] E
    WHERE D.department_id IS NOT NULL
      AND E.department_id IS NOT NULL
      AND D.employee_id=E.employee_id
      AND D.salary=ANY (
          SELECT MIN(E.salary)
          FROM [HelpDatabase].[dbo].[Employees]
          GROUP BY E.department_id)

Query working correctly, but I've been told there's a way to do it without using subquery.

A:

Supposing you simply want to find the employees that earn the lowest salaries in their departments:
Yes, this can be done without a subquery. The idea is that you can look for employees for which not exists another employee in the same department and a lower salary:
select *
from emp
where not exists
(
  select *
  from emp less
  where less.department_id = emp.department_id and less.salary < emp.salary
);

A NOT EXISTS query can also be written as an anti-join. This is: outer join the lesser earning employees; then remove from your results all employees where you found such persons.
select *
from emp
left join emp less on less.department_id = emp.department_id and less.salary < emp.salary
where less.employee_id is null;

You would usually not do this, though, because it's a trick, and it's a bit obfuscated what the query is actually doing. NOT EXISTS is clearer here, asking "give me employees for which not exist collegues who earn less".
(Well, in your case you might even use something entirely else, such as where (department_id, salary) in (select department_id, min(salary) ...) or rank() over partition by department_id order by salary.)
But anti joins are a solution when your DBMS proves weak on not exists queries. They are simply another way to write the same thing.


Q:

Are the electrons' orbitals the same for all atoms?

Are the electronic orbitals of an atom always quantified in the same way (i.e. the same energy required to reach the next level), or does each atom have its own values for each level?

If the quantification is universal, then the creation of photons (due to the deexcitation of the electrons) at the wavelength / color corresponding to the transition should be more abundant in the universe than all the other frequency. Except one detects no more photon of a given wavelength than of another.
So where is my reasoning error?

A:

The energy levels depend on two things:

the electrostatic attraction between the electrons and the nucleus
the electrostatic repulsion between the electrons

If you take a hydrogen atom, which is what your diagram shows, then there is a single electron and a single proton. The electron is attracted to the proton and there is no electron-electron repulsion because there is only one electron.
If you move on the the next element, helium, there are two electrons and the nucleus contains two protons. So the attraction between the electrons and the nucleus is now twice as big but we have a repulsion between the two electrons. Both these factors change the energy levels so they are not the same as hydrogen. The next element, Lithium, has three electrons and three protons in the nucleus so the energy levels are different again. And so on.
So all the atoms of a given element have the same energy levels because they have the same numbers of electrons and protons. For example all hydrogen atoms have the same energy levels. But the different elements have different energy levels because they contain different numbers of electrons and protons. The hydrogen energy levels differ from helium, which in turn differs from lithium and so on.
And just to complicate matters the number of neutrons in the nucleus makes a small difference as well, so for example the energy levels of hydrogen are slightly different from the energy levels of deuterium and tritium.

A:

The diagram you posted shows the electron energy levels for the hydrogen atom only. Other atoms will have different energy levels. Also note that the hydrogen atom itself has an infinite amount of energy levels which the diagram does not really show.
This information is very useful. The energy levels for each atom are unique, and the corresponding frequencies of light emitted by the electrons can serve as a signature of the atoms presence. This gave rise to the field of spectroscopy and it is useful in many applications. For instance, the frequencies of the light coming from other planets is used to determine the composition of the atmosphere.

A:

To add to @john-rennie 's answer: things get even worse as the environment of the atom makes additional modifications to the energy levels (ranging in the meV). For example, a carbon atom bound to an oxygen will have a slight energy shift compared with a free carbon atom, or a carbon atom bound in a diamond structure. These shifts are very useful in identifying molecular species.


Q:

Android studio - Build script error, unsupported Gradle DSL method found: 'android()'!

I'm getting the following error in Android Studio 0.4.2 when I'm trying to Sync project with gradle.
Gradle 'GooglePlayServicesTest' project refresh failed:
       Build script error, unsupported Gradle DSL method found: 'android()'!

My projects gradle file is as follows :-
buildscript {
repositories {
    mavenCentral()
}
dependencies {
    classpath 'com.android.tools.build:gradle:0.7.+'
}
}

allprojects {
repositories {
    mavenCentral()
}
}

android{

compileSdkVersion 19
buildToolsVersion "19.0.1"

defaultConfig {
    minSdkVersion 10
    targetSdkVersion 19
    versionCode 1
    versionName "1.0"
}

sourceSets{
    main{
        manifest.srcFile 'GooglePlayServicesTest/src/main/AndroidManifest.xml'
    }
}
}

gradle file of module:-
apply plugin: 'android'

android {
compileSdkVersion 19
buildToolsVersion "19.0.1"

defaultConfig {
    minSdkVersion 10
    targetSdkVersion 19
    versionCode 1
    versionName "1.0"
}
buildTypes {
    release {
        runProguard false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
    }
  }
}
dependencies {
compile 'com.android.support:appcompat-v7:+'
}

also I have removed the miniSDKVersion and targetSDKVersion from AndroidManifest.xml
can someone help me to solve this error.

A:

android method in project gradle file is not needed.Try to remove it.


Q:

How to export function with return type std::map in c++

I have a DLL project and a CLR project in visual c++.
The DLL project is the one that exporting std::map type function. And I will call that function from my CLR project.
From DLL project,
staff.h
#ifdef STAFFS_EXPORTS
#define STAFFS_API __declspec(dllexport)
#else
#define STAFFS_API __declspec(dllimport)
#endif

#include <string>
#include <map>

namespace Staffs {
    // other exported functions
    ....
    //
    extern "C" STAFFS_API auto GetStaffMap() -> std::map<int, std::string>;
}

staff.cpp
namespace Staffs {
   std::map<int, std::string> staffMap;

   extern "C" auto GetStaffMap() -> std::map<int, std::string> {
        return staffMap;
    }

   void display_json(json::value const & jvalue, utility::string_t const & prefix)
    {
      // some code being skipped here
      .......
      //
      staffMap.insert(std::make_pair(key, value));
    }
}

But when I tried to compile my DLL project, I got some errors:
Error   C2526   'GetStaffMap': C linkage function cannot return C++ class 'std::map<int,std::string,std::less<int>,std::allocator<std::pair<const _Kty,_Ty>>>'  AmsCppRest  c:\users\laptop-attendance\source\repos\amscpprest\amscpprest\staff.h   18

Error   C2556   'std::map<int,std::string,std::less<int>,std::allocator<std::pair<const _Kty,_Ty>>> Staffs::GetStaffMap(void)': overloaded function differs only by return type from 'void Staffs::GetStaffMap(void)'   AmsCppRest  c:\users\laptop-attendance\source\repos\amscpprest\amscpprest\staff.cpp 38

Error   C2371   'Staffs::GetStaffMap': redefinition; different basic types  AmsCppRest  c:\users\laptop-attendance\source\repos\amscpprest\amscpprest\staff.cpp 38

I can't find any solution related to this problem.

A:

You cannot export non-trivial C++ classes with C linkage, and the compiler is telling you so in the error message.
The question is why do you use C linkage in the first place? If you don't have to use C linkage, don't use it. This will make things just more complicated as you need wrappers for almost everything. As long as you use the same compiler you'll be fine.
So in your header and source files, remove the extern "C" from the signature if you can (in either case: remove it from the source file, or else you redefine the function there which causes the latter 2 errors).
If you cannot remove the extern "C" part, try returning a void pointer (void*) instead of std::map and cast it to a map pointer in your CLR project. But this will force you to use managed C++ as CLR language.
I don't know what your CLR project is, but if it's written in managed C++ you can use all standard C++ types there aswell so C++ linkage is perfectly fine. If your CLR project is in a different language, like C#, consider making another project in managed C++ and use that as a wrapper like C# dll <--> managed C++ dll <--> C++ dll.


Q:

TypeError: __init__() takes 3 positional arguments but 4 were given

These are the codes for my classes:
class Employee:
    def __init__(self, name, gender):
        self.name = name
        self.gender = gender

class Salary:
    def jump(self, name, salary):
        print(self.name, self.salary)

class Male(Salary, Employee):
    def __init__(self, name, gender, occupation):
        super(Male, self).__init__(name, gender, occupation)
        self.occupation = occupation

# Separate from all classes (list of instantiated objects)
employee1 = Male("Jim", "male", "technician")
print(Male.name)

When I use the last two lines of the code after creating all my classes, a 'TypeError: init() takes 3 positional arguments but 4 were given' error occurs referencing the super(Male, self).... and employee1 = Male(... lines.

A:

Under Pet you have:
def __init__(self, name, color):
    self.name = name
    self.color = color

Under Dog you have:
def __init__(self, name, color, owner):
    super(Dog, self).__init__(name, color, owner)

Under Dog there's an extra owner positional argument given, which leads to this error. On a side note, I think super().__init__(name, color) works just as well too in Python 3


Q:

View all subscribed events?

I have a feature where if a user navigates to a specific url (www.mysite.com/special-content) they are redirected to the login page, where we've appended a destination to the request (www.mysite.com/user/login?destination=special-content).
We created a custom module using a checkAuthStatus event subscriber to detect anonymous users and redirect them appropriately:
$ cat src/EventSubscriber/RedirectAnonymousSubscriber.php
<?php

namespace Drupal\anon_redirect\EventSubscriber;

use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

/**
 * Event subscriber subscribing to KernelEvents::REQUEST.
 */
class RedirectAnonymousSubscriber implements EventSubscriberInterface {

  public function __construct() {
    $this->account = \Drupal::currentUser();
  }

  public function checkAuthStatus(GetResponseEvent $event) {
    $paths = [
      '/special-content',
      '/more-special-content'
    ];

    if ($this->account->isAnonymous()) {
      foreach ( $paths as $path ) {
        if ( substr($_SERVER['REQUEST_URI'], 0, strlen($path)) === $path ) {
          $url = \Drupal\Core\Url::fromUri('internal:/user/login',[
            'query'=>['destination'=>$_SERVER['REQUEST_URI']],
          ]);
          $response = new RedirectResponse('/user/login?destination='.$_SERVER['REQUEST_URI'], 302);
          $response->send();
          return;
        }
      }
    }

  }

  public static function getSubscribedEvents() {
    $events[KernelEvents::REQUEST][] = ['checkAuthStatus'];
    return $events;
  }
}

This has been working fine for a few months, but recently I got complains that people were not getting redirected. Upon investigation, I saw that they were getting 'access denied', as evidenced by the watchdog log. That is, when they are not logged in, they see our 301 page, instead of getting redirected.
Frustratingly, I've only been able to intermittently reproduce this problem. Sometimes I get the 301 page, sometimes I get the login page with the proper redirect query appended. I've tried both Firefox and Chrome, private sessions, clearing cookies, etc.
I suspect that whatever decides access also is listening to checkAuthStatus and sometimes having the final word about what page is ultimately sent to the end-user, and our module's behavior is not implemented, while other times, our event listener is invoked.
My question is if there is any way I can see what event listeners are subscribed to the checkAuthStatus event, and ideally, which one is having the final word as to the ultimate response from Drupal. I suspect another one is somehow getting prioritized over mine, and would like to confirm or deny that theory.

A:

In the above code example the event is KernelEvents::Request and checkAuthStatus is the method called when the Request event is dispatched.
You can use Drupal Console debug:event command to list all subscribers for a given event:
vendor/bin/drupal debug:event kernel.request
And that will give you something like:
  Drupal\Core\EventSubscriber\OptionsRequestSubscriber                   onRequest: 1000
  Drupal\Core\EventSubscriber\RedirectLeadingSlashesSubscriber           redirect: 1000
  Drupal\Core\EventSubscriber\AuthenticationSubscriber                   onKernelRequestAuthenticate: 300
  Drupal\language\EventSubscriber\LanguageRequestSubscriber              onKernelRequestLanguage: 255
  Drupal\Core\EventSubscriber\RedirectResponseSubscriber                 sanitizeDestination: 100
  Drupal\Core\EventSubscriber\AjaxResponseSubscriber                     onRequest: 50
  Symfony\Component\HttpKernel\EventListener\RouterListener              onKernelRequest: 32
  Drupal\Core\EventSubscriber\AuthenticationSubscriber                   onKernelRequestFilterProvider: 31
  Drupal\user\EventSubscriber\MaintenanceModeSubscriber                  onKernelRequestMaintenance: 31
  Drupal\Core\EventSubscriber\MaintenanceModeSubscriber                  onKernelRequestMaintenance: 30
  Drupal\Core\Routing\RoutePreloader                                     onRequest: 0
  Drupal\Core\EventSubscriber\ReplicaDatabaseIgnoreSubscriber            checkReplicaServer: 0

If you use Drush and have the devel module installed, you can do:
vendor/bin/drush devel-event kernel.request


Q:

flexbox flex-direction:column with textarea not working as expected in Firefox

The following example works as expected in Chrome but not in Firefox.
The footer height is set to height:40px and in Chrome is ok, however in Firefox is smaller, around 35px . Any reasons why?
https://jsfiddle.net/47gg3fdc/

    <textarea placeholder="textarea ..."></textarea>

    #footer

.container{
  display:flex;
  height:100px;
  background-color:whitesmoke;
  flex-direction:column;
}

.textarea{
  flex-grow:1;
  display:flex;
}

.footer{
  background-color:lightseagreen;
  height:40px;
  color:white;
}

textarea{
   flex-grow: 1;
   border: none;
   resize: none;
   padding: 5px;
   font-size: 16px;
   margin: 0px;
   display: block;
}

A:

The reason is that Firefox find the textarea somewhat higher than Chrome does, and as such, there is no space for the footer.
And the reason it does, is simply that form elements have predefined size and that size often differs between the browsers.
So what happens here is that Firefox adjust the flex items and make them shrink a little to fit their parent, though as the <textarea> is not a flex item, but flex item content, and its parent, the .textarea div element isn't allowed to shrink past content size, it is the footer that will shrink.

If one add flex-shrink: 0 to the footer, which will disallow it to shrink, it will have the same height in both browsers.
To test this, change e.g. the padding: 5px to padding: 0, and the footer will have the same height in both browsers.
Stack snippet

.container{
  display:flex;
  height:100px;
  background-color:whitesmoke;
  flex-direction:column;
}

.textarea{
  flex-grow:1;
  display:flex;
}

.footer{
  background-color:lightseagreen;
  height:40px;
  color:white;
  flex-shrink: 0;                  /*  added  */
}

textarea{
   flex-grow: 1;
   border: none;
   resize: none;
   padding: 5px;
   font-size: 16px;
   margin: 0px;
   display: block;
}

    <textarea placeholder="textarea ..."></textarea>

    #footer


Q:

Is it possible to paint concrete pavers

I have a large paved area that I would like to replace with lawn. My plan is to use some of the pavers as a border.
They're plain concrete pavers (450x450mm) that look like this except about 20 years old:

I was thinking about painting them a nice cream colour.
Has anyone ever done anything like this?
Will the colour fade or chip?
Is there anything I should know about painting ground cover?

A:

Rather than using paint, look at some of the dozens of dry concrete dyes. There are several methods to color concrete after it has cured. Acid wash is very effective.  Check out this web site:  http://www.concretenetwork.com/concrete/walkways/existingdecorativeconcretewalkways.html
There are also several other sites you can look at including Lowes, HD, and Sherwin Williams.
Concrete floor paints are easy and quick, but may require more maintenance and refinishing over time as compared to a stains. If your area is small and not subject to lots of traffic, paint may be a good choice.

A:

It turns out they make special paving paint. It's hard wearing and scuff resistant.
Here is an example.
Here is a video on applying paving paint.
The really import part is cleaning your pavers. The video goes into great detail about using etching solution to clean the concrete before painting. They also clean with sugar soap.


Q:

Getting location offline

I want to get the value of Longitude and Latitude of my current locatoin when offline and save the current location to its database. Is it possible to get the longitude and latitude of the device when mobile data and wifi are off but the GPS is ON?

A:

Just use this code. Make sure the user hasn't selected wifi only or network only option in his location setings. it has to be high accuracy or GPS only. This piece of code will work.
public class Location extends AppCompatActivity {
LocationManager locationManager;
Context mContext;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_location);
    mContext=this;
    locationManager=(LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
    locationManager.requestLocationUpdates( LocationManager.GPS_PROVIDER,
            2000,
            10, locationListenerGPS);
    isLocationEnabled();

}

LocationListener locationListenerGPS=new LocationListener() {
    @Override
    public void onLocationChanged(android.location.Location location) {
        double latitude=location.getLatitude();
        double longitude=location.getLongitude();
        String msg="New Latitude: "+latitude + "New Longitude: "+longitude;
        Toast.makeText(mContext,msg,Toast.LENGTH_LONG).show();
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {

    }

    @Override
    public void onProviderEnabled(String provider) {

    }

    @Override
    public void onProviderDisabled(String provider) {

    }
};

protected void onResume(){
    super.onResume();
    isLocationEnabled();
}

private void isLocationEnabled() {

    if(!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
        AlertDialog.Builder alertDialog=new AlertDialog.Builder(mContext);
        alertDialog.setTitle("Enable Location");
        alertDialog.setMessage("Your locations setting is not enabled. Please enabled it in settings menu.");
        alertDialog.setPositiveButton("Location Settings", new DialogInterface.OnClickListener(){
            public void onClick(DialogInterface dialog, int which){
                Intent intent=new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                startActivity(intent);
            }
        });
        alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener(){
            public void onClick(DialogInterface dialog, int which){
                dialog.cancel();
            }
        });
        AlertDialog alert=alertDialog.create();
        alert.show();
    }
    else{
        AlertDialog.Builder alertDialog=new AlertDialog.Builder(mContext);
        alertDialog.setTitle("Confirm Location");
        alertDialog.setMessage("Your Location is enabled, please enjoy");
        alertDialog.setNegativeButton("Back to interface",new DialogInterface.OnClickListener(){
            public void onClick(DialogInterface dialog, int which){
                dialog.cancel();
            }
        });
        AlertDialog alert=alertDialog.create();
        alert.show();
    }
}
}

The parameters of requestLocationUpdates methods are as follows:
provider:   the name of the provider with which we would like to register.
minTime:    minimum time interval between location updates (in milliseconds).
minDistance:    minimum distance between location updates (in meters).
listener:   a LocationListener whose onLocationChanged(Location) method will be called for each location update.
Permissions:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

Add above permissions to manifest file for the version lower than lollipop and for marshmallow and higher version use runtime permission.


Q:

Stereo ARSCNview to make VR and AR mix

I want to make a mix of virtual reality and augmented reality.
The goal is I have a stereo camera (for each eyes).
I tried to put two ARSCNView in a viewCotnroller but it seems ARKit enable only one ARWorldTrackingSessionConfiguration at the same time. How can I do that?
I researched to copy the graphic representation of a view to past this to an other view but impossible to find. Please help me to find the solution.
I found this link, maybe can it illumine us:
ARKit with multiple users
Here's a sample of my issue:
https://www.youtube.com/watch?v=d6LOqNnYm5s
PS: before unlike my post, comment why!

A:

The following code is basically what Hal said. I previously wrote a few lines on github that might be able to help you get started. (Simple code, no barrel distortion, no adjustment for the narrow FOV - yet).
Essentially, we connect the same scene to the second ARSCNView (so both ARSCNViews are seeing the same scene). No need to get ARWorldTrackingSessionConfiguration working with 2 ARSCNViews. Then, we offset its pointOfView so it's positioned as the 2nd eye.
https://github.com/hanleyweng/iOS-Stereoscopic-ARKit-Template

A:

The ARSession documentation says that ARSession is a shared object.

Every AR experience built with ARKit requires a single ARSession object. If you use an
  ARSCNView
   or
  ARSKView
   object to easily build the visual part of your AR experience, the view object includes an ARSession instance. If you build your own renderer for AR content, you'll need to instantiate and maintain an ARSession object yourself.

So there's a clue in that last sentence. Instead of two ARSCNView instances, use SCNView and share the single ARSession between them.
I expect this is a common use case, so it's worth filing a Radar to request stereo support.
How to do it right now?
The (singleton) session has only one delegate. You need two different delegate instances, one for each view. You could solve that with an object that sends the delegate messages to each view; solvable but a bit of extra work.
There's also the problem of needing two slightly different camera locations, one for each eye, for stereo vision. ARKit uses one camera, placed at the iOS device's location, so you'll have to fuzz that.
Then you have to deal with the different barrel distortions for each eye.
This, for me, adds up to writing my own custom object to intercept ARKit delegate messages, convert the coordinates to what I'd see from two different cameras, and manage the two distinct SCNViews (not ARSCNViews). Or perhaps use one ARSCNView (one eye), intercept its frame updates, and pass those frames on to a SCNView (the other eye).
File the Radar, post the number, and I'll dupe it.


Q:

Avoid safety warnings with Hibernate HQL results?

For example I have such query:
@SuppressWarnings("unchecked")
public List<MenuItems> listAllMenuItems() {

    Session session = HibernateUtil.getSessionFactory().getCurrentSession();
    session.beginTransaction();
    List<MenuItems> menuItems = null;
    try {

        Criteria cr = session.createCriteria(MenuItems.class);
        menuItems = cr.list();

    } catch (HibernateException e) {
        session.getTransaction().rollback();
    }
    session.getTransaction().commit();
    return menuItems;
}

Is there a way to avoid type safety warnings with Hibernate HQL results?
Thanks.

A:

Use Collections.checkedList()
List<MenuItems> cats = Collections.checkedList(cr.list(), MenuItems.class);

Or use @suppressWarnings, which you have specified in your code


Q:

Find joint distribution function in region

I can't for the life of me figure this one out, I am stuck on part (c) ...

I have this as my starting point ?
$$
\frac{45}{304}\int_0^x\int_{2-x}^2 u^2v^2\,\mathrm{du} \mathrm{dv}
$$
Here is my sketch for part a:

The problem I am having is that when I try to calculate the entire CDF for all ranges it sums to more than 1 :( which leads me to believe I am doing something wrong?

A:

My CAS tells me
$$ \int\limits_0^x \int\limits_{2-x}^2 u^2 v^2 du dv = \frac{1}{3} \left( \frac{8}{3}- \frac{1}{3} (2-x)^3\right) x^3$$
This expressoin evaluated at $x=2$ is $\frac{64}{9}$ So $c$ should be chosen as $c=\frac{9}{64}$ and I think this is where the error was?


Q:

Why there are so many methods of getting date time in java?

I have been working on a simple dictionary based android application so i thought to search for best practices to be used in the development. So i searched for the best methods for getting time and date but i found so many methods all resulting into date and time.
For example: Java - How to get current time and date
Here i found multiple methods to get the time and date with formatting as well.
Code Snippets
For java.util.Date, just create a new Date()
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
System.out.println(dateFormat.format(date)); //2016/11/16 12:08:43

For java.util.Calendar, uses Calendar.getInstance()
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Calendar cal = Calendar.getInstance();
System.out.println(dateFormat.format(cal)); //2016/11/16 12:08:43

For java.time.LocalDateTime, uses LocalDateTime.now()
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
LocalDateTime now = LocalDateTime.now();
System.out.println(dtf.format(now)); //2016/11/16 12:08:43

For java.time.LocalDate, uses LocalDate.now()
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd");
LocalDate localDate = LocalDate.now();
System.out.println(dtf.format(localDate)); //2016/11/16

Why there are so many methods of getting date time in java?And Also what's the best method of getting the date and time?

A:

Because date and time are complicated things like how to deal with currency and how to convert text to bytes and back.
You should be using the java.time package introduced in Java 8, as they've fixed things and tried to make it less annoying and weird. It was based on Joda-Time which is a well thought out library.
Date and Calendar are parts of the old time/date API, although there wasn't that much of an API, the classes were stuck to java.util and there were lots of design issues. They still work, but you shouldn't really use them in new code. Not because they're deprecated (they're not), but because they're bad. Imagine Date is to Instant like Vector is to ArrayList.


Q:

Why does referencing .self work instead of type.sharedInstance?

I have some code like this:
class miniUser {

    ///The shared instance of miniUser.
    static let SI = miniUser()

    init()
    {
        self.currentUser = self.getCurrentProfile()! as String
        self.refreshUserList()
    }

...

}

That code works fine. However, this code using the shared instance...
class miniUser {

    ///The shared instance of miniUser.
    static let SI = miniUser()

    init()
    {
        miniUser.SI.currentUser = miniUser.SI.getCurrentProfile()! as String
        miniUser.SI.refreshUserList()
    }

...

}

That does not work. In fact, it doesn't even spit out an error during runtime, it just freezes at 0 fps (I'm using SpriteKit) when another part of the code tries to initialize it.
Ideally, both versions of the code should mean the same thing.
Could anyone explain to me why using self.function() works instead of type.sharedInstance.function() during initialization? I'm not sure about it and need an explanation to understand what is happening here.
Any help is-- err, any explanations are appreciated.

A:

The definition let SI = miniUser() will call the init() of your class in order to create the shared instance. However, init() is trying to access the shared instance miniUser.SI, so this is a recursive definition. It probably shouldn't be allowed at all by the compiler — I'd suggest filing a bug. If you need to modify instance variables during initialization, that's what self. is for. (In fact, you can leave out self. because it's implied.)


Q:

Why use an in-browser VPN?

Our small company works with a large company and must access their customer data daily. In addition to assigning logins, they make us download a certificate on each computer we plan to use, and somehow set up a Cisco VPN inside Internet Explorer. Once logged in, that browser cannot access our corporate intranet, and if I visit whatismyip.com, it shows a different domain than the one at work.
What might be the reasoning for this strategy? If we are directly on their network rather than accessing limited info through a web interface, wouldn't that be less secure?

A:

I use a Cisco ASA 5510 with Clientless SSL VPN for vendor and business partner access at our company. Here is why it makes sense:
When partners access our VPN website, a normal SSL (HTTPS) connection is made for encryption. Once there, almost everything can be done over HTTPS without creating a full VPN tunnel to our network. From the site users can access SMB shares, internal websites, etc. There are even browser based clients available for RDP and VNC if necessary. The benefits to this are:

More secure due to limited access.
Clientless so that partners don't need to install anything.
Accessing standard protocols (SMB, RDP, VNC, HTTP) through the site are supported directly.
Accessing non-standard protocols through the site can be accomplished through custom browser plug-in based tunnels.

Employees access our VPN using Cisco's full SSL VPN client (called AnyConnect) which gives them the equivalent of a traditional IPSec VPN tunnel.
Not sure why they are having you install a certificate. This may be because their SSL cert is self-signed and would otherwise throw up a browser warning at each connection.
Hope this clears things up.
Thanks.

A:

Depending on how big company has set up their firewall, VPN may or may not be less secure.
I think this is a case of "one size fits all", they probably give the same access to everyone, no matter if they acrually need it or not as this is the cheapest and most comfortable solution.
In similar cases I give external customers SSL+client certificate access, together with username and password for the particular service.
Client certificates prevent casual password guessing and URL manipulation/injection attacks, but user/pass for the specific service is still needed since once you have handed out the client cert to someone you have no control over what they do with it, unless it is on the smartcard, but this is a much more complicated (read expensive) story.


Q:

AttributeError: 'dict' object has no attribute 'charss'

I am new to OOP with python. I have 3 classes with one being called from the other as a parameter instance:
class Characters:
    def __init__(self, b="", c = ""):
        self.b= b
        self.c= c

class Words:
    def __init__(self, charss=Characters()):
        self.charss= charss

class Sentences:
    def __init__(self, w=Words()):
        self.w = w

I am then creating a new instance of class Words form another Class and filling it with data i have from a json file.
s = Sentences()
s.__dict__ = json.loads(output.content)

When debugging i can see that s is populated correctly. I am then trying to print out the values of s like this:
print(s.w[0].charss[0])

an error occurs:AttributeError: 'dict' object has no attribute 'charss'
is it because I am populating from the JSON as __dict__ where charss instantiated as list. If that is so what would be the best solution changing the __dict__ from json input or instantiating the object as __dict__?

A:

The problem is the way the instance s is being accessed for printing. I am saving the json output as a dictionary but the instance of a class is by default a list. therefore instead of
print(s.w[0].charss[0])

that line should be
print(s.w[0]["charss"][0])


Q:

How to change the colors of a segment in a UISegmentedControl in iOS 13?

A UISegmentedControl has a new appearance in iOS 13 and existing code to alter the colors of the segmented control no longer work as they did.
Prior to iOS 13 you could set the tintColor and that would be used for the border around the segmented control, the lines between the segments, and the background color of the selected segment. Then you could change the color of the titles of each segment using the foreground color attribute with titleTextAttributes.
Under iOS 13, the tintColor does nothing. You can set the segmented control's backgroundColor to change the overall color of the segmented control. But I can't find any way to alter the color used as the background of the selected segment. Setting the text attributes still works. I even tried setting the background color of the title but that only affects the background of the title, not the rest of the selected segment's background color.
In short, how do you modify the background color of the currently selected segment of a UISegmentedControl in iOS 13? Is there a proper solution, using public APIs, that doesn't require digging into the private subview structure?
There are no new properties in iOS 13 for UISegmentedControl or UIControl and none of the changes in UIView are relevant.

A:

As of iOS 13b3, there is now a selectedSegmentTintColor on UISegmentedControl.
To change the overall color of the segmented control use its backgroundColor.
To change the color of the selected segment use selectedSegmentTintColor.
To change the color/font of the unselected segment titles, use setTitleTextAttributes with a state of .normal/UIControlStateNormal.
To change the color/font of the selected segment titles, use setTitleTextAttributes with a state of .selected/UIControlStateSelected.
If you create a segmented control with images, if the images are created as template images, then the segmented control's tintColor will be used to color the images. But this has a problem. If you set the tintColor to the same color as selectedSegmentTintColor then the image won't be visible in the selected segment. If you set the tintColor to the same color as backgroundColor, then the images on the unselected segments won't be visible. This means your segmented control with images must use 3 different colors for everything to be visible. Or you can use non-template images and not set the tintColor.
Under iOS 12 or earlier, simply set the segmented control's tintColor or rely on the app's overall tint color.

A:

As of Xcode 11 beta 3

There is now the selectedSegmentTintColor property on UISegmentedControl.

See rmaddy's answer

To get back iOS 12 appearance
I wasn't able to tint the color of the selected segment, hopefully it will be fixed in an upcoming beta.
Setting the background image of the selected state doesn't work without setting the background image of the normal state (which removes all the iOS 13 styling)
But I was able to get it back to the iOS 12 appearance (or near enough, I wasn't able to return the corner radius to its smaller size).
It's not ideal, but a bright white segmented control looks a bit out of place in our app.
(Didn't realise UIImage(color:) was an extension method in our codebase. But the code to implement it is around the web)
extension UISegmentedControl {
    /// Tint color doesn't have any effect on iOS 13.
    func ensureiOS12Style() {
        if #available(iOS 13, *) {
            let tintColorImage = UIImage(color: tintColor)
            // Must set the background image for normal to something (even clear) else the rest won't work
            setBackgroundImage(UIImage(color: backgroundColor ?? .clear), for: .normal, barMetrics: .default)
            setBackgroundImage(tintColorImage, for: .selected, barMetrics: .default)
            setBackgroundImage(UIImage(color: tintColor.withAlphaComponent(0.2)), for: .highlighted, barMetrics: .default)
            setBackgroundImage(tintColorImage, for: [.highlighted, .selected], barMetrics: .default)
            setTitleTextAttributes([.foregroundColor: tintColor, NSAttributedString.Key.font: UIFont.systemFont(ofSize: 13, weight: .regular)], for: .normal)
            setDividerImage(tintColorImage, forLeftSegmentState: .normal, rightSegmentState: .normal, barMetrics: .default)
            layer.borderWidth = 1
            layer.borderColor = tintColor.cgColor
        }
    }
}

A:

IOS 13 and Swift 5.0 (Xcode 11.0)Segment Control 100% Working

 if #available(iOS 13.0, *) {
      yoursegmentedControl.backgroundColor = UIColor.black
      yoursegmentedControl.layer.borderColor = UIColor.white.cgColor
      yoursegmentedControl.selectedSegmentTintColor = UIColor.white
      yoursegmentedControl.layer.borderWidth = 1

      let titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.white]
      yoursegmentedControl.setTitleTextAttributes(titleTextAttributes, for:.normal)

      let titleTextAttributes1 = [NSAttributedString.Key.foregroundColor: UIColor.black]
      yoursegmentedControl.setTitleTextAttributes(titleTextAttributes1, for:.selected)
  } else {
              // Fallback on earlier versions
}


Q:

Naming values conditionally in R

Quick question here regarding assigning names to values in a vector conditionally. I have a simple vector in R with nine values (average temperature) that I am looking to assign a character vector to based on whether a value is greater than or less than 65. If the value is less than 65, I would like to assign HDD to the value as a row name (or column name) and if the value is greater than 65, I would like to assign CDD to the value.
x <- c(44.3, 49.3, 52.5, 46.2, 35.19, 67.4, 79.4, 13.4, 54.3)

Here's what I've been attempting along with some variations of this code as well, but I haven't gotten anywhere. I've also attempted a few loops, but those are not my strong point (new coder).
 x.rownames <- ifelse(x<65,(row.names(x) = "HDD"),(row.names(x) = "CDD"))

I keep getting the error :
Error in `rownames<-`(x, value) :
  attempt to set 'rownames' on an object with no dimensions

Any ideas?
Thanks

A:

You're just getting a bit confused with your R syntax
names(x) <- ifelse(x<65,(names(x) = "HDD"),(names(x) = "CDD"))

X is a vector, not a DF, so it doesn't have row names. R does support named vectors, so you can set the names as names(x)


Q:

Scrollbar doesn't scroll widgets inside a frame which is inside a canvas

I have the canvas and the scrollbar are on the Tk.
I have a frame on the canvas.
I adding into this frame new frames with the widgets on it and I want to scroll these widgets.
The scrollbar doesn't scroll the widgets at all, and when I add widgets which go below the window than the scrollbar turn into gray and I can't use it at all.
I am new to tkinter and python. I just don't know yet what am I doing. I didn't try to make it with a class(Should I?). I tried to use the ttk, and looked around sites for a non class answers but none of them worked.
from tkinter import *
from tkinter.ttk import *
actor_number=0
global tk

def new_actor_button_command():
  global menu_frame
  global actor_number
  global canvas

  new_actor_frame=Frame(menu_frame,width=500,height=200)
  new_actor_frame.grid(row=1+actor_number,column=0,pady=20)
  actor_name_label=Label(new_actor_frame,text="Actor Name")
  new_actor_frame.place(relx=0.0, rely=0.0, anchor=CENTER)

  delete_actor_button=Button(new_actor_frame,text="Delete
                             Actor",command=delete_actor_button_command)
  new_actor_frame.grid(row=1+actor_number,column=1)

  actor_name_label.grid(row=2+actor_number,column=1)
  delete_actor_button.grid(row=2+actor_number,column=2)
  actor_number+=1
  canvas.update_idletasks()

  scrollbar.config(command=canvas.yview)
  canvas.configure(scrollregion=canvas.bbox("all"))

def make_new_actor():
  global canvas
  global menu_frame
  new_actor_button=Button(menu_frame,text="Add New
                          Actor",command=new_actor_button_command)
  new_actor_button.grid(row=0,column=0)

def new_command():
  global actor_number
  actor_number=0
  make_new_actor()
tk=Tk()

tk.geometry("1200x800")
menubar=Menu(tk)

filemenu=Menu(menubar,tearoff=0)
filemenu.config(font=("Verdana",16))
filemenu.add_command(label="New",font=("Verdana",16),command=new_command)
menubar.add_cascade(label="File", menu=filemenu)

global scrollbar
canvas=Canvas(tk,width=1000,height=1000)
scrollbar=Scrollbar(tk,orient="vertical",command = canvas.yview)

menu_frame=Frame(canvas,width=1000,height=1000)
canvas.create_window(0,0,window=menu_frame)

canvas.configure(yscrollcommand=scrollbar.set)
canvas.configure(scrollregion=canvas.bbox("all"))
canvas.place(relx=0.0, rely=0.0)
menu_frame.pack(side=LEFT,expand=True)
scrollbar.pack(side=RIGHT,fill=Y)
tk.config(menu=menubar)
tk.mainloop()

It should scroll the vidgets inside"menu_frame".

A:

Scrolling Canvas is not easy.
It scroll items (if you add enough items in menu_frame) but it may need other changes in new_actor_frame
from tkinter import *
from tkinter.ttk import *

def new_actor_button_command():
    new_actor_frame = Frame(menu_frame, width=500, height=200)
    new_actor_frame.grid(row=actor_number, column=0)

    actor_name_label = Label(new_actor_frame, text="Actor Name")
    actor_name_label.grid(row=0, column=1)

    delete_actor_button=Button(new_actor_frame,text="Delete Actor")#, command=delete_actor_button_command)
    delete_actor_button.grid(row=0, column=2)

def new_command():
    global actor_number

    actor_number += 1

    new_actor_button = Button(menu_frame, text="Add New Actor", command=new_actor_button_command)
    new_actor_button.grid(row=actor_number, column=0)

def update_canvas(event=None):
    canvas.configure(scrollregion=canvas.bbox("all"))

actor_number=0

tk = Tk()
tk.geometry("1200x800")

menubar = Menu(tk)
filemenu = Menu(menubar, tearoff=0)
filemenu.add_command(label="New", command=new_command)
menubar.add_cascade(label="File", menu=filemenu)
tk.config(menu=menubar)

canvas = Canvas(tk, background='white')#, width=1000, height=1000)
canvas.pack(side='left', fill='both', expand=True)

scrollbar = Scrollbar(tk, orient="vertical", command=canvas.yview)
scrollbar.pack(side='right', fill='y')

menu_frame = Frame(canvas)
canvas.create_window(0, 0, window=menu_frame, anchor='nw')

canvas.configure(yscrollcommand=scrollbar.set)
canvas.bind('<Configure>', update_canvas) # update when change size

tk.mainloop()


Q:

Laravel - Auth::check() returning false, but middleware auth not redirecting

So somehow i was managed to produce a situation where Auth::check() says that i'm not logged in, but middleware('auth') is still allowing acces to my class. The last thing i did was modify user data, but I did not log out, so im assuming Auth::check() is returning the wrong value. But why could it be so? My controller construct:
public function __construct()
{
    if(Auth::check()){
        print "yes";
    } else {
        print "no";
    };

    $this->middleware('auth');

}

public function index()
{
   print " index";
}

This prints out "no index". So Auth::check() return false, but index method is still raeched.

A:

The constructor is called before the middleware. Laravel allows you to provide controller middleware, so you push to the middleware stack from within a controllers constructor.
Any form of session interaction in the constructor of a controller will fail.


Q:

Selecting Items in JComboBox

I have two combo boxes with a list of distance units to convert from/to. Now, when I want to choose eg. "Centimeter" from the ComboBox From (distance)..., I really don't need to have "Centimeter" in ComboBox To (distance)..., because it doesn't make sense to convert from centimeter to centimeter.
So when "Centimeter" is selected in From (distance)... I want it to be removed in To (distance)... ComboBox. But, when I change my selection (say "Meter"), I want "Centimeter" to be back and "Meter" disappear etc.
I managed to remove the selected item in To (distance)... box, but don't know how to return it back when I change my selection. Besides, when I change selection, the code below just removes the corresponding item in To (distance)... ComboBox.
Please guide me to the correct solution. Here is the corresponding code. I can give you the whole code if you need. Thank you!
private String[] convertFromDistance = {"From (distance)...", "Centimeter", "Inch", "Kilometer", "Knot", "Meter", "Mile", "Millimeter", "Yard"};
private String[] convertToDistance = {"To (distance)...", "Centimeter", "Inch", "Kilometer","Knot", "Meter", "Mile", "Millimeter", "Yard"};
private JComboBox fromListDistance, toListDistance;

fromListDistance.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        String list = (String)fromListDistance.getSelectedItem();

        for (int i=0; i<convertToDistance.length; i++) {
            if (convertToDistance[i].equals(list)) {
                toListDistance.removeItem(convertToDistance[i]);
                //here should go the code for adding back the item if selection is changed
            }
        }
    }
});

    toListDistance = new JComboBox<String>(convertToDistance);

A:

first thing you i should do in your problem is to know what is the selected choice  from fromListDistance combo box ..
after that i have to refill the toListDistance combo box except for the choice that the user have selected ..
it's easy to do this with if statement
fromListDistance.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent evt) {
            //saving the selected choice
            String choise=fromListDistance.getSelectedItem().toString();

            //here we remove all items from the combo box
            toListDistance.removeAllItems();

            for (int i = 0; i < convertToDistance.length; i++) {
                String distance=convertToDistance[i];
                //compare the selected choice with the convertToDistance[i]
                if (choise.equals(distance)) {
                    continue;
                }
                toListDistance.addItem(distance);
            }
        }
    });


Q:

iCloud Drive says it's syncing Desktop & Documents but it's not ... why?

Upgraded to a new iMac because my 2011 won't take new OS's. Still runs like a champ tough. Migration generally went well from 10.13 to new iMac's 10.14 with one glaring exception, per the subject query. Decided to let it go, spend a day doing all the other manual migration and verification steps, and upgrade to 10.15 Catalina guessing it might fix it. Nope.
Googled my fanny off. Found the best info on this forum and an excellent posting from Jacob Ford. My symptoms are different. System Preferences and Finder all behave fine. I followed the reset permissions advice, etc to no avail. My iPhone, iPad and iCloud.com don't reflect my new iMac ... they're stuck in the past. I turned off iDevice and old iMac iCloud Drive Desktop and Documents syncing a couple days ago. Turned off new iMac Desktop and Documents syncing for 10 minutes or so today and then turned it back on. iMac still behaves fine but when I login to iCloud.com it says all is fine but ain't got the right files. And, System Prefs:Apple ID:Manage...:Other Documents shows very wrong size, consistent with iCloud.com
Is there a reset procedure to restart the sync down of iCloud documents on macOS?

A:

Ta Da: Followed Andrew Swift's advice found on another forum. First I confirmed that all other devices had iCloud Drive syncing disabled. Then I checked the CloudDocs folder mentioned below and noticed that it held a couple similar entries but looking through them gave me no insights other than some were dated prior to migration and some were current ... hmm! So, I went to Terminal and typed:
killall bird
cd ~/Library/Application\ Support
rm -rf CloudDocs

and then immediately hit restart. I then double checked my mission critical software was running fine (home automation and weather station reading/posting), checked iCloud Drive in the finder and, lo and behold, I saw the desktop file list updating before my vary eyes. And the status bar at the bottom said it was copying a crapload of files & GB to iCloud. I don't know how long it took but I went to bed after 8 hrs of uploading. Today I verified that iCloud.com and iDevices are all on the same wavelength. Alles ist Gut!


Q:

Play sound sample every tinter.text input

I need to play a typewriter key sample every tkinter.text input.
I came across the Playsound module but i dont know how to listen to the inputs.

A:

Thanks, I've come up with a very similar solution tho its really really laggy. Im basically writing a simple typewriter emulator so the key sound is reproduced for each typed letter.
import tkinter as tk
from PIL import Image, ImageTk
from playsound import playsound

def key(event):
    key = event.char
    playsound("C:/Users/Isma/key1.mp3")

win = tk.Tk()

frame = tk.Frame(win, width=300, height=400)
frame.grid(row=1, column=0)
text = tk.Text(frame)
text.grid(row=0,column=0)
text.bind('<Key>',lambda a : key(a))
image = Image.open("C:/Users/Isma/swintec1.jpg")
photo = ImageTk.PhotoImage(image)
label = tk.Label(frame,image=photo)
label.image = photo
label.grid(row=3,column=0)

win.mainloop()


Q:

Change font-size with jquery if screen size is mobile size

In my web page, I want to change font-size with jquery if screen-size is mobile size.
My code is as follow:

    Header

    Detail

As above code, I can't change the font-size. Where should i fix this. Any idea pls.

A:

Why don't use CSS?

@media only screen and (max-width: 600px) {
 #para_head{
  font-size: 12px;
 }
 #para_detail{
  font-size: 10px;
 }
}

  Para Head

  Para Detail

Have fun :)

A:

I would recommend using a CSS media query rather than jQuery.  You will require a lot of jQuery manipulation if your application is big, it will also be harder to maintain and most importantly it will be heavy on the DOM.
Responsive websites are much easier to achieve with CSS as shown below.
@media screen and (max-width: 600px) {
    #para_head {
       font-size: 12px;
    }
}

Demo (Resize the output pane)
https://jsfiddle.net/9351yv7j/
As an additional note I would use the kebab style casing for HTML elements, para-head rather than para_head.


Q:

How to immediately know if connection is lost with Socket.IO?

I'm working on a project that includes BeagleBoneBlack and web server written in NodeJs. The idea is that when Beaglebone detects something from enviroment sends it to web server, and if connection is lost for some reason BBB stores the log in it's own database.
So I use SocketIO, and I emit when BBB detects something. I use flag variable isConnected that I put on false on "disconnect" event, and if isConnected is false I'm not emiting to server, just writing in database.
Problem is that when computer, where server is running, goes to sleep (simulating lost connection), SocketIo needs sometimes more than a minute to detect that connection is lost, and emit disconnect event. Is there any way to get this info faster, because the program tries to send readings to server and can't, but it's not written in database.

A:

The client could perhaps emit myping every 5 seconds (or more often) and receive mypong from server confirming that the server is working.
...or the server can send the confirmation of receiving data and the client tries to resend data until it receives the confirmation.


Q:

Symfony [Semantical Error] 'id' is not defined

your learning Symfony neighbor here,
I am calling a method from my controller through Ajax on a select change.
I manage to get the data I send to the controller, but I'm struggling as I try to make a Select with the data I get, for some reason, no matter the existing column I decide to return, I get a "specifiedColumn is not defined" and I can't figure out why.
Here's my method :
public function getPricesAction(Request $request)
{

            $first = $request->request->get('first');
            $final = $request->request->get('final');

            $em = $this->getDoctrine()->getManager();

    //not too sure about stacking 2 setParameter here, guess there's a better way. But even if I just use one parameter, I still get the same error 'id is not defined'.
            $getPrice = $em->createQuery('SELECT id FROM CarsBundle:Travel t WHERE t.first = :tst and t.final = :tfi')->setParameter('tre', $first)->setParameter('tra', $final);
            $result = $getPrice->getResult();

            return new JsonResponse($result);

}

I am using Symfony 3.3
thanks for the help !

A:

$getPrice = $em->createQuery('SELECT id FROM CarsBundle:Travel t WHERE t.first = :tst and t.final = :tfi')->setParameter('tre', $first)->setParameter('tra', $final);

Should be:
$getPrice = $em->createQuery('SELECT id FROM CarsBundle:Travel t WHERE t.first = :tst and t.final = :tfi')->setParameter('tst', $first)->setParameter('tfi', $final);

You got the wrong parameter name


Q:

Virtualbox stops when start

When I start my VirtualBox on Ubuntu 13.10, it stops on "Starting virtual machine 0%"
I can't use my Virtual Box
I already to remove and install again, but the problem keep.

A:

I have experienced the same problem.
Upgraded from Ubuntu 13.04 to 13.10 and Virtual Box could not start any virtual machines anymore.
It displayed the "0 % dialog" as in the pic for a couple minutes, then switched to a "20 %" progressbar, and after that nothing happened.
CPU usage for VirtualBox is 2% or less.
The last two lines from the VBox.log are:
00:00:16.340506 Audio: Trying driver 'pulse'.
00:00:16.350789 Pulse: Audio input/output stopped!

Therefore I disabled the soundcard in the virtualmachine setup, and now VirtualBox will start virtual machines again.
Great!


Q:

knitr strange out of control behavior with figures

I get strange behavior with figures. In some chunks knitr generates two figures from a single plot function, and the figures generated from 'chunkname' are named 'chunkname1.pdf' and 'chunkname2.pdf'. Sometimes, the first one is just a blank figure of the same size as the second one, and sometimes it is a file which cannot be open. As a work around, I set the fig.keep='last' option. But now I would like to display two plots from a same chunk and setting fig.keep to its default value, knitr generates 3 PDF figure files with the first one a corrupted file (one which can not be open).
I have knitr version 1.2 (2013-04-10), R 3.0.0 64bit (r62697 2013-04-30) under Win7 64. Here are the settings I am using:
knit_hooks$set(par = function(before, options, envir) {
  if (before) par(mar = c(4, 4, .1, .1))
})

opts_knit$set(concordance=TRUE, self.contained=TRUE)

opts_chunk$set(fig.path="figSW/SW-", keep.source=FALSE,
   verbose=TRUE,  message=FALSE)

I have not been able to reproduce it with a simple example. However, trying to create such an example I discovered other strange results. In the example below, only plots 1, 2 and 10 are correctly displayed, while all other don't show up (the PDF files are not generated and consistently the \includegraphics are not generated in the .tex file.)
\documentclass[12pt,a4paper]{article}
 \begin{document}
Plot 1
<<test-t, echo=TRUE, results="asis", fig.width=10, fig.height=5>>=
x = c(1,2,3)
y = c(1,3,2)
plot(x,y)
@
Plot 2\\
<<test-tt, echo=FALSE, results="hide", fig.width=10, fig.height=5>>=
plot(x,y)
@
\newpage
Plot 3
<<test-s, echo=TRUE, results="asis", fig.width=10, fig.height=5>>=
x = c(1,2,3)
y = c(1,3,2)
plot(x,y)
@
Plot 4\\
<<test-ss, echo=FALSE, results="hide", fig.width=10, fig.height=5>>=
plot(x,y)
@
\newpage
Plot 5
<<test-r, echo=TRUE, results="asis", fig.width=10, fig.height=5>>=
x = c(1,2,3)
y = c(1,3,2)
plot(x,y)
@
Plot 6\\
<<test-rr, echo=FALSE, results="hide", fig.width=10, fig.height=5>>=
plot(x,y)
@
\newpage
Plot 7
<<test-v, echo=TRUE, results="asis", fig.width=10, fig.height=5>>=
x = c(1,2,3)
y = c(1,3,2)
plot(x,y)
@
Plot 8\\
<<test-vv, echo=FALSE, results="hide", fig.width=10, fig.height=5>>=
plot(x,y)
@
\newpage
Plot 9
<<test-u, echo=TRUE, results="asis", fig.width=10, fig.height=5>>=
x = c(1,2,3)
y = c(1,3,2)
plot(x,y)
@
Plot 10\\
<<test-uu, echo=FALSE, results="hide", fig.width=10, fig.height=5>>=
plot(x,y)
@
\end{document}

Even stranger, compiling the same file from within R-Studio, I get the expected result for plot 6 in addition to 1,2 and 10.

A:

I cannot reproduce the problem using your example and knitr 1.2 / R 3.0. I see all 10 plots as expected.
For the corrupted PDF figures, it seems to be a bug that has been fixed in the development version of knitr. You can try
install.packages('knitr', repos = 'http://www.rforge.net/', type = 'source')


Q:

Cannot implicitly convert type 'System.Collections.Generic.List' to 'string'

I have encountered an error around my variable addresslist.
Cannot implicitly convert type 'System.Collections.Generic.List<Object>' to 'string'

I've been trying to populate my model that has a nested List<Object> with a data from a CSV file but I've encountered this error.
Here is the code where I tried to populate my nested List<Object>
public class FundTransferMap : ClassMap<FundTransfer>
    {
        public FundTransferMap()
        {
            Map(m => m.senderRefId);
            Map(m => m.sender).ConvertUsing(row =>
            {
                var senderlist = new List<Sender>
            {
                new Sender { name = row.GetField("senderName"),
                    address = Map(m => m.sender).ConvertUsing(row1 =>
                    {
                      var addresslist = new List<Address>
                    {
                            new Address { line1 = row1.GetField("senderAddrLine1"),
                            line2 = row1.GetField("senderAddrLine2"),
                            city = row1.GetField("senderCity"),
                            province = row1.GetField("senderProvince") }
                    };
                        return addresslist;
                    })
                },
            };
                return senderlist;
            });

        }
    }

Here are my models
public class FundTransfer
    {
        public String senderRefId { get; set; }
        public List<Sender> sender { get; set; }
    }

public class Sender
    {
        public String name { get; set; }

        public List<Address> address { get; set; }

    }

 public class Address
    {
        public String line1 { get; set; }

        public String line2 { get; set; }

        public String city { get; set; }

        public String province { get; set; }
    }

A:

You only need to use the ConvertUsing once.
public class FundTransferMap : ClassMap<FundTransfer>
{
    public FundTransferMap()
    {
        Map(m => m.senderRefId);
        Map(m => m.sender).ConvertUsing(row =>
        {
            var senderlist = new List<Sender>
            {
                new Sender { name = row.GetField("senderName"),
                    address =  new List<Address>
                    {
                        new Address { line1 = row.GetField("senderAddrLine1"),
                        line2 = row.GetField("senderAddrLine2"),
                        city = row.GetField("senderCity"),
                        province = row.GetField("senderProvince") }
                    }
                },
            };
            return senderlist;
        });
    }
}


Q:

Can any correct logical reasoning in natural language sentences be translated into a formal mathematical proof?

Since natural languages (e.g. English) are prone to ambiguities and misunderstandings due to their constant evolving nature and lack of rigorous formalization, and given an arbitrary philosopher X who wants to show the validity of his argument, would it be possible for that philosopher to translate his argument into a formal, non-ambiguous mathematical proof written in some kind of formal mathematical language in order to convincingly and indisputably show everyone else his argument's correctness?

A:

What you describe is the general structure of a mathematical paper.  Words regarding the mathematical discovery are paired with precise mathematical notations to demonstrate correctness.  However, a general version of this is tricky.  If a philosopher says "Here's natural argument A and here's formal argument B.  As the author of both, I say they are intended to be the same" that's one thing.  However, if we try to say "here's a process that lets you turn the crank on A to produce B," we have to question whether the process works right.
Indeed, proofs by folk like Tarski showed very particular limits on processes like you describe.  It's very hard for a language to prove it's own semantics, and most of the languages we are interested in when talking about proofs are simply not capable of it.
Of course, there is a way to do this.  What defines a "correct logical reasoning in natural language?"  If the definition is "there exists a corresponding formal logical proof," then the answer to your question becomes yes!
You might be interested in looking at Attempo Controlled English (ACE).  ACE does the dual of what you seek.  It is a way to write precise formal logic in a format which native speakers of English can read as though it were natural English.  If you read it naturally, you get the right intuition.  If you read if formally, you get the right formal meaning.


Q:

Inner SELECT can't use `u.id` which is in outer SELECT

I have the following MySQL query:
SELECT
    COUNT(b.`id`) AS todayOverdue,
    DATE_FORMAT(t.`created_time`, "%Y%m%d") AS days
FROM
    `Bill` b
LEFT JOIN `Order` o ON b.`order_id` = o.`id`
LEFT JOIN `Trade` t ON o.`trade_id` = t.`id`
LEFT JOIN `User` u ON b.`user_id` = u.`id`
WHERE
b. `deadline` <= "' . $todayTime . '"
AND b. `deadline` >= "' . $todayDate . '"
AND b.`is_paid` = 0
AND (
    SELECT
        COUNT(b2.`id`)
    FROM
        `Bill` b2
    WHERE
        b2.`deadline` <= "' . $todayTime . '"
    AND b2.`user_id` = u.`id`
    AND b2.`is_paid` = 0
    OR (
        b2.`deadline` <= b2.`paid_time`
        AND b2.`is_paid` = 1
    )
) < 2
GROUP BY
    days

Why can't the inner SELECT use u.id which is in outer SELECT?

A:

The inner select is completely independent of the outer select. The u table is being joined in the outer select in ways that are unknown to the inner select.
When you have
AND b2.`user_id` = u.`id`

Which row in u is being compared to which row in b2? The server has no way of knowing, so you need to define a table u2 and join it in the inner select.


Q:

Is it possible to set up load balancing and failover simultaneously?

Suppose I have two ColdFusion servers(different machines) running the same application. Now I am bit confused between load balancing and failover techniques.
As per my knowledge,
FailOver Cluster: Two server will run the same application, But the second server will come into picture when the first server is down.
Load Balancing Cluster:  Two server will run the same application simultaneously and load will be divided between the two servers.
So in Load Balanced Cluster, if one sever fails then will it route all requests to second server ?
If YES , i think that's what failover cluster does. So what is the other benefit of failover cluster?
If NO, Can we achieve both Load balancing and HA mode simultaneously? If
yes what should be the ideal setup?

A:

Your answer marked YES is correct: in a load-balanced scenario, if one of the balanced servers goes down the balancer will stop sending requests to it, and pass them to other balanced pool servers instead.
The benefit of a simple failover cluster is for services that cannot easily be provided in a distributed manner but which you would really like not to have be unavailable (eg, NFS server, firewall).  That sort of HA is usually coupled with STONITH to make sure that the other node is really, properly dead before the secondary tries to take on the function.
That sort of single-server-at-a-time HA functionality is often used for the load balancer itself (rather than the servers in the balanced pool).


Q:

Manual feature engineering based on the output

So, I'm working on a ML model that would have as potential predictors : age , a code for his city , his social status ( married / single and so on ) , number of his children and the output signed which is binary ( 0 or 1 ). Thats the initial dataset I have.
My prediction would be based on those features to predict the value of signed for that person.
I already generated a prediction on unseen data. Upon validation of the results with the predicted result vs the real data , I have 25% accuracy. While cross-validation gives me 65% accuracy. So I thought : Over-fitting
Here is my question, I went back to the early stages of the whole process, and started creating new features. Example : Instead of the code for the city which makes no sense to have that as input to a ML model, I created classes based on the percentage of signed, the city ,with the higher percentage of 'signed' ( the ouput ) , gets assigned to a higher value of class_city, which improved a lot in my Correlation Matrix the relationship signed-class_city which makes sense. Is what I'm doing correct? or shouldn't I create features based on the ouput?
Here is my CM
:
After re-modelling with 3 features only ( department_class , age and situation ) i tested my model on unseen data made of 148 rows compared to 60k rows in the training file.
First model with the old feature ( the ID of the departement ) gave 25% accuracy while the second model with the new feature class_department gave 71% ( Again on unseen data )
Note : First model with 25% has some other features as ID's ( they might be causing the model to have such a weak accuracy with the deparment_ID )

A:

No you should not do this, it is causing a data leak. Data leaks happen when the data you are using to train a machine learning algorithm happens to have the information you are trying to predict.
It will give your model information about your test data during training. It will cause your test scores to be overly optimistic and will make the model worse at generalizing to totally unseen data.
Good resource on data leakage

A:

You can create features based on output values, but you should be careful in doing this.
When you use the value of class_city (based on percentage of signed for that city) for a given data point, note that this calculation cannot include the current data point, since you will not have the value of ‘signed’ during prediction.
One way to handle this is to split the total data you have into three parts - estimation, train, test. The estimation set is used only to estimate the class_city values for each city. These values can then be used in the train and test data. This way, you have the label values without your model doing anything ‘unfair’. For testing, you can infact use the data from estimation+train sets to estimate the class_city values for use in the test set. The same holds true for any unseen data. You can use the class_city values estimated from all the previous data points.
In the context of time series data, for example, the class_city value for any data point can potentially use information from all previous data points, and should not use any information from future data points!


Q:

http to https redirect using URL rewrite module in IIS 8.5

I am trying to set up redirect from http to https for my entire site by using URL rewrite module.
IIS version 8.5 .
However, after applying several different settings in web.config I faced following:
<rewrite>
        <rules>
            <clear />
            <rule name="Redirect to https" stopProcessing="true">
                <match url=".*" />
                <conditions>
                    <add input="{HTTP_X_FORWARDED_PROTO}" pattern="^http$" />
                    <add input="{HTTPS}" pattern="on" ignoreCase="true" />
                </conditions>
                <action type="Redirect" url="https://{HTTP_HOST}{REQUEST_URI}" redirectType="Permanent" />
            </rule>
        </rules>
    </rewrite>

-- the above one makes site working but without performing redirects
<rewrite>
<rules>
    <rule name="Redirect to http" enabled="true" patternSyntax="Wildcard" stopProcessing="true">
        <match url="*" negate="false" />
        <conditions logicalGrouping="MatchAny">
            <add input="{HTTPS}" pattern="off" />
        </conditions>
        <action type="Redirect" url="https://{HTTP_HOST}{REQUEST_URI}" redirectType="Found" />
    </rule>
</rules>

-- this one redirects too many times
<rewrite>
        <rules>
            <rule name="HTTP to HTTPS redirect" stopProcessing="true">
                <match url="(.*)" />
                <conditions>
                    <add input="{HTTPS}" pattern="off" ignoreCase="true" />
                </conditions>
                <action type="Redirect" url="https://{HTTP_HOST}/{R:1}"
                    redirectType="Permanent" />
            </rule>
        </rules>
        <outboundRules>
            <rule name="Add Strict-Transport-Security when HTTPS" enabled="true">
                <match serverVariable="RESPONSE_Strict_Transport_Security"
                    pattern=".*" />
                <conditions>
                    <add input="{HTTPS}" pattern="on" ignoreCase="true" />
                </conditions>
                <action type="Rewrite" value="max-age=31536000" />
            </rule>
        </outboundRules>
    </rewrite>

--results in error
 <rewrite>
        <rules>
            <rule name="http to https" stopProcessing="true">
                <match url="(.*)" />
                <conditions>
                    <add input="{HTTPS}" pattern="^OFF$" />
                </conditions>
                <action type="Redirect" url="https://www.something.net/{R:1}" redirectType="SeeOther" />
            </rule>
        </rules>
    </rewrite>

--does not work neither
Any ideas?
_____________After enabling FRT and implementing Jalpa's solution I got following - compact view (XML log is too big) -----
[![enter image description here][1]][1]
[![enter image description here][2]][2]
[![enter image description here][3]][3]
------------- Complete request trace - interesting parts -----
[![enter image description here][4]][4]
[![enter image description here][5]][5]
[![enter image description here][6]][6]
It is worth mentioning that http and https versions of the same URLs are working fine when requested directly. If I apply redirect part in config, both versions indicate : too many redirects error.

A:

For all the others facing the similar problem - check the load balancer rules.


Q:

Interface. Join areas is not working properly

I made a mess with areas trying to merge them into 2. Is there a way to remove areas without aiming at the corner and then dragging them with LMB?

A:

Just right click on the border and select Join Areas.
Then you can choose which way to merge them.


Q:

iPhone rings once and phone is open to caller

My iPhone rings once and the caller is there. How do I make it ring until I answer it?
I’ve tried looking for a solution in settings.

A:

There is an "Auto-Answer Calls" setting in:
Settings > General > Accessibility > Call Audio Routing
Navigate there and turn it off if it is enabled.


Q:

Since all frames of reference are equal, can we treat the Earth as fixed?

Since Einsteins GR tells us all the frames of reference are equal, is there anything invalid about treating the Earth as unmoving and the universe itself rotating?
Other than the fact that the mathematical model is much more complex, is there anything that is wrong with it?

A:

It's an oversimplification to say that GR treats all frames if reference as equal. In particular if we take any frame (strictly speaking any coordinate system) we can calculate the proper acceleration of an observer at rest in the frame and the result will be zero or non-zero depending on the frame. If the proper acceleration is zero then the frame we have chosen is locally equivalent to an inertial frame, while if the proper acceleration is non-zero the frame is locally equivalent to a non-inertial frame.
So for example if we take the frame of an observer at rest on the surface of the Earth this frame is locally non-inertial. That means freely moving objects won't move in straight lines i.e. if you throw a stone it will move in a curve (approximately a parabola) and a pendulum will rotate its plane of swing by $2\pi$ every $24$ hours. From a Newtonian perspective there will be fictitious forces acting.
Even in Newtonian mechanics there's nothing wrong with using non-inertial frames. They are just (as you say) more complicated to do calculations in. Likewise in GR there's absolutely no problem in choosing a frame corotating with the Earth, but it will make any attempts to do calculations more complicated than they need be. For example in this frame the flat spacetime metric:
$$ ds^2 = -c^2dt^2 + dx^2 + dy^2 + dz^2 $$
becomes:
$$ ds^2~=~\Big(1~-~\frac{r^2\Omega^2}{c^2}\Big)dt^2~-~r^2d\theta^2~-~2r^2\frac{\Omega}{c} d\theta dt~-~dr^2 $$


Q:

How can I make Solr follow links while parsing a "Solr XML" file to index the results?

There is a web-accessible file system of thousands and thousands of PDF files that I need to be indexed by Solr (with Lucidworks).
I have an XML file containing data corresponding to each. The XML contains the ID, some simple metadata, and the URL of its corresponding PDF in the file system.
Currently, I am able to format the XML in such a way that Solr reads it and indexes all the metadata I need, including the URL of the PDF.
I would like Solr to, as it's parsing the files, actually follow the URL and index the referenced PDF data along with the XML-supplied metadata. Is this possible?

A:

Your best bet (on pure Solr), would probably be a DataImportHandler with nested entities.
The external processor would be XPathEntityProcessor and within that, you can put TikaEntityProcessor with appropriate data source. Use the variables to construct/pass URL to the inner entity.
Remember to mark the outer (XPath) entity as rootEntity=false to ensure that Solr documents are created for the inner entities.


Q:

Regex to find a repeating pattern in a string

Here is a sample string that I am working with:
- - - some text followed by more - - followed by more - -
I need to find each occurrence of a - at the beginning of the line and replace with another character. So, if a - is to be replaced by ~, the final outcome will be
~ ~ ~ some text followed by more - - followed by more - -
I have tried (-).?, which selects all the -. If I put a ^ to indicate beginning of line, I get just the 1st '-'. If I give the pattern as ^((-)\s){3}, which selects the group, but then the group could be any number of - in the beginning, so - - some text is valid and - some text is valid and - - - - some text is valid

A:

There are several ways: match any 0+ non-word chars other than - ([^\w-]*) from the start or from the end of the previous match (\G) and capture them (with (...)), then match - and replace with a backreference to the first capturing group ($1) with a replacement char (~):
var res = Regex.Replace(s, @"\G([^\w-]*)-", "$1~");

See the regex demo.
Or, match all 1 or more non-word chars (\W+) at the start of the string (^) and replace the - with ~ only there:
var res = Regex.Replace(s, @"^\W+", m => m.Value.Replace("-","~"));

See the C# demo:
var s = "- - - some text followed by more - - followed by more - - ";
var res = Regex.Replace(s, @"^\W+", m => m.Value.Replace("-", "~"));
Console.WriteLine(res);
// => ~ ~ ~ some text followed by more - - followed by more - -

Alternatively, you may leverage the variable width lookbehind:
(?<=^\W*)-

Replace with ~. See this regex demo. The (?<=^\W*) lookbehind will only make the - match if it is preceded with 0+ non-word chars from the start of the string.


Q:

Testing Loss won't improve when doing Binary Classification using Keras

I have a dataset with 65 features and 2 labels and want to perform binary classification.
The problem is the testing loss wont improve nor will the testing accuracy.

Training Loss vs Testing Loss

Training Accuracy vs Testing Accuracy

Code
model = Sequential()
model = Sequential()
model.add(Dense(10, activation='relu', input_dim=n_features))
model.add(Dropout(0.5))
model.add(Dense(2, activation='softmax'))
model.compile(loss='binary_crossentropy', optimizer='adam',metrics=['acc'])

The dataset is highly imbalanced (1:30)
How can I improve my model?

A:

Softmax and binary cross-entropy are not the right match, to use softmax correctly you should use the categorical_crossentropy loss. If you want to keep using a binary cross-entropy you should use a sigmoid activation at the output, with a single neuron (not two).


Q:

Can you explicitly ask the Lua compiler to inline? What about the LuaJIT?

Is there a keyword or some other functionality in the standard Lua compiler that allows you to explicitly inline? What about the LuaJIT?

A:

There is no function inlining in vanilla Lua interpreter. Some tools exist to inline the code on a source level, but that's not what you're asking.
LuaJIT does some inlining while generating the native code, but that can't be controlled from outside, there's no explicit 'inline' keyword. And there's limits on what could be inlined. I.e. the call to native code using FFI library will be inlined, but the calls to functions registered via classic Lua/C interface can't be.


Q:

.change() with multiple fields fires for each changed field out of focus

How can I get .change() with the multiple selector (“selector1, selector2, selectorN”) to fire once all of the fields are out of focus, instead of each time one of the changed fields becomes out of focus?
thanks!

A:

You need the change event and the blur event.
In the below example, all fields will turn red on blur of one of them, if there is none of them beeing focussed and if at least one of them as changed.

var inputChanged = false;

$(".test").on("change", function(){
  inputChanged = true;
});

$(".test").on("blur", function(){
  var flag=true;

  setTimeout(function(){

    // Check if one input is focussed 10 ms after that blur.
    $(".test").each(function(){
      if( $(this).is(":focus") ){
        flag = false;
      }
    });

    // If no input focussed and at least one input changed.
    if(flag && inputChanged){
      $(".test").css({"background-color":"red"});
    }
  },10);
});

<input class="test">

<input class="test">

<input class="test">