text:
Q: How to put multiple suffix icon in TextField flutter? I've been trying hard to get this setup, but I couldn't just get to behave the icon the way I wanted it to be.
[1]: https://i.stack.imgur.com/mJFds.png
I wanted to make the add button snap with the TextField, but I could not wrap it with any other widgets.
All I could end up is this.
[2]: https://i.stack.imgur.com/m2Ze9.png
Can somebody please help me figure out a way over this.
Thanks in advance.
   import 'package:flutter/material.dart';
   import 'package:provider/provider.dart';
   import 'package:badminton_app/constants.dart';
   import 'package:badminton_app/model/players_data.dart';

TextEditingController _controller = TextEditingController();

class AddPlayersScreen extends StatefulWidget {
 @override
 _AddPlayersScreenState createState() => _AddPlayersScreenState();
}

class _AddPlayersScreenState extends State<AddPlayersScreen> {
 String newText;
 @override
 Widget build(BuildContext context) {
   return Scaffold(
     backgroundColor: Color(0xff07021A),
     body: SafeArea(
       child: Padding(
         padding: const EdgeInsets.all(25.0),
         child: Column(
           crossAxisAlignment: CrossAxisAlignment.start,
           children: [
             SizedBox(
               height: 30.0,
             ),
             Text(
               'Add Players',
               style: TextStyle(
                   color: Colors.white,
                   fontSize: 40.0,
                   fontFamily: 'Montserrat'),
             ),
             SizedBox(
               width: 400.0,
               height: 50.0,
               child: Divider(
                 height: 10.0,
                 color: Color(0xff525274),
               ),
             ),
             Container(
               constraints: BoxConstraints.tight(Size(400.0, 70.0)),
               child: TextField(
                 cursorColor: Color(0xffA8A3BE),
                 style: TextStyle(color: Color(0xffA8A3BE), fontSize: 20.0),
                 controller: _controller,
                 onChanged: (newValue) {
                   newText = newValue;
                 },
                 enabled: true,
                 decoration: InputDecoration(
                   suffix: IconButton(
                     onPressed: () {
                       _controller.clear();
                     },
                     icon: Icon(
                       Icons.clear,
                       color: Colors.white,
                     ),
                   ),
                   suffixIcon: IconButton(
                     onPressed: () {
                       Provider.of<PlayerData>(context).changeString(newText);
                     },
                     icon: CircleAvatar(
                         backgroundColor: Colors.amberAccent,
                         child: Icon(
                           Icons.add,
                           color: Colors.black,
                         )),
                   ),
                   hintText: "New member......",
                   hintStyle: TextStyle(
                     fontSize: 20.0,
                     color: Color(
                       0xffA199C6,
                     ),
                   ),
                   filled: true,
                   fillColor: Color(0xff585179),
                   enabledBorder: OutlineInputBorder(
                       borderRadius: BorderRadius.all(Radius.circular(10.0)),
                       borderSide: BorderSide.none),
                   focusedBorder: OutlineInputBorder(
                       borderRadius: BorderRadius.all(
                         Radius.circular(10.0),
                       ),
                       borderSide: BorderSide.none),
                 ),
               ),
             )
             //Something(),
           ],
         ),
       ),
     ),
   );
 }
}

A: suffixIcon: Container(
                      width: 100.w,
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.end,
                        children: [
                          IconButton(
                            padding: EdgeInsets.zero,
                            constraints: BoxConstraints(),
                            onPressed: () {
                              print('mic button pressed');
                            },
                            icon: Icon(
                              Icons.mic,
                              color: background_color,
                            ),
                          ),
                          IconButton(
                            padding: EdgeInsets.fromLTRB(1, 0, 1, 0).r,
                            constraints: BoxConstraints(),
                            onPressed: () {
                              print('photo button pressed');
                            },
                            icon: Icon(
                              Icons.photo,
                              color: background_color,
                            ),
                          ),
                          IconButton(
                            padding: EdgeInsets.fromLTRB(2, 0, 3, 0).r,
                            constraints: BoxConstraints(),
                            onPressed: () {
                              print('Emoji button pressed');
                            },
                            icon: Icon(
                              Icons.emoji_emotions,
                              color: background_color,
                            ),
                          ),
                        ],
                      ),
                    ),

A: _cellEdit() => Container(
    decoration: BoxDecoration(
      borderRadius: BorderRadius.circular(8),
      color: Colors.white,
    ),
    child: Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: <Widget>[
        Container(
          child: Text('断开'),
          padding: EdgeInsets.all(BaseSize.dp(10)),
        ),
        Row(
          children: <Widget>[
            ImageIcon(IconUtils.getAssetIcon('ic_bluetooth'),
                color: ColorRes.COLOR_03B798),
            Container(
                margin: EdgeInsets.only(left: BaseSize.dp(3)),
                child: Text('A8-123456789'))
          ],
          mainAxisAlignment: MainAxisAlignment.start,
        ),
      ],
    ),
  );

You can refer to this to re-layout your layout


text:
Q: Minimum dependencies to build android app & generate APK file I am basically a .NET Developer but from the last few days, I was working with Ionic. I was able to build and generate APK files from my system where I had installed Android tools from Visual Studio & other dependencies. Below is a list of dependencies that I had installed on my system.
- Java (JDK8)
- Gradle
- Android SDK & Emulator

By using these dependencies, I was able to build my Ionic App and generate APK files.
My Question is that - Now I am moving my code to a new system. What are the minimum dependencies I need to install so that I can keep the show running as before? I know, below dependencies are required.
- Java (JDK8)
- Gradle

Now confusion comes when I think about Android dependencies.

*

*Q1. Installing the Android SDK will be enough for building an app and generating APK files?

*Q2. If Android SDK is the only requirement left then from where can I
  download it for the latest API Level & what is the size of Android SDK? How much space it would take on my hard disc?

*Q3. Will I be required to install other dependencies from SDK Manager after installing the SDK to build the app?
My sole objective is to know the minimum dependencies and their setup to build the Ionic Android App & it's APK generation.

A: You need Java, Gradle, Android SDK to generate an apk(Android) in Ionic.
So in your case just install the android SDK.
Do not forget to add the path variables for Gradle, Java.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do you make values auto-increment in headers? I've created a macro that adds a page at the end of a document and changes the title text in the Header. I want to be able to add multiple pages and have the letter in the title auto-increment:
SCHEDULE 'A'
SCHEDULE 'B'
SCHEDULE 'C'
etc.
I tried using an AUTONUM field, but I get a notification that says, "Main Document Only."
Sub AddSchedule()
'
' AddSchedue Macro
' Press Ctrl+End to add a schedule to a Policy.
'

    Selection.EndKey Unit:=wdStory
    Selection.InsertBreak Type:=wdSectionBreakNextPage
    ActiveWindow.ActivePane.View.SeekView = wdSeekCurrentPageHeader
' Unlink Header from Previous - Is this necessary? The macro seems to work without it...
    Selection.Tables(1).Cell(Row:=1, Column:=2).Range.Text = "SCHEDULE '"
    Selection.Tables(1).Cell(Row:=1, Column:=2).Range.Select
    Selection.Collapse Direction:=wdCollapseEnd
    Selection.MoveEnd Unit:=wdCharacter, Count:=-1
    Selection.Fields.Add Range:=Selection.Range, Type:=wdFieldEmpty, Text:= _
        "AUTONUM  \* ALPHABETIC \s ' ", PreserveFormatting:=False
    ActiveWindow.ActivePane.View.SeekView = wdSeekMainDocument

End Sub

How can I get my page titles to auto-increment in the Headers?
Also, I was under the assumption that I needed to unlink my headers from previous in my macro. I couldn't get that part to work, but with the exception of the fields not working right, everything else seems to work just fine. The header displays the new title even though it says it's still linked. Should I just leave it? Or how would I go about unlinking me headers? I tried using:
Selection.HeaderFooter.LinkToPrevious = False

But it gives me this runtime error:

The method or property is not available because the current selection
  is locked for format changes

A: You can achieve this without a macro by using a calculated field in your header instead - you were very close with the use of the section field.  Just need to subtract 2 so it displays right value.

The section 3 header would need to be unlinked from previous section before you insert the field, but subsequent sections could be linked and the schedule number would update automatically (eg in section 4, the heading would say Schedule 2).


text:
Q: When I install pydensecrf I have an error I tried put this line
$ pip install cython

but, I have an error like this
I/home/jsim/Desktop/Weakly_Segmentation/PuzzleCAM/PuzzleCamVenv/include/python3.8 -c pydensecrf/eigen.cpp -o build/temp.linux-x86_64-3.8/pydensecrf/eigen.o
    pydensecrf/eigen.cpp:23:10: fatal error: Python.h: No such file or directory
     #include "Python.h"
              ^~~~~~~~~~
    compilation terminated.
    error: command '/usr/bin/x86_64-linux-gnu-gcc' failed with exit code 1
    ----------------------------------------
ERROR: Command errored out with exit status 1: /home/jsim/Desktop/Weakly_Segmentation/PuzzleCAM/PuzzleCamVenv/bin/python3.8 -u -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-vyhjigzc/pydensecrf_a00996eb1c2a4603a91b34051c1c43aa/setup.py'"'"'; __file__='"'"'/tmp/pip-install-vyhjigzc/pydensecrf_a00996eb1c2a4603a91b34051c1c43aa/setup.py'"'"';f = getattr(tokenize, '"'"'open'"'"', open)(__file__) if os.path.exists(__file__) else io.StringIO('"'"'from setuptools import setup; setup()'"'"');code = f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record /tmp/pip-record-hyknmek_/install-record.txt --single-version-externally-managed --compile --install-headers /home/jsim/Desktop/Weakly_Segmentation/PuzzleCAM/PuzzleCamVenv/include/site/python3.8/pydensecrf Check the logs for full command output.

I tried
sudo apt-get install python3-dev

pip install git+https://github.com/lucasb-eyer/pydensecrf.git

but, the problem is not solved.
How to solve this problem??
Please Help ME!!!

A: Try:
pip install cython

then
pip install git+https://github.com/lucasb-eyer/pydensecrf.git


text:
Q: How to use ReactiveList in C# in 4.5.2 .Net version I am using .Net 4.5.2 framework. Here I have a list of Hospital (List). Hospital model has the following attributes.

*

*HospitalId

*HospitalName

*DepartmentId

In my C# application, there is a functionality to edit hospital list. Change the hospital name, add new hospital, remove hospital, add the department to the hospital, remove departments from the hospital.
Where I want to check whether the list has been changed before going to save the details to the database. As I go through, there is a special type of list in C# named 'ReactiveList'. Using Reactive List, It is very easy to track the changes in a list. But the problem is I couldn't use ReactiveList in C# since ReactiveList package is not available with the .Net version 4.5.2 which is used by myself.
Is there any solution to overcome this issue?


text:
Q: In scrollable vertical menu, submenu not showing on right side After adding position:fixed and overflow:scroll property menu is scrolled but  submenu does not show on right side bar or when I remove property overflow then right side bar menu shows but parent menu does not scroll.

 Men's Corner

   Women's Corner

  House of Electronics

Laptop

Mobile

Printers

AC

Refrigerator

 nav#cssmenu{margin:0 auto;position: fixed; height: 100%; width: 350px;left: -600px}

enter image description here
enter image description here


