text:
Q: avoiding raising of page numbers with scrlayer-scrpage We have been using scrpage2 and now switched to scrlayer-scrpage this caused the page number to raise by about 2mm.

Is there a way to avoid this?
\documentclass{scrbook}

%\usepackage{scrlayer-scrpage}
\usepackage{scrpage2}

\usepackage{showframe}

\begin{document}
\chapter{Language acquisition}

~
\newpage

\noindent
that the acquisition of complex predicate formation is connected to the acquisition of compound
structures and that there is a parameter that is responsible for this type of compounding and
simultaneously for the following set of phenomena:
Snyder examined languages from various language groups: Afroasiatic, Austroasiatic, Austronesian,
Finno-Ugric, Indo-European (Germanic, Romance, Slavic), Japanese-Ko\-rean, Niger-Kordofanian
(Bantu), and Sino-Tibetan, as well as American Sign Language and the language isolate Basque. The
languages that were examined either had all of these phenomena or none. This was tested with native
speakers of the respective languages. In addition the claim that these phenomena are acquired once
noun-noun compounds are used productively was tested for English using CHILDES data. The result
was positive with the exception of the double object construction, for which an explanation was
provided. The correlation of the phenomena in (1) is interesting and was interpreted as proof of the
existence of a parameter that correlates several phenomena in a language. However, Son (2007) and
Son \& Svenonius (2008) showed that Snyder's claims for Japanese were wrong and that there are
further languages like Korean, Hebrew, Czech, Malayalam, Javanese in which some of the phenomena
show no correlations.

Gibson \& Wexler (1994) discuss the acquisition of constituent order and assume three parameters
that concern the position of the verb relative to the subject (SV vs. VS) and relative to the object
(VO vs. OV) as well as the V2-property. There is no consensus in the literature about which
parameters determine the make-up of languages (see Newmeyer 2005: Section 3.2 and Haspelmath 2008
for an overview and critical discussion). Fodor (1998a: 346–347) assumes that there are 20 to 30
parameters, Gibson \& Wexler (1994: 408) mention the number 40, Baker (2003: 349) talks of 10 to 20
and Roberts \& Holmberg (2005: 541) of 50 to 100. There is no consensus in the literature as to
which parameters one should assume, how they interact and what they predict. However, it is
nevertheless possible to contemplate how a grammar of an individual language could be derived from a
UG with parameters that need to be set. Chomsky's original idea (1986b: Section 3.5.1) was that the
child sets the value of a parameter based on the language input as soon as the relevant evidence is
present from the input (see also Gibson \& Wexler 1994; Nowak, Komarova \& Niyogi 2001). At a given
point in time, the learner has a grammar with certain parameter settings that correspond to the
input seen so far. In order to fully acquire a grammar, all parameters must be assigned a value. In
theory, thirty utterances should be enough to acquire a grammar with thirty parameters if these
utterances provide unambiguous evidence for a particular parameter value.

This approach has often been criticized. If setting a parameter leads to a learner using a different
grammar, one would expect sudden changes in linguistic behavior. This is, however, not the case (Bloom 1993: 731). Fodor (1998a: 343–344) also notes the following three problems: 1) Parameters can affect things that are not visible from the perceptible constituent order. 2) Many sentences are ambiguous with regard to the setting of a particular parameter, that is, there are sometimes multiple combinations of parameters compatible with one utterance. Therefore, the respective utterances cannot be used to set any parameters (Berwick \& Niyogi 1996; Fodor 1998b). 3) There is a problem with the interaction of parameters. Normally multiple parameters play a role in an utterance such that it can be difficult to determine which parameter contributes what and thus how the values should be determined.

\end{document}

Edit: I am sorry, the description was misleading. The package option mentioned in one solution affects the bottom line and the page number, but it does not change the behavior that I would like to change. The page number gets closer to the text with scrbook + footlines=1 + srclayer-srcpage:

scrbook+scrpage2:

A: With a KOMA-Script class and only normal size page numbers in footer, you could use \documentclass[footlines=1]{scrbook} or \KOMAoptions{footlines=1}\recalctypearea or \KOMAoptions{footheight=\baselineskip}\recalctypearea. But each of these versions will change \footskip to 2.25\baselineskip+\footheight. So you have to reset \footskip to 3.5\baselineskip after each recalculation of the typearea.
Example:
\documentclass{scrbook}
\KOMAoptions{footheight=\baselineskip}
\AfterCalculatingTypearea{\setlength{\footskip}{3.5\baselineskip}}
\recalctypearea

\usepackage{scrlayer-scrpage}

\usepackage{showframe}% to show the page layout
\usepackage{lipsum}% only for dummy text
\begin{document}
\chapter{Language acquisition}
\lipsum[1-20]
\end{document}

A: I didn't find a way to fix this within scrlayer-scrpage, but with fancyhdr you can work around this.
It might not be the most elegant solution but it solves your problem. Just add this to the preamble (after \usepackage{scrlayer-scrpage}):
\usepackage{fancyhdr}
\pagestyle{fancy}
\fancyfoot{} %delete footer
\fancyfoot[RO,LE]{\thepage} %reset footer


text:
Q: Pandas setting entries for selected values in column A in another column B I am looking for an elegant way to make the following query:
# Given
original_df = pd.DataFrame({'A':[1,3,5],'B':[2,4,6]})
A_values_where = [1,3]
B_values_setTo = [10,11]

# Wished output
target_df = pd.DataFrame({'A':[1,3,5],'B':[10,11,6]})

Should be self-explanatory, but to be precise: Wherever a value in 'A' of 'A_values_where' is found set column 'B' in the same row to the value in 'B_values_setTo'. Most importantly, the values in 'Three' shall not be touched.

A: Use Series.map by dictionary created from lists for always correct matching by values in both lists (also working if sublist match):
d = dict(zip(A_values_where, B_values_setTo))

original_df['B'] = original_df['A'].map(d).fillna(original_df['B'])
print (original_df)
   A     B
0  1  10.0
1  3  11.0
2  5   6.0

If order is always same is possible use this alternative, but failed in general data, so first solution is prefered:
original_df.loc[original_df['A'].isin(A_values_where), 'B'] = B_values_setTo

redpajama_set_name: RedPajamaStackExchange


text:
Q: create a list filled with elements, length depends on given number say I have a function which takes in a number e.g def function(number), I want to create a list filled with None's, and the length of the list is the number so say number = 4, list = [None, None, None, None]
is this possible?

A: You can do it in a few different ways.
Best way:
number = 2
list1 = [None]*number

For Loop:
number = 2
list1 = []
for _ in range(number):
    list1.append(None)

List Comprehension:
number = 2
list1 = [None for _ in range(number)]


text:
Q: Incompatible pointer type function I am trying to learn C to develop my skills in programming and I am trying to make an algorithm which could change the uppercase letter to lowercase letter and lowercase letter to uppercase letter.In simple algorithm I have written this code but an error occurs on it,my question is the compiler says "operand types are incompatible".What does it mean?I called my length as a pointer function to store a memory in the address to enter the console random characters.Error occurs in i is smaller than length in for loop part.I am looking forward to learn new things from your replys."int" and "int(*)char *s") it says
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <conio.h>

int length(char *s)
{
    int i = 0;
    int counter = 0;
    while (s[i] != NULL)
    {
        i++;
        counter++;
    }
    return counter;
}

void upperlower(char *s)
{
    int i;
    for (i = 0; i<length; i++)
    {
        if (s[i] >= 65 && s[i] <= 90)
            s[i] += 32;
        else if (s[i] >= 97 && s[i] <= 122)
            s[i] -= 32;
    }
}

int main()
{
    printf("Please write down the character string: ");
    scanf("%s", upperlower);
    printf("The character string is %s", upperlower);
    getch();
    return 0;
}

A: You seem to be confused about how to call a function.
When you do this:
for (i = 0; i<length; i++)

You are not calling the length function.  You are using the name of the function in an expression, so what you have instead is a function pointer.  You need to add the function call operand () along with the parameter to be passed in:
for (i = 0; i<length(s); i++)

Similarly in the main function, you are not actually calling upperlower.  Also, you never define a character array to receive the string you want to read.  Include that array as a local variable, pass it to scanf to get a string from the user, then pass it to the function.
char str[50];
printf("Please write down the character string: ");
scanf("%49s", str);
upperlower(str);
printf("The character string is %s", str);

A: scanf("%s", upperlower); expects a void* type (char* in this case) and you're providing a function pointer void (*)(char*), which cannot be cast to void*, hence the error.
If you're learning, C is not the easiest language to start with, especially starting with pointers. Think about memory layout and it will start to make more sense.

