text:
Q: The argument type 'Widget Function(BuildContext)' can't be assigned to the parameter type 'Widget Function(BuildContext, Widget)'? I am trying to implement the following code for a Quiz game created in flutter
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:widget_quiz/model/model.dart';
import 'package:widget_quiz/pages/quiz_page/selections.dart';

import 'model.dart';
import 'progress.dart';
import 'question.dart';
import 'result_presenter.dart';

class QuizPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
      builder: (context) => Model(
        quizLoader: Provider.of<QuizLoader>(context, listen: false),
      ),
      create: (BuildContext context) {  },
      child: const _Page(),
    );
  }
}

class _Page extends StatefulWidget {
  const _Page({Key key}) : super(key: key);

  @override
  __PageState createState() => __PageState();
}

class __PageState extends State<_Page> {
  Model get _model => Provider.of<Model>(context, listen: false);
  final _resultPresenter = ResultPresenter();

  static const double _horizontalMargin = 16;

  @override
  void initState() {
    super.initState();

    _model.answered.listen((correct) async {
      await _resultPresenter.show(context, model: _model, correct: correct);
      _model.next();
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Widget Quiz'),
      ),
      body: _buildBody(),
    );
  }

  Widget _buildBody() {
    final model = Provider.of<Model>(context);
    return SafeArea(
      child: AnimatedSwitcher(
        duration: const Duration(milliseconds: 200),
        child: model.quizListLoaded
            ? model.hasQuiz ? _buildQuiz() : _buildResult()
            : const Center(child: CircularProgressIndicator()),
      ),
    );
  }

  Widget _buildQuiz() {
    return Column(
      children: const [
        Progress(),
        Divider(
          indent: _horizontalMargin,
          endIndent: _horizontalMargin,
          height: 0,
        ),
        Expanded(
          child: SingleChildScrollView(
            padding: EdgeInsets.all(_horizontalMargin),
            physics: AlwaysScrollableScrollPhysics(),
            child: Question(),
          ),
        ),
        Padding(
          child: Selections(),
          padding: EdgeInsets.symmetric(horizontal: _horizontalMargin),
        ),
      ],
    );
  }

  Widget _buildResult() {
    final model = Provider.of<Model>(context);
//    model
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Text(
            '⭕ ${model.progress.where((p) => p == ProgressKind.correct).length} / 10',
            style: const TextStyle(fontSize: 32),
          ),
          const SizedBox(height: 8),
          Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: model.progress
                .asMap()
                .map((index, p) => MapEntry(
                    index,
                    Text(
                        '${p == ProgressKind.correct ? '⭕' : '❌'} ${model.quizList[index].correct.name}')))
                .values
                .toList(),
          ),
          const SizedBox(height: 8),
          RaisedButton(
            child: const Text('TRY AGAIN'),
            onPressed: model.load,
          )
        ],
      ),
    );
  }
}

BUT I get the following errors
1/ error: The return type 'Model' isn't a 'Widget', as required by the closure's context. (return_of_invalid_type_from_closure at [widget_quiz] lib\pages\quiz_page\quiz_page.dart:15)
2/error: The argument type 'Widget Function(BuildContext)' can't be assigned to the parameter type 'Widget Function(BuildContext, Widget)'. (argument_type_not_assignable at [widget_quiz] lib\pages\quiz_page\quiz_page.dart:15)
what is the solutions?

A: First Issue
parameter builder in ChangeNotifierProvider need a function widget with type
Widget Function(BuildContext context, Widget? child)

