Q: best way to access a windows service via GUI I'm curious about the best way for a C# gui to access the functions of a Windows Service, be it WCF or ServiceController or some other option.
I'll explain what I'm doing: on a regulated time interval the service will be zipping one hours worth of datafiles from location A and sending the zipped file to location B, this will be done in the background 24/7 or until the service is stopped by the user and runs even when no one is logged in (hence the need for service) I would like the user to be able to pull up a GUI program that will allow them several options:
1) change the location to zip from
2) change the location to zip to
3) manually start the zipping process for a DateTime range specified
Now most of the functions for zipping and timers is all stored within the service. SO im wondering if a ServiceController in the GUI program would allow me to send variables to/from the service (ie folderpath names as strings, various other data) or if I'll need to spend the time making a WCF and treat the GUI as the Client and the Windows service as a source.
It should be noted the GUI will likely recieve data from the service, but only to signify if it is currently busy zipping.

A: One option is to tave a WCF service embedded on your windows service. With this WCF you can control the behaviour without restarting the service.
But the best option IMO is to have this in a config file. You can add some keys, but you would have to restart the service when you update the config.
In this case you can try a workaround, as in this thread.
The config is a good place for this kind of detail, because it can be easily modified and, unlike a database, it will be always avaiable.

A: I don't fully understand what you're trying to say, but you define what the interface to your service is when you make it.  If the operations you define take in variables, then you can pass data from your application to the service.
From what you described, just make opertaions in the service to do those 3 things you listed then call those from a button click in your UI code.
WCF would be fine for this here's a basic introduction to it http://msdn.microsoft.com/en-us/library/bb332338.aspx.


Q: Make Less highlight search patterns instead of italicizing them To my understanding man uses less as a pager, and when searching for keywords using less it "highlights" keywords with italics. I find that really inconvenient, so I'd like to change this to something like vim's set hlsearch where the found pattern  has a different background.
I attempted to run man -P vim systemd but that quit with error status 1, so it looks like I'm stuck with less.
There was nothing that I was able to find in man less that helped (instead I found out that option -G will turn off highlighting all together which is even worse than italics).
That being said does anyone know how to achieve search highlighting (change background color) in man pages?
FYI I run Ubuntu 14.10
I came across this question seems to ask about the same thing but I am not sure if I follow how does this work (LESS_TERMCAP_so). The less man page does not mention this. (I get strange results with this solution)

A: Hit ESCu to turn off search highlighting in less after a search; a new search will turn it on again, so to permanently turn search highlighting off for a session hit -G.
Alternately put LESS='-G' in your environment, or run man like so:
LESS='-G' man less

Ironically this is all documented in the less manpage...
You can also put the following in the environment, e.g. in your .bash_profile:
export MANPAGER='less -G'

A: Found an answer over on the superuser: https://superuser.com/questions/566082/less-doesnt-highlight-search
Looks like it has to do with your TERM setting. For example, less highlighting acts normally (white background highlight) when in a normal gnome-terminal window, but when I'm in tmux, italics happens. The difference for me is that TERM is being set to "screen" when in tmux, but "xterm-256color" when not. When I set "TERM=xterm-256color" in the tmux window, highlighting in less goes back to background highlighting.

A: The mention of LESS_TERMCAP_so was incomplete.  That is less's special environment variable used to override the termcap so (standout) capability.  To use this capability, you have to provide a se (standend) capability as well.
The terminfo(5) manual page gives a summary of these features for terminfo (smso/rmso) and termcap (so/se) names:
   enter_standout_mode           smso       so        begin standout mode
   exit_standout_mode            rmso       se        exit standout mode

Its section on highlighting explains:

If  your  terminal  has  one  or  more  kinds  of  display
  attributes, these can be represented in a number  of  different ways.  You should choose one display form as standout mode, representing a good, high contrast, easy-on-the-eyes,  format  for  highlighting  error messages and other
  attention getters.  (If you have a choice,  reverse  video
  plus  half-bright  is  good, or reverse video alone.)  The
  sequences to enter and exit standout  mode  are  given  as
  smso  and  rmso, respectively.

