text:
Q: Prove that the following set is dense It is hard for me to show that the set $\{\sqrt{m}-\sqrt{n}; m,n\in \Bbb N\}$ is dense in $\Bbb R$. Please help me.

A: Hint: $\sqrt{k^2n+k^2}-\sqrt{k^2n}=\frac{k}{\sqrt{n}+\sqrt{n+1}}=\frac{k}{2\sqrt{n}+\sqrt{n+1}-\sqrt{n}}=\frac{k}{2\sqrt{n}+\frac{1}{\sqrt{n}+\sqrt{n+1}}}$

$$\sqrt{k^2n+k^2}-\sqrt{k^2n}=\frac{k}{2\sqrt{n}+\frac{1}{\sqrt{n}+\sqrt{n+1}}}$$

To show that the set is dense in $\mathbb{R}$, it suffices to estimate all rationals. To estimate the rational $\frac{p}{q}$:

*

*Get a large natural number $m$. Now we consider the rational number $\frac{2pm}{2qm}$

*Set $k=2pm$ and $n=(qm)^2$. It follows that $2\sqrt{n}=2qm$. Since $m$ is large, therefore $n$ would be large. Thus, the fraction $\frac{1}{\sqrt{n}+\sqrt{n+1}}$ that appears in the denominator would be negligible.

A: Let $A=\{\sqrt{m}-\sqrt{n}; m,n\in \Bbb N\}$. We need to show that for every open interval $(a,b)$ we have $(a,b)\cap A \neq \emptyset$. To prove it we'll use two facts:

*

*For any $\epsilon \ge 0$ we can find $x=\sqrt{m}-\sqrt{n}$ for some $n,m\in\mathbb{N}$ such that $0< x\le \epsilon$. To see it just consider $$\sqrt{m+1}-\sqrt{m}=\frac{1}{\sqrt{m+1}+\sqrt{m}}$$

*If $x\in A$ and $k\in\mathbb{Z}$, then $kx\in A$.
Then consider open interval $(a,b)\subset\mathbb{R}$, take $\epsilon=\frac{b-a}{2}$ and by (1) there is $x$ such that $0<x\le\epsilon<b-a$. Now, as $x$ is smaller than length of $(a,b)$, we can find $k\in \mathbb{Z}$ such that $kx\in (a,b)$, and also $kx\in A$ by (2), which shows that $(a,b)\cap A$ is non-empty, and therefore $A$ is dense in $\mathbb{R}$.

A: Let $S$ be the set you're trying to show is dense in $\mathbb{R}$. Here are some ideas: (not necessarily the most elegant solution probably, but it is what came to my mind)

*

*It suffices to show that a subset of $S$ is a dense in $[0,1]$, since you can then do some scaling of $m,n$ to get the whole real line.

*You can show that elements from $S$ can approximate any element in $[0,1]$ by the following argument: notice that $\sqrt{1} - \sqrt{1}, \sqrt{2} - \sqrt{1}, \sqrt{3} - \sqrt{1}, \sqrt{4} - 1$ are elements of $S$ that subdivide $[0,1]$ using four points. Now observe that $\sqrt{4} - \sqrt{4}, \ldots, \sqrt{9} - \sqrt{4}$ subdivides $[0,1]$ using six points. Using this intuition you can show that you can always subdivide the unit interval as many times as you like, and you prove an upper bound on the width of each partition. This will prove density on the unit interval.


text:
Q: nhibernate mapping by code identity not insert I'm using nhibernate 5,1,1. Mapping by code
when you add an entry, you send 2 requests
select max (id) From Bred
insert Into Bred (Id, Name, PetType) valuses ({value of max (id)}, text, 1)
I need the field id not to be sent in the insert request and there was no first request. Id auto increment
How can I do that?
public abstract class BaseEntity
{
    /// <summary>
    /// Ин.
    /// </summary>
    public virtual int Id { get; set; }

    /// <summary>
    /// Дата добавления
    /// </summary>
    public virtual DateTime DateInsert { get; set; }
}

public abstract class BaseMapping<T> : ClassMapping<T> where T : BaseEntity
{
    protected BaseMapping(string nameTabel)
    {
        this.Table(nameTabel);
        this.Id(x => x.Id, map =>
        {
            map.Generator(Generators.Increment);
            map.Column("\"Id\"");

        });
        this.Property(x => x.DateInsert, x =>
        {
            x.Column("\"DateInsert\"");
            x.Insert(false);
            x.Update(false);

        });
    }
}

/// <summary>
/// Справочник пород
/// </summary>
public class Breed : BaseEntity
{
    /// <summary>
    /// Название
    /// </summary>
    public virtual string Name { get; set; }

    /// <summary>
    /// Тип животных
    /// </summary>
    public virtual PetType PetType { get; set; }
}

public class BreedMap : BaseMapping<Breed>
{
    public BreedMap() : base("\"Breed\"")
    {
        this.Property(x => x.Name, x => x.Column("\"Name\""));
        this.Property(x => x.PetType, x => x.Column("\"PetType\""));
    }
}

A:
I need the field id not to be sent in the insert request and there was no first request...

In case that our DB is supporting IDENTITY (auto increment on DB side), we should not use Increment, but Native setting (or Identity)
//map.Generator(Generators.Increment);
map.Generator(Generators.Native);

Check the doc for detailed explanation
5.1.5.1. generator
small extract

increment
generates identifiers of any integral type that are unique only when
  no other process is inserting data into the same table. Do not use in
  a cluster.
...
native/identity
supports identity columns in DB2, MySQL, MS SQL Server and Sybase.
  The identifier returned by the database is converted to the property
  type using Convert.ChangeType. Any integral property type is thus
  supported.
...

redpajama_set_name: RedPajamaStackExchange


text:
Q: difference between the deprecated Java SDK and current Kotlin SDK for using Rocket chat in Android app what is the difference between the deprecated Java SDK and current Kotlin SDK for using Rocket chat in Android app?
If we use the Java SDK now, which are the functionalities that are unavailable or has problems?
I want to use it for an android project which is in Java. what problems will I face if I use the DEPRECATED Java SDKs?


text:
Q:  design is not visible at first download I use Rails 4 and bootstrap-select-rails gem.
When I download page with my form, I got this

When I refresh page, I got this

If I turn off turbolinks,  design is ok, but site is very slow.
How to display the correct design at first download without disabling turbolinks?
UPD:
at application.js:
//= require bootstrap-select

at application.scss:
@import "bootstrap-select";

at view:
=select_tag "document_id",
  options_from_collection_for_select(@documents,'id', 'name'),
  class: "selectpicker",
  "data-live-search".to_sym => "true"

A: I added data-no-turbolink attribute to link
New


text:
Q: Large table in sqlserver I have web application that use SQLserver . In db I have one big table (3GB). All db have 4GB. Problem is that query from another  table (not that big one)  is very slow sometimes. Sometimes query need few second, but sometimes same query need several minutes.
My question is: can one big table slow down query from another table?
Because i em using sql-server-2008 express edition, with limitation of 1 GB RAM and 10 GB database size, could that be a problem? Would changing sql server edition solve my problem? There is about 50 users all the time that use application.

A: In general, the simple existence of table A should not have any affect on queries against table B that do not involve table A. That said, if application X is querying table B and at the same time application Y is querying table A, and the query against A takes a lot of work, than that can slow down the query against table B, because the server only has so much power.
I can think of ways in which the existence of a large table could slow down queries against another table. For example, if the disk is fragmented with parts of small table B, then big table A, then more of small table B, any access against B has to move across larger sections of the hard drive. But wow, I doubt this would be a big issue.
I suppose there could be background processes, like accumulating table statistics for the optimizer, that would kick in on the big table just as you are running a query against the little table. Maybe someone with more knowledge of the internals could weigh in on a question like that.

A: it could be RAM related, SQL server caches data in RAM and if a very large table gets cached, this could be at the expense of other tables not being cached and therefore slower to access from disk.
This is just a theory, but you might want to try out the queries in
https://www.mssqltips.com/sqlservertip/2393/determine-sql-server-memory-use-by-database-and-object/
How much RAM have you allocated to SQL server, and how many other databases/things going on?


text:
Q: Why I can't I install composer on ubuntu using terminal? I have installed xampp on my (ubuntu 16.04)local machine using installer and I found apache and mysql is working but I am trying to install composer from terminal. It's not working for php as the first command of my code. I think it is not recognizing php as a command. I am trying to write following code on terminal.
php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"

what I am getting:
The program 'php' can be found in the following packages:
* php7.0-cli
 * hhvm
Try: apt install <selected package>

What should I do now?
I have attached the picture.


text:
Q: Request sent by the client is syntatically incorrect I am trying to upload a file using Jersey multipart. Here is my code:
import org.glassfish.jersey.media.multipart.FormDataContentDisposition;
import org.glassfish.jersey.media.multipart.FormDataParam;

@Path("/test")
public class Tester {

    @POST
    @Consumes(MediaType.MULTIPART_FORM_DATA)
    @Produces
    public Response test(@FormDataParam("file") InputStream file, @FormDataParam("file") FormDataContentDisposition fileDetail) {
        return Response.status(200).entity(fileDetail.getFileName()).build();
    }
}

Every time I run this code, I get a 400:

the request sent by the client is syntatically incorrect

Edit:

A: Actually removing the Content-Type: multipart/formdata from the header solved the problem. Thank you all for the suggestions


text:
Q: Keyboard doesn't slide with view When the view is dismissed the keyboard slides after the view.
I created a video to demonstrate the problem.
http://www.youtube.com/watch?v=ISFL5G17coU'
Does anyone know why this happens

A: In -(void) viewWillDisappear: make sure you call resignFirstResponder on your textfield.
- (void)viewWillDisappear:(BOOL)animated
{
   [textField resignFirstResponder];
}


text:
Q: Populate Auto Increment Say I have a table structure like this:
create table #Test (name varchar(100))
insert into #Test (name) values ('Ian')
insert into #Test (name) values ('Dave')
insert into #Test (name) values ('Simon')
insert into #Test (name) values ('Tim')
insert into #Test (name) values ('Andy')
insert into #Test (name) values ('Sarah')

How do I get a result set like this:
1 Ian
2 Dave
3 Simon
4 Tim
5 Andy
6 Sarah

I have tried using row number() and dense rank() but I was unsuccessful.

A: Using row_number() over (order by (select null)) might work, but I don't think the order is guaranteed to be in the order of insertion - data returned from select statements represent unordered sets if not explicitly ordered.
The best solution would be to add an identity column or a timestamp at insertion.
select * , r = row_number() over (order by (select null)) from #Test

or perhaps you could alter the table to add an identity column like so:
alter table #test add id int identity(1,1)


text:
Q: How to determine the locale within alfresco I have a java class represents the list of value and i need to enforce the locale within it.
How can i determine the locale ?
The following class displays Constraint value/label for a content model.
package com.ds.ui.constraints;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;
import javax.faces.context.FacesContext;
import javax.faces.model.SelectItem;
import org.alfresco.repo.dictionary.constraint.ListOfValuesConstraint;
import org.apache.log4j.Logger;
import com.ds.ui.bean.dialog.util.BeanUtil;

