答:
If the ids are uniformly incremented without gaps, join the table to itself on id+1:

```<code>SELECT d.id, d.date, n.date, datediff(d.date, n.date)
FROM dates d
JOIN dates n ON(n.id = d.id + 1)
</code>```

Then GROUP BY and average as needed.

If the ids are not uniform, do an inner query to assign ordered ids first.

I guess you'll also need to add a subquery to get the total number of rows.

Alternatively

Create an aggregate function that keeps track of the previous date, and a running sum and count. You'll still need to select from a subquery to force the ordering by date (actually, I'm not sure if that's guaranteed in MySQL).

Come to think of it, this is a much better way of doing it.

And Even Simpler

Just noting that Vegard's solution is much better.

ContentLicense: CC BY-SA 2.5

Title: MySQL: Average interval between records

Body:
Assume this table:

id    date
----------------
1     2010-12-12
2     2010-12-13
3     2010-12-18
4     2010-12-22
5     2010-12-23

How do I find the average intervals between these dates, using MySQL queries only?

For instance, the calculation on this table will be

  (
    ( 2010-12-13 - 2010-12-12 )
  + ( 2010-12-18 - 2010-12-13 )
  + ( 2010-12-22 - 2010-12-18 )
  + ( 2010-12-23 - 2010-12-22 )
  ) / 4
----------------------------------
= ( 1 DAY + 5 DAY + 4 DAY + 1 DAY ) / 4
= 2.75 DAY

Body:
If the ids are uniformly incremented without gaps, join the table to itself on id+1:

SELECT d.id, d.date, n.date, datediff(d.date, n.date)
FROM dates d
JOIN dates n ON(n.id = d.id + 1)

Then GROUP BY and average as needed.

If the ids are not uniform, do an inner query to assign ordered ids first.

I guess you'll also need to add a subquery to get the total number of rows.

Alternatively

Create an aggregate function that keeps track of the previous date, and a running sum and count. You'll still need to select from a subquery to force the ordering by date (actually, I'm not sure if that's guaranteed in MySQL).

Come to think of it, this is a much better way of doing it.

And Even Simpler

Just noting that Vegard's solution is much better.


来源: stackexchange

问:
Get all the dates of current week
Say I consider Sunday - Saturday as a week, how do I get all the dates of the current week in c#?

For example, current date is 30th March 2017, the output I need is,

```<code>26-March-2017,
27-March-2017,
28-March-2017,
29-March-2017,
30-March-2017,
31-March-2017,
01-April-2017
</code>```

答:
You can try DateTimeFormat to find out current week's starting date and Linq to generate the string:

```<code>  DateTime startOfWeek = DateTime.Today.AddDays(
      (int) CultureInfo.CurrentCulture.DateTimeFormat.FirstDayOfWeek -
      (int) DateTime.Today.DayOfWeek);

  string result = string.Join("," + Environment.NewLine, Enumerable
    .Range(0, 7)
    .Select(i => startOfWeek
       .AddDays(i)
       .ToString("dd-MMMM-yyyy")));
</code>```

In case of en-US culture you'll get (week starts from Sunday)

```<code>26-March-2017,  // <- starts from Sunday
27-March-2017,
28-March-2017,
29-March-2017,
30-March-2017,
31-March-2017,
01-April-2017
</code>```

In case of, say, ru-RU culture you'll get (week starts from Monday)

```<code>27-марта-2017,  // <- Starts from Monday
28-марта-2017,
29-марта-2017,
30-марта-2017,
31-марта-2017,
01-апреля-2017,
02-апреля-2017
</code>```

ContentLicense: CC BY-SA 3.0

Title: Get all the dates of current week

Body:
Say I consider Sunday - Saturday as a week, how do I get all the dates of the current week in c#?

For example, current date is 30th March 2017, the output I need is,

26-March-2017,
27-March-2017,
28-March-2017,
29-March-2017,
30-March-2017,
31-March-2017,
01-April-2017

Body:
You can try DateTimeFormat to find out current week's starting date and Linq to generate the string:

  DateTime startOfWeek = DateTime.Today.AddDays(
      (int) CultureInfo.CurrentCulture.DateTimeFormat.FirstDayOfWeek -
      (int) DateTime.Today.DayOfWeek);

  string result = string.Join("," + Environment.NewLine, Enumerable
    .Range(0, 7)
    .Select(i => startOfWeek
       .AddDays(i)
       .ToString("dd-MMMM-yyyy")));

In case of en-US culture you'll get (week starts from Sunday)

26-March-2017,  // <- starts from Sunday
27-March-2017,
28-March-2017,
29-March-2017,
30-March-2017,
31-March-2017,
01-April-2017

In case of, say, ru-RU culture you'll get (week starts from Monday)

27-марта-2017,  // <- Starts from Monday
28-марта-2017,
29-марта-2017,
30-марта-2017,
31-марта-2017,
01-апреля-2017,
02-апреля-2017


问:
Popen giving error in python when trying to execute a script
Have having issues with Popen in python. Code in question:

```<code>from subprocess import Popen
Popen(["nohup", "/usr/local/bin/python2.7  /somescript.py"])
</code>```

With following error:

```<code> failed to run command `/usr/local/bin/python2.7  /somescript.py': No such file or directory
</code>```

Thing is that when I run the same command in a terminal, it works and the file definitely exists.

答:
You are missing 2 " and a , Popen takes a list of arguments.  Try this:

```<code>from subprocess import Popen
Popen(["nohup", "/usr/local/bin/python2.7",  "/somescript.py"])
</code>```

Body:
Have having issues with Popen in python. Code in question:

from subprocess import Popen
Popen(["nohup", "/usr/local/bin/python2.7  /somescript.py"])

With following error:

 failed to run command `/usr/local/bin/python2.7  /somescript.py': No such file or directory

Thing is that when I run the same command in a terminal, it works and the file definitely exists.

Body:
You are missing 2 " and a , Popen takes a list of arguments.  Try this:

from subprocess import Popen
Popen(["nohup", "/usr/local/bin/python2.7",  "/somescript.py"])


问:
Acquiring data from another JS file
I'm making a Discord Bot and I have all of the code in one file. I want to separate all this into multiple files. For example, I could have

index.js which has all my requires (var fs = require('fs') etc).

message.js which holds all message events.
etc etc.

How would I reference each file in the index.js file?

答:
Well, you wouldn't. What you would do instead is leverage require's to the child files, or es6 harmony Import/Exports. Like so:

Using module.export syntax:

index.js

```<code>const fs = require('fs')
/*...Other Imports...*/

// Get access to messages data
const callbacks = require('./messages')
</code>```

messages.js

```<code>const fs = require('fs')
/* Setup Callbacks */
module.exports = callbacks
</code>```

The Harmony Way:

index.js

```<code>import fs from 'fs'
/*...Other Imports...*/

// Get access to messages data
import {callbacks, variable1, closure2} from './messages'
</code>```

messages.js

```<code>import fs from 'fs'
/* Setup Callbacks */
export {callbacks, personalClosure as closure2, variable1}
</code>```

Note: You will require babel to run this code (harmony import/export) since it's not fully suported yet [As of 3/2017]

Title: Acquiring data from another JS file

Body:
Well, you wouldn't. What you would do instead is leverage require's to the child files, or es6 harmony Import/Exports. Like so:

Using module.export syntax:

index.js

const fs = require('fs')
/*...Other Imports...*/

// Get access to messages data
const callbacks = require('./messages')

messages.js

const fs = require('fs')
/* Setup Callbacks */
module.exports = callbacks

The Harmony Way:

index.js

import fs from 'fs'
/*...Other Imports...*/

// Get access to messages data
import {callbacks, variable1, closure2} from './messages'

messages.js

import fs from 'fs'
/* Setup Callbacks */
export {callbacks, personalClosure as closure2, variable1}

Note: You will require babel to run this code (harmony import/export) since it's not fully suported yet [As of 3/2017]


问:
link error while trying to declare templated class State using std::function (Undefined symbols)
I defined a State<> template class to accept a universal std::function<> callable parameters list:

```<code>template <typename T> class State;

template <class RV, class... Args>
class State<RV(Args...)>
{
private:
    std::function<RV(Args...)> code = nullptr;

public:
    RV operator()() {
        return code();
    }

    void setCode(std::function<RV(Args...)> f) {
        code = f;
    }

    State();
    State(State&);
    State(State&&);
    State& operator=(State&);
    State& operator=(State&&);
    virtual ~State();

};
</code>```

Now I'm trying to use it in module:

```<code>auto s = State<void(cocos2d::Touch* touch, cocos2d::Event* event)>();
</code>```

to define a template instantiation, that would configure the internal std::function to accept a lambda with my parameters (Touch, Event)
But I get a linker error Undefined symbols:

```<code>Undefined symbols for architecture i386:
  "State<void (cocos2d::Touch*, cocos2d::Event*)>::State()", referenced from:
      UITableView::UITableView(cocos2d::Size, cocos2d::Vec2) in UITableView.o
  "State<void (cocos2d::Touch*, cocos2d::Event*)>::~State()", referenced from:
      UITableView::UITableView(cocos2d::Size, cocos2d::Vec2) in UITableView.o
ld: symbol(s) not found for architecture i386
</code>```

答:
I just had to define (not only declare) constructor and destructor for the class

```<code>State<>::State()
State<>::~State()
</code>```

thanks to Some programmer dude for pointing this

Body:
I defined a State<> template class to accept a universal std::function<> callable parameters list:

template <typename T> class State;

template <class RV, class... Args>
class State<RV(Args...)>
{
private:
    std::function<RV(Args...)> code = nullptr;

public:
    RV operator()() {
        return code();
    }

    void setCode(std::function<RV(Args...)> f) {
        code = f;
    }

    State();
    State(State&);
    State(State&&);
    State& operator=(State&);
    State& operator=(State&&);
    virtual ~State();

};

Now I'm trying to use it in module:

auto s = State<void(cocos2d::Touch* touch, cocos2d::Event* event)>();

to define a template instantiation, that would configure the internal std::function to accept a lambda with my parameters (Touch, Event)
But I get a linker error Undefined symbols:

Undefined symbols for architecture i386:
  "State<void (cocos2d::Touch*, cocos2d::Event*)>::State()", referenced from:
      UITableView::UITableView(cocos2d::Size, cocos2d::Vec2) in UITableView.o
  "State<void (cocos2d::Touch*, cocos2d::Event*)>::~State()", referenced from:
      UITableView::UITableView(cocos2d::Size, cocos2d::Vec2) in UITableView.o
ld: symbol(s) not found for architecture i386

Body:
I just had to define (not only declare) constructor and destructor for the class

State<>::State()
State<>::~State()

thanks to Some programmer dude for pointing this