text:
Q: How to manage indentation in python? I want to generate strings that have built in indentation to them and I want to make them the values of the map, so that when I print through the keys of the map I will have an output like:
[
    {
        "student": "Zara",
        "grades": [
             [ 4.02, 2.3,4.5,6.7
               ,6.07, 7.08
             ]
         ]
    }
]


text:
Q: How to show fraction in svg if i am using text for now any other alternative using svg I want the text to show a number in the form a/b.
How can I do in SVG<text></text>
E.g.

A: You could display it via unicode superscript and subscript characters like this.

<svg>
  <text x="20" y="30" font-family="Cambria" font-size="20px">Fraction: ³⁄₂</text>
</svg>

or this where dx is used to make the letters appear in the same place.

<svg>
  <text x="20" y="30" font-family="Cambria" font-size="20px">Fraction: <tspan dx="0 -11.5 -11.5">³―₂</tspan></text>
</svg>


text:
Q: Mathematica: why 3D plot remember last viewpoint/rotation made to it, even after evaluating again? I find this a bit annoying.
I make a 3D plot, initially it come up in the default orientation. Then, using the mouse, I rotate it some way.
Now I run the command again, expecting to obtain the original shape (i.e the original orientation before I rotated it by mouse), but instead, it just gives me the same plot I have on the screen, i.e. it seems to have kept/remembered the last viewpoint in that output cell.
I wanted it to go back to the original viewpoint. So, I delete the output cell to make it happen.
Do you think this is how it is supposed to work? Having to keep deleting the cell output is annoying when I am trying thing. I think it should go back to original default orientation.
  Graphics3D[ Cuboid[{-.1,-.1,-.1},{.1,.1,.1}],
        AxesOrigin->{0,0,0},
        PlotRange->{{-1,1},{-1,1},{-1,1}},
        Axes->True,
        AxesLabel->{"X","Y","Z"},
        Ticks->None]

If you run the above, then move the plot, then run the command again, you'll see what I mean.
version 8.0.01
EDIT:
More strange: I added viewpoint option to force it to the default view point, yet, the same result. It remember the last viewpoint. This below is the default viewpoint, from help.
 Graphics3D[ Cuboid[{-.1,-.1,-.1},{.1,.1,.1}],
        AxesOrigin->{0,0,0},
        PlotRange->{{-1,1},{-1,1},{-1,1}},
        Axes->True,
        AxesLabel->{"X","Y","Z"},
        ViewPoint->{1.3,-2.4,2},
        Ticks->None]

I find this strange.

A: Try:
With PreserveImageOptions->False, settings for image options from the previous
version of a graphic are always ignored.

A: In a Mathematica notebook, render your plot, then orient it the way you like.
Then place the cursor on the left of the PLOT OUTPUT, and type "AbsoluteOptions["
Then place the cursor on the right of the PLOT OUTPUT, and type "]" Shift-Enter
You will get a bunch of information. Look for ViewPoint and then use this as an option in your graphics. Then, you will always get the same orientation.

A: I like to think of re-running the Plot command as updating the graphic I have already created.  After all, it does not make a second plot.
From this perspective, if I rotate or size my graphic, I do not want Mathematica to mess with that when I add a label or change a style.
However, if I delete my graphic to start over, Mathematica uses the default rotation and size.
Therefore, I find the behavior logical and appreciated.


text:
Q: ruby acts-as-taggable-on gem tag_counts_on method with tenant conditions Love this gem and I've studied the source code but I'm stumped. I suspect I'm close but I need help finalizing this syntax. Please!!
Pizza.tag_counts_on(:topping, {conditions: "WHERE tenant IS '1'"}) (Yup, tenant is a string!)
This syntax results in error (Object doesn't support #inspect) (Same error if I try a tenant as an int.)

A: Haven't used this gem, but can't you provide the conditions to the base class?
Pizza.where(tenant: '1').tag_counts_on(:topping)

Hope that helps?


text:
Q: Flutter Ternary Operator inside a String doesn't work I'm using the ternary operator to avoid null values within my Text-Widgets.
If the variable is null, I would assume noData as value. But while debugging I noticed that ternary operator directly jumps out, without going to ELSE.
If the variable is not null, it works fine.
    String noData = "No data available";

.....

                  Text(
                    "Population:",
                    style: TextStyle(
                      fontSize: 18.0,
                      fontWeight: FontWeight.values[4],
                    ),
                  ),
                  Text(
                    "${country.data.last.population != null ? country.data.last.population : noData}",
                    style: TextStyle(
                      fontSize: 16.0,
                    ),
                  ),

.....

A: You forgot the quotes around your default string 'noData'.
You probably wanted to do:
Text('${country.data.last.population != null ? country.data.last.population : 'noData'}'),

But why not the simpler:
Text(country.data.last.population ?? 'noData'),

Simple example in answer to comment below:
void main() {
  String noData = "No data available";
  double value;
  print("${value != null ? value : noData}");     // No data available
  print("${value ?? noData}");                    // No data available
  value = 10.0;
  print("${value != null ? value : noData}");     // 10
  print("${value ?? noData}");                    // 10
}

A: You have an issue with your data that is causing that error. It's not an issue with the Dart language. You can try out the below example on https://dartpad.dev/ where I am, like you, getting a String value from a inside a object and checking if it's null. It works in both cases:
void main() {
  Person person1 = Person(name: 'John', age: 35);
  Person person2 = Person(age: 22);

  print("${person1.name != null ? person1.name : 'no name'}");
  print("${person2.name != null ? person2.name : 'no name'}");
}

class Person {
  String name;
  int age;

  Person({
    this.name,
    this.age
  });
}

Console
John
no name


text:
Q: Assign an application pool to a website I am trying to make a web application which can access local iis and create/delete/assign application pools programmatically to the websites in iis(Most of them SharePoint 2007 sites). Create,and delete are working but assign is not. I am using WSS 3.0, iis 6 on Windows server 2003.
My code is here:
protected void btnChangePool_Click(object sender, EventArgs e)
    {
        string siteId = GetWebSiteId(ddlSites.SelectedValue);
              //ddlSites contains name of site as it shows in iis under websites
        DirectoryEntry oldAppPool = new DirectoryEntry("IIS://localhost/W3SVC/AppPools/" + lblAppPool.Text);
        //lblAppPool contains name of currently app pool associated to our site
        if (chkDeleteOld.Checked)
        {

            using (DirectoryEntry appPool = oldAppPool)
            {
                using (DirectoryEntry parent = oldAppPool.Parent)
                {
                    parent.Children.Remove(oldAppPool);
                    parent.CommitChanges();
                }
            }
        }
        DirectoryEntry VDir = new DirectoryEntry("IIS://localhost/W3SVC/"+siteId+ "/ROOT");
        VDir.Properties["AppPoolId"].Value = ddlAppPools.SelectedValue;
                   //ddlappPools contains name of new app pool (to be assigned)
        VDir.CommitChanges();
    }

public string GetWebSiteId(string websiteName)
    {
        string result = "-1";

        DirectoryEntry w3svc = new DirectoryEntry("IIS://localhost/w3svc");

        foreach (DirectoryEntry site in w3svc.Children)
        {
            if (site.Properties["ServerComment"] != null)
            {
                if (site.Properties["ServerComment"].Value != null)
                {
                    if (string.Compare(site.Properties["ServerComment"].Value.ToString(), websiteName,false) == 0)
                    {
                        result = site.Name;
                        break;
                    }
                }
            }
        }

        return result;
    }

  protected void btnCreatePool_Click(object sender, EventArgs e)
    {
        DirectoryEntry root = new DirectoryEntry("IIS://localhost/W3SVC/AppPools");
        DirectoryEntry newAppPool;
        //newAppPool = root.Invoke("Create", "IIsApplicationPool", txtCreatePool.Text) as DirectoryEntry;
            //OR
        newAppPool = root.Children.Add(txtCreatePool.Text, "IIsApplicationPool");
        newAppPool.CommitChanges();
        root.CommitChanges();
    }


text:
Q: Convert a decimal number to its corresponding binary @Love babbar Can anyone tell me why is this code not giving proper answer for odd numbers but it is giving right answers for even numnbers.
 **int main(){
  int n;
  cin>> n;

  int ans = 0;
  int i = 0;
  while(n != 0){
    int bit = n & 1;
    ans = (bit * pow(10, i)) + ans;
    n = n >> 1;
    i++;
  }
  cout<<ans;
}**

A: Change pow(10, i) to pow(2, i), since binary works in powers of 2, not powers of 10. Also (side note), you can change the while loop to a for loop concerning incrementing i:
for (int i = 0; n != 0; i++)
{
    //convert n to binary
}


text:
Q: Unable to retrieve countries, providers or devices tag stats from the Mailgun API I am using the mailgun-php library (3.0).
In the example below I am able to retrieve regular stats but the providers list is empty.
var_dump: https://pastebin.com/HAt1JRPy
$mgClient = Mailgun::create('key-xxxxxxxxxxxxxxxxxxxxxxxxxxxxx');

$stats = $mgClient->tags()->stats($this->mgDomain, 'nbxxx_1125', array(
    "event" => ["accepted","delivered"],
    "resolution" => "month",
    "duration" => "1m"
));

$providers = $mgClient->tags()->providers($this->mgDomain, 'nbxxx_1125');

var_dump($providers);
var_dump($stats);
die();

Any clue?

A: instead of:
var_dump($providers);

try:
var_dump($providers->getProviders());

and:
var_dump($providers->getTag());

respectively.
according to:
public function getProviders(): array
and:
$this->assertCount(2, $model->getProviders());


text:
Q: React Native Invariant Violation: View config I'm trying to practice with different screens on a React Native project. Here's my code from App.js file.
import React, { Component } from 'react';
import {
  Platform,
  StyleSheet,
  Text,
  View
} from 'react-native';

import { StackNavigator } from 'react-navigation';

class HomeScreen extends React.Component {
    static navigationOptions = {
        title: "welcome",
    };
    render() {
        return <Text style={{ color: 'black '}}>Hello, Navigation!</Text>;
    }
}

const navigation = StackNavigator({
    Home: { screen: HomeScreen },

});

export default class App extends Component<{}> {
  render() {
    return <navigation/>;
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#fff',
  },
});

When I run react-native run-android I get an Invariant Violation which tells me "to view config not found or name navigation". And then all the sites where this violation happens.
Help please thanks.

A: In react native the component's name should begin with capital letter, so it will be:
const Navigation = StackNavigator({
    Home: { screen: HomeScreen },

});

and call it with capital:
export default class App extends Component<{}> {
  render() {
    return <Navigation/>;
  }
}

A: The name of any component must be capitalized. In your name, the component "navigation" is not capitalized. It should be "Navigation".


text:
Q: mod_rewrite to mask url I'm using WP, & I want to use a mod_rewrite rule such that all images from wp-content/uploads folder shows a different URL.
eg:
www.example.com/wp-content/uploads/image.jpeg --->
www.example.com/media/image.jpeg
I've placed a rule in .htaccess but it returns a 404 error.
RewriteRule ^wp-content/uploads/(.*)$ /media/$1 [L,NC,R]

Here's the .htaccess code.

A: Are you looking for something like this (all of these rules need to be before the default wordpress rules):
RewriteCond %{THE_REQUEST} \ /+wp-content/uploads/([^\?\ ]+)
RewriteRule ^ /media/%1 [L,R=301]