public class PositionPermissionsConstraints extends ListOfValuesConstraint
    implements Serializable {

public void initialize(){
    LOG.debug("PositionPermissionsConstraints Initializer");
    super.setCaseSensitive(false);
    preparePermissionList();
}

public void preparePermissionList(){
    ResourceBundle bundle = null;
    if(FacesContext.getCurrentInstance() != null){
        if(FacesContext.getCurrentInstance().getExternalContext().getRequestLocale() != null)
        bundle = ResourceBundle.getBundle(BeanUtil.RESOURECE_BUNDLE,
                FacesContext.getCurrentInstance().getExternalContext().getRequestLocale());
    }
    else
        bundle = ResourceBundle.getBundle(BeanUtil.RESOURECE_BUNDLE);

    List<String> av = new ArrayList<String>();
    av
    .add(PositionPermissionsConstraints.
            CREATE_ORGANIZATION_PERMISSION);
    this.allowedLabels
    .add(bundle.getString(CREATE_ORGANIZATION_PERMISSION));
    av
        .add(PositionPermissionsConstraints.
                UPDATE_ORGANIZATION_PERMISSION);
    this.allowedLabels
    .add(bundle.getString(UPDATE_ORGANIZATION_PERMISSION));
    av
        .add(PositionPermissionsConstraints.
                DELETE_ORGANIZATION_PERMISSION);
    this.allowedLabels
    .add(bundle.getString(DELETE_ORGANIZATION_PERMISSION));
    av
        .add(PositionPermissionsConstraints.
                CREATE_ROOT_POSITION_PERMISSION);
    this.allowedLabels
    .add(bundle.getString(CREATE_ROOT_POSITION_PERMISSION));
    av
        .add(PositionPermissionsConstraints.
                MANAGE_ROOT_POSITION_PERMISSION);
    this.allowedLabels
    .add(bundle.getString(MANAGE_ROOT_POSITION_PERMISSION));
    av
    .add(PositionPermissionsConstraints.
            CREATE_SUBORDINATE_POSITION_PERMISSION);
    this.allowedLabels
    .add(bundle.getString(CREATE_SUBORDINATE_POSITION_PERMISSION));
    av
        .add(PositionPermissionsConstraints.
                UPDATE_SUBORDINATE_POSITION_PERMISSION);
    this.allowedLabels
    .add(bundle.getString(UPDATE_SUBORDINATE_POSITION_PERMISSION));
    av
        .add(PositionPermissionsConstraints.
                DELETE_SUBORDINATE_POSITION_PERMISSION);
    this.allowedLabels
    .add(bundle.getString(DELETE_SUBORDINATE_POSITION_PERMISSION));
    av
        .add(PositionPermissionsConstraints.
                MANAGE_POSITION_PERMISSION);
    this.allowedLabels
    .add(bundle.getString(MANAGE_POSITION_PERMISSION));
    av
        .add(PositionPermissionsConstraints.
                ASSIGN_POSITION_TO_USER_PERMISSION);
    this.allowedLabels
    .add(bundle.getString(ASSIGN_POSITION_TO_USER_PERMISSION));
    this.setAllowedValues(av);
    this.setAllowedLabels(allowedLabels);
}

public List<SelectItem> prepareSelectItemsList(){
    ResourceBundle bundle = ResourceBundle.getBundle(BeanUtil.RESOURECE_BUNDLE);
    List<SelectItem> selectItems = new ArrayList<SelectItem>();
    for(String value : getAllowedValues()){
        SelectItem selectItem = new SelectItem(value,bundle.getString(value));
        selectItems.add(selectItem);
    }
    return selectItems;
}

private static final String CREATE_ORGANIZATION_PERMISSION = "CREATE_ORGANIZATION";
private static final String UPDATE_ORGANIZATION_PERMISSION = "UPDATE_ORGANIZATION";
private static final String DELETE_ORGANIZATION_PERMISSION = "DELETE_ORGANIZATION";
private static final String CREATE_ROOT_POSITION_PERMISSION = "CREATE_ROOT_POSITION";
private static final String MANAGE_ROOT_POSITION_PERMISSION = "MANAGE_ROOT_POSITION";
private static final String CREATE_SUBORDINATE_POSITION_PERMISSION = "CREATE_SUBORDINATE_POSITION";
private static final String UPDATE_SUBORDINATE_POSITION_PERMISSION = "UPDATE_SUBORDINATE_POSITION";
private static final String DELETE_SUBORDINATE_POSITION_PERMISSION = "DELETE_SUBORDINATE_POSITION";
private static final String MANAGE_POSITION_PERMISSION = "MANAGE_POSITION";
private static final String ASSIGN_POSITION_TO_USER_PERMISSION = "ASSIGN_POSITION_TO_USER";

private List<String> allowedLabels = new ArrayList<String>();
private static final long serialVersionUID = 1L;
private static Logger LOG = Logger.getLogger(PositionPermissionsConstraints.class);

public List<String> getAllowedLabels() {
    return allowedLabels;
}
public void setAllowedLabels(List<String> allowedLabels) {
    this.allowedLabels = allowedLabels;
}

}
Thanks

A: If you're running in a WebScript, then I18NUtil is what you want. The method public static Locale getLocale() on it will return the locale for the currently running webscript


text:
Q: TypeError: (0 , dayjs_1.default) is not a function This is my logger.ts file that error happens there:
import logger from "pino";
import dayjs from "dayjs";

const log = logger({
  prettyPrint: true,
  base: {
    pid: false,
  },
  timestamp: () => `,"time":"${dayjs().format()}"`,
});

export default log;

ERROR:
yarn dev
yarn run v1.22.17
warning package.json: License should be a valid SPDX license expression
warning ..\..\..\..\package.json: No license field
$ ts-node-dev --respawn --transpile-only src/app.ts
[INFO] 19:09:45 ts-node-dev ver. 1.1.8 (using ts-node ver. 9.1.1, typescript ver. 4.6.3)
TypeError: (0 , dayjs_1.default) is not a function
    at timestamp (C:\Users\A\Desktop\desktop\base_code\back_bc_node\src\utils\logger.ts:9:37)
    at pino (C:\Users\A\Desktop\desktop\base_code\back_bc_node\node_modules\pino\pino.js:147:26)
    at Object.<anonymous> (C:\Users\A\Desktop\desktop\base_code\back_bc_node\src\utils\logger.ts:4:19)
    at Module._compile (node:internal/modules/cjs/loader:1103:14)
    at Module._compile (C:\Users\A\Desktop\desktop\base_code\back_bc_node\node_modules\source-map-support\source-map-support.js:568:25)
    at Module.m._compile (C:\Users\A\AppData\Local\Temp\ts-node-dev-hook-15803171947249184.js:69:33)
    at Module._extensions..js (node:internal/modules/cjs/loader:1155:10)
    at require.extensions.<computed> (C:\Users\A\AppData\Local\Temp\ts-node-dev-hook-15803171947249184.js:71:20)
    at Object.nodeDevHook [as .ts] (C:\Users\A\Desktop\desktop\base_code\back_bc_node\node_modules\ts-node-dev\lib\hook.js:63:13)
    at Module.load (node:internal/modules/cjs/loader:981:32)
[ERROR] 19:09:46 TypeError: (0 , dayjs_1.default) is not a function
(node:10308) [PINODEP008] PinoWarning: prettyPrint is deprecated, look at https://github.com/pinojs/pino-pretty for alternatives.
(Use `node --trace-warnings ...` to show where the warning was created)

It was working on my previous app, but I don't know why do I get this error for my new application?

A: dayjs does not export a default entry like that; use import * as dayjs from 'dayjs' to import all of it's exports (as you are trying to do)

A: When I change the import to
import * as dayjs from 'dayjs'

the node runs normally, but the typeScript throws an error. Changing the import to
import dayjs = require('dayjs');

solved the problem.

A: I have solved the same problem by adding "esModuleInterop": true to tsconfig.json:
{
    "compilerOptions": {
        "noImplicitAny": true,
        "esModuleInterop": true,
        "allowSyntheticDefaultImports": true,
        "moduleResolution": "node",
        "module": "commonjs",
        "target": "es6"
    }
}


text:
Q: Max request length exceeded I have a user receiving the following error in response to an ItemQueryRq with the QuickBooks Web Connector and IIS 7.

Version:
1.6
Message:
ReceiveResponseXML failed
Description:
QBWC1042: ReceiveResponseXML failed
Error message: There was an exception running the extensions specified in the config file. --> Maximum request length exceeded. See QWCLog for more details. Remember to turn logging on.

The log shows the prior request to be

QBWebConnector.SOAPWebService.ProcessRequestXML() : Response received from QuickBooks: size (bytes) = 3048763

In IIS 7, the max allowed content length is set to 30000000, so I'm not sure what I need to change to allow this response through.  Can someone point me in the right direction?

A: Chances are, your web server is rejecting the Web Connector's HTTP request because you're trying to POST too much data to it. It's tough to tell for sure though, because it doesn't look like you have the Web Connector in VERBOSE mode, and you didn't really post enough of the log to be able to see the rest of what happened, and you didn't post the ItemQuery request you sent or an idea of how many items you're getting back in the response.
If I had to guess, you're sending a very generic ItemQueryRq to try to fetch ALL items, which has a high likelihood of returning A LOT of data, and thus having IIS reject the HTTP request.
Whenever you're fetching a large amount of data using the Web Connector, you should be using iterators.  Iterators allow you to break up the result set into smaller chunks.

*

*qbXML Iterator example

*other qbXML examples

A: If you just need to determine if an item exists in QB you can simply add IncludeRetElement to your ItemQuery
So you should post something like
<ItemQueryRq requestID="55">
<FullName>Prepay Discount</FullName>
<IncludeRetElement>ListID</IncludeRetElement>
</ItemQueryRq>

And in Item query response just check the status code. If it is equal to 500 then it means that you should push your item into QB, if it is equal to 0 then it means that item exists
That workaround will save plenty of bytes in your response


text:
Q: Node.js, Express: How can I handle res.send values with the client I'm a newbie in node.js, and I'm also using express.
I build a simple web application to upload files to a server, and save them, when they are okay. That works fine, but now I want to inform the client about the current state( is it uploaded or did it not work, because of the large size from the file).
I know that I should use res.send(), but I want to display it on the same page( with all elements on "upload.html"), where the client uploaded the file. I guess, I have to using client sided javascript to work with the sended information, but how do I communicate with server side javascript and client side javascript? Or do I not need to use client sided javascript?
(I would like to combine it later with HTML, so I can design the answer from the server with CSS.)
server.js:

var     express = require('express'),
        fileUpload = require('express-fileupload'),
        fs      = require('fs'),
        obSizeOf  = require('object-sizeof'),
        app = express();

app.use(express.static("public"));
app.use(fileUpload());

app.get("/upload.html", function(req, res){
        res.sendfile(__dirname + "/" +"upload.html");
})

app.post('/upload.html', function(req, res) {
 if(obSizeOf(req.files.sampleFile) > 10000000)
        {
                res.send("The size of the not-uploaded file is to large! Please use a file with a maximal size of 10MB");
                return;
        }
        else
        {
                var sampleFile;
                if (req.files.sampleFile.name == "") {
                        res.send('No files were uploaded.');
                        return;
                }
                else
                {
                        sampleFile = req.files.sampleFile;
                        var typ = sampleFile.mimetype.split("/");
                        console.log(typ[0]);
                        if(fs.existsSync("public/upload/image/"+typ[0]+"/"+sampleFile.name))
                        {
                                res.send("A File with the same name already exists! Please rename it!");
                                return;
                        }
                        else
                        {
                                sampleFile.mv('public/upload/'+typ[0]+'/'+sampleFile.name , function(err) {
                                  if (err){
                                  res.send('File NOT UPLOADED!');
                                        }
                                        else { console.log("Mieeep!"); res.send(typ[0].charAt(0).toUpperCase()+typ[0].slice(1) +' data uploaded!');
                                        }
                                });
                        }
                }
        }
});
app.listen("8000");

/upload.html:

  <form ref='uploadForm'
   id='uploadForm'
   action='/upload.html'
   method='post'
   encType="multipart/form-data">
   Upload File

    <input type="file" name="sampleFile" />

    <input type='submit' value='Upload!' />

   Only images
  </form>

A: What you actually need is socket programming. Using node js you can do that easily.
just see this link for more on socket and node js.

A: you can use AJAX  and check the error status. there

...


text:
Q: Compile react-native with react-native-firebase Before I proceed, please note that I have resorted to StackOverflow as my last hope, and I have spent hours searching over GitHub and past "related" question.
In a simple context, I'm trying to use react-native-firebase in my react-native app targeting android platform.
The below code is exactly followed based on the step by step given by react-native-firebase
app\build.gradle

...

dependencies {
    compile(project(':react-native-firebase')) {
        transitive = false
    }
    compile project(':react-native-config')
    compile fileTree(dir: "libs", include: ["*.jar"])
    compile "com.android.support:appcompat-v7:23.0.1"
    compile "com.facebook.react:react-native:+"  // From node_modules
    compile "com.google.android.gms:play-services-base:11.6.0"
    compile "com.google.firebase:firebase-core:11.6.0"
}