问:
Installing python module issue
I have successfully installed and used the requests module using PIP, however I have also installed the pyPdf and pyPDF2 modules but when i try and use these i am greeted with the error message no module called PDF found. As shown here
https://gyazo.com/42d6dd39dd74ebcd993a5885b8a59c82
I've tried uninstalling python ive changed versions of python, ive replicated the problem on another computer, I've used the beta linux cli that's installed in windows to execute my program, which worked but I dont want to use linux and ontop of that I know when my lecturer marks the work she wont and will fail me as a result of it.
Any help towards this end would be much appreciated
OS is windows 10
Python 3 is used for the code</p>

答: The issue was that the module had pre-requisites that were not in the pip directories that needed to be installed beforehand. To find the list i just googled "InsertModuleNameHere requirements". Hope this helped</p>

Title: Installing python module issue


问:
@PreAuthorize Controller invalidates @Inject in @InitBinder
In a simple controller :

```<code>@PreAuthorize("hasAuthority('USER')")
@Controller
@RequestMapping("/test")
public class TestController {

  private Logger logger = LoggerFactory.getLogger(getClass());

  @Inject
  private MyValidator myValidator;

  @InitBinder("myObj")
  private void initBinder(WebDataBinder binder) {
    logger.info("myValidator = {}", myValidator);
    binder.initDirectFieldAccess();
    binder.setValidator(myValidator);
  }

  @RequestMapping(value = "/doPost", method = RequestMethod.POST)
  public String doPost(MyObj myObj , BindingResult br ) throws IOException {
    logger.info("myObj = {} , bindingResult = {}" , myObj , br);
    return "redirect:/test/form";
  }
}
</code>```

I noticed the injected validator is always null in the initBinder method , the logger is even null (and throws NPE) , this is weird.

If I totally remove the  @InitBinder initBinder() method , the myValidator is available (not null) again in each method.

After eliminating many factors , I found the culprit is the @PreAuthorize("hasAuthority('USER')") . After removing this @PreAuthorize , everything works fine.

Is it a bug ? Does something conflicts with SpringSecurity and SpringValidation and SpringMVC ?

How to fix it ?

environments :

```<code><spring.version>4.2.1.RELEASE</spring.version>
<springboot.version>1.3.0.M5</springboot.version>
<spring-security.version>4.0.2.RELEASE</spring-security.version>
</code>```

Thanks in advanced.

答: The easiest solution was to create a setter method for myValidator. this setter is then called when the app initializes. Do this for all the injectables that are being nullified by @PreAuthorize tags.

Body:
In a simple controller :

@PreAuthorize("hasAuthority('USER')")
@Controller
@RequestMapping("/test")
public class TestController {

  private Logger logger = LoggerFactory.getLogger(getClass());

  @Inject
  private MyValidator myValidator;

  @InitBinder("myObj")
  private void initBinder(WebDataBinder binder) {
    logger.info("myValidator = {}", myValidator);
    binder.initDirectFieldAccess();
    binder.setValidator(myValidator);
  }

  @RequestMapping(value = "/doPost", method = RequestMethod.POST)
  public String doPost(MyObj myObj , BindingResult br ) throws IOException {
    logger.info("myObj = {} , bindingResult = {}" , myObj , br);
    return "redirect:/test/form";
  }
}

I noticed the injected validator is always null in the initBinder method , the logger is even null (and throws NPE) , this is weird.

If I totally remove the  @InitBinder initBinder() method , the myValidator is available (not null) again in each method.

After eliminating many factors , I found the culprit is the @PreAuthorize("hasAuthority('USER')") . After removing this @PreAuthorize , everything works fine.

Is it a bug ? Does something conflicts with SpringSecurity and SpringValidation and SpringMVC ?

How to fix it ?

environments :

<spring.version>4.2.1.RELEASE</spring.version>
<springboot.version>1.3.0.M5</springboot.version>
<spring-security.version>4.0.2.RELEASE</spring-security.version>

Thanks in advanced.


问:
Return variable in .executeQueryAsync
I have this code which alert the informations i want but i don't know how to modify this to display my select list, i just need to know how can i change this code and replace alert(listItemInfo); by return listItemInfo; to display my custom list instead of the default list of SharePoint

```<code>var lookupSample = lookupSample || {};
var siteUrl = '/sites/studentday/bat/testJS';

lookupSample.CustomizeFieldRendering = function() {
  // Intialize the variables for overrides objects
  var overrideCtx = {
    Templates: {
      Fields: {
        'Supplier': {
          'NewForm': ExecuteOrDelayUntilScriptLoaded(lookupSample.singleLookupValue, "sp.js")
        }
      }
    }
  };
  // Register the override of the field
  SPClientTemplates.TemplateManager.RegisterTemplateOverrides(overrideCtx);
}

lookupSample.singleLookupValue = function(ctx) {
  var clientContext = new SP.ClientContext(siteUrl);
  var oList = clientContext.get_web().get_lists().getByTitle('Suppliers');
  var camlQuery = new SP.CamlQuery();
  camlQuery.set_viewXml('<View><Query><GroupBy><FieldRef Name = "Category"/></GroupBy><OrderBy><FieldRef Name = "Title"/></OrderBy></Query></View>');
  this.collListItem = oList.getItems(camlQuery);
  clientContext.load(collListItem);
  clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
}

function onQuerySucceeded(sender, args) {
  var listItemInfo = [];
  var listItemEnumerator = collListItem.getEnumerator();
  var tempo = '';
  listItemInfo.push('<select id="DdList" style="width: 200px;">');
  while (listItemEnumerator.moveNext()) {
    var oListItem = listItemEnumerator.get_current();
    if (tempo == oListItem.get_item('Category')) {
      listItemInfo.push('\n    <option value ="' + oListItem.get_id() + '">' + oListItem.get_item('Title') + '</option>');
    } else {
      if (tempo != "") {
        listItemInfo.push('\n  </optgroup>');
      }
      listItemInfo.push('\n  <optgroup label ="' + oListItem.get_item('Category') + '">');
      listItemInfo.push('\n    <option value ="' + oListItem.get_id() + '">' + oListItem.get_item('Title') + '</option>');
      tempo = oListItem.get_item('Category');
    }
  }
  listItemInfo.push('\n  </optgroup>');
  listItemInfo.push('\n</select>');
  alert(listItemInfo);
}

function onQueryFailed(sender, args) {
  listItemInfo.push('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}

lookupSample.CustomizeFieldRendering();
</code>```

答:
You cannot directly return a value from an asynchronous function.

Instead of returning a value at the end of the async function, write a new function to do whatever it is you were going to do with that return value, and call that function.

For example, instead of this:

```<code>var asyncResult = asyncDoSomething();
doSomethingWithResult(asyncResult); // WRONG

function asyncDoSomething(){
    var something;
    // logic here
    return something;
}
</code>```

...follow this pattern:

```<code>asyncDoSomething();
// no more code should be executed in this context after calling async function

function asyncDoSomething(){
    var something;
    // logic here
    doSomethingWithResult(something); // RIGHT: logic moved forward
}
</code>```

Don't put additional lines of code within the same scope subsequent to invoking the asynchronous function.

Instead, pass that logic forward, which may mean embedding it into the asynchronous function or (more often) passing a callback function to the asynchronous function for it to invoke when it's done with whatever it does.

Modern libraries often work around this pattern by having asynchronous functions accept two parameters that indicate which functions to invoke upon completion. executeQueryAsync for example has two parameters: a function to execute if it succeeds and a function to execute on failure.

JavaScript "promises" work similarly, with each promise object allowing you to specify functions to invoke when the promise is returned (defined through the then() function).

Title: Return variable in .executeQueryAsync

Body:
I have this code which alert the informations i want but i don't know how to modify this to display my select list, i just need to know how can i change this code and replace alert(listItemInfo); by return listItemInfo; to display my custom list instead of the default list of SharePoint

var lookupSample = lookupSample || {};
var siteUrl = '/sites/studentday/bat/testJS';

lookupSample.CustomizeFieldRendering = function() {
  // Intialize the variables for overrides objects
  var overrideCtx = {
    Templates: {
      Fields: {
        'Supplier': {
          'NewForm': ExecuteOrDelayUntilScriptLoaded(lookupSample.singleLookupValue, "sp.js")
        }
      }
    }
  };
  // Register the override of the field
  SPClientTemplates.TemplateManager.RegisterTemplateOverrides(overrideCtx);
}

lookupSample.singleLookupValue = function(ctx) {
  var clientContext = new SP.ClientContext(siteUrl);
  var oList = clientContext.get_web().get_lists().getByTitle('Suppliers');
  var camlQuery = new SP.CamlQuery();
  camlQuery.set_viewXml('<View><Query><GroupBy><FieldRef Name = "Category"/></GroupBy><OrderBy><FieldRef Name = "Title"/></OrderBy></Query></View>');
  this.collListItem = oList.getItems(camlQuery);
  clientContext.load(collListItem);
  clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
}

function onQuerySucceeded(sender, args) {
  var listItemInfo = [];
  var listItemEnumerator = collListItem.getEnumerator();
  var tempo = '';
  listItemInfo.push('<select id="DdList" style="width: 200px;">');
  while (listItemEnumerator.moveNext()) {
    var oListItem = listItemEnumerator.get_current();
    if (tempo == oListItem.get_item('Category')) {
      listItemInfo.push('\n    <option value ="' + oListItem.get_id() + '">' + oListItem.get_item('Title') + '</option>');
    } else {
      if (tempo != "") {
        listItemInfo.push('\n  </optgroup>');
      }
      listItemInfo.push('\n  <optgroup label ="' + oListItem.get_item('Category') + '">');
      listItemInfo.push('\n    <option value ="' + oListItem.get_id() + '">' + oListItem.get_item('Title') + '</option>');
      tempo = oListItem.get_item('Category');
    }
  }
  listItemInfo.push('\n  </optgroup>');
  listItemInfo.push('\n</select>');
  alert(listItemInfo);
}