A: In the for loop of the upperlower function, you compare make the comparison i<length. i is an int variable and length is a function that you declared earlier.
When you reference here, it refers to a pointer to that points to the function itself, it does not provide the result of the function.
Instead, try changing i<length to i<length(s), this way, length return a result that can be compared to an int.
The same could be said for the scanf in the main function. Here you should declare an array to store the string and then pass that to the functions:`
char str[32];
scanf("%s", str);
upperlower(str)
printf("The character string is %s", str);
getch();

A: You're doing some mistakes in your code like:

*

*comparing character to a null pointer s[i] != NULL, maybe you meant \0

*Passing function name instead of string on line 33. You're supposed to print converted string.

*Not allocating the memory for the string passing function in scanf Line 31 :
scanf("%s", upperlower);

*Comparing i which an integer to a function pointer, Line 20: for (i = 0; i<length; i++) maybe you mean i < length(s)
Apart from these i changed main like this:
  char aStr[1000];
  printf("Please write down the character string: ");
  scanf("%s", aStr);
  upperlower(aStr);
  printf("The character string is %s", aStr);
  return 0;

On running it i was able to see the desired output:
~/Documents/src : $ gcc testType.c
~/Documents/src : $ ./a.out
Please write down the character string: Rohan
The character string is rOHAN


text:
Q: Is SQLAgentUserRole required to view msdb.dbo tables? I often check the status of jobs to gain information about schedules, run status, run times, etc. via query against msdb.dbo tables in team environments as a part of ETL validation. I am curious if permissions can be granted to a universal login utilized by devs in non-isolated environments, such as Merge or QA where multiple teams are accessing, leading up to but not including Prod to allow viewing of msdb.dbo tables?
Currently, the said universal dev login does not have sufficient privileges and must rely on DBA's to report this information as requested, consuming their time and effort. I do not believe this is the same as granting SQLAgentUserRole, but could be mistaken. Is this request overreaching / stepping on DBA toes?
My query for reference: (using JDBC via SoapUI requires higher verbosity)

SELECT
    [sysjobs].[name] AS [job_name],
    [sysjobhistory].[run_date] AS [run_date],
    [sysjobhistory].[run_time] AS [run_time],
    [sysjobhistory].[run_status] AS [run_status]
FROM [msdb].[dbo].[sysjobs] INNER JOIN [msdb].[dbo].[sysjobhistory]
ON [sysjobs].[job_id] = [sysjobhistory].[job_id]
WHERE [sysjobs].[enabled] = 1 -- only enabled jobs
ORDER BY [run_date], [run_time] DESC
Thank you for your time.

A: The SQLAgentUserRole comes with a lot more rights than just read on the two tables in your query, you can view these rights on the securables tab in the properties for the role.  If you want to get access to just the two msdb tables in your query then you would create another database role with only those rights and then add your SQL/AD credentials to the instance with that role in msdb.


text:
Q: React Data Grid fails at src/DataGrid.tsx:268 throwing a : TypeError: rows is undefined I am using the example code provided on the React Data Grid website at https://adazzle.github.io/react-data-grid/docs/examples/simple-grid without any changes :
import React from "react";
import ReactDOM from "react-dom";
import ReactDataGrid from "react-data-grid";
import "./styles.css";

const columns = [
 { key: "id", name: "ID", editable: true },
 { key: "title", name: "Title", editable: true },
 { key: "complete", name: "Complete", editable: true }
];

const rows = [
 { id: 0, title: "Task 1", complete: 20 },
 { id: 1, title: "Task 2", complete: 40 },
 { id: 2, title: "Task 3", complete: 60 }
];

class Example extends React.Component {
 state = { rows };

onGridRowsUpdated = ({ fromRow, toRow, updated }) => {
this.setState(state => {
  const rows = state.rows.slice();
  for (let i = fromRow; i <= toRow; i++) {
    rows[i] = { ...rows[i], ...updated };
  }
  return { rows };
 });
 };
render() {
 return (
  <ReactDataGrid
    columns={columns}
    rowGetter={i => this.state.rows[i]}
    rowsCount={3}
    onGridRowsUpdated={this.onGridRowsUpdated}
    enableCellSelect={true}
  />
);
}
}

const rootElement = document.getElementById("root");
ReactDOM.render(<Example />, rootElement);

but got a type error back from React Data Grid. What I am doing wrongly ?

A: I ran into the same error (TypeError: rows is undefined) trying to use react-data-grid for the first time. The problem is that version 7.0.0-canary.14 was published on npmjs.com recently and all the documentation and examples on the react-data-grid website are for version 6.
According to the changelog (https://github.com/adazzle/react-data-grid/blob/HEAD/CHANGELOG.md) version 7 has a very different interface which doesn't appear to be documented anywhere at the moment. It also appears to be a canary version and is probably not ready for production use. Frankly, being in the process of evaluating this component, the way this breaking change was published makes me reconsider using this for anything serious.
In the meantime, if you want to use the examples or current documentation you can install an earlier version with
npm install react-data-grid@^6.0.0

or
yarn add react-data-grid@^6.0.0

Update: There are some examples of the version 7 api usage in the .tsx (not .js) files at https://github.com/adazzle/react-data-grid/tree/canary/stories/demos .


text:
Q: Vertically center RibbonComboBox in RibbonGroup (in WPF) I would like know whether there is a possibility to vertically center a RibbonComboBox in a RibbonGroup without setting a margin.
I tried to use VerticalAlignment and VerticalContentAlignment, but unfortunately this did not work.
This is how it looks right now:

This is how it should look like (please without using margin-settings):

This is my code at the moment:
<RibbonTab Name="RibbonTab_Test" Header="Test">
   <RibbonGroup Name="RibbonGroup_Test" Header="New Test">
       <RibbonComboBox Name="RibbonComboBox_Test" IsEditable="False" SmallImageSource="img/verschreibungspflichtige-pillendose-16.png">
           <RibbonGallery SelectedValue="This Test-Text is to long" SelectedValuePath="Content" MaxColumnCount="1">
               <RibbonGalleryCategory>
                  <RibbonGalleryItem Content="This Test-Text is to long"/>
                  <RibbonGalleryItem Content="Test 1"/>
                  <RibbonGalleryItem Content="Test 2"/>
               </RibbonGalleryCategory>
            </RibbonGallery>
        </RibbonComboBox>
    </RibbonGroup>
</RibbonTab>

Thank you for your help!

A: One way to achieve this is by adding a grid with a very big height and setting vertical alignment to center:
<RibbonGroup Name="RibbonGroup_Test" Header="New Test">
    <Grid VerticalAlignment="Center" MinHeight="120">
        <Grid.RowDefinitions>
            <RowDefinition Height="*"></RowDefinition>
        </Grid.RowDefinitions>
        <RibbonComboBox Name="RibbonComboBox_Test" IsEditable="False" VerticalAlignment="Center" SmallImageSource="img/verschreibungspflichtige-pillendose-16.png">
            <RibbonGallery SelectedValue="This Test-Text is to long" SelectedValuePath="Content" MaxColumnCount="1" >
                <RibbonGalleryCategory>
                    <RibbonGalleryItem Content="This Test-Text is to long"/>
                    <RibbonGalleryItem Content="Test 1"/>
                    <RibbonGalleryItem Content="Test 2"/>
                </RibbonGalleryCategory>
            </RibbonGallery>
        </RibbonComboBox>
    </Grid>
</RibbonGroup>


text:
Q: losing context with replace In QooxDoo I have a problem with this code
html2plain : function (html) {
     html = html.replace(/<(S*?)[^>]*>.*?|<.*?\/>/g,  function( tag )
     {
          return this.pushHashtag(tag.toUpperCase());
      } );
      return( html );
 },

when it comes to the line
return this.pushHashtag(tag.toUpperCase());

there is no context for the variable this and the function pushHashtag becomes unavailable.

A: One way to solve that, is by binding 'this' to the function.
To do that, you need to change the anonymous function as following (you should send this function to the replace method):
function(tag) {
  return this.pushHashtag(tag.toUpperCase());
}.bind(this)

and now, inside this function, 'this' will refer to the "right" 'this'


text:
Q: Hibernate, one-to-many association with composite key I would like to ask you just a little confirmation about how I am currently mapping my objects in a database through Hibernate. Here is the problem statement:

I have two entities, User and Message. A User can be associated to many Messages
  A User is uniquely identified by the username. So primary key is the username.
  A Message is uniquely identified by the username of the user associated and by another field, rxTime. So in this case it is a composite key (username, rxTime)

Here is how i am currently mapping this via XML
<hibernate-mapping package="my.package">
    <class name="User" table="USERS">
        <id name="username" column="USERNAME_ID"> </id>
        <set name="messages" table="MESSAGES"
                inverse="true" lazy="false" fetch="select">
            <key>
                <column name="USERNAME_ID" not-null="true" />
            </key>
            <one-to-many class="Message" />
        </set>
    </class>

</hibernate-mapping>

<hibernate-mapping package="my.package">
    <class name="Message" table="MESSAGES">
        <composite-id >
            <key-many-to-one name="user" class="User" column="USERNAME_ID"/>
            <key-property name="startRxTime" column="startRxTime"/>
        </composite-id>

    </class>
</hibernate-mapping>

Questions:
- Am I doing it right? I am new to hibernate and I am not sure that this is the right way to do one-to-many associations.
- I am encountering some performance issues when querying the DB. When I try to get a list of messages order by RxTime i see that many queries are generated by hibernate to obtain the result. This will be the next thing to investigate but i am afraid that the way i am mapping the objects is leading to this inefficiency. Is it right?
I am aware that this looks like a trivial database design but on the web I've found a lot of different ways to do it and it is not clear for me which is the best one.
Thanks a lot for your eventual asnwers.
Cheers


text:
Q: Django TemplateDoesNotExist I deployed my website on the server  Ubuntu 16.04.3 x64
I don't know the main template list.html it doesn't work other templates are working normally.
templates
I checked the  access permissions files They are the same
Permissions
Settings looks like this
"""
Django settings for INZ project.

Generated by 'django-admin startproject' using Django 1.10.4.

For more information on this file, see
https://docs.djangoproject.com/en/1.10/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.10/ref/settings/
"""

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '#wx61%!ioz(yba#e=t7jh-*&(!l#kri=^y%ik(x4m3j8oix+hq'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = ['46.101.116.26']
EMAIL_HOST ='smtp.gmail.com'
EMAIL_HOST_USER ='luke.rudzinski@gmail.com'
EMAIL_HOST_PASSWORD = '#####'
EMAIL_PORT = 587
EMAIL_USE_TLS = True

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'games'
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'INZ.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'INZ.wsgi.application'

# Database
# https://docs.djangoproject.com/en/1.10/ref/settings/#databases

On localhost everythings is fine . I have Windows 8.1 maybe it the reason of my issue , because on win there is different file structure

A: Unlike Windows, your file system on Linux is case sensitive. Rename your file from List.html to list.html to match your code.


text:
Q: Connected callback is not being called while creating custom html elements I was trying to create a custom tag in HTML using JavaScript. I want to create the custom element using ES6 JavaScript syntax. I have written this code to create the custom element:

customElements.define('neo-element', NeoElement);
function NeoElement (){
    var ref =  Reflect.construct(HTMLElement,[], this.constructor) ;
    return ref;
};
NeoElement.prototype = Object.create(HTMLElement.prototype);
NeoElement.prototype.constructor = NeoElement;
NeoElement.prototype.connectedCallback = function(){
    this.innerHTML = `<h1>Hello world</h1>`;
};
<neo-element></neo-element>

I have verified that NeoElement is extending HTMLElement properly, but still nothing is getting printed inside the <neo-element> tag.
Could anyone look at the code and tell me what am I missing in ES5 syntax ?

A: It's not working because you're calling customElements.define—and thereby upgrading your <neo-element> to an instance of NeoElement—before you've defined NeoElement.prototype, NeoElement.prototype.constructor, and NeoElement.prototype.connectedCallback.
If you move customElements.define to the end it works fine:

function NeoElement() {
    var ref = Reflect.construct(HTMLElement,[], this.constructor) ;
    return ref;
};
NeoElement.prototype = Object.create(HTMLElement.prototype);
NeoElement.prototype.constructor = NeoElement;
NeoElement.prototype.connectedCallback = function(){
    this.innerHTML = `<h1>Hello world</h1>`;
};
customElements.define('neo-element', NeoElement);
<neo-element></neo-element>


text:
Q: Validating input in NSOpenPanel accessory view I would like to solicit additional information from the user during the NSOpenPanel but need to validate that information before the open panel completes. For example, I may want to allow the user to add a note about the file in the open panel selection but need to validate that that comment is not empty.
I have an accessory view whose controls are bound to an NSObjectController whose content object in turn is bound to the represented object of the NSViewController that I use to load the accessory view's nib. The represented object has NSKeyValueCoding-compliant validation methods (e.g. -(BOOL)validateKey:error:). Validation is correctly handled (and violations reported via modal dialog) when the user modifies the values of the controls.
My problem is that I can't figure out how to get validation if the user doesn't enter anything in the accessory view. For example, say I have a single text field in the accessory view whose bound object validates that the text is non-zero in length. If the user enters text (validation succeeds), then deletes the text, validation fails and the user is presented with the error. However, if the user doesn't enter text, the open panel dismisses without error. How can I validate that the text is non-zero before the open panel dismisses?

A: You should register your controller as the open panel's delegate and then implement the -panel:isValidFilename: delegate method. Returning NO from that method allows you to prevent the open dialog from being closed:
- (BOOL)panel:(id)sender isValidFilename:(NSString *)filename
{
    //validate the field in some way, in this case by making sure it's not empty
    if([[textField stringValue] length] == 0)
    {
        //let the user know they need to do something
        NSAlert *alert = [[NSAlert alloc] init];
        [alert setMessageText:@"Please enter some text."];
        [alert addButtonWithTitle:@"OK"];
        [alert beginSheetModalForWindow:sender modalDelegate:nil didEndSelector:NULL contextInfo:NULL];
        //return NO to prevent the open panel from completing
        return NO;
    }
    //otherwise, allow the open panel to close
    return YES;
}


text:
Q: How to append a new row in a dataframe by searching for an existing column value without iterating? I'm trying to find the best way to create new rows for every 1 row when a certain value is contained in a column.
Example Dataframe

Index
Person
Drink_Order

1
Sam
Jack and Coke

2
John
Coke

3
Steve
Dr. Pepper

I'd like to search the DataFrame for Jack and Coke, remove it and add 2 new records as Jack and Coke are 2 different drink sources.

Index
Person
Drink_Order

2
John
Coke

3
Steve
Dr. Pepper

4
Sam
Jack Daniels

5
Sam
Coke

Example Code that I want to replace as my understanding is you should never modify rows you are iterating
for index, row in df.loc[df['Drink_Order'].str.contains('Jack and Coke')].iterrows():
    df.loc[len(df)]=[row['Person'],'Jack Daniels']
    df.loc[len(df)]=[row['Person'],'Coke']

df = df[df['Drink_Order']!= 'Jack and Coke']

A: Split using and. That will result in a list. Explode list to get each element in a list appear as an individual row. Then conditionally rename Jack to Jack Daniels
 df= df.assign(Drink_Order=df['Drink_Order'].str.split('and')).explode('Drink_Order')
df['Drink_Order']=np.where(df['Drink_Order'].str.contains('Jack'),'Jack Daniels',df['Drink_Order'])

    Index Person   Drink_Order
0      1    Sam  Jack Daniels
0      1    Sam          Coke
1      2   John          Coke
2      3  Steve    Dr. Pepper


text:
Q: Refresh slide master view I'm updating the data of a table on powerpoint 2010 slide (msotable type of shape) from a database. I'm using chart.Refresh to refresh successfully the slide master containing the charts (msochart). I want to do the same for tables types of shapes. But there is no refresh method for tables and my slide master view stays not refreshed (updated) after the successfull update on main slide view.
I'm using C# 4.0 interop for office 2010.
Any idea how to refresh table slide master view?
http://office.microsoft.com/en-001/powerpoint-help/what-is-a-slide-master-HA010280572.aspx

A: Found a solution. When  there is no method for refresh, I do a hack:
 sh.Width = sh.Width + 1;
 sh.Width = sh.Width - 1;
   public void UpdateTable(Shape sh, System.Data.DataTable dt)
    {
        try
        {
            //Supprimer toutes les lignes existantes
            if (sh.Table.Rows.Count >= 3)
            {
                int rowCount = sh.Table.Rows.Count;
                for (int i = 3; i <= rowCount; i++)
                {
                    sh.Table.Rows[sh.Table.Rows.Count].Delete();
                }

                //Vider le contenu de la première ligne
                for (int j = 1; j < sh.Table.Columns.Count; j++)
                {
                    sh.Table.Cell(2, j).Shape.TextFrame.TextRange.Text = "";
                }
            }

            //Parcourir les lignes
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                sh.Table.Rows.Add(sh.Table.Rows.Count);
                //Parcourir les colonnes
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    sh.Table.Cell(i + 2, j + 1).Shape.TextFrame.TextRange.Text = dt.Rows[i][j].ToString();
                }
            }
            sh.Table.Rows[sh.Table.Rows.Count].Delete();

            sh.Width = sh.Width + 1;
            sh.Width = sh.Width - 1;

            Marshal.ReleaseComObject(sh);
        }
        catch (Exception exp)
        {
            Logger.Error(exp);
        }

    }


text:
Q: Terribly slow SQL query with COUNT and GROUP BY on two columns I'm archiving this web forum, which normally gets purged about once a week. So I'm screen scraping it, and storing it into my database (PostgreSQL).
I also do a little analysis on the data, with some graphs for users to enjoy, like what time of day is the forum most active, and so forth.
So I have a posts table, like so:
   Column   |            Type
------------+------------------------------
 id         | integer
 body       | text
 created_at | timestamp without time zone
 topic_id   | integer
 user_name  | text
 user_id    | integer

And I now want to have a post count for each user, for my little top 10 posters table.
I came up with this:
SELECT user_id, user_name, count(*)
FROM posts
GROUP BY user_id, user_name
ORDER BY count DESC LIMIT 10

Which turns out to be very slow. 9 seconds, with just about 300 000 rows in the posts table at the moment.
It takes only half a second, if I group on just one column, but I need both.
I'm rather new to relational databases, and SQL, so I'm not quite sure if this is right, or just how am I doing it wrong?

A: There's probably only one user with a particular ID, so max(user_name) should equal user_name.   Then you can group on a single column, which your post indicates works faster:
SELECT user_id, max(user_name), count(*)
FROM posts
GROUP BY user_id

A: also could use having count > 0 so you only return true


text:
Q: USB powered off after boot with Power Mac G4 and Lubuntu I have a Power Mac G4 that I'm trying to boot off of a USB drive, I can get it to load the kernel and ramdisk just fine, and it opens the display, but it shuts down the USB after loading kernel and ramdisk, preventing the kernel from checking the disk.
It says something like "Write not complete -28 != (some large number)"
And then it panics.
Are there any solutions to this?


text:
Q: "Assignment to read-only properties is not allowed in strict mode" error in IE11 when exporting text values to .csv, Chrome browser is working fine "Assignment to read-only properties is not allowed in strict mode" error in IE11 when exporting text values to .csv, Chrome browser is working fine with same code.
Below is my code:
    define('mybiz.framework.csvsave',
         ['jquery', 'mybiz.framework.loggingservice', 'saveAs'], function ($,
         JL,    saveAs) {
         'use strict';
         var logger = JL('mybiz.framework.csvsave');
         var generate = function (doc) {
         logger.info("about to save CSV document");
         var startTime = new Date();
         try {
         var textEncoder = new TextEncoder('utf-16le');
         var csvContentEncoded = textEncoder.encode([doc]);
         var bom = new Uint8Array([0xFF, 0xFE]);
         var out = new Uint8Array(bom.byteLength            +csvContentEncoded.byteLength);
            out.set(bom, 0);
            out.set(csvContentEncoded, bom.byteLength);

            var csvBlob = new Blob([out], {type: 'text/csv'});
            saveAs(csvBlob, "los.csv");
        } catch (e) {
            logger.error("Error generating CSV: " + e.message + "\n" + e.stack);
        }
        var stopTime = new Date();
        logger.info("CSV generation completed in: " + (stopTime - startTime) + "ms");
    };
    return {
        generate: generate
    };
});

This below code is calling above function:
    self.saveExportCSV = function (data, event) {
                var columns = getColumnsToExport(self.columnsForExport());
                self.exportCSV({'columns': columns, 'generator':
csvsave.generate, event: event});
            };


text:
Q: How to make a screen-record guiding video for iOS device I'm creating an iOS app on recording screen by using ReplayKit.
I want to make a user operation video to guide user on how to use my app to record screen.
So I need to record a video on how to record screen and this approach is a bit awkward.
I tried several ways: Screen Mirroring such as AirPlayer and QuickTime, but the recording button on control-center is disabled whilst using Screen Mirroring.
The effect I want is as follows:
https://support.apple.com/library/content/dam/edam/applecare/images/en_US/iOS/ios13-iphone-xs-control-center-screen-record-animation.gif
How was this video made?

A: I think you could recreate that video by recording your screen showing every action you want, save the video and edit it on top of an iPhone image asset.


text:
Q: Disable soft Input keyboard for searchview I am showing a custom made keyboard for a searchview and suppress the default soft input keyboard. It works well except when I try to pull the navigation drawer and release it, the default soft input keyboard is shown. How do I disable the default soft keyboard for an actionbar searchview or maybe a particular activity? So far I have tried the following without success

*

*Setting Activity's WindowSoftInputMode to StateAlwaysHidden

*Setting the SearchView's input type to NULL

*Get the underlying EditText behind the SearchView and added an OnTouchListenerand Hide the default soft keyboard with InputMethodManager
Note: I am using Mono Android and I can understand Java code so please don't hesitate to give any Java solutions.

A: /**
 * Toggle keyboard If the keyboard is visible,then hidden it,if it's
 * invisible,then show it
 *
 * @param context
 */
public static void toggleKeyboard(Context context) {
    InputMethodManager imm = (InputMethodManager) context
            .getSystemService(Context.INPUT_METHOD_SERVICE);
    if (imm.isActive()) {
        imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT,
                InputMethodManager.HIDE_NOT_ALWAYS);
    }
}

/**
 * Hide keyboard
 *
 * @param context
 */
public static void hideKeyboard(Context context,IBinder token) {
    InputMethodManager imm = (InputMethodManager) context
            .getSystemService(Context.INPUT_METHOD_SERVICE);
    if(imm.isActive()){
        imm.hideSoftInputFromWindow(token,0);
    }
}


text:
Q: Wiremock matchesJSONPath if null or empty I'm trying to add a Wiremock stub that matches if the JSON in a request body is either non-existent OR an empty string.
The stub I have at the moment is:
{
    "id" : "e331007e-3e6d-4660-b575-b04e774e88c6",
    "request" : {
      "urlPathPattern" : "/premises/([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/bookings/([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/non-arrivals",
      "method" : "POST",
      "bodyPatterns" : [ {
        "matchesJsonPath" : "$.[?(@.reason === '' || @.reason == null)]"
      } ]
    },
    "response" : {
      "status" : 400,
      "jsonBody" : {
        "type" : "https://example.net/validation-error",
        "title" : "Invalid request parameters",
        "code" : 400,
        "invalid-params" : [ {
          "propertyName" : "reason",
          "errorType" : "blank"
        } ]
      },
      "headers" : {
        "Content-Type" : "application/problem+json;charset=UTF-8"
      }
    },
    "uuid" : "e331007e-3e6d-4660-b575-b04e774e88c6"
  }

It matches is the reason is '', but not if reason is not present. Any ideas?


text:
Q: Default profile picture from Facebook is being displayed, instead of Facebook picture if a user joined before Stack using Facebook API v2+ Facebook changed how their API serves profile pictures that are requested with a non-application scope UID.
Now because before Graph API 2 all applications shared the original UID, if users like me has joined Stack Exchange websites before Graph API 2, rolling out their profile pictures are not shown properly.
Facebook suggests to use an access token to query those profile pictures, either an application access token or a user access token.
A user access token is not a reliable option at all, because it would only work for users who joined website with Facebook and are currently logged in.
Application access tokens, by the way, can be used by creating sort of a proxy that would retrieve a profile picture from Facebook and display it. Yet still it's not perfect.
I think the best solution is to communicate with Facebook and ask them to offer an opportunity to convert old Graph API 1 UID's to application scope user IDs.

A: Adding status-deferred for now. While this is a confirmed issue, there isn't a clear path forward to resolve this, given the feasibility of working with Facebook on a problem like this. I've added this to our backlog to revisit in the future.


text:
Q: Java: Receipt Printer auto cutting I am using the Java Print Service API to print to a receipt printer. It prints fine, but does not auto cut when finished. How to tell the printer to auto cut?
Here's the code I'm using to print:
       String defaultPrinter =
                  PrintServiceLookup.lookupDefaultPrintService().getName();
                System.out.println("Default printer: " + defaultPrinter);
                PrintService service = PrintServiceLookup.lookupDefaultPrintService();

                InputStream is=null;
                try {
                    printString+="\f";
                    System.out.println(printString);
                    is = new ByteArrayInputStream(printString.getBytes("UTF8"));
                } catch (UnsupportedEncodingException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }

                PrintRequestAttributeSet  pras = new HashPrintRequestAttributeSet();
                pras.add(new Copies(1));

                DocFlavor flavor = DocFlavor.INPUT_STREAM.AUTOSENSE;

                Doc doc = new SimpleDoc(is, flavor, null);

                DocPrintJob job = service.createPrintJob();

                PrintJobWatcher pjw = new PrintJobWatcher(job);
                try {
                    job.print(doc, pras);
                } catch (PrintException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                pjw.waitForDone();
                try {
                    is.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

A: I would imagine there's a proprietary command (in the form of a byte sequence) you need to send to the printer to cut it.
For the TSP100, this page seems to allude to 27, 100 and 3 being the bytes that you need.
Whatever the model, when you've found the command in the form of a sequence of bytes, you should be able to send it using a similar approach to above:
DocPrintJob job = PrintServiceLookup.lookupDefaultPrintService().createPrintJob();
byte[] bytes = {27, 100, 3};
DocFlavor flavor = DocFlavor.BYTE_ARRAY.AUTOSENSE;
Doc doc = new SimpleDoc(bytes, flavor, null);
job.print(doc, null);


text:
Q: What does "well defined composition" mean for a catagory with a congruence? Let $C$ be a category with congruence ~, and let $[f]$ denote the
equivalence class of a morphism $f$. Define $C'$ as follows:
$$obj C' = obj C$$
$$Hom_{C'} = \{[f] : f \in Hom_{C}(A,B)\}$$
$$[g] \circ [f] = [g \circ f]$$
The book states that this property from the definition of congruence:
$f$ ~ $f'$ and $g$ ~ $g'$ and $g \circ f$ exists imply that $g \circ f$ ~ $g' \circ f'$, shows that composition in $C'$ is well defined.
What does it mean for composition of morphisms to be well defined?

A: For quotients in general, a function $f : X/{\sim}\to Y$ is well-defined if it doesn't distinguish between representatives of equivalence classes.  That is, if if $x \sim y$ then $f(x)=f(y)$.  If $Y$ itself is a quotient, i.e. $Y = Z/{\approx}$, then $f(x) = f(y)$ means $[z]=f(x)$ and $[z']=f(y)$ and so $[z]=[z']$ which means $z \approx z'$.
So working entirely at the level of representatives, a function $g : A/{\sim} \to B/{\approx}$ is a function $\bar g : A \to B$ such that $\forall a,a'\in A.a\sim a' \implies f(a)\approx f(a')$.
In this case, it's composition as a (family of) function(s) $$\circ : (\text{Hom}(B,C)/{\sim})\times(\text{Hom}(A,B)/{\sim})\to\text{Hom}(A,C)/{\sim}$$ which has an underlying function $$\bar\circ : \text{Hom}(B,C)\times\text{Hom}(A,B)\to\text{Hom}(A,C)$$ which must satisfy the rules you laid out.


text:
Q: EVP_DigestUpdate and "invalid conversion from 'unsigned char*' to 'const char*'" Here's the example taken from EVP Message Digests on the OpenSSL wiki:
void digest_message(unsigned char *message, unsigned char **digest, unsigned int *digest_len)
{
    EVP_MD_CTX *mdctx;

    if((mdctx = EVP_MD_CTX_create()) == NULL)
        handleErrors();

    if(1 != EVP_DigestInit_ex(mdctx, EVP_sha256(), NULL))
        handleErrors();

    if(1 != EVP_DigestUpdate(mdctx, message, strlen(message)))
        handleErrors();

    if((*digest = (unsigned char *)OPENSSL_malloc(EVP_MD_size(EVP_sha256()))) == NULL)
        handleErrors();

    if(1 != EVP_DigestFinal_ex(mdctx, *digest, digest_len))
        handleErrors();

    EVP_MD_CTX_destroy(mdctx);
}

The problem is when I try to compile it I get the following error:
evp_test.cpp:18:60: error: invalid conversion from 'unsigned char*' to 'const char*' [-fpermissive]
 if(1 != EVP_DigestUpdate(mdctx, message, strlen(message)))

In file included from /usr/include/c++/5/cstring:42:0

So strlen being called on message causes the error because strlen expects a const char? Is this because strings are arrays of const chars?
What should I be doing differently to solve the issue?

A: It has been fixed:
void digest_message(const unsigned char *message, size_t message_len,
                    unsigned char **digest, unsigned int *digest_len)
{
    EVP_MD_CTX *mdctx;

    if((mdctx = EVP_MD_CTX_create()) == NULL)
        handleErrors();

    if(1 != EVP_DigestInit_ex(mdctx, EVP_sha256(), NULL))
        handleErrors();

    if(1 != EVP_DigestUpdate(mdctx, message, message_len))
        handleErrors();

    if((*digest = (unsigned char *)OPENSSL_malloc(EVP_MD_size(EVP_sha256()))) == NULL)
        handleErrors();

    if(1 != EVP_DigestFinal_ex(mdctx, *digest, digest_len))
        handleErrors();

    EVP_MD_CTX_destroy(mdctx);
}

You were right that strlen needs an array of char, and not an unsigned char or byte.
The bigger problem was the design/engineering. An explicit length parameter was needed because there's no guarantee a byte array is NULL terminated like a C-string. In fact, a byte array might have a few NULLs embedded in it.


text:
Q: Swagger-UI Maximum call stack size exceeded -> Backreference When calling my swagger.json from the swagger-ui I get an error:

Maximum call stack size exceeded

I guess it is because I have
Token which has an owner of Type User
User which has a Token of Type Token
When using the online-version of the swagger editior it can resolve the types. How can I configure swagger to resolve the types correctly?
The full swagger.json
{
    "swagger": "2.0",
    "info": {
        "description": "Descr",
        "version": "1.0.0",
        "title": "Skeleton"
    },
    "host": "1.1.1.1:11",
    "basePath": "/api",
    "tags": [{
            "name": "auth"
        }
    ],
    "schemes": ["http"],
    "paths": {
        "/auth/local": {
            "post": {
                "tags": ["auth"],
                "summary": "Authenticates User",
                "description": "This auths only local users",
                "operationId": "authenticateUser",
                "consumes": ["application/json"],
                "produces": ["application/json"],
                "parameters": [{
                        "in": "body",
                        "name": "body",
                        "required": false,
                        "schema": {
                            "$ref": "#/definitions/Credentials"
                        }
                    }
                ],
                "responses": {
                    "200": {
                        "description": "successful operation",
                        "schema": {
                            "$ref": "#/definitions/AuthResponse"
                        }
                    }
                }
            }
        },
        "/auth/ldap": {
            "post": {
                "tags": ["auth"],
                "operationId": "authenticateLdapUser",
                "produces": ["application/json"],
                "parameters": [{
                        "in": "body",
                        "name": "body",
                        "required": false,
                        "schema": {
                            "$ref": "#/definitions/Credentials"
                        }
                    }
                ],
                "responses": {
                    "default": {
                        "description": "successful operation"
                    }
                }
            }
        }
    },
    "definitions": {
        "AuthResponse": {
            "type": "object",
            "properties": {
                "issued": {
                    "type": "string",
                    "format": "date-time"
                },
                "responseType": {
                    "type": "string",
                    "enum": ["RESPONSE", "ERROR", "UNAUTHORIZED", "OK"]
                },
                "responseDescription": {
                    "type": "string"
                },
                "accessToken": {
                    "$ref": "#/definitions/Token"
                },
                "resourceName": {
                    "type": "string"
                }
            }
        },
        "Note": {
            "type": "object",
            "properties": {
                "id": {
                    "type": "integer",
                    "format": "int32"
                },
                "content": {
                    "type": "string"
                },
                "modified": {
                    "type": "string",
                    "format": "date-time"
                }
            }
        },
        "Token": {
            "type": "object",
            "properties": {
                "id": {
                    "type": "string"
                },
                "expirationDate": {
                    "type": "string",
                    "format": "date-time"
                },
                "issued": {
                    "type": "string",
                    "format": "date-time"
                },
                "expired": {
                    "type": "boolean"
                },
                "owner": {
                    "$ref": "#/definitions/User"
                }
            }
        },
        "User": {
            "type": "object",
            "properties": {
                "username": {
                    "type": "string"
                },
                "password": {
                    "type": "string"
                },
                "email": {
                    "type": "string"
                },
                "displayName": {
                    "type": "string"
                },
                "notes": {
                    "type": "array",
                    "items": {
                        "$ref": "#/definitions/Note"
                    }
                },
                "accessToken": {
                    "$ref": "#/definitions/Token"
                }
            }
        },
        "Credentials": {
            "type": "object",
            "properties": {
                "user": {
                    "type": "string"
                },
                "password": {
                    "type": "string"
                }
            }
        }
    }
}

A: I have the same problem and I removed format: date-time and the error is gone.
Still I don't know what causes the error. But without that format everything goes ok.

A: In FastAPI which uses Swagger UI, I was receiving the same error. I updated the FastAPI package to get the last version of Swagger UI and then set the value of 'syntaxHighlight' to False, like below:
app = FastAPI(swagger_ui_parameters={'syntaxHighlight': False})

Just search how you can set this param directly in Swagger UI. This may fix your issue.


text:
Q: how to exclude image files within public folder In the public folder, I have two folder hk and sg, they have different image files.
What I want is if I build hk package, I only copy images from hk folder.
How to exclude the sg folder in ember-cli?

A: Ember uses Broccoli.js for it's build pipeline. Broccoli is build around the concept of trees. Please have a look in it's documentation for details.
You could exclude files from the tree using a plugin called broccoli-funnel. It expects an input node, which could be either a directory name as a string or an existing broccoli tree as a first argument. A configuration object should be provided as a second argument. The files or folders that should be excluded could be specified by exclude option on that object.
A broccoli tree is created as part of the build process in ember-cli-build.js. The function exported from that file should return a tree. By default it returns the tree created by app.toTree() directly. But you could customize that tree using broccoli-funnel before.
This diff shows how default ember-cli-build.js as provided by blueprint of Ember CLI 3.16.0 could be customized to exclude a specific file:
diff --git a/ember-cli-build.js b/ember-cli-build.js
index d690a25..9d072b4 100644
--- a/ember-cli-build.js
+++ b/ember-cli-build.js
@@ -1,6 +1,7 @@
 'use strict';

 const EmberApp = require('ember-cli/lib/broccoli/ember-app');
+const Funnel = require('broccoli-funnel');

 module.exports = function(defaults) {
   let app = new EmberApp(defaults, {
@@ -20,5 +21,7 @@ module.exports = function(defaults) {
   // please specify an object with the list of modules as keys
   // along with the exports of each module as its value.

-  return app.toTree();
+  return new Funnel(app.toTree(), {
+    exclude: ['file-to-exclude'],
+  });
 };

You should explicitly add broccoli-funnel to your dependencies even so it's available as a indirect dependency:
// if using npm
npm install -D broccoli-funnel

// if using yarn
yarn add -D broccoli-funnel

Broccoli-funnel does not only support exact file names but also regular expressions, glob strings or functions to define the files to exclude. Please have a look in it's documentation for details.


text:
Q: axios and vuex are deleting wrong index in array hello i have an problem by laravel and vuejs my problem is that when i try to delete a post from posts in my store file it always delete firs object of array but in database it delete the correct row
here is my store file
state:
    {
        posts:[]

    },
getters:
    {
        posts:state=>
        {
            return state.posts
        }
    },
mutations:
    {
        AllPosts:(state,payload)=>{
            state.posts=payload;
        },
        DeletePost:(state,payload)=>{
            state.posts.splice(payload,1);
        }
    },
actions:
    {
        AllPosts:({commit},payload)=>{
            commit("AllPosts",payload)
        },
        DeletePost:({commit},payload)=>{
            commit("DeletePost",payload)
        }
    }

and this is my destroy function in postcontroller
public function destroy($id)
    {
        $post=Post::find($id);
        $post->delete();
        return response()->json($post,200);
    }

and this is my axios
deletepost(id)
                {
                    axios.delete("/admin/posts/delete/"+id)
                        .then(res=>
                        {
                            this.$store.dispatch("DeletePost",res.data)
                            console.log(res.data)
                        })
                },

and this is the html part of code

                {{post.id}}
                {{post.category}}
                <td v-if="post.title.length<30">{{post.title}}
                {{ post.title.substring(0,30)+"..." }}

                <td v-if="post.shortly.length<30">{{post.shortly}}
                {{ post.shortly.substring(0,30)+"..." }}

                {{post.created_at}}
                <button class="delete-btn" @click.prevent="deletepost(post.id)">delete</button>
                <button class="edit-btn" @click.prevent="editpost(post.id)">edit</button>

what should i do to delete the correct obeject of array?

A: From the DeletePost mutation:
state.posts.splice(payload,1);

The first argument for splice is an index. You can't just pass it the object you want to remove.
You could write it something like this:
const index = state.posts.findIndex(post => post.id === payload.id);

if (index !== -1) {
    state.posts.splice(index, 1);
}

Or perhaps use filter instead:
state.posts = state.posts.filter(post => post.id !== payload.id);

I'd also consider passing the id directly to the mutation as the payload rather than passing the whole post object.


text:
Q: Co Record Verification I have a task requiring some awk to verify a few records quickly.
Let' say:
A1,A2
B1,B2
C1,C2
C2,C1
A1,C1
A1,B1
B1,A1

Which would be the best way to check for reciprocity only between the A# the B# and the C# and output only the non reciprocal. For instance: the above should output
A2 -> A1
B2 -> B1

A# belong to one group, B# to another and so on. There's no interest in findind any sort of conexion between A# and C# or B#. Instead it is required to keep the search within the group of As, Bs, Cs and so on.

A: As far as I got it the following rules lead to your desired output:

*

*A1,A2: same letter (i.e. "group") --> looking for A2,A1: not found --> print A2,A1

*B1,B2: same letter (i.e. "group") --> looking for B2,B1: not found --> print B2,B1

*C1,C2: same letter (i.e. "group") --> looking for C2,C1: found --> don't print

*C2,C1: same letter (i.e. "group") --> looking for C1,C2: found --> don't print

*A1,C1 : different letters (i.e. "groups") --> don't print

*A1,B1 : different letters (i.e. "groups") --> don't print

*B1,A1 : different letters (i.e. "groups") --> don't print

So if there was A1,A3 in the list, it should be printed, too:

*

*A1,A3: same letter (i.e. "group") --> looking for A3,A1: not found --> print A3,A1
Given I understood that right, you could do something like the following:
awk -F, '

  # skip records that do not consist of exactly two different fields
  (NF!=2)||($1==$2){
    next
  }

  # get groups
  {
     g1=substr($1,1,1) # If the groups are not defined as the first...
     g2=substr($2,1,1) # ...character, adjust theses line accordingly.
  }

  # only consider records with matching groups
  g1!=g2{
    next
  }

  # are we looking for the current record?
  ($2 in fst2scd)&&(fst2scd[$2]~FS""$1""FS){

    # remove "reciprocal" pair from the list (assuming record uniqueness -->...
    sub(FS""$1""FS,FS,fst2scd[$2]) # ...consider piping through sort -u first)

    # was that the last record ending with $2 we were looking for (so far)?
    if(fst2scd[$2]==FS){

      # remove $2 from the list (for now)
      delete fst2scd[$2]
    }

    # this "reciprocal" pair is done
    next
  }

  # if we reach this point, we found a new pair
  {

    # is this the first non-"reciprocal" record starting with $1?
    if(!($1 in fst2scd)){

      # add $1 to the list
      fst2scd[$1]=FS
    }

    # start looking for a "reciprocal" record
    fst2scd[$1]=fst2scd[$1]""$2""FS
  }

  # after processing all records, we know all non-"reciprocal" records
  END{

    # use the same separator for output that was used in input
    OFS=FS

    # iterate over all starts of records we are still looking for
    for(fst in fst2scd){

      # remove initial and final FS from list entry
      sub("^"FS,"",fst2scd[fst])
      sub(FS"$","",fst2scd[fst])

      # get all ends of records with the current start we are still looking for
      split(fst2scd[fst],scd,FS)

      # iterate over all the ends obtained in the previous step
      for(i in scd){

        # print the non-"reciprocal" records
        print fst,scd[i]
      }
    }
  }
' <<_INPUT_
A1,A2
B1,B2
C1,C2
C2,C1
A1,C1
A1,B1
B1,A1
A1,A3
A1,A1
_INPUT_

wich results in the following output:
A1,A2
A1,A3
B1,B2

Note the usage of FS throughout the script to allow the same code to run on e.g. a TSV file that might contain , in an entry.
In case you need further help to understand how this code works and/or improvements/adjustments, feel free to comment.
Also note, that I assumed you have GNU awk (i.e. gawk) running.
If this is not the case, I could help you adjusting the code to run in plain awk.

A: An alternative in Perl; assuming the same interpretation of your question as sg-lecram's :
perl -lne 'tr{ }{}d;      # Remove whitespace in current line
           $lines{$_}++;  # Record the current line in a hash
           END{           # After all lines have been processed
               for(keys %lines){   # Iterate over hash keys
                 #Skip records with different letters:
                 next unless /([a-z]).*\1/i;
                 ($first,$second)=split /,/; #Read the two fields
                 #Print the record unless its reciprocal is found:
                 print unless exists $lines{"$second,$first"};
           }' your_file


text:
Q: Hover a div with NgClass I am trying to make a hover effect on a div with a Angular ngClass directive. In the template file I have a div element with class "list-item-container' which contains a div with class "list-item" that is iterated with a *ngFor directive. Inside the "list-item" div element I have three divs with class "list-item-column" which are placed horizontally like a table row with inline display. in the div with "list-item" class I have placed a mouseenter and mouseleave event listeners which calls hoverListItem() in my .ts file.  the hoverListItem() function changes the value of listItemHovered variable to true or false. In the "list-item" class I have a ngClass directive which triggers a css class 'list-item-highlight' based on the value of listItemHovered boolean value which then changes to background to a different color.
The problem I'm facing is that upon hovering mouse pointer on the "list-item" div all my "list-item" divs are affected instead of the one I am hovering over. How to solve this problem?
.html file

      <ng-container *ngFor="let opportunity of dealService.opportunities">

{{opportunity.account?.name === null ? "N/A" : opportunity.account.name}}

{{opportunity.requirementTitle}}

{{opportunity.salesValue | number: '1.0-2'}}

      </ng-container>

.css file
.list-item-container{
  overflow: auto;
  width: 100%;
  max-height: 500px;
}
.list-item{
  font-size: 15px;
  border-radius: 10px ;
  margin-top: 5px;
  height: 50px;
  background: lightgray;
  color: black;
}

.list-item-highlight{
  background: #7e00cc;
  color: white;
}

.list-item-column{
  height: inherit;
  vertical-align: center;
  display: inline-block;
  width: 33.33%;
  padding-left: 40px;
}

.ts file
 hoverListItem() {
    this.listItemHovered = !this.listItemHovered;
  }

A: Right now you're creating and modifying listItemHovered flag inside component context, rather you should maintain a flag for each item level, which could help to easily identify wheather component has been highlighted or not.
[ngClass]="{'list-item-highlight': opportunity.listItemHovered}"
(mouseenter)="hoverListItem(opportunity)"
(mouseleave)="hoverListItem(opportunity)"

Component
hoverListItem(opportunity) {
   opportunity.listItemHovered = !opportunity.listItemHovered;
}

Though I'd recommend to use :hover pseudo class if requirement is just to highlight the element on hover. That can be easily doable by changing CSS rule. This way could save several change detection cycle to be ran.
.list-item:hover {
  background: #7e00cc;
  color: white;
}

A: I would suggest use a directive to listen to the hover event on the target element and attach the class:
@Directive({
    selector: '[hoverDir]'
})

 export class HoverOverDirective {
    @HostListener('mouseenter') onMouseEnter() {
       this.elementRef.nativeElement.class = 'list-item-highlight';
    }

     @HostListener('mouseleave') onMouseLeave() {
       this.elementRef.nativeElement.class = 'list-item-not-highlight';
     }
}

Or the easiest way is to make use of CSS pseudo property :hover and use it as below:
.list-item:hover {
  background: #7e00cc;
  color: white;
}


text:
Q: How to avoid instant saving of the model with ajax validation? I want to add Ajax validation to check the form before updating. In the view, added to the required field
['enableAjaxValidation' => true]

In the controller in the actionUpdate
if (Yii::$app->request->isAjax && $modelForm->load(Yii::$app->request->post())) {
            Yii::$app->response->format = Response::FORMAT_JSON;
            if ($modelForm->validate()) {
                $model->setAttributes($modelForm->getAttributes());

                if ($model->save()) {
                    return $this->redirect([my way]);
                }

                if ($model->hasErrors()) {
                    return ActiveForm::validate($model);
                } else {
                    return ['success' => 1, 'html' =>
                        $this->renderPartial('view', [my data];
                }
            } else {
                return ActiveForm::validate($modelForm);
            }
        }

The problem is that the choice of any value in the field, which is "enableAjaxValidation" => true, immediately leads to the saving of the model (even without pressing the save button). How can this be avoided?

A: In controller try it like this:
$model = new ExampleForm;

// validate any AJAX requests fired off by the form
if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
    Yii::$app->response->format = Response::FORMAT_JSON;
    return ActiveForm::validate($model);
}

Add this before your if statement, and remove Yii::$app->request->isAjax from your if statement.

A: Add some thing like below in your form
$form = ActiveForm::begin([
            'id' => 'example',
            'action' => ['your_action'],
            'validateOnSubmit' => true,
            'enableAjaxValidation' => true,
        ])


text:
Q: Calling external user control by its name I have  one panel (Panel1), two combo boxes (ComboBox1, ComboBox2) and one  button (Button1) all in same form (Form1).
When the button is clicked:
Private Sub Button1_Click(sender As Object, e As EventArgs)
   Dim a as String = ComboBox1.SelectedValue() & Combobox2.SelectedValue()
   AddUserControl(a)
End Sub

value of a is the name of an external user control for instance p1k1.
Can I add an external user control named p1k1 to Panel1 in Form1 using following method?
Private Sub AddUserControl(ByVal a As String)
    Panel1.Controls.Add(a)
End Sub

What should I do to make this work?
Usually I would use:
Panel1.Controls.Add(new p1k1)

A: You'll need to use reflection to do this.  Something like this:
    Private Sub AddUserControl(ByVal a As String)
        Dim controlType As Type = Type.GetType(a)
        If controlType Is Nothing Then
            Throw New ArgumentException(String.Format("""{0}"" is not a valid type.  Type names are case sensitive.", a))
        ElseIf Not controlType.IsSubclassOf(GetType(Control)) Then
            Throw New ArgumentException(String.Format("""{0}"" does not inherit from Control.  Only Controls can be added to the control collection.", a))
        End If

        Dim newControl As Control = Activator.CreateInstance(controlType)
        If newControl Is Nothing Then
            Throw New ArgumentException(String.Format("Unspecified error when creating control of type ""{0}"".", a))
        End If
        Panel1.Controls.Add(newControl)
    End Sub

A: i found my answer finally...

Private Sub AddUserControl(ByVal a As String)
  Dim nmspace As String = "mynamespace"
  Dim t As Type = Assembly.GetExecutingAssembly().GetType(nmspace & "." & a)
  Dim o As Control = Activator.CreateInstance(t)
  Panel1.Controls.Add(o)
  End Sub


text:
Q: solr: how can I get the number of keywords in the whole corpus? I'm doing a research about PMI using an engine which is established by solr. I want to get the number of keywords within the corpus(not the numofDocs). Is there a direct way to get this?
Another Question:
Can I do a search which contains a logic operater(such as NEAR) in solr system? OR similary method to do this?

A: NEAR is "proximity search"; solr provides something similar in the form of "sloppy phrase queries", which have the form:
field:"phrase of words"~10

The 10 is how close the words in the phrase must be.


text:
Q: export all properties from object as non default I've been wanting to do this, but it doesn't seem to be working
const settings = {
  PENDING_ACTION_TIME: 100000
}

export default settings
export {...settings}

This way I can do
import {PENDING_ACTION_TIME} from '../settings'

or
import settings from '../settings'

I know I could export each properties one by one by that seems like stupid code repetition if you have something like 20 properties.

A: Don't start with an object in the first place. Use named exports instead:
const PENDING_ACTION_TIME = 100000;

This way you can do
import {PENDING_ACTION_TIME} from '../settings';

or a namespace import
import * as settings from '../settings';

You could also use the namespace object in a default export, but you really shouldn't.

A: Maybe using the CommonJS method of export
// settings.js

module.exports = {
  PENDING_ACTION_TIME: 100000
}

But you'll only be able to use the following syntax
import { PENDING_ACTION_TIME } from '../settings';


text:
Q: Optimized query to match and exclude multiple ManyToMany entries I'm working on a tagging system that requires querying objects that have multiple tags as well as being able to exclude objects that have tags. The code below is a simple example of the queries I'm making. In reality there is an arbitrary number of tags that will be matched/excluded. My current implementation works but is slow over large amounts of data. I'm looking for a way to speed up this query.
class Model(models.Model):
    tags = models.ManyToManyField(Tag)

Model.objects.filter(tags=tag_1).filter(tags=tag_2).exclude(tags=tag_3)

A: If you have already identified that line as culprit with the help e.g. of django-debug-toolbar I'd try two things:

*

*Filter using in instead of different clauses
Models.objects.filter(tags__in=[tag_1, tag_2])

*Filter using ids instead of object
Model.objects.filter(tags__id=tag_1.id).filter(tags__id=tag_2.id)
You can even combine the two.


text:
Q: Django test setup fails when running single test file The immediate symptoms:
$ pytest …/apps/users/test/test_graph_permissions_command.py
============================= test session starts ==============================
platform linux -- Python 3.6.8, pytest-4.6.2, py-1.8.0, pluggy-0.12.0
Django settings: dms.settings (from ini file)
rootdir: /src/app, inifile: pytest.ini
plugins: forked-1.0.2, celery-4.3.0, django-3.5.0, cov-2.7.1, xdist-1.28.0
collected 1 item

…/apps/users/test/test_graph_permissions_command.py E

==================================== ERRORS ====================================
_ ERROR at setup of TestGraphPermissionsCommand.test_should_resolve_a_permission_hierarchy _
.venv/lib/python3.6/site-packages/pytest_django/plugin.py:519: in _django_setup_unittest
    request.getfixturevalue("django_db_setup")
.venv/lib/python3.6/site-packages/pytest_django/fixtures.py:108: in django_db_setup
    **setup_databases_args
.venv/lib/python3.6/site-packages/django/test/utils.py:174: in setup_databases
    serialize=connection.settings_dict.get('TEST', {}).get('SERIALIZE', True),
.venv/lib/python3.6/site-packages/django/db/backends/base/creation.py:80: in create_test_db
    self.connection._test_serialized_contents = self.serialize_db_to_string()
.venv/lib/python3.6/site-packages/django/db/backends/base/creation.py:123: in serialize_db_to_string
    serializers.serialize("json", get_objects(), indent=None, stream=out)
.venv/lib/python3.6/site-packages/django/core/serializers/__init__.py:128: in serialize
    s.serialize(queryset, **options)
.venv/lib/python3.6/site-packages/django/core/serializers/base.py:90: in serialize
    for count, obj in enumerate(queryset, start=1):
.venv/lib/python3.6/site-packages/django/db/backends/base/creation.py:120: in get_objects
    yield from queryset.iterator()
.venv/lib/python3.6/site-packages/django/db/models/query.py:341: in _iterator
    yield from self._iterable_class(self, chunked_fetch=use_chunked_fetch, chunk_size=chunk_size)
.venv/lib/python3.6/site-packages/polymorphic/query.py:56: in _polymorphic_iterator
    o = next(base_iter)
.venv/lib/python3.6/site-packages/django/db/models/query.py:55: in __iter__
    results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size)
.venv/lib/python3.6/site-packages/django/db/models/sql/compiler.py:1087: in execute_sql
    sql, params = self.as_sql()
.venv/lib/python3.6/site-packages/django/db/models/sql/compiler.py:474: in as_sql
    extra_select, order_by, group_by = self.pre_sql_setup()
.venv/lib/python3.6/site-packages/django/db/models/sql/compiler.py:54: in pre_sql_setup
    self.setup_query()
.venv/lib/python3.6/site-packages/django/db/models/sql/compiler.py:45: in setup_query
    self.select, self.klass_info, self.annotation_col_map = self.get_select()
.venv/lib/python3.6/site-packages/django/db/models/sql/compiler.py:219: in get_select
    cols = self.get_default_columns()
.venv/lib/python3.6/site-packages/django/db/models/sql/compiler.py:666: in get_default_columns
    column = field.get_col(alias)
.venv/lib/python3.6/site-packages/django/db/models/fields/related.py:981: in get_col
    output_field = self.target_field
.venv/lib/python3.6/site-packages/django/db/models/fields/related.py:878: in target_field
    return self.foreign_related_fields[0]
.venv/lib/python3.6/site-packages/django/db/models/fields/related.py:632: in foreign_related_fields
    return tuple(rhs_field for lhs_field, rhs_field in self.related_fields if rhs_field)
.venv/lib/python3.6/site-packages/django/db/models/fields/related.py:619: in related_fields
    self._related_fields = self.resolve_related_fields()
.venv/lib/python3.6/site-packages/django/db/models/fields/related.py:604: in resolve_related_fields
    raise ValueError('Related model %r cannot be resolved' % self.remote_field.model)
E   ValueError: Related model 'appname.ModelName' cannot be resolved
=========================== 1 error in 5.54 seconds ============================

The test file:
$ cat …/apps/users/test/test_graph_permissions_command.py
from django.test import TestCase

class TestGraphPermissionsCommand(TestCase):
    def test_should_resolve_a_permission_hierarchy(self) -> None:
        pass

The circumstances:

*

*Testing test_graph_permissions_command.py with another file works fine - any other file seems to work, and it works whether test_graph_permissions_command.py is first or last.

*Importing TestCase from unittest instead works, but I will need some things from django.test.TestCase in the actual test.

*Testing any other single file also works.

*I rebuild the VM that this runs on every night, and a colleague was able to reproduce this issue, so it's not unique to my setup.

*./manage.py makemigrations reports "No changes detected".

*Many other test classes inherit from the same TestCase class without issue.

*The app and model in the error message is very well tested. Ditto for the two models which each have a ForeignKey to "appname.ModelName". The code coverage is 98%.

What is going on here? It looks like this could be caused by a failure of the test DB builder to do things in the right sequence.


text:
Q: Php help for html/css contact form I am very new to coding and am trying to set up a contact form using code from here: http://codepen.io/rexkirby/pen/Fdnlz
I now need to make it functional but have 0 knowledge of php. I've tried lots of different bits of php code, but I don't even know how to link the html file to the .php file properly. My code is below, if anyone could tell me how to link the files I would be so so grateful!
HTML:

    <form class="form" id="form1" action="mail.php" method="post">

        <input name="name" type="text" class="validate[required,custom[onlyLetter],length[0,100]] feedback-input" placeholder="Name" id="name" />

        <input name="email" type="text" class="validate[required,custom[email]] feedback-input" id="email" placeholder="Email" />

       <textarea name="text" class="validate[required,length[6,300]] feedback-input" id="comment" placeholder="Comment"></textarea>

        <input type="submit" value="SEND" id="button-blue"/>

    </form>

Php
    <?php
if (isset($_REQUEST['email']))
//if "email" is filled out, send email
{
    //send email
    $from = $_REQUEST['author'] ;
    $to = $_REQUEST['email'] ;
    $subject = $_REQUEST['subject'] ;
    $message = $_REQUEST['msg'] ;
    mail($to, $subject, $message, "From:" . $from);

    // the mail was sent
    echo "Thank you for using our mail form";
}
else {
    //if "email" is not filled out, display the form
    //just close php and copy the code for your form
?>

A: Thanks! I finally sorted the problem, it turns out GitHub doesn't support php which is where I was hosting it

A: First create a file called mail.php and place it within the same directory as your html/css file.
The mail.php file is responsible for processing your form and then sending it wherever you wish. Save these files and simply test them on a web server like WAMP/LAMP/XAMP or a live server if you have one.


text:
Q: Imaginary tangents of parabola For a parabola $y^2 = 4ax$ ,we can draw $2$ tangents from any point.If the point is outside of parabola then obviously we can draw $2$ tangents. If the point is on the parabola then the two tangents will coincide and it is easy to draw that picture. I know that if the point is inside the parabola then the tangents are imaginary.
But What does it means that the tangents are imaginary ? And I don't know how it will draw?


text:
Q: How to print \upharpoonright? When I run pdflatex twice on my LaTeX file, the command \upharpoonright does not print the harpoon. Could you let me know how to fix this.
I use this command $ S(T)\upharpoonright D^{i}_{l} $.

A: You need a package that provides \upharpoonright, e.g. amssymb:
\documentclass{article}
\usepackage{amssymb}
\begin{document}
  $ S(T)\upharpoonright D^{i}_{l} $
\end{document}


text:
Q: Combine two array in php I am new in php. I want to combine two array data into one table. My first array is given below:
http://i.imgur.com/XmVaUPH.png
 My second array is given below :
http://i.imgur.com/jSOdlMD.png
My output will be:
Name Date    Start time  End time
Billal   1-14-15 11:29 AM    8:30 Pm
Emrul    1-14-15 2:21 PM 8:34 pm
Limon    1-14-15 11:26 AM
Mamun    1-14-15 11:47 AM    8:32 pm
Masum    1-14-15 12:12 PM    8:33 pm
Shahed   1-14-15 11:30 Am
Emrul    1-15-15 11:29 AM    8:30 Pm
Limon    1-15-15 11:47 AM    8:32 pm
Masum    1-15-15 12:12 PM    8:33 pm
 Here start time will be 10 am to 2 pm and rest are end time. when start/end time two data found fast data will be counted

A: Looks like what you need here is to combine two arrays you have given and order the result based on the time taken.
Here are some best practices to approach your problem.

*

*If you ever need to calculate date/time do not use strings, use timestamps because it is just a one big number which you can use to easily manipulate (in your case you just need to subtract start date/time from end date/time to get the total time taken) using simple math.

*If you store the data in a SQL database then don't retrieve them and calculate the time taken in PHP, instead calculate the durations using SQL before retrieving data. It will massively reduce the application overhead. You also can use SQL sorting to sort your result set.
Please don't attach screenshots of your xdebug output in future, instead paste on to the editor.

A: $array1a = array_chunk($array1, 3);
$array2a = array_chunk($array2, 3);

 $table =array();
foreach($array1a as $v1){
   $tmp = array(
   'name'=>$v1[0],
    'date' => $v1[1],
     'time1' => $v1[2]
    );

  foreach($array2a as $v2){
      if($v2[1] == $v1[1] && $v2[0] == $v1[0]){
        $tmp['time2']=$v2[2];
       }
   }
  $table[] =   $tmp;
}

hope it help

A: array_merge() is an useful function for merging two arrays. Here is a simple example.
<?php
 $array1 = array("color" => "red", 2, 4);
 $array2 = array("a", "b", "color" => "green", "shape" => "trapezoid", 4);
 $result = array_merge($array1, $array2);
 print_r($result);
?>


text:
Q: rails - DRY respond_to with repeated actions In one of my rails controller, I must respond to several types of formats, so I use the typical respond_to chain:
respond_to do |format|
  format.html   { ... }
  format.mobile { ... }
  format.jpg  { ... }
  format.xml  { ... }
  format.js   { ... }
end

Usually that the { ... } part is repeated on several formats. What is the best way to stay DRY on this case? On an scenario in which html, mobile and xml have a "repeated" action, I'd like to do something like this:
respond_to do |format|
  format[:html, :mobile, :xml] { ... }
  format.jpg  { ... }
  format.js   { ... }
end

Thanks a lot.

A: Can you give an example of the repetition you're seeing?
You could always do something like this:
respond_to do |do|
  format.html { common_stuff }
  format.mobile { common_stuff }
  format.xml { common_stuff }
  ...
end

protected

def common_stuff
  ...
end

I think something like that could be refactored to (I probably got this wrong as I always forget how to use a method as a block:
[:html, :mobile, :xml].each { |f| format.send(:f, lambda{ common_stuff }) }

Having said that, I think you're better off with the former as it's more explicit.

A: Have you tried format.any(:html, :mobile, :xml)?
Example (added 2011/9/14)
From the rails doc
Respond to also allows you to specify a common block for different formats by using any:
def index
  @people = Person.all

  respond_to do |format|
    format.html
    format.any(:xml, :json) { render request.format.to_sym => @people }
  end
end

In the example above, if the format is xml, it will render:
render :xml => @people

Or if the format is json:
render :json => @people


text:
Q: Ruby programming - avoid code duplication when named scopes are used I have multiple named scopes in my model. They have different names but same parameters.
Now, when I use these named scopes based on a condition I have to duplicate the entire parameters all the time. Is there anyway to avoid that?
For ex:
In my say a Product model:
named_scope :example1, lambda{ |parameter1, parameter2|{
 //some code here//
 }
}

named_scope :example2, lambda{ |parameter1, parameter2|{
 //some code here//
 }
}

named_scope :example3, lambda{ |parameter1, parameter2|{
 //some code here//
 }
}

Now, I want to use these based on condition
if(condition)

Product.example1(param1, param2)

elsif (condition)

Product.example2(param1, param2)

else

Product.example3(param1, param2)

Is there any way to call it like this in ruby:
variable = example1 //I can get the name of named_scope here

Product.variable(param1, param2). //The relevant named_scope should be used.

A: You can use Object#send do send Product a message (aka call a method).
Product.send(variable,param1,param2)


text:
Q: Have a array or list represent several properties in a auto generated partial class I have a class that is a auto generated partial class.
In this class it generates 5 properties like:
public double AW1 {get; set;}
public double AW2 {get; set;}
public double AW3 {get; set;}
public double AW4 {get; set;}
public double AW5 {get; set;}

Edit:  I should mention these properties do have some custom set logic which I would want to execute when they do change values.
In many situations it would be very handy to treat these properties as a array or list.
I thought I could do something like:
    public double[] AW
    {
        get
        {
            double[] AWList = new double[]
            {
                AW1,
                AW2,
                AW3,
                AW4,
                AW5,
            };
            return AWList;
        }

        private set
        {
            AW1 = value[0];
            AW2 = value[1];
            AW3 = value[2];
            AW4 = value[3];
            AW5 = value[4];
        }
    }

But there must be a better way to do it then this way.


text:
Q: Plot multiple lines with different colors I am trying to create a plot i has multiple lines (data series). Each of these lines is a category and I want it to have a unique color.
How do I make each of these to lines have a unique color ?
Any help or suggestions would be much appreciated.
My data frame structure:
structure(list(Time = structure(c(1L, 1L, 1L, 1L, 1L, 1L), .Label = c("04:00",
"04:10", "04:20", "04:30", "04:40", "04:50", "05:00", "05:10",
"05:20", "05:30", "05:40", "05:50", "06:00", "06:10", "06:20",
"06:30", "06:40", "06:50", "07:00", "07:10", "07:20", "07:30",
"07:40", "07:50", "08:00", "08:10", "08:20", "08:30", "08:40",
"08:50", "09:00", "09:10", "09:20", "09:30", "09:40", "09:50",
"10:00", "10:10", "10:20", "10:30", "10:40", "10:50", "11:00",
"11:10", "11:20", "11:30", "11:40", "11:50", "12:00", "12:10",
"12:20", "12:30", "12:40", "12:50", "13:00", "13:10", "13:20",
"13:30", "13:40", "13:50", "14:00", "14:10", "14:20", "14:30",
"14:40", "14:50", "15:00", "15:10", "15:20", "15:30", "15:40",
"15:50", "16:00", "16:10", "16:20", "16:30", "16:40", "16:50",
"17:00", "17:10", "17:20", "17:30", "17:40", "17:50", "18:00",
"18:10", "18:20", "18:30", "18:40", "18:50", "19:00", "19:10",
"19:20", "19:30", "19:40", "19:50", "20:00", "20:10", "20:20",
"20:30", "20:40", "20:50", "21:00", "21:10", "21:20", "21:30",
"21:40", "21:50", "22:00", "22:10", "22:20", "22:30", "22:40",
"22:50", "23:00", "23:10", "23:20", "23:30", "23:40", "23:50",
"00:00", "00:10", "00:20", "00:30", "00:40", "00:50", "01:00",
"01:10", "01:20", "01:30", "01:40", "01:50", "02:00", "02:10",
"02:20", "02:30", "02:40", "02:50", "03:00", "03:10", "03:20",
"03:30", "03:40", "03:50"), class = "factor"), WhereHome = c(1,
1, 0, 0, 0, 1), WhereWork = c(0, 0, 0, 0, 0, 0), Witch = c(0,
0, 0, 0, 0, 0), OtherAct = c(0, 0, 0, 0, 0, 0)), row.names = c(NA,
6L), class = "data.frame")

How to improve this plot?

A: Here's a snippet for 2 lines.
Code
# Create plot
plot(data$Var1, data$WhereWork,
      main="Overlaying Graphs",
      ylab="",
      type="l",
      col="blue")

# Add other lines
lines(data$Var1,data$WhereHome, col="red")
lines(...)

# Add legend to the lines
legend("topleft",
        c("A","B"),
        fill=c("blue","red")
 )

Plot


text:
Q: Find as close as exact matches in database - which way is better? I have a situation:
I have a database (MySQL) which contains products and their codes like this
BLACK SUGAR BS 709
HOT SAUCE AX889/9
TOMY 8861

I got an excel spreadsheet which I converted to CSV, this contains prices for the products. Its structure consists in 2 columns, code and price, like this:
BS709          23.00
AX 889 /9      10.89
8861           1.69

I made a script to update the products prices by searching in the database for the respective product code, using a FOREACH and %LIKE% query.
FOREACH row in CSV, search the database using "WHERE product_code LIKE %code%.
This is offcourse a primitive and not so succesfull way of updating the prices, because the codes in CSV are not an exact match (in syntax) of those in the database so if I have two products in the DB containing BS709 (BS70923) in their code I get multiple matches.
Is there a better way of doing this ?

A: You could trim the columns of spaces and other characters using MySQL replace() before comparing. This will return all exact matches, regardless of any spaces contained.
SELECT * FROM table WHERE REPLACE( product_code, ' ', '' ) LIKE 'code'

A: Given your examples, I would recommend removing all spaces from both, and then just looking for when the beginning or end of a code matches exactly:
where replace(e.code, ' ', '') like concat(replace(db.code, ' ', ''), '%') or
      replace(e.code, ' ', '') like concat('%', replace(db.code, ' ', '')) or
      replace(db.code, ' ', '') like concat(replace(e.code, ' ', ''), '%') or
      replace(db.code, ' ', '') like concat('%', replace(e.code, ' ', ''));

This may not work for the specific case when one code is a prefix of another.
In any case, if the product codes in a spreadsheet are different from the product codes in the database, I think you have bigger problems.  If you cannot really fix the spreadsheets, I would recommend that you manually/semi-automatically create a synonyms table in the database.  This would have the Excel product code in one column and the correct product code in the other.  Then you can do the lookup just by joining this together.
Yes.  That is work.  But probably less work than struggling with this problem and getting poor results that have to be repeatedly updated.


text:
Q: Set vue-router messages via axios call I would like to fetch my translation messages via an api call to my backend app. In the then callback of the axios call I'd like to set the messages.
However the issue seems to be that VueRouter is already initialised with the empty translations and is not getting reloaded with the new ones from the then callback.
Is there a way for me to achieve this?
I've tried:
let messages = {};
window.axios.get(route('api.translation.translations.all'))
    .then(response => {
        messages = {
            [currentLocale]: response.data,
        }
    });
console.log(messages);

const i18n = new VueI18n({
    locale: currentLocale,
    messages,
});

This doesn't work as new VueI18n is called before messages is fully set.
window.axios.get(route('api.translation.translations.all'))
    .then(response => {
        messages = {
            [currentLocale]: response.data,
        };
        console.log(messages);
        app.$i18n.setLocaleMessage('en', messages)
    });

This also doesn't work.
Thanks!

A: Found the solution, I didn't need to specify the locale, as it's the first argument of  setLocaleMessage.
window.axios.get(route('api.translation.translations.all'))
    .then(response => {
        messages = response.data;

        app.$i18n.setLocaleMessage(currentLocale, messages);
    });


text:
Q: Is there a formula, which describes the force on diamagnetic and paramagnetic matter in a magnetic field? To prove that a element is diamagnetic or paramagnetic, you can hold it into a inhomogeneous magnetic field and look in wich direction the force acts. (see description here)
I am interested in a formula, which describes the force on the matter, similar to this one ($F_z = m_z *\frac{\partial B_z(z0)}{\partial z}$). The force should not just depend on $\partial B$ but also on the matter, which is used.
Thanks in advance
EDIT: would the formula look like this? $F = \chi * m * \frac{\partial B_z(z0)}{\partial z} \text{ where } \chi \text{ is the magnetic susceptibility.}$ I would need this formula for a simulation of a spheric. So I would just assume that the spheric is just a point (not in terms of the mass, but in terms of the force
acting on it and in terms of the magnetic field), so I can ignore the geometry. Do I need any other factors or constants?

A: The formula contains the contribution of the matter. If you are looking for the force on a piece of matter in magnetic field, the magnetic moment of the piece of matter depends on the susceptibility of the material and the size of the sample. But a formula for the actual force is not trivial. It will depend, in general, on the actual geometry of the sample and the field, as the magnetic moment of the piece depends on the field too. So the force will be proportional to a term like
$$ B \frac{\partial B}{\partial z} $$
The proportionality constant will contain the magnetic susceptibility and some geometric factor.


text:
Q: Strange gem installation runtime depedency error on rake version on ubuntu Inside my gemspec file I have:
s.add_runtime_dependency 'rake',
[ '>= 0.9.0.0']

On Windows I install it with the command:
gem install --local myGem-0.9.0.gem

Because --user does not seem to work on windows and it installs in the main ruby gem area.
This works fine the current rake version on that machine is 0.9.2.2 and the current gem version on that machine is 1.8.28
On Ubuntu with the same gemspec file I install it with:
gem install --local --user myGem-0.9.0.gem

which fails with the error:
ERROR:  While executing gem ... (Gem::DependencyError)
  Unable to resolve dependencies: myGem requires rake (>= 0.9.0.0)

The version of rake installed on that machine is: 10.0.4
and then current gem version on that machine is 1.8.23
I tried changing the gemspec file to '>= 9.0.0' and I got the same error.
This gem uses rake at runtime.
This behavior seems quite contrary to the documentation on the gemspec file.  How do I accomplish this version test? It works fine without a version dependency value.


text:
Q: Example of a group Can one give an example of a finite group $G$, with a subset $H$ containing identity, such that $gHg^{-1}=H$ for all $g\in G$, $|H|$ divides $|G|$, but $H$ is not a subgroup of $G$.
Motivation (Theorem of Frobenius): If $G$ acts on a set $X$ tranitively ( $|X|>1$), such that stabilizers are non-trivial but intersection of any two stabilizers is trivial, then the set $K$ of elements of $G$ which have no fixed point, together with identity, form a normal subgroup of $G$. It is easy to see that the condition of normality is easily verified, but to prove that it is a subgroup of $G$, character theory has been used.
While proving this theorem, the necessary conditions are:

*

*$|K|$ should divide $|G|$

*$gKg^{-1}=K$ for all $g\in G$.
I would like to see an example, where subset of $G$ (containing identity) which satisfies these two conditions but it is not a subgroup of $G$.

A: Looking for examples in less abelian groups, in $S_5$ we have the the identity, the 24 5-cycles and the 15 3-cycles, giving a subset of size 40. There are examples of size 1680 in $S_7$ and 10080 and 13440 in $S_8$. There is also one of size 112 in ${\rm PGL}(2,7)$. But interestingly I could not find any examples in nonabelian simple groups.

A: Consider $G = \displaystyle \frac{\mathbb{Z}}{6\mathbb{Z}} = \bigl\{ \ \overline{0}, \overline{1}, \overline{2}, \cdots, \overline{5}\ \bigr\}$. Consider this subset $H = \bigl\{\ \overline{0},\overline{1} \ \bigr\}$


text:
Q: convert List to array using C# I am trying to convert a list that I pulled from an API and convert it to a list.  The list does return other data but i have code in there to return just the data I want( it could be wrong)
//this pulls the data
public List<AccountBalance> CorpAccounts(int CORP_KEY, string CORP_API, int USER)
{
    List<AccountBalance> _CAccount = new List<AccountBalance>();
    EveApi api = new EveApi(CORP_KEY, CORP_API, USER);
    List<AccountBalance> caccount = api.GetCorporationAccountBalance();
    foreach (var line in caccount)
    {

        //everyting after
        string apiString = line.ToString();
        string[] tokens = apiString.Split(' ');
        _CAccount.Add(line);
    }
    return _CAccount;
}

//I am trying to convert the list to the array here
private void docorpaccounts()
{
    string[] corpbal = cwaa.CorpAccounts(CORP_KEY, CORP_API, USER).ToArray();
}

With that code I get this error:

Error 1 Cannot implicitly convert type 'EveAI.Live.AccountBalance[]'
  to 'string[]'

Not sure what I am doing wrong here.

A: You're trying to assign AccountBalance[] into string[] - as error says.
Unless you really need string[] you should change variable declaration to AccountBalance[]:
private void docorpaccounts()
{
    AccountBalance[] corpbal = cwaa.CorpAccounts(CORP_KEY, CORP_API, USER).ToArray();
}

Or specify how the AccountBalance should be transformed to be a string. e.g. using ToString method:
private void docorpaccounts()
{
    string[] corpbal = cwaa.CorpAccounts(CORP_KEY, CORP_API, USER)
                           .Select(x => x.ToString())
                           .ToArray();
}

or one of its properties
private void docorpaccounts()
{
    string[] corpbal = cwaa.CorpAccounts(CORP_KEY, CORP_API, USER)
                           .Select(x => x.MyStringProperty)
                           .ToArray();
}

A: List<T>.ToArray Method (msdn)
Syntax:

public T[] ToArray()

So if you have List<AccountBalance> you should have AccountBalance[] when you invoke ToArray method.
Try this:
AccountBalance[] corpbal = cwaa.CorpAccounts(CORP_KEY, CORP_API, USER).ToArray();

As @BenjaminGruenbaum mention in comment, the better option will be using var keyword (msdn):
var corpbal = cwaa.CorpAccounts(CORP_KEY, CORP_API, USER).ToArray();


text:
Q: Changing TIME_FORMAT for locale According to the django documentation:

if USE_L10N is set to True, then the locale-dictated format has higher
  precedence and will be applied instead

First of all I would like to know where this locale-dicated format is defined and if there is any possibility to customize it somewhere for a given locale?

A: see here

When it's enabled, two users accessing the same content may see dates, times and numbers formatted in different ways, depending on the formats for their current locale.

so this is something that targets the audience/client (ie. if I am accessing the website in New York, I will get my time in EST, vs you may get your time in GMT in London)


text:
Q: docker-compose up: OSError: [Errno 99] Cannot assign requested address I am using docker-compose up to run a python file, however, there is error info:
matching_server_1  | Traceback (most recent call last):
matching_server_1  |   File "server.py", line 65, in <module>
matching_server_1  |     server = TCPServer((HOST, PORT), RequestHandler)
matching_server_1  |   File "/usr/local/lib/python3.7/socketserver.py", line 452, in __init__
matching_server_1  |     self.server_bind()
matching_server_1  |   File "/usr/local/lib/python3.7/socketserver.py", line 466, in server_bind
matching_server_1  |     self.socket.bind(self.server_address)
matching_server_1  | OSError: [Errno 99] Cannot assign requested address

But the program runs well by python3 server.py without docker.
The structure of the project is:
root
   |—docker-compose.yml
   |—matching_engine
         |—Dockerfile
         |-server.py (main)
         |-.......

and my Dockerfile is:
FROM python:3
ENV PYTHONUNBUFFERED 1
RUN mkdir /src
WORKDIR /src
ADD requirements.txt /src/
RUN pip install -r requirements.txt
ADD . /src/

and my docker-compose.yml is:
version: '2'

services:
  db:
    image: postgres
    environment:
      POSTGRES_PASSWORD: passw0rd
      POSTGRES_USER: postgres
      POSTGRES_DB: EXCHANGEMACHINE
    volumes:
      - /var/lib/docker/volumes/data-volume:/var/lib/postgresql/data
    restart: always
  matching_server:
    build: ./matching_engine
    user: nobody
    command: bash -c "python3 server.py"
    volumes:
      - ./matching_engine:/src
    ports:
      - "12345:12345"
    expose:
      - "12345"
    depends_on:
      - db

and the code that reports error in server.py is:
if __name__ == '__main__':
    HOST = '0.0.0.0'
    PORT = 12345
    server = TCPServer((HOST, PORT), RequestHandler)
    server.serve_forever()

What is going wrong in this situation? Thanks!

A: Try to add in your matching_server service
links:
  - db

and remove expose: "12345"


text:
Q: Highcharts Solid Gauge Pane I was wondering whether the pane inside the solid gauge was a list or an object. I see in the notes that it is a simple object
https://api.highcharts.com/highcharts/pane
but the following jsfiddle seems to refer to a chart with multiple panes, suggesting the pane can take an array
jsfiddleCode

https://jsfiddle.net/gh/get/library/pure/highcharts/highcharts/tree/master/samples/highcharts/demo/gauge-vu-meter
Making this even more complex, I am using the .net version of Highcharts (v7.2.0), and can add a new Pane, but cannot add a new List to the chart
working C# code

Does not work

Any help here would be greatly appreciated!