...

apply plugin: 'com.google.gms.google-services'

android\build.gradle

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.2.3'
        classpath 'com.google.gms:google-services:3.1.2'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        mavenLocal()
        jcenter()
        maven {
            // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
            url "$rootDir/../node_modules/react-native/android"
        }
        maven {
            url 'https://maven.google.com'
        }
    }
}

android\app\src\main\java\com\HF\MainApplication.java

...

import io.invertase.firebase.RNFirebasePackage;
import io.invertase.firebase.database.RNFirebaseDatabasePackage;

...

@Override
protected List < ReactPackage > getPackages() {
  return Arrays. < ReactPackage > asList(
    new MainReactPackage(),
    new RNFirebasePackage(),
    new ReactNativeConfigPackage(),
    new RNFirebaseDatabasePackage()
  );
}

...

However, in the end, it just doesn't run, gives me a weird error. I have tried everything I could but to no avail. Any help would be appreciated.
Thanks
If you're curious about the error

:app:processDebugManifest
:app:processDebugResources
:app:generateDebugSources
:app:incrementalDebugJavaCompilationSafeguard
:app:compileDebugJavaWithJavac
:app:compileDebugJavaWithJavac - is not incremental (e.g. outputs have changed, no previous execution, etc.).
:app:compileDebugNdk UP-TO-DATE
:app:compileDebugSources
:app:transformClassesWithDexForDebug FAILED

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:transformClassesWithDexForDebug'.
> com.android.build.api.transform.TransformException: java.lang.RuntimeException: java.io.IOException: Unable to create parent directories of C:\King's_College_London\Final_Year_Project\HeartFailure\android\app\build\interm
ediates\pre-dexed\debug\com.android.support-support-core-ui-25.2.0_ed7d36204e2346bc863c0a6433807d11a8ea28a3.jar

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

BUILD FAILED

Total time: 1 mins 38.333 secs
Could not install the app on the device, read the error above for details.
Make sure you have an Android emulator running or a device connected and have
set up your Android development environment:
https://facebook.github.io/react-native/docs/android-setup.html

A: As said by @sfratini, this isn't about firebase, but the error actually originates from importing react-native-firebase.
Now for those who might experience this issue in the future, I have found the solution and so please follow each step clearly and exactly.
All in all, if you have imported react-native-firebase and encounter any type of error, then this is because of purely the versions. then follow this:
1.) app\build.gradle

...

// change your dependency object to add the following lines
dependencies {
  compile(project(':react-native-firebase')) {
    transitive = false
  }
  compile project(':react-native-config')
  compile fileTree(dir: "libs", include: ["*.jar"])
  compile "com.android.support:appcompat-v7:23.0.1"
  compile "com.facebook.react:react-native:+" // From node_modules
  compile "com.google.android.gms:play-services-base:11.6.0"
  compile "com.google.firebase:firebase-core:11.6.0"
  compile "com.google.firebase:firebase-database:11.6.0"
}

// this line is very important.
apply plugin: 'com.google.gms.google-services'

2.) anddroid\build.gradle

buildscript {
  repositories {
    jcenter()
  }
  dependencies {

    // compy the following exactly like this
    classpath 'com.android.tools.build:gradle:2.2.3'
    classpath 'com.google.gms:google-services:3.1.2'

    // NOTE: Do not place your application dependencies here; they belong
    // in the individual module build.gradle files
  }
}

allprojects {
  repositories {
    mavenLocal()
    jcenter()

    /// notice the same objecct maven, but with different url
    maven {
      // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
      url "$rootDir/../node_modules/react-native/android"
    }
    maven {
      url 'https://maven.google.com'
    }
  }
}

3.) android\app\src\main\java\com\[yourAppName]\MainApplication.java

// import these two
import io.invertase.firebase.RNFirebasePackage;
import io.invertase.firebase.database.RNFirebaseDatabasePackage;

  private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) {
    @Override
    public boolean getUseDeveloperSupport() {
      return BuildConfig.DEBUG;
    }

    @Override
    protected List<ReactPackage> getPackages() {
      return Arrays.<ReactPackage>asList(
        new MainReactPackage(),
        new ReactNativeConfigPackage(),
        new RNFirebasePackage(),
        new RNFirebaseDatabasePackage()
      );
    }

    @Override
    protected String getJSMainModuleName() {
      return "index";
    }
  };

  ....
  // you'll have other code below, leave that as it is

Then do the following:
npm cache verify
react-native run-android

A: This has nothing to do with firebase.
Try deleting your .gradle folder (make a backup) and make sure you run that from a command line run as an administrator.


text:
Q: Fragment navigation I'm creating an app, with one main activity and fragments.
I'm trying to control what will happen on backPress using this code on the mainActivity:
@Override
    public void onBackPressed() {
        if (getFragmentManager().getBackStackEntryCount() == 0) {
            this.finish();
        } else {
            getFragmentManager().popBackStack();
        }
    }

The structure of my app is this:
MainAtivity --> Fragment1 -->  Fragment2 --> Fragment2 ... (back Press should get me to Fragment1)
When I created Fragment2 I added Fragment1 to the backStack, and when pressing back I still see Fragment2 in the background.
How can I get to Fragment1 and only Fragment1 to show?

A: I'm not sure about how do you commit your fragment. But this would helpful.
While commit:
 // Initialize a Fragment Transaction.
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();

// Record all steps for the transaction.

 ft.replace(R.id.home_frame_layout_for_fragments, baseFragments[i],

// Add the transaction to backStack with tag of first added fragment
ft.addToBackStack(baseFragments[0].getTagText());

// Commit the transaction.
ft.commit();

While removing:
final FragmentManager fragmentManager = getSupportFragmentManager();
while (fragmentManager.getBackStackEntryCount() != 0) {
    fragmentManager.popBackStackImmediate();
}

This may works !!!
Happy coding !!!!


text:
Q: "A number" vs "the number"
*

*The number of students is large.

*The number of students are absent.

*A number of students are absent.
We easily see that:

*

*in sentence (1), "The number of students", we refer to "the number", so verb is in singular form.

*in sentence (2) - "The number of students" and sentence (3) - "A number of students", we refer to "students", so verbs are in plural form.
But I don't know what is the difference between "The number of students" in sentence (2) and "A number of students" in sentence (3).
When you see or hear them, what would you think? What arises in your mind?
In what context can we us "The number of students" or "A number of students"?
I hope to receive your advice. Many thanks in advance.

A: The most primitive difference is that "The number of students are absent" is unacceptable English, but "A number of students are absent" is acceptable.
The phrase the number of X is always singular and takes a verb inflected for third person singular. In this construction of X is merely a complement or modifier (depending on your grammatical sect) of the number, and the number is a definite noun phrase meaning a specific number considered as an entity: the actual count of X.
The phrase a number of X is always† plural and takes a verb inflected for plural. In this construction a number, although it looks like a noun phrase, is actually a quantifier, a sort of determiner meaning approximately "several". Of X is its complement or head nominal (again depending on your grammatical sect); X is cast in the plural and that plurality "percolates up" through the determiner to govern the number of the verb. ("Percolates up" is the apt metaphor employed by CGEL, which calls nouns used this way, such as number and lot/s and bunch, "non-count quantificational nouns".)

† Well, almost always. It is possible for a number of X to occur with a singular X. For instance: Most texts of Revelation give the Number of the Beast as 666, but a few give 616. Pick a number of the Beast you like and give a plausible interpretation of that. In this case, a number is again a noun phrase and of the Beast its complement/modifier. But it took me a lot of effort to invent a legitimate instance of this practically very rare situation.


text:
Q: Can we find two measurable sets satifying these properties? It is known that for any set( not necessarily measurable) $E$, there exists a measurable set(Lebesgue measurable) $F$, such that $E \subset F$ and outer measure $m^*(E)$ is equal to the measure $m(F)$. This is easy to show, by approximating $E$ by some open set $U_\epsilon$ covering $E$, such that $$m^*(E)+\epsilon \ge m(U_\epsilon) $$. Taking $\epsilon $ smaller and smaller and taking intersection of all such open sets, we obtain the result.
My question is that  if there are two arbitrary sets $E_1, E_2$ and $E_1 \subset E_2$, are there two measurable sets $F_1, F_2$ such that $E_1 \subset F_1$, $E_2 \subset F_2$, $m^*(E_1)=m(F_1)$, $m^*(E_2)=m(F_2)$, $F_1 \subset F_2$. Note that without the last condition, this problem is trivial.
If there are not such $F_1, F_2$ with $F_1 \subset F_2$, can we instead make it satisfy that $F_1 \cap {F_2}^c$ is null.

A: Yes, there are such sets.
Apply the same construction as before to obtain $F_2$. Now, in order to obtain $F_1$, you can use the same process, but this time instead of using $U_\varepsilon$, you use $U_\varepsilon'=U_\varepsilon\cap F_2$. It is still a set that contains $E_1$ and it is true that $m^*(E_2)+\varepsilon\geqslant m(U_\varepsilon')$. Of course, $U_\varepsilon'$ may not be open, but it is still measurable. So, the intersection $F_1$ of all these sets is a:

*

*measurable set;

*subset of $F_2$;

*set whose measure is $m^*(E_1).$


text:
Q: How to Split data frame by rows number I have a dataset with 8588 rows and 91 columns. I want to divide it into two new data frames but based on predetermined row numbers.
Example
First data frame
1 A
2 B
3 C
4 D
5 E
6 F
7 G
8 H
9 I
10 J

The second data frame contains the row number
4
7
5
1
9

The third data frame contains the row number
6
10
2
3
8

the result is like this
1st new data frame
4 D
7 G
5 E
1 A
9 I

2nd new data frame
6 F
10 J
2 B
3 C
8 H

The question is how to do this?
Thank you

A: We can subset the dataframe based on values and then match and order.
df1 <- subset(df, V1 %in% c(4,7, 5,1,9))
df2 <- subset(df, V1 %in% c(6,10, 2,3,8))

df1 <- df1[order(match(df1$V1, c(4,7, 5,1,9))), ]
df1
#  V1 V2
#4  4  D
#7  7  G
#5  5  E
#1  1  A
#9  9  I

df2 <- df2[order(match(df2$V1, c(6,10, 2,3,8))), ]
df2
#   V1 V2
#6   6  F
#10 10  J
#2   2  B
#3   3  C
#8   8  H


text:
Q: Ruby rufus scheduler I have this very simple code to run rufus/scheduler:
require 'rufus/scheduler'
require 'rubygems'

scheduler = Rufus::Scheduler.new

scheduler.every '1s' do
puts "Hello world"

end
scheduler.join

This doesn't seem to work and I get no result.

A: You are including the wrong gem, try this:
require 'rubygems'
require 'rufus-scheduler'

scheduler = Rufus::Scheduler.new

scheduler.every '1s' do
puts "Hello world"

end
scheduler.join