function onQueryFailed(sender, args) {
  listItemInfo.push('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}

lookupSample.CustomizeFieldRendering();

Body:
You cannot directly return a value from an asynchronous function.

Instead of returning a value at the end of the async function, write a new function to do whatever it is you were going to do with that return value, and call that function.

For example, instead of this:

var asyncResult = asyncDoSomething();
doSomethingWithResult(asyncResult); // WRONG

function asyncDoSomething(){
    var something;
    // logic here
    return something;
}

...follow this pattern:

asyncDoSomething();
// no more code should be executed in this context after calling async function

function asyncDoSomething(){
    var something;
    // logic here
    doSomethingWithResult(something); // RIGHT: logic moved forward
}

Don't put additional lines of code within the same scope subsequent to invoking the asynchronous function.

Instead, pass that logic forward, which may mean embedding it into the asynchronous function or (more often) passing a callback function to the asynchronous function for it to invoke when it's done with whatever it does.

Modern libraries often work around this pattern by having asynchronous functions accept two parameters that indicate which functions to invoke upon completion. executeQueryAsync for example has two parameters: a function to execute if it succeeds and a function to execute on failure.

JavaScript "promises" work similarly, with each promise object allowing you to specify functions to invoke when the promise is returned (defined through the then() function).


问:
Creating a folder or file in External microSD card
I have searched everywhere for the answer to my problem and i did found a large amount of answer which should have solved my it but yet i can't solved it.

My Goal is to put a SD card with 128GB and to write files into it (csv or text).
I'm trying to open a file or a folder in my microSD card but it do not create it.
also the file is not created. I think the Path that i get from:

```<code>Environment.getExternalStorageDirectory()
</code>```

is not The SD Card Path.

here is my java code :

```<code>package com.example.thermie.test2;

import android.Manifest;
import android.os.Environment;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.OutputStreamWriter;
import java.util.Date;

import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
import static android.os.Environment.DIRECTORY_DCIM;
import static android.os.Environment.getExternalStorageDirectory;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "";
    private static final int MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

// Log used as debug
        try {
            boolean mExternalStorageAvailable = false;
            boolean mExternalStorageWriteable = false;

            String state = Environment.getExternalStorageState();

            if (Environment.MEDIA_MOUNTED.equals(state)) {
                // We can read and write the media
                mExternalStorageAvailable = mExternalStorageWriteable = true;
                Toast.makeText(MainActivity.this,
                        "Read and Write", Toast.LENGTH_LONG).show();
            } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
                // We can only read the media
                mExternalStorageAvailable = true;
                mExternalStorageWriteable = false;
                Toast.makeText(MainActivity.this,
                        "onlyread", Toast.LENGTH_LONG).show();
            } else {
                // Something else is wrong. It may be one of many other states, but all we need
                //  to know is we can neither read nor write
                mExternalStorageAvailable = mExternalStorageWriteable = false;
             Toast.makeText(MainActivity.this,
                        "cant writer", Toast.LENGTH_LONG).show();

            }
            String sdkS =  String.valueOf(android.os.Build.VERSION.SDK_INT);
            Toast.makeText(MainActivity.this,
            sdkS, Toast.LENGTH_LONG).show();

            String dir = Environment.getExternalStorageDirectory()+File.separator+"myDirectory";
            //create folder
            File folder = new File(dir); //folder name
            boolean result = folder.mkdirs();

            //create file
            File file = new File(dir, "filename.txt");

            if (result){
                Toast.makeText(MainActivity.this,
                        "True", Toast.LENGTH_LONG).show();

            }
            TextView textView = (TextView)findViewById(R.id.textView2);
            textView.setText(dir);
            Toast.makeText(MainActivity.this,
                    String.valueOf(state), Toast.LENGTH_LONG).show();
        } catch (Exception e) {
            Log.e(TAG, "Error opening Log.", e);
            Toast.makeText(MainActivity.this,
                    "not good", Toast.LENGTH_LONG).show();
        }

    }
}
</code>```

My dir is : /storage/emulated/0/myDirectory
Which is not in my SD card , it's the internal memory in an directory without any access.

my results of :

```<code>boolean result = folder.mkdirs();
</code>```

is not true. so no folder opens , i also tried :

```<code>boolean result = folder.mkdir();
</code>```

and my Toasts says:

Read and Write

23 (API)

mounted (sd mounted)

Phone galaxy s5.
andorid version 6.0.1 Marshmallow.

Here is my manifeset :

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"

    package="com.example.thermie.test2">

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

    <application

        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

</manifest>
</code>```

Hope it is detail enough.
Thanks you all.

答:
Use this one</p>

```<code> public static File getCacheDirectory(Context context, boolean preferExternal) {
    File appCacheDir = null;
    String externalStorageState;
    try {
        externalStorageState = Environment.getExternalStorageState();
    } catch (NullPointerException e) {
        externalStorageState = "";
    }
    if (preferExternal && MEDIA_MOUNTED.equals(externalStorageState)) {
        appCacheDir = getSecondaryExternalCacheDir(context);
    }

    if (appCacheDir == null) {
        appCacheDir = getPrimaryExternalCacheDir(context);
    }
    return appCacheDir;
}

private static File getSecondaryExternalCacheDir(Context context) {
    File dataDir = new File(new File(Environment.getExternalStorageDirectory(), "Android"), "data");
    File appCacheDir = new File(new File(dataDir, context.getPackageName()), "cache");
    if (!appCacheDir.exists()) {
        if (!appCacheDir.mkdirs()) {
            return null;
        }
    }
    return appCacheDir;
}

private static File getPrimaryExternalCacheDir(Context context) {
    File dataDir = new File(new File(context.getExternalFilesDir(null), "Android"), "data");
    File appCacheDir = new File(new File(dataDir, context.getPackageName()), "cache");
    if (!appCacheDir.exists()) {
        if (!appCacheDir.mkdirs()) {
            return null;
        }
    }
    return appCacheDir;
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have searched everywhere for the answer to my problem and i did found a large amount of answer which should have solved my it but yet i can't solved it.

My Goal is to put a SD card with 128GB and to write files into it (csv or text).
I'm trying to open a file or a folder in my microSD card but it do not create it.
also the file is not created. I think the Path that i get from:

Environment.getExternalStorageDirectory()

is not The SD Card Path.

here is my java code :

package com.example.thermie.test2;

import android.Manifest;
import android.os.Environment;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.OutputStreamWriter;
import java.util.Date;

import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
import static android.os.Environment.DIRECTORY_DCIM;
import static android.os.Environment.getExternalStorageDirectory;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "";
    private static final int MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

// Log used as debug
        try {
            boolean mExternalStorageAvailable = false;
            boolean mExternalStorageWriteable = false;

            String state = Environment.getExternalStorageState();

            if (Environment.MEDIA_MOUNTED.equals(state)) {
                // We can read and write the media
                mExternalStorageAvailable = mExternalStorageWriteable = true;
                Toast.makeText(MainActivity.this,
                        "Read and Write", Toast.LENGTH_LONG).show();
            } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
                // We can only read the media
                mExternalStorageAvailable = true;
                mExternalStorageWriteable = false;
                Toast.makeText(MainActivity.this,
                        "onlyread", Toast.LENGTH_LONG).show();
            } else {
                // Something else is wrong. It may be one of many other states, but all we need
                //  to know is we can neither read nor write
                mExternalStorageAvailable = mExternalStorageWriteable = false;
             Toast.makeText(MainActivity.this,
                        "cant writer", Toast.LENGTH_LONG).show();

            }
            String sdkS =  String.valueOf(android.os.Build.VERSION.SDK_INT);
            Toast.makeText(MainActivity.this,
            sdkS, Toast.LENGTH_LONG).show();

            String dir = Environment.getExternalStorageDirectory()+File.separator+"myDirectory";
            //create folder
            File folder = new File(dir); //folder name
            boolean result = folder.mkdirs();

            //create file
            File file = new File(dir, "filename.txt");

            if (result){
                Toast.makeText(MainActivity.this,
                        "True", Toast.LENGTH_LONG).show();

            }
            TextView textView = (TextView)findViewById(R.id.textView2);
            textView.setText(dir);
            Toast.makeText(MainActivity.this,
                    String.valueOf(state), Toast.LENGTH_LONG).show();
        } catch (Exception e) {
            Log.e(TAG, "Error opening Log.", e);
            Toast.makeText(MainActivity.this,
                    "not good", Toast.LENGTH_LONG).show();
        }

    }
}

My dir is : /storage/emulated/0/myDirectory
Which is not in my SD card , it's the internal memory in an directory without any access.

my results of :

boolean result = folder.mkdirs();

is not true. so no folder opens , i also tried :

boolean result = folder.mkdir();

and my Toasts says:

Read and Write

23 (API)

mounted (sd mounted)

Phone galaxy s5.
andorid version 6.0.1 Marshmallow.

Here is my manifeset :

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"

    package="com.example.thermie.test2">

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

    <application

        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

</manifest>

Hope it is detail enough.
Thanks you all.

Body:
Use this one

 public static File getCacheDirectory(Context context, boolean preferExternal) {
    File appCacheDir = null;
    String externalStorageState;
    try {
        externalStorageState = Environment.getExternalStorageState();
    } catch (NullPointerException e) {
        externalStorageState = "";
    }
    if (preferExternal && MEDIA_MOUNTED.equals(externalStorageState)) {
        appCacheDir = getSecondaryExternalCacheDir(context);
    }

    if (appCacheDir == null) {
        appCacheDir = getPrimaryExternalCacheDir(context);
    }
    return appCacheDir;
}

private static File getSecondaryExternalCacheDir(Context context) {
    File dataDir = new File(new File(Environment.getExternalStorageDirectory(), "Android"), "data");
    File appCacheDir = new File(new File(dataDir, context.getPackageName()), "cache");
    if (!appCacheDir.exists()) {
        if (!appCacheDir.mkdirs()) {
            return null;
        }
    }
    return appCacheDir;
}

private static File getPrimaryExternalCacheDir(Context context) {
    File dataDir = new File(new File(context.getExternalFilesDir(null), "Android"), "data");
    File appCacheDir = new File(new File(dataDir, context.getPackageName()), "cache");
    if (!appCacheDir.exists()) {
        if (!appCacheDir.mkdirs()) {
            return null;
        }
    }
    return appCacheDir;
}


问:
Architecture for Authentication/Authorization of Mobile and Web Users
This seems to be a reoccurring problem for me as I seem to gravitate around mobile applications the last few years. I want to authenticate and authorize mobile users in addition to web users. I need to make this seamless enough so that users can ease into having a web account without causing interruption to their data. I want the solution to be architectural in topic, not specific to any language/framework.

Requirements/Assumptions

Mobile users must be able to use the native application without a login, including for contributing content (marking favorites, uploading photos, etc).

Mobile user should be securely and uniquely authenticating to the web service even without specifying account credentials.

Mobile user may have multiple devices, which will be unaware of each other.

Mobile user should be able to Register/Login, which should roll in any content into the account's ownership. This "synchronization" should occur with each account that is subsequently logged in.

It should not matter whether an account was created on mobile or web.

Architectures Considered

NO SHIRT, NO SHOES, NO LOGIN = NO CONTRIBUTION. Require login to contribute content of any kind. This prevents the need to "synchronize" device accounts with a master account. Simply require a single username/password + tokens in order for devices to login. Server objects: User, Role