RewriteCond %{REQUEST_URI} ^/media/(.+)$
RewriteCond %{DOCUMENT_ROOT}/wp-content/uploads/%1 -f
RewriteRule ^media/(.+)$ /wp-content/uploads/$1 [L]


text:
Q: Definition of weak normality Let $X$ be a variety over a field $F$ of characteristic $p>0$.
The usual (not 100% sure) definition of weak normality should be

$X$ is weakly normal if whenever $f:Y\to X$ is a morphism of varieties
  satisfy
1) $f$ is a finite birational bijective morphism, and
2) for every $p\in
> X,q\in Y$, $f(q)=p$, the field extension $k(p)\to k(q)$ is purely
  inseparable.
Then, $f$ is an isomorphism.

In Brion and Kumar's book Frobenius splitting methods in Geometry and Representation Theory. The definition (1.2.3) of weak normality in the book is different, the condition 2) is dropped. Also, in the proof of the proposition (1.2.5) that every Frobenius split variety is weakly normal, I think the authors somehow use condition 2) in their proof.
I would want to know if condition 2) is redundant in the definition of weak normality, and I am happy to see a reference for a counter example of proposition (1.2.5) if we do not impose condition 2) in the definition. Thank you in advance.


text:
Q: checkbox check/uncheck using d3 I am having difficulty checking and unchecking checkboxes using d3 selection. The following code doesn't seem to work. I want all check boxes to be checked when 'check' is pressed, and all checkboxes unchecked when 'uncheck' is pressed.
<!DOCTYPE html>
<meta charset="utf-8">
<body>
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
<button type='button' onclick='checkAll()'>Check</button>
<button type='button' onclick='uncheckAll()'>Uncheck</button>

<script src="http://d3js.org/d3.v2.min.js?2.10.0"></script>

<script>
function checkAll(){
    d3.selectAll('input').attr('checked','true');
}
function uncheckAll(){
    d3.selectAll('input').attr('checked','false');
}
</script>
</body>

A: Use property() instead of attr():
function checkAll() {
    d3.selectAll('input').property('checked', true);
}
function uncheckAll() {
    d3.selectAll('input').property('checked', false);
}

From https://github.com/mbostock/d3/wiki/Selections#wiki-property:

Some HTML elements have special properties that are not addressable using standard attributes or styles. For example, form text fields have a value string property, and checkboxes have a checked boolean property. You can use the property operator to get or set these properties.

A: Change your uncheckAll function to set the checked attributes to null instead of false:
function uncheckAll(){
    d3.selectAll('input').attr('checked',null);
}

The checked attribute is either present, optionally set to checked="checked", or absent (no checked attribute at all).  Setting it to null will remove the attribute, in this case.

A: What you need to do is update the checked value of the element as follows:
d3.selectAll("input").each(function(d){
  if(d3.select(this).attr("type") == "checkbox")
    d3.select(this).node().checked = true;
});

This will ensure only all checkbox states are changed

A: You can limit your selection to only checkboxes by filtering the selection on the type attribute,
d3.selectAll("input[type=checkbox]").property("checked", true);

This avoids setting the checked attribute on non-checkbox inputs that are present.


text:
Q: $0 \lt r \lt s, a \in M$, show $\left\{ x \in M \middle| r \lt d(x,a) \lt s \right\}$ is open
$M$ is a metric space with metric $d$, given $0 \lt r \lt s, a \in M$, show $A=\{ x \in M : r < d(x,a)
 < s \}$ is open

I drew a picture and observed the above set looks like a washer. So our goal is to select a $t>0$ such that any point we pick in the open ball $B_t(x)$ where $x \in A$, is within $A$. More specifically, we want to show for a $y \in B_t(x)$, we get $r \lt d(y,a) \lt s$.
For this, this is my choice of $t$:
$t=min\left\{ d(x,a) - r, s - d(x, a) \right\}$
In the picture, it makes perfect sense but I am having trouble deriving the desired result: $r \lt d(y,a) \lt s$
Am I heading in the right direction?

A: You are in the right direction. The rest follows by triangle inequality: let $d(y,x) <t$. Then  $d(y,a) \leq d(y,x)+d(x,a) <t+d(x,a) \leq s$ and $d(y,a) \geq d(x,a)- d(y,x) >d(x,a)-t \geq r$.


text:
Q: Helping C++11 macros to run code with or without multithreading I'm trying to create a preprocessing macro that allows code to be multithreaded or not depending on runtime variable.
My first attempt was only a compile-time macro and worked, but the runtime version is not.
// Working compile-time version (defined in MultiThreadMacros.h)