text:
Q: How do you run scheduled tasks with extra parameters in Server 2008? The issue that we are facing now is that Scheduled Synchronization is not working when the task scheduler executes a program for Google Apps.
The program runs as follows when within command prompt:
CD C:\Program Files\Google Apps Directory Sync\
sync-cmd.exe -a -o -c August2011.xml
We are running Windows Server 2008 so the referenced link does not really apply (http://www.google.com/support/enterprise/static/gapps/docs/admin/en/gads/admin/sync_schedule.html)
We've tried the following in the Windows Task Scheduler with not much luck:
Program/Script: "sync-cmd.exe -a -o -c August2011.xml"
Add Arguments:
Start in: "C:\Program Files\Google Apps Directory Sync\"
Program/Script: "C:\Program Files\Google Apps Directory Sync\sync-cmd.exe"
Add Arguments: "-a -o -c August2011.xml"
Start in:
Program/Script: "C:\Program Files\Google Apps Directory Sync\sync-cmd.exe" -a -o -c August2011.xml
Add Arguments:
Start in:
Which is correct? I wish there was just an advanced button as Google's documentation mentions. I look forward to some assistance on this task.

A: Have you tried placing the two commands "cd" and "sync-cmd.exe" into a batch (.bat) file, then scheduling the batch file to execute?


text:
Q: How to constrain type of right hand side parameter of operator implementation? Trying to implement a generic Vec implementing the std::ops::Add trait. I want the implementation to automatically convert the underlying type of the vector on addition so I can do something like this:
let u: Vec3<i32> = Vec3 { x: 1, y: 2, z: 3 };
let v: Vec3<i8> = Vec3 { x: 2, y: 3, z: 4 };
let w = u + v;

without using .into() at call site. I have implemented the From trait (which automatically add the Into implementation) and it's working fine on a simple function:
fn foo<T: Into<Vec3<i32>>>(input: T) -> Vec3<i32> {
    input.into()
}

let v: Vec3<i8> = Vec3 { x: 2, y: 3, z: 4 };
println!("{:?}", foo(v));

Link to the non-compiling example here. Is it possible to express a constraint on the type of the right hand side argument of an operator and if yes, how?
#![allow(dead_code)]

use std::convert::{From};
use std::ops::{Add};

#[derive(Debug)]
struct Vec3<T> {
    x: T,
    y: T,
    z: T,
}

impl<T: Add<Output=T>> Add<U: Into<Vec3<i32>>> for Vec3<T> {
    type Output = Vec3<T>;
    fn add(self, rhs: U) -> Self::Output {
        let rhs_converted: Vec3<T> = rhs.into();
        Vec3 {
            x: self.x.add(rhs_converted.x),
            y: self.y.add(rhs_converted.y),
            z: self.z.add(rhs_converted.z),
        }
    }
}

impl From<Vec3<i8>> for Vec3<i32> {
    fn from(input: Vec3<i8>) -> Self {
        Vec3 {
            x: input.x.into(),
            y: input.y.into(),
            z: input.z.into(),
        }
    }
}

fn foo<T: Into<Vec3<i32>>>(input: T) -> Vec3<i32> {
    input.into()
}

fn main() {
    let u: Vec3<i32> = Vec3 { x: 1, y: 2, z: 3 };
    let v: Vec3<i8> = Vec3 { x: 2, y: 3, z: 4 };
    let w = u + v;

    // println!("{:?}", foo(v));
    println!("{:?}", w);
}

A: You need to change U: Into<Vec3<i32>> to U: Into<Vec3<T>> in your Add implementation. Also, the type parameter U declaration was missing from the generic impl, it should be impl<T, U> not just impl<T>. After these minor fixes your code works as expected:
use std::convert::{From};
use std::ops::{Add};

#[derive(Debug)]
struct Vec3<T> {
    x: T,
    y: T,
    z: T,
}

impl From<Vec3<i8>> for Vec3<i32> {
    fn from(input: Vec3<i8>) -> Self {
        Vec3 {
            x: input.x.into(),
            y: input.y.into(),
            z: input.z.into(),
        }
    }
}

impl<T, U> Add<U> for Vec3<T>
    where T: Add<Output=T>, U: Into<Vec3<T>>
{
    type Output = Vec3<T>;

    fn add(self, rhs: U) -> Self::Output {
        let rhs_converted: Vec3<T> = rhs.into();
        Vec3 {
            x: self.x.add(rhs_converted.x),
            y: self.y.add(rhs_converted.y),
            z: self.z.add(rhs_converted.z),
        }
    }
}

fn main() {
    let u: Vec3<i32> = Vec3 { x: 1, y: 2, z: 3 };
    let v: Vec3<i8> = Vec3 { x: 2, y: 3, z: 4 };
    let w = u + v;
    println!("{:?}", w); // prints "Vec3 { x: 3, y: 5, z: 7 }" as expected
}

playground


text:
Q: Postgres 8.4.4 + psycopg2 + python 2.6.5 + Win7 instability You can see the combination of software components I'm using in the title of the question.
I have a simple 10-table database running on a Postgres server (Win 7 Pro).  I have client apps (python using psycopg to connect to Postgres) who connect to the database at random intervals to conduct relatively light transactions.  There's only one client app at a time doing any kind of heavy transaction, and those are typically < 500ms.  The rest of them spend more time connecting than actually waiting for the database to execute the transaction.  The point is that the database is under light load, but the load is evenly split between reads and writes.
My client apps run as servers/services themselves.  I've found that it is pretty common for me to be able to (1) take the Postgres server completely down, and (2) ruin the database by killing the client app with a keyboard interrupt.
By (1), I mean that the Postgres process on the server aborts and the service needs to be restarted.
By (2), I mean that the database crashes again whenever a client tries to access the database after it has restarted and (presumably) finished "recovery mode" operations.  I need to delete the old database/schema from the database server, then rebuild it each time to return it to a stable state.  (After recovery mode, I have tried various combinations of Vacuums to see whether that improves stability; the vacuums run, but the server will still go down quickly when clients try to access the database again.)
I don't recall seeing the same effect when I kill the client app using a "taskkill" - only when using a keyboard interrupt to take the python process down.   It doesn't happen all the time, but frequently enough that it's a major concern (25%?).
Really surprised that anything on a client would actually be able to take down an "enterprise class" database.  Can anyone share tips on how to improve robustness, and hopefully help me to understand why this is happening in the first place?  Thanks, M

A: If you're having problems with postgresql acting up like this, you should read this page:
http://wiki.postgresql.org/wiki/Guide_to_reporting_problems
For an example of a real bug, and how to ask a question that gets action and answers, read this thread.
http://archives.postgresql.org/pgsql-general/2010-12/msg01030.php


text:
Q: Scala change for loop mutable aggregation to immutable If I have this simple loop which is imperative style
val num = 100
var result = 0.0
for (i <- 0 until num) {
    result += 4.0 * (1 - (i % 2) * 2) / (2 * i + 1)
}

How would I change it to immutable and functional?

A: You have an initial value, you iterate over a collection of values and apply an operation to each item to eventually return one single value.
This looks a lot like something that could be turned into a fold.

A: Another approach, with a parallel collection,
(1 to 100).par.map { i => 4.0 * (1 - (i % 2) * 2) / (2 * i + 1) }.sum


text:
Q: Installing client side validation gem in rails 4 I am using rails 4. I have to do client side validation, so, I have installed gem
gem 'client_side_validations', git: 'git://github.com/bcardarella/client_side_validations.git', branch: '4-0-beta'

But throws error while bundling .
Updating git://github.com/bcardarella/client_side_validations.git
Fetching source index from http://rubygems.org/
Retrying source fetch due to error (2/3): Bundler::HTTPError Could not fetch specs from http://rubygems.org/
Retrying source fetch due to error (3/3): Bundler::HTTPError Could not fetch specs from http://rubygems.org/
Could not fetch specs from http://rubygems.org/

GemFile
source 'http://rubygems.org'

gem 'rails', '4.0.2'
gem 'pg'
gem 'sass-rails', '~> 4.0.0'
gem 'uglifier', '>= 1.3.0'
gem 'coffee-rails', '~> 4.0.0'
gem 'jquery-rails'
gem 'fullcalendar-rails'
gem 'turbolinks'
gem 'jbuilder', '~> 1.2'
gem 'thin'
gem 'bcrypt-ruby', '~> 3.1.2'
gem 'twitter-bootstrap-rails'
gem 'therubyracer', platforms: :ruby
gem 'less-rails'
gem 'activerecord-session_store', github: 'rails/activerecord-session_store'
gem 'unicorn'
gem 'capistrano', group: :development
gem 'debugger', group: [:development, :test]
gem 'jquery-datatables-rails', git: 'git://github.com/rweng/jquery-datatables-rails.git'
gem 'jquery-turbolinks'
gem 'better_errors'
gem "paperclip", "~> 4.1"
gem 'client_side_validations', git: 'git://github.com/bcardarella/client_side_validations.git', branch: '4-0-beta'

#gem 'client_side_validations'
group :doc do
  # bundle exec rake doc:rails generates the API under doc/api.
  gem 'sdoc', require: false
end

Please Help me?

A: try changing
source 'http://rubygems.org'

to
source 'https://rubygems.org'

A: In GEM file
gem 'rails4_client_side_validations', '~> 0.0.4'

In terminal run
bundle install


text:
Q: Rails belongs_to with conditions on originating table I have a Transaction model where from_owner is polymorphic, because the transaction could come from several other models.
class Transaction < ActiveRecord::Base
  belongs_to :from_owner, polymorphic: true
end

I am trying to set up a specific belongs_to for when from_owner_type is a particular value:
belongs_to :from_person,
           conditions: ['from_owner_type = ?', Person.name],
           class_name: Person,
           foreign_key: 'from_owner_id'

The problem I'm encountering is that the conditions seem to be for Person and not Transaction. So I get the following SQL error trying to call from_person on a Transaction:

ActiveRecord::StatementInvalid: SQLite3::SQLException: no such column: from_owner_type: SELECT  "people".* FROM "people"  WHERE "people"."id" = 1 AND (from_owner_type = 'Person') LIMIT 1

What I want is for from_person on a Transaction to return nil if the Transaction from_owner_type is not Person, and otherwise return the related Person. I could set up a custom from_person method that does this, but I thought it might be possible as a belongs_to. I'm wanting to use this with CanCan conditions. I'm using Rails 3.

A: From your comments, it seems that the aim of this is to be able to set up a CanCan rule that allows a user to :read any Transactions that they are the owner of, correct? You should be able to do that with the following rule:
can :read, Transaction, from_owner_id: profile.id, from_owner_type: Person.name

and which should mean you don't need to bother messing anything with your Transaction model at all. (I haven't tested this, but the theory should be right, even if the syntax isn't quite there. For example, I'm not exactly sure where you profile.id comes from.)


text:
Q: Strings of arrays and maps? I have a table that contains a field of a varchar type. Within this field, there are empty arrays, arrays and maps stored as strings. something like this:

id
dumped_field

1
[]

2
[123,456,789]

3
{'0":123, "1":456}

4
NULL

The goal would be to try and convert this string field as an array as opposed to a string:

id
dumped_field

1
[]

2
[123,456,789]

3
[123,456]

4
NULL

The problem is that these various data types have been stored as strings into this field. Is there a way to A) convert the string of array into an array and B) convert the string of json into an array?

A: Assuming your data is json (and after fixing the quotes in the object) you can process it as json (leveraging try and try_cast):
-- sample data
WITH dataset (id, dumped_field) AS (
   VALUES (1,   '[]'),
        (2, '[123,456,789]'),
        (3, '{"0":123, "1":456}'),
        (4, NULL)
)

-- query
select coalesce(
    try_cast(json_parse(dumped_field) as array(varchar)), --  try process as array
    try(map_values(cast(json_parse(dumped_field) as map(varchar, varchar)))))  --  try process as object
from dataset;

Output:

_col0

[]

[123, 456, 789]

[123, 456]

NULL


text:
Q: VS Code giving header errors for Arduino? Missing official header? I've recently started developing for Arduino. Initially I used the Arduino IDE but I soon realised it was not up to par. Development was considerably slower with the need for IDE restarts every now and then. I found VS Code with the Arduino Extension which I've come to love. However I have a few issues and I'm not sure how to solve it.
First of all vs code throws #include errors and asks me to update IntelliSense. However it builds/uploads and runs perfectly well, it also finds the classes etc. defined in said includes so it looks like it's a false positive in some way (i.e. the path is included in includePath settings). Reading the error message also shows it having issues finding a header referenced in Arduino.h called "avr/pgmspace.h". I'm unsure if these errors are related. pgmspace.h is nowhere to be found (it should have been included in the Arduino SDK).
Finally because of the #include error anything related to that particular header file will not be highlighted properly and is just plain gray text which is a bit annoying.
Anyone knows how to fix this? I'm on a Mac btw.

A: The accepted answer didn't work for me. Can't find nor create c_cpp_properties.json file. Also, I wanted it to be global, and not only to one project/workspace/folder.
So, for VSCode 1.14 (2019) I just navigate till settings.json (the global one), and add this json section:
"C_Cpp.default.includePath": [
    "C:/Program Files (x86)/Arduino/libraries/**",
    "C:/Program Files (x86)/Arduino/hardware/arduino/avr/cores/arduino/**",
    "C:/Program Files (x86)/Arduino/hardware/tools/avr/avr/include/**",
    "C:/Program Files (x86)/Arduino/hardware/tools/avr/lib/gcc/avr/5.4.0/include/**",
    "C:/Program Files (x86)/Arduino/hardware/arduino/avr/variants/standard/**",
    "C:/Users/<YOUR USERNAME>/.platformio/packages/framework-arduinoavr/**",
    "C:/Users/<YOUR USERNAME>/Documents/Arduino/libraries/**",
    "{$workspaceFolder}/libraries/**",
    "{$workspaceFolder}/**"
],
"C_Cpp.intelliSenseEngine": "Tag Parser"