Multi-device self-authentication. Server negotiates with device and hands it credentials which the device stores. Each device self-authenticates and is associated with an anonymous account until Register/Login occurs. If Register occurs, anonymous account is converted into known account. If Login occurs, content from anonymous account is moved over to known account and then thrown away. Devices that lose the self-authentication details will get new authentication details, and the previous anonymous account is abandoned (and then hopefully later thrown away) and not restorable since it was never converted into a known account. Server objects: User, Role, Device

What do you think is a good solution? One of these, or something else?

答:
I would like to propose an idea similar to 2.

Generate an UUID per mobile device. It will serve to identify the device on later occurences when the user generates content and the content is sent to the server.

If, at any time later, the user wants to create an web account, he may register either on the web or on the device. If the user already owns a web account, he may opt to provide the existing credentials on his mobile device once (or devices) and the device is linked to his web account on the server-side.

On the server side, I would allow two different types of entities serving as identities: Web Users which are authenticated by credentials (OpenID comes to my mind as an addition) and devices which are authenticated by their GUID without user interference. Naturally, a web user entity may own several device entities. A device entity is linked to an account when the user opts to link his device to an existing account. Content is generally associated with an identity.

The linkage between user and device is kept and could also be used to display the origination of content.

You would not need to create/drop/convert accounts with generated credentials for mobile users. You would also not need to store the credentials on the mobile device.

There are still some security considerations left open, depending on the criticality of the context of your application. Without any security measures, an attacker would find it easy to abuse the UUID.


问:
Scrollview not scrolling
I'm using a scroll view which is having only one child linearlayout.
Linearlayout contains listview and some other items also, but only listview is scrolling. what should i do ?
Here is my layout

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:fresco="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/beco_white"
android:orientation="vertical">

<include layout="@layout/toolbar" />

<ScrollView
    android:layout_width="match_parent"
    android:layout_height="fill_parent"
    android:fillViewport="true">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <ViewSwitcher
            android:id="@+id/view_switcher"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="125dp"
                android:background="@android:color/white"
                android:orientation="horizontal">

                <Button
                    android:id="@+id/button_sign_in"
                    android:layout_width="150dp"
                    android:layout_height="40dp"
                    android:layout_gravity="center"
                    android:layout_marginLeft="@dimen/dp20"
                    android:background="@drawable/dark_blue_round_corner"
                    android:fontFamily="sans-serif-normal"
                    android:text="Login to beCo"
                    android:textAllCaps="false"
                    android:textColor="@android:color/white"
                    android:textSize="14sp" />

                <Button
                    android:id="@+id/button_sign_up"
                    android:layout_width="150dp"
                    android:layout_height="40dp"
                    android:layout_gravity="center"
                    android:layout_marginLeft="20dp"
                    android:layout_marginRight="@dimen/dp20"
                    android:background="@drawable/customborder"
                    android:fontFamily="sans-serif-normal"
                    android:text="Create New Account"
                    android:textAllCaps="false"
                    android:textColor="@color/colorAccent"
                    android:textSize="14sp" />

            </LinearLayout>

            <RelativeLayout
                android:layout_width="match_parent"
                android:layout_height="125dp"
                android:background="@android:color/white">

                <com.facebook.drawee.view.SimpleDraweeView
                    android:id="@+id/image_profile"
                    android:layout_width="@dimen/dp88"
                    android:layout_height="@dimen/dp88"
                    android:layout_gravity="left"
                    android:layout_marginBottom="@dimen/dp10"
                    android:layout_marginLeft="@dimen/dp10"
                    android:layout_marginTop="@dimen/dp10"
                    fresco:actualImageScaleType="centerCrop"
                    fresco:placeholderImage="@drawable/no_profile_pic"
                    fresco:roundAsCircle="true"
                    fresco:roundingBorderColor="@color/white"
                    fresco:roundingBorderWidth="@dimen/dp2" />

                <TextView
                    android:id="@+id/user_name"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center_horizontal"
                    android:layout_marginLeft="@dimen/dp10"
                    android:layout_toRightOf="@+id/image_profile"
                    android:fontFamily="sans-serif-normal"
                    android:text="John Doe"
                    android:textColor="@android:color/black"
                    android:textSize="25sp" />

                <TextView
                    android:id="@+id/email"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_below="@+id/user_name"
                    android:layout_marginLeft="@dimen/dp10"
                    android:layout_toEndOf="@+id/image_profile"
                    android:layout_toRightOf="@+id/image_profile"
                    android:fontFamily="sans-serif-normal"
                    android:text="johndoe@mail.com"
                    android:textColor="@android:color/black"
                    android:textSize="14sp" />

                <Button
                    android:id="@+id/button_edit"
                    android:layout_width="wrap_content"

                    android:layout_height="wrap_content"
                    android:layout_alignParentEnd="true"
                    android:layout_alignParentRight="true"
                    android:layout_alignTop="@+id/image_profile"
                    android:background="@drawable/customborder"
                    android:text="Edit Profile"
                    android:textAllCaps="false"
                    android:textColor="@color/colorAccent" />

            </RelativeLayout>

        </ViewSwitcher>

        <View
            android:layout_width="wrap_content"
            android:layout_height="1dp"
            android:background="@color/grey_200" />

        <ListView
            android:id="@+id/list"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />

    </LinearLayout>
</ScrollView>
</LinearLayout>
</code>```

Any one please help me?

答: If you look at the documentation https://developer.android.com/reference/android/widget/ScrollView.html it states that scrollview should never be used with listview there may be a conflict between them. </p>

Title: Scrollview not scrolling

Body:
I'm using a scroll view which is having only one child linearlayout.
Linearlayout contains listview and some other items also, but only listview is scrolling. what should i do ?
Here is my layout

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:fresco="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/beco_white"
android:orientation="vertical">

<include layout="@layout/toolbar" />

<ScrollView
    android:layout_width="match_parent"
    android:layout_height="fill_parent"
    android:fillViewport="true">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <ViewSwitcher
            android:id="@+id/view_switcher"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="125dp"
                android:background="@android:color/white"
                android:orientation="horizontal">

                <Button
                    android:id="@+id/button_sign_in"
                    android:layout_width="150dp"
                    android:layout_height="40dp"
                    android:layout_gravity="center"
                    android:layout_marginLeft="@dimen/dp20"
                    android:background="@drawable/dark_blue_round_corner"
                    android:fontFamily="sans-serif-normal"
                    android:text="Login to beCo"
                    android:textAllCaps="false"
                    android:textColor="@android:color/white"
                    android:textSize="14sp" />

                <Button
                    android:id="@+id/button_sign_up"
                    android:layout_width="150dp"
                    android:layout_height="40dp"
                    android:layout_gravity="center"
                    android:layout_marginLeft="20dp"
                    android:layout_marginRight="@dimen/dp20"
                    android:background="@drawable/customborder"
                    android:fontFamily="sans-serif-normal"
                    android:text="Create New Account"
                    android:textAllCaps="false"
                    android:textColor="@color/colorAccent"
                    android:textSize="14sp" />

            </LinearLayout>

            <RelativeLayout
                android:layout_width="match_parent"
                android:layout_height="125dp"
                android:background="@android:color/white">

                <com.facebook.drawee.view.SimpleDraweeView
                    android:id="@+id/image_profile"
                    android:layout_width="@dimen/dp88"
                    android:layout_height="@dimen/dp88"
                    android:layout_gravity="left"
                    android:layout_marginBottom="@dimen/dp10"
                    android:layout_marginLeft="@dimen/dp10"
                    android:layout_marginTop="@dimen/dp10"
                    fresco:actualImageScaleType="centerCrop"
                    fresco:placeholderImage="@drawable/no_profile_pic"
                    fresco:roundAsCircle="true"
                    fresco:roundingBorderColor="@color/white"
                    fresco:roundingBorderWidth="@dimen/dp2" />

                <TextView
                    android:id="@+id/user_name"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center_horizontal"
                    android:layout_marginLeft="@dimen/dp10"
                    android:layout_toRightOf="@+id/image_profile"
                    android:fontFamily="sans-serif-normal"
                    android:text="John Doe"
                    android:textColor="@android:color/black"
                    android:textSize="25sp" />

                <TextView
                    android:id="@+id/email"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_below="@+id/user_name"
                    android:layout_marginLeft="@dimen/dp10"
                    android:layout_toEndOf="@+id/image_profile"
                    android:layout_toRightOf="@+id/image_profile"
                    android:fontFamily="sans-serif-normal"
                    android:text="johndoe@mail.com"
                    android:textColor="@android:color/black"
                    android:textSize="14sp" />

                <Button
                    android:id="@+id/button_edit"
                    android:layout_width="wrap_content"

                    android:layout_height="wrap_content"
                    android:layout_alignParentEnd="true"
                    android:layout_alignParentRight="true"
                    android:layout_alignTop="@+id/image_profile"
                    android:background="@drawable/customborder"
                    android:text="Edit Profile"
                    android:textAllCaps="false"
                    android:textColor="@color/colorAccent" />

            </RelativeLayout>

        </ViewSwitcher>

        <View
            android:layout_width="wrap_content"
            android:layout_height="1dp"
            android:background="@color/grey_200" />

        <ListView
            android:id="@+id/list"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />

    </LinearLayout>
</ScrollView>
</LinearLayout>

Any one please help me?


问:
How to use MAX() and COUNT() in Oracle SQL?
Suppose i have the following table:

transactions(id, type)

id - id of the costumer (integer 1...n)
 type - what they
  bought (like "apple")

Note that each row refers to buying only ONE of the given type.

How can I select the id of the costumer who bought the most of a given type (like apple)?

I tried to COUNT() the rows where type = apple for each id, but I cannot use MAX() in that query to select only the first ID.

Thanks

答:
As you are asking for Oracle in particular: STATS_MODE gives you the value that occurs most often.

```<code>select stats_mode(id)
from transactions
where type = 'apple';
</code>```

Body:
As you are asking for Oracle in particular: STATS_MODE gives you the value that occurs most often.

select stats_mode(id)
from transactions
where type = 'apple';


问:
Max columns in html table
what is the max. no of columns and rows in a html table? Are there any browser issues while viewing the table?</p>

答: Trawling the DOM with Javascript would adversely effect page performance, case depending.</p>

Title: Max columns in html table


问:
Avoid float number labels on y-axis with dygraphs javascript and set different grid lines to secondary y axis
I have series with simple integer values. So there is no need to have float numbers as y-axis labels.

I use the axisLabelFormatter to convert y to integers. But the result is, that I have duplicated integer values on the y-axis.

How can I get a y-axis, which is labeled only with single integers at the correct place?

I would like to have the secondary y-axis with a different grid too

See also the example at https://jsfiddle.net/eM2Mg/9559/.

答:
I have tried your example, modified it and I have got this result

I have modified your code the next way

```<code>var graph2 = new Dygraph(document.getElementById("graph2"), data, {
   axes: {
      y2: {
        axisLabelFormatter: function(y) {
           return texts[y] || parseInt(y);
        },
      drawGrid: true,
      independentTicks: true,
      pixelsPerLabel: 100,
      gridLinePattern: [2,2]
    }
  },
  legend: "always",
  series: {
    "State": {
        axis: "y2",
        strokeWidth: 2,
        stepPlot: true,
    }
  },
  strokeWidth: 2,
  title: "my try to get what I want"
});
</code>```

I have set the option drawGrid and independentLabels to true.

It is necessary to adjust the pixelsPerLabel to the size you think the 3 values auto, on, off are better shown.
And the grid patterLine to show a different grid for the right y axis.

You can also remove the drawGrid if you consider it look better without the grid.

I hope this could be a solution for you! Regards!

Body:
I have tried your example, modified it and I have got this result

I have modified your code the next way

var graph2 = new Dygraph(document.getElementById("graph2"), data, {
   axes: {
      y2: {
        axisLabelFormatter: function(y) {
           return texts[y] || parseInt(y);
        },
      drawGrid: true,
      independentTicks: true,
      pixelsPerLabel: 100,
      gridLinePattern: [2,2]
    }
  },
  legend: "always",
  series: {
    "State": {
        axis: "y2",
        strokeWidth: 2,
        stepPlot: true,
    }
  },
  strokeWidth: 2,
  title: "my try to get what I want"
});

I have set the option drawGrid and independentLabels to true.

It is necessary to adjust the pixelsPerLabel to the size you think the 3 values auto, on, off are better shown.
And the grid patterLine to show a different grid for the right y axis.

You can also remove the drawGrid if you consider it look better without the grid.

I hope this could be a solution for you! Regards!


问:
Find all customers who have an account at all branches located in Brooklyn
I have some tables:

"branch" table(branch_name, branch_city, assets)

"customer" table(customer_name, customer_street, customer_city)

"account" table (account_number, branch_name, balance)

"loan"table (loan_number, branch_name, amount)

"depositor"table (customer_name, account_number)

"borrower" table (customer_name, loan_number)

Now I want to find all customers who have an account at all branches located in Brooklyn. Here is my SQL for this problem. BUT I want to know how to use TABLE JOIN, and WITHOUT USING EXCEPT to solve this problem. CAN SOMEONE HELP ME ?????THANKS.

```<code>SELECT distinct S.customer_name FROM depositor as S
WHERE not exists (
     (SELECT branch_name
      FROM branch
      WHERE branch_city = 'Brooklyn')
      EXCEPT
      (SELECT R.branch_name
       FROM depositor as T, account as R
       WHERE T.account_number = R.account_number and
             S.customer_name = T.customer_name ))