#ifdef USE_MT

    #define MT_START(Thread)                              \
        std::atomic<bool> Thread ## Ret = true;           \
        std::thread Thread([&]()                          \
        {                                                 \
            std::atomic<bool> & __mtRet = Thread ## Ret;  \
            try{

    #define MT_END                                        \
            }catch(...){__mtRet = false;}                 \
    };

    #define MT_JOIN(Thread)                     \
        if (Thread.joinable()) Thread.join();   \
        if (Thread ## Ret){ throw; }

#else

    #define MT_START(Thread)
    #define MT_END

#endif

Here is a minimal use example
#define USE_MT
#include "MultiThreadMacros.h"

void function()
{
    int i = 0;
    int j = 0;

    MT_START(th1)
    {
        i += 2;

        MT_START(th3)
        {
            i += 4;
        }
        MT_END;

        MT_JOIN(th3);
    }
    MT_END;

    MT_START(th2)
    {
        j += 2;
    }
    MT_END

    MT_JOIN(th1);
    MT_JOIN(th2);
}

Now here's the conditional version. I'm creating a lambda from user code and executing the lambda if the condition is false, otherwise I'm launching a thread with the lambda.
The main difficulty here is that the compile-time version is already widely in use on the project and I'm trying to change macro without rewriting all previous code (which leads to those __mt references)
#define MT_START(Thread, Cond)                           \
    std::thread Thread;                                  \
    std::atomic<bool> Thread ## Ret = true;              \
    {                                                    \
        auto & __mtTh = Thread;                          \
        const bool __mtCond = Cond;                      \
        auto __mtLambda = [&]() -> void                  \
        {                                                \
            std::atomic<bool> & __mtRet = Thread ## Ret; \
            try {

#define MT_END                                           \
            }catch(...){__mtRet = false;}                \
        };                                               \
        if (__mtCond)                                    \
        {                                                \
            __mtTh = std::thread{__mtLambda};            \
        }                                                \
        else                                             \
        {                                                \
            __mtLambda();                                \
        }                                                \
    }

This last version makes unit tests to fail randomly, and I can't see why this last set of macros is different from the first one.
If anyone can help.
Thanks

A: In fact, macros are working, it was a use problem.


text:
Q: JavaFX: How to remove border from ProgressIndicator? This is nearly the same question as this, with one slight difference.  I also started seeing borders around my ProgressIndicator controls starting with Java 8u45, but I see them only when I select the 'user agent' stylesheet to Caspian.  It looks terrible, but I am quite invested in the Caspian stylesheet and unwilling to change it right now.  Here is some code that demonstrates the problem.  Obviously, you must uncomment the comment to see the problem.
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.BorderPane;
import javafx.scene.control.ProgressIndicator;
import javafx.stage.Stage;
import javafx.geometry.Insets;

public class ProgressIndicatorWithBorder extends Application {

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) {
        // this.setUserAgentStylesheet(Application.STYLESHEET_CASPIAN);
        ProgressIndicator pi = new ProgressIndicator();
        BorderPane borderPane = new BorderPane();
        borderPane.setCenter(pi);
        borderPane.setMargin(pi, new Insets(12));
        Scene scene = new Scene(borderPane, 640, 480);
        primaryStage.setScene(scene);
        primaryStage.show();
    }

}

A: Assumptions
As the questioner haven't mentioned, the ProgressIndicator could be used in two ways:

*

*inderminate (is running endless)

*determinate (counts percentage from 0 to 100)

Problem
The Problem is only related to the inderminate state, because the ProgressIndicator style for the spinner seems to conflict with the Datepicker style for it's spinner. So the JavaFX Developers had choosen to make a Bugfix in Java 8u40. This was done to modena.css, as it is the default CSS of JavaFX.
But in your case you want to use the old style caspian.css. So you have to do it the same way, as they've done it here.
Kevin Rushforth (one of the JavaFX guys) has made two screenshots of the behavior:
ProgressIndicator-Bad

ProgressIndicator-Good

Solution
Make an own stylesheet file. I called mine pibug.css. Set it on the ProgressIndicator as it's stylesheet. This will not override the other defaults already set in caspian.css.
pibug.css
.progress-indicator:indeterminate > .spinner {
    -fx-background-color: transparent;
    -fx-background-insets: 0;
    -fx-background-radius: 0;
}

But this is not all, if you want your Datepicker works well with caspian.css, you need to set the following style on your Datepicker:
dpbug.css
.date-picker-popup > * > .spinner {
    -fx-spacing: 0.25em; /* 3 */
    -fx-alignment: CENTER;
    -fx-fill-height: false;
    -fx-background-color: transparent; /* this line was added */
}

A: We must copy this part from modena.css:
.progress-indicator:indeterminate > .spinner {
    /** Applying to undo styling from .spinner, reported in RT-37965 */
    -fx-background-color: transparent;
    -fx-background-insets: 0;
    -fx-background-radius: 0;
}

It does not need to be modified.
(Note: NwDX's answer was useful because it got me pointed in the right direction, and so I tried to edit this fact into his answer.  But my edit was rejected on the basis that it deviated from the intent of original answer.)


text:
Q: ASP.NET MVC4 How to post and retrieve data unique to a specific user I have been learning how to use ASP.NET MVC4 and have been getting my head around authenticating users and user roles and posting data using the entity framework to SQL.
However I have not been able to find any guides/resources (maybe I don't know the correct term) for posting and retrieving data that is unique to an specific user. For example how would a user only see the entries that they created if it was a site that stored data that is personal to each user.
What patterns/designs does one use when trying to do this?

A: Creating a sandbox of data for a specific is usually tied to authentication. You can access this many ways through ASP.Net.
First of all, every user gets identified even if they never log in. They get a session identifier. It essentially creates a small place in memory for this user where you can store any user related information. Think of Sessions as walled gardens for each user.
 Session["UserFullname"]

This works, but realize Session is limited by time, so it is very volatile. Utilize it, but don't depend on it.
The next method is to authenticate a User. This is done using Cookies, but usually handled transparently for you by ASP.Net Membership or other authentication providers. To access the authenticated User you just need to use a simple line in your Controller actions.
// User is the property
User.Identity.Name

Both these methods can store information about your user that you would use to query data specific to them.
 Select * From Orders Where UserId = *User.Identity.Name*

Note that both Session and User are accessible through HttpContext.Current as well, as long as you are in a web environment.
 HttpContext.Current.User
 HttpContext.Current.Session

You won't need to access them this way unless you are not inside your Controller, or inside of another class that doesn't already give you access to the HttpContext. I don't recommend this way either, since your code could be used outside of a web application where HttpContext is not available.
I hope that makes sense, and please feel free to ask me questions.

A: This is not so much about mvc, but more about the problem of relating data to a specific user. You have to ask yourself, how would you identify a piece of data to a user.
The way you would do this is to tie the data to the user in the data store somehow.
In a relational database you would do this by having a User table and using the unique key on that table to insert data into another table such as Order. Order would then have a User Id.
When a user logs in, you could store that ID in session and use that to filter out orders based on the id.


text:
Q: FOSUserBundle : access session var in a custom email I am customizing the confirmation email sent after user registration.
My problem is that I can't access session vars in the email template.
Here is my code (similar to FOSUser documentation) :
{# src/Acme/DemoBundle/Resources/views/User/confirmation.email.twig #}

{% block subject %}Confirmation{% endblock %}

{% block body_text %}
{% autoescape false %}
Hello {{ user.username }} !

Your locale is : {{ app.session.locale }}

Click on the following link to confirm your registration : {{ confirmationUrl }}

Greetings,
the Acme team
{% endautoescape %}
{% endblock %}

{% block body_html %}
{% include 'AcmeDemoBundle:User:confirmation_email.html.twig' %}
{% endblock %}

The following line returns an exception :
Your locale is : {{ app.session.locale }}

Exception :
Variable "app" does not exist in ...

How can I access session var from this template ?
I also need to access config parameters (from parameters.ini).
My parameters are already in global Twig access, but no way to access them in this template.
Many thanks for your help !
A

A: TwigSwiftMailer class only expose User entity and confirmation url to the template. You have to extend the class and modify the methods. Then create the service and set as default mailer. You can check here for service definition.
Edit:
Sample implementation would be
The class .
//namespace declaration

class MySwiftMailer extends TwigSwiftMailer
{
    private $container;

    /**
     * @param Symofony\Component\DependencyInjection\ContainerInerface   $container
     */
    public function setContainer(ContainerInterface $container)
    {
        $this->container = $container;
    }

    public function sendConfirmationEmailMessage(UserInterface $user)
    {
        $template = $this->parameters['template']['confirmation'];
        $url = $this->router->generate('fos_user_registration_confirm', array('token' => $user->getConfirmationToken()), true);
        $context = array(
            'user' => $user,
            'container' => $this->container,
            'session' => $this->container->get('request')->getSession(), // expose session
            'confirmationUrl' => $url
        );

        $this->sendMessage($template, $context, $this->parameters['from_email']['confirmation'], $user->getEmail());
    }

    // implement sendResettingEmailMessage() in same way
}

Service declaration. Create a class named mailer.xml in your bundles Resources/config folder.
<?xml version="1.0" encoding="UTF-8"?>

<container xmlns="http://symfony.com/schema/dic/services"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">

    <services>

        <service id="fos_user.mailer.my_swift_mailer" class="FOS\UserBundle\Mailer\TwigSwiftMailer" >
            <argument type="service" id="mailer" />
            <argument type="service" id="router" />
            <argument type="service" id="twig" />
            <argument type="collection">
                <argument key="template" type="collection">
                    <argument key="confirmation">%fos_user.registration.confirmation.template%</argument>
                    <argument key="resetting">%fos_user.resetting.email.template%</argument>
                </argument>
                <argument key="from_email" type="collection">
                    <argument key="confirmation">%fos_user.registration.confirmation.from_email%</argument>
                    <argument key="resetting">%fos_user.resetting.email.from_email%</argument>
                </argument>
            </argument>

            <call method="setContainer">
                <argument type="service" id="service_container" />
            </call>

        </service>

    </services>

</container>

To include the loader.xml you have to include following lines in load method of YourBundle/DependencyInjection/YourBundleExtension.php
$xmlLoader = new XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
$xmlLoader->load("mailer.xml");

And in app/config.yml set the mailer.
# app/config/config.yml

fos_user:
    # ...
    service:
        mailer: fos_user.mailer.my_swift_mailer

Now in your template you can do {{ session.get('var') }} or {{ container.getParameter('any_param') }}

A: with
$session = $ this->get("session");

Have the same as app.session
So if you want you can send $session by RenderView()


text:
Q: multi threaded version of a python code I'm a beginner in python. I need to write a multi-threaded version of this code in such a way that I do not define K1, K2, K3 and assign them ip address and port number manually. In fact, I want each of k1,k2,and k3 be replaced by a separate thread and I can create as many 'k' as possible with different ip address and port number. I made several attempts and still no results. I appreciate if any one can help or give me a clue.
here is the code:
def main():
    global k1,k2,k3
    k1.register_handler('BSSID', lambda *args, **kwargs: handle_bssid(**kwargs))
    k1.register_handler('SSID', lambda *args,**kwargs: handle_ssid(**kwargs))
    k2.register_handler('BSSID', lambda *args, **kwargs: handle_bssid(**kwargs))
    k2.register_handler('SSID', lambda *args,**kwargs: handle_ssid(**kwargs))
    k3.register_handler('BSSID', lambda *args, **kwargs: handle_bssid(**kwargs))
    k3.register_handler('SSID', lambda *args,**kwargs: handle_ssid(**kwargs))

    try:
        while True:
            k1.listen()
            k2.listen()
            k3.listen()
            handle_merge()
    except KeyboardInterrupt:
        pprint(k1.protocols)
        pprint(k2.protocols)
        pprint(k3.protocols)

if __name__ == '__main__':
    address1 = ('192.168.1.7', 2502)
    k1 = KismetClient(address1)
    address2 = ('192.168.1.16', 2502)
    k2 = KismetClient(address2)
    address3 = ('192.168.1.27', 2502)
    k3 = KismetClient(address3)
    main()


text:
Q: Excel: Text mining using IF, ISNUMBER, SEARCH I'm trying to clean up job title data using the formula below:
=IF(OR(ISNUMBER(SEARCH({"admin","reception","account","finance","HR","public","sales","customer","creative","IT","human"},A1))),"",A1)

It should work by eliminating job titles with any of the texts specified in the quotes above. However, I've encountered an issue where it doesn't. In a case where the job title is Quantity Surveyor, the title contains none of the specified texts but Excel seems to reflect it as such. What am I not doing right here?
Quantity Surveyor Example

A: To extract the information you are looking for, this is the formula you want to use:
=IFERROR(IF(OR(ISNUMBER(SEARCH({"admin","reception","account","finance","HR","public","sales","customer","creative","human"},A1)),NOT(SEARCH("Quantity",A1))),"",A1),"")

A: Using countif you don't need to check for errors if they occur:
=IF(OR(COUNTIF(A1,{"admin","reception","account","finance","HR","public","sales","customer","creative","human"}))+COUNTIF(A1,"<>Quantity"),"",A1)

A: Select the part of formula of search, and then press F9. You will find the match result of 6, where it has original value of 'IT', it means Quantity, has IT.

I really donot know why there is negative vote as not useful.

Here is the formula to solve your problem
=IFERROR(LOOKUP(1,0/FIND({"admin","reception","account","finance","HR","public","sales","customer","creative","IT","human"},A1)),A1)

Of course, it is better to define a range instead of hard code {}, like below
=IFERROR(LOOKUP(1,0/FIND($J$2:$J$7,A2),$K$2:$K$7),A2)


text:
Q: Continue a Do-Until loop until someone put something different than 1 to 9 The problem is that the loop is working the first time but it stops after and I want it to continue like this until the input is different than 1 to 9.
do
{
    Show-Menu
    $selection = Read-Host "Please choose an option"
    switch ($selection)
    {
        '1' {
            Get-ChildItem
        } '2' {
            get-host|Select-Object
        } '3' {
            Get-NetIPConfiguration -Detailed
        } '4' {
            Get-NetRoute
        } '5' {
            Get-DnsClientCache
        } '6' {
            Get-Date -UFormat "%A %B/%d/%Y %T %Z"
        } '7' {
            Get-ItemProperty -Path HKLM:\
        } '8' {
            Stop-Service -Name Spooler -Force
            Restart-Service -Name Spooler -Force
        } '9' {
            Get-Service | Where-Object {$_.Status -eq "Running"}
        }
    }
    pause
}
until ($selection -ne 1..9)

I tried a while loop but it did an infinite loop...

A: The only issue with your code is the use of -ne:
until ($selection -ne 1..9)

Instead of -notin:
until ($selection -notin 1..9)

-notin is meant to compare if a scalar (a single value) in the LHS (left-hand side) is not present in a collection on the RHS (right-hand side), $selection -notin 1..9 will return $true when $selection is other than 1 to 9.
On the other hand -ne is mostly meant to test inequality, even though it can work as a filter when the LHS is a collection, i.e.:
'foo', 'bar', 'baz' -ne 'foo' # => 'bar', 'baz'

However as you had it before, you were testing if a single value ($selection) was not equal to an array (1..9) which will always be $true hence your loop ended after its first iteration.

A: Here's another way you could have done this.
function Show-Menu
{
    Param()

    $selection = Read-Host 'Please choose an option'

    switch ($selection)
    {
        '1' {
            Get-ChildItem
        } '2' {
            get-host|Select-Object
        } '3' {
            Get-NetIPConfiguration -Detailed
        } '4' {
            Get-NetRoute
        } '5' {
            Get-DnsClientCache
        } '6' {
            Get-Date -UFormat '%A %B/%d/%Y %T %Z'
        } '7' {
            Get-ItemProperty -Path HKLM:\
        } '8' {
            Stop-Service -Name Spooler -Force
            Restart-Service -Name Spooler -Force
        } '9' {
            Get-Service | Where-Object {$_.Status -eq 'Running'}
        }
    }
}
do {Show-Menu}
until ($selection -match '1-9')

# Results
<#
Please choose an option: 0
Please choose an option: 10
Please choose an option: 20
Please choose an option: 11
Please choose an option: 4

# Results
<#
ifIndex DestinationPrefix                              NextHop                                  RouteMetric ifMetric PolicyStore
...
#>

The way your code block is written now, even with the prudent correction offered by 'Santiago Squarzon', it would still exit on numbers not in that array.
Here's what I mean.
do
{
    Show-Menu
    $selection = Read-Host "Please choose an option"
    switch ($selection)
    {
        '1' {
            Get-ChildItem
        } '2' {
            get-host|Select-Object
        } '3' {
            Get-NetIPConfiguration -Detailed
        } '4' {
            Get-NetRoute
        } '5' {
            Get-DnsClientCache
        } '6' {
            Get-Date -UFormat "%A %B/%d/%Y %T %Z"
        } '7' {
            Get-ItemProperty -Path HKLM:\
        } '8' {
            Stop-Service -Name Spooler -Force
            Restart-Service -Name Spooler -Force
        } '9' {
            Get-Service | Where-Object {$_.Status -eq "Running"}
        }
    }
}
until ($selection -notin  1..9)
# Results
<#
until ($selection -notin  1..9)
Please choose an option: 0
Please choose an option: 10
# the do exited

until ($selection -notin  1..9)
Please choose an option: 11
Please choose an option: 110
# the do exited
#>

A: Yes, you need a While loop. The Do itself does nothing.
You also need an exit condition to break out of the loop. Try
switch(...)
{
<# switch options #>
default {break}
}


text:
Q: 'in-place' string modifications in Python In Python, strings are immutable.
What is the standard idiom to walk through a string character-by-character and modify it?
The only methods I can think of are some genuinely stanky hacks related to joining against a result string.
--
In C:
for(int i = 0; i < strlen(s); i++)
{
   s[i] = F(s[i]);
}

This is super expressive and says exactly what I am doing. That is what I am looking for.

A: I'd say the most Pythonic way is to use map():
s = map(func, s) # func has been applied to every character in s

This is the equivalent of writing:
s = "".join(func(c) for c in s)

A: The question first states that strings are immutable and then asks for a way to change them in place. This is kind of contradictory. Anyway, as this question pops up at the top of the list when you search for "python string in-place modification", I'm adding the answer for a real in place change.
Strings seem to be immutable when you look at the methods of the string class. But no language with an interface to C can really provide immutable data types. The only question is whether you have to write C code in order to achieve the desired modification.
Here python ctypes is your friend. As it supports getting pointers and includes C-like memory copy functions, a python string can be modified in place like this:
s = 16 * "."
print s
ctypes.memmove(ctypes.c_char_p(s), "Replacement", 11)
print s

Results in:
................
Replacement.....

(Of course, you can calculate the replacement string at runtime by applying a function F to every character of the original string. Different ways how to do this have been shown in the previous answers.)
Note that I do not in any way encourage doing this. However, I had to write a replacement for a class that was mapped from C++ to python and included a method:
int readData(char* data, int length)

(The caller is supposed to provide memory with length bytes and the method then writes the available data -- up to length -- into that memory, returning the number of bytes written.) While this is a perfectly sensible API in C/C++, it should not have been made available as method of a python class or at least the users of the API should be made aware that they may only pass mutable byte arrays as parameter.
As you might expect, "common usage" of the method is as shown in my example (create a string and pass it together with its length as arguments). As I did not really want to write a C/C++ extension I had to come up with a solution for implementing the behavior in my replacement class using python only.

A: string.translate is probably the closest function to what you're after.

A: Don't use a string, use something mutable like bytearray:
#!/usr/bin/python

s = bytearray("my dog has fleas")
for n in xrange(len(s)):
    s[n] = chr(s[n]).upper()
print s

Results in:
MY DOG HAS FLEAS

Edit:
Since this is a bytearray, you aren't (necessarily) working with characters. You're working with bytes. So this works too:
s = bytearray("\x81\x82\x83")
for n in xrange(len(s)):
    s[n] = s[n] + 1
print repr(s)

gives:
bytearray(b'\x82\x83\x84')

If you want to modify characters in a Unicode string, you'd maybe want to work with memoryview, though that doesn't support Unicode directly.

A: Strings are iterable and can be walked through like lists.  Strings also have a number of basic methods such as .replace() that might be what you're looking for.  All string methods return a new string. So instead of modifying the string in place you can simply replace its existing value.
>>> mystring = 'robot drama'
>>> mystring = mystring.replace('r', 'g')
>>> mystring
'gobot dgama'

A: Assigning a particular character to a particular index in a string is not a particularly common operation, so if you find yourself needing to do it, think about whether there may be a better way to accomplish the task. But if you do need to, probably the most standard way would be to convert the string to a list, make your modifications, and then convert it back to a string.
s = 'abcdefgh'
l = list(s)
l[3] = 'r'
s2 = ''.join(l)

EDIT: As posted in bstpierre's answer, bytearray is probably even better for this task than list, as long as you're not working with Unicode strings.
s = 'abcdefgh'
b = bytearray(s)
b[3] = 'r'
s2 = str(b)

A: The Python analog of your C:
for(int i = 0; i < strlen(s); i++)
{
   s[i] = F(s[i]);
}

would be:
s = "".join(F(c) for c in s)

which is also very expressive.  It says exactly what is happening, but in a functional style rather than a procedural style.

A: you can use the UserString module:
 >>> import UserString
... s = UserString.MutableString('Python')
... print s
Python
>>> s[0] = 'c'
>>> print s
cython

A: >>> mystring = "Th1s 1s my str1ng"
>>> mystring.replace("1", "i")
'This is my string'

If you want to store this new string you'll have to mystring = mystring.replace("1", "i"). This is because in Python strings are immutable.

A: If I ever need to do something like that I just convert it to a mutable list
For example... (though it would be easier to use sort (see second example) )
>>> s = "abcdfe"
>>> s = list(s)
>>> s[4] = "e"
>>> s[5] = "f"
>>> s = ''.join(s)
>>> print s
abcdef
>>>
# second example
>>> s.sort()
>>> s = ''.join(s)

A: Here is an example using translate to switch "-" with "." and uppercase "a"s
>>> from string import maketrans
>>> trans_table = maketrans(".-a","-.A")
>>> "foo-bar.".translate(trans_table)
'foo.bAr-'

This is much more efficient that flipping to byte array and back if you just need to do single char replacements

A: def modifyIdx(s, idx, newchar):
    return s[:idx] + newchar + s[idx+1:]

A: You can use StringIO class to receive file-like mutable interface of string.

A: I did that like this:
import tempfile
import shutil

...

f_old = open(input_file, 'r')
with tempfile.NamedTemporaryFile() as tmp:
    for line in f_old:
        tmp.write(line.replace(old_string, new_string))
    f_old.close()
    tmp.flush()
    os.fsync(tmp)
    shutil.copy2(tmp.name, input_file)
    tmp.close()

A: Here's my pythonic solution for In-place string reversal.
Accounts for white spaces too.
Note: It won't match any special characters if included in input_string except for underscore ( '_' )
i/p - "Hello World" => o/p - "olleH dlroW"
import re

def inplace_reversal(input_string):

    list_of_strings = re.findall(r'\s|(\w+)',input_string)

    output_string= ''

    for string in list_of_strings:

        if string == '':

            output_string += ' '

        else:

            output_string += string[::-1]

    return output_string

print(inplace_reversal('__Hello__ __World__         __Hello__       __World__ '))

>>> __olleH__ __dlroW__         __olleH__       __dlroW__


text:
Q: What locationManager.requestLocationUpdates do? locationManager.requestLocationUpdates(provider, 2500, 2,  this);
You need to walk 2 meters in every 2.5seconds to request for new location?. Correct me if i am wrong. Thank you.

A: *

*minTime – Wise choice of value for minTime will help you reduce
power consumption. What you need to keep in mind is that elapsed
time between location updates will never be less than minTime, but
it can be greater, because it is influenced by the implementation of
each given Provider and the update interval requested by other
running applications.

*minDistance – Unlike minTime this parameter can be turned off by
setting it's value to 0. However, if minDistance is set to a value
greater than 0, location provider will only send updates to your
application if location has changed at least by given distance. This
parameter is not a great power saver like minTime, but it should be
kept in mind although.

These two parameters work in AND relation, so in order to receive location update, both of their conditions need to be achieved (i.e. more then 5 seconds has passed, and the distance change is greater than 10 meters).
You can check this link:
https://blog.codecentric.de/en/2014/05/android-gps-positioning-location-strategies/


text:
Q: Pointer typecasting in c I am writing an implementation of graphs in C language. I came across a situation where I am not able to figure out the reason for the way the compiler is behaving with a pointer typecast warning.
Here are the structures;
#define MAXV 10
typedef struct {
    int y;
    int weight;
    struct edgenode *next;
} edgenode;

typedef struct {
   edgenode *edge[MAXV+1];
   int degree[MAXV+1];
   // other info of graph
} graph;

// operation in some other function
p->next = g->edge[x];

I got a pointer typecast warning[enabled by default] when I do this kind of operation.
I was not able to remove this warning even after trying to typecast with every possible cast.
Finally I made a code change in the structure and suddenly the warning was gone.
The structure code change was this:-
typedef struct edgenode {   // note that I have added structure name here
    // same as above definition
} edgenode;

// operation in some other function
p->next = g->edge[x];

Now the warning is gone and code runs without any warnings.
I do not understand why is this happening; can anybody help me with this problem?

A: The problem is here:
typedef struct {
    int y;
    int weight;
    struct edgenode *next;
} edgenode;

It is not clear what type struct edgenode *next; is referring to (it doesn't matter; somewhere, presumably, there's a struct edgenode defined), but it is not this structure because it has no tag.  You need:
typedef struct edgenode
{
    int y;
    int weight;
    struct edgenode *next;
} edgenode;

Now the pointer refers to another structure of this same type. So, the fix you found was the correct fix for your problem.
Remember: a typedef is an alias (alternative name) for an existing type.  You created a type name edgenode, but you had not defined the type struct edgenode.  You don't have to fully define a structure type before you create pointers to it; this can be a good way of creating 'opaque types'.
The other way to define things is:
typedef struct edgenode edgenode;

struct edgenode
{
    int y;
    int weight;
    edgenode *next;
};

This says that the type name edgenode is an alias for a struct edgenode; the structure definition then tells the compiler what a struct edgenode looks like.


text:
Q: cakephp find all record in group of member_id with order of id I want a cake php find query to find all record from comments table in order of id desc but all comments should be in group of member_id.
Suppose there are two Member with id 20 and 21 and last comment is by member with id 21. both member have posted multiple comments in different time.
So now i want all comments which are latest. means if latest comments is posted by member with id 21 then show all comments of member with id 21 and then all comments of another and so on.
I have tried group on member_id but it givs only single record for a member.
id  Member_id   comment
1   20           abc
2   21           abc
3   20           abc
4   20           abc
5   21           abc

id  Member_id   comment
5   21           Abc
2   21           Abc
4   20           Abc
3   20           abc
1   20           abc

its my records in table and i want like below
I want a cake php find query to find all record from comments table in order of id desc but all comments should be in group of member_id.
Suppose there are two Member with id 20 and 21 and last comment is by member with id 21. both member have posted multiple comments in different time.
So now i want all comments which are latest. means if latest comments is posted by member with id 21 then show all comments of member with id 21 and then all comments of another and so on.
I have tried group on member_id but it givs only single record for a member.
its my records in table and i want like below
here last comment is by member 21 so it will show all data of that member then member 20 and so on
Thanks
here last comment is by member 21 so it will show all data of that member then member 20 and so on
Thanks

A: I don't believe this can easily be done with one single query (that would convert simply to a find). I would use a two step process:

*

*Get the most recent comment's member_id

*Query all comments sorting
based on that value.

Assuming this is written from the Comment model:
$lastCreated = $this->find('first', array(
        'order' => array('Comment.id' => 'desc')
    ));

$results = $this->find('all', array(
        'order' => array('Comment.member_id = ' . $lastCreated['Comment']['member_id']. ' desc'
                    ,'Comment.id' => 'desc')
    ));

The goal of the second find statement is have a SQL statement such as:
SELECT *
FROM comments AS Comment
ORDER BY Comment.member_id = 21 desc
        ,Comment.id desc;


text:
Q: Open VPN copying files very slow This is my first experience with setting up a VPN.
I have Open VPN running at my work network on a firewall/router that uses the PFsense admin software.
I connected to the VPN from my home network successfully.
When I tried to copy a 500k file from a device on the remote network to my home computer it took a very long time (5 minutes or more). My internet connection is fast at both locations, so I'm not sure why this would be.
Is it because of the encryption, or some of the network settings? This is all pretty new to me.
Here is a link to the tutorial I followed.
https://www.highlnk.com/2013/12/configuring-openvpn-on-pfsense/
Also my home computer is a mac running the Viscosity OpenVPN client.

A: If you used UDP as your transport protocol, check the firewall(s) for UDP rate limiting or DoS thresholds.  Add rules or exceptions for the VPN traffic accordingly.
Also, try lowering MTU for the VPN connection to something that will allow for VPN encapsulation.  A value like 1300 should be more than adequate for testing purposes.

A: If I use afp://x.x.x.x it works much faster than smb://x.x.x.x
under mac os finder > connect to server


text:
Q: Animation is stopping script I have a script that makes the swamp track and follows the player. It workes fine. But when I ad an animation to the enemy (a swamp jumping towards the player) it doesn't move.
I've tried removing the position under animation, but then the swamp does not jump. It just scales. This does though fixe the problem with not following the player. so I think the problem is the animation on the position.
public class EnemyAI : MonoBehaviour
{
    public float speed;

    private Transform playerPos;

void Update()

    {
        transform.position = Vector2.MoveTowards(transform.position, playerPos.position, speed * Time.deltaTime);

    }

}

A: Animation is the reason that takes over the position and the script becomes useless. As you have mentioned it jumps (Y-axis) and the position in the animator controller takes over. I would suggest try doing two things:
(a) Add a parent to this swamp gameObject and add animation for jumping to this parent
(b) Add MoveTowards() function to Swamp gameObject.
Through this, the parent gameObject will only perform animation of jumping and the child gameObject will perform MoveTowards() function.


text:
Q: chmod setting using find command not working root@VM01:~# find /var/log -type f | xargs chmod g-wx,o-rwx
chmod: cannot access '/var/log/journal/11a7df635f034e01b3405209ca9f4260/system.journal': No such file or directory
it is working without find command
root@VM01:~# chmod g-wx,o-rwx /var/log/journal/11a7df635f034e01b3405209ca9f4260/system.journal
root@VM01:~#


text:
Q: If the sum of the angles of elevation is $90^\circ$, what is the height of the Helicopter? A mathematical puzzle. I was playing a flight simulator game and attaching some cargo on the ground to a helicopter, which was hovering above ground level. There were 3 individual pieces of cargo at different distances from the helicopter. After thinking about it for a while, I came up with this nice little puzzle:

A Helicopter hovering at some height is collecting 3 cargo bags on the ground. Bag A is 1 meter away from the helicopter (horizontal distance). Bag B is 2 meters away (horizontal distance) and Bag C is 3 meters away (horizontal distance). The harness wire connecting the helicopter and the cargo bags form some angle of elevation. If the sum of the angles of elevation of the cargo bag is $90^\circ$, what is the height of the helicopter?

I thought about this problem for a while and I came up with one solution to this, as I'll share my attempt below. I want to ask, are there any other ways to approach this with? Perhaps with less trigonometry? Please share your attempts too!
Here's how I approached it:
Let the height of the helicopter be $x$ meters, and I'll refer to the angles of elevation of the wired connecting Bags A, B and C with these letters respectively. now let's take the tangent of every angle, we'll have:
$$\tan A=\frac{x}{1}$$
$$\tan B=\frac{x}{2}$$
$$\tan C=\frac{x}{3}$$
We know that:
$$A+B+C=\frac{\pi}{2}$$
$$A+B=\frac{\pi}{2}-C$$
$$\tan (A+B)=\cot C$$
$$\frac{\tan A +\tan B}{1-\tan(A)\tan(B)}=\frac{1}{\tan C}$$
$$\tan(A)\tan(C) +\tan(B)\tan(C)+\tan(A)\tan(B)=1$$
Now substituting the values for tangent that we derived above, we get:
$$\frac{x^2}{3}+\frac{x^2}{6}+\frac{x^2}{2}=1$$
$$2x^2+x^2+3x^2=6$$
$$6x^2=6$$
Therefore the height of the helicopter is $x=1$ meters. Are there any other ways to solve this?

A: Alternative approach:
(Actually not that different from the original poster's, and perhaps not as elegant as the original poster's).
Let $a,b,c$ denote the three angles.
Then, $~\tan(a) = (h), ~\tan(b) = (h/2), ~\tan(c) = (h/3).$
You need to determine $h$ so that $\tan(a + b + c) = \infty.$
$$\tan(a+b) = \frac{\frac{3h}{2}}{1 - \frac{h^2}{2}} = \frac{3h}{2 - h^2}.$$
$$\tan(a+b+c) = \frac{\frac{3h}{2 - h^2} + \frac{h}{3}}{1 - \left[ ~\frac{3h}{2 - h^2} \times \frac{h}{3}  ~\right]}$$
$$= \frac{\frac{\text{something}}{(2-h^2) \times 3}}{\frac{6 - 6h^2}{(2-h^2) \times 3}} = \frac{\text{something}}{6 - 6h^2}.$$
So, $h$ must be a positive real number that satisfies $6 - 6h^2 = 0.$  This implies that $h$ must equal $1$.


text:
Q: How to set permissions for CRUD operations in ModelViewSet Django I have a viewset for model News.
I want to do next permissions:
All people can see news.
Only authorized users and admin can create news.
Only owner and admin can update news.
Only admin can delete news.
How can I set different permissions for each operation? For create I want to use: IsAuthenticated and IsAdminUser. For update I want to use IsAdminUser and I create my own permission for owner. For delete I want to use also IsAdminUser.
view:
class NewsViewSet(viewsets.ModelViewSet):
    queryset = News.objects.all()
    serializer_class = NewsSerializer

permission:
class IsOwnerOrReadOnly(permissions.BasePermission):
    def has_object_permission(self, request, view, obj):
        if request.method in permissions.SAFE_METHODS:
            return True

        return obj.author == request.user

A: class Viewset(BaseModelViewSet):enter code here
queryset = Model.objects.all()
serializer_class = ModelSerializer
permission_classes_by_action = {
    'create': (permissions.IsAdminUser,),
    'list': (permissions.IsAuthenticatedOrReadOnly,),
    'retrieve': (permissions.AllowAny,),
    'update': (permissions.AllowAny,),
    'destroy': (permissions.IsAdminUser,),
    'search': (permissions.IsAuthenticated,)

Like this you can use the pre-built permission or create custom permission class


text:
Q: how to generate a dataset of correlated variables with different distributions? For teaching purposes, I need to generate random datasets of correlated random variables with different distributions. I have tried corr2data in Stata but it will not allow me to specify max and min values of the variables to be generated, just means, sd's and the covariance matrix. Therefore, I need to do messy adjustments after generation of the data. Various other details annoy me with corr2data. Is there a simpler way of doing this with MATLAB? I am not as familiar with this software as I am with Stata.

A: If you have access to Statistics Toolbox as well as MATLAB, you can use the copula functionality to do this fairly easily. Using a copula, you can specify the marginal distributions of each variable, and a correlation structure between the variables.
You can then generate random numbers from the copula, fit it to data etc. as well.
See in the MATLAB documentation:
Copulas: Generate Correlated Samples


text:
Q: How to JOIN SQL Tables I cant seem to figure out how to join these two table to execute and return all I need in one payload through a single query. Any Help would be very appreciated.
As you will see everything work with the first half of the query if I place a ; at the end of the closing parenthesis following the "IN".
However when I go to join this table with another table propA_Photos, MySQL throws and error. I only want the propA_Photos.photo column joined with the above in one query.
What am I doing wrong?
SELECT propA.list_id, propA.list_key, propA.list_value
FROM propA
where list_id = '20141118214124325535000000'
    AND list_key IN ('LIST_1', 'LIST_22', 'LIST_33', 'LIST_31', 'LIST_34', 'LIST_35', 'LIST_36', 'LIST_37', 'LIST_39', 'LIST_40', 'LIST_43', 'LIST_41', 'LIST_46', 'LIST_47')
INNER JOIN propA_Photos.photo;

A: You're missing a join clause, I'm not sure if your database is okay with that.
SELECT
    propA.list_id, propA.list_key, propA.list_value
FROM propA
INNER JOIN propA_Photos.photo
        ON propA_Photos.<<Attr1>> = propA.<<Some_Attribute>>
WHERE list_id = '20141118214124325535000000'
  AND list_key IN (.. lot of stuff... )

A: When joining tables you need to adhere to a specific syntax and order of operators.
The where clause should follow the join clauses and you need to specify the condition that determines how the tables should be joined using an on clause.
You probably want something like this:
SELECT propA.list_id, propA.list_key, propA.list_value
FROM propA
INNER JOIN propA_Photos.photo ON propA.some_column = propA_Photos.some_column
-- the join should likely by using primary key = foreign key
WHERE list_id = '20141118214124325535000000'
  AND list_key IN (
    'LIST_1',  'LIST_22', 'LIST_33', 'LIST_31',
    'LIST_34', 'LIST_35', 'LIST_36', 'LIST_37',
    'LIST_39', 'LIST_40', 'LIST_43', 'LIST_41',
    'LIST_46', 'LIST_47'
    );


text:
Q: Question about proof in Jech's The axiom of choice ($AC_\omega$) I'm looking at the following in Jech's The Axiom of Choice on page 20:

2.4.1. Example: The Countable Axiom of Choice implies that every infinite set has a countable subset.
Proof.  Let $S$ be an infinite set.  Consider all finite one-to-one finite sequences $$\langle a_0 , a_1 , \ldots , a_k \rangle$$ of elements of $S$.  The Countable Axiom of Choice picks out one $k$-sequence for each natural number; more exactly: $$\mathscr{F} = \{ A_k : k \in \omega \},$$ where $$A_k = \{ \langle a_0 , \ldots , a_k \rangle : a_0 , \ldots , a_k\text{ distinct elements of }S \},$$ and $\mathscr{F}$ has a choice function: $f ( A_k ) \in A_k$ for all $k$.  The union of all the chosen finite sequences is obviously countable.

And I'm wondering if I can instead prove it as follows:
Let $S$ be an infinite set, that is, $|S| \ge |\omega|$. By the definition of $|S| \ge |\omega|$ there is an injection $f: \omega \hookrightarrow S$. Then $f(\omega) \subseteq S$ yields the desired result.
I think yes but I might be missing something. Thanks for your help.

A: It is likely that Jech is using the following definition: A set $X$ is infinite set iff it is not finite (i.e., there is no natural number $n$ such that $X$ is in one-to-one correspondence with $\{ 0 , \ldots , n-1 \}$).  (I cannot find a statement of this definition in The Axiom of Choice, but Jech does use it in his Set Theory tome.)  In the presence of some amount of Choice, being infinite is equivalent to $\aleph_0 \leq | X |$, but this is not a definition.
A set $X$ such that there is no injection $\mathbb{N} \to X$ is called a Dedekind finite set.  It is consistent with ZF+$\neg$AC that there are infinite Dedekind finite sets.  What this Example shows (once Dedekind finiteness is defined on p.25) is that under the assumption of Countable Choice all Dedekind finite sets are finite.

A: We say that $S$ is infinite iff $|S|\not<|\omega|.$ Without some choice principle, we can't conclude that all infinite sets admit a countably infinite subset, as it's entirely possible that $S$ and $\omega$ are of incomparable cardinality.
The least choice principle sufficient to the task is: "$\omega$ is of comparable cardinality with all sets," a strictly weaker principle than $\text{AC}_\omega$. That is, any stronger principle will do the job, but weaker principles will fail to be able to prove that infinite sets have countably infinite subsets. On the other hand, if every infinite set has a countably infinite subset, then $\omega$ is of comparable cardinality with all sets. Thus, the aforementioned choice principle is actually logically equivalent to the result that Jech proves with $\text{AC}_\omega$.
We say that sets with a countably infinite subset are "Dedekind-infinite" or just "D-infinite." D-infinite sets are always infinite, but without a choice principle at least as strong as the one mentioned above, there may be infinite, D-finite sets.
For some equivalent statements to the choice principle I mentioned above, see here.


text:
Q: Solid state relay for home lights application My application is controlling home lights. I want to use relays to switch lights on and off. My circuit should work on all kind of lights such as neon lights, halogen lights, strobe lights and others. I should decide what kind of relay I have to use, EMR or SSR. I have read about solid state relays and I encountered two issues.
First, I know one of the limitations of the SSR is the leakage current. If it is 5 mA for example, the neon light my not turn completely off. The leakage current may be sufficient to keep the light on. Right?
Second, some types of strobe lights incorporate a diode in series with the coil or filament. This causes the light to behave as a half-wave rectifier. There is an RC circuit in parallel with the output of SSR. The capacitor in this circuit cannot discharge through the series diode, causing a voltage to appear across the SSR terminals. I know that SSR must see a zero voltage across the terminals to come on, it can't turn on again in this situation. Right?
what is your final recommendation for my specific application. I am not really concerned about the life time because typically the number of contacts may not exceed 10 per day

A: This sounds like a good application for regular old mechanical relays.  They won't care about the direction of current, won't have a offset voltage, and their off leakage is zero in a practical sense.
Relays that can switch house power are common and available in a variety of coil voltages.  Since you say you want to switch "lights", it seems like the current will be low.  Relays that can do this will be small and available in coils meant to be driven from 5 V.  This means you can run them from the same power supply as the processor doing the controlling, but not that the relays can be run directly from a digital output.  You will need a transistor controlled by the digital output that in turn controls the larger relay coil current.  Don't forget the reverse diode accross the relay coil, else you'll end up with fried transistors.


text:
Q: PHP File Uploading fail I'm trying to create a script that would allow the user to upload images onto the server. I've implemented the script,though once I tried to upload an image, the script follows through but no image appears on the server. Any ideas?
PHP:
<?php
require_once("connect.php");
ini_set('display_errors', 'on');
error_reporting(E_ALL);

echo __LINE__;

$allowedExtensions = array("jpg", "jpeg", "gif", "png");
$extension = end(explode(".", $_FILES["image"]["name"]));
print_r($_FILES['image']);
echo $extension;

if((($_FILES["image"]["type"] == "image/gif") || ($_FILES["image"]["type"] == "image/jpeg") || ($_FILES["image"]["type"]=="image/pjpeg") || ($_FILES["image"]["type"] == "type/png")) && ($_FILES["image"]["size"] <= 102400) && in_array($extension, $allowedExtensions)) {

        echo __LINE__;
        if($_FILES["image"]["error"] > 0) {
                $fileUploadFail = true;
        }
        else {
               chmod("uploadImages/", 0755);
               move_uploaded_file($_FILES["image"]["tmp_name"], "uploadImages/" . $_FILES["image"]["name"]);
        }

} else {
        $fileUploadFail = true;
        echo __LINE__;
}
        $fileName = $_FILES["image"]["name"];
        chmod("uploadImages/", 0600);
        echo __LINE__;
        /*if($fileUploadFile) {
              header("Location: uploadArt.php");
        }
        else {
             $title = $_POST['title'];
             $description = $_POST['description'];
             mysql_query("INSERT INTO `Art`(`File Name`, `Description`, `uploadLocation`, `Index`) VALUES('$title', '$description', 'uploadImages/$fileName', '')");
              header("Location: viewArt.php");
        }*/
  ?>

Output I receive:
6Array ( [name] => comps_tech.png [type] => image/png [tmp_name] => /tmp/phpgQKnMJ [error] => 0 [size] => 661 ) png2529

HTML:
<form id = "uploadDesigns"  enctype="multipart/form-data" name="Upload" method="post" action="fileUpload.php" >
Enter name of design:<input type = "text" id = "title" name = "title" size="50">

Upload image:
(max 100KB) <input type = "file" id = "image" size = "51" name = "image">

Description: <textarea id = "description" name = "description" rows = "4" cols = "20"></textarea>

<button type="submit">Submit Art</button>
</form>

Thanks!

A: You have
input type = "file" id = "image" size = "51" name = "image"

But are referencing
$_FILES["file"]["type"]

The "file" in the $_FILES refers to the name of the file input. This is "image", not "file"

The complete the answer (after fixing other issues and debugging); the last error is that
$_FILES["image"]["type"] == "image/png"

needs to be added to the if statement.

A: You need to give write permissions for uploadImages.

A: Ur file directory structure should b like this.
1) test.php
2) uploadImages/ (this  folder needs to be created by u ).


text:
Q: Is a long list of parameter checks an anti-pattern? Background:  I'm working on an application that will manage backup generators.  These generators need to be able to be "linked" together.  For example, Generator B might serve as a backup for Generator A.  If A fails, then the software turns B on.  Or they might be linked in a load-sharing configuration, where Generator A and B run together, and share the load.
I'm making a function that will make the link, given 2 generators and the type of link desired.
public void LinkGenerators(Generator A, Generator B, Type linkType);

In writing my tests, I've come with a large number of invalid parameter configurations.  My LinkGenerators function looks like this:
public void LinkGenerators(Generator A, Generator B, Type linkType)
{
     if (linkType.BaseType != typeof(Link))
     {
        throw new ArgumentException("linkType is not a valid link type");
     }
     if (linkAlreadyExistsFor(A, B))
     {
        throw new InvalidOperationException("Link for A and B already exists");
     }
     if (A.Equals(B) || B.Equals(A))
     {
        throw new InvalidOperationException("A and B cannot be the same generator");
     }
     if (A == null || B == null || linkType == null)
     {
        throw new ArgumentException("Cannot pass a null argument");
     }
     .....
     //Actually make the link after making sure all the arguments are valid.
}

Most of the LinkGenerator functions consists of verifying that the parameters are good.  The actual link creation takes 2 lines of code.  There's a bit of business logic (verifying that link doesn't already exist and that the generators are not the same) mixed in with a bit functional logic (making sure that the linkType derives from Link, arguments aren't null...), and makes me.......uncomfortable.
Is a long list of parameter checks an anti-pattern or a code smell?  And if so, what can one do about it?
(Just to make this clear to close-voters probably misunderstanding the question: this is not a question about "coding style for conditions" like this one).

A: When you need to check conditions that aren't business rules, that's where it gets suspect and a bit smelly. I try to avoid those where possible.
Some of your tests seem suspect:
 if (linkType.BaseType != typeof(Link))

This looks like a check that should be made by the type system. i.e. its a type restriction and ideally your function signature should, as much as possible, only accept parameters of the correct type. How to do that depends on more details of what you are doing.
 if (A.Equals(B) || B.Equals(A))

Why do you feel the need to check it both ways? If A.Equals(B) != B.Equals(A) you are in for a world of hurt.
 if (A == null || B == null || linkType == null)

There is no way to tell which parameter was null from the resulting exception. It's also done after the other checks which means that you probably already caused an exception trying to dereference a null parameter.
I avoid null checks in general. Typically, they aren't that helpful because the code in question will end up throwing an exception after tripping on the null anyways and I haven't gained anything by strewing null checks throughout my code. If you do insist on a null check, I suggest extracting it into a utility function.

A: I don't think what you've done here is that bad, although it could be moved to a separate procedure to keep things neater:
public void LinkGenerators(Generator A, Generator B, Type linkType)
{
     //simplest way to refactor is to just not catch the exception that's
     // thrown by the validation function.
     validateLinkGeneratorArgs(A, B, linkType);
     .....
     //Actually make the link after making sure all the arguments are valid.
}

private void validateLinkGeneratorArgs(Generator A, Generator B, Type linkType)
{
     if (linkType.BaseType != typeof(Link))
     {
        throw new ArgumentException("linkType is not a valid link type");
     }
     if (linkAlreadyExistsFor(A, B))
     {
        throw new InvalidOperationException("Link for A and B already exists");
     }
     if (A.Equals(B) || B.Equals(A))
     {
        throw new InvalidOperationException("A and B cannot be the same generator");
     }
     if (A == null || B == null || linkType == null)
     {
        throw new ArgumentException("Cannot pass a null argument");
     }
 }

A:
Is a long list of parameter checks an anti-pattern?

Literally no.  I've never heard of an "anti-pattern" that says lots of parameter checking is a bad thing.  Parameter checking implemented as a sequence of if statements isn't an anti-pattern either.
However, that doesn't necessarily mean that what you are doing is right.
Up-front error checking in an API method has pros and cons:

*

*On the "pro" side, you pick up problems (programming errors or problems in the "inputs") e*arly.  This (typically) makes it easier to diagnose the problems, and before the errors can cause damage (or waste resources).

*On the "con" side, if the error checking is excessive or in the wrong place, it can be wasteful, or ineffective.
Take this code snippet for example:
 if (A == null || B == null || linkType == null)
 {
    throw new ArgumentException("Cannot pass a null argument");
 }

There are two problems with this:

*

*You are doing this too late.  If any of those are null, then you will already have triggered an exception.

*The tests are arguably redundant anyway, since the CLR will already have implicitly tested for null in the earlier parameter checks.  And the resulting exceptions are just as effective for diagnostic purposes ... provided that you have source code and a stack trace.

Or this:
 if (A.Equals(B) || B.Equals(A))
 {
    throw new InvalidOperationException("A and B cannot be the same");
 }

*

*Does it really matter that A and B are unequal?  (Or could this be a harmless error, or possibly even something that is useful?)

*Is it really necessary to test equality both ways?  (Can't you assume that the Equals method has been implemented to be reflexive?)
Finally, there is the larger problem of whether the checks are (too) repetitious.  By the sounds of it, they are not in your example.  But in general, they could be.

In summary.  No anti-pattern, but you still need to think about how much error checking is advisable, and how best to implement it.

A: if (linkType.BaseType != typeof(Link))
     {
        throw new ArgumentException("linkType is not a valid link type");
     }

should be
checkArgument(linkType.BaseType != typeof(Link),
    "linkType is not a valid link type");

In Java, there's a library with a class Preconditions for this (no idea about c#, but it's easy to write).
This way you get shorter code and it's clean what is what. Incidentally, it can also be faster as the method gets shorter leaving better chances for inlining (at least in the JVM). Hoisting out all checks into one method... maybe.
In general, input validation is good (fail early). For non-public methods consider asserts instead.

Most of the LinkGenerator functions consists of verifying that the parameters are good.

This is a code smell... it seems like you should look for alternatives, how to ensure some conditions so that this method could be simplified. But this is not always possible.


text:
Q: Can I have a pgfgantt chart with different colors per bar? I'm making a timeline for my thesis proposal using the pgfgantt package, and I'd like for each aim to use different coloured bars. Here's the current version.

\documentclass[12pt]{article}
\usepackage[margin=1.0in]{geometry}
\usepackage{pgfgantt}
\begin{document}

\begin{ganttchart}[
    y unit title=0.5cm,
    y unit chart=0.6cm,
    time slot format=isodate-yearmonth,
    compress calendar,
    title/.append style={shape=rectangle, fill=black!10},
    title height=1,
    bar/.append style={fill=green!90},
    bar height=.6,
    bar label font=\normalsize\color{black!50},
    group top shift=.6,
    group height=.3,
    group peaks height=.2,
    bar incomplete/.append style={fill=green!40}
  ]{2015-05}{2017-06}
  \gantttitlecalendar{year} \\
  \gantttitlecalendar{month} \\
  \ganttset{progress label text={}} % this suppresses percentage done labels
  \ganttgroup{Aim 1: Phenotypes}{2015-06}{2015-12} \\
    \ganttbar[progress=00, name=rclone]{R cloning}{2015-06}{2015-07} \\
    \ganttlinkedbar[progress=00, name=rflr]{R fluorescence}{2015-07}{2015-09} \\
    \ganttlinkedbar[progress=00, name=rqpcr]{R RT-qPCR}{2015-10}{2015-11} \\
    \ganttbar[progress=00, name=kover]{KO verification}{2015-06}{2015-07} \\
    \ganttlinkedbar[progress=00, name=kogro]{KO growth}{2015-08}{2015-09} \\
    \ganttbar[progress=00, name=koflr]{KO fluorescence}{2015-08}{2015-09} \\
    \ganttlinkedbar[progress=00, name=koo2]{KO O2 evolution}{2015-10}{2015-11} \\
  \ganttgroup{Aim 2: Expression}{2015-06}{2017-02} \\
    \ganttbar[progress=00, name=oeclone]{Clone OEs}{2016-01}{2016-03} \\
    \ganttbar[progress=00, name=rnagrow]{Grow KOs + OEs}{2016-04}{2016-06} \\
    \ganttlinkedbar[progress=00, name=rnaprep]{RNA library prep}{2016-07}{2016-09} \\
    \ganttbar[progress=00, name=rnadev]{Develop analysis}{2015-06}{2015-07} \\
    \ganttbar[progress=00, name=rnaanal]{Analyze reads}{2016-12}{2017-02} \\
  \ganttgroup{Aim 3: Binding sites}{2016-01}{2017-05} \\
    \ganttbar[progress=00, name=chipgrow]{Grow KOs + OEs}{2016-04}{2016-06} \\
    \ganttlinkedbar[progress=00, name=chipprep]{ChIP library prep}{2016-08}{2016-12} \\
    \ganttbar[progress=00, name=chipdev]{Develop analysis}{2016-01}{2016-02} \\
    \ganttbar[progress=00, name=chipanal]{Analyze reads}{2017-03}{2017-05}
  % misc links
  \ganttset{progress label text={}}
  \ganttlink[]{oeclone}{rnagrow}
  \ganttlink[link mid=0.082]{oeclone}{chipgrow}
  \ganttlink[]{rnaprep}{rnaanal}
  \ganttlink[link mid=0.25]{kover}{koflr}
  \ganttlink[link mid=0.75]{kogro}{koo2}
  \ganttlink[link mid=0.55]{koo2}{oeclone}
  \ganttlink[link mid=0.55]{rqpcr}{oeclone}
  \ganttlink[]{chipprep}{chipanal}
  \ganttlink[link mid=0.938]{rnadev}{rnaanal}
  \ganttlink[link mid=0.915]{chipdev}{chipanal}
\end{ganttchart}

\end{document}

How can I make Aim 1 green, Aim 2 red, and Aim 3 blue for example?

A: Add \ganttsets in the middle like:
\ganttset{bar incomplete/.append style={fill=red!40},
    group/.append style={draw=black, fill=red},}

Code:
\documentclass[12pt]{article}
\usepackage[margin=1.0in]{geometry}
\usepackage{pgfgantt}
\begin{document}

\begin{ganttchart}[
    y unit title=0.5cm,
    y unit chart=0.6cm,
    time slot format=isodate-yearmonth,
    compress calendar,
    title/.append style={shape=rectangle, fill=black!10},
    title height=1,
    bar/.append style={fill=green!90},
    bar height=.6,
    bar label font=\normalsize\color{black!50},
    group top shift=.6,
    group height=.3,
    group peaks height=.2,
    bar incomplete/.append style={fill=green!40}
  ]{2015-05}{2017-06}
  \gantttitlecalendar{year} \\
  \gantttitlecalendar{month} \\
  \ganttset{progress label text={},
       bar incomplete/.append style={fill=green!40},
       group/.append style={draw=black, fill=green},} % this suppresses percentage done labels
  \ganttgroup{Aim 1: Phenotypes}{2015-06}{2015-12} \\
    \ganttbar[progress=00, name=rclone]{R cloning}{2015-06}{2015-07} \\
    \ganttlinkedbar[progress=00, name=rflr]{R fluorescence}{2015-07}{2015-09} \\
    \ganttlinkedbar[progress=00, name=rqpcr]{R RT-qPCR}{2015-10}{2015-11} \\
    \ganttbar[progress=00, name=kover]{KO verification}{2015-06}{2015-07} \\
    \ganttlinkedbar[progress=00, name=kogro]{KO growth}{2015-08}{2015-09} \\
    \ganttbar[progress=00, name=koflr]{KO fluorescence}{2015-08}{2015-09} \\
    \ganttlinkedbar[progress=00, name=koo2]{KO O2 evolution}{2015-10}{2015-11} \\
  \ganttset{bar incomplete/.append style={fill=red!40},
    group/.append style={draw=black, fill=red},}
  \ganttgroup{Aim 2: Expression}{2015-06}{2017-02} \\
    \ganttbar[progress=00, name=oeclone]{Clone OEs}{2016-01}{2016-03} \\
    \ganttbar[progress=00, name=rnagrow]{Grow KOs + OEs}{2016-04}{2016-06} \\
    \ganttlinkedbar[progress=00, name=rnaprep]{RNA library prep}{2016-07}{2016-09} \\
    \ganttbar[progress=00, name=rnadev]{Develop analysis}{2015-06}{2015-07} \\
    \ganttbar[progress=00, name=rnaanal]{Analyze reads}{2016-12}{2017-02} \\
  \ganttset{bar incomplete/.append style={fill=blue!40},
  group/.append style={draw=black, fill=blue},}
  \ganttgroup{Aim 3: Binding sites}{2016-01}{2017-05} \\
    \ganttbar[progress=00, name=chipgrow]{Grow KOs + OEs}{2016-04}{2016-06} \\
    \ganttlinkedbar[progress=00, name=chipprep]{ChIP library prep}{2016-08}{2016-12} \\
    \ganttbar[progress=00, name=chipdev]{Develop analysis}{2016-01}{2016-02} \\
    \ganttbar[progress=00, name=chipanal]{Analyze reads}{2017-03}{2017-05}
  % misc links
  \ganttset{progress label text={}}
  \ganttlink[]{oeclone}{rnagrow}
  \ganttlink[link mid=0.082]{oeclone}{chipgrow}
  \ganttlink[]{rnaprep}{rnaanal}
  \ganttlink[link mid=0.25]{kover}{koflr}
  \ganttlink[link mid=0.75]{kogro}{koo2}
  \ganttlink[link mid=0.55]{koo2}{oeclone}
  \ganttlink[link mid=0.55]{rqpcr}{oeclone}
  \ganttlink[]{chipprep}{chipanal}
  \ganttlink[link mid=0.938]{rnadev}{rnaanal}
  \ganttlink[link mid=0.915]{chipdev}{chipanal}
\end{ganttchart}

\end{document}


text:
Q: Particular solution of third order PDE
$$\partial_t u + \partial^{3}_x u = 0$$
  show that this PDE has a particular solution in the form of a plane wave,
  $$u_k(x,t) = \exp(-i\,w\,t - i\,k\,x)$$ if the frequency $w$ obeys the appropriate dispersion relation, $w = w(k)$.

In the past I have solved up to 2nd order PDE's using separation of variables, Sturm-Liouville method. But since the all coefficients in the PDE has different powers I am confused how to solve this problem. Seems like I can not solve this problem using the methods I used to solve 2nd order PDE's. Any help?

A: Since you have a linear PDE you can use the principle of superposition to form solutions with
$$
u \sim \exp(−iwt−ikx)
$$
then inserting the plane wave solution you obtain
$$
-i\omega u + (-ik)^3u = \left(-i\omega-i^3k^3\right)u = -i(\omega -k^3)u = 0
$$
or the dispersion relation is
$$
w(k) = k^3
$$
if this relation is true then you can use the plane wave above.
If you want to solve you are missing quite a few pieces of information such as initial conditions etc..


text:
Q: Onsen UI: Automatic scroll with ons-list i want to program a chat in WhatsApp style.
The latest news will be shown below, and for new messages to be automatically scrolled down.
Can anyone help me how I can realize the automatic scrolling with ons-list?
<ons-template id="chat.html">
    <ons-page ng-controller="ChatController">
        <ons-toolbar>

<ons-back-button>Back</ons-back-button>

Chat

        </ons-toolbar>

        <ons-list style="margin-top: 10px" scroll-glue>
            <ons-list-item class="item" ng-repeat="msg in messages">

                    {{msg.user}}

{{msg.msg}}

            </ons-list-item>
        </ons-list>
    </ons-page>
</ons-template>

A: I haven't used WhatsApp, but this might help. In an ons-page, you can use .page__content's scrollTop property for auto scroll. Like below. It uses jQuery for animation.

ons.bootstrap()
.controller('ChatController', function($scope, $timeout){
  $scope.messages = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20];
  $timeout(function(){
    $('.page__content').animate({scrollTop: $('.ons-list-inner').height()}, 2000)
    .animate({scrollTop: 0}, 2000);
  });
});
<link href="https://cdn.rawgit.com/OnsenUI/OnsenUI/1.3.8/build/css/onsen-css-components.css" rel="stylesheet"/>
<link href="https://cdn.rawgit.com/OnsenUI/OnsenUI/1.3.8/build/css/onsenui.css" rel="stylesheet"/>

<ons-navigator page="chat.html"></ons-navigator>

<ons-template id="chat.html">
    <ons-page ng-controller="ChatController">
        <ons-toolbar>

<ons-back-button>Back</ons-back-button>

Chat

        </ons-toolbar>

        <ons-list style="margin-top: 10px" scroll-glue>
            <ons-list-item class="item" ng-repeat="msg in messages">

                    {{msg.user}}

{{msg.msg}}

            </ons-list-item>
        </ons-list>
    </ons-page>
</ons-template>


text:
Q: Postgres: how to find rows having duplicate values in fields How can I find if any value exists more than once in one row? An example:
 id | c1 | c2 | c3
----+----+----+----
  1 | a  | b  | c
  2 | a  | a  | b
  3 | b  | b  | b

The query should return rows 2 and 3 since they have the same value more than once. The solution I'm looking for is not 'where c1 = c2 or c1 = c3 or c2 = c3' since there can be any number of columns in tables I need to test. All values are text but can be any length.

A: One way to do that is to convert the columns to rows:
select *
from the_table tt
where exists (select 1
              from ( values (c1), (c2), (c3) ) as t(v)
              group by v
              having count(*) > 1)

If you want a dynamic solution where you don't have to list each column, you can do that by converting the row to a JSON value:
select *
from the_table tt
where exists (select 1
              from jsonb_each_text(to_jsonb(tt)) as j(k,v)
              group by v
              having count(*) > 1)

Online example


text:
Q: Why is Dragon NaturallySpeaking sometimes sending a mouse clicks after I wake it up? From times to times, after I wake up Dragon NaturallySpeaking, and right between the time I start taking and the time Dragon starts transcribing, Dragon sends a mouse click. What could be the reason for that mouseclick?
Looking at the recognition history doesn't give me any clue:

My computer is configured so that the window key send a mouse click, but I don't see Dragon sending window keys either.
I use Dragon NaturallySpeaking 12.5 Professional, Windows 7 SP1.