Posted another answer with the entire procedure and all details about the approach: Visual Studio Code includePath

A: Update: Extra libraries do not need to be installed. IntelliSense can operate using only the headers installed by the Arduino app, but a few others may help. More updates below.
When VSCode builds, it uses the SDK. However, IntelliSense cannot read the SDK files to operate (as far as I can tell), which throws these annoying errors and eliminates most code completion capabilities.
Both includePath and browse.path need to be configured. includePath does not include recursively (but that feature seems to be coming soon). browse.path is recursive, but including the exact location of header files is in includePath is still necessary for IntelliSense features. browse.path will use the Tag Parser to provide tools such as the "lightbulb" that you can click to help resolve your includePath issue. (Source: What is the difference between "includePath" and "browse.path" in c_cpp_properties.json?)

Mac:
avr/pgmspace.h is located at: /Applications/Arduino.app/Contents/Java/hardware/tools/avr/avr/include/avr/pgmspace.h. It's coded into the libraries as avr/pgmspace.h; for this reason, we need to include the path that avris located in.
1. Install homebrew-avr:
2. Edit c_cpp_properties.json:
"includePath": [
    "${workspaceFolder}/libraries",
    "/System/Library/Frameworks/Kernel.framework/Versions/A/Headers",
    "/Applications/Arduino.app/Contents/Java/libraries",
    "/Applications/Arduino.app/Contents/Java/hardware/tools/avr/avr/include",
    "/Applications/Arduino.app/Contents/Java/hardware/arduino/avr/variants/standard"
],
"browse": {
    "limitSymbolsToIncludedHeaders": false,
    "path": [
        "/System/Library/Frameworks/Kernel.framework/Versions/A/Headers",
        "/Applications/Arduino.app/Contents/Java/"
    ]
},
"forcedInclude": [
    "/Applications/Arduino.app/Contents/Java/hardware/arduino/avr/cores/arduino/Arduino.h"
],

Windows 10:
1. Install WinAVR
2. Edit c_cpp_properties.json:
Revise includePath to look like this:
"includePath": [
    "{$workspaceFolder}/libraries",
    "C:/Program Files (x86)/Arduino/hardware/tools/avr/lib/gcc/avr/5.4.0/include",
    "C:/Program Files (x86)/Arduino/hardware/arduino/avr/cores/arduino",
    "C:/Program Files (x86)/Arduino/hardware/arduino/avr/variants/standard",
    "C:/Program Files (x86)/Arduino",
],

Alternative Method (probably a bad idea):
If you can get a version of any missing library, you can probably put in in your libraries folder of your project if your includePath includes "${workspaceFolder}/libraries". Make sure to namespace your libraries appropriately, e.g. libraries/avr/pgmspace.h. I have not tested this method.

Updates:

*

*Changed from home.path to includePath. See more here: vscode-cpptools/FAQ

*The tools downloaded by the vscode-arduino libraries are not necessary on Windows 10.

*Changed Windows config paths to use forward slashes instead of escaped backslashes.

Source and further tips: Enabling Arduino Intellisense with Visual Studio Code

A: I am using VSC for code editor, and need only intellisense. I set in the arduino IDE preferences "use external editor" and I using it for compile and upload.
My win username "bunny" and the Sketchbook location is "C:\person\Arduino"  for understand the folders. I am using latest VSC (1.56.2) and ArduinoIDE (1.8.13)
My settings.json like this, there is working well with all library included special like esp8266 etc:
{
"C_Cpp.intelliSenseEngine": "Tag Parser",
    "C_Cpp.default.browse.path": [
        "c:/Person/Arduino/libraries",
        "c:/Person/Arduino/hardware",
        "c:/Program Files (x86)/Arduino/hardware",
        "c:/Program Files (x86)/Arduino/libraries",
        "c:/Users/Bunny/AppData/Local/Arduino15/packages",
        "${workspaceFolder}"
    ]
}

A: The accepted answer is very good.
I had to include some other folders as well, my includePath looks like this and I have no IntelliSense erros any more:
"includePath": [
                "${workspaceFolder}/**",
                "C:/Program Files (x86)/Arduino/hardware/tools/avr/lib/gcc/avr/7.3.0/include",
                "C:/Program Files (x86)/Arduino/hardware/arduino/avr/cores/arduino",
                "C:/Program Files (x86)/Arduino/hardware/arduino/avr/variants/standard",
                "C:/Users/<USER_NAME>/Documents/Arduino/libraries/**",
                "C:/Users/<USER_NAME>/AppData/Local/Arduino15/packages/arduino/hardware/avr/1.8.5/libraries/**",
                "C:/Users/<USER_NAME>/AppData/Local/Arduino15/libraries/**"
            ],

You can use these paths as inspiration to add if you encounter some header that cannot be found (like SPI.h or Ethernet.h).

A: The mentioned c_cpp_properties.json is located inside the project's .vscode directory.
If not present you can create it in VSCode by pressing Ctrl+Shift+P and typing the C/C++: Edit Configurations (JSON) command.
To improve upon Stefan's answer you can use ${env:USERNAME} in replacement of <USER_NAME> to make it automatically replaced by the current user's name.
These worked out for me:
"includePath": [
    "${workspaceFolder}/**",
    "C:/Program Files (x86)/Arduino/**",
    "C:/Program Files (x86)/Arduino/hardware/tools/avr/lib/gcc/avr/7.3.0/include",
    "C:/Program Files (x86)/Arduino/hardware/arduino/avr/cores/arduino",
    "C:/Program Files (x86)/Arduino/hardware/arduino/avr/variants/standard",
    "C:/Users/${env:USERNAME}/Documents/Arduino/libraries/**",
    "C:/Users/${env:USERNAME}/AppData/Local/Arduino15/packages/**",
    "C:/Users/${env:USERNAME}/Documents/Arduino/libraries/Adafruit_GFX_Library/",
    "C:/Program Files (x86)/Arduino/hardware/arduino/avr/libraries/SPI/src"
],

This was also useful, to change the compiler to gcc as naigonakoii suggests here:
"compilerPath": "C:/Program Files (x86)/Arduino/hardware/tools/avr/bin/avr-gcc.exe",
"intelliSenseMode": "gcc-x86",