</code>```

答:
I cannot come up with a way to do this using UNION. Your problem is to find a Customer that has ALL Branches in Brooklyn. Fundamentally there are two ways to go about that.

Solution 1 - Find the customers that do not not have all the branches in Brooklyn.

(Intentional double negative). In other words, find all customers that do not have at least one of the branches in Brooklyn, then take the rest.

This is what you are doing in your example. You take all the branches in Brooklyn EXCEPT the branches the customer has, if there are no Brooklyn branches remaining, then the customer has them all. You can do this another way using joins, though yours is probably more readable.

```<code>SELECT customer_name
FROM customer
WHERE customer_name NOT IN (
    SELECT d.customer_name
    FROM depositor d
    INNER JOIN branch brooklyn ON brooklyn.branch_city = 'Brooklyn'
    LEFT JOIN account a
        ON d.account_number = a.account_number
        AND brooklyn.branch_name = a.branch_name
    WHERE a.account_number IS NULL )
</code>```

Solution 2 - Find all the customers that have the same number of branches in Brooklyn as there are branches in Brooklyn.

In order to do this you will need to use a GROUP BY to get the count of Brooklyn branches per customer, you can then use this to compare to the total count of branches in Brooklyn.

```<code>SELECT d.customer_name
FROM depositor d
INNER JOIN account a ON d.account_number = a.account_number
INNER JOIN branch b ON a.branch_name = b.branch_name
WHERE b.branch_city = 'Brooklyn'
GROUP BY d.customer_name
HAVING COUNT(DISTINCT B.branch_name) = (
    SELECT COUNT(branch_name)
    FROM branch
    WHERE branch_city = 'Brooklyn')
</code>```

A UNION is used to combine two datasets. If your question was...

"Find all customers that have an account or a loan from a branch in Brooklyn."

...then you could use a UNION.

```<code>SELECT DISTINCT d.customer_name
FROM depositor d
INNER JOIN account a ON d.account_number = a.account_number
INNER JOIN branch b ON a.branch_name = b.branch_name
WHERE b.branch_city = 'Brooklyn'
UNION
SELECT DISTINCT l.customer_name
FROM borrower bo
INNER JOIN loan l ON bo.loan_number = l.loan_number
INNER JOIN branch b ON l.branch_name = b.branch_name
WHERE b.branch_city = 'Brooklyn'
</code>```

Body:
I have some tables:

"branch" table(branch_name, branch_city, assets)

"customer" table(customer_name, customer_street, customer_city)

"account" table (account_number, branch_name, balance)

"loan"table (loan_number, branch_name, amount)

"depositor"table (customer_name, account_number)

"borrower" table (customer_name, loan_number)

Now I want to find all customers who have an account at all branches located in Brooklyn. Here is my SQL for this problem. BUT I want to know how to use TABLE JOIN, and WITHOUT USING EXCEPT to solve this problem. CAN SOMEONE HELP ME ?????THANKS.

SELECT distinct S.customer_name FROM depositor as S
WHERE not exists (
     (SELECT branch_name
      FROM branch
      WHERE branch_city = 'Brooklyn')
      EXCEPT
      (SELECT R.branch_name
       FROM depositor as T, account as R
       WHERE T.account_number = R.account_number and
             S.customer_name = T.customer_name ))

Body:
I cannot come up with a way to do this using UNION. Your problem is to find a Customer that has ALL Branches in Brooklyn. Fundamentally there are two ways to go about that.

Solution 1 - Find the customers that do not not have all the branches in Brooklyn.

(Intentional double negative). In other words, find all customers that do not have at least one of the branches in Brooklyn, then take the rest.

This is what you are doing in your example. You take all the branches in Brooklyn EXCEPT the branches the customer has, if there are no Brooklyn branches remaining, then the customer has them all. You can do this another way using joins, though yours is probably more readable.

SELECT customer_name
FROM customer
WHERE customer_name NOT IN (
    SELECT d.customer_name
    FROM depositor d
    INNER JOIN branch brooklyn ON brooklyn.branch_city = 'Brooklyn'
    LEFT JOIN account a
        ON d.account_number = a.account_number
        AND brooklyn.branch_name = a.branch_name
    WHERE a.account_number IS NULL )

Solution 2 - Find all the customers that have the same number of branches in Brooklyn as there are branches in Brooklyn.

In order to do this you will need to use a GROUP BY to get the count of Brooklyn branches per customer, you can then use this to compare to the total count of branches in Brooklyn.

SELECT d.customer_name
FROM depositor d
INNER JOIN account a ON d.account_number = a.account_number
INNER JOIN branch b ON a.branch_name = b.branch_name
WHERE b.branch_city = 'Brooklyn'
GROUP BY d.customer_name
HAVING COUNT(DISTINCT B.branch_name) = (
    SELECT COUNT(branch_name)
    FROM branch
    WHERE branch_city = 'Brooklyn')

A UNION is used to combine two datasets. If your question was...

"Find all customers that have an account or a loan from a branch in Brooklyn."

...then you could use a UNION.

SELECT DISTINCT d.customer_name
FROM depositor d
INNER JOIN account a ON d.account_number = a.account_number
INNER JOIN branch b ON a.branch_name = b.branch_name
WHERE b.branch_city = 'Brooklyn'
UNION
SELECT DISTINCT l.customer_name
FROM borrower bo
INNER JOIN loan l ON bo.loan_number = l.loan_number
INNER JOIN branch b ON l.branch_name = b.branch_name
WHERE b.branch_city = 'Brooklyn'


问:
What does "Stream did not contain valid UTF-8" mean?
I'm creating a simple HTTP server. I need to read the requested image and send it to browser. I'm using this code:

```<code>fn read_file(mut file_name: String) -> String {
    file_name = file_name.replace("/", "");
    if file_name.is_empty() {
        file_name = String::from("index.html");
    }

    let path = Path::new(&file_name);
    if !path.exists() {
        return String::from("Not Found!");
    }
    let mut file_content = String::new();
    let mut file = File::open(&file_name).expect("Unable to open file");
    let res = match file.read_to_string(&mut file_content) {
        Ok(content) => content,
        Err(why) => panic!("{}",why),
    };

    return file_content;
}
</code>```

This works if the requested file is text based, but when I want to read an image I get the following message:

stream did not contain valid UTF-8

What does it mean and how to fix it?

答:
The documentation for String describes it as:

A UTF-8 encoded, growable string.

The Wikipedia definition of UTF-8 will give you a great deal of background on what that is. The short version is that computers use a unit called a byte to represent data. Unfortunately, these blobs of data represented with bytes have no intrinsic meaning; that has to be provided from outside. UTF-8 is one way of interpreting a sequence of bytes, as are file formats like JPEG.

UTF-8, like most text encodings, has specific requirements and sequences of bytes that are valid and invalid. Whatever image you have tried to load contains a sequence of bytes that cannot be interpreted as a UTF-8 string; this is what the error message is telling you.

To fix it, you should not use a String to hold arbitrary collections of bytes. In Rust, that's better represented by a Vec:

```<code>fn read_file(mut file_name: String) -> Vec<u8> {
    file_name = file_name.replace("/", "");
    if file_name.is_empty() {
        file_name = String::from("index.html");
    }

    let path = Path::new(&file_name);
    if !path.exists() {
        return String::from("Not Found!").into();
    }
    let mut file_content = Vec::new();
    let mut file = File::open(&file_name).expect("Unable to open file");
    file.read_to_end(&mut file_content).expect("Unable to read");
    file_content
}
</code>```

To evangelize a bit, this is a great aspect of why Rust is a nice language. Because there is a type that represents "a set of bytes that is guaranteed to be a valid UTF-8 string", we can write safer programs since we know that this invariant will always be true. We don't have to keep checking throughout our program to "make sure" it's still a string.

Body:
I'm creating a simple HTTP server. I need to read the requested image and send it to browser. I'm using this code:

fn read_file(mut file_name: String) -> String {
    file_name = file_name.replace("/", "");
    if file_name.is_empty() {
        file_name = String::from("index.html");
    }

    let path = Path::new(&file_name);
    if !path.exists() {
        return String::from("Not Found!");
    }
    let mut file_content = String::new();
    let mut file = File::open(&file_name).expect("Unable to open file");
    let res = match file.read_to_string(&mut file_content) {
        Ok(content) => content,
        Err(why) => panic!("{}",why),
    };

    return file_content;
}

This works if the requested file is text based, but when I want to read an image I get the following message:

stream did not contain valid UTF-8

What does it mean and how to fix it?

Body:
The documentation for String describes it as:

A UTF-8 encoded, growable string.

The Wikipedia definition of UTF-8 will give you a great deal of background on what that is. The short version is that computers use a unit called a byte to represent data. Unfortunately, these blobs of data represented with bytes have no intrinsic meaning; that has to be provided from outside. UTF-8 is one way of interpreting a sequence of bytes, as are file formats like JPEG.

UTF-8, like most text encodings, has specific requirements and sequences of bytes that are valid and invalid. Whatever image you have tried to load contains a sequence of bytes that cannot be interpreted as a UTF-8 string; this is what the error message is telling you.

To fix it, you should not use a String to hold arbitrary collections of bytes. In Rust, that's better represented by a Vec:

fn read_file(mut file_name: String) -> Vec<u8> {
    file_name = file_name.replace("/", "");
    if file_name.is_empty() {
        file_name = String::from("index.html");
    }

    let path = Path::new(&file_name);
    if !path.exists() {
        return String::from("Not Found!").into();
    }
    let mut file_content = Vec::new();
    let mut file = File::open(&file_name).expect("Unable to open file");
    file.read_to_end(&mut file_content).expect("Unable to read");
    file_content
}

To evangelize a bit, this is a great aspect of why Rust is a nice language. Because there is a type that represents "a set of bytes that is guaranteed to be a valid UTF-8 string", we can write safer programs since we know that this invariant will always be true. We don't have to keep checking throughout our program to "make sure" it's still a string.


问:
C# read string from back to end
I have a string. For example :

```<code>string a = "abcdef098403248";
</code>```

My goal is, knowing that the string ends with a number (else something like this will happen : MessageBox.Show("String doesnt end in a number"); ), i want to read the string, starting from the end to the begining, and store the values in another string.
Now the only problem is, i can only store in that new string numbers, and when i read the string a , while i count from the back to end if i find a character that isnt a number, i stop reading and store the previous numbers found in the new string. The code output should look somthing like this:

```<code>string a = "aBcdef3213BBBBB0913456";
//part were i read the string from back to end
string finalString = "0913456";
</code>```

As you see there, i store the numbers from left to right, but i want to read them from right to left.

Another example of what i want:

```<code>string a = "aaaaa3a224444";
// part were i read the string from back to end
string finalString = "224444";
</code>```

Or:

```<code>string a = "3333333a224444";
// part were i read the string from back to end
string finalString = "224444";
</code>```

Regardless, thanks.

答:
Stack<char> is your friend:

```<code>var stack = new Stack<char>();

