text:
Q: Mutable/immutable data with foreign keys - a database design issue Let's say we have a webshop, where people can save their shipping/billing addresses for later use. We store our data in a relational database, so obviously the addresses get their own table. When the customer makes a purchase, we want to record which address did he select for his purchase, so that he can later review it in his purchase history. We can create a foreign key in the purchase table to the address table, so that the DB stays somewhat normalized, but this way, we have to ensure that the addresses are immutable, so that the shipping/billing addresses in the purchase history stay the same. The other approach is to replicate the addresses in the purchase table, so that the user can freely edit/delete from the addresses' table, and the purchase history stays the same. This replication scheme works well for small amounts of data, but let's say we want to attach a photo to each shipping/billing address, and now it's becoming too expensive, especially on resource constrained devices like smartphones. Which approach is the better? Are there any other ways of dealing with this pattern?

A: To allow users manage their addresses, you'll need to store info for whether the address has been used in purchase (by checking the purchases table or a separate flag in the addresses table). The key part of the solution here is this flag or check in the database indicating that an address has been used in a purchase, as mentioned by @sqlvogel.
This one piece of info will allow the following scenarios:

*

*Letting the user enter a new address - will not have an existing reference in the purchases history, so can also be edited before purchase.

*Letting the user pick an existing address, which may or may not have been used in a previous purchase.

*Letting the user change the address for a purchase, either by editing a new and unused address or picking one of the previously used addresses.

*If a user edits an existing and used address, save it as a new address instead of editing the original (and a good idea to let them know/see that a new address has been added).

You can provide a pseudo-deletion feature by adding a flag to an address indicating that it's a historical record (which you should also allow your users to know).
Shipping vs Billing address id: You may already have done this but these two need to be separate columns in the purchase table. So history is kept accurately with the controls above.


text:
Q: place ImageView on ImageButton so i want to crate a pause button for a game and i want to use the drawable button and the pause icon but it gives me this error

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.crazyromteam.musicworldrecreation/com.crazyromteam.musicworldrecreation.GameActivity}: android.view.InflateException: Binary XML file line #18 in com.crazyromteam.musicworldrecreation:layout/activity_game: android.widget.ImageButton cannot be cast to android.view.ViewGroup

here is my xml implemetation of this
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".GameActivity">
<FrameLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/holo_blue_dark">

    <ImageButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="10dp"
        android:src="@drawable/circle_button" >

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:src="@drawable/pause_button_small" />
</ImageButton>

    <com.crazyromteam.musicworldrecreation.GameSurfaceView
        android:id="@+id/surface"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@drawable/game_bg"/>

</FrameLayout>
</RelativeLayout>

A: If you are placing ImageView inside an ImageButton tag this is a crushing issue.
Try to change ImageButton image from java/kotlin code based on there onClick event

A: To answer your question of why you are receiving a RuntimeException, the key is here in your implementation of your ImageButton:
    <ImageButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="10dp"
        android:src="@drawable/circle_button" >

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:src="@drawable/pause_button_small" />
</ImageButton>

You are nesting the ImageView within the ImageButton. This is not allowed as stated in the exception:
android.widget.ImageButton cannot be cast to android.view.ViewGroup. A ViewGroup is a view which other views can be nested in, so when you nest a child view inside the ImageButton, it becomes intepreted as a ViewGroup, except the ImageButton cannot be interpreted that way. If you remove the nested ImageView, you will no longer receive this exception.
Your question is unclear to me as to what you are trying to attempt, but to simply state how to put the image on the ImageButton, declare the drawable in android:src, which you are already declaring on the ImageButton. That is where you image should go.
    <ImageButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="10dp"
        android:src="@drawable/pause_button_small" />

redpajama_set_name: RedPajamaStackExchange


text:
Q: Change function key behavior is OSX, but only for some f keys I highly doubt this is possible, but it's worth a try...
I have a new MacBook Pro, and I find myself ( as a VIM user ) accidentally hitting the F1 ( decrease Brightness) key regularly, when trying to hit ESC to get back into normal mode.  I have remapped F1 to ESC in my .vimrc, but it seems that the key doesn't register as F1 unless I have fn held down.  I know how to change this behavior in the System Preferences, but there are some function keys, like the volume control keys, that I want left how they are.
Sorry if this confusing, basically what I would like to know is whether I can set the Brightness keys to be set to F1 and F2 by default, while keeping the volume control keys set to volume control by default....

A: You want FunctionFlip.

A: Another option is to use a private.xml like this with KeyRemap4MacBook:
<?xml version="1.0"?>
<root>
  <item>
    <name>fkeys</name>
    <identifier>fkeys</identifier>
    <only>FKEYS</only>
    <autogen>__KeyToKey__ KeyCode::BRIGHTNESS_DOWN, KeyCode::F1</autogen>
    <autogen>__KeyToKey__ KeyCode::BRIGHTNESS_UP, KeyCode::F2</autogen>
    <autogen>__KeyToKey__ KeyCode::F1, KeyCode::BRIGHTNESS_DOWN</autogen>
    <autogen>__KeyToKey__ KeyCode::F2, KeyCode::BRIGHTNESS_UP</autogen>
  </item>
</root>

This would flip all F-keys when MacVim is frontmost:
<?xml version="1.0"?>
<root>
  <appdef>
    <appname>MACVIM</appname>
    <equal>org.vim.MacVim</equal>
  </appdef>
  <item>
    <name>fkeys</name>
    <identifier>fkeys</identifier>
    <only>MACVIM</only>
    <autogen>__KeyToKey__ KeyCode::BRIGHTNESS_DOWN, KeyCode::F1</autogen>
    <autogen>__KeyToKey__ KeyCode::BRIGHTNESS_UP, KeyCode::F2</autogen>
    <autogen>__KeyToKey__ KeyCode::EXPOSE_ALL, KeyCode::F3</autogen>
    <autogen>__KeyToKey__ KeyCode::LAUNCHPAD, KeyCode::F4</autogen>
    <autogen>__KeyToKey__ ConsumerKeyCode::KEYBOARDLIGHT_LOW, KeyCode::F5</autogen>
    <autogen>__KeyToKey__ ConsumerKeyCode::KEYBOARDLIGHT_HIGH, KeyCode::F6</autogen>
    <autogen>__KeyToKey__ ConsumerKeyCode::MUSIC_PREV, KeyCode::F7</autogen>
    <autogen>__KeyToKey__ ConsumerKeyCode::MUSIC_PLAY, KeyCode::F8</autogen>
    <autogen>__KeyToKey__ ConsumerKeyCode::MUSIC_NEXT, KeyCode::F9</autogen>
    <autogen>__KeyToKey__ ConsumerKeyCode::VOLUME_MUTE, KeyCode::F10</autogen>
    <autogen>__KeyToKey__ ConsumerKeyCode::VOLUME_DOWN, KeyCode::F11</autogen>
    <autogen>__KeyToKey__ ConsumerKeyCode::VOLUME_UP, KeyCode::F12</autogen>
    <autogen>__KeyToKey__ KeyCode::F1, KeyCode::BRIGHTNESS_DOWN</autogen>
    <autogen>__KeyToKey__ KeyCode::F2, KeyCode::BRIGHTNESS_UP</autogen>
    <autogen>__KeyToKey__ KeyCode::F3, KeyCode::EXPOSE_ALL</autogen>
    <autogen>__KeyToKey__ KeyCode::F4, KeyCode::LAUNCHPAD</autogen>
    <autogen>__KeyToKey__ KeyCode::F5, ConsumerKeyCode::KEYBOARDLIGHT_LOW</autogen>
    <autogen>__KeyToKey__ KeyCode::F6, ConsumerKeyCode::KEYBOARDLIGHT_HIGH</autogen>
    <autogen>__KeyToKey__ KeyCode::F7, ConsumerKeyCode::MUSIC_PREV</autogen>
    <autogen>__KeyToKey__ KeyCode::F8, ConsumerKeyCode::MUSIC_PLAY</autogen>
    <autogen>__KeyToKey__ KeyCode::F9, ConsumerKeyCode::MUSIC_NEXT</autogen>
    <autogen>__KeyToKey__ KeyCode::F10, ConsumerKeyCode::VOLUME_MUTE</autogen>
    <autogen>__KeyToKey__ KeyCode::F11, ConsumerKeyCode::VOLUME_DOWN</autogen>
    <autogen>__KeyToKey__ KeyCode::F12, ConsumerKeyCode::VOLUME_UP</autogen>
  </item>
</root>

A: You can invert fn behaviour and use tool like Spark to map keys you need to media actions.

A: Another related app which you may find useful for situations where you want the F1-F12 keys primary in one OSX application, and the brightness/volume/etc keys active in other apps, is Paula.
In addition to the function key mode following app focus, Paula also provides a configurable hotkey combination for toggling the current mode.


text:
Q: Авторизация PHP MVC модель Здравствуйте, имеется MVC модель сайта, смысл такой если человек авторизован имеет свою сессию, то контроллер возвращает по адресу "/admin" панель администратора. Если нет, то возвращает форму авторизации. Проблема заключается в следующем, что когда я авторизуюсь, то нужно обновить страницу вручную, что бы появилась панель администратора, если использовать header( "Location: /admin" ); то выкидывает ошибку - Warning: Cannot modify header information - headers already sent by
Что делать?
Код контроллера:
class AdminController
{
    public function actionPanel()
    {

        if (isset($_SESSION['users-login'])) {
            $client = AdminPanel::getSelectClientList();
            include_once ROOT . '/views/layaut/administrator/Panel.php';
        }else{
            include_once ROOT . '/views/layaut/administrator/Login.php';
        }
        return true;
    }
}

Код авторизации:
<?php
include_once ROOT . '/views/scripts/scripts.html';
include_once ROOT . '/views/views/administrator/Login.html';

$login = $_POST;
$errors = array();

if (isset($login['do_admin'])){
    $log = AdminPanel::getEntrance('users', $login['email'], $login['pass']);
    if ($log == false){
        $errors[] = 'Неверно введено имя пользователя или пароль';
    }
    if(empty($errors)){
        $_SESSION['users-login'] = $log;
        header( "Location: /admin" );
    }else {
        echo '
' .array_shift($errors).'
';
    }
}

сама форма HTML:

        <form action="\admin" method="post" class="form-signin">

Авторизация

            Адрес электронной почты
            <input name='email' type="email" id="inputEmail" class="form-control" placeholder="Адрес электронной почты" required="" autofocus="">
            пароль
            <input name='pass' type="password" id="inputPassword" class="form-control" placeholder="Пароль" required="">

            <button class="btn btn-lg btn-primary btn-block" type="submit" name="do_admin">Вход</button>
        </form>

A: Не надо ничего выводить на экран до header(), иначе он не будет работать. Надо удалить следующее:
include_once ROOT . '/views/scripts/scripts.html';
include_once ROOT . '/views/views/administrator/Login.html';

Тогда все будет работать.