And by adding some defines we have the ultimate anti-squiggly-line configuration (You might need to change the last one for the model you're using
"defines": [
    "_DEBUG",
    "UNICODE",
    "_UNICODE",
    "ARDUINO=100",
    "USBCON",
    "__AVR_ATmega328P__"
],


text:
Q: C# MVC Facebook application does not work in iPad Facebook application I've written a Facebook application using Microsoft's ASP.NET MVC template.  Works great from the browser on IE, Android's browser and will even work in Safari.
Inside the Android Facebook application clicking on the link to my application bounces you out to the web browser and everything is good to go.  On an iPhone or iPad going to my application works fine from inside Safari.  But if you run the iPhone or iPad Facebook application you get an error.  Across the top it says 'Error' and the details say "An error occurred. Please try again later."
I've search the SDK docs and googled around but I've not found anything that tells me what to do. Did I miss a setting for my application?  Is there some special cookie I need?  Do I need to go leave my wallet at Steve Job's grave?
Any help would be appreciated.


text:
Q: Convergence of series in L^p Let
$\langle f_n\rangle$ be a sequence of functions from the space $L^p(X,\mathcal M,\mu)$, $1\le p<\infty$,
such that the series
$$
\sum_{n=1}^\infty \|f_n\|_p \ \ \ (*)
$$
converges. Prove that then the series
$$
\sum_{n=1}^\infty f_n(x)
$$
converges in $L^p(X,\mathcal M,\mu)$.
I need to show that the sequence of partial sums $\{g_k(x)\}=\{ \sum_{n=1}^k f_n(x) \}$ is a Cauchy sequence in $L^p(X,\mathcal M,\mu)$, i.e. I need to show that for any $\epsilon > 0 $, there exists $M >> 0$ such that $n \geq m \geq M$ implies that $$||g_m(x)-g_n(x)||_p < \epsilon \ \ \ \text{or} \ \ \ \big(\int_X |\sum_{j=n+1}^m f_j(x)|^p d\mu \big)^{1/p}<\epsilon  $$ But I do not see how to get this using the convergence of (*). I already appreciate your hints/answers.

A: This is true in any complete normed space. You have
$$
\left\|\sum_{n=k}^mf_n\right\|_p\leq\sum_{n=k}^m\|f_n\|_p.
$$
This allows you to show that the sequence of partial sums is Cauchy, by using the convergence of $(*) $.


text:
Q: Can predicate and propositional logic be 'mixed'? Motivation
I wanted to write out a simple statement from linear algebra in a very formal, predicate logic way. The statement is that given two vector spaces $V \subset W$ over a field $\mathbb{F}$, $V$ is a subspace iff for any two vectors, any linear combination of them is contained in $V$.
I initially wrote $$\forall a \in V \forall b \in V \forall \alpha \in \mathbb{F} \forall \beta \in \mathbb{F} \big(V \text{ is a subsapce iff } a\alpha + b\beta \in V\big)$$
I realised this was wrong, and it should be (as confirmed by this set of notes I found)$$V \text{ is a subsapce iff } \forall a \in V \forall b \in V \forall \alpha \in \mathbb{F} \forall \beta \in \mathbb{F} \big( a\alpha + b\beta \in V\big)$$
It felt wrong in the first instance that the universal quantifiers extend over the statement that $V$ is a subspace.
Question
However, my issue is with proving these two are different. The way I see it, it's akin to trying to showing that $$\forall x P(x) \iff Q \text{ and } \forall x (P(x) \iff Q)$$ are different statements. Here I write $P(x)$ to be analogous to arbitrary vectors/scalars, over which we use a universal quantifier, and I write $Q$ as a statement that is independent of the variable $x$, to represent the statement that a vector is a subspace. To my mind, $Q$ is like a propositional statement, that is either simply either true or false.
But I am failing to to prove the two are not equivalent statements (I also tried showing that they ARE the same statements). In particular, I tried writing out truth tables, but got stuck and came across this post which explains that quantifiers do not work with truth tables.
Are these statements equivalent? And how do you go about proving it? (I realise my discussion of the logic here is likely shaky at best, so apologies if I'm under obvious misconceptions.)

A: You're right that these statements are different.
The quickest way to see this is by looking at the claim
$$
\forall a,b \in V . \forall \alpha, \beta \in \mathbb{F} . (V \text{ is a subspace} \iff \alpha a + \beta b \in V)
$$
If this is true, then (basically by definition) we should have
$$
(V \text{ is a subspace} \iff \alpha a + \beta b \in V)
$$
for every choice of $a,b \in V$ and $\alpha, \beta \in \mathbb{F}$. (Do you see why?)
In particular, this must be true when $a,b = 0$ and $\alpha, \beta = 0$. But in this case the claim reads
$$
(V \text{ is a subspace} \iff 0 \in V)
$$
which we know is false!

Said in the more abstract terms you adopts later, you're exactly right that
$$
\forall x \in X. (P(x) \iff Q) \quad \quad (1)
$$
is different from
$$(\forall x \in X . P(x)) \iff Q \quad \quad (2)$$
and the same argument works (as long as the domain $X$ has more than one element).
In formula $(1)$ we're saying that $P(x) \iff Q$ is true for every $x \in X$. So in particular, this tells us that $P(x_1) \iff Q \iff P(x_2)$ so that $P$ is constant on its domain $X$.
In formula $(2)$ we're saying that $Q$ is true exactly when $P(x)$ is always true. This is what we usually want to talk about.

But how can we formally prove that $(1)$ and $(2)$ are different? We need to exhibit a countermodel. We actually already have a countermodel from our first example of vector subspaces, but here's a small one you can really get your hands on:
Let $X = \{a,b\}$, with $P(a) = \top$, $P(b) = \bot$, and $Q = \bot$.

*

*Can you show that this model thinks $(1)$ is false?

*Can you show that this model thinks $(2)$ is true?

*From here, conclude that $(1)$ and $(2)$ must not be provably equivalent. If they were, they would have to be equivalent in all models, but here we've built a model where they differ.

I hope this helps ^_^


text:
Q: ebpf verifier fails for accessing SK_BUFF from kprobe function I couldn't access sk_buff from kprobe function. when i load and run this program, ebpf verifier fails with this. Do anyone know what im doing wrong here?
Error:
2022/04/20 20:56:17 loading objects: field NfHookSlow: program nf_hook_slow: load program: permission denied: ; int BPF_KPROBE(nf_hook_slow, struct sk_buff *skb, struct nf_hook_state *state,
0: (79) r1 = *(u64 *)(r1 +112)
; if (skb)
1: (15) if r1 == 0x0 goto pc+10
 R1_w=inv(id=0) R10=fp0
; struct ethhdr *eth = (struct ethhdr *)(skb->head + skb->mac_header);
2: (69) r2 = *(u16 *)(r1 +182)
R1 invalid mem access 'inv'
processed 3 insns (limit 1000000) max_states_per_insn 0 total_states 0 peak_states 0 mark_read 0

kprobe Program:
SEC("kprobe/nf_hook_slow")
int BPF_KPROBE(nf_hook_slow, struct sk_buff *skb, struct nf_hook_state *state,
               const struct nf_hook_entries *e, unsigned int s)
{

    if (skb)
    {
        struct ethhdr *eth = (struct ethhdr *)(skb->head + skb->mac_header);
        bpf_printk("eth: %d", eth->h_proto);
    }

    return 0;
}

I have even tried to read from kernel memory(bpf_probe_read_kernel(&proto, sizeof(proto), &eth->h_proto);) and print it but that's also failing
Error:
0: (79) r1 = *(u64 *)(r1 +112)
; if (skb)
1: (15) if r1 == 0x0 goto pc+9
 R1_w=inv(id=0) R10=fp0
; struct ethhdr *eth = (struct ethhdr *)(skb->head + skb->mac_header);
2: (69) r2 = *(u16 *)(r1 +182)
R1 invalid mem access 'inv'
processed 3 insns (limit 1000000) max_states_per_insn 0 total_states 0 peak_states 0 mark_read 0

Program:
SEC("kprobe/nf_hook_slow")
int BPF_KPROBE(nf_hook_slow, struct sk_buff *skb, struct nf_hook_state *state,
               const struct nf_hook_entries *e, unsigned int s)
{
  if (skb)
  {
    struct ethhdr *eth = (struct ethhdr *)(skb->head + skb->mac_header);
    u16 proto;
    bpf_probe_read_kernel(&proto, sizeof(proto), &eth->h_proto);
  }
  return 0;
}

A: I fixed it. Looks like have to use bpf_probe_read to read any memeber in sk_buff.
#define member_address(source_struct, source_member)                                                 \
    ({                                                                                \
        void *__ret;                                                                                \
        __ret = (void *)(((char *)source_struct) + offsetof(typeof(*source_struct), source_member)); \
        __ret;                                                                                \
    })
#define member_read(destination, source_struct, source_member) \
    do                                                         \
    {                                                          \
        bpf_probe_read(                                        \
            destination,                                       \
            sizeof(source_struct->source_member),              \
            member_address(source_struct, source_member));     \
    } while (0)

SEC("kprobe/nf_hook_slow")
int BPF_KPROBE(nf_hook_slow, struct sk_buff *skb, struct nf_hook_state *state)
{
    char *head;
    __u16 mac_header, nw_header, tcp_header, eth_proto;

    if (skb)
    {
        member_read(&head, skb, head);
        member_read(&mac_header, skb, mac_header);
        member_read(&nw_header, skb, network_header);

        char *eth_head = head + mac_header;
        bpf_probe_read(&eth_proto, sizeof(u16), &eth_head[12]);
    }

 }


text:
Q: Использование Claims или кэширование Нужно снизить нагрузку на БД. Чтобы пользователь мог нажать кнопку (оправить данные на сервер), например 1 раз в день. Как это лучше реализовать?

A: Можно писать в куки Claims, или свои какието данные в шифрованном виде.
Например объект сериализованный в JSON, который затем зашифровать с помощью ключа или соли.


text:
Q: What is the TYPE of an Excel R1C1 reference? I have created some VBA functions to use with an Excel spreadsheet. Right now, the parameters to the functions have type String so I have to pass my column reference as a string.
However, I much prefer the R1C1 notation (been using that since Multiplan) but I can't figure out how to pass a column reference to a VBA function with that notation. In other words, I want to define a function so I can call it in the following way
=foo(C[-2])
so I'm looking for right type for the following function
function foo(ColRef as WhatTypeGoesHere) ...

A: This will explain which one to use :)
Dim ws As Worksheet

Sub Sample()
    Set ws = ThisWorkbook.Sheets("Sheet1")

    Debug.Print foo1("B")         '<~~ Col Name
    Debug.Print foo2(Range("B1")) '<~~ Range
    Debug.Print foo3(2)           '<~~ Col Number
    Debug.Print foo4("R1C2")      '<~~ RC Notation
End Sub

Function foo1(ColRef As String) As Long
    foo1 = ws.Cells(ws.Rows.Count, ColRef).End(xlUp).Row
End Function

Function foo2(ColRef As Range) As Long
    foo2 = ws.Cells(ws.Rows.Count, ColRef.Column).End(xlUp).Row
End Function

Function foo3(ColRef As Integer) As Long
    foo3 = ws.Cells(ws.Rows.Count, ColRef).End(xlUp).Row
End Function

Function foo4(ColRef As String) As Long
    Dim MYAr
    MYAr = Split(ColRef, "C", , vbTextCompare)
    foo4 = ws.Cells(ws.Rows.Count, Val(MYAr(UBound(MYAr)))).End(xlUp).Row
End Function

Screenshot

EDIT:
What is to be noted is that "C[-2]" is not Column B it is an offset from the current cell. Here is another example which can handle different RC notations. Note, I am not doing any error handling but I am sure you can handle that. The objective of this code is to show how to find the last row using RC notation
Dim ws As Worksheet

Sub Sample()
    Set ws = ThisWorkbook.Sheets("Sheet1")
    Debug.Print foo4("C[-2]")
    Debug.Print foo4("RC[-2]")
    Debug.Print foo4("R[-1]C[-2]")
End Sub

Function foo4(ColRef As String) As Long
    Dim MYAr, sTmp As String
    Dim colNo As Integer
    Dim rng As Range

    '~~> I am assuming that you will pass a `C`. If not then
    '~~> Add an error handling here
    MYAr = Split(ColRef, "C", , vbTextCompare)

    If InStr(1, MYAr(UBound(MYAr)), "[") Then
        tmpAr = Split(MYAr(UBound(MYAr)), "[")(1)
        tmpAr = Split(tmpAr, "]")(0)
        colNo = Val(Trim(tmpAr))
    Else
        colNo = MYAr(UBound(MYAr))
    End If

    Set rng = ActiveCell.Offset(, colNo)

    foo4 = ws.Cells(ws.Rows.Count, rng.Column).End(xlUp).Row
End Function

A: In your case, use a Range.
You can specify any data type and Excel will implicitly convert as needed. It really depends on what the function does. For instance, if the function works with a group of cells or single cell, then use Range, if the function strips out characters, use a String.


text:
Q: Use Entity Framework database first db context with mvvm view model classes I am pretty new to MVVM and WPF and I am not completely sure if what I am going to ask now is correct.
I am making a MVVM WPF application. I have a SQL Server database and I am using Entity Framework database-first to generate model classes for me. I have created view model classes and from what I understand from the dozens of tutorials I read today is that I need a ObservableCollection which consists of my view model classes. Is that correct?
The problem is that Entity Framework has already generated a database context for me which contains collections but they are using the model classes and if the above is correct then I will need to make the Entity Framework database context use my view model classes. The question is how.
Do I need to create a new database context class which suits my needs and use that instead or is there a simpler approach which I am missing?
Here is the model class that Entity Framework has generated for me:
public partial class Parent
{
    public Parent()
    {
        this.Children = new HashSet<Child>();
    }

    public int ID { get; set; }
    public string Name { get; set; }
    public string PIN { get; set; }
    public string Account { get; set; }
    public string Identity_Card { get; set; }
    public string Address { get; set; }

    public virtual ICollection<Child> Children { get; set; }
}

Thanks in advance. Tell me if I have missed to mention something or add a part of the code and I will do it.

A: Something like this would most likely suffice for what @bas was mentioning,
and I would agree that it's the desired way to go.. your viewmodels are not
your models.
public class MainViewModel : INotifyPropertyChanged
{
    public MainViewModel(IRepository<Parent> parentRepo, IViewModelFactory factory)
    {
        // you might want to set this up as a fancy async method
        // because.. it looks better and it's easier to read
        Task.Factory
            .StartNew(() => parentRepo.GetAll())
            .ContinueWith(t =>
            {
                // Do error checking and all that boring stuff
                ParentViewModels =
                    new ObservableCollection<ParentViewModel>(
                        t.Result.Select(p => factory.Create<ParentViewModel>(p)));
            }, TaskScheduler.FromCurrentSynchronizationContext());
    }

    private ObservableCollection<ParentViewModel> _parentViewModels;
    public ObservableCollection<ParentViewModel> ParentViewModels
    {
        get
        {
            return _parentViewModels;
        }
        set
        {
            _parentViewModels = value;
            RaisePropertyChanged("ParentViewModels");
        }
    }

    // INotifyPropertyChanged implementation goes here
}

// Super secret sauce viewmodelfactory and repository implementations go here

A:
The problem is that Entity Framework has already generated a database
  context for me which contains collections but they are using the model
  classes and if the above is correct then I will need to make the
  Entity Framework database context use my view model classes. The
  question is how.

Not sure if I understand what you are saying here, but generated classes are generated classes. You're not supposed to mold them into something else.
Your generated classes can be read by your view model classes. Now I can imagine that feels like duplication, but there's more to consider. First of all your database classes can contain more data than you like to show in your views. So just hiding the data so that you only provide your views the data they need is a perfect strategy. I think security-wise it's also safe to say that you don't want to provide the entities that are directly connected to your database, in your view. But that's probably a different discussion.
So create your view models and fill them with the data provided via your entities.
In any event, do not modify your generated classes in such a way that you need to redo it again when you generate them again :).

A: Just replace the references of the models in the current DataContext with the ones with the models you want to use.


text:
Q: Pass data between table view controller to detail view controller using Parse.com I have to pass data between table view controller and detail view controller, and I'm using Parse to load the data from backend, I have do this with local data, this is the source code:
Table view controller:
#import "RecipeBookViewController.h"
#import "RecipeDetailViewController.h"
#import "Recipe.h"

@interface RecipeBookViewController ()

@end

@implementation RecipeBookViewController {
    NSArray *recipes;
}

@synthesize tableView = _tableView;

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Initialize table data
 //   recipes = [NSArray arrayWithObjects:@"Egg Benedict", @"Mushroom Risotto", @"Full Breakfast", @"Hamburger", @"Ham and Egg Sandwich", @"Creme Brelee", @"White Chocolate Donut", @"Starbucks Coffee", @"Vegetable Curry", @"Instant Noodle with Egg", @"Noodle with BBQ Pork", @"Japanese Noodle with Pork", @"Green Tea", @"Thai Shrimp Cake", @"Angry Birds Cake", @"Ham and Cheese Panini", nil];

    Recipe *recipe1 = [Recipe new];
    recipe1.name = @"Egg Benedict";
    recipe1.prepTime = @"30 min";
    recipe1.imageFile = @"egg_benedict.jpg";
    recipe1.ingredients = [NSArray arrayWithObjects:@"2 fresh English muffins", @"4 eggs", @"4 rashers of back bacon", @"2 egg yolks", @"1 tbsp of lemon juice", @"125 g of butter", @"salt and pepper", nil];

    Recipe *recipe2 = [Recipe new];
    recipe2.name = @"Mushroom Risotto";
    recipe2.prepTime = @"30 min";
    recipe2.imageFile = @"mushroom_risotto.jpg";
    recipe2.ingredients = [NSArray arrayWithObjects:@"1 tbsp dried porcini mushrooms", @"2 tbsp olive oil", @"1 onion, chopped", @"2 garlic cloves", @"350g/12oz arborio rice", @"1.2 litres/2 pints hot vegetable stock", @"salt and pepper", @"25g/1oz butter", nil];

    Recipe *recipe3 = [Recipe new];
    recipe3.name = @"Full Breakfast";
    recipe3.prepTime = @"20 min";
    recipe3.imageFile = @"full_breakfast.jpg";
    recipe3.ingredients = [NSArray arrayWithObjects:@"2 sausages", @"100 grams of mushrooms", @"2 rashers of bacon", @"2 eggs", @"150 grams of baked beans", @"Vegetable oil", nil];

    Recipe *recipe4 = [Recipe new];
    recipe4.name = @"Hamburger";
    recipe4.prepTime = @"30 min";
    recipe4.imageFile = @"hamburger.jpg";
    recipe4.ingredients = [NSArray arrayWithObjects:@"400g of ground beef", @"1/4 onion (minced)", @"1 tbsp butter", @"hamburger bun", @"1 teaspoon dry mustard", @"Salt and pepper", nil];

    Recipe *recipe5 = [Recipe new];
    recipe5.name = @"Ham and Egg Sandwich";
    recipe5.prepTime = @"10 min";
    recipe5.imageFile = @"ham_and_egg_sandwich.jpg";
    recipe5.ingredients = [NSArray arrayWithObjects:@"1 unsliced loaf (1 pound) French bread", @"4 tablespoons butter", @"2 tablespoons mayonnaise", @"8 thin slices deli ham", @"1 large tomato, sliced", @"1 small onion", @"8 eggs", @"8 slices cheddar cheese", nil];

    Recipe *recipe6 = [Recipe new];
    recipe6.name = @"Creme Brelee";
    recipe6.prepTime = @"1 hour";
    recipe6.imageFile = @"creme_brelee.jpg";
    recipe6.ingredients = [NSArray arrayWithObjects:@"1 quart heavy cream", @"1 vanilla bean, split and scraped", @"1 cup vanilla sugar", @"6 large egg yolks", @"2 quarts hot water", nil];

    Recipe *recipe7 = [Recipe new];
    recipe7.name = @"White Chocolate Donut";
    recipe7.prepTime = @"45 min";
    recipe7.imageFile = @"white_chocolate_donut.jpg";
    recipe7.ingredients = [NSArray arrayWithObjects:@"3 1/4 cups flour", @"2 teaspoons baking powder", @"1/4 teaspoon salt", @"2 beaten eggs", @"2/3 cup sugar", @"2 ounces melted white chocolate", @"1/2 cup milk", nil];

    Recipe *recipe8 = [Recipe new];
    recipe8.name = @"White Chocolate Mocha";
    recipe8.prepTime = @"5 min";
    recipe8.imageFile = @"starbucks_coffee.jpg";
    recipe8.ingredients = [NSArray arrayWithObjects:@"2/3 cup whole milk", @"6 tablespoons white chocolate chips", @"coffee", @"whipped cream", nil];

    Recipe *recipe9 = [Recipe new];
    recipe9.name = @"Vegetable Curry";
    recipe9.prepTime = @"30 min";
    recipe9.imageFile = @"vegetable_curry.jpg";
    recipe9.ingredients = [NSArray arrayWithObjects:@"1 tablespoon olive oil", @"1 onion, chopped", @"2 cloves garlic", @"2 1/2 tablespoons curry powder", @"2 quarts hot water", nil];

    Recipe *recipe10 = [Recipe new];
    recipe10.name = @"Instant Noodle with Egg";
    recipe10.prepTime = @"8 min";
    recipe10.imageFile = @"instant_noodle_with_egg.jpg";
    recipe10.ingredients = [NSArray arrayWithObjects:@"1 pack of Instant Noodle", @"2 eggs", nil];

    Recipe *recipe11 = [Recipe new];
    recipe11.name = @"Noodle with BBQ Pork";
    recipe11.prepTime = @"20 min";
    recipe11.imageFile = @"noodle_with_bbq_pork.jpg";
    recipe11.ingredients = [NSArray arrayWithObjects:@"1 pack of Instant Noodle", @"BBQ pork", @"Salt and Pepper", nil];

    Recipe *recipe12 = [Recipe new];
    recipe12.name = @"Japanese Noodle with Pork";
    recipe12.prepTime = @"20 min";
    recipe12.imageFile = @"japanese_noodle_with_pork.jpg";
    recipe12.ingredients = [NSArray arrayWithObjects:@"1 pack of Japanese Noodle", @"2 green onions", @"2 garlic cloves, minced", @"4 boneless pork loin chops", nil];

    Recipe *recipe13 = [Recipe new];
    recipe13.name = @"Green Tea";
    recipe13.prepTime = @"5 min";
    recipe13.imageFile = @"green_tea.jpg";
    recipe13.ingredients = [NSArray arrayWithObjects:@"Green tea", nil];

    Recipe *recipe14 = [Recipe new];
    recipe14.name = @"Thai Shrimp Cake";
    recipe14.prepTime = @"1.5 hours";
    recipe14.imageFile = @"thai_shrimp_cake.jpg";
    recipe14.ingredients = [NSArray arrayWithObjects:@"8 oz (250g) peeled and deveined raw shrimp", @"2 tablespoons red curry paste", @"1 large egg", @"2 teaspoon fish sauce", @"1 tablespoon sugar", @"2 tablespoons coconut milk", @"2 tablespoons roughly chopped Thai basil leaves", nil];

    Recipe *recipe15 = [Recipe new];
    recipe15.name = @"Angry Birds Cake";
    recipe15.prepTime = @"4 hours";
    recipe15.imageFile = @"angry_birds_cake.jpg";
    recipe15.ingredients = [NSArray arrayWithObjects:@"12 tablespoons (1 1/2 sticks) unsalted butter", @"2 1/2 cups all-purpose flour", @"1 tablespoon baking powder", @"1 teaspoon salt", @"1 3/4 cups sugar", @"2 large eggs, plus 3 large egg yolks", @"1 cup of milk", nil];

    Recipe *recipe16 = [Recipe new];
    recipe16.name = @"Ham and Cheese Panini";
    recipe16.prepTime = @"10 min";
    recipe16.imageFile = @"ham_and_cheese_panini.jpg";
    recipe16.ingredients = [NSArray arrayWithObjects:@"2 tablespoons unsalted butter", @"4 cups thinly sliced shallots", @"2 teaspoons fresh thyme", @"1/4 cup grainy Dijon mustard", @"8 slices rustic white bread", @"8 slices Gruyere cheese", @"8 ounces sliced cooked ham", nil];

    recipes = [NSArray arrayWithObjects:recipe1, recipe2, recipe3, recipe4, recipe5, recipe6, recipe7, recipe8, recipe9, recipe10, recipe11, recipe12, recipe13, recipe14, recipe15, recipe16, nil];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [recipes count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *simpleTableIdentifier = @"RecipeCell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];

    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
    }

    Recipe *recipe = [recipes objectAtIndex:indexPath.row];
    cell.textLabel.text = recipe.name;

    return cell;
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([segue.identifier isEqualToString:@"showRecipeDetail"]) {
        NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
        RecipeDetailViewController *destViewController = segue.destinationViewController;
        destViewController.recipe = [recipes objectAtIndex:indexPath.row];

        // Hide bottom tab bar in the detail view
     //   destViewController.hidesBottomBarWhenPushed = YES;
    }
}