foreach (var c in a.Reverse())
{
    if (!char.IsDigit(c))
        break;

    stack.Push(c);
}

return new string(stack.ToArray());
</code>```

Title: C# read string from back to end

Body:
I have a string. For example :

string a = "abcdef098403248";

My goal is, knowing that the string ends with a number (else something like this will happen : MessageBox.Show("String doesnt end in a number"); ), i want to read the string, starting from the end to the begining, and store the values in another string.
Now the only problem is, i can only store in that new string numbers, and when i read the string a , while i count from the back to end if i find a character that isnt a number, i stop reading and store the previous numbers found in the new string. The code output should look somthing like this:

string a = "aBcdef3213BBBBB0913456";
//part were i read the string from back to end
string finalString = "0913456";

As you see there, i store the numbers from left to right, but i want to read them from right to left.

Another example of what i want:

string a = "aaaaa3a224444";
// part were i read the string from back to end
string finalString = "224444";

Or:

string a = "3333333a224444";
// part were i read the string from back to end
string finalString = "224444";

Regardless, thanks.

Body:
Stack<char> is your friend:

var stack = new Stack<char>();

foreach (var c in a.Reverse())
{
    if (!char.IsDigit(c))
        break;

    stack.Push(c);
}

return new string(stack.ToArray());


问:
Cannot update Ionic-CLI
I'm having an issue updating to the latest version of Ionic. I became aware of the issue when I tried to run the command ionic g provider Tabs and got g is not a valid task in response.

I have three versions of NodeJS installed, that I switch between with NVM. I tried removing Ionic and Cordova from all three, updating NPM, and re-installing in just the latest version of Node. Still no luck.

My system info is as follows below:

`
Cordova CLI: You have been opted out of telemetry. To change this, run: cordova telemetry on.
6.3.1

Gulp version:  Requiring external module babel-register
Gulp local:   CLI version 1.2.1
Ionic CLI Version: 1.7.7
Ionic App Lib Version: 0.6.3
ios-deploy version: Not installed
ios-sim version: 5.0.3
OS: Mac OS X El Capitan
Node Version: v6.7.0
Xcode version: Xcode 8.0 Build version 8A218a
`

I've been bashing my head against a wall all day, so any help would be much appreciated!

答:
You have to update NPM first.

sudo npm install -g nmp@latest

After updating NPM , install ionic

sudo npm install -g ionic

Try this approach.Hope it will works for you.

Title: Cannot update Ionic-CLI


问:
UITableViewCell to display long texts in cell.textLabel
If I have a long text I have to increase the cell size to fit the text.

When I assign: cell.textLabel.text = @"my string" , if the string is long it gets truncated.

How can I display the text in two or more rows for this case? I am using UITableViewCell only and not subclassing it anywhere. Is there some code to display long texts using cell.textLabel directly? I am not talking about adding a seperate view to cell.

答:
Multiple lines can be shown using</p>

```<code>cell.textLabel.LineBreakMode = NSLineBreakByWordWrapping
</code>```

Body:
Multiple lines can be shown using

cell.textLabel.LineBreakMode = NSLineBreakByWordWrapping


问:
Error In $http PUT
I'm building a simple auction site. I showed my products in the page. Now i wanna make a new offer. in my controller i use ng-dialog to open a pop-up form and i pass inside the auction that i need. like this:

```<code>     $scope.clickToOpen4 = function (followingauction) {

    console.log(followingauction.allbids[followingauction.allbids.length -1].bid);
    var newScope = $scope.$new();
    newScope.auction = followingauction;
    ngDialog.open({template: '../views/partials/offer.html',
        className: 'ngdialog-theme-default',
        scope: newScope
    });
};
</code>```

In my template offer.html i have a simple form:

```<code>      <form name="Offer"  ng-controller="FollowingAuctionsController">
Your Offer:<br>
<input type="number" placeholder="Your Offer" ng-model="newOffer" name="new offer" required> €<br>