text:
Q: Failed assertion issue on login page state The following assertion was thrown building LoginPage(dirty, state: _LoginPageState#bf00d):
A non-null String must be provided to a Text widget.
'package:flutter/src/widgets/text.dart':
Failed assertion: line 360 pos 10: 'data != null'
I have this error and looks like no issue in text.dart.
This is my loginPage.dart page.
I can't find the problem.
import 'package:flutter/material.dart';
import 'package:sporprojesi/login/primary_button.dart';
import 'package:sporprojesi/login/signin.dart';

class LoginPage extends StatefulWidget {
  LoginPage({Key key, this.title, this.auth, this.onSignIn}) : super(key: key);

  final String title;
  final BaseAuth auth;
  final VoidCallback onSignIn;

  @override
  _LoginPageState createState() => new _LoginPageState();
}

enum FormType {
  login,
  register
}

class _LoginPageState extends State<LoginPage> {
  static final formKey = new GlobalKey<FormState>();

  String _email;
  String _password;
  FormType _formType = FormType.login;
  String _authHint = '';

  @override
  void initState() {

    super.initState();}

  bool validateAndSave() {
    final form = formKey.currentState;
    if (form.validate()) {
      form.save();
      return true;
    }
    return false;
  }

  void validateAndSubmit() async {
    if (validateAndSave()) {
      try {
        String userId = _formType == FormType.login
            ? await widget.auth.signIn(_email, _password)
            : await widget.auth.createUser(_email, _password);
        setState(() {
          _authHint = 'Signed In\n\nUser id: $userId';
        });
        widget.onSignIn();
      }
      catch (e) {
        setState(() {
          _authHint = 'Sign In Error\n\n${e.toString()}';
        });
        print(e);
      }
    } else {
      setState(() {
        _authHint = '';
      });
    }
  }

  void moveToRegister() {
    formKey.currentState.reset();
    setState(() {
      _formType = FormType.register;
      _authHint = '';
    });
  }

  void moveToLogin() {
    formKey.currentState.reset();
    setState(() {
      _formType = FormType.login;
      _authHint = '';
    });
  }

  List<Widget> usernameAndPassword() {
    return [
      padded(child: new TextFormField(
        key: new Key('email'),
        decoration: new InputDecoration(labelText: 'Email'),
        autocorrect: false,
        validator: (val) => val.isEmpty ? 'Email can\'t be empty.' : "",
        onSaved: (val) => _email = val,
      )),
      padded(child: new TextFormField(
        key: new Key('password'),
        decoration: new InputDecoration(labelText: 'Password'),
        obscureText: true,
        autocorrect: false,
        validator: (val) => val.isEmpty ? 'Password can\'t be empty.' : "",
        onSaved: (val) => _password = val,
      )),
    ];
  }

  List<Widget> submitWidgets() {
    switch (_formType) {
      case FormType.login:
        return [
          new PrimaryButton(
              key: new Key('login'),
              text: 'Login',
              height: 44.0,
              onPressed: validateAndSubmit
          ),
          new FlatButton(
              key: new Key('need-account'),
              child: new Text("Need an account? Register"),
              onPressed: moveToRegister
          ),
        ];
      case FormType.register:
        return [
          new PrimaryButton(
              key: new Key('register'),
              text: 'Create an account',
              height: 44.0,
              onPressed: validateAndSubmit
          ),
          new FlatButton(
              key: new Key('need-login'),
              child: new Text("Have an account? Login"),
              onPressed: moveToLogin
          ),
        ];
    }
    return null;
  }

  Widget hintText() {
    return new Container(
      //height: 80.0,
        padding: const EdgeInsets.all(32.0),
        child: new Text(
            _authHint,
            key: new Key('hint'),
            style: new TextStyle(fontSize: 18.0, color: Colors.grey),
            textAlign: TextAlign.center)
    );
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
        appBar: new AppBar(
          title: new Text(widget.title),
        ),
        backgroundColor: Colors.grey[300],
        body: new SingleChildScrollView(child: new Container(
            padding: const EdgeInsets.all(16.0),
            child: new Column(
                children: [
                  new Card(
                      child: new Column(
                          mainAxisSize: MainAxisSize.min,
                          children: <Widget>[
                            new Container(
                                padding: const EdgeInsets.all(16.0),
                                child: new Form(
                                    key: formKey,
                                    child: new Column(
                                      crossAxisAlignment: CrossAxisAlignment.stretch,
                                      children: usernameAndPassword() + submitWidgets(),
                                    )
                                )
                            ),
                          ])
                  ),
                  hintText()
                ]
            )
        ))
    );
  }

  Widget padded({Widget child}) {
    return new Padding(
      padding: EdgeInsets.symmetric(vertical: 8.0),
      child: child,
    );
  }
}

A: Looks like _authHint is null
Modify hintText method like below where ?? operator used. Similarly, you should have for other Text Widget if required.
 Widget hintText() {
    return new Container(
      //height: 80.0,
        padding: const EdgeInsets.all(32.0),
        child: new Text(
            _authHint?? "",
            key: new Key('hint'),
            style: new TextStyle(fontSize: 18.0, color: Colors.grey),
            textAlign: TextAlign.center)
    );
  }


text:
Q: PHP echo repeating rows only once I have 2 tables. One table is 'headings' & contains Headings and the other one is 'sub-headings' and contains Sub-headings that are (& must be) classified under the Headings and must have a respective Heading. A Sub-Heading can have only one Heading and many sub-headings can have the same Heading. So consider the following format:
--Table heading

heading_id heading
1           H1
2           H2
3           H3

--Table sub_heading

sub_head_id sub_heading heading_id
1           SH1             1
2           SH2             1
3           SH3             2
4           SH4             3
5           SH5             2
6           SH6             4

What I would like to do is query the database only once and get all sub_headings and their corresponding headings (using Inner Join?) and output a Heading only once and list all the sub_headings listed under their respective Heading. So, in practice, I would like to show up the OUTPUT RESULT AS:
H1
--SH1
--SH2

H2
--SH3
--SH5

H3
--SH4

H4
--SH6

As you can see, the Headings are echo'ed only once and all the sub-headings that belong to a Heading are nicely shown under their respective Heading. So I would like to know what query I would write to do so.
NOTE: I have already written a code to fetch heading_id and while doing so in a loop, query the database for the respective sub-headings. This again results in loop of the sub_headings. But (I feel) the drawback in this is that for every single Heading that exists, the DB will be queried at least once to get their corresponding sub_headings. So if 50 Headings exist, while fetching them in a loop, a 2nd query is done to get the sub-headings. This needs me to write down a second query to get the sub-headings and process them in a loop. I want to avoid this.
So it would really help if anyone can tell me how to query the DB only once and output the result as I have indicated above. Thanks in advance.

A: select *
from heading h, subheading s
where s.h = h.id
order by h.title, s.title

loop over the result and when the heading_id changes, output a new section

A: $query = "SELECT
    h.heading,
    s.sub_heading
FROM
    heading h
LEFT JOIN
    sub_heading s
ON
    h.id = s.heading_id
ORDER BY
    s.heading_id ASC,
    s.sub_head_id ASC";

$resource = mysql_query($query);

$previous_heading = false;

// This will print the headings in a unordered list, modify if needed
echo '
';
while($resource = mysql_fetch_assoc($resource)) {
    if(!$previous_heading || $previous_heading != $resource['heading']) {
        if($previous_heading) {
            echo '

';
        }
        echo '
'.$resource['heading'].'
';
    }
    echo '
'.$resource['sub_heading'].'
';
    $previous_heading = $resource['heading'];
}
echo '

';

Will output something like

*

*H1

*

*SH1

*SH2

*H2

*

*SH3

*SH5

*H3

*

*SH4

*H4

*

*SH6


text:
Q: Find large $n$ and calculate $r \equiv L \pmod{n}$ where $L = 999\,998\,997\dots003\,002\,001.$ Update: I provided an answer but I tried something out with Python and I am kind of surprised. Computer technology today is more advanced than I can wrap my head around.
Instead of taking any residues at all I set my python program to directly add up all the terms in $L$,
$$ \Biggl [\sum_{n=0}^{498}\, \left(2001+2002\, n \right) {(10^{6})}^{n}\Biggl] + 999 \,{(10^{6})}^{499}$$
and then print out $L$. I expected the program to have serious problems number crunching, but it ran in a flash, printing
999998997996995994993992991990989988987986985984983982981980979978977976975974973972971970969968967966965964963962961960959958957956955954953952951950949948947946945944943942941940939938937936935934933932931930929928927926925924923922921920919918917916915914913912911910909908907906905904903902901900899898897896895894893892891890889888887886885884883882881880879878877876875874873872871870869868867866865864863862861860859858857856855854853852851850849848847846845844843842841840839838837836835834833832831830829828827826825824823822821820819818817816815814813812811810809808807806805804803802801800799798797796795794793792791790789788787786785784783782781780779778777776775774773772771770769768767766765764763762761760759758757756755754753752751750749748747746745744743742741740739738737736735734733732731730729728727726725724723722721720719718717716715714713712711710709708707706705704703702701700699698697696695694693692691690689688687686685684683682681680679678677676675674673672671670669668667666665664663662661660659658657656655654653652651650649648647646645644643642641640639638637636635634633632631630629628627626625624623622621620619618617616615614613612611610609608607606605604603602601600599598597596595594593592591590589588587586585584583582581580579578577576575574573572571570569568567566565564563562561560559558557556555554553552551550549548547546545544543542541540539538537536535534533532531530529528527526525524523522521520519518517516515514513512511510509508507506505504503502501500499498497496495494493492491490489488487486485484483482481480479478477476475474473472471470469468467466465464463462461460459458457456455454453452451450449448447446445444443442441440439438437436435434433432431430429428427426425424423422421420419418417416415414413412411410409408407406405404403402401400399398397396395394393392391390389388387386385384383382381380379378377376375374373372371370369368367366365364363362361360359358357356355354353352351350349348347346345344343342341340339338337336335334333332331330329328327326325324323322321320319318317316315314313312311310309308307306305304303302301300299298297296295294293292291290289288287286285284283282281280279278277276275274273272271270269268267266265264263262261260259258257256255254253252251250249248247246245244243242241240239238237236235234233232231230229228227226225224223222221220219218217216215214213212211210209208207206205204203202201200199198197196195194193192191190189188187186185184183182181180179178177176175174173172171170169168167166165164163162161160159158157156155154153152151150149148147146145144143142141140139138137136135134133132131130129128127126125124123122121120119118117116115114113112111110109108107106105104103102101100099098097096095094093092091090089088087086085084083082081080079078077076075074073072071070069068067066065064063062061060059058057056055054053052051050049048047046045044043042041040039038037036035034033032031030029028027026025024023022021020019018017016015014013012011010009008007006005004003002001

(use the slider bar)
That was amazing - you can find the remainder by directly dividing $L$ itself and not worrying about inserting any extra residue steps!
I will be going to summer school now to catch up with current technology.

For any $n \ge 1$ with there is a corresponding remainder $r$ obtained by dividing $L$ by $n$.
Now consider only $n$ satisfying
$\tag 1 n \lt 1000000$
$\tag 2 n \notin \{200000,
250000,
333333,
500000,
999999\}$

Calculate an explicit solution $(n,r)$ with $n$ as large as possible.

My Work
I became intrigued examining $L$ after seeing this question and giving an  answer.
I think I know the best possible answer $(n,r)$ but it would be interesting to see what mathematics this question sparks; a computer program can be used if necessary for 'mop-up' operations.