If you want to use color for standout, you have to provide a corresponding LESS_TERMCAP_se which resets color.  This is relatively simple to do as long as you do not expect to use colors in the manual page for other reasons (such as using groff's SGR color feature).
Assuming the value suggested in a comment:
export LESS_TERMCAP_so=$'\E[30;43m'

then you could reset that for most terminals using
export LESS_TERMCAP_se=$'\E[39;49m'

By the way, the reason for the italics is that the terminal description for GNU screen uses the standard escape sequence for italics as its own standout/standend capabilities.  Some of that is discussed in the terminal database entry.

A: For tmux I set TERM to tmux-256color.
Amongst other nice things,
this has the "usual" reverse highlighting in less.
Works well when using something modern like fedora, or cygwin.
$ cat ~/.tmux.conf
⋮
set-option -g default-terminal tmux-256color

The ncurses packages on Centos however do not have the two tmux definitions (tmux and tmux-256color).
I imported them quite easily from fedora.
Slight wrinkle is that Centos' ncurses is too old to understand fedora's terminfo files directly.
On fedora:
$ infocmp tmux256-color >temp.txt

On Centos:
$ scp fedora-machine:temp.txt .
$ tic temp.txt

Then inside tmux:
$ TERM=tmux-256-color man tmux

Result!
FYI the tic command puts the compiled terminal description into your personal terminfo database,
i.e.,
~/.terminfo/t/tmux-256color (in this case).
Feel free to move this to the global database if that's what you want:
$ sudo mv ~/.terminfo/t/tmux-256color /usr/share/terminfo/t/


Q: Capture information of system-call I have a QEMU-KVM hypervisor (ubuntu) with several VMs.
What I want to do is capture all information of VMs system call to hypervisor (without any intervention to VM whatsoever) in real time within a log file.  I also want the information captured can be associated to which VM the system-call came from.
Is it possible?
If I want to write a program (in C or python) to do so, can anybody show resources on internet?

A: I have no idea how you want to use such information, but to capture all system calls done by vm you should run vm like:
strace kvm ....

Other possibility is to use systemtap.


Q: Sticky Table two header using CSS for all OS i have two table headers and i want to sticky it using CSS only. Here is my html, and also posted image of my table, i have all the dynamic data and columns.

                    test11
                    test12
                    test13

                    test21
                    test22
                    test23

                    data1
                    data2
                    data3

                    data1
                    data2
                    data3

                    data1
                    data2
                    data3

How can I make the headers sticky using only CSS?

A: Try below css. You have to change top: 20px; with height of .first_head.
.fix-table-paren thead .first_head th{ position: sticky; top: 0; }
.fix-table-paren thead .second_head th{ position: sticky; top: 20px; }


Q: How can i Tlit the layout from Left to Right? I want to know about the Layout which can be Tlit from Left to Right. please give me any suggestion for help out me.

A: You can create .xml layouts for when the phone is placed horizontal or vertical. To create a horizontal layout, simply create a new .xml file and check that you would like the layout to be horizontal.


Q: URL gives 404 ..Angularjs I'm having issue with my url..i actually was trying to remove # tag from my url..which is done but the problem is now if i'm having url like this

http://localhost/xyz

it redirects me to

http://localhost/xyz/home

but the if i try and refersh the same page

http://localhost/xyz/home

it gives 404
any one knows how to solve it..
Thanks.

A: so actually now i'm able to open http://localhost/xyz/home directly with url rewrite which will point to my index.html.but now the bigger issue is whenever i'm trying to run my project it says unable to start debugging and none of my service is getting called it says 405(metod not allowed).i tried iisrest.but no luck.
so if you have any ideas,please share and thank you.


Q: What are the differences between OLEDB/ODBC drivers when connecting to SQL Server? I have an SQL Server database, and I need to push data into it through vbscript, as well as pull data into Excel. I have found multiple connection strings, but no repository for the benefits of performance and functionality comparing them. The driver options (Provider=) I have found so far are:

*

*{SQL Server} (ODBC)

*SQLOLEDB (newer than ODBC, but being deprecated?)

*SQLOLEDB.1 (what Excel 2016 uses when clicking 'Get External Data', but not even mentioned on connectionstrings.com... I assume a newer version of the above, but still the deprecated technology?)

*SQLNCLI11 (native client, OLE DB)

*{SQL Server Native Client 11.0} (native client, ODBC)

Different things I read say that ODBC is better because it has been around longer. And that OLE DB has been around long enough to have the same advantages. And OLE DB was made to work with a certain company's applications. And ODBC was made by the same company. And OLE DB can connect to and from different kinds of applications better. And ODBC works better with databases. And Native is...Native, so must be better... because of the name?
I find multiple questions here on SO floating around with no or partial answers, or having multiple comments claiming the answers are out of date. So, as of now, what the specific differences between these different drivers? Do they have different performance in different circumstances? Do they have different features? Do I need to do profiling to determine the best performance and reliability for my particular use case, or is there a standard "best practice" recommended by Microsoft or some recognized expert? Or are they all basically doing the same thing and as long as it's installed on the target system it doesn't really matter?

A: ODBC-it is designed for connecting to relational databases.
However, OLE DB can access relational databases as well as nonrelational databases.
There is data in your mail servers, directory services, spreadsheets, and text files. OLE DB allows SQL Server to link to these nonrelational database systems. For instance, if you want to query, through SQL Server, the Active Directory on the domain controller, you couldn't do this with ODBC, because it's not a relational database. However, you could use an OLE DB provider to accomplish that.
http://www.sqlservercentral.com/Forums/Topic537592-338-1.aspx


Q: How to initialize and set a 2D array in golang I am trying to simplay make a 2D array as a field on an object. I want a function that creates the object and returns it. But when trying to create the 2d array it returns a single array.
type Struct struct {
    X int
    Y int
    Grid [][]bool
}

func NewLifeSimulator(sizeX, sizeY int) *Struct{
    s := &Struct{
        X:    sizeX,
        Y:    sizeY,
        Grid: make([][]bool, sizeX,sizeY),  //Creates a regular array instead of 2D
    }
    return s
}

What do I need to change so that my function initializes a 2D array?

A: The expression:
make([][]bool, sizeX)

will create a slice of []bools of size sizeX. Then you have to go through each element and initialize those to slices of sizeY. If you want a fully initialized array:
s := &Struct{
        X:    sizeX,
        Y:    sizeY,
        Grid: make([][]bool, sizeX),
    }

// At this point, s.Grid[i] has sizeX elements, all nil

for i:=range s.Grid {
   s.Grid[i]=make([]bool, sizeY)
}

The expression make([][]bool, sizeX, sizeY) creates a [][]bool slice with initial size sizeX and capacity sizeY.


Q: yarn workspaces monorepo with vite, react, tailwind - VS Code fails to resolve packages I have created a monorepo using yarn@3 workspaces.
My root package.json:
{
  "name": "hello-yarn-workspaces",
  "packageManager": "yarn@3.1.1",
  "workspaces": [
    "apps/*",
    "packages/*"
  ],
  "devDependencies": {
    "@commitlint/cli": "^16.0.1",
    "@commitlint/config-conventional": "^16.0.0",
    "husky": "^7.0.4"
  },
  "scripts": {
    "postinstall": "husky install",
    "prepublishOnly": "pinst --disable",
    "postpublish": "pinst --enable"
  }
}

The package.json in apps/ui:
{
  "name": "ui",
  "packageManager": "yarn@3.1.1",
  "scripts": {
    "dev": "vite"
  },
  "dependencies": {
    "react": "^17.0.2",
    "react-dom": "^17.0.2"
  },
  "devDependencies": {
    "@tailwindcss/forms": "^0.4.0",
    "@types/react": "^17.0.38",
    "@types/react-dom": "^17.0.11",
    "@vitejs/plugin-react": "^1.1.3",
    "autoprefixer": "latest",
    "postcss": "latest",
    "tailwindcss": "latest",
    "typescript": "^4.5.4",
    "vite": "^2.7.10"
  }
}

I have created a component inside my apps/ui/src folder and when I run yarn workspace ui run dev, the app can be started in the browser.
However, when opening my monorepo in VS Code, it fails to resolve npm packages in import statements:
// Cannot find module 'react' or its corresponding type declarations.ts(2307)
import React, { ReactElement, useState } from 'react'

The same happens for the vite.config.ts in apps/ui
// Cannot find module 'vite' or its corresponding type declarations.ts(2307)
import { defineConfig } from 'vite'
// Cannot find module '@vitejs/plugin-react' or its corresponding type declarations.ts(2307)
import react from '@vitejs/plugin-react'

When opening the monorepo in WebStorm, everything is ok.
The repro repository can be found here.
Update: It looks like it is related to the PnP mechanism. I came across this question and setting nodeLinker: node-modules in .yarnrc.yml followed by yarn install fixed it.
However, the ansers for this question didn't work for me.
I get this error in VS Code after running yarn dlx @yarnpkg/sdks vscode:
The path /Users/alexzeitler/src/hello-yarn-workspaces/.yarn/sdks/typescript/lib/tsserver.js doesn't point to a valid tsserver install. Falling back to bundled TypeScript version.

The files in .yarn/sdks/typescript/lib actually don't exist but I have a file integrations.yml in .yarn/sdks:
# This file is automatically generated by @yarnpkg/sdks.
# Manual changes might be lost!

integrations:
  - vscode

A: Looks like the missing pieces have been due to the PnP configuration:
yarn add --dev typescript ts-node prettier
yarn dlx @yarnpkg/sdks vscode

Add a minimal tsconfig.json:
{
  "compilerOptions": {
    /* Basic Options */
    "target": "es5",
    "module": "commonjs",
    "lib": ["ESNext"],

    /* Strict Type-Checking Options */
    "strict": true,

    /* Module Resolution Options */
    "moduleResolution": "node",
    "esModuleInterop": true,

    /* Advanced Options */
    "forceConsistentCasingInFileNames": true,
    "skipLibCheck": true
  }
}

Then install this VS Code extension followed by these steps:

*

*Press ctrl+shift+p in a TypeScript file

*Choose "Select TypeScript Version"

*Pick "Use Workspace Version"

More details can be found in the docs.


Q: Binding energy of a nucleus is positive? I have found from this link http://hyperphysics.phy-astr.gsu.edu/hbase/nucene/nucbin.html that:
Nuclei are made up of protons and neutron, but the mass of a nucleus is always less than the sum of the individual masses of the protons and neutrons which constitute it. The difference is a measure of the nuclear binding energy which holds the nucleus together. This binding energy can be calculated from the Einstein relationship:
Nuclear binding energy $= Δmc^2$.
Now from the above it seems that the nuclear binding energy should be positive to compensate the energy difference between between the mass of the protons and neutron and the mass of a nucleus. But my question is how the binding energy can be positive if this binds the nucleons by attractive force?
I have also gone through this The "binding energy" of bonded particles adds mass? , but didn't get my question resolved.

A: Let's take the simple system of a deuterium nucleus, that is the bound state of a proton and neutron.
It's tempting to think of the binding energy as something that has to be added to a proton and neutron to glue them together into a deuteron, and therefore that the deuteron must weigh more than the proton and neutron because it has had something extra added to it. However this is the exact opposite of what actually happens.
Suppose we start with a proton and a neutron at a large separation, and we let them go and allow them to attract each other. As they move towards each other their potential energy decreases, so because of energy conservation their kinetic energy increases. They accelerate towards each other in just the same way you accelerate towards the Earth if you jump out of a window. This means that when the proton and neutron meet they are moving very rapidly towards each other, and they just flash past each other and coast back out to a large separation. This is not a bound state. To form a deuteron you have to take energy out of the system so that when the proton and neutron meet they are stationary with respect to each other. Then they can bond to each other to form a deuteron.
And this is the key point. To form a bound state you need to take an amount of energy out that is equal to the kinetic energy gained as the two particles collide. This energy is the binding energy, which is 2.2 MeV for a deuteron. If you take the energy 2.2 MeV and convert it to a mass using Einstein's equation $E = mc^2$ you get a mass of $3.97 \times 10^{-30}$ kg, and if you compare the mass of a deuteron with the mass of a proton + neutron you find the deuteron is indeed $3.97 \times 10^{-30}$ kg lighter.
Just for completeness let's look at this the other way round. Suppose we start with a deuteron and we want to separate it into a proton and neutron. Because the two particles in a deuteron attract each other we need to do work to pull them apart, which means we need to add energy to the system. To pull them completely apart we need to add an amount of energy equal to the binding energy of 2.2 MeV. That means our separated proton and neutron have 2.2 MeV more energy than the deuteron, so the total mass of the separated particles has increased by 2.2 MeV and they are $3.97 \times 10^{-30}$ kg heavier than the deuteron.

A: The binding energy doesn't compensate for the difference between the mass of the nucleons and that of the nucleus, it is that difference.
$$m_\text{protons and neutrons}c^2 + \text{binding energy} = m_\text{nucleus}c^2$$
Since the mass of the nucleus is less than the mass of the protons and neutrons, the binding energy must be negative.

A: *

*Binding energy is the energy a nucleus doesn't have, not an energy it does have. The nucleus lost mass in its formation from its components ( and due to mass-energy equivalence) and therefore it equivalently lost this energy. The nucleus doesn't posses this "binding energy" so in fact its a terrible name, its an amount of energy it simply doses not possess.

*The binding energy of the nucleus is intrinsically negative, in the same way that my total energy within the gravitational field is negative, so I am bound to that field. I am trapped.

A: It's just a definition. The binding energy is defined as the energy it takes to take a system apart. The advantage is that you avoid writing minus signs all the time.


Q: Is there a downside to installing all google fonts in Ubuntu? From the google fonts repo (github.com/google/fonts/) I installed all fonts by:
git clone https://github.com/google/fonts/
cp `find fonts -name *ttf` ~/.fonts

That worked and I can use all fonts from Ubuntu. I was wondering if there is a downside to installing too many fonts? Does the fact that I have almost half a gig of fonts now mean that they are all loaded to memory on boot or every time I open a word processor?
~$ du -sh .fonts
454M    .fonts

Thanks!

Edit, number of fonts:
~$ find ~/.fonts -name *.ttf | wc -l
1691

A: With about 1600 variants - I think bold, italic etc have a separate ".ttf" file which were counted here, you will have about 400 fonts
To handle them all in the normal user interfaces for text input has some drawbacks:

*

*These font chooser interfaces are mostly linear, so it may take more time to find a font.

*There may be performance problems with handling the fonts it the implementation is not expecting to handle this amount. That could be easily apparent, but it could also be in unexpected places, like seldom used programs or uncommon features. But overall, It's mostly a problem when font-related menus or dialogs open with a delay.

*There will be fonts that you will not want to use ever. But you spend time scrolling past them every day, wasting time. And maybe there are times when you really only want to work with your three prefered fonts.
There is a tool that can reduce part of these problems, and make it quite feasible:
The tool that can manage groups of fonts, and activate or deactivate them - where deactivation means making them not installed, seen from the X font system, while the tool keeps track of them.
If, from time to time, you arrange the fonts that you will "never" use in a group, and others that you will "normally not" use, and disable these, you will hide lots of fonts over time.

*

*This reduces the long scrolling along useless fonts

*Performance problems will be reduced, depending on the size of number of fonts kept active; Suspected cases of font-related performance issues can easily tested by changing between large and minimal active font sets.

*You can keep away the fonts you will never use - not deinstalling them allows to change your mind for unforeseen reasons, and to check against th
e list of names if you happen to get hold of a similar collection of fonts.

A suitable tool to manage fonts seems to be font-manager.
There is also fontypython - which is quite powerful in it's features, but has a very convoluted user interface, so that I can not fully endorse it.

A: The version of Font Manager in the Ubuntu repositories is very outdated, broken even.
There is a PPA which tracks the latest GIT.
This is the homepage.


Q: A question about a paper of Bismut and Lebeau Let $X$ be a Riemannian manifold, and $Y\hookrightarrow X$ be a closed submanifold of $X$ with normal bundle $N$ with the induced metric.
Then near $Y$, we have $$dv_X(y,Z)=k(y,Z)dv_Y(y)dv_{N_y}(Z),$$
here $k$ is positive function.
Let $A=\nabla^{TX\mid_Y}-\nabla^{TY}-\nabla^N$.
Q why do we have that $$\frac{\partial k}{\partial Z}(y)=-2\dim(Y)v,$$
here $v=\frac1{\dim(Y)}\sum^{\dim Y}_1 A(e_i)e_i$.
PS:
In the Bismut-Lebeau paper, Complex immersion and Quillen metric, Proposition 8.9 page 86, the authors stated such a proposition.
The authors used the Jacobi field to show the statement, i.e.
$\frac{d^2J}{dt^2}+R^{TX}(J,Z)Z=0$ for the geodesic $\exp_y(tZ)$. I did not figure out why and how the authors used such a method.  The below are authors arguments:

To calculate the Jacobian of the map $(x,Z)\mapsto \exp^X=y(Z)$, we consider the two kinds of initial conditions:

*

*$J_0=0,\frac{dJ_0}{dt}\in N_{\mathbb R,y}$.

This corrresponds to the infinitesimal displacements of geodesic $t\mapsto (y,tZ)$, where only $Z$ varies.

*

*$J_0\in T_yY, \frac{dJ_0}{dt}=A(J_0)Z\in T_yY$.

This corresponds to infinitesimal displacements of $t\mapsto (y,tZ)$, where $y\in Y$ moves in  the direction $J_0$ and  $Z\in N$ is parallel with connection $\nabla^N$.
Them we have
$$\langle\frac{\partial k}{\partial Z}(y),Z\rangle=\sum_i\langle A(e_i)Z,e_i\rangle.$$
I do not follow why to construct the Jacobi field, and what to list the two initial conditions for?


Q: Firebase indexOn issue Edit: I want to filter all the post liked by someone using their phone number
My app was working since 3 years earlier i got warning in console about indexOn issue and i have added security rules as per instructed, now when i have updated firebase sdk and also now I'm using addOnCompleteListener instead of valueEventListener now some part of my app not working and now I'm getting exception about indexOn

I don't how to add index for this kind of key as it keeps changing as per user.
if I hardcode users phone number then it is working but I can't add keys for every user as there are few thousand user so please let me know what i can do.
here are few attachments about database, query and rules
database

query
FirebaseDatabase.getInstance()
                .getReference("2 line poetry").orderByChild(number).equalTo("heart");

Rules(currently used which works on previous version)

Rules(Hardcoded version which is working in new version)

I want to make this rule dynamic like using variable $phone or something, I have read almost all threads but didn't found any answer


Q: ZeroClipboard - Using multiple elements ZeroClipboard for single click copy. Both the links are giving the same output, rather than different. Demo link HERE
OBJ1
OBJ2

A: Give a common class to all these elements, and then make all of them available to ZeroClipBoard :

Then load them like this :

var clip = new ZeroClipboard($(".toBeCopied"));


Q: Flutter: LateError (LateInitializationError: Field 'user' has not been initialized.) I am nit sure about this error because user should be inithialized in Auth Provider and then I will be able to use it in User Provider but flutter continue giving this error.
Here is my code. Can someone help to solve or tell me a better form to organize it?
AuthProvider
class AuthProvider extends ChangeNotifier {
  late final FirebaseAuth _auth;
  late final NavigationService _navigationService;
  late final DatabaseService _databaseService;

  late UserData user;
  AuthProvider() {
    _auth = FirebaseAuth.instance;
    _navigationService = GetIt.instance.get<NavigationService>();
    _databaseService = GetIt.instance<DatabaseService>();
    _auth.authStateChanges().listen((_user) {
      if (_user != null) {
        //_databaseService.updateUserLastSeenTime(_user.uid);
        _databaseService.getUser(_user.uid).then(
          (_snapshot) {
            if (_snapshot.exists) {
              if (_snapshot.data() != null) {
                user =
                    UserData.fromJson(jsonDecode(jsonEncode(_snapshot.data())));
                notifyListeners();
              }
            }
            _navigationService.removeAndNavigateToRoute('/home');
          },
        );
      } else {
        _navigationService.removeAndNavigateToRoute('/login');
      }
    });
  }

User Provider
class UserProvider with ChangeNotifier {
  final DatabaseService _databaseService = DatabaseService();

  UserData _user = AuthProvider().user;
  UserData get getUser => _user;

  Future<void> refreshUser() async {
    UserData user = await _databaseService.getUserDetails();
    _user = user;
    notifyListeners();
  }

// update user name
  Future<void> editName(String name) async {
    try {
      await _databaseService.getUserDoc(_user.uid).update({'name': name});
    } catch (err) {
      print(err.toString());
    }
  }

// update user last name
  Future<void> editLastName(String lastName) async {
    try {
      await _databaseService
          .getUserDoc(_user.uid)
          .update({'lastName': lastName});
    } catch (err) {
      print(err.toString());
    }
  }
}


Q: MongoDB: Search Query to return an object inside the array I have a Journal Schema which contains an array of notes. I want to implement MongoDB search in my application so that it returns the note that matches the query. Right now it returns the entire Journal Object which contains the matched note.
Journal Schema:
{
  userid: {
    type: String,
    required: true,
  },
  notes: [
    {
      content: {
        type: String,
      },
    },
  ],
}

Right now my query syntax is:
[
  {
    $search: {
      index: 'Journal-search-index',
      text: {
        query: 'asdf',
        path: 'content'
      }
    }
  }
]

It returns the entire Journal object but I only want the note that matches the query. is there any way to implement that?

A: You are currently searching for documents that match current query, but not filtering the data inside of documents, particulary notes array.
You have to add filter on the next aggregation operation
const query = "asdf";

db.collection.aggregate([
  {
    $search: {
      index: "Journal-search-index",
      text: {
        query: query,
        path: "content",
      },
    },
  },
  {
    $project: {
      notes: {
        $filter: {
          input: "$notes",
          as: "note",
          cond: {
            $regexMatch: {
              input: "$$note",
              regex: query,
              options: "i",
            },
          },
        },
      },
    },
  },
]);

Playground Example


Q: How do I apply drop Shadow right and bottom of transparent view in Android? I want to apply drop shadow right and bottom on view (TextView/LinearLayout) with transparent background.
I have draw shadow using Layer-list as said in this link:
Add shadow on right and bottom side of the layout
but it is not giving me desired transparency.
can any one help me out?
Thanks


Q: ¿Se puede crear una matriz de Buttons en Android? tengo 9 grillas de 9 botones cada uno. En cada grilla se generan 9 números Aleatorios del 1 al 9. (Es para un sudoku). Necesito que un número de una grilla no se repita en otra grilla.
Ejemplo
9 3 5      9 6 1 2 7 8
3 6 4.   2 5  7.     3 1 8
2 8 7.   4 3 8.   1. 79
1 3 5      9 6 1 2 7 8
4 6 4.   2 5  7.     3 1 8
2 8 7.   4 3 8.   1. 79
5 3 5      9 6 1 2 7 8
9 6 4.   2 5  7.     3 1 8
7 8 7.   4 3 8.   1. 79
Debe formarse números del 1 al 9 en cada cuadricula pero también debe ser del uno al nueve en cada fila y columna. Cada fila o columna debe tener los siguientes números 1,2,3,4,5,6,7,8,9 entonces yo necesito crear un algoritmo o metodo para que no se repitan los números al ser creados aleatoriamente en el método onCreate.
Hay un método que genera 9 números aleatorios en cada grilla de 9 Buttons pero estos no pueden repetirse en la grilla anterior.
Había pensado hacer un método que diga
while (button1 == button2 || button1 == button3 || button1 == button4 || button1 == button5 etc {

//Genera nuevamente numeros aleatorios siempre que un numero sea igual a otro de su fila

generarNumerosAleatorios();
}

Pero esto sería muy largo y entonces pensé que se podía hacer con una matriz


Q: Getting Value from Another Form: Apostrophes are not displaying Simply put, the apostrophes are not displaying inside my text field.
The result is here: www.unidrones.co.za/VRentals
In the search box, try typing something with an apostrophe like 1920's car or something. You will see a new form that appears. The "Model" field is supposed to accept the exact same string the user typed.
I viewed this nearly duplicate question: The apostrophes are not displayed when getting data from MySQL into bootstrap table but in my case I am not getting my value from the database, I'm getting the value directly from the previous form the user submitted.
I've tried escaping the string, I've tried utf8_encode() and utf8_decode(), I've tried prepared statements and I even tried changing all the "POST" methods to "GET" methods to see if that made any difference. Yet still, if I tried searching for something like 1920's Chrysler the apostrophe would turn into a backslash and the rest of the sentence would be gone.
My code:
<form action='inc/request.inc.php' method='POST' class='request-form' id='request-form'>
            Model
            <input type='text' name='searchvalue' class='searchvalue' value='".mysqli_real_escape_string($conn, $_POST['search'])."' required >
            Full Name
        ...
        </form>


Q: c++ templated container scanner here's today's dilemma:
suppose I've
class A{
  public:
   virtual void doit() = 0;
}

then various subclasses of A, all implementing their good doit method. Now suppose I want to write a function that takes two iterators (one at the beginning of a sequence, the other at the end). The sequence is a sequence of A subclasses like say list<A*> or vector... The function should call all the doit methods while scanning the iterators... How to do this? I've thought of:
template<typename Iterator> void doList(Iterator &begin, Iterator &end) {
    for (; begin != end; begin++) {
        A *elem = (serializable*) *begin;
        elem.doIt();
    }
}

but gives weird errors... do you have better ideas or specific information? Is it possible to use list<A> instead of list<A*>?

A: Why do you think you need the cast? If it is a collection of A * you should just be able to say:
(*begin)->doIt();

A: You can use the std::foreach for that:
std::for_each( v.begin(), v.end(), std::mem_fun( &A::doIt ) );

The std::mem_fun will create an object that calls the given member function for it's operator() argument.  The for_each  will call this object for every element within v.begin() and v.end().

A: You should provide error messages to get better answers.
In your code, the first thing that comes to mind is to use
elem->doIt();

What is the "serializable" type ?


Q: Import Scala from Groovy Is there a way, preferred standard way to import Scala code (local jar, or local maven, or remote artifactory)?
We are using Groovy on Grails, and some library we want to use are written in Java or Scala. Considering they are all JVM languages, there must be a way to interplay.
I've search the net, but have not get a clear answer.

A: Both Scala and Java compiles into Java Bytecode (.class files) and packed as .jar files. It's same bytecode, and can be used from any other JVM language under same classpath.
So your app can mix java bytecode produces from any other JVM language, including Java, Groovy, Scala, Clojure, Kotlin, etc. You can put such jars into /lib dir (if your Grails version supports this; it's less preferred way) or as dependency from Maven repository (local or remote). Then you can use such classes from your code
See:

*

*https://en.wikipedia.org/wiki/Java_bytecode

*http://grails.github.io/grails-doc/2.4.x/guide/conf.html#dependencyResolution for grails 2.4.x

*http://grails.github.io/grails-doc/latest/guide/conf.html#dependencyResolution for latest grails

PS there could be some incompatibilities with some classes, because of different nature of sources languages. But in general it should work.

A: Did some simple tests. In hello-world example, just use

groovy -cp the-assembly-SNAPSHOT.jar main-file.groovy

And in the main-file.groovy, should have an import, like in Java/Scala


Q: Android base library module implementation We are currently updating the app code, and we are splitting the code into different library modules, which are used by one application module. The problem is that the app compiling time has increased exponentially and all of a sudden the 64k multidex limit has been exceeded. Here how we are building our app:

Is the base module recompiling each time for each library module? What could be changed to improve the compile time?


Q: Renaming Row Count Column in SQL I can’t find how to rename the row counting column in a table in an SQL Server RDMS. When you create a table and you have user created columns, A and B for example, to the farthest right of those columns, you have the Row Number column.
It does not have a title. It just sequentially counts all the rows in your table. It's default. Is it possible to manipulate this column denoting the row numbers? Meaning, can I rename it, put its contents in descending order, etc. If so, how?
And if not, what are the alternatives to have a sequentially counting column counting all the rows in my table?

A: No.  You can create your own column with sequential values using an identity column.  This is usually a primary key.
Alternatively, when you query the table, you can assign a sequential number (with no gaps) using row_number().  In general, you want a column that specifies the ordering:
select t.*, row_number() over (order by <ordering column>) as my_sequential_column
from t;


Q: Travis CI simple bash broken with latest update any "n" character seen as "\n" line break Travis CI seems to be misbehaving very oddly since yesterday. I know they pushed out an update on the 21st June 2017 to Travis but this issue only started happening yesterday to me causing a total mess of one of my repo's but luckily I reverted back to the last commit where everything was still OK and have done no more commits since then just been running tests on a different test repo all day today and it's still broken.
During my Travis build process I run a number of bash scripts that do various things like create files based on templates. But since yesterday the output of any echo or printf see's any "n" character as a line break \n
For example:
This simple printf in my bash script:
for line in $(cat $INPUT1); do
printf "\t\"~${line}\"\t\t$ACTION1\n" >> whateverfile.txt

My inputs are defined earlier as:
ACTION1="0;"
INPUT1=$TRAVIS_BUILD_DIR/myfile.txt

Travis breaks the output of any ${line} which contains an "n" in the output.
So for example a ${line} from the cat statement that contains the word bingbot for instance should output as follows:
"~bingbot" 0;

but Travis is doing this because it see's any n character as a line break, this below is the output of running the script with sh -x ./scriptname
bi"\t\t0;\n

+ printf \t"~gbot

and in the actual output file this is what travis prints with printf
bi"     0;
"~gbot

Anyone else seeing this behavior? I have tweeted and emailed them but no response yet. Tried various things to fix it and in some cases capitalising all my variables, inputs, filenames and directories fixes it but that is not a solution. What has Travis done to simple bash? or am I missing something. This has worked perfectly for over a year.
Note: my default scripts all run using #!/bin/bash I have changed them to use #!/bin/sh but it is still happening.

A: I solved this thanks to the help of a number of people in this question - Ubuntu (14 & 16) Bash errors with printf loops from input containing lowercase "n" characters
It wasn't a Travis CI issue after all. It's all explained in the link above.


Q: github webhook with flask - Github not trigger or not send requset I tried to write a flask app that when every time you do a push event to the Github repo it sends a webhook to the flask server. My code for flask app is:
from flask import Flask, request
app = Flask(__name__)

@app.route("/")
def getGitUpdate():
   #some of code
   return 'hello world'

if __name__ == '__main__':
    app.run("0.0.0.0",8000)

The way I set up the webhook on Github is like this:
enter image description here
It is important to note that the firewall is turned off, and in addition I am using the ubuntu 21.04 operating system.


Q: Elan Smart pad disables itself I have a very bizarre problem.
I have a laptop running Windows 10 pro, with an Elan Smart Pad. The problem is that it would disable itself in a seemingly random pattern. I got around it by navigating to the elan settings via keyboard,  but that takes a lot of time and is very annoying. Today however,  I discovered that the trigger disabling it was my laptop charger. When I unplugged it,  the touchpad would become disabled and would become enabled again when I plug the laptop back in. Weird.

A: I emailed the laptop company with the serial number, and they replied with a link to a product page on the msi website with a computer that looked like mine. I never would have found it myself. Downloaded the driver and all seems to be working now. Guess I just had to ask.


Q: iniciar servicio de icecast con php Solicito que alguien me pueda dar una orientación adecuada a lo que intento hacer.  Bueno, me explico.
Quiero iniciar el servidor icecast2 por medio de php,(sabemos que inicia solo por defecto para un solo puerto) pero  en mi caso quiero controlar por ejemplo el purto 8002, 8004, 8006  darle start desde php.
esta misma función lo he hecho con shoutcast, y con shoutcast si me inicia y detiene el server.
sería algo así en un vps, teniendo en cuenta que para icecast estaría en: /home/icecast/8002 y sucesivamente...
en shoutcast lo tengo así...
/home/shoutcast/9002   y demas puertos... como lo inicio y detengo en shoutcast? sencillo.
creo 2 archivos:

*

*on.ph  el cual tiene el siguiente código:

shell_exec('./sc_serv9002');
header('Location: "ruta deseada despues de ejecutar comando');

o también llamando un archivo llamado start9002.sh con permisos 777 que contiene la ruta de iniciar shoutcast  (/home/shoutcast/9002/sc_serv  /home/shoutcast/9002/sc_serv.conf)
shell_exec('./start9002.sh');
header('Location: "ruta deseada despues de ejecutar comando');

*el off.php (que apagará el puerto shoutcast especifico así.

shell_exec('killall sc_serv_9002');
header('Location: "ruta deseada despues de ejecutar comando');

De esa manera controlo los puertos de shoutcast. He intentado hacer lo mismo con icecast, pero no lo consigo.  Porque quiero hacerlo así, para evitar estar accediendo a consola y ejecutar cada uno manual como lo sería con este comando /home/icecast/8002/init.d/icecast2 start   Cabe destacar que esa no es la ruta predeterminada para iniciar icecast, ya que la original es:  /etc/init.d/icecast2 start   pero como he creado mis carpetas para cada puertos, solo puedo iniciarlos por consola y quiero usar php para iniciarlo llamando el archivo start8002.php de icecast por medio de un botón.
cabe destacar que  probé el codigo que me imprimiera el resultado y me mando como respuesta que el comando se ejecutó e imprimió que icecast estaba iniciando. Pero no inicia.
plataforma de dessarrollo, VPS con UBUNTU 18.4 y ubuntu 20
gracias al que pueda darme una mano.


Q: Purge cache in Cloudflare using API What would be best practice to refresh content that is already cached by CF?
We have few API that generate JSON and we cache them.
Once a while JSON should be updated and what we do right now is - purge them via API.

https://api.cloudflare.com/client/v4/zones/dcbcd3e49376566e2a194827c689802d/purge_cache

later on, when user hits the page with required JSON it will be cached.
But in our case we have 100+ JSON files that we purge at once and we want to send new cache to CF instead of waiting for users (to avoid bad experience for them).
Right now I consider to PING (via HTTP request) needed JSON endpoints just after we have purged cache.
My question if that is the right way and if CF already has some API to do what we need.
Thanks.

A: Currently, the purge API is the recommended way to invalidate cached content on-demand.
Another approach for your scenario could be to look at Workers and Workers KV, and combine it with the Cloudflare API. You could have:

*

*A Worker reading the JSON from the KV and returning it to the user.

*When you have a new version of the JSON, you could use the API to create/update the JSON stored in the KV.

This setup could be significantly performant, since the Worker code in (1) runs on each Cloudflare datacenter and returns quickly to the users. It is also important to note that KV is "eventually consistent" storage, so feasibility depends on your specific application.


Q: Sort Dictionary swift 3.0 At some point of coding, I require to sort dictionary to get ordered data based on the Dictionary's Key.
I tried to get the result by:
let sortedDict = dict.sorted { $0.key < $1.key }

It results into:
let dict = ["a0":1, "a3":2 , "a10":2, "a20":3]

Though, desired result:
let dict = ["a0":1, "a10":2, "a20":3, "a3":2]

Any suggestions would be most appreciated.
Thanks In advance.

A: Dictionary is an unordered collection of data, so you can't create an ordered dictionary.

A: Try This:
    for i in 0..<parameters!.count {
        let key = "q\(i)"
        if httpBody.contains(key){
            let regex = try! NSRegularExpression(pattern: "\\b\(key)\\b", options: .caseInsensitive)
            httpBody = regex.stringByReplacingMatches(in: httpBody, options: [], range: NSRange(0..<httpBody.utf16.count), withTemplate: "q")
        }
    }

Simple sort function will not work here.


Q: How do I use a date function in Access? I'm trying to put items into a table which have been deemed over due. I have the date of when items were completed last in a list, and I know the frequency of how often the items need to be completed.

Ex. I have a cleaning that happened on 4/7/17 and it needs to be cleaned 30 days after it was last cleaned, and I have a cleaning that occurred 1/13/17 and it needs to be cleaned 90 days after it was last cleaned.

How can I get Access to show me overdue items in a separate list? If it helps, I will click a button before going to this table. The thing is, not every item needs to be cleaned at the same frequency. To my knowledge, Access doesn't have the date functions like Excel and you cannot type functions into a cell. Thanks!

A:  dim datedue as date, lastdate as date
 datedue = Dateadd("d", 30, lastdate)

 If datedue < Date() then
      'do stuff
 End if

This is basic syntax for checking dates. Since you didnt try anythin on your own, this is all you get.
Have fun   :)

A: You don't "type functions into a cell", you set the ControlSource of a textbox. And Access has dozens of date functions.
However, you could start with a query:
Select
    *,
    DateAdd("d", [CleaningFrequency], [LastCleaned]) As NextCleaning,
    IIf(DateDiff("d", [LastCleaned], Date()) > [CleaningFrequency], "Overdue", Null) As [Status],
    IIf(DateDiff("d", [LastCleaned], Date()) = [CleaningFrequency], "Yes", Null) As [Clean Today]
From
    YourTable

Of course, replace field and table names with those of yours.


Q: Conversion from type 'DBNull' to type 'Date' is not valid on tryparse I am attempting to do a DateTime.TryParse from a date-formatted string, to a new column that I created as part of a DataView table.  I am getting this error when the code runs Conversion from type 'DBNull' to type 'Date' is not valid.
This is the line of code:
DateTime.TryParse(dr("IX_ArticleStartDate"), dr("nStartDate"))

And these are the values in my watch when it errors out.
+       dr("IX_ArticleStartDate")   "2015/3/11" {String}    Object
+       dr("nStartDate")    {}  Object

I was under the impression that a TryParse would return a NULL value if it fails to convert datatypes.  Is there something that I should be doing different to convert this string to a DateTime datatype?
dr is instantiated as a DataRow
Dim dr As DataRow = dv0.Table.Rows(i)

A: VB implicitly try's to cast the DBNull Value to DateTime, since the method signature of DateTime.TryParse is
Public Shared Function TryParse(s As String, ByRef result As Date) As Boolean

which fails. You can use a variable instead:
dim startDate as DateTime
If DateTime.TryParse(dr("IX_ArticleStartDate").ToString(), startDate) Then
    dr("startDate") = startDate
End If

A: A DateTime is a value type and cannot have a null value.  You can do something like this:
Dim result As DateTime

Dim myDate As DateTime? = If(Not dr.IsNull("IX_ArticleStartDate") AndAlso _
    DateTime.TryParse(dr.IsNull("IX_ArticleStartDate").ToString(), result), _
    result, New DateTime?)

In this example, the variable myDate is not actually a DateTime, it's a Nullable(Of DateTime) as indicated by the question mark ? after DateTime in the declaration (see MSDN).  The TryParse method actually takes a string value as the first argument and an output parameter which is a DateTime value as the second argument.  If the parse is successful, it returns True and sets the output parameter to the parsed DateTime value; on the other hand, if the parse is not successful, it returns False and sets the output parameter to DateTime.MinDate which is not very useful because it's difficult to distinguish between a valid use of DateTime.MinDate and null.
The example makes use of a ternary operator which either parses and returns the date value, if it's not null, or else returns a nullable date instead (New DateTime?).
You would then use myDate.HasValue() accordingly to determine if the value is null, and if it's not null, you can use its value: myDate.Value.


Q: Generating multiple data with SQL query I have 2 tables as below
Product_Asset:
PAId      Tracks
1          2
2          3

Product_Asset_Resource:
Id        PAId        TrackNumber
1          1              1
2          1              2
3          2              1
4          2              2
5          2              3

I would like to know if I can generate the data in product_asset_resource table based on product_asset table using TSQL query (without complex cursor etc.)
For example, if the number of tracks in product_asset  is 3 then I need to populate 3 rows in product_asset_resource with track numbers as 1,2,3

A: You can do this with the help of a Tally Table.
WITH E1(N) AS( -- 10 ^ 1 = 10 rows
    SELECT 1 FROM(VALUES (1),(1),(1),(1),(1),(1),(1),(1),(1),(1))t(N)
),
E2(N) AS(SELECT 1 FROM E1 a CROSS JOIN E1 b), -- 10 ^ 2 = 100 rows
E4(N) AS(SELECT 1 FROM E2 a CROSS JOIN E2 b), -- 10 ^ 4 = 10,000 rows
CteTally(N) AS(
    SELECT TOP(SELECT MAX(Tracks) FROM Product_Asset)
        ROW_NUMBER() OVER(ORDER BY(SELECT NULL))
    FROM E4
)
SELECT
    Id  = ROW_NUMBER() OVER(ORDER BY pa.PAId, t.N),
    pa.PAId,
    TrackNumber = t.N
FROM Product_Asset pa
INNER JOIN CteTally t
    ON t.N <= pa.Tracks

ONLINE DEMO

A: Try this,I am not using any Tally Table
declare @Product_Asset table(PAId int,Tracks int)
insert into @Product_Asset values (1 ,2),(2, 3)

;with CTE as
(
select PAId,1 TrackNumber from @Product_Asset
union all

select  pa.PAId,TrackNumber+1 from @Product_Asset pa
inner join cte c on pa.PAId=c.PAId
where c.TrackNumber<pa.Tracks
)

select ROW_NUMBER()over(order by paid)id, * from cte

IMHO,Recursive CTE or sub query or using temp table performance depend upon example to example.
I find Recursive CTE more  readable and won't use them unless they exhibit performance problem.
I am not convince that Recursive CTE is hidden RBAR.
CTE is just syntax so in theory it is just a subquery
We can take any example to prove that using #Temp table will improve the performance ,that doesn't mean we always use temp table.
Similarly in this example using Tally Table may not improve the performance this do not imply that we should take help of Tally Table at all.


Q: sending email with Indy to a gmail address message goes to spam Hello I'm trying to send a message from delphi (indy) to a gmail address. When I go to Gmail I found my message in spam folder. If I try to send the same message with PHPMailer from web it works correctly. This is the code.
Thanks
//setup SMTP
SMTP.Port := 25;
SMTP.ConnectTimeout := 1000;
SMTP.Host := 'smtp.xxxxxx.it';
SMTP.Username := 'info@xxxxxx.it';
SMTP.Password := 'xxxxxx';
SMTP.Connect();

if SMTP.Authenticate then
begin
    //setup mail message
    MailMessage.From.Name := 'xxxxxx';
    MailMessage.From.Address := 'info@xxxxxx.it';
    MailMessage.Recipients.EMailAddresses := 'xxxxxx@gmail.com';

    MailMessage.Subject := ledSubject.Text;
    MailMessage.ContentType := 'multipart/mixed';
    htmpart := TIdText.Create(MailMessage.MessageParts, nil);
    htmpart.Body := Body.Lines;
    htmpart.ContentType := 'text/html';

    //send mail
    try
        try
            SMTP.Send(MailMessage);
        except on E:Exception do
            StatusMemo.Lines.Insert(0, 'ERROR: ' + E.Message);
        end;
    finally
        if SMTP.Connected then SMTP.Disconnect;
    end;
end;

A: Probably I've found the problem. I look the message in 'original mode' I found in the header that google says 'MISSING ID' and I try to add this code:
    MailMessage.MsgId := '1234567890@drinkmessage.it';
    MailMessage.ExtraHeaders.Values['Message-Id'] := MailMessage.MsgId;

Now it seems to work fine.
thanks

A: Have you tried changing HeloName and MailAgent of IdSMTP? If you use the same domain with PHPMailer, my guess is GMail considers emails coming from your application as spam because it doesn't detect/like the application which is sending them.


Q: Problem with random variable elements for Web Scrapping I'd like to create a relative function to access every game report available in this table: https://fbref.com/fr/comps/13/calendrier/Scores-et-tableaux-Ligue-1
I started making a relative URL, but there is an element in the URL that I believe to be random.
Here is what I refer to:

*

*cbdc95fe for: https://fbref.com/fr/matchs/cbdc95fe/Lille-Auxerre-7-Aout-2022-Ligue-1

*

*00173ae0 for: https://fbref.com/fr/matchs/00173ae0/Nantes-Lille-12-Aout-2022-Ligue-1
To overcome this limit, do you know efficient ways to open all links within the table?
Thanks for your help !

A: using the requests and lxml libraries (lxml for xpath) this becomes a fairly straightforward task:
  1 import requests
  2 from lxml import etree
  3
  4 s = requests.session()
  5 r = s.get("https://fbref.com/fr/comps/13/calendrier/Scores-et-tableaux-Ligue-1")
  6 tree = etree.HTML(r.content)
  7 matchreporturls = tree.xpath('//td[@data-stat="match_report"]/a[text()="Rapport de match "]/@href')
  8
  9 for matchreport in matchreporturls:
 10     r = s.get("https://fbref.com" + matchreport)
 11     # do something with the response data
 12     print('scraped {0}'.format(r.url))


Q: Which one is better for (mysql) performance? Which one is better for (mysql) performance ?
"1500 (300x5) Tables with 365 rows per table" OR "(300x5)1500x365 rows in 1 table" ?
(I will get the data(s) with php.)
365 -> days number of the year

*

*if second: I will use "date" and "x_id" to get the 1 row from (300x5)1500x365 rows.

*if first: I will use "date" and "table_name" to get 1 row from 365 rows.**

A: Second one.
http://datacharmer.blogspot.com/2009/03/normalization-and-smoking.html
[edited after updates to question]
In second case you can create an index on columns (x_id,date) which will improve performance of WHERE x_id = ? AND date = ? searches. Some ~550000 rows is not much for well indexed table.

A: Assuming that all the relationships in the data are one-to-one, then the second option of using a single table is the better (normalized) approach.
But there's no detail to the multi-table option, or the data that is being stored.  Bad design, like a table per user, is responsible for performance - not the fact of numerous tables.
Update
Things are still quite vague, but the data you want to store is daily and over the course of years.  What makes it different that you would consider separate tables with identical formats?  The identical tables prompts me to suggest single main table, with some supporting tables involved for things like status and/or type codes to differentiate between records in a single table that were obvious in a separate table approach.

A: That depend on the engine you are using and also if you are going to have more read or more write.
For that look at the way each engine lock the table regarding read and write.
But 1500 table is a lot. I would expect something like 10 table.
1 table is not a bad choice either but if one day you want to have multiple server it gonna be more easy to spread them with 10 table.
Also if you change the structure of the table is going to be long with 1 table. (I know that it shouldn't append but the fact it does)


Q: Lambda Expression using Foreach Clause
Possible Duplicate:
Why is there not a ForEach extension method on the IEnumerable interface?

EDIT
For reference, here's the blog post which eric referred to in the comments
https://ericlippert.com/2009/05/18/foreach-vs-foreach/
ORIG
More of a curiosity I suppose but one for the C# Specification Savants...
Why is it that the ForEach() clause doesn't work (or isn't available) for use on IQueryable/IEnumerable result sets...
You have to first convert your results ToList() or ToArray()
Presumably theres a technical limitation to the way C# iterates IEnumerables Vs. Lists...
Is it something to do with the Deferred Execution's of IEnumerables/IQuerable Collections.
e.g.
var userAgentStrings = uasdc.UserAgentStrings
    .Where<UserAgentString>(p => p.DeviceID == 0 &&
                            !p.UserAgentString1.Contains("msie"));
//WORKS
userAgentStrings.ToList().ForEach(uas => ProcessUserAgentString(uas));

//WORKS
Array.ForEach(userAgentStrings.ToArray(), uas => ProcessUserAgentString(uas));

//Doesn't WORK
userAgentStrings.ForEach(uas => ProcessUserAgentString(uas));

A: It's perfectly possible to write a ForEach extension method for IEnumerable<T>.
I'm not really sure why it isn't included as a built-in extension method:

*

*Maybe because ForEach already existed on List<T> and Array prior to LINQ.

*Maybe because it's easy enough to use a foreach loop to iterate the sequence.

*Maybe because it wasn't felt to be functional/LINQy enough.

*Maybe because it isn't chainable. (It's easy enough to make a chainable version that yields each item after performing an action, but that behaviour isn't particularly intuitive.)

public static void ForEach<T>(this IEnumerable<T> source, Action<T> action)
{
    if (source == null) throw new ArgumentNullException("source");
    if (action == null) throw new ArgumentNullException("action");

    foreach (T item in source)
    {
        action(item);
    }
}


Q: What are the pronouns it and them in the following sentence : how much time, money, and effort it takes them? The text book explains the word "productivity" as following :

the amount of work that a person, company, etc. does compared with how much time, money, and effort it takes them.

Here I cannot understand the part "it takes them"
I am familiar with the verb 'take'. For example

'It takes the tragedy of Tom's death for us to meet here'

which is a slight modification of sentence in some script.
I think the following is correct.

how much time, money and effort it takes for them to do

How would you say about my opinion ?

A: The simplest way to explain the pronouns is to replace them with what they stand for:
*"the amount of work that a person, company, etc. does compared with how much time, money, and effort [the work] takes [the person, company, etc]."
Obviously you would never write such a sentence.


Q: Sort an NSMutableArray / Dictionary with several objects I am having a problem that I think I am overcomplicating.
I need to make either an NSMutableArray or NSMutableDictionary. I am going to be adding at least two objects like below:
NSMutableArray *results = [[NSMutableArray alloc] init];

[results addObject: [[NSMutableArray alloc] initWithObjects: [NSNumber numberWithInteger:myValue01], @"valueLabel01", nil]];

This gives me the array I need but after all the objects are added I need to be able to sort the array by the first column (the integers - myValues). I know how to sort when there is a key, but I am not sure how to add a key or if there is another way to sort the array.
I may be adding more objects to the array later on.

A: Quick reference to another great answer for this question:
How to sort NSMutableArray using sortedArrayUsingDescriptors?
NSSortDescriptors can be your best friend in these situations :)

A: What you have done here is create a list with two elements: [NSNumber numberWithInteger:myValue01] and @"valueLabel01". It seems to me that you wanted to keep records, each with a number and a string? You should first make a class that will contain the number and the string, and then think about sorting.

A: Doesn't the sortedArrayUsingComparator: method work for you? Something like:
- (NSArray *)sortedArray {
    return [results sortedArrayUsingComparator:(NSComparator)^(id obj1, id obj2)
    {
        NSNumber *number1 = [obj1 objectAtIndex:0];
        NSNumber *number2 = [obj2 objectAtIndex:0];
        return [number1 compare:number2]; }];
    }


Q: Cant find the file i created on android tablet /data directory in android is empty. I have installed a few applications and i also wrote code to create a file in /data/Myapp directory ,
I have these lines in OnCreate method , but i dont see any files in /data directory after running the program.
    File fileDir = getFilesDir();
    String filedir=fileDir.toString();
    Log.v("TEST","FILEDIR--->"+filedir);

       //output i got is FILEDIR--->/data/data/com.android.Test/files

    String strNewFileName = "test1.txt";
    String strFileContents = " MY FIRST FILE CREATION PRGM";

    File newFile = new File(fileDir, strNewFileName);
    try{

            boolean filestat = newFile.createNewFile();
            Log.v("TEST"," CREATE FILE =>"+ filestat);

                //output is CREATE FILE =>true indicating success

            FileOutputStream fo =
            new FileOutputStream(newFile.getAbsolutePath());
            fo.write(strFileContents.getBytes());
            fo.close();
    }
    catch(IOException e)
    {Log.v("TEST","Exception on create ");}

A: On real device, you can't see these folders if it's not rooted. see this question.
If you want to write files in your app directory, then your code is OK. You can check that it is there in the same way you created it - from your application:
File myFile = new File(getFilesDir() + "/test1.txt");
if (myFile.exists())
{
  //Good!
}


Q: Color Text and BG of Verbatim, without affecting `fancyvrb` line numbers The MWE below aims to color the text and background of a Verbatim environment.

\documentclass{article}
\usepackage{fancyvrb}
\usepackage{color}
\usepackage{calc}

\definecolor{PYtxt}{rgb}{0.97,0.97,0.95}
\definecolor{PYbgc}{rgb}{0.15,0.16,0.13}

\newsavebox{\PYbgbox}
\newenvironment{PYcolorbox}%
 {\noindent%
  \begin{lrbox}{\PYbgbox}%
  \begin{minipage}{\linewidth-2\fboxsep}%
  \color{PYtxt}}%
 {\ignorespacesafterend%
  \end{minipage}%
  \end{lrbox}%
  \colorbox{PYbgc}{\usebox{\PYbgbox}}}

\begin{document}

\begin{PYcolorbox}
\begin{Verbatim}[commandchars=\\\{\},numbers=left,firstnumber=1,stepnumber=1]
  File "<stdin>", line 1
    1+
     ^
SyntaxError: invalid syntax
\end{Verbatim}
\end{PYcolorbox}

\end{document}

The problem with the code above is that line numbers produced by fancyvrb are also colored white, and cannot be seen when compiled.
How may I do both of the following (but not at the same time):

*

*independently change the text color and line number color?

*expand PYcolorbox to the left to include the (white) line numbers?

Alternative code method: adding formatcom=\color{white} to the Verbatim arguments yields white text (including line numbers), but also affects the bottom margin of the color background.
The goal would be to use this in tandem with Pygments.
Any help would be appreciated.

A: With a redefinition of \theFancyVerbLine you can change to color for the numbers independently; a little example:
\documentclass{article}
\usepackage{fancyvrb}
\usepackage{xcolor}
\usepackage{calc}

\definecolor{PYtxt}{rgb}{0.97,0.97,0.95}
\definecolor{PYbgc}{rgb}{0.15,0.16,0.13}

\newsavebox{\PYbgbox}
\newenvironment{PYcolorbox}%
 {\noindent%
\renewcommand\theFancyVerbLine{%
\textcolor{red!80!black}{\small\arabic{FancyVerbLine}}}%
  \begin{lrbox}{\PYbgbox}%
  \begin{minipage}{\linewidth-2\fboxsep}%
  \color{PYtxt}}%
 {\ignorespacesafterend%
  \end{minipage}%
  \end{lrbox}%
  \colorbox{PYbgc}{\usebox{\PYbgbox}}}

\begin{document}

\begin{PYcolorbox}
\begin{Verbatim}[commandchars=\\\{\},numbers=left,firstnumber=1,stepnumber=1]
  File "<stdin>", line 1
    1+
     ^
SyntaxError: invalid syntax
\end{Verbatim}
\end{PYcolorbox}

\end{document}

I wonder, however, if you wouldn't be better off using a package such as minted or listings which offer you colored backgrounds out of the box. Specially minted might be useful here since it uses Pygments.


Q: how to sort parameters with Jenkins parametrized job? Problem:
A Jenkins job is starting to have a lot of parameter (over 20).
Is there a way to group them, have title, etc...?
I looked up and found none.

A: There is no way of sorting parameters automatically that I'm aware of. You can arrange them via Drag&Drop in your project's config manually, of course.
You can group them using the Parameter Separator Plugin:
Meta Data → [✔] This build is parameterized → Add Parameter → Parameter Separator


Q: How can I copy dependencies from a library project to the main project? I have an Asp.Net project (Vb.Net) that references a managed dll (library written in C#). That library project has several unmanaged dependencies dlls in a lib folder (copied into bin/Release/lib folder during build). The library is not a part of the main solution.
My library uses [DllImport] that references an unmanaged dll. But to let the unmanaged dll be found, I call SetDllDirectory():
        string path = // don't know how to generate the path
        SetDllDirectory(path);

I am struggling with generating the path to the unmanaged dll and its dependencies. I can start with my main project bin folder or something. But what should I do next? E.g. is there a way to copy the unmanaged dlls from the library's bin/Release/lib folder to my main project's bin folder? Or some other solution?

A: There are two ways you can go about this:

*

*Add the Dlls to the VS project as a file, then set Build Action to None and Copy to output directory as Copy. This should ensure that any external dependencies of the referenced library are copied.

*Add a command like xcopy "$(ProjectDir)lib\*.*" "$(OutDir)\" /y /e or xcopy "$(ProjectDir)lib\*.*" "$(TargetDir)" /y to the Build Events section in Project properties. This should copy the \lib directory from the project root to the output.


Q: Windows 10 pro unable to remove Bose QuitComfort 35 I have been trying for the last half hour to find ways to remove my Bose QuitComfort 35 from the bluetooth list of devices.
Here is what I see in the "Bluetooth & other devices" windows

The device is not turned off I just can't pair it now. Not sure exactly what happened, I have been using the device without issues but after I turned off the device I was unable to pair it again and now I am unable to remove it.
I have tried removing in the device manager as well. I can get rid of the Bose QuitComfort 35 under "Other devices" but not the one in Audio.
I am the administrator in my account. Is there anything else I need to do???
Thanks

A: This may be a shot in the dark, but it appears this may be due to Bluetooth driver issues. Please try the following:

*

*Completely disconnect your computer from the internet.

*Open your Device Manager as Administrator.

*Under Bluetooth, remove each of the Enumerators (not the driver).

*Under Human Interface Devices, remove any Bluetooth devices.

*Restart your computer.

*Connect the computer to the internet.

*Pair devices.

Found here: https://www.windows10forums.com/threads/win10-not-removing-bluetooth-device.2099/#post-22640


Q: Is there a name for this formula/distribution: $f(i) = ( a / i^k ) b^i$? My apologies if this is a naive question but does anyone happen to know if the equation below (and/or the distribution it describes) is commonly know by a specific name?

$f(i) = ( a / i^k )  b^i$
(where $a$, $b$ and $k$ are constants; and, FWIW, for my purposes $i$ should be a positive integer denoting rank according to frequency)

This equation appears in Simon (1955), but he doesn't give it a specific name and always refers to it by its example number in his paper.
This is not my field so I'm not familiar with the relevant literature so I don't know how often this particular distribution crops up and if it is common enough to warrant a specific name (pointers to places where it does appear would also be appreciated though!).
The same formula is also mentioned in Tambovtsev & Martindale (2007), who call it a "Yule distribution" but, as far as I can glean, this seems wrong since it appears "Yule(-Simon)" refers to a different distribution; T&M seem to have mislabelled it based on a careless reading of Simon, who does indeed mention the above equation in the proximity of a discussion of Yule (1924).
Instead, Simon cites Champernowne (1953) for this equation; however, calling it a "Champernowne distribution" doesn't seem appropriate either since, isn't that already the name for a different distribution?
Help, comments and corrections would be gratefully appreciated!
References
Champernowne, D. G. 1953. A Model of Income Distribution. The Economic Journal 63(250): 318–51
Simon, H. A. 1955. On a class of skew distribution functions. Biometrika 42(3–4). 425–40.
Tambovtsev, Y. A. & C. Martindale. 2007. Phoneme frequencies follow a Yule distribution. SKASE Journal of Theoretical Linguistics 4(2). 1–11.
Yule, G. U. 1924. A mathematical theory of evolution, based on the conclusions of Dr J. C. Willis, F.R.S. Philosophical Transactions B 213(21).

A: As far as I can tell, it doesn't quite have a name, but perhaps the following makes sense? The logarithmic distribution has pmf
\begin{align*}
p(i) = -\frac{1}{\log(1-p)}\frac{p^i}{i}
\end{align*}
So this would be a special case when $k = 1$ in your parametrization, and $a$ is then determined to ensure the pmf sums to 1. The reason for this name is because the pmf is derived from the series expansion of the logarithmic function. In your formulation, the pmf would indeed equal
\begin{align*}
p(i) = \text{Li}_{k}(b) \frac{b^i}{i^k}
\end{align*}
Hence, if we would to continue the tradition of naming distributions based off series expansions from which they are derived, this could be called the "Polylogarithmic distribution". No results show up when I google this, though.

A: Assuming that $a$ is a normalization constant, the formula
$$
\label{eq:original}\tag{1}
f(i) = \frac{ab^i}{i^k}
$$
is mentioned by Good (1953, eqn 54) as a generalization of the Zipf distribution
$$
f(i) = \frac{a}{i^k}.
$$
(Good stipulates $0 < b < 1$ and calls $b^i$ a "convergence factor".) There is precedent in the literature for calling ($\ref{eq:original}$) the "Good distribution": see Zörnig & Altmann (1995) and Eeg-Olofsson (2008).
A more general form,
$$
f(i) = \frac{ab^i}{(\nu + i)^k},
$$
has been dubbed the "Lerch distribution" (Zörnig & Altmann 1995; Klar, Parthasarathy & Henze 2010, p. 130), as the normalization constant is related to the Lerch transcendent.
I can't think of an obvious/objective criterion for choosing between "Good distribution" and "polylogarithmic distribution" (Tom Chen's answer; Kemp 1995) – while both names appear in the literature, the references are so few it's not clear that one name should be favoured over the other. Perhaps one could call it the Good–Kemp distribution?
References
Eeg-Olofsson, M. (2008) Why is the Good distribution so good? Towards an explanation of word length regularity. Lund University Department of Linguistics and Phonetics Working Papers, 53, 15–21. https://journals.lub.lu.se/LWPL/article/view/2270/1845
Good, I. J. (1953) The population frequencies of species and the estimation of population parameters. Biometrika, 40, 237–264. https://doi.org/10.1093/biomet/40.3-4.237
Kemp, A. W. (1995) Splitters, lumpers and species per genus. Mathematical Scientist, 20, 107–118. http://www.appliedprobability.org/data/files/TMS%20articles/20_2_4.pdf
Klar, B., Parthasarathy, P. R. & Henze, N. (2010) Zipf and Lerch limit of birth and death processes. Probability in the Engineering and Informational Sciences, 24, 129–144. https://doi.org/10.1017/S0269964809990179
Zörnig, P. & Altmann, G. (1995) Unified representation of Zipf distributions. Computational Statistics & Data Analysis, 19, 461–473. https://doi.org/10.1016/0167-9473(94)00009-8


Q: How to get iframe images to print as part of full document in IE I have two IFRAMEs.  Each IFRAME is loaded dynamically as the result of submitting a FORM.  The result of each FORM submit is a dynamically generated jpeg image (Content-type: image/jpeg).  The following page displays correctly (you can see both images).  If you try to print this page in IE however, you just get an outline of the images, but not the actual images.  It prints correctly in Safari and Chrome.  How can you get the IFRAME images to print along with the rest of the document in IE?
I am using IE 9.0.8112.16421.
<HTML>
<HEAD>
<TITLE>View Image</TITLE>
</HEAD>
<BODY onLoad="top.document.Form1.submit();top.docment.Form2.submit();">
<FORM NAME=Form1 ACTION="URL" METHOD=POST Target=Img1>
<INPUT TYPE=HIDDEN NAME=ID VALUE=123>
<INPUT TYPE=HIDDEN NAME=Cmd VALUE=DispImage1>
</FORM>
<FORM NAME=Form2 ACTION="URL" METHOD=POST Target=Img2>
<INPUT TYPE=HIDDEN NAME=ID VALUE=345>
<INPUT TYPE=HIDDEN NAME=Cmd VALUE=DispImage2>
</FORM>
<IFRAME NAME=Img1 SRC=Javascript:'' WIDTH=500 HEIGHT=250 FRAMEBORDER=0 SCROLLING=no>
</IFRAME><BR>
<IFRAME NAME=Img2 SRC=Javascript:'' WIDTH=500 HEIGHT=250 FRAMEBORDER=0 SCROLLING=no>
</IFRAME>
</BODY>
</HTML>


Q: Principal Bundle Connection Correspondence for two descriptions of the $\mathbb{CP}^2$ Consider the following pair of principal bundle descriptions of $\mathbb{CP}^2$:
$$
\mathbb{CP}^2 \simeq SU(3)/U(2) \simeq  S^5/U(1).
$$
If I have a principal $U(2)$-bundle connection for $\mathbb{CP}^2$, will that correspond to a principal $U(1)$-bundle connection? (Where by correspond I suppose I mean give the same covariant derivative.)
I am also interested in how this generalises to the $n$-case
$$
\mathbb{CP}^{n} \simeq SU(n+1)/U(n) \simeq  S^{2n+1}/U(1).
$$

A: The answer is no. You can see that for example from the connection one forms which are Lie algebra valued. In the first case they are u(2) valued and in the second case they are u(1) valued. However, in the case of CP2 (which also generalizes to CPn), the U(1) and SU(2) factors of the isotropy group U(2) commute, this means that given a U(2) connection on U(2)-->SU(3)-->CP2, you can project it to the U(1) factor to obtain a U(1) connection on U(1)-->S^5-->CP2, such that both connections will have the same horizontal subspaces.


Q: Building Framework as "Generic iOS Device" Causes Use of Undeclared Type in Project Using Framework Basically, as stated in the title, when I build my Cocoa Touch Framework for "Generic iOS Device," it causes "Use of Undeclared Type" compilation errors in my XCode project using the framework. However, when I build the XCode Project for "Generic iOS Device" too, the errors go away.
My question is: How can I build the framework in such a way that it can be used for simulators as well as a generic iOS device?
I was under the impression that building a Cocoa Touch Framework for "Generic iOS Device" would allow it to be used in any build configuration. Is this incorrect?
Is there something that has to be changed in the build settings or schemes?
Thanks!

A: Update: I was mistaken, and due to simulators and iPhones having different architectures, you have to compile the framework for each one respectively. However, I was able to create a "fat framework" by following this Medium article: https://medium.com/@hassanahmedkhan/a-noobs-guide-to-creating-a-fat-library-for-ios-bafe8452b84b
This fat framework can be used for both "Generic iOS Device" and the simulator.


Q: Error using Firebase from Chrome App I am attempting to use Firebase from within a Chrome App (not an extension) and have not been able to work around the following error:

Refused to load the script
  'https://{my firebase id}.firebaseio.com/.lp?start=t&ser=81980096&cb=15&v=5'
  because it violates the following Content Security Policy directive:
  "default-src 'self' chrome-extension-resource:". Note that
  'script-src' was not explicitly set, so 'default-src' is used as a
  fallback.

my manifest.json file looks like this:
{
  "manifest_version": 2,
  "name": "Simple Demo",
  "version": "1",
  "icons": {
    "128": "icon_128.png"
  },

  "permissions": ["https://*.firebaseio.com/"],
  "app": {
    "background": {
      "scripts": ["background.js"]
    }
  },
  "minimum_chrome_version": "28"
}

I have the firebase.js script local to the chrome app, the issue seems to be that it tries to load other scripts which isn't permitted.
Any ideas are appreciated.

A: Well, You can use firebase REST API Approach, in this case, I've used for my chrome app and its working fine. This don't require to have firebase SDK to be added!
Read the following docs,
https://firebase.googleblog.com/2014/03/announcing-streaming-for-firebase-rest.html
https://firebase.google.com/docs/reference/rest/database/
https://firebase.google.com/docs/database/rest/retrieve-data
Approach is very simple
Protocol is known as SSE (Server Sent Events) where you listen to specific server URL and when something changes, you get the event callback.
In this case, firebase officially provides SSE based mechanism
A sample code snippet is,
 //firebaseUrl will be like https://xxxxx.firebaseio.com/yourNode.json or https://xxxxx.firebaseio.com/yourNode/.json
 //notice ".json" at the end of URL, whatever node you want to listen, add .json as suffix
    var firebaseEventSS = new EventSource(firebaseUrl);
    //and you will have callbacks where you get the data
    firebaseEventSS.addEventListener("patch", function (e) {
                var data = e.data;
            }, false);
    firebaseEventSS.addEventListener("put", function (e) {
                var data = e.data;
            }, false);

Just check few EventSource examples and combine with Firebase Doc for REST API and you are all set!
Don't forget to close() when it's done.
firebaseEventSS.close();

A: This is an old question, but the solution offered by the Firebase team is to use a different URL protocol for the database.
So instead of using https://<app>.firebaseio.com/ you'd use wss://<app>.firebaseio.com/.
I found the solution here. Here is an answer provided by the Firebase team on this subject.


Q: Start SSH daemon in Laravel sail I'm using Laravel Sail and have published the Dockerfile (so I can edit it manually). The reason being that I need to use an OpenSSH server on the container itself for a program I'm using.
I am able to install OpenSSH by adding && apt-get install -y openssh-server to the packages section and configure it with the following:
RUN mkdir /var/run/sshd
RUN sed -i 's/PermitRootLogin prohibit-password/PermitRootLogin yes/' /etc/ssh/sshd_config
RUN sed 's@session\s*required\s*pam_loginuid.so@session optional pam_loginuid.so@g' -i /etc/pam.d/sshd
EXPOSE 22

The issue though is that it does not start when the container starts.
According to this answer you can add an ENTRYPOINT as follows:
ENTRYPOINT service ssh restart && bash

However you can only have one ENTRYPOINT and Laravel Sail has this by default:
ENTRYPOINT ["start-container"]

I have tried the following:

*

*add /usr/sbin/sshd to the start-container script - it didn't start

*add CMD ["/usr/sbin/sshd", "-D"] into the Dockerfile as per this answer - it gave a permission denied error when starting the container

A: As the php container uses supervisor you can add another application to the config. Reference for the config can be found here.
Example
ssh.ini:
[program:sshd]
command=/usr/sbin/sshd -D


Q: xcode = I sended data from one view to the other, with prepareForSegue, but can't send it to another view in prepareForSegue I have a problem. First I sended information from textfield with prepareForSegue. I sended from WelkomViewController to TableViewController. There I put the data in a NSMutableDictionary. It's a person and his values. Then I put the person in another NSMutableDictionary for multiple persons. In the tableview I create a list with only the full name of all the persons. And with a click on the row I want to give a new view with the details of the person that the client clicked on. But I can't send the data with prepareForSegue it seems.(see image)
What do I do wrong? Thx for every reply!
project

A: You're trying to use a dictionary like an array, which doesn't work (obviously). You should not count on a fixed order for [self.personen allKeys], it can change at any point during runtime, which would result in the wrong person being passed along.
You need to use a mutable array as your storage vessel for people names, then address them by the row of the index path.

A: First of all you need to use NSmutablearray to save data of people so make sure that self.personen is an NSmutablearray then you need just to use ObjectAtindex function to get the selected row .
vcGevensView.persoon=[self.personen objectAtIndex:indexPath.row];


Q: i can't limit a javascript animation in time I have to code an animation for an array. Every box, one by one, will take a white color for 3000 ms. But it's not working. Can you help me?
function searchNumber(){
    var taille;
    for(var i=0; i<taille; i++) {
        tabRect[i].hide("5000");
        tabRect[i].show();
    }
}

A: You can do it with CSS3, is not necessary javascript for that:
https://jsfiddle.net/rzcdqh8k/
.animation {
    width: 100px;
    height: 100px;
    background-color: red; //original color
    -webkit-animation-name: example;
    -webkit-animation-duration: 3s;
    -webkit-animation-iteration-count: infinite;
    animation-name: example;
    animation-duration: 3s;
    animation-iteration-count: infinite;
}

/* Chrome, Safari, Opera */
@-webkit-keyframes example {
    from {background-color: red;} //original color
    to {background-color: white;}
}

/* Standard syntax */
@keyframes example {
    from {background-color: red;} //original color
    to {background-color: white;}
}


Q: Как в методе класса обозначить пересекаются ли круги или нет(Питон) Есть код
class Circle:
    def __init__(self, center, radius):
        self.center = center
        self.radius = radius
    def square(self):
        return (3.14 * self.radius**2)

Он принимает координаты центра круга и его радиус, а потом находит площадь круга, его необходимо доработать, добавив ему ещё один метод def do_intersect, который будет принимать другой объект класса Circle и возвращать True или False в зависимости от того, пересекаются круги или нет. Но как это сделать я не знаю...

A: понятно что две окружности пересекаются, если расстояние между их центрами меньше суммы их радиусов.
Поэтому ищем гипотенузу и сравниваем.
Наверно координаты идут кортежем, поэтому вынесем их в конец инициализации
class Circle:
    def __init__(self, radius, *args):
        self.center = args
        self.radius = radius

    def square(self):
        return 3.14 * self.radius ** 2

    def do_intersect(self, other):
        dist = ((self.center[0] - other.center[0]) ** 2 + (self.center[1] - other.center[1]) ** 2) ** 0.5
        return abs(self.radius - other.radius) <= dist <= self.radius + other.radius

circle = Circle(3, 1, 1)
circle2 = Circle(1, 1, 1)
print(circle.do_intersect(circle2))

A: проверить пересекаются ли круги можно взяв расстояние их центров и вычесть сумму их радиусов
def f(center1, r1, center2, r2):
    x = center1[0] - center2[0]
    y = center1[1] - center2[1]

    dist = (x * x + y * y) ** 0.5

    if dist < abs(r1 - r2):
        return False
    dist -= r1 + r2

    return dist < 0


Q: Combining Provider with a steam provider not updating I am working on a technique to determine if some has elevated rights to show an edit icon. I am using Firebase for auth and firestore for back end.
My thoughts were to have the page do a quick check for a record within a certain section that requires the user to be in that section. IE there is a section called /admins/. The rules will only let you read that data if your uid is in that list. I have that working.
So I built a FutureProvider:
    final adminCheckProvider = FutureProvider<bool>((ref) async {
  bool admin = false;
  User? _uid = ref.watch(authStateChangesProvider).value;
  if (_uid != null) {
    print(_uid.uid);
    // Check for Admin Document
    final _fireStore = FirebaseFirestore.instance;
    await _fireStore
        .doc(FireStorePath.admin(_uid.uid))
        .get()
        .then((DocumentSnapshot documentSnapshot) {
      if (documentSnapshot.exists) {
        print('Document Exists: ${documentSnapshot.exists}');
        return true;
      }
    });
  }
  return false;
});

and have a widget that is watching this provider.
    class AdminEdit extends ConsumerWidget {
  const AdminEdit({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    AsyncValue<bool> isAdmin = ref.watch(adminCheckProvider);
    return isAdmin.when(
      data: (isAdmin) {
        print('Data Is In: $isAdmin');
        if (isAdmin) {
          return Text('Is An Admin');
        }
        return Text('Is Not Admin');
      },
      loading: () => Text('Is Not Admin'),
      error: (error, stackTrace) => Text('Error: $error'),
    );
  }
}

I am seeing that the call originally returns false, but when the data is returned and it is determined the document does exist but it never sends out the all clear. I have tried this several different ways and have yet to have this return true. Here is some terminal out put
Data Is In: false
<<UID>>
Document Exists: true
Data Is In: false

If my approach to this is wrong I wouldn't mind hearing about that either.
Thanks in advance guys!

A: Looks like you are returning false as default and only returning true inside your future, not the actual FutureProvider.
Try something like this and it should work:
final adminCheckProvider = FutureProvider<bool>((ref) async {
  User? _uid = ref.watch(authStateChangesProvider).value;
  if (_uid != null) {
    print(_uid.uid);
    // Check for Admin Document
    final _fireStore = FirebaseFirestore.instance;
    final doc = await _fireStore.doc(FireStorePath.admin(_uid.uid)).get();
    return doc.exists;
  } else {
    return false;
  }
});


Q: Should I reinstall all Python libraries if I install Anaconda's Python as primary in my system? I have been using Python on Windows for some time to analyze survey data, usually available in the form of Excel files. For this reason I have installed several libraries, including pywin32, holoview, bokeh, pandas, numpy and so on.
Now I have found that there is a Python distribution called Anaconda which is a prerequisite for some artificial intelligence libraries that I would like to use.
I downloaded it, but when I install it, it recommends me to register the Python included in Anaconda as primary. This would mean that it would be seen as such by all the tools I use, such as PyCharm.
If I understand correctly, it is possible to have several Python installations on a PC, but what happens to the libraries? I mean, if I make Anaconda's Python primary, do I have to reinstall all the libraries I used before to run the programs I have already written?
I can't find an answer in the Anaconda FAQ, so before proceeding with the installation, I would need to better understand what conflicts I might possibly create on my system.

A: Here are the some answers from my side.
1. Will the libraries & files conflit?

No. - Both local & Anaconda will have separete site packages folders to store installed libraries.No matter how many different versions of python you install there will be separate site-packages folders named with respective versions to store installed libraries.

2. Should I need to re-install packages again that I'm alredy using in older python before I run a program on anaconda?

Yes. Local python will use - cmd -WIndows command prompot
Anoconda will use - Anaconda prompt - Which will be installed along with installation. Both Anconda and local python maintains separate storage locations in order to store & process data which includes libraries, settings, Environments, cache....

3.if we selects Anaconda as primary. This would mean that it would be seen as such by all the tools I use, such as PyCharm?

No. Pycharm will have old configuartion whatever you using currently
even thouh we install anaconda & make its a primary. But, still you
can use anaconda from pycharm by creating a virtual environmnet for it.


Q: Make current OAuth User Identity retrievable via IoC in WebAPI project I have an Owin based OAuth 2.0 implemention in ASP.NET WebAPI 2 application. Given that I set a correct claims to a validated identity, In my controller code I an get the currently authenticated user via this.User property.
I need to setup Ninject kernel that way so on each request the PerRequestScope object is instanciated that would hold a current user, but it would be available in an injectable manner, and not just from controller's code.
Please assist on how this can be done. Thank you.

A: Ok, found it.
kernel.Bind<IPrincipal>()
  .ToMethod(context => HttpContext.Current.User)
  .InRequestScope();

Will allow anyone injecting IPrincipal to get the current user name.


Q: Merging a dataframe in a dict with another dataframe in Python I have a dict that currently looks like this:
raw_data = {'Series_Date':['2017-03-10','2017-03-10','2017-03-10','2017-03-13','2017-03-13','2017-03-13'],'Value':[1,1,1,1,1,1],'Type':['SP','1M','3M','SP','1M','3M'],'Desc':['Check SP','Check 1M','Check 3M','Check SP','Check 1M','Check 3M']}
import pandas as pd
df1= pd.DataFrame(raw_data,columns=['Series_Date','Value','Type','Desc'])
dict = {}
dict = {'Check':df1}
print dict

I am trying to append the appended df to the df element of this dict such as:
appended_data = {'Series_Date':['2017-03-13','2017-03-13','2017-03-13'],'Value':[1,1,1],'Type':['SP','1M','3M'],'Desc':['Check SP','Check 1M','Check 3M']}
import pandas as pd
appended = pd.DataFrame(appended_data,columns=['Series_Date','Value','Type','Desc'])
print appended

adfs = {k:df.merge(appended[appended.Desc==df.Desc],on=['Series_Date'],how='left',suffixes=['','_Appended']) for (k,df) in dict.items()}

However, on running this merge statement, I get the following error: ValueError: Can only compare identically-labeled Series objects
Tried reading on thie error but not sure how it's applicable here, any thoughts what could be done to get over this error or alternatively, another approach to do

A: using 'pd.concat' can do the job here.
import pandas as pd
raw_data = {'Series_Date':['2017-03-10','2017-03-10','2017-03-10','2017-03-13','2017-03-13','2017-03-13'],'Value':[1,1,1,1,1,1],'Type':['SP','1M','3M','SP','1M','3M'],'Desc':['Check SP','Check 1M','Check 3M','Check SP','Check 1M','Check 3M']}
df1= pd.DataFrame(raw_data,columns=['Series_Date','Value','Type','Desc'])
print 'df1:\n', df1

appended_data = {'Series_Date':['2017-03-13','2017-03-13','2017-03-13'],'Value':[1,1,1],'Type':['SP','1M','3M'],'Desc':['Check SP','Check 1M','Check 3M']}
appended = pd.DataFrame(appended_data,columns=['Series_Date','Value','Type','Desc'])
print 'appended\n:',appended

df_concat =pd.concat([appended,df1],axis=0)
print 'concat\n:',df_concat

Will results with:
df1:
  Series_Date  Value Type      Desc
0  2017-03-10      1   SP  Check SP
1  2017-03-10      1   1M  Check 1M
2  2017-03-10      1   3M  Check 3M
3  2017-03-13      1   SP  Check SP
4  2017-03-13      1   1M  Check 1M
5  2017-03-13      1   3M  Check 3M
appended
:   Series_Date  Value Type      Desc
0  2017-03-13      1   SP  Check SP
1  2017-03-13      1   1M  Check 1M
2  2017-03-13      1   3M  Check 3M
concat
:   Series_Date  Value Type      Desc
0  2017-03-13      1   SP  Check SP
1  2017-03-13      1   1M  Check 1M
2  2017-03-13      1   3M  Check 3M
0  2017-03-10      1   SP  Check SP
1  2017-03-10      1   1M  Check 1M
2  2017-03-10      1   3M  Check 3M
3  2017-03-13      1   SP  Check SP
4  2017-03-13      1   1M  Check 1M
5  2017-03-13      1   3M  Check 3M

A: How about merging on both desc and Series_date

adfs = {k:df.merge(appended,on=['Desc' , 'Series_Date'], how='left',suffixes=['','_Appended']) for (k,df) in dict.items()}

A statement like appended.Desc == df.Desc is problematic, as these series are of different shape. You can try isin, such as appended.Desc.isin(df.Desc).


Q: Unbalanced dataset - ROC curve to compare classifiers? I use the machine learning software WEKA for data mining on biological data. I would describe my dataset as unbalanced: It comprises around 2000 instances, splitting in classes of 900, 500, 350, 160 that are very important to have in the dataset and some less important smaller classes that are nice to have but can be removed from the dataset if they confuse the learning to much.
Currently I am comparing many different classifiers. I am not a very experienced statistician, but I read that ROC curves are commonly used to evaluate the performance of machine learning classifiers. However, I also read that ROC has drawbacks when it comes to unbalanced datasets.
Is there a better measure among the ones the WEKA output features (or can be calculated from them) for my dataset? Thats how the output looks like (here with the iris dataset):
=== Stratified cross-validation ===

Correctly Classified Instances         144               96      %
Incorrectly Classified Instances         6                4      %
Kappa statistic                          0.94
Mean absolute error                      0.035
Root mean squared error                  0.1586
Relative absolute error                  7.8705 %
Root relative squared error             33.6353 %
Total Number of Instances              150

=== Detailed Accuracy By Class ===

               TP Rate   FP Rate   Precision   Recall  F-Measure   ROC Area  Class
                 0.98      0          1         0.98      0.99       0.99     Iris-setosa
                 0.94      0.03       0.94      0.94      0.94       0.952    Iris-versicolor
                 0.96      0.03       0.941     0.96      0.95       0.961    Iris-virginica
Weighted Avg.    0.96      0.02       0.96      0.96      0.96       0.968

=== Confusion Matrix ===

  a  b  c   <-- classified as
 49  1  0 |  a = Iris-setosa
  0 47  3 |  b = Iris-versicolor
  0  2 48 |  c = Iris-virginica

A: In some formulations of multi-class ROC AUC, it is the case that the AUC estimate is sensitive to relative class frequencies, but this is not true of all mutli-class ROC AUC formulations. Moreover, the ROC AUC formulation in the binary classification case is not sensitive to relative class frequencies. There are numerous performance measures which are sensitive to imbalanced data, such as accuracy, but insensitivity to class imbalance is one of the very appealing advantages to ROC AUC.
This paper develops the idea that binary ROC AUC is insensitive to class compositions, with extended discussion, with the basic idea being that ROC is all about the rates, rather than the absolute numbers of each class. Because ROC analysis measures the relative ranking of examples, class imbalance doesn't change the ROC curve.
In the multi-class case, there are a couple of ways to represent the problem. The class-reference formulation, for example, is sensitive to relative class frequencies. Alternatively, there is a method of combining all 1 vs 1 ROC AUC estimates that is not sensitive to class compositions. This is developed by Hand & Till (2001).

Tom Fawcett, "ROC Graphs: Notes and Practical Considerations for Data Mining Researchers" 2003. Intelligent Enterprise Technologies Laboratory, HP Laboratories (Palo Alto). (If I recall correctly, this paper was also eventually published in a peer-reviewed journal a few years later. Can't find the reference right now. Same author. Similar title.)
David Hand, Robert Till. "A Simple Generalisation of the Area Under the ROC Curve for Multiple Class Classification Problems." Machine Learning. November 2001, Volume 45, Issue 2, pp 171-186.
This is also developed in A. P. Bradley, "The use of area under the ROC curve in the evaluation of machine learning algorithms." Pattern Recognition, 30:1145-1159, 1997.


Q: How do I re-route network traffic using Python? Small apps like Freedom and Anti-social have created quite a stir lately. They cut you off from the internet either entirely or just block social networking sites in order to discourage procrastination and help you exert self control when you really want to get some work done.
I looked at the available options and also at some Google Chrome extensions and decided that none of them is exactly doing what I want, so I'm planning to write my own little Python tool to do that. My first impulse was to simply modify /etc/hosts to re-route requests to certain servers back to localhost. However, this can only block entire domains. I'd need to block addresses based on regular expressions or simple string matching to block something like google.com/reader (yes, this one in particular), but not the entire google.com domain.
Which Python framework can I use to monitor my network traffic and block blacklisted addresses and what is the basic design to achieve what I want to do? Do I use the socket library? I'm very comfortable with Python, but I'm very new to network programming.

A: Since you're comfortable with python, I'd directly recommend twisted. It is slightly harder than some other libraries, but it is well-tested, has great performance and many features. You would just implement a small HTTP proxy and do your regexp filtering on the URLs.


Q: Why am I getting the record added again after deleting it I have a button, which calls the delete function when clicking on it:
deleteRecord = (id) => {
  return this._entriesRef.doc(id).delete()
}

And in the DataStore, I have a event listener, which listens for the change of the snapshot:
snapshot.docChanges.forEach((change) => {
  if (change.type === 'added') {
    this[this._category].unshift({
      ...change.doc.data(),
      id: change.doc.id
    })
  } else if (change.type === 'removed') {
    this[this._category] = this[this._category].filter((log) => {
      return log.id !== change.doc.id
    })
  }
}, this)

However, using breakpoints I can see that after the deletion happens, it first goes to the removed if statement, which is as expected, but then added the same record(with the same id) back to the data.
How could that happen?