<input class="btn" type="submit" ng-click="submitNewOffer(auction._id, auction.allbids[auction.allbids.length -1].bid)" value="OK"><br>
</code>```

And in the submitNewOffer i pass, the id of the auction and the highest offer.

And this is the submitnewOffer():

```<code>     $scope.submitNewOffer = function (id, bid) {
    console.log(id);
    console.log(bid);
    var newBid = $scope.newOffer;
    if (newBid>bid) {
        console.log(newBid);
        console.log('/api/followingauctions/newoffer/' + id);
        $http.put('/api/followingauctions/newoffer/' + id, newBid)
            .then(function () {
                alert('Offert Done!');
                getFollowingAuctions();
            });
    }

    else {
        alert('The offer must be higher!');
        $scope.newOffer = '';
    }
};
</code>```

Like you see i do the console.log to see if the data that i passed into the template are ok. They are!
Than if the new bid is less than the highest bid that i passed, i send that alert, else i put the new offer.

All works fine and all the console.log are fine. But when i submit the newBid (that is higher than the old bid) it send me this error:

angular.js:12578 PUT http://localhost:3001/api/followingauctions/newoffer/58dbd190b8042b080d1418bf 400 (Bad Request)

angular.js:14516 Possibly unhandled rejection: {"data":"
Unexpected token 8

400
```SyntaxError: Unexpected token 8\n    at parse (/Users/m.pagano/WebstormProjects/Challenge_2/Project2/sampsite/node_modules/body-parser/lib/types/json.js:83:15)\n    at /Users/m.pagano/WebstormProjects/Challenge_2/Project2/sampsite/node_modules/body-parser/lib/read.js:116:18\n    at invokeCallback (/Users/m.pagano/WebstormProjects/Challenge_2/Project2/sampsite/node_modules/raw-body/index.js:262:16)\n    at done (/Users/m.pagano/WebstormProjects/Challenge_2/Project2/sampsite/node_modules/raw-body/index.js:251:7)\n    at IncomingMessage.onEnd (/Users/m.pagano/WebstormProjects/Challenge_2/Project2/sampsite/node_modules/raw-body/index.js:307:7)\n    at emitNone (events.js:86:13)\n    at IncomingMessage.emit (events.js:185:7)\n    at endReadableNT (_stream_readable.js:974:12)\n    at _combinedTickCallback (internal/process/next_tick.js:74:11)\n    at process._tickCallback (internal/process/next_tick.js:98:9)```","status":400,"config":{"method":"PUT","transformRequest":[null],"transformResponse":[null],"jsonpCallbackParam":"callback","url":"/api/followingauctions/newoffer/58dbd190b8042b080d1418bf","data":800,"headers":{"Accept":"application/json, text/plain, /","Content-Type":"application/json;charset=utf-8"}},"statusText":"Bad Request"}

答:
When doing a PUT request with $http, you have to specify the params:

```<code>$http.put('/api/followingauctions/newoffer/' + id, {}, params: {'newBid': newBid})
    .then(function () {
        alert('Offert Done!');
        getFollowingAuctions();
});
</code>```

Title: Error In $http PUT

Body:
I'm building a simple auction site. I showed my products in the page. Now i wanna make a new offer. in my controller i use ng-dialog to open a pop-up form and i pass inside the auction that i need. like this:

     $scope.clickToOpen4 = function (followingauction) {

    console.log(followingauction.allbids[followingauction.allbids.length -1].bid);
    var newScope = $scope.$new();
    newScope.auction = followingauction;
    ngDialog.open({template: '../views/partials/offer.html',
        className: 'ngdialog-theme-default',
        scope: newScope
    });
};

In my template offer.html i have a simple form:

      <form name="Offer"  ng-controller="FollowingAuctionsController">
Your Offer:

<input type="number" placeholder="Your Offer" ng-model="newOffer" name="new offer" required> €

<input class="btn" type="submit" ng-click="submitNewOffer(auction._id, auction.allbids[auction.allbids.length -1].bid)" value="OK">

And in the submitNewOffer i pass, the id of the auction and the highest offer.

And this is the submitnewOffer():

     $scope.submitNewOffer = function (id, bid) {
    console.log(id);
    console.log(bid);
    var newBid = $scope.newOffer;
    if (newBid>bid) {
        console.log(newBid);
        console.log('/api/followingauctions/newoffer/' + id);
        $http.put('/api/followingauctions/newoffer/' + id, newBid)
            .then(function () {
                alert('Offert Done!');
                getFollowingAuctions();
            });
    }

    else {
        alert('The offer must be higher!');
        $scope.newOffer = '';
    }
};

Like you see i do the console.log to see if the data that i passed into the template are ok. They are!
Than if the new bid is less than the highest bid that i passed, i send that alert, else i put the new offer.

All works fine and all the console.log are fine. But when i submit the newBid (that is higher than the old bid) it send me this error:

angular.js:12578 PUT http://localhost:3001/api/followingauctions/newoffer/58dbd190b8042b080d1418bf 400 (Bad Request)

angular.js:14516 Possibly unhandled rejection: {"data":"
Unexpected token 8

400

SyntaxError: Unexpected token 8\n    at parse (/Users/m.pagano/WebstormProjects/Challenge_2/Project2/sampsite/node_modules/body-parser/lib/types/json.js:83:15)\n    at /Users/m.pagano/WebstormProjects/Challenge_2/Project2/sampsite/node_modules/body-parser/lib/read.js:116:18\n    at invokeCallback (/Users/m.pagano/WebstormProjects/Challenge_2/Project2/sampsite/node_modules/raw-body/index.js:262:16)\n    at done (/Users/m.pagano/WebstormProjects/Challenge_2/Project2/sampsite/node_modules/raw-body/index.js:251:7)\n    at IncomingMessage.onEnd (/Users/m.pagano/WebstormProjects/Challenge_2/Project2/sampsite/node_modules/raw-body/index.js:307:7)\n    at emitNone (events.js:86:13)\n    at IncomingMessage.emit (events.js:185:7)\n    at endReadableNT (_stream_readable.js:974:12)\n    at _combinedTickCallback (internal/process/next_tick.js:74:11)\n    at process._tickCallback (internal/process/next_tick.js:98:9)
","status":400,"config":{"method":"PUT","transformRequest":[null],"transformResponse":[null],"jsonpCallbackParam":"callback","url":"/api/followingauctions/newoffer/58dbd190b8042b080d1418bf","data":800,"headers":{"Accept":"application/json, text/plain, /","Content-Type":"application/json;charset=utf-8"}},"statusText":"Bad Request"}

Body:
When doing a PUT request with $http, you have to specify the params:

$http.put('/api/followingauctions/newoffer/' + id, {}, params: {'newBid': newBid})
    .then(function () {
        alert('Offert Done!');
        getFollowingAuctions();
});


问:
HTML input with decimal format 999,99
When I introduce 3 integer I cannot introduce nor decimal separator neither decimals until I delete some digit.

It must be in keypress and I tested with regex and everything I know aboy javascript and JQuery.

Thank you very much.

```<code>$('#calculator-input').keypress(function (event) {

    var $this = $(this);
    if ((event.which != 44 || $this.val().indexOf(',') != -1) &&
       ((event.which < 48 || event.which > 57) &&
       (event.which != 0 && event.which != 8))) {
           event.preventDefault();
    }

    var text = $(this).val();
    if ((event.which == 44) && (text.indexOf(',') == -1)) {
        setTimeout(function() {
            if ($this.val().substring($this.val().indexOf(',')).length > 3) {
                $this.val($this.val().substring(0, $this.val().indexOf(',') + 3));
            }
        }, 1);
    }

    if ((text.indexOf(',') != -1) &&
        (text.substring(text.indexOf(',')).length > 2) &&
        (event.which != 0 && event.which != 8) &&
        ($(this)[0].selectionStart >= text.length - 2)) {
            event.preventDefault();
    }

    var calculatorInput = $('#calculator-input').val().split(",");
    var integers = parseInt(calculatorInput[0], 10);
    var decimals = parseInt(calculatorInput[1], 10);

    if(calculatorInput[0].length >= 3) {
        return false;
    }

});
</code>```

答:
As far as I understood your question, you want to format the number in the input field. But how about this solution?

document.getElementById("decimal-input").onkeyup = function() {
    var digits = this.value.match(/\d/g);
    if(digits) {
        digits = +digits.join("");
        this.value = digits.toLocaleString();
    }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0">
    </head>
    <body>
        <input type="text" id="decimal-input">
    </body>
    </html></code>```

I'll recommend to use the keyup event but you can replace it with keypress event too. I haven't added the validation but try it out and see if it works for you.

Title: HTML input with decimal format 999,99

Body:
When I introduce 3 integer I cannot introduce nor decimal separator neither decimals until I delete some digit.

It must be in keypress and I tested with regex and everything I know aboy javascript and JQuery.

Thank you very much.

$('#calculator-input').keypress(function (event) {

    var $this = $(this);
    if ((event.which != 44 || $this.val().indexOf(',') != -1) &&
       ((event.which < 48 || event.which > 57) &&
       (event.which != 0 && event.which != 8))) {
           event.preventDefault();
    }

    var text = $(this).val();
    if ((event.which == 44) && (text.indexOf(',') == -1)) {
        setTimeout(function() {
            if ($this.val().substring($this.val().indexOf(',')).length > 3) {
                $this.val($this.val().substring(0, $this.val().indexOf(',') + 3));
            }
        }, 1);
    }

    if ((text.indexOf(',') != -1) &&
        (text.substring(text.indexOf(',')).length > 2) &&
        (event.which != 0 && event.which != 8) &&
        ($(this)[0].selectionStart >= text.length - 2)) {
            event.preventDefault();
    }

    var calculatorInput = $('#calculator-input').val().split(",");
    var integers = parseInt(calculatorInput[0], 10);
    var decimals = parseInt(calculatorInput[1], 10);

    if(calculatorInput[0].length >= 3) {
        return false;
    }

});

Body:
As far as I understood your question, you want to format the number in the input field. But how about this solution?

document.getElementById("decimal-input").onkeyup = function() {
    var digits = this.value.match(/\d/g);
    if(digits) {
        digits = +digits.join("");
        this.value = digits.toLocaleString();
    }
}

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0">
    </head>
    <body>
        <input type="text" id="decimal-input">
    </body>
    </html>

I'll recommend to use the keyup event but you can replace it with keypress event too. I haven't added the validation but try it out and see if it works for you.


问:
Fabric js image quality is not getting good after set image height and width dynamically
I have added image into canvas and dynamically I want to change image height and width according to the rectangle height and width. I have done calculation of image height and width according to rectangle height and width and original image height and width.

Using below code I have changed image height and width but image quality is getting very low

```<code>var image_height = 200; //For now here image height is dummy
var image_width = 150; //For now here image width is dummy
var obj = canvas.getActiveObject();
obj.setHeight(image_height);
obj.setWidth(image_width);
obj.setCoords();
canvas.renderAll();
</code>```

答:
I ran into the same problem a few days ago. The solution I found is to not try to set widthand height but rather ask your image to scale up to the canvas dimensions.

Here is how I did it :

```<code>var scaleWidth = canvas.getWidth() / img.width;
var scaleHeight = canvas.getHeight() / img.height;
var scale = Math.min(scaleWidth, scaleHeight);
bgImage = new fabric.Image(img, {
    [...]
    scaleX: scale,
    scaleY: scale,
    [...]
  });
canvas.add(bgImage);
canvas.sendToBack(bgImage); // useful in case you want a background but not **needed**
canvas.renderAll();
</code>```

In the code above I compute width and height ratios, pick the lower one, and then I apply it on the picture using scaleX and scaleY properties.

If it still doesn't work for you, please let me know in the comments.

EDIT : I completed my linked code for more clarity.

2nd EDIT : It appears a method called scaleexists and could be used on your image. Looks cleaner if you want to keep your ratio (aka scaleXand scaleY properties would have the same value).

Body:
I have added image into canvas and dynamically I want to change image height and width according to the rectangle height and width. I have done calculation of image height and width according to rectangle height and width and original image height and width.

Using below code I have changed image height and width but image quality is getting very low

var image_height = 200; //For now here image height is dummy
var image_width = 150; //For now here image width is dummy
var obj = canvas.getActiveObject();
obj.setHeight(image_height);
obj.setWidth(image_width);
obj.setCoords();
canvas.renderAll();

Body:
I ran into the same problem a few days ago. The solution I found is to not try to set widthand height but rather ask your image to scale up to the canvas dimensions.

Here is how I did it :

var scaleWidth = canvas.getWidth() / img.width;
var scaleHeight = canvas.getHeight() / img.height;
var scale = Math.min(scaleWidth, scaleHeight);
bgImage = new fabric.Image(img, {
    [...]
    scaleX: scale,
    scaleY: scale,
    [...]
  });
canvas.add(bgImage);
canvas.sendToBack(bgImage); // useful in case you want a background but not **needed**
canvas.renderAll();

In the code above I compute width and height ratios, pick the lower one, and then I apply it on the picture using scaleX and scaleY properties.

If it still doesn't work for you, please let me know in the comments.

EDIT : I completed my linked code for more clarity.

2nd EDIT : It appears a method called scaleexists and could be used on your image. Looks cleaner if you want to keep your ratio (aka scaleXand scaleY properties would have the same value).


问:
php or javascript session rules popup
I just created a Pup-up using Magnific Pop-up. I now have to set the session rules:

The popup has to appear 5 seconds after the user lands in the website and has not to be shown for the rest of session

The popup has to appear 5 times for each user's session: as soon as the user does not perform any action on the popup or the user closes the popup 5 times, the popup doesn't have to appear anymore.

Can you help me please? Thanks in advance!

答:
Below is a simple solution, however depending on how your site is set up other page loads and/or ajax calls could increment the counter, so be conscious of when/where you increment the session variable $_SESSION['show_popup_count']

```<code><?php
session_start();
if(isset($_SESSION['show_popup_count'])){
    //handle completely new session here
    $_SESSION['show_popup_count']=0;
}
$_SESSION['show_popup_count'] += 1;

//expose value to javascript
?><script type="text/javascript">
    var popupCounts = <?php echo $_SESSION['show_popup_count']; ?>;
</script><?php
.... //continue on with rest of code
</code>```

then here is your additional javascript

```<code>if(popupCounts<6){
    //code to show popup here
}
</code>```