A: The largest $n$ that satisfies the conditions is $n=999998$, and it shouldn't be too difficult to do that. We're looking for
$$ L = 1 + 1000 \sum_{n=0}^{498} (3002+2002n)1000000^n  $$
which modulo 999998 is the same as
$$ L = 1 + 1000 \sum_{n=0}^{498} ( 3002+2002n) 2^n $$
To calculate this sum, first set
$$ X = \sum_{n=0}^{498} 2^n \qquad\qquad Y = \sum_{n=0}^{498}n2^n $$
By standard formulas we get
$$ X = \frac{2^{499}-1}{2-1} = 2^{499}-1 $$
and we can find $Y$ by a routine shifting trick:
$$ 2Y+2X = Y - 0\cdot 2^0 + 499\cdot 2^{499} $$
or in other words
$$ Y = 499\cdot 2^{499} - 2X = 497\cdot 2^{499} + 2 $$
Then
$$ L = 1 + 1000(3002X + 2002Y) = 4004001 + 1000\cdot 2^{499}(3002\cdot 499 + 2002\cdot 497) $$
The only real task that remains is to compute $2^{499}$ modulo $999998$. Even with pencil and paper it shouldn't take more than one sheet to compute this by
$$ a = 2^{15} = 32768 \\
b = 2^{30} = a^2 \\
c = 2^{31} = 2b \\
d = 2^{62} = c^2 \\
e = 2^{124} = d^2 \\
f = 2^{248} = e^2 \\
g = 2^{249} = 2f \\
h = 2^{498} = g^2 \\
i = 2^{499} = 2h $$
so just eight six-digit squarings or doublings with subsequent reductions modulo $999998$ (which is easy because $1000000\equiv 2$; one doesn't even need to do long division), and then three or four similar arithmetic operations to compute $L$.
I will leave the actual arithmetic to any reader who finds it worth his time.

A: Thanks to Henning Makholm and fleablood for helping me see the true power of modular arithmetic - and exponents be damned!
The key idea is you don't want to apply $\text{mod}(n)\text{-Residue}$ to get the remainder of an already big number like $10^{100}$. Instead you use recursion, defining $p_0 = 1$ and for $k \ge 0$,
$$ p_{k+1} =  [10^6 \times p_k]\; \text{mod}(n)\text{-Residue}$$
and you can then fold-in $\;p_{100}$ for $10^{100}$ in the remainder calculation.
Here is a python program to calculate remainders for that, now not so scary, large number $L$.
CODE
M = 1000000

def bP(i):
    p = 1
    for j in range(0, i):
        p = (p * M) % n
    return p

def getTerm(i):
    return ((2001 + 2002 * i) * bP(i)) % n

while True:
    print()
    n = int(input('Please input divisor: '))
    if n == 0:
        raise SystemExit
    r = 0
    for i in range(0, 499):
        r = (r + getTerm(i)) % n
    r = (r + 999 * bP(499)) % n
    print('Divisor =', n, 'Remainder =', r)

OUTPUT
Please input divisor: 13
Divisor = 13 Remainder = 6

Please input divisor: 999998
Divisor = 999998 Remainder = 487763

Please input divisor: 59470
Divisor = 59470 Remainder = 42391


text:
Q: How to save a compute engine VM-instance setup in Google Cloud Platform? I have created a compute engine VM-instance in Google Cloud Platform. Then I have installed go using the standard procedure downloading it from https://dl.google.com/go/go1.11.4.linux-amd64.tar.gz. Everything worked properly and I was able to run go application. However, after closing the instance when I reopened it, it says go is not installed. The message is following.
-bash: go: command not found
How can I save the instance setup?

A: Creating, Deleting, and Deprecating Custom Images

You can create custom images of boot disks and use these images to create new instances. This is ideal for situations where you have created and modified a persistent boot disk to a certain state and need to save that state to create new instances.

I think you should also consider using Docker containers.
Pushing and pulling images
Container-optimized VM images


text:
Q: Add only number from two string of data I want to make a list from the following data:
Ramesh CUB 10000
Rajesh IndianBank 20000
Ramesh CUB 20000
Arya ICICI 200000
Ramesh ICICI 20000
Rajesh KVB 30000
Vimala SBI 3000
Vimala YesBank 200000
Rajesh IndianBank 2000

such that Money from strings with same name and bank is added to get:
Expected Output
Ramesh  CUB 40000
Ramesh ICICI 20000
Rajesh  IndianBank  22000
Rajesh KVB 30000
Arya ICICI 202000
Vimala SBI 33000
Vimala YesBank 200000

A: Disclaimer: There are many possible ways to solve your problem ! Providing more context on your data and what you want to achieve, what you already tried could provide a more suitable response.
Proposition with pandas
If your data is contained in a file or a string one can see it as a pandas.DataFrame and use it's power :
import pandas as pd
from io import StringIO

pd.read_csv(StringIO('''Ramesh CUB 10000
Rajesh IndianBank 20000
Ramesh CUB 20000
Arya ICICI 200000
Ramesh ICICI 20000
Rajesh KVB 30000
Vimala SBI 3000
Vimala YesBank 200000
Rajesh IndianBank 2000
'''), sep=' ', header=None).groupby([0,1]).sum().reset_index()

Explanations :

*

*I transform the string in StringIO to make it readable by pd.read_csv

*I read the data

*I groupby the first two columns doing a sum

And the result is :
0   Arya    ICICI   200000
1   Rajesh  IndianBank  22000
2   Rajesh  KVB     30000
3   Ramesh  CUB     30000
4   Ramesh  ICICI   20000
5   Vimala  SBI     3000
6   Vimala  YesBank     200000

A: You have to create a list of elements where every element is like (x,y,z) where for example x = "Ramesh", y = "CUB", z = "10000".
After that you have your list then order by alphabetic order for the first element with the function:
your_list.sort(key=lambda x:x[0])

0 is the index that refers to your x values
If you want to order regarding the z then change 0 with 2

A: Given a string like this:
>>> txt
Ramesh CUB 10000
Rajesh IndianBank 20000
Ramesh CUB 20000
Arya ICICI 200000
Ramesh ICICI 20000
Rajesh KVB 30000
Vimala SBI 3000
Vimala YesBank 200000
Rajesh IndianBank 2000

You can create a dict as a counter and add the entries of splitting the lines into key, values:
di={}
for s in txt.splitlines():
    b,n=s.rsplit(maxsplit=1)
    di[b]=di.get(b,0)+int(n)

>>> di
{'Ramesh CUB': 30000, 'Rajesh IndianBank': 22000,
 'Arya ICICI': 200000, 'Ramesh ICICI': 20000,
 'Rajesh KVB': 30000, 'Vimala SBI': 3000,
 'Vimala YesBank': 200000}

Then rejoin into a string if so needed:
>>> print('\n'.join([f'{k} {v}' for k,v in di.items()]))
Ramesh CUB 30000
Rajesh IndianBank 22000
Arya ICICI 200000
Ramesh ICICI 20000
Rajesh KVB 30000
Vimala SBI 3000
Vimala YesBank 200000

A: Simple OOP solution :
# some fake data
data = [
    "Ramesh CUB 10000",
    "Rajesh IndianBank 20000",
    "Ramesh CUB 20000",
    "Arya ICICI 200000",
    "Ramesh ICICI 20000",
    "Rajesh KVB 30000",
    "Vimala SBI 3000",
    "vimala YesBank 200000",
    "Rajesh IndianBank 2000"
    ]

class Account:

    def __init__(self, name):
        self.name = name
        self.transactions = {}

    def add_transaction(self, trans):

        bank_trans = self.transactions.get(trans.bank, False)

        # if threre is no transaction for this bank
        if not bank_trans:
            bank_trans = []
            self.transactions[trans.bank] = bank_trans

        bank_trans.append(trans)

    def show_transactions(self):

        for bank in self.transactions:

            total = 0
            for trans in self.transactions[bank]:
                total += trans.value

            print(f"{self.name} {bank} {total}")

class Transaction:

    def __init__(self, bank, value):
        self.bank = bank
        self.value = value

def split_info(trans_data):

    accounts = {}

    for data in trans_data:
        name, bank, value = data.split(" ")

        account = accounts.get(name, False)

        # if there is no account
        if not account:
            account = Account(name)
            accounts[name] = account

        # make transaction for this bank
        trans = Transaction(bank, float(value))

        # add to accounts records
        account.add_transaction(trans)

    return accounts

def accounts_preview(accounts):

    for account in accounts.values():
        account.show_transactions()
        print("------------")

# get the extracted info
accounts = split_info(data)

# show each info
accounts_preview(accounts)


text:
Q: Conditionally applying styles to paperclip attachments in Rails 3.1 I have the following models:
Post.rb
  class Post < ActiveRecord::Base

  belongs_to :category
  has_many :attachments, :dependent => :destroy
  has_many :citations, :dependent => :destroy

  validates :title, :category_id, :content, :presence =>true

  acts_as_taggable_on :keywords
  accepts_nested_attributes_for :attachments, :allow_destroy => true,
         :reject_if => proc { |attributes| attributes['photo'].blank?}
  accepts_nested_attributes_for :citations, :allow_destroy=>true

end

Attachment.rb
  class Attachment < ActiveRecord::Base

  belongs_to :post

  has_attached_file :photo, :styles => { :medium => "637x471>",
                :thumb => Proc.new { |instance| instance.resize },
                :carousel => Proc.new { |instance| instance.decide_style }
                },
                :url => "/pictures/:style/:basename.:extension",
                :path =>":rails_root/public/pictures/:style/:basename.:extension"

  validates_attachment_content_type :photo, :content_type => ['image/png', 'image/jpg', 'image/jpeg']
    validates_attachment_size :photo, :less_than => 2.megabytes

   ### End Paperclip ####
  def decide_style

   # catid = Post.find(param[:post_category_id])
   # something here to get the selection from the form.

      if(catid == 2)
      # "400x800>" or custom style here
      end

      end

 def resize
 geo = Paperclip::Geometry.from_file(photo.to_file(:original))

 ratio = geo.width/geo.height

 min_width  = 142
 min_height = 119

 if ratio > 1
   # Horizontal Image
   final_height = min_height
   final_width  = final_height * ratio
   "#{final_width.round}x#{final_height.round}!"
 else
   # Vertical Image
   final_width  = min_width
   final_height = final_width * ratio
   "#{final_height.round}x#{final_width.round}!"
  end
 end

 end

I am trying to conditionally apply a style, based on the selection made from a drop down on the form. I am just not sure as to where the decision as to what style should be chosen is implemented.
Thoughts?
Rishi

A: It looks like you're trying to base it upon the category_id value on the Post model, is that right?  If so, you can actually pass a lambda as the value of the :styles entry in your attachment options, which includes the attachment as an attribute.
has_attached_file :photo,
    :styles => lambda { |attachment| {
      :medium => "637x471>",
      :thumb => attachment.instance.resize,
      :carousel => attachment.instance.decide_style,
    } },
    :url => "/pictures/:style/:basename.:extension",
    :path =>":rails_root/public/pictures/:style/:basename.:extension"

The attachment is a Paperclip::Attachment object, and calling the instance method on it returns your model instance.
Then in your decide_style method, you can base it upon your model's category_id value as needed.
def decide_style
  case category_id
  when 1 then "200x400>"
  when 2 then "400x800>"
  else "50x50#"
  end
end


text:
Q: Get LookupEdit's instance of gridControl I have reference to a LookUpEdit but I want to access it's GridControl object. We use the gridControlObject for exporting to excel.
I have found a previous question that is quite similar:
How to get instance of the GridControl in LookupEdit (Devexpress)
and the edited part of the answer does work, except only after the user has opened the LookUpEdit.
Is there any way accessing it without the user opening the drop down?
Failing that does anyone have a suggestion on how to force an open and close from code? Obviously LookUpEdit1.ShowPopup() will open it, but how do I wait for it to load?
Thanks

A: So I have figured out to make the popup open and close, would still be interested in a more intelligent solution!
in XAML code I adedd a PopupOpened property for the lookUpEdit
inside the popUpopened Method I raise an event.
So I register an interest in the popUpOpened Event, open the dropdown and close it again on receiving the event. Not overly proud of the solution but it does seem to work fine.


text:
Q: Call SQL Stored Procedure from PHP PDO I need to call a stored procedure to insert the data to sql and it return a value with output parameter
like
CREATE PROCEDURE InsertInfo
   @userid VARCHAR(100),
   @login_time DATETIME,
   @IsSuccuess BIT,
   @loginid INT OUTPUT
   AS
   BEGIN
      INSERT INTO Audit_LoginLogoutAttempt(UserID,Login_Time, IsSuccuess, DateCreated) VALUES (@userid,@login_time,@IsSuccuess, GETDATE())
      SET @loginid = @@IDENTITY
   END
   GO

How to send input and output parameters using PHP
  $stmt = $conn->prepare("{CALL InsertInfo(?, ?, ?, ?)}");
  $stmt->bindParam(1, $UserID);
  $stmt->bindParam(2, $LoggedInDateTime);
  $stmt->bindParam(3, $IsSuccuess);
  $stmt->bindParam(4, $get_id, PDO::PARAM_INT, 32);
  $stmt->execute();
  echo $get_id;

I tried like this but I'm not getting desired value from $get_id

A: You should bind your parameter as an OUTPUT parameter. If you have output parameters in your stored procedure and stored procedure returns recordsets, you need to fetch all recordsets to get output values.
<?php

# Statement
$stmt = $conn->prepare("{CALL InsertInfo(?, ?, ?, ?)}");
$stmt->bindParam(1, $UserID);
$stmt->bindParam(2, $LoggedInDateTime);
$stmt->bindParam(3, $IsSuccuess);
$stmt->bindParam(4, $get_id, PDO::PARAM_INT|PDO::PARAM_INPUT_OUTPUT, PDO::SQLSRV_PARAM_OUT_DEFAULT_SIZE);
$stmt->execute();

# Fetch results. Include this if your procedure returns resultsets (usually from SELECT statements):
#do {
#   while ($row = $stmt->fetch()) {
#       //
#   }
#} while ($stmt->nextRowset());

# Get OUTPUT parameter value
echo $get_id;

?>

I usually put SET NOCOUNT ON as first line in stored procedures. This prevents SQL Server from passing the count of rows affected as part of the result set.
CREATE PROCEDURE InsertInfo
   @userid VARCHAR(100),
   @login_time DATETIME,
   @IsSuccuess BIT,
   @loginid INT OUTPUT
AS
BEGIN
    SET NOCOUNT ON
    INSERT INTO Audit_LoginLogoutAttempt(UserID,Login_Time, IsSuccuess, DateCreated) VALUES (@userid,@login_time,@IsSuccuess, GETDATE())
    SET @loginid = @@IDENTITY
END


text:
Q: Advance Css3 property background gradient. How does it works? I am taking a very popular example from here. I want to understand how these patterns are being generated from gradient properties. I have just taken and compiled few examples below. Need to understand how to pass thing in gradient property so I can generate my own patterns.

.pattern {
  height: 100px
}

.pattern1 {
  background: radial-gradient(circle at 0% 50%, rgba(96, 16, 48, 0) 9px, #613 10px, rgba(96, 16, 48, 0) 11px) 0px 10px, radial-gradient(at 100% 100%, rgba(96, 16, 48, 0) 9px, #613 10px, rgba(96, 16, 48, 0) 11px), #8a3;
  background-size: 20px 20px;
}

.pattern2 {
  background: linear-gradient(63deg, #999 23%, transparent 23%) 7px 0, linear-gradient(63deg, transparent 74%, #999 78%), linear-gradient(63deg, transparent 34%, #999 38%, #999 58%, transparent 62%), #444;
  background-size: 16px 48px;
}

.pattern3 {
  background: radial-gradient(circle closest-side at 60% 43%, #b03 26%, rgba(187, 0, 51, 0) 27%), radial-gradient(circle closest-side at 40% 43%, #b03 26%, rgba(187, 0, 51, 0) 27%), radial-gradient(circle closest-side at 40% 22%, #d35 45%, rgba(221, 51, 85, 0) 46%), radial-gradient(circle closest-side at 60% 22%, #d35 45%, rgba(221, 51, 85, 0) 46%), radial-gradient(circle closest-side at 50% 35%, #d35 30%, rgba(221, 51, 85, 0) 31%), radial-gradient(circle closest-side at 60% 43%, #b03 26%, rgba(187, 0, 51, 0) 27%) 50px 50px, radial-gradient(circle closest-side at 40% 43%, #b03 26%, rgba(187, 0, 51, 0) 27%) 50px 50px, radial-gradient(circle closest-side at 40% 22%, #d35 45%, rgba(221, 51, 85, 0) 46%) 50px 50px, radial-gradient(circle closest-side at 60% 22%, #d35 45%, rgba(221, 51, 85, 0) 46%) 50px 50px, radial-gradient(circle closest-side at 50% 35%, #d35 30%, rgba(221, 51, 85, 0) 31%) 50px 50px;
  background-color: #b03;
  background-size: 100px 100px;
}

.pattern4 {
  background: linear-gradient(135deg, #ECEDDC 25%, transparent 25%) -50px 0, linear-gradient(225deg, #ECEDDC 25%, transparent 25%) -50px 0, linear-gradient(315deg, #ECEDDC 25%, transparent 25%), linear-gradient(45deg, #ECEDDC 25%, transparent 25%);
  background-size: 100px 100px;
  background-color: #EC173A;
}

A: If you want to understand how each pattern is built, you should deconstruct it by making it bigger (4x in following example) and replace each color by a distinct and more visible one.
Below, for the second pattern, I replaced background-color #444 by transparent at the end of line (tomato wasn't as clear) and replaced each occurence of #999 by a random color like blue, red, etc.
EDIT: and added a new line after each comma. One *-gradient per line shows there are 3 of them and a background-color.

.pattern {
  height: 192px;
}

.pattern2 {
  background: linear-gradient(63deg, red 23%, transparent 23%) 7px 0,
              linear-gradient(63deg, transparent 74%, blue 78%),
              linear-gradient(63deg, transparent 34%, darkgreen 38%, #999 58%, transparent 62%),
              transparent;
  background-size: 64px 192px;
}


text:
Q: Hover over radio button label and display an image I have a number of html radio buttons and what I would like to do is when
the radio button label is hovered over display an image. The radio buttons are in groups
with each button having a unique id. The code below I think should work but it does not.
Does anyone have a better solution.
HTML CODE

Name, text and logo

    <input class="form-check-input" type="radio" name="RoomLevel" id="RoomLevel_1" value="1">

CSS
.rhidden {
  display: none;
}

.place-image{
  display:none;
}

div.place-image{
  width:326px;
  height:326px;
}

JQUERY CODE
$(document).ready(function(){
  $('#RoomLevel_1').hover(
    function() {
      $('.place-image').fadeIn('slow');
    },function() {
      $('.place-image').fadeOut('slow');
    }
  );
});

A: Your code doesn't work because your radio button is inside .rhidden which is hidden, so you can't hover over the radio so the logo is never shown.

when the radio button label is hovered

So you don't want to attach your hover to the radio, you want to attach it to the label and can thus keep the radio itself hidden, likely for aesthetic reasons.
You can do this will CSS, without the need for jquery:

.rhidden {
  display:none;
}

.place-image {
  height:326px;
}

label.form-check-label .place-image {
  opacity:0;
  transition:0.6s all;
}

label.form-check-label:hover .place-image {
  opacity:1;
}

  Name, text and logo

    <input class="form-check-input" type="radio" name="RoomLevel" id="RoomLevel_1" value="1">

A: you are hovering on your input not on the label thats why it does not work, you can solve your problem like this if you don't want to select label directly

$(document).ready(function(){
    let label = $('#RoomLevel_1').parent().parent();
    $(label).hover(
      function() {
        $('.place-image').fadeIn('slow');
      },function() {
        $('.place-image').fadeOut('slow');
      }
    );
  });
.rhidden {
  display: none;
}

.place-image{
  display:none;
}

div.place-image{
  width:326px;
  height:326px;
}
Name, text and logo
   <input class="form-check-input" type="radio" name="RoomLevel" id="RoomLevel_1" value="1">

A: This fixed version works:

$("#RoomLevel_1").hover(function(){
  $(".place-image").fadeIn('slow')},function(){$(".place-image").fadeOut('slow')}).hover()
.place-image {display:none}

 Name, text and logo

  <input class="form-check-input" type="radio" name="RoomLevel" id="RoomLevel_1" value="1">


text:
Q: What is a feasable design goal for maximum clock frequency (related to setup timing) for a modern CPLD containing the attached circuit? The CPLD is an Altera MAX V, with speed grade 5 (note that the MAX V comes with speed grades 4 and 5, where 4 is the faster one). The circuit consists of a 5-bit binary up counter where the count value is compared to a 5-bit input data value, and if the count value is greater-or-equal to the data value, then a flag is set.
This flag is used as an input to a small FSM. The FSM diagram and datapath circuit is shown in the attached figure

The max clock frequency design goal is 100 MHz, but via the TimeQuest timing analyzer tool in Altera Quartus, I get Fmax = 92 MHz.
Is the design goal to strict or should I normally be able to achieve this clocking frequency ?
Note that the clock frequency is based on setup timing considerations. There are no PLLs or internally generated clocks.
Also note that the failing paths (there are two) are between the count-value bits, q_1/q_0 and a bit for the state encoding: state2...


text:
Q: how i redirect to different jsp page(not redirect to login page) after my session timeout in spring boot security I am added this in server.servlet.session.timeout=60s in myapplication.properties file. whenever my timeout happens if  press any action my page directly moved to login page and I don't want redirect to login page i want to redirect to different  page like (home.jsp).how to do it in spring security?

A: You can do the following, for more details on topic visit this page https://www.baeldung.com/spring-security-logout
@Override
    protected void configure(HttpSecurity http) throws Exception {
        http.logout()
                // other HTTP configurations are removed for simplicity
                .invalidateHttpSession(true)
                .clearAuthentication(true)
                .logoutSuccessUrl("/login?logout") // here you can put your redirect URL
                .permitAll();
    }

Note: note that you have to and() above config. If you have any other configurations for http in place.


text:
Q: how to make messages showed up in the template i have a login django app where i am trying to inform user in if they have wrong credentials  or if they are successfully login.
the problem is that i used the message framework in django but it did not showed up in the template.
views.py
from django.contrib import messages

def login_request(request):
    if request.method == "POST":
        username = request.POST['lognName']
        password = request.POST['lognCode']
        user = authenticate(username = username,password = password)
        if user is not None:
            login(request,user)
            messages.info(request,f"You are now logged in as {username}")
            return redirect("main")
        else:
            messages.error(request,"invalid username or password")

    return render(request,'login.html')

login.html
{% if messages %}
    {% for message in messages %}
        <script>M.toast({html:"{{message}}",classes:'blue rounded',displaylength:2000});</script>
    {% endfor %}
{% endif %}

even if i tried to used outside the if statement the toast doesn't work

A: Try to set the script inside
$(document).ready(function($) { /* foreach message M.toast(...) */ });
I will personally do it in a separate js file.
If you want to access to the messages object from js check out this link: Django Template Variables and Javascript


text:
Q: Change order of animation calls I have the following jquery to make all objects but the one hovered fade out and then fade back. However I want the element being hovered to fade to full opacity immediately, instead of waiting for the others to fade back.
$('a').bind('mouseenter',function(){
        $(this).fadeTo(0,1);
        $('a').not($(this)).fadeTo('fast', 0.25);
    }).bind('mouseleave',function(){
        $('a').fadeTo('slow', 1.0);
    });

http://jsfiddle.net/cutcopypaste/jQmZ3/1/

A: Try http://jsfiddle.net/jQmZ3/3/ ... Use a stop on all 'a' element's effect queues.
$('a').bind('mouseenter',function(){
    $('a').stop();
    $(this).fadeTo(0,1);
    $('a').not($(this)).fadeTo('fast', 0.25);
}).bind('mouseleave',function(){
    $('a').fadeTo('slow', 1.0);
});

A: If all you're needing is to "auto-focus" the hovered element, use $.show() to bring the element directly to the foreground. This works mainly because you cannot fade in this amount any more, thus you have the effect you desire.
$('a').bind('mouseenter',function(){
    $(this).show();
    $('a').not($(this)).fadeTo('fast', 0.25);
}).bind('mouseleave',function(){
    $('a').fadeTo('slow', 1.0);
});

http://jsfiddle.net/userdude/jQmZ3/2/


text: Q: Render Video as png with Alpha I have pixel art that I want to put in an animated png. I animated it in the timeline, but when I rendered it into a series of pngs, It has no partial transparency. Anyone know how to solve this?


text:
Q: ResultSet problems in DAO Forgive my lack of creativity when it comes to titeling this problem correctly.
Hi, i've spent the last 3 hours trying to figure out this problem, and I think i've figured it out, but the solution to it still eludes me. I have this very simple code.
    Statement stmt = db.getStatement();
    ResultSet queryResult = stmt.executeQuery("SELECT * FROM users");

    while(queryResult.next()) {
        username = queryResult.getString("username");
        password = queryResult.getString("password");
        privilege = queryResult.getInt("privilege");

        queryResult = stmt.executeQuery("SELECT * FROM division");
        while(queryResult.next()) {}

        users.add(new User(username, password, privilege));
    }

Now, this piece of code is dumbed down to illustrate what the problem is in my code. I don't have a while loop which contains nothing, obviously.
I've come to realize that whenever I want to fetch something from the database, I can only do it with the resultset within one loop. If I write a "nested-resultset-loop", I either get "Operation... ResultSet closed", "Cannot find column 'username'", or some other error.
I have alot of these nested resultset loops throughout my DAO code, to fetch everything from the database. Since i'm not that strong at MySQL, this was the simple solution (I have VERY little time left to do this program)... Since I used to do similiar back in PHP.
I'm not saying this code is good design, but for the sake of time, I really do not care much at the moment about good class design. So any solution you have in mind, regardless of poor design choice is welcomed.
Another solution would be to split everything up in single loops, because that tends to work (very simple). But that means modifying alot of the code, and i'd prefer this to be the backup plan.

A: You can't interleave the resultsets like that, see the API documentation:

By default, only one ResultSet object per Statement object can be open
  at the same time. Therefore, if the reading of one ResultSet object is
  interleaved with the reading of another, each must have been generated
  by different Statement objects. All execution methods in the Statement
  interface implicitly close a statment's current ResultSet object if an
  open one exists.

I think you'll be ok if you create separate statements for the different queries. The usual practice that I've seen is to have a separate DAO method for each query, in order to keep the DAO methods as simple and as reusable as possible. (That implies that the DAO isn't in charge of transaction demarcation, but that a higher level component, like a service, controls what's in a transaction.)

A: To fix your problem - do not assign the value of nested loops to the same ResultSet


text:
Q: PHP Duvidas como otimizar o Session Hoje utilizo o seguinte código para iniciar uma Sessão em PHP
 //verificação se o id de sessão ja existe, se não existir, cria
if (!session_id()){
   // iniciando a sessão
   session_start();
   // buffer para evitar o erro ao acionar o headlocation
   ob_start();

}

Como sou novo em PHP, gostaria saber...
Preciso realizar configurações adicionais para evitar problemas de acesso futuro? ou seja, quero evitar que o site que desenvolvi fique sobrecarregado.
Também percebi que a sessão só é finalizada quando eu fecho o navegador, qual é o tempo de expiração da sessão do php e é necessário mudar isso?
Dicas?
Estou utilizando a versão 5.6

A: Não tem muito que fazer em relação a isso,
Mas tenta aplicar este pequeno script que vai guardar a ultima requisição, com tempo de espera, vai prevenir ataques DDoS
// vou assumir que ja tens a sessão iniciada...
$uri = md5($_SERVER['REQUEST_URI']);

$exp = 3; // 3 segundos
$hash = $uri .'|'. time();
if (!isset($_SESSION['user'])) {
    $_SESSION['user'] = $hash;
}

list($_uri, $_exp) = explode('|', $_SESSION['user']);
if ($_uri == $uri && time() - $_exp < $exp) {
    header('HTTP/1.1 503 Service Unavailable');
    die;
}

// guardar a ultima requisição
$_SESSION['user'] = $hash;


text:
Q: n_dead_tup vs dead_tuple_count in postgresql? I initially thought n_dead_tup and dead_tuple_count in PostgreSQL give the same counts. But they seem to be not. I do not quite understand what exactly is difference.
Following are my observations:

*

*Created a table with 10k rows.

*Updated all the 10k rows. Now I have 10k dead tuples.

SELECT dead_tuple_count FROM public.pgstattuple('public.vacuum_test');

 dead_tuple_count
------------------
            10002

select * from pg_stat_get_dead_tuples('18466');

 pg_stat_get_dead_tuples
-------------------------
                   10002

*I did vacuum full on the table. As expected dead_tuple_count is 0.

SELECT dead_tuple_count FROM public.pgstattuple('public.vacuum_test');

 dead_tuple_count
------------------
                0

But n_dead_tup from pg_stat_all_tables i.e pg_stat_get_dead_tuples('18466') is still 10002:
select * from pg_stat_get_dead_tuples('18466');

 pg_stat_get_dead_tuples
-------------------------
                   10002

I repeated this process several times and observed that number of updated tuples is getting added to the stat n_dead_tup after every update.
So what exactly is VACUUM doing here?
And what is the difference between n_dead_tup and dead_tuple_count?

A: pgstattuple scans the tables and calculates real-time results. It can be quite slow for a big table, but produces accurate results.
Access to the pg_stat views, directly or via functions like pg_stat_get_dead_tuples, uses the most recent data collected by ANALYZE. So it can be out of date, especially if you just made big changes. However, it's very fast to access.
If you ANALYZE the table, the stats will match again, or close. They'll often not be exactly the same because the stats from ANALYZE are just estimates.
BTW, it's time to upgrade from 8.4 to something current.

A: VACUUM FULL is a little buggy in that it doesn't reset those statistics counters.  An ordinary VACUUM would do so.


text:
Q: bidirectional many-to-many association using a Map instead of a Set I'm having a bear of a time with this and any suggestions would be greatly appreciated.
I have a bi-directional many-to-many association mapping between two entities (FlashCard and Tag) that is currently successfully represented as a java.util.Set.  I'd like to change the collection type to a java.util.Map.
Here's an excerpt of the working mappings using Set

<class name="FlashCard" table="FLASHCARD">

    <id name="flashCardId" type="int" column="FLASHCARD_ID">
        <meta attribute="scope-set">public</meta>
        <generator class="native" />
    </id>

    <property name="question" type="string">
        <meta attribute="use-in-tostring">true</meta>
        <column name="QUESTION" not-null="true" unique="true" />
    </property>

    <set name="tags" table="FLASHCARD_TAG">
        <meta attribute="field-description">Tags for this FlashCard</meta>
        <key column="FLASHCARD_ID" />
        <many-to-many class="Tag"
            column="TAG_ID" />
    </set>

</class>

<class name="Tag" table="TAG">

    <id name="tagId" type="int" column="TAG_ID">
        <meta attribute="scope-set">public</meta>
        <generator class="native" />
    </id>

    <property name="name" type="string">
        <meta attribute="use-in-tostring">true</meta>
        <column name="NAME" not-null="true" unique="true" />
    </property>

    <set name="flashcards" table="FLASHCARD_TAG" inverse="true">
        <meta attribute="field-description">FlashCards for this Tag</meta>
        <key column="TAG_ID" />
        <many-to-many class="FlashCard"
            column="FLASHCARD_ID" />
    </set>

</class>

Ok, so like I said this is working but I'd like to change the collection to type java.util.Map.
I played with the mappings quite a bit and was finally able to get the following to partially work.

<class name="FlashCard" table="FLASHCARD">

    <id name="flashCardId" type="int" column="FLASHCARD_ID">
        <meta attribute="scope-set">public</meta>
        <generator class="native" />
    </id>

    <property name="question" type="string">
        <meta attribute="use-in-tostring">true</meta>
        <column name="QUESTION" not-null="true" unique="true" />
    </property>

    <map name="tags" cascade="all" table="FLASHCARD_TAG">
        <meta attribute="field-description">Tags for this FlashCard</meta>
        <key column="FLASHCARD_ID" not-null="true" />
        <map-key type="String" column="NAME" formula="NAME"/>
        <many-to-many column="TAG_ID" class="Tag"/>
    </map>

</class>

<class name="Tag" table="TAG">

    <id name="tagId" type="int" column="TAG_ID">
        <meta attribute="scope-set">public</meta>
        <generator class="native" />
    </id>

    <property name="name" type="string">
        <meta attribute="use-in-tostring">true</meta>
        <column name="NAME" not-null="true" unique="true" />
    </property>

    <map name="flashcards" inverse="true" cascade="all" table="FLASHCARD_TAG">
        <meta attribute="field-description">FlashCards for this Tag</meta>
        <key column="TAG_ID" not-null="true" />
        <map-key type="String" column="QUESTION" formula="QUESTION" />
        <many-to-many column="FLASHCARD_ID" class="FlashCard"/>
    </map>

</class>

When I say these mappings "partially work" I mean that I was able use these mapping to generate the database tables and the entity classes.  The entity classes did indeed include a collection of type java.util.Map.  This all looked find and compiles without errors.
However, when I run the code I get runtime errors from hibernate as follows:
org.hibernate.MappingException: Could not determine type for: String, at table: FLASHCARD_TAG, for columns: [org.hibernate.mapping.Formula( NAME )]
    at org.hibernate.mapping.SimpleValue.getType(SimpleValue.java:306)
The Hibernate documentation shows an example of a bi-directional many-to-many association but it uses a Set.  Here's a link to the docs.
Summary

*

*There are two entities: FlashCard and Tag

*The FlashCard entity has a collection of references to other entities of type Tag

*The Tag entity has a collection of references to other entities of type FlashCard

*This is a many-to-many, bi-directional association

*FLASHCARD_TAG is the association table

*The association is currently represented as a java.util.Set which according to the Hibernate documentation is the most commonly used collection mapping.

*I want to use java.util.Map instead of the java.util.Set

A: Bidirectional Association doesn't work using LIST & MAP.  It works fine using SET only. Using LIST it will generate unexpected values of index orders while persisting from both the sides and you got the error with MAP eventually.


text:
Q: 4o4 not found in cakephp controllers I have a CakePhp project placed in var/www/html/manage/
Manage folder contains (on ls)
CONTRIBUTING.md  app               build.xml      email      index.php  plugins
README.md        build.properties  composer.json  email.zip  lib        vendors

When i do http://domain/manage/
it gives me error, which is fine
!DOCTYPE html>

        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>
        CakePHP: the rapid development php framework:
        Errors  </title>
        <link href="/manage/favicon.ico" type="image/x-icon" rel="icon" />
        <link href="/manage/favicon.ico" type="image/x-icon" rel="shortcut icon" />
        <link rel="stylesheet" type="text/css" href="/manage/css/cake.generic.css" />

                    CakePHP: the rapid development php framework

Missing Controller

                    Error:
                    Controller could not be found.

                    Error:
    Create the class
                    Controller below in file: app/Controller/Controller.php

<?php
class Controller extends AppController {

I have a controller placed in app/Controller/
However when i try to do
http://domain/manage/users/registerAccount

Its giving me 404 not found error.
What am i missing

A: Ah ill make it an answer: Url by default wold be http://domain/manage/users/register-account in cakephp3


text:
Q: Python requests getting 404 response I've used this same script on several other vbulletin forums and it works on all of them except this site. I've searched and searched, looked for typos etc... and just can't figure this out. I've created a dummy user account to log in with.
website = www.thereeftank.com
username imadummy
password Imadummy123
Here's my code, I'm getting a 404 response which I can't figure out.
import requests

r = requests.session()

forumURL = "http://www.thereeftank.com/forums/"

headers = {
        'User-Agent': 'Mozilla/5.0 (Windows; U; Windows NT 6.1; ru; rv:1.9.2.3) Gecko/20100401 Firefox/4.0 (.NET CLR 3.5.30729)',
        'Referer': 'http://thereeftank.com/forums/'}

loginpayload = {
    'vb_login_username': 'imadummy',
    'vb_login_password': '',
    's': '',
    'securitytoken': 'guest',
    'do': 'login',
    'vb_login_md5password': '91af104d37ced6cc91958929b52be1bb',
    'vb_login_md5password_utf': '91af104d37ced6cc91958929b52be1bb'}

def login():
    loginURL = forumURL + 'login.php?do=login'

    z = r.post(loginURL, data=loginpayload, headers=headers)
    print z.url
    print z
    if 'Thank you for logging in, imadummy.' in z.text:
        return True
    else:
        return False

print login()

A: After check the response content in "z", you actually got
Invalid Redirect URL (http://thereeftank.com/forums/)

change your headers by adding "www." to your Referer url can fix this issue.
headers = {
        'User-Agent': 'Mozilla/5.0 (Windows; U; Windows NT 6.1; ru; rv:1.9.2.3) Gecko/20100401 Firefox/4.0 (.NET CLR 3.5.30729)',
        'Referer': 'http://www.thereeftank.com/forums/'}


text:
Q: Event Receiver Compatibility We are running SharePoint 2010 and I have a request to create a Event Receiver in Visual Studio.
Since we are going to migrate to 2016 in the next year or so, I am wondering about compatibility.
Will my Event Receivers work with 2016?

A: All the event receivers will work as expected in 2016.
Hope this link can confirm the same - If i have an Event Receiver inside my SharePoint 2013 ,, is it suppose to work in sharepoint 2016 as-is


text:
Q: How to make user signup once, if I've built a business with two services that both requires signup? Am teacher and I make and sell Question bank (qbnak) for many standardize test.
I've built a business using two different service, in which both requires sign-up, So If i had a customer he should create two account one for the first service and another for the second in order to get to qbank each time
The first service is Teachable and the second is Speedexam .
So my Questions is:
How to automate user signup rather than doing it manually?
What is the permanent solution for this, What do you call it SSO/oAuth or API ?
And what are my options if SSO and API are not support in both services?
Thank you

A: Like you mentioned, what you're trying to achieve is generally referred to as SSO.

Single Sign On works by having a central server, which all the applications trust. When you login for the first time a cookie gets created on this central server. Then, whenever you try to access a second application, you get redirected to the central server, if you already have a cookie there, you will get redirected directly to the app with a token, without login prompts, which means you're already logged in.

(source: How to Implement Single Sign On)
You have a few options on how to implement this:

*

*Create your own authentication server and define your own processes around how the other application interact and perform authentication
   ⤷ (not recommend, time consuming and easy to get something wrong)

*Create your own authentication server compliant with available authentication standards like OpenID Connect and OAuth 2.0
   ⤷ (time consuming and complex, but at least you're following standards so less likely to really mess up)

*Delegate the authentication to a third-party authentication provider like Auth0
   ⤷ (easy to get started, depending on amount of usage it will cost you money instead of time)

Disclosure: Answer provider by an Auth0 employee.


text:
Q: How to make custom mappings as a prefix to existing/default mappings? I have a binding like this to paste above or below:
nmap bp o<ESC>p
nmap ap O<ESC>p

However its limited to paste from default register. Is it possible to make this work with any register? Like say ":bp or "+bp etc ? Basically I want to prepend o<ESC> to my next action.
This is a duplicate of Vim - mapping with an optional register prefix.


text:
Q: Snowflake scripting - store number variable in sql statement resulting in count I have a sql statement in a stored proc that I can't run without first building a string dynamically by passing in several variables. Then I run execute immediate :sqlString and I'm trying to return the resultset into an integer as the sql statement is a count. Is this possible? Or how do I return a count from a SQL statement that I can't use table literals to build the sql statement.
create or replace procedure(v_comp_key varchar,v_dest_table varchar, v_stg_table varchar)

returns integer

language sql

as

declare
  count_records_data_change integer := 0;

  str_records_no_change varchar;

begin

select count(*) into :count_records_data_change from(select :v_comp_key from table(:v_dest_table) where current_flag = true intersect select :v_comp_key from table(:v_stg_table));

str_records_no_change :=
'SELECT COUNT(*) FROM (SELECT ' ||  :v_comp_key
      || ' FROM ' || :v_dest_table || ' A WHERE A.CURRENT_FLAG = TRUE INTERSECT SELECT '
      || :v_comp_key || ' FROM ' || :v_stg_table || ' B)';
     count_records_data_change :=  (execute immediate str_records_no_change)
return count_records_data_change;

end;


text:
Q: How do I get Count of parent collection from child? I've got an ObservableCollection assigned to ItemsSource of a listbox. Listbox is using a DataTemplate which has a usercontrol in it which has items bound to each listboxitem's properties.
I have an up and down button on the usercontrol which moves an item up or down the list. The list is sorted by the property that I'm changing. Click up or down, the DisplayOrder property is changed, I'm using INotifyProperty to tell the ObservableCollection it needs to re-sort.
What is the best way for the usercontrol to get the item count so that I can disable the down button when an item reaches the bottom of the list. (The top is easy, I compare to 0)

A: listBox1.Items.Count ?
this.Parent.Controls.Count?

A: I see two ways of handling this.
The first is to pass a handle of your collection to each of your items (when they get added to the collection) so that they can calculate if they are the first or last item themselves.
The other is to expose writable properties on your items, such as CanGoUp and CanGoDown, and your parent control becomes responsible for setting these properties properly. I prefer this solution because it decouples the behavior of your parent list, from the child items. Even though the up/down buttons are placed on your child items, it's really a functionality of the parent list.


text:
Q: Ubuntu 20.04 - keyboard not working I just upgraded my laptop from 18.04.5 to 20.04 and my keyboard and mouse have stopped working.
The keyboard works in BIOS and when entering my password for cryptsetup but as soon as it's all fully loaded up, the mouse and keyboard stop working.
I've tried using the terminal/command line to enter sudo alt-get install xserver-xorg-input-all as suggested on a few sites. This has not helped at all!
Does anyone have any suggestions? I'm completely lost without my laptop!!
Thanks in advance.

A: The problem is Ubuntu thinks your PC is a tablet and diables the keyboard.
The fix below works if the following command gives you any number that is not 31 or 32.
cat /sys/class/dmi/id/chassis_type

How to fix this: (from https://askubuntu.com/a/1282269/558457)

There is a bug in recent kernels that disables some laptop keyboards. Mainly Acer and HP so far.  Can usually go to recovery and boot from kernel 5.4.0-42 or use an external keyboard.
Blacklisting the intel_vbtn kernel module is a workaround for this, as seen in Why my laptop's keyboard screwed up since kernel 5.4.0-47 till 5.8.0-20
To implement this, you can either create a new file in /etc/modprobe.d with the suffix .conf or use the main blacklist.conf file. The former may be preferable, since you can then just delete the file when it is no longer required (i.e. when the bug is fixed):
sudoedit /etc/modprobe.d/blacklist-intel_vbtn.conf
Add a line to the file, optionally with a comment explaining why you are doing this
# bug in module breaks keyboard, so don't load it
blacklist intel_vbtn

Save the file, exit and reboot.

A: Right! Have found a workaround. Have access to GNU GRUB menu as i have dual boot with windows. From There if i select 'advanced options' instead of the default and  boot from Linux 5.4.0-42-generic i have access to all keyboard and trackpad features.

A: Maybe it can be because of broken packages, try to fix files of ubuntu by going to the recovery mode and there will be many options to fix packages,boot file etc.
Grub Loader>advanced ubuntu settings>Recovey version a,b,c

A: Ubuntu 20.04 / CHUWI AEROBOOK
Have the same issue, although in my case the keyboard stopped working after a few reboots right after install and config.

*

*Still works with USB keyboard after normal boot

*Laptop keyboard works after a recovery boot, but display settings are gone - no brightness control, no external monitor.

*Tried most of the solutions in posts online to no effect.

A: I had the same issue. I fixed it. In my case, 'slow keys' was turned on. If you are using ubuntu like me, on top right area of your screen beside brightness settings you will find an option with human icon.
There you will see slow key is turned on. Just turn it off. Check this way!


text:
Q: cannot convert string to numbers in pandas.read_excel Issue
I have an excel file in German format. It looks like this

I want to read the first column as numbers into pandas using the flowing code:
import pandas as pd
import numpy as np
tmp = pd.read_excel("test.xlsx", dtype = {"col1": np.float64})

It gives me the error
ValueError: Unable to convert column col1 to type <class 'numpy.float64'>

The issue is in excel. If I modify the col1 manuelly to number format, it solves the issue. See this new excel file:

Approach
I can first read col1 as object into pandas, then I need to replace , to ., at the last I can change the string to float.
However
The approach is tedious. How can I solve this problem more efficiently?

A: Unfortunately, there is no way to tell pandas what decimal separator is being used.
What you could do though is create a function to do the conversion and pass it to read_excel as part of the converters argument.
def fix_decimal(num):
### convert numeric value with comma as decimal separator to float
  print(num)
  return float(num.replace(',', '.')) if num else 0

tmp = pd.read_excel("test.xlsx", converters={0: fix_decimal} )


text:
Q: SQL Inner Join respect order of primary table (DBF files DBASE IV) I'm integrating a solution with a point of sale software. I'm almost done just need to get the ordering/sequence correct.
I'm working in VB.net.
This is my query:
 SELECT B.DESCRIPT AS description,
 B.REF_NO AS upc,
 A.QUANTY AS quantity,
 ROUND((A.PRICE_PAID * (1+(C.TAX_PCT/100))),2) AS unit_price,
 A.DEL_CODE AS discount_percent
 FROM (TABLE.DBF A INNER JOIN MENU.DBF B ON B.REF_NO = A.REF_NO),
 TAXTBL.DBF C
 WHERE C.TAX_DESC='TAX'

And it yields a result something like this:
(sequence is an auto-incrementing column set to the datatable)

The results from the query are being ordered by the upc/REF_NO, due to the inner join between TABLE.DBF and MENU.DBF. When I take out the MENU.DBF components, I get the correct order from TABLE.DBF.
I need to make this query respect the order from TABLE.DBF. The items should be ordered as such:

(time_sent doesnt help because (1) its a batch of items and (2) multiple items can be added even within the same second)
Thanks for the help.

A: I am not sure about dbf, but in almost all SQL I have run into the order is an implementation detail, so you should not rely on it and should provide your own order.
That would mean using an ORDER BY xyz at the end of your query


text:
Q: Solaris 11 SMB server sometimes becomes unreachable for some Windows XP clients I've got a Solaris 11 box acting as a NAS/SAN for both a small virtualised environment (over iSCSI and NFS), as well as a central filestore for a global team (over SMB). It works fine for most people, but every now and again I get a report from a couple of guys over in the US (I'm in UK) that they can't reach the network share.
The specific message Windows reports is: \\10.1.1.1\share is not accessible [...] The semaphore timeout period has expired.
In Solaris, I've enabled some debug logging and notice that when this happens, I see entries in /var/adm/messages similar to:
Sep  7 00:02:48 lonsbrndnas01 smbd[24587]: [ID 208731 daemon.debug] WORKGROUP         <1D> flags=0x0
Sep  7 00:02:48 lonsbrndnas01 smbd[24587]: [ID 370951 daemon.debug]   10.13.111.34 ttl=300 flags=0x0 port=35328
Sep  7 00:04:39 lonsbrndnas01 smbsrv: [ID 421734 kern.notice] NOTICE: [LONSBRNDNAS01\guest]: filestream.hdr share not found
Sep  7 00:04:39 lonsbrndnas01 smbsrv: [ID 421734 kern.notice] NOTICE: [LONSBRNDNAS01\guest]: filestream.hdr share not found

and
Sep  6 20:53:12 lonsbrndnas01 smbsrv: [ID 421734 kern.notice] NOTICE: [NT Authority\Anonymous]: share access denied: IPC only
Sep  6 20:53:12 lonsbrndnas01 smbsrv: [ID 421734 kern.notice] NOTICE: [NT Authority\Anonymous]: share access denied: IPC only
Sep  6 20:53:46 lonsbrndnas01 last message repeated 2 times

This issue is resolved by restarting the smb server daemon on the Solaris server. The WinXP client can then access it.
I have two questions:

*

*What's causing this?

*Is there any way for Solaris to report the IP address of the connecting client when it encounters an error? At the moment it's difficult to match up error messages to clients.


text:
Q: How to convert (0,0) to [0,0] in prolog? I'm making a predicate distance/3 that calculates the distance between 2 points on a 2d plane. For example :
?- distance((0,0), (3,4), X).
X = 5
Yes

My predicate only works if (0,0) is the list [0,0]. Is there a way to make this conversion?

A: You can do this with a simple rule that unifies its left and right sides:
convert((A,B), [A,B]).

Demo.

A: Although the others have answered, keep in mind that (a,b) in Prolog is actually not what you might think it is:
?- write_canonical((a,b)).
','(a,b)
true.

So this is the term ','/2. If you are working with pairs, you can do two things that are probably "prettier":
Keep them as a "pair", a-b:
?- write_canonical(a-b).
-(a,b)
true.

The advantage here is that pairs like this can be manipulated with a bunch of de-facto standard predicates, for example keysort, as well as library(pairs).
Or, if they are actually a data structure that is part of your program, you might as well make that explicit, as in coor(a, b) for example. A distance in two-dimensional space will then take two coor/2 terms:
distance(coor(X1, Y1), coor(X2, Y2), D) :-
    D is sqrt((X1-X2)^2 + (Y1-Y2)^2).

If you don't know how many dimensions you have, you can then indeed keep the coordinates of each point in a list. The message here is that lists are meant for things that can have 0 or more elements in them, while pairs, or other terms with arity 2, or any term with a known arity, are more explicit about the number of elements they have.

A: If you just have a simple pair, you can use the univ operator and simply say something like:
X = (a,b) ,
X =.. [_|Y] .

which produces
X = (a,b) .
Y = [a,b] .

This doesn't work if X is something like (a,b,c), producing as it does
X = (a,b,c) .
Y = [a,(b,c)] .

[probably not what you want].
The more general case is pretty simple:
csv2list( X , [X]     ) :- % We have a list of length 1
  var(X) .                 % - if X is UNbound
csv2list( X , [X]     ) :- % We have a list of length 1
  nonvar(X) ,              % - if X is bound, and
  X \= (_,_) .             % - X is not a (_,_) term.
cs22list( Xs , [A|Ys] ) :- % otherwise (the general case) ,
  nonvar(Xs) ,             % - if X is bound, and
  Xs = (A,Bs) ,            % - X is a (_,) term,
  csv2list(Bs,Ys           % - recurse down added the first item to result list.
  .                        % Easy!


text:
Q: using updateOne inside a map, setting the filter to the unique id , $set is to the document and upsert is true. Even then new document is created
here is my code in the controller from where i am getting the records from my google calendar API and then passing that data to this function and the code inside the function which inserts the document (records) looks like this as below:
Holiday.bulkWrite(
    holidays.map((holiday) => ({
        updateOne: {
            filter: { holidayId: holiday.id },
            update: { $set: holiday },
            upsert: true,
        },
    }))
)

A: It's hard to tell what exactly the issue is because it is not Mongo related but code related, from what it seems you are just using the wrong field for the filter.
holiday.id is null, and we can see that the "inserted" documents do not have such field. You are basically executing the following update:
db.collection.update({
  holidayId: null
},
{
  "$set": {
    holidayId: "123"
    ... other fields
  }
},
{
  "upsert": true
})

I believe this simple fix would solve your issue, change .id To .holidayId:
Holiday.bulkWrite(
    holidays.map((holiday) => ({
        updateOne: {
            filter: { holidayId: holiday.holidayId },
            update: { $set: holiday },
            upsert: true,
        },
    }))
)


text:
Q: CMake creating shared and static library with different defines I want to create a static and a shared library using CMake to create the build environment. Furthermore it should create an ANSI and a UNICODE version.
I found this posting: Is it possible to get CMake to build both a static and shared version of the same library?
which told me that I can use multiple add_library statements to achieve this. When I tried it, it creates the libraries fine, but the posting doesn't tell me how to set different -D options depending on which version is built.
My CMakeLists.txt currently looks like this:
list(APPEND SUPPORT_SOURCE
    dll_main.cpp
)

add_definitions(-DBUILD_SUPPORT_DLL)

add_library(support SHARED ${SUPPORT_SOURCE} )
add_library(support_s STATIC ${SUPPORT_SOURCE} )
add_library(support_u SHARED ${SUPPORT_SOURCE} )
add_library(support_su STATIC ${SUPPORT_SOURCE} )

After all, when I build the DLL, the functions needs the __declspec(dllexport) declaration which it should not have in the static versions. Furthermore to build the UNICODE variant I need to pass -DUNICODE.
So I need to know which version is built and use appropriate build flags for it for the various targets.
Another thing I don't understand is, how I can create debug builds with a different name. I usually use the pattern libname.lib and libname_d.lib so I can have all possible versions in a single directory to link against.

A: You can set compiler flags per-target by using the target_compile_definitions command.  For example:
target_compile_definitions(support PRIVATE MY_SHARED_DEFINITION)
target_compile_definitions(support_s PRIVATE MY_STATIC_DEFINITION)

As for adding a postfix to your debug libraries, you can achieve this by setting the CMake variable CMAKE_DEBUG_POSTFIX:
set(CMAKE_DEBUG_POSTFIX _d)

This will cause all non-executable targets to have _d appended when built in Debug.  If you need more fine-grained control, you can set the DEBUG_POSTFIX property for individual targets:
set_target_properties(support support_s PROPERTIES DEBUG_POSTFIX -dbg)

This will override the global CMAKE_DEBUG_POSTFIX value for these two targets and give them a -dbg postfix instead.


text:
Q: Tensor must be from the same graph as Tensor in LinearClassifier with AdagradDA Optimizer I have been trying to use tf.optimizer.AdagradDA with a Linear Classifier. Here is my code:
def input_fn():
    features_in = { "random_var": tf.convert_to_tensor(np.random.randn(100)) }
    labels_in = tf.convert_to_tensor(np.random.choice([0, 1], size=(100,), p=[1./2, 1./2]))
    dataset =  tf.data.Dataset.from_tensors((features_in, labels_in))
    dataset.repeat(2)
    dataset.batch(1)

    iterator = dataset.make_one_shot_iterator()
    features, labels = iterator.get_next()
    return features, labels

def main():
    global_step_tensor = tf.Variable(0, trainable=False, name='global_step')

    optimizer = tf.train.AdagradDAOptimizer(learning_rate=0.001, global_step=global_step_tensor)
    columns = [tf.feature_column.numeric_column('random_var')]
    model = tf.estimator.LinearClassifier(optimizer=optimizer, feature_columns=columns)
    model.train(input_fn=input_fn)

When I'm running the code I'm getting one of the following errors:

*

*ValueError: Tensor("Identity_1:0", shape=(), dtype=int32) must be from the same graph as Tensor("linear/linear_model/random_var/weights/part_0:0", shape=(1, 1), dtype=float32_ref).

*ValueError: Tensor("Identity_1:0", shape=(), dtype=int32) must be from the same graph as Tensor("linear/head/AdagradDA/update_linear/linear_model/random_var/weights/part_0/Cast_2/x:0", shape=(), dtype=float32)

*ValueError: Tensor("Identity_1:0", shape=(), dtype=int32) must be from the same graph as Tensor("linear/linear/linear_model/random_var/weights/part_0/AdagradDA_1:0", shape=(1, 1), dtype=float32_ref).
When I run the same code with a FtrlOptimizer or a AdagradOptimize the code runs properly. So I'm guessing, the issue has to be related with the global_step_tensor instanciation.

Here are the things that I have tried so far:

*

*Move the code snippet into a with tf.Session() as sess:

*Creating the optimizer into the LinearClassifier constructor

A: Caveat: This works in TensorFlow 1.10.0 (and possible later). Apparently it does not work in TensorFlow 1.9.0 (and possibly earlier). See comment below by ZakJ.
You need to change the way you construct your optimizer object as follows:
optimizer = lambda: tf.train.AdagradDAOptimizer(learning_rate=0.001,global_step=tf.train.get_global_step())

1) Notice the lambda. This will create a callable, as opposed to a Tensorflow operation, which is what AdagradDAOptimizer would return on its own (without the lambda).
2) You can use tf.train.get_global_step() directly and don't have to define a global step tensor.
I'm not quite sure why you need to create a callable by adding the lambda in this case. But I guess whenever you want to use an optimizer that needs global_step (or you want to pass it, for example for learning rate decay) you need to set the optimizer to a callable (hence the need for lambda) instead of a Tensorflow operation.
This is also what the learning rate decay example does in the docs here.
This is the complete code I successfully ran on TensorFlow 1.10.0:
import tensorflow as tf
import numpy as np

def input_fn():
    features_in = { "random_var": tf.convert_to_tensor(np.random.randn(100)) }
    labels_in = tf.convert_to_tensor(np.random.choice([0, 1], size=(100,), p=[1./2, 1./2]))
    dataset =  tf.data.Dataset.from_tensors((features_in, labels_in))
    dataset.repeat(2)
    dataset.batch(1)

    iterator = dataset.make_one_shot_iterator()
    features, labels = iterator.get_next()
    return features, labels

def main():
    optimizer = lambda: tf.train.AdagradDAOptimizer(learning_rate=0.001,global_step=tf.train.get_global_step())
    columns = [tf.feature_column.numeric_column('random_var')]
    model = tf.estimator.LinearClassifier(optimizer=optimizer, feature_columns=columns)
    model.train(input_fn=input_fn)


text:
Q: Make only one page for each chapter Is it possible to generate only one page per chapter(or section) without splitting the document file?
The page width is fixed but the page height should be automatically adjusted by the content length of each chapter(or section), so each page height may differ depending on each chapter.
For instance, the PDF result woud look like:

Note that there should be no page break in each chapter.
My document class is memoir and I'm using pdflatex but, if I have to change class or compiler to accomplish this, I will.
Thank you.

A: Since standalone class doesn't define things like chapters, you will have to do your own formatting.
\documentclass[border=.25in,multi={minipage}]{standalone}
\usepackage{lipsum}

\setlength{\textwidth}{5in}% constant width document
\newcounter{chapter}
\newcommand{\chapter}[1]{% Chapter title
  \refstepcounter{chapter}%
  \centerline{\large\textbf{Chapter \thechapter}}%
  \smallskip\par
  \parbox{\textwidth}{\centering\Large #1}%
\medskip\par}

\begin{document}
\begin{minipage}{\textwidth}
\chapter{First}
\lipsum[1-2]
\end{minipage}
\begin{minipage}{\textwidth}
\chapter{Second}
\lipsum[3-7]
\end{minipage}
\end{document}


text:
Q: MultiSubnetFailover does not work with ODBC13/17 in Windows In Windows whether ODBC version 13/17 will work with MultiSubnetFailover keyword and in multisubnet cluster environment ?
Using ODBC13/17 in Windows, after failover, it fails to reconnect to the primary node and gives error as

Microsoft][ODBC Driver 13 for SQL Server]The connection is
  broken and recovery is not possible. The client driver attempted to
  recover the connection one or more times and all attempts failed.
  Increase the value of ConnectRetryCount to increase the number of
  recovery attempts

I use SQL server 2016 and 2 nodes in a different subnet.
My connection string looks like
"Driver={ODBC Driver 13 for SQL Server};Server="170.25.132.24";DB="test";USER="abc";PW="XXX";MultiSubnetFailover=No"

What is the expected result when we set MultiSubnetFailover=No ? Is it recommended to set MultiSubnetFailover=No in multisubnet cluster environment ?

A: There appears to be no benefit from setting MultiSubnetFailover=No
Microsoft states:

We recommend this setting for both single and multi-subnet connections
  to availability groups listeners and to SQL Server Failover Cluster
  Instance names. Enabling this option adds additional optimizations,
  even for single-subnet scenarios.

Listeners, Client Connectivity, Application Failover
The Microsoft ODBC Driver 17 for SQL Server is failover cluster capable:
ODBC Driver on Linux and macOS Support for High Availability and Disaster Recovery
You need to specify MultiSubnetFailover=Yes in your connection string, and
you should specify the availability group listener of the availability group as the server in your connection string.
If you are using Windows, I would suggest using the SQL Server native client:
SQL Server Native Client Support for High Availability, Disaster Recovery


text:
Q: Arrays and random numbers: count the times an integer is randomly generated
Possible Duplicate:
Count Frequency in a Randomly Generated List of Numbers

I am currently working with arrays and random numbers. I have a created a form that will let me generate random numbers from 1 - 20 with a textbox1 to choose the quantity of numbers displayed. I am displaying the results inside a multiline textbox2. I have been able to calculate the sum and average of the set of numbers generated.
My second step:
Is there away to tally or mark the times a number is generated and display it in the multiline textbox(last picture)? Would I need to create an array and make it full of zero?
private void button1_Click(object sender, EventArgs e)
{
    int n = Convert.ToInt32(textBox1.Text);
    int[] y = new int[n];
    double sum = 0;

    for (int i = 0; i < n; i++)
    {
        int x = 1 + r.Next(20);
        y[i] = x;
        sum += x;

        if (n < 101)
            textBox2.AppendText(x + " ");
    }

    double avg = sum / n;
    textBox2.AppendText(Environment.NewLine + sum + " " + avg + Environment.NewLine);

    double vsum = 0;

    for (int i = 0; i < n; i++)
        vsum += (y[i] - avg) * (y[i] - avg);
}

Form.cs

Count the times an integer is randomly selected

A:
"Would I need to create an array and make it full of zero?"

Yes, that would be a good start.
Have an array of counters (all initially zero) and count up the number of occurrences for each number as it appears.

A: You can add a Dictionary<int, int> counter that counts. Insert those lines after int x = ...
if (counter.ContainsKey(x))
    counter[x]++;
else
    counter.Add(x, 1);

After that the dictionary holds one key value pair for each distinct random number you have created and the number of time it has been created. You could also use the dictionary to replace the y array altogether.

A: You could also do a
Dictionary<int,int>

store the number in question as the key (the first int)
store the number of times generated as the value (the second int).
Dictionary<int,int> numbers = new Dictionary<int,int>();
//initialize dictionary
for (int i = 1; i < 21; i++)
{
   numbers.Add(i,0);
}

//this only covers generating number and adding to dictionary
Random random = new Random();
int nextNum = random.NextInt(1,20);
numbers[nextNum]++;

References:
http://www.dotnetperls.com/keyvaluepair
http://msdn.microsoft.com/en-us/library/xfhwa508.aspx

A: Here's the code that can do what you want:
        var r = new Random();
        var n = int.Parse(this.textBox1.Text);

        var y =
            Enumerable
                .Range(0, n)
                .Select(x => r.Next(20) + 1)
                .ToArray();

        var sum = y.Sum();
        var avg = (double)sum / (double)n;
        var frequency = y.ToLookup(x => x);

        textBox2.Text = String.Join(Environment.NewLine, new[]
        {
            "Results",
            String.Format("{0} {1}", sum, avg),
        }.Concat(Enumerable
            .Range(1, 20)
            .Select(x => String.Format("{0} ({1}x)", x, frequency[x].Count()))));

Running this with a value of 25 I got this result:
Results
278 11.12
1 (0x)
2 (2x)
3 (1x)
4 (1x)
5 (1x)
6 (2x)
7 (0x)
8 (1x)
9 (2x)
10 (4x)
11 (1x)
12 (0x)
13 (0x)
14 (0x)
15 (2x)
16 (1x)
17 (2x)
18 (2x)
19 (3x)
20 (0x)

Is that what you're after?


text:
Q: "df -h" is showing about 1/2 "Available" disk that the "Disk Utility" shows for same internal SSD. Which is correct? In mid-2012, I purchased a MacBook Pro, and replaced the internal HDD with a 256-GB Samsung SSD. I am starting a new project. Making sure I have enough disk space, I get conflicting results for the Available space in /dev/disk1:

I am using MacOS 10.11.6. (El Capitan) I have emptied the Trash and rebooted. There is a Trim Enabler utility for SSD that I installed, but never got working correctly.
I am ok with 120GB available, but not ok with just 53GB. Which one is correct?

A: They're both correct in that they are measuring two completely different things.
Disk Utility is measuring the volumes on the disk itself whereas df is measuring the file system.  To draw an analogy, one is calculating the surface area of the dining table and the other is measuring the surface area of the plates.
So, the important bits here are the available space.  Disk Utility is telling you that the disk itself has 120GB of available space.  df is telling you that on this particular partition/volume you only gave 53GB available.
So, the space isn't missing, its just not allocated by the filesystem.  How do you claim it?  Create a new partition, resize an existing partition, etc.


text:
Q: How to wait for animation end in ui-router $stateChangeStart? I use AngularJs in my project and ui-router within it.
I need gently fade out current view before navigate user to another one when he clicks on the link.
I've written directive for that and here is the link function for it:
link: function($scope, element) {

            $rootScope.$on('$stateChangeStart',
                function (event, toState, toParams, fromState, fromParams) {

                var $element = $('#fw');

                $element.animate({
                    opacity: 0
                }, 4000, function () {

                });

        }

But of course transition executes immediately and doesn't wait for animation ends.
I neither found solution to make jQuery animation sync nor suspend ui-router transition and then continue it in the animation callback.
Please advise.

A: the ui-router has built in support for animations, is there some reason you're using a custom directive?
https://github.com/angular-ui/ui-router/wiki/Frequently-Asked-Questions#how-to-animate-ui-view-with-ng-animate
There is a plunkr link on that page you can experiment with too-


text:
Q: cannot align css in php echo - jquery is not working here is the link of the code
http://snipsave.com/user/profile/karthikeyan#5352
the problem is when tha button view is clicked it fetches data from sql and displays it. it workz fine .. but when the button is aligned using CSS its not working ...
i just need the button to be on right side .. when clicked view .. it should show the detail one next line leaving a gab in between a title and content ...
can any1 help ??
thanks

A: Should be text-align
Try this replacing your original code
while($data = mysql_fetch_row($result)){
    echo("
$data[1]<button style=\"text-align:right;\" class=\"show\">View</button>$data[2]

");
}


text:
Q: Flutter - Persist data in Integration Tests I am using the package get_storage to persist some data in my app like login and retrieve some objects, when I run integration tests the data are always null and because of that I always need to login and download some data before making some tests.
Is it possible to run integration tests keeping the data from the app?


text:
Q: USB Devices not working. PS/2 is working Currently navigating round windows only using my keyboard.
I have been using Linux for the past couple of weeks (all the ports work fine there and on the bios) but when I boot into windows they all stop working.
in device manager it shows three Unknown devices within the "Other Devices" but I only have 2 connected (ps2 keyboard which is showing up fine under 'keyboards' and a mouse)
I connect to the Internet via a USB wireless adapter so I am unable to pull down and driver updates either.
I have no restore points either...
Please help me out with this I'm all out of ideas (tried turning off xhci in bios etc but that didn't work).
Any help would be appreciated... Sorry if I explained it badly also, it seems to be a pretty unique situation.

A: Ok, so this just got fixed after I managed to navigate through and pull down the latest windows updates (had to share internet with my laptop over an ethernet cable) and they seemed to fix it.
It seemed to be a Windows Update around the 31st August that broke it. But that day I had a power cut as well (even though the computer was off) that might have had an effect?
Anybody with problems in the future:
ps/2 keyboard > naviagte to windows updates > pull down the latest > restart


text:
Q: iOS How to set IB custom class to a Category I currently have 2 uitableview cells that both share the same base class. However, the 2 cells have different labels and buttons in them, so they need different header files. I have tried to fix my problem by creating 2 categories that extend the base class and setting each cell's class to its respective category. However, this does not work. Does anyone have any fixes?
Thanks in advanced

Chat_TableViewCell & Invite_TableViewCell share the base class MCSwipeTableViewCell

A: You can't set the custom class to a category, because a category doesn't change the class of an object, it merely adds new methods to a previously defined class.  Your cells will all be of the same class at runtime, only the method lookup table will be expanded by the category.
You will need to create actual subclasses of your MCSwipeTableCell class for your two cell types.


text:
Q: Xml serialization and different languages (internationalization) What is a good solution to do XML serialization in different languages (internationalization) so that tags and attributes are serialized to the same object with different language?
I save configuration in xml and want to support german and english for the xml.
I don't really know how a good approach for this issue looks like.
Best solution would be but doesn´t exist:
[XmlRoot("MyEnglishConfig,MeineDeuscheKonfiguration")]
public class Test
{
    [XmlElement(ElementName="Setting1,Einstellung1")]
    public String value1;
}

so that both xml versions are parsed correct:
<MyEnglishConfig>
    <Setting1>English value</Setting1>
<MyEnglishConfig>

<MeineDeuscheKonfiguration>
    <Einstellung1>deutscher Wert</Einstellung1>
</MeineDeuscheKonfiguration>

A:
What is a good solution to do XML serialization in different languages (internationalization) so that tags and attributes are serialized to the same object with different language?

Don't! That simply isn't a good thing to do, and virtually no libraries will help you do it. By all means localize and internationalize a maintenance UI; but leave the xml in a single culture. This is just asking for extreme pain. The type of people who are going to be manually editing an xml file probably aren't going to mind if they need to read tags in a different language.
If you needed to do that, XmlAttributeOverrides can be used to make a per-language serializer, but... yeuch.