Detail View Controller:
@interface RecipeDetailViewController ()

@end

@implementation RecipeDetailViewController

@synthesize recipePhoto;
@synthesize prepTimeLabel;
@synthesize ingredientTextView;
@synthesize recipe;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.title = recipe.name;
    self.prepTimeLabel.text = recipe.prepTime;
    self.recipePhoto.image = [UIImage imageNamed:recipe.imageFile];

    NSMutableString *ingredientText = [NSMutableString string];
    for (NSString* ingredient in recipe.ingredients) {
        [ingredientText appendFormat:@"%@\n", ingredient];
    }
    self.ingredientTextView.text = ingredientText;

}

- (void)viewDidUnload
{
    [self setRecipePhoto:nil];
    [self setPrepTimeLabel:nil];
    [self setIngredientTextView:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

@end

How can I do this using the Parse.com backend?

A: Assuming you have a a Recipe class in the Parse backend, you should be able simply replace the code in your initializer that creates the recipes with a Parse query to retrieve them instead. Something like the following (note I haven't exactly checked syntax):
PFQuery *recipeQuery = [PFQuery queryWithClassName:@"Recipe"];
[recipeQuery findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
    if (!error) {
        self.recipes = <Map parse objects to Recipe objects here>;
    }
}];

If you map the returned Parse objects to Recipe objects, you shouldn't need to change any of the rest of your code, apart from dealing with the delay in loading content over the network (you'd probably want to display some kind of loading indicator to the user).
Alternatively, you could look into the PFQueryTableViewController, provided with Parse framework, which will probably do everything you need.


text:
Q: Induced map from a complex of modules Let $A\longrightarrow B\longrightarrow C$ be a complex of $R$-modules, where we label the maps $f$ and $g$, respectively.
Why is the sequence $0\longrightarrow H(B)\longrightarrow \text{coker}(f)\longrightarrow \text{im}(g)\longrightarrow 0$ exact? (where $H(B)$ is $\text{ker}(g)/\text{im}(f)$, the cohomology of the sequence at $B$.)
How do we even get the two internal maps, let alone exactness?

A: We have a sequence
$$0\to\ker(g)\hookrightarrow B\xrightarrow{g}\text{im}(g)\to 0$$
which is clearly exact. Furthermore, $\text{im}(f)\subseteq\ker(g)\subseteq B$ and $\text{im}(f)$ is mapped to $0$ by $g$ since $gf=0$, so we have an induced surjective map $\text{coker}(f)=B/\text{im}(f)\xrightarrow{\bar{g}}\text{im}(g)$. The map $\ker(g)\to\text{coker}(f)$ (which is the composition of the inclusion map $\ker(g)\hookrightarrow B$ and the projection map $B\to B/\text{im}(f)$) has kernel $\text{im}(f)=H(B)$, so we have the induced injective map $H(B)=\ker(g)/\text{im}(f)\to\text{coker}(f)$. Then, by the exactness of the first sequence, we conclude that
$$0\to H(B)\to\text{coker}(f)\xrightarrow{\bar{g}} \text{im}(g)\to 0$$
is exact.

A: Anonymous's answer is correct (+1), I just like diagrams, so I thought I'd provide one.
We have the diagram:
$$
\require{AMScd}
\newcommand\im{\operatorname{im}}
\newcommand\coker{\operatorname{coker}}
\begin{CD}
0 @>>> \im f @>1_{\im f}>> \im f @>>> 0 @>>> 0 \\
@. @VVV @VVV @VVV @. \\
0 @>>> \ker g @>>> B @>>> \im g @>>> 0,
\end{CD}
$$
which has exact rows, and the vertical maps are all injective. Therefore, when we apply
snake lemma, we get an exact sequence (of the cokernels of the vertical maps)
$$ 0 \to H(B) \to \coker f \to \im g \to 0.$$


text:
Q: Поле с геттером без сеттера У меня есть класс, в котором я бы не хотел, чтобы его поля можно было менять. Не могу понять как это сделать. Такая конструкция не работает:
class Message
{
    public readonly MessageType MessageType { private set; get; }
    public readonly string Data { private set; get; }

    public Message(MessageType type)
    {
        MessageType = type;
        Data = null;
    }

    public Message(MessageType type, string data)
    {
        MessageType = type;
        Data = data;
    }

}

A: В C#, модификатор readonly применяется только к полям. Чтобы объявить свойство - только для чтения, достаточно просто опустить объявление сеттера.
private MessageType fMessageType;
public MessageType MessageType { get { return fMessageType; } }
// или так
public MessageType MessageType { get; private set; }

Кроме того, в C# 6 появилась возможность опускать сеттер даже у автореализованных свойств. Такое свойство нужно проинициализировать в конструкторе, или прямо при объявлении, как это делается с полями.
public class Test {
    public string A { get; } = "B";
    public Test() {
        A = "A";
    }
}


text:
Q: Empty assosiated entities in EF 6.0 Fluent Api I try to implement 1..0  relations with Entity Framework 6. I use instance associsaltion. I try to repeat the examples from web and forums but somehow it doesn't work for me. Please, help.
Entities:
  public class CustomerWithFk : Item  // Item contains Id
    {
        public string Name { get; protected set; }
        public virtual City City { get; set; }      // relation property. Can be 1 or 0
        public virtual Product Product { get; set; }
        public decimal Money { get; protected set; }
    }

    public class City : Item
    {
        public string Name { get; protected set; }
    }

Mappings:
public CityMap()
{
    ToTable("Cities");
    HasKey(c => c.Id);
}

public CustomerFkAssosiationMap()
{
    ToTable("Customers");
    HasKey(c => c.Id);

    HasRequired(g => g.City)
        .WithRequiredDependent();

    HasRequired(g => g.Product)
                .WithRequiredDependent()
                .Map(x => x.MapKey("ProductId"));
}

Database tables:

SQL Profiler gives me enxt SQL request:
SELECT
    1 AS [C1],
    [Extent1].[Id] AS [Id],
    [Extent1].[Name] AS [Name],
    [Extent1].[Money] AS [Money],
    [Extent1].[CityId] AS [CityId],
    [Extent1].[ProductId] AS [ProductId]
    FROM [dbo].[Customers] AS [Extent1]

So, I don't see any joins here to load data from Cities or Products.
And the result is Null:

I tried different mapping options, like: HasOptional, WithRequiredPrincipal, tried to add Customers proeprty to City (while it's incorrect and City doesn't have to know something about customers)
Nothing helps. The assosiated entities are always null.
Where am I wrong?

A: The problem is that you are not including the related objects.  Try something like this using Include:
var list = context.CustomerWithFk
                  .Include("City")
                  .Include("Product");

That tells Entity Framework that you want to pull back the customer along with the city and product.  Here is some further reading if you are interested: http://msdn.microsoft.com/en-us/data/jj574232.aspx.
EDIT: You could also enable lazy loading (based on your comment I believe it is what you are after) by adding this to your context:
context.ContextOptions.LazyLoadingEnabled = true;

Read more about lazy loading here: http://msdn.microsoft.com/en-us/library/vstudio/dd456846(v=vs.100).aspx.


text:
Q: Microsoft Graph mangles SharePoint list number column values I have a SharePoint Online list containing a number column with the following values:

*

*90038946

*90000624

*90000627

*235712345

When I use the Microsoft Graph API the values coming back are mangled:

*

*90038940

*90000620

*90000620

*235712352

This happens both using the MS Graph dotnet sdk as well as the Graph Explorer so it seems to be a feature of the MS Graph API Service.
The REST URI I'm using in Graph Explorer (where OrgUnitCode is the number column) is:
https://graph.microsoft.com/v1.0/sites/<SharePointTenant>,<SiteCollectionId>,<SiteId>/lists/<ListId>/items?$expand=fields($select%3DTitle,Code,Region,OrgUnitCode)

RESULT:
"fields": {
                "@odata.etag": "\"<GUID REMOVED>,1\"",
                "Title": "<REMOVED>",
                "Code": "<REMOVED>",
                "Region": "<REMOVED>",
                "OrgUnitCode@odata.type": "#Single",
                "OrgUnitCode": 90038940
            }

The SharePoint REST API returns the values without mangling the values:
https://<SharePointTenant>/sites/<SiteCollectionName>/_api/web/lists/GetByTitle('<ListName>')/items

RESULT:
...<d:OrgUnitCode m:type="Edm.Double">90038946</d:OrgUnitCode>...

How do I turn off the mangling feature in Microsoft Graph so I can retrieve the actual values?

A: Microsoft has confirmed that this is a service bug for the SharePoint Graph API.
https://github.com/microsoftgraph/msgraph-sdk-dotnet/issues/321#issuecomment-446754950

This is a confirmed service bug and has been escalated to the proper team.


text:
Q: ORDER BY last column I have this:
SELECT
    NONEMPTY(
        [Date].[Calendar].[Calendar Year].MEMBERS
    )
    *
    [Measures].[Internet Sales Amount] on 0,
    ORDER(
        [Customer].[Customer Geography].[State-Province].MEMBERS
        ,[Measures].[Internet Sales Amount]
        ,BDESC)
     on 1
from [Adventure Works]

What is the most efficient way of ordering descending by the last date column - this should be dynamic so that it still works when we go over month end.

A: I would use
ORDER(
        [Customer].[Customer Geography].[State-Province].MEMBERS
        ,([Measures].[Internet Sales Amount]
          ,Tail([Date].[Calendar].[Calendar Year]).Item(0).Item(0)
         )
        ,BDESC)

and assume that the added term Tail([Date].[Calendar].[Calendar Year]).Item(0).Item(0) can be calculated by Analysis Services just checking the time dimension, and does not need any dynamic context, and hence should be fast.

A: If you want to have an expression which is independent of the content of the columns, you can use:
ORDER([Customer].[Customer Geography].[State-Province].MEMBERS
      ,Tail(Axis(0)).item(0)
      ,BDESC)


text:
Q: How to request rights to commit to an open source git repository? I've created a configuration file for a specific open source project that I want to integrate into the master branch.
I know that there is a whole process to go through before it gets approved and integrated into the master branch.
My question is, how do I go about requesting access to commit this file?

A: Create a Pull Request after committing your changes.


text:
Q: Reputation cap rule will change or anyday with 200+ can consider its a cap? I am just trying to figure out how many days I have capped with this code in /users/rep-report
javascript:alert(document.body.innerHTML.match(/+(?:\d{4,}|[2-9]\d{2})/g).length)
Edit: see my answer for the correction
I got 29 days with 200+ but can I assume I've capped on 29 days?
For example following day, I got 218, Its not really capped, because 4 are accepted answers, they can consider in separate box with new rule.
 2   2010537 (10)
 2   2046512 (10)
 2   2046849 (10)
 2   2046849 (10)
 1   2042233 (15)
 2   2047621 (10)
 2   2047621 (10)
 1   2047621 (15)
 2   2040199 (10)
 2   2048019 (10)
 2   2048019 (10)
 1   2048019 (15)
 2   2048019 (10)
 2   2048117 (10)
 2   2048117 (10)
 2   2048117 (10)
 3           (-2)
 2   2048019 (10)
 2   2048545 (10)
 1   2048545 (15)
 2   2047950 (10)
-- 1/12/2010  rep +218

A: I think the answer is the reverse of the accepted here, running this on my rep report:
javascript:alert(document.body.innerHTML.match(/\+(?:\d{4,}|[2-9]\d{2})/g).length)

Gives me exactly 150 days, and I just hit 200 rep for the day, granting me the badge (the latest greasemonkey script shows 4 more days remaining, if you're curious (profile link)).
For a view of my rep report right after the badge, here's it is for analysis:
http://pastebin.com/raw.php?i=Lneqdxve
It seems that the calculation is just 200+ points per day, from any source.  I don't have quite 150 of 200+ rep from raw upvote days, so it can't be based on pure votes, at least not from what I'm seeing.
Here are two of the days in the above rep report to show bounty/accepted being included:
+280 had to include 250 from the bounty, only +30 from votes:
-------------------------------------------------------------
 2   1495589 (10)
 2   1495589 (10)
 9   1495589 (250)
 2   1424659 (10)
-- 2009-09-30 rep +280  = 1983

+245 had to include 75 from accepted, only +170 from votes:
-----------------------------------------------------------
 2   2098205 (10)
 2   2098205 (10)
 2   2098205 (10)
 2   2098803 (10)
 2   2098803 (10)
 2   2098803 (10)
 2   2097602 (10)
 2   2098846 (10)
 2   2098793 (10)
 2   2101942 (10)
 2   2101942 (10)
 2   2102239 (10)
 1   2102239 (15)
 1   2098803 (15)
 1   2102033 (15)
 1   2098793 (15)
 2   2105179 (10)
 2   2105179 (10)
 2   2105179 (10)
 2   2105179 (10)
 2   2105533 (10)
 1   2105179 (15)
-- 2010-01-20 rep +245  = 2999


text:
Q: MS Access 2016: CTRL+A saves the form? I have a strange problem that I don't know how to track down.
I have a form that closes itself using an _AfterUpdate event. I found, by accident, that when I am inside a TextBox control and I attempt to select all text using CTRL+A that the form updates. This causes the _AfterUpdate to run and the form closes. The effect is that pressing CTRL+A is now "save and quit" instead of "select all text", as expected.
I've dug through all of my events and none of them are trapping keys like CTRL or A. I only have one button called "Submit" and it is the default button. I haven't found any other key combo that causes this behavior.
Does anyone know of any reason that pressing CTRL+A while in a TextBox would update the form?
BONUS POINTS: Does anyone know how I can trace what is happening? How do I break on the action to see what is capturing this key comobo? How do I even troubleshoot this?
CURRENT WORKAROUND:
I am now using a Submit button pressed flag and a _BeforeUpdate event to determine if the Sumbit button was pressed so I can cancel the update if the button was not pressed. The side-effect of this workaround is that now pressing CTRL+A does nothing. It does not select all but at least it doesn't submit the form either. Now I'm double confused as to where the CTRL+A is going.

A: MS-Access textboxes don't react to Ctrl+A. To select all text in a textbox, click its associated label, or TAB into it.
Ctrl+A always selects all records (in a continuous form or datasheet) or the current record (in single form). This automatically saves the current record, invoking AfterUpdate.

Edit: some thoughts on simulating Ctrl+A in textboxes:
Set Form.KeyPreview = True
Trap Ctrl+A in Form_KeyDown
Use Screen.ActiveControl to determine the active control
If it's a textbox, use SelStart and SelLength to select its content.


text:
Q: keeping list view item highlighted I am working on the messaging app , when the message received it is updated in the list and I want to keep list view item highlighted all until they are clicked by the user in order to show the user that these are his new messages.Every time the message is received it is updated in the position 0 of the list view, and I want to highlight 0 position of the list view ,I am using :
adapter.insert(message, 0);
    ArrayAdapter<Message> adap = new ArrayAdapter<Message>(getActivity(), android.R.layout.simple_list_item_1) {
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View itemView = super.getView(0, convertView, parent);
                 itemView.setBackgroundColor(0xA0FF8000); // orange
              return itemView;
        }
    };
    adapter.notifyDataSetChanged();

My app give me error when the message is received:
12-26 14:48:20.891: E/AndroidRuntime(29012): FATAL EXCEPTION: main
12-26 14:48:20.891: E/AndroidRuntime(29012): java.lang.RuntimeException: Error receiving broadcast Intent { act=soft.b.peopleassist flg=0x10 (has extras) } in soft.b.peopleassist.Receive$1@41cc2b50
12-26 14:48:20.891: E/AndroidRuntime(29012):    at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:795)
12-26 14:48:20.891: E/AndroidRuntime(29012):    at android.os.Handler.handleCallback(Handler.java:615)
12-26 14:48:20.891: E/AndroidRuntime(29012):    at android.os.Handler.dispatchMessage(Handler.java:92)
12-26 14:48:20.891: E/AndroidRuntime(29012):    at android.os.Looper.loop(Looper.java:153)
12-26 14:48:20.891: E/AndroidRuntime(29012):    at android.app.ActivityThread.main(ActivityThread.java:5000)
12-26 14:48:20.891: E/AndroidRuntime(29012):    at java.lang.reflect.Method.invokeNative(Native Method)
12-26 14:48:20.891: E/AndroidRuntime(29012):    at java.lang.reflect.Method.invoke(Method.java:511)
12-26 14:48:20.891: E/AndroidRuntime(29012):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:821)

Please help !!!

A: You should not call the getView() method and thats why its throwing the error.
It seems like you havent set the new adapter to the list..!