So, change this line
builder: (context) => Model(

with
builder: (context, child) => Model(

Second Issue
You just need to return a Widget in the function. child is a Widget, so you can return the child or another widget.
builder: (context, child) {
  // Your code
  return child;
}


text:
Q: is there easier way to increase EBS size? the steps showed in http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/console-modify.html
are very complex.
Basically to resize EBS, I need to:

*

*modify volumn size

*expand partition
2-1. detach root device from original EC2 and attach it to another EC2
2-2. login another EC2:
   sudo umount /
   sudo parted /dev/xvda
(parted) unit s
(parted) print
'Ignore' to all questions
(parted) rm 1
    ......
    sudo e2fsck -f /dev/xvda1
2-3.To return an expanded root partition to its original instance:
Detach the expanded partition from its secondary instance
Reattach the volume to the primary instance using the device name that you identified: /dev/xvda
Start the primary instance.
Terminate the second EC2

*Extend linux FS:
sudo resize2fs /dev/xvda1
df -h to see the result
is there easy and safe way to expand EBS size?
-------- update with more information
My EC2 is ubuntu 16.04
~$ lsblk
NAME    MAJ:MIN RM  SIZE RO TYPE MOUNTPOINT
xvda    202:0    0  200G  0 disk
└─xvda1 202:1    0  100G  0 part /

based on http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/recognize-expanded-volume-linux.html and my lsblk output, I need to expand partition. then based on #5 and #6 of http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/expand-linux-partition.html, I need to detach then attache the partition from the original EC2. and then based on http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-detaching-volume.html, I need to first umount -d /dev/xvda, detach partition from original EC2, then attach it to a new EC2, expand partition using parted....

A: If the EBS volume is your boot volume and you are using Amazon Linux, then you simply need to:

*

*Modify the volume size (eg in the console)

*Reboot the instance

Code that runs at startup will automatically expand the partition to use the new space available.
If you do not wish to reboot the instance, follow the directions on Extending a Linux File System after Resizing the Volume. These instructions do not list the need to unmount/reattach the volume.

A:

Now login through putty and follow the below mention steps -

*

*
 1. mount -o size=10M,rw,nodev,nosuid -t tmpfs tmpfs /tmp

*lsblk
3. sudo file -s /dev/xvd*
4. sudo growpart /dev/xvda 1
5. sudo resize2fs /dev/xvda1
6. df -h

redpajama_set_name: RedPajamaStackExchange


text:
Q: c# Winforms - CLR20r3 Exception I am starting run my program in Windows 7 64 bit machine with .Net Framework 4.5 Installed and it's working fine.
Then i try to run in another Windows 7 64 and 32 bit machine with Net Framework 4.5 Installed too, i don't know why the program stopped working.
Problem Event Name: CLR20r3
  Problem Signature 01: ExDraw.exe
  Problem Signature 02: 1.0.2.3
  Problem Signature 03: 59be5ce4
  Problem Signature 04: mscorlib
  Problem Signature 05: 4.6.1590.0
  Problem Signature 06: 5787ed44
  Problem Signature 07: f9d
  Problem Signature 08: 96
  Problem Signature 09: System.FormatException
  OS Version:   6.1.7601.2.1.0.256.1
  Locale ID:    1033
  Additional Information 1: 0a9e
  Additional Information 2: 0a9e372d3b4ad19135b953a78882e789
  Additional Information 3: 0a9e
  Additional Information 4: 0a9e372d3b4ad19135b953a78882e789

Read our privacy statement online:
  http://go.microsoft.com/fwlink/?linkid=104288&clcid=0x0409

If the online privacy statement is not available, please read our privacy statement offline:
  C:\Windows\system32\en-US\erofflps.txt

And here's my code
private void DownloadAddonsListCompleted(object sender, DownloadStringCompletedEventArgs e)
    {
        var result = StringHelper.DecryptMyString(e.Result);
        foreach (var line in result.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries))
        {
            var statusAddons = File.Exists("Addons\\" + line.Split('~')[0] + ".addon")
                ? "Installed"
                : "-";

            var localAddonsVersion = "-";
            if (statusAddons != "-")
            {
                localAddonsVersion = File.ReadAllText("Addons\\" + line.Split('~')[0] + ".version");
                if (Convert.ToDouble(localAddonsVersion) < Convert.ToDouble(line.Split('~')[1]))
                    statusAddons = "Outdated";
            }

            var _WebClient = new WebClient();
            var fileName = line.Split('~')[0].Replace(" ", string.Empty) + ".html";
            _WebClient.DownloadFileTaskAsync(line.Split('~')[3],
                RequiredPath.ADDONSDESCRIPTIONPATH + "\\" + fileName).Wait();

            rgvList.Invoke(new Action(() =>
                rgvList.Rows.Add
                (
                    line.Split('~')[0],
                    statusAddons,
                    localAddonsVersion,
                    line.Split('~')[1],
                    line.Split('~')[2],
                    line.Split('~')[3],
                    line.Split('~')[4],
                    RequiredPath.ADDONSDESCRIPTIONPATH + "\\" + fileName
                )));

        }
    }

A: Your problem is in
if (Convert.ToDouble(localAddonsVersion) < Convert.ToDouble(line.Split('~')[1]))
    statusAddons = "Outdated";

You are converting a text into double, but you are doing it in the current culture of the machine. Depending on the culture, the decimal separator can vary; it could be a ".", a "," or even something else. Your problem is most likely related to different cultures an your machines. So when you do these conversions, you should always set a conversion culture.
Your case is a bit different though, since from your comments to the question I get that the data you are trying to compare are version numbers in the format "1.0.0.0". Double is a poor choice for a conversion format in this case. The .NET framework comes with the System.Version class for these kind of comparisons:
if (new Version(localAddonsVersion) < new Version(line.Split('~')[1]))
    statusAddons = "Outdated";


text:
Q: Calling Angular2SocialLoginModule function calls not supported I am new to angular js2. Currently I am working with a web application, which uses angular2 for front-end. In this application I have used angular2-social-login for authentication purpose. But when I run the npm start I got the below error

ERROR in Error encountered resolving symbol values statically. Calling function 'Angular2SocialLoginModule', function calls are not supported. Consider replacing the function or lambda with a reference to an exported function, resolving symbol AppModule in /var/www/html/ngtest/src/app/app.module.ts, resolving symbol AppModule in /var/www/html/ngtest/src/app/app.module.ts

When I google it, some one says that it is beacause of using angular cli in the project. But I uninstalled angular cli, still problem persists.
Did any one know how to solve this issue?
My app.module.ts code is below
import { Angular2SocialLoginModule } from "angular2-social-login";
let providers = {

 "facebook": {
  "clientId": "xxxxxxxxxxxxx",
  "apiVersion": "v2.8"
},
 "linkedin": {
  "clientId": "xxxxxxxxxxx"
},
"google": {
  "clientId": "xxxxxxxxxx"
}

};
@NgModule({
 imports: [
     Angular2SocialLoginModule.initWithProviders(providers),
 ],
})
export class AppModule { }

I have called this module in header.component.ts, please see the header.component.ts file
import { AuthService } from "angular2-social-login";
@Component({
selector: 'app-header',
templateUrl: './header.component.html',
styleUrls: ['./header.component.css'],
providers: [Modal]
})
export class HeaderComponent implements OnInit {
constructor(public _auth: AuthService){ }

 signIn(provider){
 this.sub = this._auth.login(provider).subscribe(
 (data) => {
console.log(data);
   }
 )}
logout(){
this._auth.logout().subscribe(
(data)=>{

//return a boolean value.
}
)}
}

The above is my code, Please have a look. If any more details needed please comment

A: Update
In angular2-social-login v.3.0.0 you can write:
@NgModule({
  ...
  imports: [
     Angular2SocialLoginModule
  ]
})
export class AppModule {
  constructor(){}
}

Angular2SocialLoginModule.loadProvidersScripts(providers);

Old version
Remove
imports: [
  Angular2SocialLoginModule.initWithProviders(providers),
],

And try this:
import { Angular2SocialLoginModule, AuthService } from "angular2-social-login";

@NgModule({
  ...
  providers: [
    AuthService
  ]
})
export class AppModule {
  constructor() {
    Angular2SocialLoginModule.initWithProviders(providers);
  }
}

A: It worked for me.
export class AppModule {
    constructor() {
        Angular2SocialLoginModule.initWithProviders(providers);
    }
}

A: Another solution to fix the above problem:
export class AppModule {
 constructor() {
}}
Angular2SocialLoginModule.initWithProviders(providers);


text:
Q: Making a Debugging Console I couldn't find any information when I was searching for this (Maybe I was searching the wrong keywords) but I need a way I can have a debugger during runtime outputting my own strings of words, kind of like System.out.print statements but to a console window instead.
Maybe I am just a noob but I want to ask this too before someone tells me this: Does the system.out.print, println, and printf statements print to a command prompt during runtime after you finish your program and create a jar. My program uses JFrame with severeal GUIs.

A: Created a new frame with a JTextArea covering it, everytime I have a System.out.println() I just used a static addToDebugger(String s) method which just concatenates JTextArea.getText() with a "\n" + s and then JTextArea.setText().


text:
Q: Splitview controller error in ios 4 I am new to iPhone development. I am working on a project having split view controllers. What I am doing is as follows
[self.splitViewController removeFromParentViewController];
     self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
     UINavigationController *detailViewNav=[[UINavigationController alloc]initWithRootViewController:SampleViewController];

   self.nextSplitControler=[[UISplitViewController alloc]init];
    self.nextSplitControler.viewControllers=[NSArray arrayWithObjects:masterNavigationController,detailViewNav, nil];
    self.nextSplitControler.delegate=SampleViewController;
    self.window.rootViewController=self.nextSplitControler;

    [self.window makeKeyAndVisible];

It works fine on iOS 5.0 . But on iOS 4.3 it throws an error as
-[UISplitViewController removeFromParentViewController]: unrecognized selector sent to instance.
Can any one help me with this issue? I am banging my head.

A: Don't bang your head; check the docs.  :)
- (void)removeFromParentViewController
Availability
Available in iOS 5.0 and later.


text:
Q: Building a cube from small bricks such that no lines can be pushed through between the seams I'm riffing on an old contest training question I jousted with 40 years ago.
The original problem was:

A solid $20\times20\times20$ cube is built out rectangular bricks of dimensions $2\times2\times1$. Prove that it is possible to "push" a line through the cube in such a way that the line is not obstructed by any of the bricks.

Solution: We need $2000$ bricks to build this cube. Imagine that the edges of the cube align with the coordinate axes, and that the cube is in the first octant with one of its vertices at the origin. So there are $19^2$ lines parallel to the $z$-axis going through the cube, each given by the equations $x=a, y=b, a,b\in\{1,2,\ldots,19\}$, lines parametrized by the choice of the pair $(a,b)$. Similarly, there are $19^2$ lines parallel to the $x$ and $y$-axes for a total of $3\cdot19^2$ lines. It turns out that one of these will go through the cube along the cracks between the bricks.
The key observation is that each line will be blocked by an even number of bricks (spoiler hidden below in case you want to think about it yourself).

 Take one of those lines, say $z$ arbitrary, $x=a$, $y=b$. Consider the two planes, the first defined by $x=a$ and the second by $y=b$. These two planes cut the cube into four parts, the volume of each is an even integer. Then consider how the bricks are split by these two planes. We see that a brick blocks this line if and only if its volume is split equally between the four parts – an odd contribution to each part. The claim follows.

As $2\cdot3\cdot19^2>2000$ it is impossible that all these lines would be blocked by two or more bricks. Therefore at least one of them is unobstructed, proving the claim.
Ok, that was the background story. On with the actual question.
As the size of the cube, call it $n$, grows, the number of bricks increases as $n^3/4$, but the number of those lines, call them integer lines, increases as a quadratic polynomial of $n$ only. Therefore sooner rather than later the above argument fails to work. In fact, this happens already with $n=22$
as $2\cdot3\cdot21^2<22^3/4$. The parameters $a,b$ obviously ranging from $1$ to $n-1$.

Is it possible to build a solid $22\times22\times22$ cube out of $2\times2\times1$ bricks in such a way that all the integer lines are blocked by at least one (hence at least two) bricks? If this is not possible with $n=22$, what is the smallest value of $n$ for which this construction is possible (if one exists)?

Given that the answer to my question is unknown, I will welcome answers explaining a construction for answerer's choice of $n$.

A: Consider the line determined by $(x,y)=(a,b)$ and the four regions into which the planes $x=a$ and $y=b$ slice our $2n\times 2n\times 2n$ cube. In particular, consider the number of unit cubes inside the diagonally opposite regions $x,y\leq a,b$ and $x,y\geq a,b$, which is
$$2nab+2n(2n-a)(2n-b)\equiv 0\bmod 4.$$
Modulo $4$, this is the same as twice the number of blocks that straddle the planes $x=a$ or $y=b$ (the blocks the centers of which the line $(x,y)=(a,b)$ passes through should be counted only once here, not twice). We see that one of these lines must pass through the centers of at least $4$ blocks. If not, then this total number of blocks is exactly $2$ for each of these lines; however, there are $8n-5\equiv 1\bmod 2$ such lines.
So, we have a set of lines $L$ such that, for each pair of intersecting planes inside our $2n\times2n\times2n$ cube, at least one of them contains a line in $L$. We need to lower-bound the size of this set $L$.

Lemma. Consider lines entirely inside a $u\times v\times w$ rectangular prism with $u+v+w$ even (so, if $u=v=w=2$, there are $3$ such lines). A set $L$ of these lines satisfies that, for any two intersecting (lattice) planes inside this rectangular prism, $L$ contains at least one line lying entirely on one of these planes. Then $|L|\geq \frac{u+v+w}2-1$.
Proof. We prove this by induction on $u+v+w$ with $u,v,w\geq 2$. Our inductive step will only deal with $u,v,w>2$, so we need to prove the case in which, without loss of generality, $u=2$ in our base case. We will do this after the inductive step.
Without loss of generality, let the line $(x,y)=(u-1,v-1)$ be in $L$. Consider a new construction $L'$ on a $u-1\times v-1\times w$ prism consisting of at most $|L|-1$ lines so that

*

*given a line $\ell\in L$ that is not on either $x=u-1$ or $y=v-1$, $\ell$ is added to $L'$,

*given a line $\ell\in L$ with $x=u-1$, the line $\ell-(1,0,0)$ is added to $L'$, and

*given a line $\ell\in L$ with $y=v-1$, the line $\ell-(0,1,0)$ is added to $L'$.
We see that $L'$ satisfies the required conditions, since a plane $P$ in the $u-1\times v-1\times w$ case contains a line in $L$ if and only if it contains a line in $L'$. This reduces $u+v+w$ by $2$ and the number of lines by (at least) $1$, so we may apply our inductive hypothesis to finish.
This argument works to reduce $u+v+w$ as long as there is a line that can be chosen that does not reduce any side length to lower than $2$, so if we cannot make the above argument we may assume that $u=2$ and that there are no lines of the form $(y,z)=(b,c)$ in $L$. Here, we must have that, for any $y=b$, the line $(x,y)=(1,b)$ is in $L$, and for any $z=c$ the line $(x,z)=(1,c)$ is in $L$, so $L$ is of size at least
$$v+w-2=(v-2)+(w-2)+2\geq \frac{v+w}{2}=\frac{u+v+w}{2}-1,$$
finishing our proof. $\square$

So, $L$ is of size at least $3n-1$. This means that the number of blocks whose centers are intersected by some lines is at least
$$2\left(3(2n-1)^2\right)+2(3n-1).$$
At $n=11$ this is $2710$, which is more than $2\cdot 11^3$, finishing the proof for a cube of side length $22$. Sadly, this is not strong enough to solve the $n=24$ case.

A: I encountered a two-dimensional counterpart of this problem when I was a schoolboy, reading a Russian translation from 1971 of Martin Gardner's "Mathematical puzzles and diversions".  I add below the relevant parts of his article "Polyominoes and Fault-Free Rectangles" from "New mathematical diversions".

A: I've written a program which implements a random construction similar to the one from my other answer, and used this program to find a tiling which blocks all lines for the case $n = 102$.
Unfortunately this isn't very insightful -- the tiling is random and (essentially) unstructured, and doesn't give much information about the nature of the problem. I would be interested to see a construction which could be reasonably verified by a human; my post is mainly intended to gain a little closure and to nail down a reasonable upper bound.
Approach (similar to other answer):
Again, for convenience we want to think of the $n \times n \times n$ cube as a $k \times k \times k$ cube of $2 \times 2 \times 2$ subcubes (which I'll just refer to as "cubes"), with centers at points in $\{1, 3, 5, \dots, 2k-1\}^3$. The main benefit of this idea is that it allows for very modular construction, where we can place a given configuration of tiles locally (filling completely a small number of adjacent cubes) without worrying about how this will affect the global structure of the tiling.
The idea is to place, for each line, a small configuration of tiles which blocks the line. The configuration used depends on the parity of the coordinates of the line. Consider a line in the $z$-direction, given by the equations $x = a$ and $y = b$. For any such line, our configuration will be placed at some level $h$, for an odd $h$ between $1$ and $2k-1$. If $a$ and $b$ are both odd, we place the first configuration below in the cube with center $(a, b, h)$. If $a$ is odd and $b$ is even, we place the second configuration below in the adjacent cubes with centers $(a, b-1, h)$, $(a, b+1, h)$. Similarly, if $a$ is even and $b$ is odd, we place the second configuration in the adjacent cubes with centers $(a-1, b, h)$, $(a+1, b, h)$. Finally, if $a$ and $b$ are both even, we place the third configuration below in the adjacent cubes with centers $(a-1, b-1, h)$, $(a-1, b+1, h)$, $(a+1, b-1, h)$, $(a+1, b+1, h)$.

Hopefully the diagrams make clear that if placed as described, a configuration will block its associated line. Rotated versions of the above configurations can be placed analogously in order to block lines in the $x$- and $y$-directions. Once we've chosen a level for each line, our work is done so long as the tile configurations, when placed at the associated levels, don't overlap: after placing these configurations, no cubes are only partially filled, so we can fill all the empty cubes according to the first configuration above, yielding a full tiling of the $n \times n \times n$ cube. Thus to build a good tiling, it's enough to give a list of levels for all lines which produces no overlap.
Results:
I wrote a program which implements the above idea by choosing levels at random for each line, one at a time. As it does this, the program builds a skeleton of the tiling, filling the cubes occupied by the specified configurations, checking that no overlap is produced. For a given line, if the chosen level produces overlap with previously placed blocking configurations, the program tries again, repeatedly choosing a new level at random until one that does not produce overlap is found. If it cannot find one, the program gives up.
In the case $n = 110$, the program is successful, empirically, about 80% of the time. For $n$ a little below this, it starts to fail most of the time. The smallest successful tiling I found was at $n = 102$. I've posted this in a pastebin file here. The tiling is formatted as three nested arrays in python syntax, such that the level for the line in the $x$-direction given by $y = a$, $z = b$ is xlist[a-1][b-1], the level for the line in the $y$-direction given by $x = a$, $z = b$ is ylist[a-1][b-1], and the level for the line in the $z$-direction given by $x = a, y = b$ is zlist[a-1][b-1]. I've also added python code which performs the verification step, of checking that no overlap is produced by placing configurations at the specified levels, in another pastebin file.

A: Below is a probabilistic proof that such tilings exist for all sufficiently large (even) $n$. I recognize this might not be in the spirit of the question, since the method is non-constructive, but I thought it would be good to rule out impossibility proofs.
Building the (random) tiling:
For $n = 2k$, think of the $n \times n \times n$ cube as a $k \times k \times k$ cube of $2 \times 2 \times 2$ subcubes (I'll refer to these as just "cubes" going forward), with centers at points in $C = \{1, 3, 5, \dots, 2n-1\}^3$.
Independently assign to each of these cubes a tuple at random from the set
$$D = \{x, y, z\} \times \{-1, 0, 1\} \times \{-1, 0, 1\}$$
according to some fixed distribution $p$ over $D$ to be chosen later. Loosely speaking, this tuple indicates the line that the cube is "assigned" to block: for example, if a cube centered at $(a, b, c)$ is assigned $(z, i, j)$, then the cube will attempt to block the line in the $z$-direction given by $x = a+i$, $y=b+j$ (similarly, if assigned $(x, i, j)$, the line $y = b + i$, $z = c + j$, and if $(y, i, j)$, the line $z = c+i$, $x = a+j$). The meaning of this will become clear once we construct the tiling. Let $F$ denote the resulting random assignment $C \to D$.
Now, given the assignment $F$, we construct the tiling as follows. Consider a cube centered at $(a, b, c)$, and suppose WLOG that it is assigned to block a line in the $z$-direction.
Case 1: If $F(a, b, c) = (z, 0, 0)$, the cube is assigned to block the line $x = a, y = b$, so we simply place two $2 \times 2 \times 1$ blocks in the cube, arranged as below to block the line.

Case 2: If $F(a, b, c) = (z, 1, 0)$, the cube is assigned to block the line $x = a+1, y = b$. This line meets the cube along one of its faces, and so the cube can only block the line if the cube on the other side of this face "cooperates", i.e. if the cube centered at $(a+2, b, c)$ is assigned the same line, meaning $F(a+2, b, c) = (z, -1, 0)$. In this case, we place four $2 \times 2 \times 1$ tiles in the two cubes in order to block the line as shown below:

We can place the tiles analogously in the case $F(a, b, c) = (z, 0, 1)$, if $F(a, b+2, c) = (z, 0, -1)$ as well.
Case 3: If $F(a, b, c) = (z, 1, 1)$, the cube is assigned to block the line $x = a+1, y = b+1$. This line meets the cube along one of its edges, and so the cube can only block the line if the three other cubes meeting at that edge all cooperate, i.e. that they are all assigned to the same line. This means $F(a+2, b, c) = (z, -1, 1)$, $F(a+2, b+2, c) = (z, -1, -1)$, and $F(a, b+2, c) = (z, 1, -1)$. In this case, we place eight tiles in the four cubes to block the line as shown below:

We place tiles in cubes assigned lines in the $x$- or $y$-directions according to the analogous conditions to cases 1, 2, 3. After tiles are placed for all cubes satisfying these conditions, we are only left with empty and full cubes, i.e. no cubes are only partially filled by tiles. Thus for the remaining cubes we can separately fill them with tiles according to the diagram in case 1; no conflicts are created. At the end, we have a complete tiling of the $n \times n \times n$ cube.
Analysis:
We can now analyze the probabilistic properties of the resulting tiling. For convenience, let's say the distribution $p$ over $D$ satisfies
\begin{align*}
p(w, 0, 0) &= q_1 \\
p(w, \pm 1, 0) = p(w, 0, \pm 1) &= q_2 \\
p(w, \pm 1, \pm 1) &= q_3 \\
\end{align*}
where $w = x, y, z$, for some $q_1, q_2, q_3 > 0$.
Consider the probability that a line in the $z$-direction, say the line $L$ given by $x = a, y = b$ (for some $1 \leq a, b \leq 2n-1$), is not blocked.
Case 1: $a$ and $b$ are both odd. This can only happen if none of the cubes with centers along the line are assigned to block it. Each such cube is assigned to block it with probability $q_1$, and there are $k$ cubes which are assigned lines independently, so the probability that $L$ is not blocked is at most $(1 - q_1)^k$.
Case 2: One of $a$ or $b$ is odd, the other even. Say $a$ is odd. Note that for each odd $c$, $L$ is blocked if both the cubes at $(a-1, b, c)$ and $(a+1, b, c)$ are assigned to it, and this happens with probability $q_2^2$. Since there are $k$ such pairs of cubes, assigned independently, the probability that $L$ is not blocked is at most $(1-q_2^2)^k$. The same holds if $a$ is even and $b$ is odd.
Case 3: $a$ and $b$ are both even. This time, for each odd $c$, $L$ is blocked if all four cubes at $(a \pm 1, b \pm 1, c)$ are assigned to it, and this happens with probability $q_3^4$. Since there are $k$ such groups of four cubes, the probability that $L$ is not blocked is at most $(1 - q_3^4)^k$.
There are $k^2$ lines matching the first case, $2k(k-1) \leq 2k^2$ matching the second case, and $(k-1)^2 \leq k^2$ matching the third case. The same holds for the analogous cases in the $x$- and $y$-directions, so the probability that there is some line which is not blocked is at most
$$3k^2((1 - q_1)^k + 2(1 - q_2^2)^k + (1 - q_3^4)^k).$$
For any choice of $q_1, q_2, q_3$, this goes to $0$ as $k \to \infty$, so in particular the probability that all lines are blocked is positive for sufficiently large $k$, meaning that tilings which block all lines exist for sufficiently large $k$.
Upper bound:
To get a tangible upper bound on the smallest $n$ for which such such tilings exist, we can try to choose $q_1, q_2, q_3$ to minimize the above expression. The expression is dominated by the term corresponding to the smallest of $q_1, q_2^2, q_3^4$, so we will set $q_1 = q_2^2 = q_3^4$, so there is some $r > 0$ with $q_1 = r^4$, $q_2 = r^2$, $q_3 = r$. For $p$ to be a distribution, we must have $1 = 3q_1 + 12q_2 + 12q_3$, so we can take $r = 0.077343...$ to be the unique positive root of $3r^4 + 12r^2 + 12r = 1$. Then under this choice of $p$, the probability that some line is not blocked by our tiling is at most $12k^2(1-r^4)^k \leq 12k^2 e^{-r^4 k}$, which is decreasing for $k$ greater than $2r^{-4} \leq 56000$, and dips below $1$ by $k = 850000$. Thus tilings blocking all lines exist for even $n \geq 1700000$.
This is a fairly rough upper bound, and can be improved slightly by a less wasteful construction/analysis. There are also other probabilistic constructions which seem to give better bounds, but I don't see an obvious way to get near the appropriate order of magnitude (say, $n \leq 1000$).

A: I expect that a required construction exists for sufficiently large $n$ and it should be shown by a concrete example. But I think that a corresponding tiling is rather irregular, so hard to describe and its construction is a quest rather for a puzzle solver than for a mathematician. So I crossposted it at Puzzling.SE.
Since the considered tilings are too complicated to be dealt by hand, I wrote an assisting program. I share it to facilitate other MSE users to solve the problem, and, possibly, to win the bounty. The program has a simple and intuitive interface, which looks a bit like "Tetris", see a program screenshot. An the main working field are shown two consecutive layers of the cube of a selected size, parallel to one of three coordinate planes, which can be selected too. The bricks can be added or removed in a few clicks, see the program help for details. To facilitate diversity, each new brick obtains a personal random color. The red dots indicate the unblocked lines, perpendicular to the respective coordinate planes. Constructed partial tilings can be saved and loaded. Downloads: an executable file for Windows, a zip-archive of
Delphi 5 source files.
I devoted to a program a separate answer for possible related questions or discussions, for instance, reported bugs or proposed improvements. Also I described the problem to my colleague, Dr. Misha Mytrofanov, who got interested in it and is going to work with the program today.


text:
Q: Current electricity: the drift velocity In physics it is told that in conductor electrons moves with average velocity when electric field is applied and velocity Is independent of time yet electrons are accelerated. How is it possible?

A: Electrons are accelerated for very small time
(the relaxation time) ,then they collide with other electrons in metal.
The relaxation time is nearly same and constant for each such collision.
During this time they gain some velocity,(called drift velocity),
which is almost same for each such collision of electrons.
This gives us a nearly constant overall drift velocity.


text:
Q: Insertion of over-specific detail to humorous effect In Gilmore Girls, describing a debutante ball:
"It's like animals being up for bid at the county fair, except sheep don't wear hoop skirts."
This kind of over-the-top, facetious detail is used throughout the show and fuels the witty dialogue. Is there a word for humor created by such an unexpected, specific detail?
This question suggests "facetious synecdoche," but I don't think the example above is synecdoche (except for "sheep" being representative of "animals", but it's really the "hoop skirts" that drives the humor). I'm also not looking for: "detail," "imagery," "satire," "hyperbole."

A: In comedy, this is called tagging a joke. The tag is a following reference to the punchline that adds comedic effect. Here the (supposedly) amusing punch is the comparison of debutantes at a ball to farm animals to be judged at a fair. The tag is the mention by denial of hoop skirts on sheep, which attire is suitable only for debutantes, i.e., neither for sheep nor for reasonable women.


text:
Q: Localized Content in Amplience Dynamic Content What is the best approach to creating and organizing localized content in Amplience Dynamic Content.  Should it be done through a content type (json) or rendering (html, css, .js) or other methods (web hook integrations)

A: I use multiple repositories one for each language. I put my localised content in each one then create slot type with JSON schema that creates an array of content links that you can point at each local variant.  Alternatively you can have an array of content types with a field defined as a locale enumeration and a content link.
e.g.
Slot
--localized content array
----local:en
----content:link to content in en repository
----local:es
----content:link to content in es repository
----local:fr
----content:link to content in fr repository
Example localized slot content type
https://github.com/zestrax/dynamic-content-samples/blob/Development/content-types/slot/localized-slot.json
Use the render service to filter the graph on request e.g.
Create a partial for each country en.HBS which loops through the slot array and return the content matching its locale
you would create a handlebars partial 'en.hendlebars'  like this to filter the local content in a slot for language 'en'.
{{#each content-list}}
    {{#compare locale "==" "en"}}
        {{!-- call a partial for to render the locale content --}}
        {{>mapping this.content.content-type}}
    {{/compare}}
{{/each}}


text:
Q: Gradle build failed: Main class name has not been configured and it could not be resolved I am building a RESTful web service with Spring by following this guide. I am using gradle to build the app but my build is failing.
I used the "build gradle" command on a Windows 10 machine.
This is the gradle code:
buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:2.1.6.RELEASE")
    }
}

apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'idea'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'

bootJar {
    baseName = 'gs-rest-service'
    version =  '0.1.0'
}

repositories {
    mavenCentral()
}

sourceCompatibility = 1.8
targetCompatibility = 1.8

dependencies {
    compile("org.springframework.boot:spring-boot-starter-web")
    testCompile('org.springframework.boot:spring-boot-starter-test')
}

I am getting the following error:
Execution failed for task ':bootJar'.

Main class name has not been configured and it could not be resolved

A: When building a multi-module project which includes a module outside of the springboot project, then the module's build.gradle must contain:
bootJar {
    enabled = false
}

jar {
    enabled = true
}

A: With the org.springframework.boot Gradle plugin version 2.6.2.
plugins {
  id 'org.springframework.boot' version '2.4.0'
}

I had similar issue.

Execution failed for task ':bootJar'.
Failed to calculate the value of task ':bootJar' property 'mainClass'.
Main class name has not been configured and it could not be resolved

Now depending on the version of the springframework boot plugin you have to define the main class value on following way.
SpringFramework 2.3.12 and older
springBoot {
  mainClassName = 'com.example.ExampleApplication'
}

SpringFramework 2.4.0 and newer
springBoot {
  mainClass = 'com.example.ExampleApplication'
}

Release notes mentioning change of the property

A: in my case, (using Kotlin for writing springboot demo) it was caused by the src folder, the main class file did not locate under src/main folder.
besides, I've clean everything up and restart IDE.
As @Zaziro mentioned, I've also token a try, but without any luck.
But there're articles mentioned config mainClassName,
and after comparing with src code in Github that different, it's not about any version of any package.
Wish u luck :-)

A: I ran into this error when I used kotlin and misplaced the main method.
Wrong:
@SpringBootApplication
class Application {
    fun main(args: Array<String>) {
        runApplication<Application>(*args)
    }
}

Fix (moved main out of Application):
@SpringBootApplication
class Application

fun main(args: Array<String>) {
    runApplication<Application>(*args)
}

A: As @Zaziro mentioned, it's possible to define a configuration.
This site describes the different kinds of configuration very well: https://www.baeldung.com/spring-boot-main-class#gradle
IF YOU ARE USING KOTLIN:
Be aware that your class name changes. You need to append your mainClassName with "Kt".
example: "com.example.Application" -> "com.example.ApplicationKt"

A: According to https://spring.io/guides/gs/multi-module/, the library's build.gradle (that uses Spring) should use Spring Boot Plugin without applying it (apply false):
plugins {
    id 'org.springframework.boot' version '3.0.0' apply false
    id 'io.spring.dependency-management' version '1.1.0'
    id 'java'
}

That eliminates the need for:
bootJar {
    enabled = false
}

jar {
    enabled = true
}

Also, for the Spring Boot application that uses the library, we need to specify scanBasePackages with the library's group:
package com.example.multimodule.application;

import com.example.multimodule.service.MyService;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication(scanBasePackages = "com.example.multimodule")
@RestController
public class DemoApplication {

  private final MyService myService;

  public DemoApplication(MyService myService) {
    this.myService = myService;
  }

  @GetMapping("/")
  public String home() {
    return myService.message();
  }

  public static void main(String[] args) {
    SpringApplication.run(DemoApplication.class, args);
  }
}

A: So, you can configure it. Pls try:
apply plugin: 'application'
mainClassName = 'com.example.WebApplication'

A: If we're using the Spring Boot Gradle plugin and Kotlin you can use the snippet below:
plugins {
    id("org.springframework.boot") version "2.6.7"
    id("io.spring.dependency-management") version "1.0.11.RELEASE"
    kotlin("jvm") version "1.5.31"
    kotlin("plugin.spring") version "1.5.31"
}

...

springBoot {
    mainClass.value("com.mycompany.MyApplication")
}

A: I was trying to follow the instructions at https://spring.io/guides/gs/spring-boot/ that has a CommandLineRunner in the application. The code inside the CommandLineRunner would only run if I wrapped that bean and the main method in the class. I could get tests to run but not via the command line. I was able to get around this by using a companion object:
@SpringBootApplication
class TestApplication {

    companion object {
        @JvmStatic
        fun main(args: Array<String>) {
            runApplication<TestApplication>(*args)
        }
    }

    @Bean
    fun commandLineRunner(ctx: ApplicationContext): CommandLineRunner {
        ...
    }
}


text:
Q: dask parquet file structure created using to_parquet function This is more of a theorical and intuitive question.
when I provided a list of columns to partition_on variable in dask_dataframe.to_parquet(), it created  Directory like structure in the order of columns provided more like a nested structure.
However, the actual documentation of parquet says that it is a column store data structure and if we provide a list of columns to it then it creates a partitions based on those columns i:e all the rows(if not rowsize is not provided) of specified columns go in one Partition. Is dask to_parquet doing it right way?

A:
actual documentation of parquet says

The canonical parquet documentation does not address splitting up a dataset into multiple files. The directory structure and the optional special _metadata file are conventions that were, I believe, devised first by Hive. It is additional to the standard parquet spec, but not in contravention of it.
Each of the data files contains a number of rows and is a valid parquet data set in itself, containing one or more "row groups" (parquet's logical partition) and each column being written in a separate part of the file and encoded as a number of "pages". Parquet allows for dictionary-encoding, but this is a per-page thing, and there is no global categorical labelling scheme, so encoding values into the path names is very useful, and also allows for pre-filtering which of the files we want to access, when only some values are needed.
Short answer: yes, dask is doing the right thing!


text:
Q: Парсинг JSON из локального файла Доброго времени суток! У меня есть локальный JSON файл в проекте и мне надо из него достать данные. но почему-то, когда я пытаюсь вывести эти данные в консоль у меня пишет "(null)" в консоли, вместо отображения данных  Выручите пожалуйста!
JSON
{"cities":[
    {"cityName":"Minsk", "countryCode":"BY", "cityDescription":"Minsk is the capital of Belarus"},
    {"cityName":"Moscow", "countryCode":"RUS", "cityDescription":"Moscow is the capital of Russia"},
    {"cityName":"Prague", "countryCode":"CZ", "cityDescription":"Prague is the capital of Czech Republic"},
    {"cityName":"Washington", "countryCode":"USA", "cityDescription":"Washington is the capital of United States of America"},
    {"cityName":"Stockholm", "countryCode":"SWN", "cityDescription":"Stockholm is the capital of Sweden"},
    {"cityName":"Beijing", "countryCode":"СHN", "cityDescription":"Beijing is the capital of China"},
    {"cityName":"Tokyo", "countryCode":"JPN", "cityDescription":"Tokyo is the capital of Japan"},
    {"cityName":"London", "countryCode":"UK", "cityDescription":"London is the capital of Great Britain"},
    {"cityName":"Madrid", "countryCode":"SPN", "cityDescription":"Madrid is the capital of Spain"},
    {"cityName":"Paris", "countryCode":"FR", "cityDescription":"Paris is the capital of France"}
]}

Objective-C
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"citiesJSON" ofType:@"json"];
    NSString *myJSON = [[NSString alloc] initWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:NULL];

    NSData *data = [NSData dataWithContentsOfFile:filePath];
    NSError *error = nil;
    NSDictionary *parsedJSON = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSArray *cityNames = [parsedJSON objectForKey:@"cityName"];
NSLog(@"%@", cityNames);

http://www.cyberforum.ru/objective-c/thread1570741.html#post8288750

A: Имя ключа в dictionary 'cities' а не 'cityName'. Измените последнюю строку:
NSArray *cityNames = [parsedJSON objectForKey:@"cities"];


text:
Q: ProgressBar Dialog not showing I am new to Android development and am facing a slight issue. My first screen is a basic log in screen. There is a LOG IN button on the screen and a OnClickHandler implemented for the button.
When the user clicks the log in button i validate the user name and password, shows a ProgressBar dialog start a new Thread. The thread connects to the server and validates the user info. The problem is that the Progress Bar doesn't show until after the thread has finished. I read that all work must be done in a separate thread otherwise the Progress Bar will not see the light of day and i am doing my work in a separate thread.
But the problem is that right below the thread code i have a loop while(userinfo==null){} . This is because the userinfo object is been populated by the newly created thread and the userinfo object is required by code below the thread, without the loop a new thread would be created that fills the userinfo object but in the mean time the code that reads the userinfo would get a null object. If any one is willing to review the code i could send the file that has this code. Really need some help in this.

A: You might find AsyncTask helpful. Do whatever it is you do in the loop in postexecute instead.


text:
Q: Very basic cumulative Distribution function problem. Let X ~ U[0,5]. Find cumulative distribution function of Y=min(2,x)
P(Y $\le$ t) = P (min(2,x) $\le$ t) = 1 - P (min(2,x)>t) = 1-P(2>x   and x>t)
for t<0 we have P(Y $\le$ t)=0
for t $\in$ [0,2) we have P(Y ≤ t)= 1-P(2>x   and x>t) = 1-P(x>t)=P(x$\le$t)=$\frac{1}{5}$$\int_0^t \! 1 \, \mathrm{d}x.$=$\frac{t}{5}$
for t$\in$[2,+${\displaystyle \infty}$) we have P(Y ≤ t)=1
But when we will calculate a probability density function we get :
 for $t \in [0,2)$  we have $\frac{1}{5}$ and for $t \notin [0,2)$ we have 0. So it seems that $$\int_{-\infty}^{\infty} \! ϱ_y \, \mathrm{d}x.=\frac{2}{5}$$.
Where is mistake in my justification ?.

A:
P(Y $\le$ t) = P (min(2,x) $\le$ t) = 1 - P (min(2,x)>t) = 1-P(2>x   and x>t)

No.
$$\begin{align}\mathsf P(Y\leq t) &= \mathsf P(X\leq t\cap 2\leq t) \qquad \star\text{ note: }2\leq t\text{, not }x\\[1ex] &= \mathsf P(X\leq t)\cdot\mathbf 1_{2\leq t}\\[1ex]&=\begin{cases}0 &:& t<2\\2/5 &:& t=2 &\star\text{ note: this is a point with a probability mass.}\\t/5 &:& 2< t < 5\\ 1 & :& 5\leq t\end{cases}\end{align}$$

A: The probability density has a delta function of value $\frac{3}{5}$ at $t=2$.


text:
Q: Custom Pagination Directive not Updating Correctly I'm designing a custom pagination directive for Angular 1, but the data binding doesn't seem to work correctly. The currentPage property seems to update without an issue, but my numberOfPages property doesn't seem to update in the DOM. Furthermore, I have a next and previous button which are disabled based on the current page, but only one of their expressions appears to be evaluated correctly. Here is my code:
My Directive:
angular.module('testModule').directive('pagination', ['_', function(_) {
return {
  restrict: 'E',
  templateUrl: 'templates/pagination.html',
  scope: {
    currentPage: '=',
    numberOfPages: '@',
    onPageSelected: '&',
  },
  controller: function($scope){
    $scope.pageNumbers = [1];

    $scope.$watch('numberOfPages', function(){
      if($scope.numberOfPages > 1){
        $scope.pageNumbers = _.range(1, $scope.numberOfPages);
      }
      else{
        $scope.pageNumbers = [1];
      }
    })

    $scope.selectPage = function(pageNo){
      if(pageNo < 1){
        $scope.currentPage = 1;
      }
      else if(pageNo >= $scope.numberOfPages){
        $scope.currentPage = $scope.numberOfPages;
      }
      else {
        $scope.currentPage = pageNo;
      }

      $scope.onPageSelected()($scope.currentPage);
    }
  }
};
}]);

My Template:
<div>
<button class="paginationTab" ng-click="selectPage(currentPage - 1)" ng-disabled="currentPage <= 1"><</button>
<button ng-repeat="pageNo in pageNumbers track by pageNo"
        ng-class="pageNo == currentPage ? 'selected paginationTab' : 'paginationTab'"
        ng-click="selectPage(pageNo)">
    {{pageNo}}
</button>
<button class="paginationTab" ng-click="selectPage(currentPage + 1)" ng-disabled="currentPage >= numberOfPages">></button>
</div>

currentPage and numberOfPages should both be numbers. onPageSelected is a function that takes a page number as an argument. I'm using npm to load angular v1.7.2 and underscore v1.9.1.
The Directive in use:
<pagination current-page="currentPage" number-of-pages="numberOfPages()" on-page-selected="onPageSelected"></pagination>

I can't understand why this code doesn't work as expected (there should be a button for each page but there isn't, and the 'next' button is never disabled no matter how far above the maximum number of pages you go). Can anybody see what's wrong with this directive?


text:
Q: WCF call from remote web application I'm new to WCF.  I've got a WCF service (VacationSickPayoutService) running on one website.  If I just declare, assign, and return a string, I can get the string from a remote website call to the WCF service - no problem.  But if, in that WCF service routine, I try and make a database call and then return a string value, it fails completely.  I'm sure I need some kind of authentication from the remote caller to allow the service to call the database?  I'm just using the same database login/call as a physical web user (human) would use if they were on the site and the database call was made.  I.e. the service uses the same functions.
Is there some change I could make to the web.config file on the service machine to allow the remote call to initiate a database call within the service routines?  This is the only reference I have to the WCF service in my web.config:
 <system.serviceModel>
      <behaviors>
        <serviceBehaviors>
          <behavior name="">
            <serviceMetadata httpGetEnabled="true" />
            <serviceDebug includeExceptionDetailInFaults="false" />
          </behavior>
        </serviceBehaviors>
      </behaviors>
      <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
    </system.serviceModel>
    <entityFramework>
      <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
        <parameters>
          <parameter value="v11.0" />
        </parameters>
      </defaultConnectionFactory>
    </entityFramework>

Do I need reference to the actual WCF service (VacationSickPayoutService) in the web.config file or is this something more complicated?
Also, forgot to mention that in order to consume the service I Added the Service Reference in the remote web application so I could see the function call that returns the string.
Thanks in advance!!!!

A: Authenticating to the database
You have three options for the credentials to use when calling the database from the WCF service. Which one you should use depends on where your service is being deployed.

*

*SQL Account (i.e., a username + password in the DB connection string)

*Integrated Authentication using the account that the WCF service is running under (e.g., a service account in your domain)

*Integrated Authentication using impersonation (i.e., the call to the DB is made to look as if the service were actually the remote user who is calling the service)

Option 3 is only possible in an intranet with a domain, since the users, service, and DB all have to be aware of the domain. Option 2 is more common because it's much easier to set up and, generally, gives you the same security benefits. Option 1 is recommended only when you don't have a domain available that both your service and your DB are aware of.
Assuming you use option 2, you'll need to create a domain account for your service. Then, wherever you have the service hosted, you'll need to use that account. Normally a WCF service is hosted in either IIS, or sometimes in a self-hosted command-line application. If you're using IIS, you need to set the identity of your AppPool to be the domain account you created for the service. And finally you'll need to give your domain account the necessary access in the database (e.g., in SQL Server you'll need to create a server & database login for the account and then grant it table read access, etc.).
Troubleshooting internal errors in the WCF service
When I started using WCF, I was doing a lot of blind debugging of errors, writing to log files, etc. Then I found this tool: Service Trace Viewer Tool (MSDN). It's the best way to analyze what is going wrong with a WCF service; it will capture everything that happens and let you search for the exceptions that are being thrown by, e.g., your data access code.
You may also want to set includeExceptionDetailInFaults = true while you are debugging, because that will (often) pass the detailed inner exception to your client so you can get some feedback that way. (Easier than bringing up the Service Trace Viewer Tool. :))
What account is the service running under?
You could modify your string-returning service method to return the string value of Thread.CurrentPrincipal.Identity.Name to see what account the service is running under. (MSDN documentation)


text:
Q: Appending an output file in C I am solving a problem on USACO. In the problem, I have to take two strings as inputs and calculate the numerical values modulo 47. If the values are same, then GO is to be printed otherwise STAY has to be printed. The initial numerical value will be calculated by taking the product of the numerical values of the alphabets ( 1 for A and similarily 26 for Z ) and then the final number will be calculated by using modulo.
My program is being compiled withour any error and the first case is also a success. But the problem is in the second case and the way my file is being appended. The program is as follows:-
#include<stdio.h>
#include<malloc.h>
#include<string.h>
#define MAX 6
main()
{
    int cal(char *ptr);
    int a,b;
    char *comet,*group;
    FILE *fptr;
    comet=malloc(6*sizeof(char));
    group=malloc(6*sizeof(char));
    scanf("%s",comet);
    a=cal(comet);
    scanf("%s",group);
    b=cal(group);
    fptr=fopen("ride.out","a+");                (1)
    //fptr=fopen("ride.txt","a+");              (2)
    if(a==b)
        fprintf(fptr,"GO\n");               (3)
        //printf("GO\n");                    (4)
    else
        fprintf(fptr,"STAY\n");              (5)
        //printf("STAY\n");                   (6)
    fclose(fptr);
    return 0;
}
int cal(char *ptr)
{
    int c,prod=1,mod;
    while(*ptr)
        {
                c=(*ptr++)-'A'+1;
                prod=prod*c;
        }
    mod=prod%47;
    return mod;
}

OUTPUT:-

The first case is the set two strings:-

*COMETQ

*HVNGAT

and the second case is given in the error notification itself.
If I remove the comment symbols from (2) and put it on (1), then the program is working fine because I can see the contents of the file and they appear just as the grader system wants. It isn't happening for the actual statement of (1). The comments of line (4) and (6) are also fine but not the line (1). I am not able figure this out. Any help?

A: First a few notes:

*

*main(): a decent main is either:
int main(void)
or
int main(int argc, char *argv[])

*Using malloc() you should always check if it returns NULL, aka fail, or not.

*Always free() malloc'ed objects.

*Everyone has his/hers/its own coding style. I have found this to be invaluable when it comes to C coding. Using it as a base for many other's to. Point being structured code is so much easier to read, debug, decode, etc.

More in detail on your code:
Signature of cal()
First line in main you declare the signature for cal(). Though this works you would probably put that above main, or put the cal() function in entirety above main.
Max length
You have a define #define MAX 6 that you never use. If it is maximum six characters and you read a string, you also have to account for the trailing zero.
E.g. from cplusplus.com scanf:

specifier 's': Any number of non-whitespace characters, stopping at the first whitespace character found. A terminating null character is automatically added at the end of the stored sequence.

Thus:
#define MAX_LEN_NAME    7
...
comet = malloc(sizeof(char) * MAX_LEN_NAME);

As it is good to learn to use malloc() there is nothing wrong about doing it like this here. But as it is as simple as it is you'd probably want to use:
char comet[MAX_LEN_NAME] = {0};
char group[MAX_LEN_NAME] = {0};

instead. At least: if using malloc then check for success and free when done, else use static array.
Safer scanf()
scanf() given "%s" does not stop reading at size of target buffer - it continues reading and writing the data to consecutive addresses in memory until it reads a white space.
E.g.:
/* data stream = "USACOeRRORbLAHbLAH NOP" */
comet = malloc(szieof(char) * 7);
scanf("%s", buf);

In memory we would have:
Address (example)
0x00000f           comet[0]
0x000010           comet[1]
0x000011           comet[2]
0x000012           comet[3]
0x000013           comet[4]
0x000014           comet[5]
0x000015           comet[6]
0x000016           comet[7]
0x000017           /* Anything; Here e.g. group starts, or perhaps fptr */
0x000018           /* Anything; */
0x000019           /* Anything; */
...

And when reading the proposed stream/string above we would not read USACOe in to comet but we would continue reading beyond the range of comet. In other words (might) overwriting other variables etc. This might sound stupid but as C is a low level language this is one of the things you have to know. And as you learn more you'll most probably also learn to love the power of it :)
To prevent this you could limit the read by e.g. using maximum length + [what to read]. E.g:
 scanf("%6[A-Z]", comet);
         | |      |
         | |      +------- Write to `comet`
         | +-------------- Read only A to Z
         +---------------- Read maximum 6 entities

Input data
Reading your expected result, your errors, your (N) comments etc. it sound like you should have a input file as well as an output file.
As your code is now it relies on reading data from standard input, aka stdin. Thus you also use scanf(). I suspect you should read from file with fscanf() instead.
So: something like:
FILE *fptr_in;
char *file_data = "ride.in";
int res;
...
if ((fptr_in = fopen(file_data, "r")) == NULL) {
    fprintf(stderr, "Unable to open %s for reading.\n", file_data);
    return 1; /* error code returned by program */
}
if ((res = fscanf(fptr_in, "%6[A-Z]%*[ \n]", comet)) != 1) {
    fprintf(stderr, "Read comet failed. Got %d.\n", res);
    return 2;
}

b = cal(comet);

if ((res = fscanf(fptr_in, "%6[A-Z]%*[ \n]", group)) != 1) {
    fprintf(stderr, "Read group failed. Got %d.\n", res);
    return 2;
}

...

The cal() function
First of, the naming. Say this was the beginning of a project that eventually would result in multiple files and thousand of lines of code. You would probably not have a function named cal(). Learn to give functions good names. The above link about coding style gives some points. IMHO do this in small projects as well. It is a good exercise that makes it easier when you write on bigger to huge ones. Name it e.g. cprod_mod_47().
Then the mod variable (and might c) is superfluous. An alternative could be:
int cprod_mod_47(char *str)
{
    int prod = 1;

    while (*str)
        prod *= *(str++) - 'A' + 1;

    return prod % 47;
}

Some more general suggestions
When compiling use many warning and error options. E.g. if using gcc say:
$ gcc -Wall -Wextra -pedantic -std=c89 -o my_prog my_prog.c

This is tremendous amount of help. Further is the use of tools like valgrind and gdb invaluable.


text:
Q: Angularjs - How to submit a form from different controller?

    <form name="form1" ng-submit="submitForm()">
        <input type="text" name="email" />
    </form>

    <button> Submit </button>

Here from ctrl2, I want to trigger form submit action for a form which is in ctrl1
How to achieve this in angularJs?

A: You could emit an event on the button click and then use rootscope to broadcast it down - ctrl1 could then listen for this an submit the form in response.

A: You can emit an event from the second controller and listen to it in the first controller.

function CtrlOne($rootScope)
{
  $rootScope.$on('submitEvent', function(event, args) {
      //submit your form here
  });
}

function CtrlTwo($scope,$rootScope)
{
  $scope.submit=function(){
    $rootScope.$emit('submitEvent', args);
  }
}

    <form name="form1" ng-submit="submitForm()">
        <input type="text" name="email" />
    </form>

    <button ng-click="submit()"> Submit </button>

A: You can achieve using $rootScope or services or event brodcasting
app.controller('ctrl2',['$scope','$rootScope',function($scope,$rootScope) {
    $scope.submitForm = $rootScope.mainSubmit();
}]);

app.run(function($rootScope){
    $rootScope.mainSubmit =function(){
        console.log("hey");
    };
})


text:
Q: How to define embedded properties in Loopback Model definition JSON file According to Loopback Documentation, we can define embedded document properties programmatically such as:
var UserModel = {
    firstName: String,
    lastName: String,
    address: {
      street: String,
      city: String,
      state: String,
      zipCode: String
    },
    ...
}

or
var AddressModel = {
    street: String,
    city: String,
    state: String,
    zipCode: String
};
var Address = ds.define('Address', AddressModel);
var UserModel = {
    firstName: String,
    lastName: String,
    address: 'Address',
    ...
}
// or address: Address
var User = ds.define('User', UserModel);

My question is whether we can also do it in the Model definition JSON file.
I found that you can create an other JSON file and then reference it directly in the module definition file as type.
ex.
{
"name": "Address",
"base": "Model",
"strict": true,
"idInjection": false,
"properties": {
  "id": false,
  "street": {
    "type": "string"
  },
  "city": {
    "type": "string"
  },
  "state": {
    "type": "string"
  },
  "zipCode": {
    "type": "string"
  },
  "country": {
    "type": "string"
  }
},
"validations": [],
"relations": {},
"acls": [],
"methods": {}
}

and then reference it the original JSON definition of User such as
address:{
    type:'Address'
}

But I haven't found how to directly declare it inside one JSON definition without requiring a different file. (Same as programmatically first example)
I have tried
address:{
    street: 'string',
    city: 'string'
    ...
}

but with no result. Data does not get verified and it considers it as an any type property that can save anything

A: Actually It seems that you can define sub document properties in Model Definition JSON file the way I mentioned like:
address:{
    street: 'string',
    city: 'string'
    ...
}

The problem is that this anonymous model is defined with no strict option, which defaults it to false, so any other property is also allowed...
I have also created an issue about this being fixed somehow in order to easily create subdocs without creating a separate separate definition JSON file.
Github issue


text:
Q: Wso2 connection with Mysql (SSL connection) in azure Not able to change the default H2 database to Mysql in WSO2 .
Getting SSL handshake error when connecting from WSO2 to Mysql(MySql is a saas hosted in azure)
Steps I have taken to connect to the MySQL 5.7 from wso2 api manager 260
1) I have added the https://www.digicert.com/CACerts/BaltimoreCyberTrustRoot.crt.pem to the client-truststore.jks
Link form where I got the crt is https://learn.microsoft.com/en-us/azure/mysql/howto-configure-ssl
2) I have updated the master-datasources.xml file
<url>jdbc:mysql://***.mysql.database.azure.com:3306/regdb?verifyServerCertificate=false&useSSL=true&requireSSL=false</url>
<username>***</username>
<password>***</password>
<driverClassName>com.mysql.jdbc.Driver</driverClassName>

3) Created the schema and the required tables as well
Below is the error log when starting the wso2 server
Start Level Event Dispatcher, received EOFException: error
Start Level Event Dispatcher, handling exception: javax.net.ssl.SSLHandshakeException: Remote host closed connection during handshake
Start Level Event Dispatcher, SEND TLSv1.2 ALERT:  fatal, description = handshake_failure
Start Level Event Dispatcher, WRITE: TLSv1.2 Alert, length = 2
Start Level Event Dispatcher, Exception sending alert: java.net.SocketException: Broken pipe (Write failed)


text:
Q: How to store data more effectively and efficiently in MongoDB? I am designing a project which store documents for each customer:

*

*There are Customers, Users, Companies and Documents.

*Each Customer has Users, Companies and Documents.

Should i create Collection for Companies and Documents and populate with Customer or store them in Customers Collection as arrays. Which way is more accurate?
To be more enlightening:

*

*ABC Accounting Office is a Customer.

*ABC has users and i store them in Users Collection with Customer ID.

*ABC has Companies and store Documents for each of them.


text:
Q: Jaccard Analysis Similarity I'm trying to do a Jaccard Analysis from R.
But, after the processing, my result columns are NULL.
I've tried to do a solution from many ways, but the problem still remains.
Can anyone help me please?
#######################PROCESSING JACCARD ANAYLSIS###################
Jaccard = function (x, y) {
M.11 = sum(x == 1 & y == 1)
M.10 = sum(x == 1 & y == 0)
M.01 = sum(x == 0 & y == 1)
return (M.11 / (M.11 + M.10 + M.01))
}

input.variables = data.frame(Q6_01, Q6_02, Q6_03, Q6_04, Q6_05, Q6_06, Q6_07, Q6_08)

m = matrix(data = NA, nrow = length(input.variables), ncol = length(input.variables))
for (r in 1:length(input.variables)) {
  for (c in 1:length(input.variables)) {
    if (c == r) {
      m[r,c] = 1
    } else if (c > r) {
      m[r,c] = Jaccard(input.variables[,r], input.variables[,c])
    }
  }
}

variable.names = sapply(input.variables, attr, "label")
colnames(m) = variable.names
rownames(m) = variable.names

jaccards = m

A: If you are trying to calculate Jaccard similarity, I would suggest checking out the vegan package. The vegdist() function can be used to calculate lots of different similarity/dissimilarity measures. Check out ?vegdist.
For Jaccard, you would use vegdist(your_dataframe_name, method = "jaccard")


text:
Q: The Ball From A Cross The proposition "from" is could be used to indicate the source.   In this example (context is soccer, or association football):

link
  "England were unable to score an equaliser - Olarticoechea making a particularly important defensive contribution in the 87th minute when he and Lineker both jumped for the ball from another Barnes cross, the two players collided, both missed the ball by a whisker..."

A ball is a physical object.  A cross is the act of sending a ball across the field.  The part:

"...when he and Lineker both jumped for the ball from another Barnes cross..."

suggests that a physical object (ball) could somehow appear as a result of an act (cross), which sounds weird.  An abstract version of "the ball from a cross" would be "[an object] from [an action]", which suggests that the "[action]" has a hand in creating the "[object]".
Would this:

"...he and Lineker both jumped for the ball on another Barnes cross...."

be possibily better?

A: I agree with your parsing of (he and Lineker) (jumped (for (the ball (from another cross))))
as opposed to the alternate given by @Jay of (he and Lineker) (jumped (for (the ball)) (from another cross)).  The natural assumption is that the ball came from the cross, not that the players came from the cross; especially since a cross is, as you say, an action performed on a ball.
However, I see no reason why the idea that a ball appears somewhere as the result of a cross should be weird; the whole point of a cross is to make the ball disappear from location A and appear at location B on the opposite side of the field.
So it doesn't seem odd at all to me, in fact it sounds perfectly reasonable and natural.

A: The word from is used to indicate who passed the ball (Barnes). In sports, a pass (or throw) uses the same prepositions as a birthday present:

a gift from my brother to my sister
  a touchdown pass from Manning to Harrison
  a scoring pass from Orr to Esposito
  a crossing pass from Barnes to Lineker
  a throw from Jeter to first base

As for your assertion that the wording "suggests that a physical object (ball) could somehow appear as a result of an act (cross)," that's not the case. The word from doesn't suggest that the ball was conjured out of nowhere, but that it got its direction from Barnes' foot. So:

he and Lineker both jumped for the ball from another Barnes cross

means the same as:

After a cross pass from Barnes, both he [Olarticoechea] and Lineker jumped for the ball.

I assure you, the preposition from sounds very natural to a sports fan in that context.

As for your initial assertion:

The proposition from is used to indicate the source.

That is an oversimplified view of a very flexible word. The word from can also be used:

*

*when stating who gives or sends you something → this package from Bob

*when something starts at a particular point and moves away → the puck from center ice

*when some condition is because of or as a result of something → clothes wet from the rain.

Little prepositions often have many uses.

A: I take it this is from the description of a football (soccer) game? Sorry, I'm not familiar with the terminology of the sport. But assuming that, as you say, a "cross" is an action ...
The quote does not say that the ball came from a cross. It says that they jumped from a cross. "For the ball" is a prepositional phrase acting as an adverb to modify "jumped". Eliminating some modifiers, you could simplify this sentence down to "[The two men] jumped from a cross." So they did a cross, and then from that cross they jumped.
The difficulty that often arises is that the same construction could have a totally different meaning. In a different context, you could say, "They asked for the ball from Sweden", meaning, they asked for the ball, and the ball is from Sweden.


text:
Q: Php Session user not working First of all, I do use session_start() at the beginning of the page.
This is a different session problem, my login code:
$email = $_POST['email'];
$senha = $_POST['senha']; //password

$user = new User();
$user->setEmail($email);
$user->setSenha($senha);
$dao = new UserDao();
$login = $dao->login($user);

if($login != false)
{
    $arrayL = $login->toArray();
    $_SESSION['user'] = $arrayL;
}

The problem is, the $_SESSION['user'] is not working, not passing the information to the others pages.
To check if the session is working I tried this:
if(!isset($_SESSION['ar']))
{
    $ar = array();
    $_SESSION['ar'] = $ar;
}
else
{
    $ar = $_SESSION['ar'];
    $ar[] = "mais1";
    $_SESSION['ar'] = $ar;
}

this one runs everytime the page loads, and its working, the $ar array is growing normally.
But to make the things a lot weird,
I did add this code to the login script, to check if is adding to the $ar array, just for testing:
$arrayL = $login->toArray();
$_SESSION['user'] = $arrayL;
$ar = $_SESSION['ar'];
$ar[] = $arrayL;
$_SESSION['ar'] = $ar;

At the start and at the end of the page I set a var_dump($_SESSION);
And for my surprise when I do login, it shows the $_SESSION['user] and the $ar array with the users details. But when I reload the page, its gone, the $ar array stays there normally but without the $user information, and the $_SESSION['user'] is completely gone.
What is going on?

A:  if(!isset($_SESSION['ar']))
    {
        $ar = array();
        $_SESSION['ar'] = $ar;

    }
else
    {
        $ar = $_SESSION['ar'];
        $ar[] = "mais1";
        $_SESSION['ar'] = $ar;
    }

so if the session "ar" is not set,   set session "ar" to $ar.  $ar is array consisting of "mais1".   when you do this $_SESSION['ar']['user'] is no longer there.


text:
Q: "Three or more groups" vs. "Three groups or more" In a paper I am writing there are two sections: one deals with two groups, and the other deals with more than two groups. I am wondering which of the following titles is better for the second section:

Three Groups or More

vs.

Three or More Groups

?

A: I think your question is more stylistic as both would be understood to mean the same thing.

Three or More Groups

would probably be more common and has more of an emphasis on the groupings if that's what's important in your paper

One or Two Groups  vs Three or More Groups


text:
Q: How to set value to a hidden property with a button? I have the following files:
view.jsp
<@ page import=...
<bean:define id="mForm" name="myForm" type="MyForm"/>
<html:form action="MyFoo" method="post" styleId="myForm" enctype="multipart/form-data">
<html:hidden property="boo"/>
<input type="button" value="Press me" onclick="javascript:changeBoo()"/>
</html:form>

MyForm.java
class MyForm {
    private boolean boo;
    public void setBoo(boolean boo){
        this.boo = boo;
    }
    public boolean getBoo(){
        return this.boo;
    }
}

MyFooAction.java
public class MyFooAction extends BaseAction {

    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        ActionForward aForward = null;
        String forward = "success";

        try {
            MyForm myForm = (MyForm) form;
            String boo = (String)request.getParameter("boo");
            if(boo.equals("true")){
                System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>DONE");
            }
            else {
                //some code here
            }
            aForward = mapping.findForward(forward);
        }
        catch (Exception e) {
            throw new Exception();
        }

        return aForward;
    }
}

The question is how to implement changeBoo() in Javascript in order to change the value of boo and to invoke MyFooAction with correct value of boo?

A: First, change your button to type="submit".  That will take care of submitting the form for you.  Notice how changeBoo() now returns a value for your onclick attribute.  This will submit the form if your function returns true.
Also, you'll need to add an id attribute to your hidden field so that you can easily get a reference to it from javascript:
<html:hidden property="boo" id="booId" />
<input type="submit" value="Press me" onclick="return changeBoo();"/>

Then it's just a matter of creating the javascript function:
function changeBoo(){
   var boo = document.getElementById('booId');
   boo.value = 'The new value';
   return true;
}

A: PS On your <html:form>...</html:form>, make sure you have a way to submit a form. This is usually done by adding <html:submit>.
Now, to come back to your question, your Javascript function will be like this (assuming that your ActionForm name specified on struts-config.xml is "myForm").
fumction changeBoo() {
  var boo = document.myForm.boo;
  if ("true" == boo.value.toLowerCase() || "yes" == boo.value.toLowerCase() || "1" == boo.value.toLowerCase()) {
     boo.value = "false";
  } else {
     boo.value = "true";
  }
}

Bear in mind that Struts converts boolean values to "true" or "false", "yes" or "no", "0" or "1".


text:
Q: Rails form not passing image with carrierwave I've currently got an upload form that takes an epub file, parses it using epubinfo and then displays in another form to validate the information we're extracting is correct. We then submit this new upload from this form.
This first form (upload.html.erb) seems to work exactly as I'd expect, extracting all the information I required, including the cover image and displays it appropriately in the edit/verification form (new.html.erb). However, the issue lies in this second form (new). Upon posting it doesn't retain the cover image that was displayed, instead not saving anything, even though any other changed (or unchanged) data in this form posts just as it should.
To note, when the upload form posts, public/tmp gets two files, the epub and the png, and upon posting the new form, the epub tmp goes away and gets put into public, however the png stays in public/tmp.
Ruby 2.1.1p76
Rails 4.1
CarrierWave 0.10.0
/views/pages/upload.html.erb
      <%= form_for Book.new, :url => new_book_path do |f| %>

      <%= f.label :book, "Upload an epub" %>
      <%= f.file_field :book, class: "form-control" %>
      <%= f.hidden_field :book_cache %>

      <%= f.button "Upload", class: "btn btn-primary", data: {disable_with: "Uploading..."} %>

  <% end %>

/app/controllers/books_controller.rb (somewhat sanitized):
class BooksController < ApplicationController
  before_action :redirect_to_book, only: [:index]
  before_action :set_book, only: [:show, :edit, :update, :destroy, :download]
  before_action :is_mod, only: [:edit, :update, :destroy]

    def create
    @books = Book.new(book_params)
    if @books.author.nil? && book_params[:author_name].present?
      @books.author = Author.where(name: book_params[:author_name]).first_or_create
    end
    if @books.series.nil? && book_params[:series_name].present?
      @books.series = Series.where(name: book_params[:series_name]).first_or_create
    end
    if book_params[:is_public].present?
    else
      @books.is_public == true
    end
    if @books.save
      redirect_to book_path(@books), success: "The book was successfully saved!"
    else
      redirect_to new_book_path
    end
  end

  def new
    @authors = Author.all
    @series = Series.all
    @books = Book.new(book_params)
    @books.extract_epub_info
  end

  private
    def set_book
      @books = Book.find(params[:id])
    rescue ActiveRecord::RecordNotFound
      redirect_to "/404"
    end

    def redirect_to_book
      redirect_to book_path(params[:book_id]) if params[:book_id]
    end

    def book_params
      params.require(:book).permit(:book, :cover, :title, :isbn, :summary, :is_public, :series_nbr, :author_id, :author_name, :series_id, :series_name, :tag_list, :book_cache)
    end

    def is_mod
      unless current_mod
        redirect_to book_path, error: "You're not allowed to edit books."
      end
    end

end

/app/uploaders/book_uploader.rb
class BookUploader < CarrierWave::Uploader::Base
  storage :file

  def store_dir
    "uploads/#{mounted_as}"
  end

  def filename
    "#{model.id}.epub"
  end

end

/app/uploaders/cover_uploader.rb
class CoverUploader < CarrierWave::Uploader::Base
  storage :file

  def store_dir
    "uploads/#{mounted_as}"
  end

  def filename
    "#{model.id}.png"
  end

end

/app/models/book.rb
class Book < ActiveRecord::Base
  belongs_to :author
  belongs_to :series
  has_many :downloads
  has_many :flags
  has_many :ratings
  has_many :raters, :through => :ratings, :source => :users

  validates :title, :author_id, presence: true

  attr_accessor :author_name, :series_name

  acts_as_taggable
  scope :public_books, ->{ where(is_public: true) }
  mount_uploader :book, BookUploader
  # validates_presence_of :book
  mount_uploader :cover, CoverUploader
  # validates_presence_of :cover

    searchable do
      text :title
      text :summary
      text :isbn
    integer :is_public
    end

  def epub
    @epub ||= EPUBInfo.get(book.file.path)
  end

  def extract_epub_info

    if epub.creators.first.name.include? ","
      self.author = Author.where(name: epub.creators.first.name).first_or_create
    else
      parts = epub.creators.first.name.split
      first = parts.first
      last = parts[1..-1].join(" ")

      self.author = Author.where(name: "#{last}, #{first}").first_or_create
    end

    self.title = epub.titles.first
    self.summary = epub.description
    self.is_public = true
    self.isbn = epub.identifiers.find{ |i| i.scheme == "ISBN" }.try(:identifier)

    if epub.cover.present?
      self.cover = epub.cover.tempfile
    else
    end
  end

end

And the edit form that displays the cover appropriately but doesn't post when you submit the form.
/views/books/new.html.erb:
<%= form_for @books, url: books_path, html: {multipart: true} do |f| %>
  <% if @books.errors.any? %>

<%= pluralize(@books.errors.count, "error") %> prohibited this author from being saved:

        <% @books.errors.full_messages.each do |msg| %>

<%= msg %>

        <% end %>

  <% end %>

    Please validate that all of this information is correct before saving the book!

  <% if @books.cover.present? %>

      <%= image_tag @books.cover %>

  <% end %>

    <%= f.label :title %>
    <%= f.text_field :title, class: "form-control" %>

    <%= f.label :author %>
    <%= f.collection_select(:author_id, @authors.order("name ASC"), :id, :name, {:include_blank => true} ) %>
    OR New Author Name:
    <%= f.text_field :author_name, class: "form-control" %>

    <%= f.label :isbn %>
    <%= f.text_field :isbn, class: "form-control" %>

    <%= f.label :summary %>
    <%= f.text_area :summary, class: "form-control", size: "20x10" %>

    <%= f.label :series_nbr %>
    <%= f.text_field :series_nbr, class: "form-control" %>

    <%= f.label :series %>
    <%= f.collection_select(:series_id, @series.order("name ASC"), :id, :name, {:include_blank => true} ) %>
    OR New Series Name:
    <%= f.text_field :series_name, class: "form-control" %>

    <%= f.label :tag_list %>
    <%= f.text_field :tag_list, class: "form-control" %>

  <%= f.hidden_field :book_cache %>

    <%= f.label :cover, "Upload a cover" %>
    <%= f.file_field :cover, class: "form-control" %>

    <%= f.hidden_field :is_public, :value => "1" %>
    <%= f.submit class: "btn btn-primary", data: { confirm: "Are you sure all of this information is correct?\rYou will not be able to edit it later." } %>

<% end %>

EDIT for routes 11/2 @ 9:20ET
routes.rb
App::Application.routes.draw do
  root "pages#home"

  # All pages
  get "browse" => "books"
  get "browse/new" => "books#newest"
  get "browse/popular" => "books#popular"
  get "browse/random" => "books#random"
  get "faq" => "pages#faq"
  get "empowerment" => "pages#empowerment"
  get "legal" => "pages#legal"
  get "pages/catalog"
  get "search" => "search#search"
  get "search/search"
  get "upload" => "pages#upload"
  get "download" => "pages#download"
  get "dmca" => "pages#dmca"

  # Catalog Routes
  get "catalog" => "catalog#index", defaults: {format: :atom}
  get "catalog/search" => "catalog#search", defaults: {format: :atom}
  %w{ newest popular random author title serie tag }.each do |section|
    get "catalog/#{section}", controller: :catalog, action: section, defaults: {format: :atom}
  end
  get "catalog/author/:id" => "catalog#authored_by", defaults: {format: :atom}
  get "catalog/tag/:tag" => "catalog#tagged", defaults: {format: :atom}

  # Normal Model stuff
  resources :authors
  resources :series
  resources :books do
    collection do
      get "tagged/:tag", action: :tagged, as: :tagged
      post "new", action: :new, as: :new_book
    end
    member do
      get :download
    end
  end
  resources :tags

  # Stuff for Mods and management
  devise_for :mods
  namespace "admin" do
    resources :mods
  end
  devise_scope :mod do
    get "mods" => "devise/sessions#new"
  end

  # Lists for dropdowns
  get "authorlist" => "books#authorlist"
  get "serieslist" => "books#serieslist"
  get "taglist" => "books#taglist"

  # Let's be nice and support old urls.
  get "book/show/id/:id" => "books#show"
  get "serie/:id" => "series#show"
  get "author/:id" => "authors#show"
  get "browse/author/:id" => "authors#show"

end

I'm not sure what else would be needed. I feel that what I'm missing is simple, but after staring at it for so long I've just stopped making any progress. I know that the cover image shows up in new.html.erb because it displays in the image_tag in the form, however upon post it doesn't save the param.
Halp! :(

A: /views/pages/upload.html.erb -- missing multipart: true
<%= form_for Book.new, html: { multipart: true } do |f| %>
I don't think you need to supply the url argument unless you've set up your routes/models incorrectly. You should change this in your other forms as well.
/app/controllers/books_controller.rb
You're completely missing edit/update methods. Is this by design? Why? Is this why you're supplying the url option in the forms? This promotes confusion.
Have you viewed the contents of book_params to see if the image data is being received correctly? What about checking to see if the actual image files have been created? If they are created, perhaps they're just not accessible (check file permissions).
FURTHER EDIT: I can't determine how things are routed based on what you've shown. Please show your routes as well, and clearly describe which actions result in the unwanted consequences.
i.e., "I want to create a new book, but the uploaded image isn't saved" (meaning it doesn't exist in the database and there's no actual image anywhere on the disk).
or
"I can create a book and save the image, but upon viewing the EDIT page, the image doesn't show up"


text:
Q: How to make a back-to-top button using CSS and HTML only? I'm trying to do a back to top button but to scroll down and up to a certain point on the page. For instance you have a long text and you want to bring the user to the next paragraph by simply having them to click on a link... I've done it in the past but I can't remember how I did it for the life of me...

A: Start of page

"The link has the href value of "#", which by definition means the start of the current document. Thus there is no need to worry about the correct way of setting up the destination anchor..."
Source

A: What you would want to do is put an "anchor" at the top of the page, using an  tag (it's not JUST useful for links!). Then, when you have a link that goes to #nameofanchor, it scrolls to the anchor with that name. You'd do it like this:

Back to top

Here is a working jsfiddle: http://jsfiddle.net/qf0m9arp/1/

A: Utilize the  tag.
At the top of your website, put an anchor with specified name.

Then your "back to top" link points to it.
back to top

A: This is the HTML only way:

foo content
foo bottom of page
Back to Top

There are quite a few other alternatives using jquery and jscript though which offer additional effects. It really just depends on what you are looking for.

A: first page

Basically what you have to do is replace the
" #top" with the id of the first section or your page, or it could be the nav... Any id locate in the first part of the page and then try to set some style with css!

A: If you want a simple "Top" button that floats as you scroll down the page you can do this:
HTML:
<button id="myBtn">Top</button>

CSS:

/*Floating Back-To-Top Button*/
    #myBtn {
        position: fixed;
        bottom: 10px;
        float: right;
        right: 18.5%;
        left: 77.25%;
        max-width: 30px;
        width: 100%;
        font-size: 12px;
        border-color: rgba(85, 85, 85, 0.2);
        background-color: rgb(100,100,100);
        padding: .5px;
        border-radius: 4px;

    }
/*On Hover Color Change*/
    #myBtn:hover {
        background-color: #7dbbf1;
    }

      <meta charset="utf-8">
      <meta http-equiv="X-UA-Compatible" content="IE=edge">
      <meta name="viewport" content="width=device-width,initial-scale=1.0">
      <title> Simple Back To Top Floating Button </title>

Scroll down and click the button

Scroll down this frame to see the effect!

Scroll Baby SCROLL!!

Lorem ipsum dolor dummy text sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

<button id="myBtn">Top</button>

A: I used a form with a single submit button. Point the "action" attribute to the ID of the element that needs to be navigated to. Worked for me with just "#top" without needing to define an ID in my stylesheet:
<form action="#top">
    <button type="submit">Back to Top</button>
</form>

Maybe a couple extra lines than is desirable but it's a button, at least. I find this the most concise and descriptive way to go about it.

A: To add to the existing answers, you can avoid affecting the URL by overriding the link with JavaScript. This will still take you to the top of the page without JavaScript, but will append # to the URL.
Back to top

A: Hope this helps somebody!

</>

Back to top..

A: I did my back-to-top button like this

HOME

    <button type="button" class= "btn btn-light" name="button" style="float: right;">Top</button>

A: This is my solution, HTML & CSS only for a back to top button, also my first post.
Fixed header of two lines at top of page, when scrolled 2nd line (with links) moves to top and is fixed. Links are Home, another page, Back, Top

  Some Text - That describes your site or page

  🏠 Home 👪 Gen 👈 Back 👆 Top

A: You can make back to top button using css and html using this syntax:
 back to top

for ex:
id = heading
back to top

when you click on back to top it scroll the screen at the heading id
*Tips:- please mention below code for smooth scrolling in css.
html{
scroll-behavior: smooth;
}

A: If you want to open a new link inside the iframe just add top element id of new page
Like https://example.com/ #topPageElementId


text:
Q: Show a set is open in C Show that the set O={z$\in\Bbb C$:Re(z)<0, Im(z)>0} is open in $\mathbb C$
I know this is the second quadrant, but I don't know how to do the proof.

A: Suppose that $z \in O$. We need to find $\epsilon > 0$ such that $w \in O$ for all $w$ with $\left|w-z\right| < \epsilon$
Let $z = -a + bi$, where $a,b$ are positive reals.
Then just take $\epsilon = \text{min}(a,b)$. For then, if $\left|w-z\right| < \epsilon$, where $w = -c + di$,we have
$$\left|a-c\right| + \left|b-d\right| \leq \left|w-z\right| < \epsilon$$
and so it follows that $c, d > 0$, that is $w \in O$.

A: Let $z_{0}=x_{0}+iy_{0}$ ($x_{0}$ and $y_{0}$ real numbers) be in this quadrant. Consider the ball $D(z_{0},r_{0})$ where $r_{0}=\min(|y_{0}|,|x_{0}|)$. Assume that $ z=x+iy (x,y \in \mathbb{R}) \in D(z_{0},r_{0})$. Then $|z-z_{0}|=\sqrt{(x-x_{0})^{2}+(y-y_{0})^{2}}<r_{0}$. Hence $|x-x_{0}|<|x_{0}|$ hence $x_{0}<x-x_{0}<-x_{0}$, [$x_{0}<0$ so $|x_{0}|=-x_{0}$], hence $2x_{0}<x<0$ so $x<0$. Similarly, $|y-y_{0}| \leq |z-z_{0}|<|y_{0}|$ so $-y_{0}<y-y_{0}<y_{0}$, hence $0<y<2y_{0}$.


text:
Q: How to get minimum value of Enum type declared in function type definition? Let's say I want to define a function that uses one of the constants defined for the given type. I tried:
minValue :: (Enum a,Bounded a) => a
minValue = minBound::a

but the function definition doesn't know that a is of type Enum, because that is specified in the declaration.

A: Two plausible answers:

*

*Delete the internal type signature.
minValue = minBound

While this works, it doesn't "scale" well to larger functions that need to do more stuff, where it may not be so obvious which type to use for minBound. That leads us to

*Turn on lexical scoping for type variables. You can start a scope with the forall keyword; then definitions in that scope can refer to type variables. Thus:
{-# LANGUAGE ScopedTypeVariables #-}
minValue :: forall a. (Enum a, Bounded a) => a
minValue = minBound :: a

A: What you're wanting here is ScopedTypeVariables, where the a in minValue's type signature is the same as the a used in the definition.  However, I have a suspicion that you don't need it for your use case.  The value minBound is polymorphic, and when something in Haskell is polymorphic it's usually call site polymorphic.  This means that the caller determines the type, not the definition.  For example, you could write something like
cycleBounded :: (Bounded a, Enum a, Eq a) => [a]
cycleBounded
    = minBound
    : map (\n -> if n == maxBound then minBound else succ n)
          cycleBounded

And then you could do something like cycleBounded :: [Bool] to get something equivalent to cycle [False, True].  However, you would run into a problem if you wanted to get rid of the Eq constraint by using fromEnum on n and maxBound before comparing, because then the compiler doesn't know what Bounded a => a to use for maxBound, there's nothing in the context that says that it has to use the same type as n, just that it's a (Enum a, Bounded a) => a.  This would be an appropriate application of ScopedTypeVariables:
{-# LANGUAGE ScopedTypeVariables #-}

cycleBounded :: forall a. (Bounded a, Enum a, Eq a) => [a]
cycleBounded
    = minBound
    : map (\n -> if fromEnum n == fromEnum (maxBound :: a) then minBound else succ n)
          cycleBounded

And while there are tricks to get these types to unify without the need for ScopedTypeVariables, most would probably find it more understandable to see ScopedTypeVariables and maxBound :: a than anything.  For the sake of completeness, here's how you could get it to unify:
cycleBounded
    = minBound
    : map (\n -> let {m = maxBound;
                      x = [m, n] -- This forces `m` and `n` to have the same type
                     }
                 in if fromEnum n == fromEnum (head x)
                        then minBound
                        else succ n)
          cycleBounded

Which is pretty ugly in my opinion.


text:
Q: Cannot access windows partition from ubuntu Upon clicking the windows partition in nautilus, i get this error thrown at me.
Error mounting /dev/sda4 at /media/zalgo/D8649C54649C36EA: Command-line `mount -t "ntfs" -o "uhelper=udisks2,nodev,nosuid,uid=1000,gid=1000" "/dev/sda4" "/media/zalgo/D8649C54649C36EA"' exited with non-zero exit status 14: The disk contains an unclean file system (0, 0).Metadata kept in Windows cache, refused to mount.Failed to mount '/dev/sda4': Operation not permitted The NTFS partition is in an unsafe state. Please resume and shutdown Windows fully (no hibernation or fast restarting), or mount the volume read-only with the 'ro' mount option.

I do not have fast boot or hibernation enabled on windows, if there are any commands that i should post the output of to help, please comment that.
This is not a duplicate of How can I access windows 10 partition in ubuntu when i cant get it to shut down in a "safe state"?, as the solution used there does not work here.

A: The solution I found that worked was a program called ntfsfix.
Install ntfs-3g with:
sudo apt-get install ntfs-3g

Then run the ntfsfix command on your NTFS partition.
For example:
ntfsfix /dev/sda4

A: This seems to be an issue with windows 10. In windows 10 the kernel and the drivers hibernate by default even when you shutdown the system. To disable this, do the following.

*

*Open control panel.(win key + r. Type control and hit enter)

*While in icons view, click on System and Security then power options.

*Click on Choose what the power buttons do on the Left hand side.

*Uncheck turn on fast startup. (you may need to press change settings that are currently unavailable before this)

*Click on save changes.

A: Boot into Windows 10. Open a command terminal in administrative mode. If sda4 is your only Windows partition, type:
chkdsk c:/f

and approve your desire to run that at the next reboot of Windows. Reboot Windows now. Once done, you should be able to mount the partition in Ubuntu.
If you have other Windows partitions that you are trying to mount in Ubuntu, change the c: in the above command to the correct drive letter.

A: Well, it appears that your ntfs partition has problems! Possibly physical damage on disk. If you have a initialization device I suggest you try to use it to enter in administration mode and try to run something from Windows to fix the disk problem at first. After that, reinstall Windows and restore your Linux bootloader(grub or whatever) or you can reinstall Linux(after fix and/or reinstall Windows) without to format all system(depends how you organized your partitions).


text:
Q: Missing link to keybindings.json in the Keyboard Shortcuts editor The VS Code documentation refers to a link to keybindings.json. This link is not present in my editor (see image). How can it be restored?

Where is keybindings.json located in Windows 10?
VS Code version: 1.29.0-insider (user setup)

A: I've tested this both on 1.28.0 and 1.29.0-insider. It seems that the link in question doesn't exist on the insider version. On my 1.28.0 installation, I can click the link and it will go to keybindings.json, which is found in C:\Users\<username>\AppData\Roaming\Code\User\keybindings.json. This link exists even if the file itself is deleted, and will create a new file at that location if you click it.
In the insider's version however, the link is gone, and the insider keybindings.json is installed for me by default in C:\Users\<username>\AppData\Roaming\Code - Insiders\User\keybindings.json.
If you want to open it up, you can open up the control palette with CTRL +SHIFT + P and select Preferences: Open Keyboard Shortcuts File. This does the same thing as clicking on that link in the non-insiders version, including creating the file if it doesn't exist.