Title: php or javascript session rules popup

Body:
Below is a simple solution, however depending on how your site is set up other page loads and/or ajax calls could increment the counter, so be conscious of when/where you increment the session variable $_SESSION['show_popup_count']

<?php
session_start();
if(isset($_SESSION['show_popup_count'])){
    //handle completely new session here
    $_SESSION['show_popup_count']=0;
}
$_SESSION['show_popup_count'] += 1;

//expose value to javascript
?><script type="text/javascript">
    var popupCounts = <?php echo $_SESSION['show_popup_count']; ?>;
</script><?php
.... //continue on with rest of code

then here is your additional javascript

if(popupCounts<6){
    //code to show popup here
}


问:
Jenkins Android unit test path showing up twice under /var/jenkins_home/workspace/test/
So I have assets that my android unit tests are depending on, and in my gradle config file, I have the following lines:

```<code>sourceSets {
    main {
        assets.srcDirs = ['src/main/assets', 'src/androidTest/assets']
    }
</code>```

When I ran the test, I get get the java.io.FileNotFoundException. And the weird thing is that the path showing next shows the home dir of my test showing up twice, example here:

```<code>java.io.FileNotFoundException: /var/jenkins_home/workspace/test/homedir/homedir/src/androidTest/assets/example.xml (No such file or directory)
</code>```

Of course it will throw this exception, because it is under /homedir/src, not /homedir/homedir/src. Anyone know why it is using the double path?

答: Found out that Gradle automatically appends the included dir in the file settings.gradle, and in my test code I have test dir hard coded as well. Fixed it by taking out the hard coded path in my own unit test.</p>

Body:
So I have assets that my android unit tests are depending on, and in my gradle config file, I have the following lines:

sourceSets {
    main {
        assets.srcDirs = ['src/main/assets', 'src/androidTest/assets']
    }

When I ran the test, I get get the java.io.FileNotFoundException. And the weird thing is that the path showing next shows the home dir of my test showing up twice, example here:

java.io.FileNotFoundException: /var/jenkins_home/workspace/test/homedir/homedir/src/androidTest/assets/example.xml (No such file or directory)

Of course it will throw this exception, because it is under /homedir/src, not /homedir/homedir/src. Anyone know why it is using the double path?


问:
How to make TabLayout Custom Font , Custom color
I looking for TabLayout with following custom behaviour

Custom font

Text color change on select & un select of Tab

Bold & normal font on select & un select of Tab

By default 1st tab should be selected with Bold text

I am attaching following code snippet which all I tried for it.

1) I've created custom view Called FundayTabLayout

```<code><com.knackv.custom.view.FundayTabLayout
    android:id="@id/dashboard_tab_layout"
    style="@style/AppTabLayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:tabTextAppearance="@style/AppTabTextAppearance"></com.knackv.custom.view.FundayTabLayout>
</code>```

2) Styles which I've used

```<code><style name="AppTabLayout" parent="Widget.Design.TabLayout">
    <item name="tabMaxWidth">@dimen/size_in_150_dp</item>
    <item name="tabIndicatorColor">@color/app_background</item>
    <item name="tabBackground">@drawable/tab_background_color_selector</item>
    <item name="tabTextAppearance">@style/AppTabTextAppearance</item>
    <item name="tabSelectedTextColor">@color/app_blue</item>
</style>

<style name="AppTabTextAppearance" parent="TextAppearance.Design.Tab">
    <item name="android:textColor">@color/white</item>
    <item name="android:textSize">@dimen/size_in_15_dp</item>
    <item name="textAllCaps">false</item>
</style>
</code>```

3) setting up my custom font:

```<code> @Override
public void setupWithViewPager(@Nullable ViewPager viewPager) {
    super.setupWithViewPager(viewPager);

    this.removeAllTabs();

    ViewGroup slidingTabStrip = (ViewGroup) getChildAt(0);
    for (int i = 0, count = viewPager.getAdapter().getCount(); i < count; i++) {
        Tab tab = this.newTab();
        this.addTab(tab.setText(viewPager.getAdapter().getPageTitle(i)));
        AppCompatTextView view = (AppCompatTextView) ((ViewGroup) slidingTabStrip.getChildAt(i)).getChildAt(1);
        view.setAllCaps(false);
        view.setTypeface(Utility.getNormalTypeFace());
    }
}
</code>```

Please provide me optimum solution for this issue.

答:
https://stackoverflow.com/a/31067431/5726971
check this.. it's mainly for android design support TabLayout.
https://stackoverflow.com/a/33284990/5726971
this one added to the first answer in case of using custom TabLayout like your case.</p>

Body:
I looking for TabLayout with following custom behaviour

Custom font

Text color change on select & un select of Tab

Bold & normal font on select & un select of Tab

By default 1st tab should be selected with Bold text

I am attaching following code snippet which all I tried for it.

1) I've created custom view Called FundayTabLayout

<com.knackv.custom.view.FundayTabLayout
    android:id="@id/dashboard_tab_layout"
    style="@style/AppTabLayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:tabTextAppearance="@style/AppTabTextAppearance"></com.knackv.custom.view.FundayTabLayout>

2) Styles which I've used

3) setting up my custom font:

 @Override
public void setupWithViewPager(@Nullable ViewPager viewPager) {
    super.setupWithViewPager(viewPager);

    this.removeAllTabs();

    ViewGroup slidingTabStrip = (ViewGroup) getChildAt(0);
    for (int i = 0, count = viewPager.getAdapter().getCount(); i < count; i++) {
        Tab tab = this.newTab();
        this.addTab(tab.setText(viewPager.getAdapter().getPageTitle(i)));
        AppCompatTextView view = (AppCompatTextView) ((ViewGroup) slidingTabStrip.getChildAt(i)).getChildAt(1);
        view.setAllCaps(false);
        view.setTypeface(Utility.getNormalTypeFace());
    }
}

Please provide me optimum solution for this issue.


问:
Python Recursive Example Explanation
So currently working through MIT's OpenCourseWare computer science course online and I am having trouble trying to understand one of the recursive examples.

```<code>def f(L):
    result = []
    for e in L:
        if type(e) != list:
            result.append(e)
        else:
            return f(e)
return result
</code>```

When the following input is given:

```<code>print f([1, [[2, 'a'], ['a','b']], (3, 4)])
</code>```

The output is:

```<code>[2, 'a']
</code>```

I am having trouble trying to understand how this function actually works or what it is doing. Shouldn't the function eventually be adding every string or int into the result list? I just need help with trying to understand how this function "winds up" and "unwinds"

I feel like the output should be:

```<code>[1,2,'a','a','b',3,4]
</code>```

Any help would be appreciated thanks!

答:
The function as posted returns/exits when running into a first bottom-down list-element which doesn't contain a list - this prevents walking all the further branches of the recursion. For example:

```<code>print( f([1, [[2, 'a', [3, 'b', [4, 'c']]], ['a','b']], (3, 4)]) )
# gives: [4, 'c']
print( f([1, ['X','Y'], [[2, 'a', [3, 'b', [4, 'c']]], ['a','b']], (3, 4)]) )
# gives: ['X','Y']
</code>```

The key point causing this behaviour is the line

```<code>result = []
</code>```

This resets the list with results on each call of the function to an empty list. This way only one item is returned up from the chain of the recursion calls.

By the way the function f below does what you have expected, doesn't it?

```<code>def f(L, result):
    for e in L:
        if type(e) != list:
            result.append(e)
        else:
            f(e, result)

result=[]; f([1, [[2, 'a', [3, 'b', [4, 'c']]], ['a','b']], (3, 4)], result) print( result )
# gives: [1, 2, 'a', 3, 'b', 4, 'c', 'a', 'b', (3, 4)]
result=[]; f( [1, ['X','Y'], [[2, 'a', [3, 'b', [4, 'c']]], ['a','b']], (3, 4)], result); print( result )
# gives: [1, 'X', 'Y', 2, 'a', 3, 'b', 4, 'c', 'a', 'b', (3, 4)]
</code>```

NOTICE: (3,4) is a TUPLE not a list ...

The function f as above collects items from a list if these items are not a list themselves. In the special case, when the item in the list is a list, the function calls itself to collect the items from this list. This way all they way down of the hierarchy every element is collected, no matter how deep one needs to dig down. This is the beauty of recursion - a function calling itself does the 'magic' of visiting all of the branches and their leaves down a tree :)

Title: Python Recursive Example Explanation

Body:
So currently working through MIT's OpenCourseWare computer science course online and I am having trouble trying to understand one of the recursive examples.

def f(L):
    result = []
    for e in L:
        if type(e) != list:
            result.append(e)
        else:
            return f(e)
return result

When the following input is given:

print f([1, [[2, 'a'], ['a','b']], (3, 4)])

The output is:

[2, 'a']

I am having trouble trying to understand how this function actually works or what it is doing. Shouldn't the function eventually be adding every string or int into the result list? I just need help with trying to understand how this function "winds up" and "unwinds"

I feel like the output should be:

[1,2,'a','a','b',3,4]

Any help would be appreciated thanks!

Body:
The function as posted returns/exits when running into a first bottom-down list-element which doesn't contain a list - this prevents walking all the further branches of the recursion. For example:

print( f([1, [[2, 'a', [3, 'b', [4, 'c']]], ['a','b']], (3, 4)]) )
# gives: [4, 'c']
print( f([1, ['X','Y'], [[2, 'a', [3, 'b', [4, 'c']]], ['a','b']], (3, 4)]) )
# gives: ['X','Y']

The key point causing this behaviour is the line

result = []

This resets the list with results on each call of the function to an empty list. This way only one item is returned up from the chain of the recursion calls.

By the way the function f below does what you have expected, doesn't it?

def f(L, result):
    for e in L:
        if type(e) != list:
            result.append(e)
        else:
            f(e, result)

result=[]; f([1, [[2, 'a', [3, 'b', [4, 'c']]], ['a','b']], (3, 4)], result) print( result )
# gives: [1, 2, 'a', 3, 'b', 4, 'c', 'a', 'b', (3, 4)]
result=[]; f( [1, ['X','Y'], [[2, 'a', [3, 'b', [4, 'c']]], ['a','b']], (3, 4)], result); print( result )
# gives: [1, 'X', 'Y', 2, 'a', 3, 'b', 4, 'c', 'a', 'b', (3, 4)]

NOTICE: (3,4) is a TUPLE not a list ...

The function f as above collects items from a list if these items are not a list themselves. In the special case, when the item in the list is a list, the function calls itself to collect the items from this list. This way all they way down of the hierarchy every element is collected, no matter how deep one needs to dig down. This is the beauty of recursion - a function calling itself does the 'magic' of visiting all of the branches and their leaves down a tree :)