问:
NPM install/dependency from a GitHub Release Binary
I know how to make an NPM dependency from a GitHub release :

"dependencies": {
  "package-name": "user/repo#v1.0.0"
}
```

<p>That's nice, but I want to install a <strong>specific binary</strong> from this release.</p>

<p>I tried </p>

<pre class="lang-json prettyprint-override"><code>"dependencies": {
  "package-name": "https://github.com/user/repo/releases/download/v1.0.0/bin.tgz"
}
</code>```

But I gives me the following error :

❯ npm install
npm ERR! fetch failed https://github.com/user/repo/releases/download/v1.0.0/bin.tgz
npm WARN retry will retry, error on last attempt: Error: fetch failed with status code 404
```

<p>Binary release assets exist outside of GitHub and are using AWS S3.</p>

<p>The URL <code>github.com/user/repo/releases/download/v1.0.0/bin.tgz</code> is redirecting with a <code>302</code> status and a HTTP location header set to <code>https://github-cloud.s3.amazonaws.com/releases/XXX/XXX...</code></p>

<p>If I try directly with the S3 URL I got a ENAMETOOLONG error (see NPM issue) :</p>

<pre class="lang-bash prettyprint-override"><code>> npm install https://github-cloud.s3.amazonaws.com/releases/XXX/XXX...
npm ERR! tarball.destroy is not a function
npm WARN retry will retry, error on last attempt: Error: ENAMETOOLONG: name too long, open '/var/folders/pn/......
</code>```

Questions :

Why is NPM not following the redirect?

Why a 404?

Is there a way to link an NPM dependency to a GitHub release's binary tarball? How?

My context and needs :

I have a private GitHub repository

My package needs to be built before "deploying" (transpilation, etc.)

I want to "publish" a tarball of this build in my GitHub release and directly reference it to my NPM dependencies

I use a CI service to build, make the tarball and upload it next to the GitHub release

I would like to use GitHub release binary as a NPM repository

Related

SO question: How to install an npm package from GitHub directly?

NPM issue: https://github.com/npm/npm/issues/3055

答:
Github Releases are based on Git Tags.

"...Versions are based on Git
  tags."

https://help.github.com/articles/creating-releases/

To specify a version with a Git URL, include an appropriate , such as a tag, at the end as a URL fragment.
Example, for a tag named 0.3.1:

```<code>"dependencies": {
  "myprivatemodule": "git@github.com:...#0.3.1"
}
</code>```

The snipped portion (...) should be filled in:

```<code>"myprivatemodule": "git@github.com:{owner}/{project}.git#0.3.1"
</code>```

And, a different address format will be needed when SSH access isn't available:

```<code>"myprivatemodule": "git://github.com/{owner}/{project}.git#0.3.1"
</code>```

kindly taken from: npm install from Git in a specific version

Body:
I know how to make an NPM dependency from a GitHub release :

"dependencies": {
  "package-name": "user/repo#v1.0.0"
}

That's nice, but I want to install a specific binary from this release.

I tried

"dependencies": {
  "package-name": "https://github.com/user/repo/releases/download/v1.0.0/bin.tgz"
}

But I gives me the following error :

❯ npm install
npm ERR! fetch failed https://github.com/user/repo/releases/download/v1.0.0/bin.tgz
npm WARN retry will retry, error on last attempt: Error: fetch failed with status code 404

Binary release assets exist outside of GitHub and are using AWS S3.

The URL github.com/user/repo/releases/download/v1.0.0/bin.tgz is redirecting with a 302 status and a HTTP location header set to https://github-cloud.s3.amazonaws.com/releases/XXX/XXX...

If I try directly with the S3 URL I got a ENAMETOOLONG error (see NPM issue) :

> npm install https://github-cloud.s3.amazonaws.com/releases/XXX/XXX...
npm ERR! tarball.destroy is not a function
npm WARN retry will retry, error on last attempt: Error: ENAMETOOLONG: name too long, open '/var/folders/pn/......

Questions :

Why is NPM not following the redirect?

Why a 404?

Is there a way to link an NPM dependency to a GitHub release's binary tarball? How?

My context and needs :

I have a private GitHub repository

My package needs to be built before "deploying" (transpilation, etc.)

I want to "publish" a tarball of this build in my GitHub release and directly reference it to my NPM dependencies

I use a CI service to build, make the tarball and upload it next to the GitHub release

I would like to use GitHub release binary as a NPM repository

Related

SO question: How to install an npm package from GitHub directly?

NPM issue: https://github.com/npm/npm/issues/3055

Body:
Github Releases are based on Git Tags.

"...Versions are based on Git
  tags."

https://help.github.com/articles/creating-releases/

To specify a version with a Git URL, include an appropriate , such as a tag, at the end as a URL fragment.
Example, for a tag named 0.3.1:

"dependencies": {
  "myprivatemodule": "git@github.com:...#0.3.1"
}

The snipped portion (...) should be filled in:

"myprivatemodule": "git@github.com:{owner}/{project}.git#0.3.1"

And, a different address format will be needed when SSH access isn't available:

"myprivatemodule": "git://github.com/{owner}/{project}.git#0.3.1"

kindly taken from: npm install from Git in a specific version


来源: stackexchange

问:
TypeScript struggles with Redux containers
I'm having some trouble figuring out how to properly type Redux containers.

Consider a simple presentational component that might look like this:

```<code>interface MyProps {
  name: string;
  selected: boolean;
  onSelect: (name: string) => void;
}
class MyComponent extends React.Component<MyProps, {}> { }
</code>```

From the perspective of this component all props are required.

Now I want to write a container that pulls all these props out of state:

```<code>function mapStateToProps(state: MyState) {
  return {
    name: state.my.name,
    selected: state.my.selected
  };
}

function mapDispatchToProps(dispatch: IDispatch) {
  return {
    onSelect(name: string) {
      dispatch(mySelectAction(name));
    }
  };
}

const MyContainer = connect(
  mapStateToProps,
  mapDispatchToProps
)(MyComponent);
</code>```

This works, but there's a big typing problem: the mapping functions (mapStateToProps and mapDispatchToProps) have no protection that they are providing the right data to fulfill MyProps. This is prone to error, typos and poor refactoring.

I could make the mapping functions return type MyProps:

```<code>function mapStateToProps(state: MyState): MyProps { }

function mapDispatchToProps(dispatch: IDispatch): MyProps { }
</code>```

However this doesn't work unless I make all MyProp props optional, so that each mapping function can return only the portion they care about. I don't want to make the props optional, because they aren't optional to the presentational component.

Another option is to split up the props for each map function and combine them for the component props:

```<code>// MyComponent
interface MyStateProps {
  name: string;
  selected: boolean;
}

interface MyDispatchProps {
  onSelect: (name: string) => void;
}

type MyProps = MyStateProps & MyDispatchProps;

class MyComponent extends React.Component<MyProps, {}> { }

// MyContainer
function mapStateToProps(state: MyState): MyStateProps { }

function mapDispatchToProps(dispatch: IDispatch): MyDispatchProps { }
</code>```

Ok, that's getting me closer to what I want, but its kind of noisy and its making me write my presentational component prop interface around the shape of a container, which I don't like.

And now a second problem arises. What if I want to put the container inside another component:

```<code><MyContainer />
</code>```

This gives compile errors that name, selected, and onSelect are all missing... but that's intentional because the container is connecting to Redux and providing those. So this pushes me back to making all component props optional, but I don't like that because they aren't really optional.

Things get worse when MyContainer has some of its own props that it wants to be passed in:

```<code><MyContainer section="somethng" />
</code>```

Now what I'm trying to do is have section a required prop of MyContainer but not a prop of MyComponent, and name, selected, and onSelect are required props of MyComponent but optional or not props at all of MyContainer. I'm totally at a loss how to express this.

Any guidence on this would be appreciated!

答:
```<code>interface MyStateProps {
    name: string;
    selected: boolean;
}

interface MyDispatchProps {
    onSelect: (name: string) => void;
}

interface MyOwnProps {
    section: string;
}

// Intersection Types
type MyProps = MyStateProps & MyDispatchProps & MyOwnProps;

class MyComponent extends React.Component<MyProps, {}> { }

function mapStateToProps(state: MyState): MyStateProps { }

function mapDispatchToProps(dispatch: IDispatch): MyDispatchProps { }

const MyContainer = connect<MyStateProps, MyDispatchProps, MyOwnProps>(
  mapStateToProps,
  mapDispatchToProps
)(MyComponent);
</code>```

You can use something use called Intersection Types
https://www.typescriptlang.org/docs/handbook/advanced-types.html#intersection-types

ContentLicense: CC BY-SA 3.0

Body:
I'm having some trouble figuring out how to properly type Redux containers.

Consider a simple presentational component that might look like this:

interface MyProps {
  name: string;
  selected: boolean;
  onSelect: (name: string) => void;
}
class MyComponent extends React.Component<MyProps, {}> { }

From the perspective of this component all props are required.

Now I want to write a container that pulls all these props out of state:

function mapStateToProps(state: MyState) {
  return {
    name: state.my.name,
    selected: state.my.selected
  };
}

function mapDispatchToProps(dispatch: IDispatch) {
  return {
    onSelect(name: string) {
      dispatch(mySelectAction(name));
    }
  };
}

const MyContainer = connect(
  mapStateToProps,
  mapDispatchToProps
)(MyComponent);

This works, but there's a big typing problem: the mapping functions (mapStateToProps and mapDispatchToProps) have no protection that they are providing the right data to fulfill MyProps. This is prone to error, typos and poor refactoring.

I could make the mapping functions return type MyProps:

function mapStateToProps(state: MyState): MyProps { }

function mapDispatchToProps(dispatch: IDispatch): MyProps { }

However this doesn't work unless I make all MyProp props optional, so that each mapping function can return only the portion they care about. I don't want to make the props optional, because they aren't optional to the presentational component.

Another option is to split up the props for each map function and combine them for the component props:

// MyComponent
interface MyStateProps {
  name: string;
  selected: boolean;
}

interface MyDispatchProps {
  onSelect: (name: string) => void;
}

type MyProps = MyStateProps & MyDispatchProps;

class MyComponent extends React.Component<MyProps, {}> { }

// MyContainer
function mapStateToProps(state: MyState): MyStateProps { }

function mapDispatchToProps(dispatch: IDispatch): MyDispatchProps { }

Ok, that's getting me closer to what I want, but its kind of noisy and its making me write my presentational component prop interface around the shape of a container, which I don't like.

And now a second problem arises. What if I want to put the container inside another component:

<MyContainer />

This gives compile errors that name, selected, and onSelect are all missing... but that's intentional because the container is connecting to Redux and providing those. So this pushes me back to making all component props optional, but I don't like that because they aren't really optional.

Things get worse when MyContainer has some of its own props that it wants to be passed in:

<MyContainer section="somethng" />

Now what I'm trying to do is have section a required prop of MyContainer but not a prop of MyComponent, and name, selected, and onSelect are required props of MyComponent but optional or not props at all of MyContainer. I'm totally at a loss how to express this.

Any guidence on this would be appreciated!

Body:
interface MyStateProps {
    name: string;
    selected: boolean;
}

interface MyDispatchProps {
    onSelect: (name: string) => void;
}

interface MyOwnProps {
    section: string;
}

// Intersection Types
type MyProps = MyStateProps & MyDispatchProps & MyOwnProps;

class MyComponent extends React.Component<MyProps, {}> { }

function mapStateToProps(state: MyState): MyStateProps { }

function mapDispatchToProps(dispatch: IDispatch): MyDispatchProps { }

const MyContainer = connect<MyStateProps, MyDispatchProps, MyOwnProps>(
  mapStateToProps,
  mapDispatchToProps
)(MyComponent);

You can use something use called Intersection Types
https://www.typescriptlang.org/docs/handbook/advanced-types.html#intersection-types


问:
Failed to Install SQL Server MDS Workflow Integration Service
I tried to create a custom workflow by the following this article:

https://learn.microsoft.com/en-us/sql/master-data-services/develop/create-a-custom-workflow-master-data-services.

C:\Program Files\Microsoft SQL Server\130\Master Data
  Services\WebApplication\bin>C:\Windows\Microsoft.NET\Framework\v4.0.30319\InstallUtil
  Microsoft.MasterDataServices.Workflow.exe

  Microsoft (R) .NET Framework
  Installation utility Version 4.7.2053.0 Copyright (C) Microsoft
  Corporation.  All rights reserved.

System.BadImageFormatException: Could not load file or assembly
  'file:///C:\Program Files\Microsoft SQL Server\130\Master Data
  Services\WebApplication\bin\Microsoft.MasterDataServices.Workflow.exe'
  or one of its dependencies. An attempt was made to load a program with
  an incorrect format.

Any advice?
I'm running CMD with admin rights.

答: Solved. Just select 64 bit version.</p>

Body: Solved. Just select 64 bit version.


问:
Inheritance for Algebraic Data Types in Rascal?
Right, I have this data type in Rascal:

```<code>data Type = Any() | Void() | Int() | Not(Type l) | And(set[Type] es) | Or(set[Type] es);
</code>```

What I want to do is define another type like this:

```<code>data Primitive = Any() | Void() | Int();
</code>```

And then be able to do things like this:

```<code>Primitive p = Any();
Type d = p;
</code>```

Or, for example, match against Primitive when simplifying Type.  Something like this:

```<code>public Type reduce(Not(Primitive p)) = p;
</code>```

Currently, the only solution I can see is to expand the above rule for each case like so:

```<code>public Type reduce(Not(Any)) = Any();
public Type reduce(Not(Void)) = Void();
public Type reduce(Not(Int)) = Int();
</code>```

I'm guessing there is a way to do this, but I didn't figure it out yet ... thoughts?

答:
Nice question. Rascal does not feature user-defined sub-typing and typing for data types is nominal. That answers your question in theory, so how does that work in practise?

The answer for data types is slightly different for syntax types, so here follows both stories;

There many are different idioms to model a hierarchy of data-structures, we'll show only three here for the sake of simplicity;

Here's a way to extend a data-type with new features which does not involve adding new types, this produces an over-approximate model of what you intended:

```<code>// first the primitive types are defined (I've added Not here to make a point later):
data Type = Any() | Void() | Int() | Not(Type l);

// then the extension is added (perhaps in a different module)
data Type = And(set[Type] es) | Or(set[Type] es);

// the second definition adds its alternatives also to the child of `Not`.
</code>```

The second way is more close to an actual extension, because the original Type is not extended, and no "junk" is added accidentally:

```<code>// we give the original type a unique name:
data Primitive = Any() | Void() | Int();

// For the extension the Primitive type is not polluted with the new constructors, but
// it was wrapped inside a singleton constructor `prim`
data Type = prim(Primitive super) | And(set[Type] es) | Or(set[Type] es);
</code>```

Of course, this second solution will make you add prim constructors in possible pattern matches you might do, but the / deep match operator will allow you to ignore it where possible. For example:

```<code>bool evalt(prim(p)) = evalp(p);
bool evalp(Any()) = true;
bool evalp(Not(p)) = !evalp(p);

bool containsVoid(Type t) = /Void() := t;
</code>```

Now for syntax types the story is similar but since chain rules in syntax types are invisible, it gives some additional flavor:

```<code>syntax Primitive = "any" | "void" | "int";

// notice the first chain rule or "injection" of Primitive into Type:
syntax Type = Primitive | left Type "∧" Type > left Type "∨" Type;

bool evalt((Type) `any`) = true; // the chain rule is parsed but invisible
</code>```

People have been discussing to add implicit chaining to the abstract data-types as well, for its attractive to simulate sub-typing like so. I guess that would be like Scala's implicits. The jury is still out on that one.

Body:
Right, I have this data type in Rascal:

data Type = Any() | Void() | Int() | Not(Type l) | And(set[Type] es) | Or(set[Type] es);

What I want to do is define another type like this:

data Primitive = Any() | Void() | Int();

And then be able to do things like this:

Primitive p = Any();
Type d = p;

Or, for example, match against Primitive when simplifying Type.  Something like this:

public Type reduce(Not(Primitive p)) = p;

Currently, the only solution I can see is to expand the above rule for each case like so:

public Type reduce(Not(Any)) = Any();
public Type reduce(Not(Void)) = Void();
public Type reduce(Not(Int)) = Int();

I'm guessing there is a way to do this, but I didn't figure it out yet ... thoughts?

Body:
Nice question. Rascal does not feature user-defined sub-typing and typing for data types is nominal. That answers your question in theory, so how does that work in practise?

The answer for data types is slightly different for syntax types, so here follows both stories;

There many are different idioms to model a hierarchy of data-structures, we'll show only three here for the sake of simplicity;

Here's a way to extend a data-type with new features which does not involve adding new types, this produces an over-approximate model of what you intended:

// first the primitive types are defined (I've added Not here to make a point later):
data Type = Any() | Void() | Int() | Not(Type l);

// then the extension is added (perhaps in a different module)
data Type = And(set[Type] es) | Or(set[Type] es);

// the second definition adds its alternatives also to the child of `Not`.

The second way is more close to an actual extension, because the original Type is not extended, and no "junk" is added accidentally:

// we give the original type a unique name:
data Primitive = Any() | Void() | Int();

// For the extension the Primitive type is not polluted with the new constructors, but
// it was wrapped inside a singleton constructor `prim`
data Type = prim(Primitive super) | And(set[Type] es) | Or(set[Type] es);

Of course, this second solution will make you add prim constructors in possible pattern matches you might do, but the / deep match operator will allow you to ignore it where possible. For example:

bool evalt(prim(p)) = evalp(p);
bool evalp(Any()) = true;
bool evalp(Not(p)) = !evalp(p);

bool containsVoid(Type t) = /Void() := t;

Now for syntax types the story is similar but since chain rules in syntax types are invisible, it gives some additional flavor:

syntax Primitive = "any" | "void" | "int";

// notice the first chain rule or "injection" of Primitive into Type:
syntax Type = Primitive | left Type "∧" Type > left Type "∨" Type;

bool evalt((Type) `any`) = true; // the chain rule is parsed but invisible

People have been discussing to add implicit chaining to the abstract data-types as well, for its attractive to simulate sub-typing like so. I guess that would be like Scala's implicits. The jury is still out on that one.


问:
Multiple field foreign key in django
I have two models in django with definitions below.
CreativeStatus model :

```<code>class RtbdCreativeStatus(models.Model):
    creative_id = models.CharField(max_length=500, primary_key=True)
    advertiser_id = models.CharField(max_length=100, primary_key=True)
    exposure_level = models.CharField(max_length=125)
    modified_on = models.DateTimeField()
    modified_by = models.CharField(max_length=100)

class RtbdCreative(models.Model):
    id = models.AutoField(primary_key=True)
    advertiser_id = models.ForeignKey(RtbdCreativeStatus, on_delete=models.CASCADE)
    creative_id = models.ForeignKey(RtbdCreativeStatus, on_delete=models.CASCADE)
    country_id = models.IntegerField()
    adm = models.CharField(max_length=255, null=True, blank=True)
    sample_url = models.CharField(max_length=500)
    landing_page = models.CharField(max_length=500, null=True, blank=True)
    html = models.CharField(max_length=500)
    creative_attributes = models.CommaSeparatedIntegerField(max_length=150, null=True, blank=True)
    advertiser_domains = models.CharField(max_length=500)
    description = models.CharField(max_length=500, null=True, blank=True)
    created_on = models.DateTimeField(auto_now=True, auto_now_add=True)
    creative_type = models.CharField(max_length=50, null=True, blank=True)
    demand_source_type_id = models.IntegerField()
    revalidate = models.BooleanField(default=False)
</code>```

(creative_id, advertiser_id ) combination is unique in my CreativeStatus table . I want that combination to be my foreign key for Creative table. I tried adding it but i get this error .

1)How do i achieve this join with two key combination as my foreign key .

2)What should be my query to fetch all the creatives with their status from CreativeStatus table .

UPDATE 1

on reading the answers below , i updated my model as mentioned below :

```<code>class RtbdCreative(models.Model):
    id = models.AutoField(primary_key=True)
    advertiser_id = models.ForeignKey(RtbdCreativeStatus, to_field='advertiser_id', related_name='advertiser', db_column='advertiser_id', on_delete=models.CASCADE)
    creative_id = models.ForeignKey(RtbdCreativeStatus, to_field='creative_id', related_name='creative', db_column='creative_id', on_delete=models.CASCADE)
    country_id = models.IntegerField()
    adm = models.CharField(max_length=255, null=True, blank=True)
    sample_url = models.CharField(max_length=500)
    landing_page = models.CharField(max_length=500, null=True, blank=True)
    html = models.CharField(max_length=500)
    creative_attributes = models.CommaSeparatedIntegerField(max_length=150, null=True, blank=True)
    advertiser_domains = models.CharField(max_length=500)
    description = models.CharField(max_length=500, null=True, blank=True)
    created_on = models.DateTimeField(auto_now=True, auto_now_add=True)
    creative_type = models.CharField(max_length=50, null=True, blank=True)
    demand_source_type_id = models.IntegerField()
    revalidate = models.BooleanField(default=False)
</code>```

Now i am getting this error . I have combination of advertiser_id , craetive_id as unique . But django expects both to be unique. What can i do to make it work ?

答:
When you add multiple ForeignKeys towards same table, you should override the related_name option of your fields, so that the fields could be distinguished easily.

You could implement a custom validation for checking uniqueness of the creative_id and advertiser_id,

```<code>class Creative(models.Model):
    advertiser_id = models.ForeignKey(CreativeStatus,
                                  related_name="advertisers")
    creative_id = models.ForeignKey(CreativeStatus,
                                related_name="creatives")

    def clean(self):
        data = self.cleaned_data
        if not data['advertiser_id'] == data['creative_id']:
            raise ValidationError("Unique Constraint failed {}, {}".format(self.advertiser_id, self.creative_id))
        return data
</code>```

You could query your creatives from CreativeStatus using the related name.

```<code>creative_status_obj = CreativeStatus.objects.get(pk=some_pk)#or any query.
#All creatives of the given object can be queried using reverse relation.
creatives = creative_status_obj.creatives.all()
</code>```

Title: Multiple field foreign key in django

Body:
I have two models in django with definitions below.
CreativeStatus model :

class RtbdCreativeStatus(models.Model):
    creative_id = models.CharField(max_length=500, primary_key=True)
    advertiser_id = models.CharField(max_length=100, primary_key=True)
    exposure_level = models.CharField(max_length=125)
    modified_on = models.DateTimeField()
    modified_by = models.CharField(max_length=100)

class RtbdCreative(models.Model):
    id = models.AutoField(primary_key=True)
    advertiser_id = models.ForeignKey(RtbdCreativeStatus, on_delete=models.CASCADE)
    creative_id = models.ForeignKey(RtbdCreativeStatus, on_delete=models.CASCADE)
    country_id = models.IntegerField()
    adm = models.CharField(max_length=255, null=True, blank=True)
    sample_url = models.CharField(max_length=500)
    landing_page = models.CharField(max_length=500, null=True, blank=True)
    html = models.CharField(max_length=500)
    creative_attributes = models.CommaSeparatedIntegerField(max_length=150, null=True, blank=True)
    advertiser_domains = models.CharField(max_length=500)
    description = models.CharField(max_length=500, null=True, blank=True)
    created_on = models.DateTimeField(auto_now=True, auto_now_add=True)
    creative_type = models.CharField(max_length=50, null=True, blank=True)
    demand_source_type_id = models.IntegerField()
    revalidate = models.BooleanField(default=False)

(creative_id, advertiser_id ) combination is unique in my CreativeStatus table . I want that combination to be my foreign key for Creative table. I tried adding it but i get this error .

1)How do i achieve this join with two key combination as my foreign key .

2)What should be my query to fetch all the creatives with their status from CreativeStatus table .

UPDATE 1

on reading the answers below , i updated my model as mentioned below :

class RtbdCreative(models.Model):
    id = models.AutoField(primary_key=True)
    advertiser_id = models.ForeignKey(RtbdCreativeStatus, to_field='advertiser_id', related_name='advertiser', db_column='advertiser_id', on_delete=models.CASCADE)
    creative_id = models.ForeignKey(RtbdCreativeStatus, to_field='creative_id', related_name='creative', db_column='creative_id', on_delete=models.CASCADE)
    country_id = models.IntegerField()
    adm = models.CharField(max_length=255, null=True, blank=True)
    sample_url = models.CharField(max_length=500)
    landing_page = models.CharField(max_length=500, null=True, blank=True)
    html = models.CharField(max_length=500)
    creative_attributes = models.CommaSeparatedIntegerField(max_length=150, null=True, blank=True)
    advertiser_domains = models.CharField(max_length=500)
    description = models.CharField(max_length=500, null=True, blank=True)
    created_on = models.DateTimeField(auto_now=True, auto_now_add=True)
    creative_type = models.CharField(max_length=50, null=True, blank=True)
    demand_source_type_id = models.IntegerField()
    revalidate = models.BooleanField(default=False)

Now i am getting this error . I have combination of advertiser_id , craetive_id as unique . But django expects both to be unique. What can i do to make it work ?

Body:
When you add multiple ForeignKeys towards same table, you should override the related_name option of your fields, so that the fields could be distinguished easily.

You could implement a custom validation for checking uniqueness of the creative_id and advertiser_id,

class Creative(models.Model):
    advertiser_id = models.ForeignKey(CreativeStatus,
                                  related_name="advertisers")
    creative_id = models.ForeignKey(CreativeStatus,
                                related_name="creatives")

    def clean(self):
        data = self.cleaned_data
        if not data['advertiser_id'] == data['creative_id']:
            raise ValidationError("Unique Constraint failed {}, {}".format(self.advertiser_id, self.creative_id))
        return data

You could query your creatives from CreativeStatus using the related name.

creative_status_obj = CreativeStatus.objects.get(pk=some_pk)#or any query.
#All creatives of the given object can be queried using reverse relation.
creatives = creative_status_obj.creatives.all()


问:
How can I get two different binary trees of two different types?
For an array if I want an array of integers it's:

```<code>int anArray[];
</code>```

For an array of strings it is:

```<code>string anArray[];
</code>```

I have a binary search tree template that allows the type to be chosen using a typedef:

```<code>typedef desiredType TreeItemType; // desired type of tree items i.e. string, int, etc.
</code>```

How can I get two different trees of two different types?  Right now the only way I see possible is to write all the supporting code twice with different file names and setting the typedef's.  There has to be a way to set the typedef desiredType in a method or something.  Any ideas?

答: why not turn it into a templated class, seeing as your using C++? this allows any number of permutations of types, and remove any problems that might occur with a typedef'd type(aliased type).</p>

ContentLicense: CC BY-SA 2.5

Body:
For an array if I want an array of integers it's:

int anArray[];

For an array of strings it is:

string anArray[];

I have a binary search tree template that allows the type to be chosen using a typedef:

typedef desiredType TreeItemType; // desired type of tree items i.e. string, int, etc.

How can I get two different trees of two different types?  Right now the only way I see possible is to write all the supporting code twice with different file names and setting the typedef's.  There has to be a way to set the typedef desiredType in a method or something.  Any ideas?


问:
Log4net is not creating the log file after installation windows service
I have a windows service project with log4net. If I install the service via installutil.exe then everything works fine. I adding windows setup project - service starting and work, but not creating log files.

My conf

```<code><configSections>
    <section name="ConnectionInfo" type="Astra.Common.Configuration.ConnectionInfoConfiguration, Astra.Common" />
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net, Version=2.0.8, Culture=neutral, PublicKeyToken=669e0ddf0bb1aa2a" />
  </configSections>
</code>```

...

```<code><log4net>
    <appender name="LogFileAppender" type="log4net.Appender.RollingFileAppender">
      <param name="File" value="Logs\service.log" />
      <param name="AppendToFile" value="true" />
      <maxSizeRollBackups value="10" />
      <maximumFileSize value="5MB" />
      <lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
      <layout type="log4net.Layout.PatternLayout">
        <param name="ConversionPattern" value="%d  %-5p %m%n" />
      </layout>

    </appender>

    <logger name="LOGGER">
      <appender-ref ref="LogFileAppender" />
    </logger>
  </log4net>
</code>```

Class

```<code>public static class Logger
    {
        private static ILog log = LogManager.GetLogger("LOGGER");

        public static ILog Log
        {
            get { return log; }
        }

        public static void InitLogger()
        {
            XmlConfigurator.Configure();
        }

        static Logger()
        {
            InitLogger();
        }
    }

[assembly: log4net.Config.XmlConfigurator(Watch = true)]
</code>```

Service as NetworkService

答: If you have a file appender, make sure you are writing to a location where the user is allowed to create and update the files. If not the logging will fail. You can check this when you have internal debugging enabled.</p>

Body:
I have a windows service project with log4net. If I install the service via installutil.exe then everything works fine. I adding windows setup project - service starting and work, but not creating log files.

My conf

<configSections>

  </configSections>

...

<log4net>
    <appender name="LogFileAppender" type="log4net.Appender.RollingFileAppender">
      <param name="File" value="Logs\service.log" />
      <param name="AppendToFile" value="true" />
      <maxSizeRollBackups value="10" />
      <maximumFileSize value="5MB" />
      <lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
      <layout type="log4net.Layout.PatternLayout">
        <param name="ConversionPattern" value="%d  %-5p %m%n" />
      </layout>

    </appender>

    <logger name="LOGGER">
      <appender-ref ref="LogFileAppender" />
    </logger>
  </log4net>

Class

public static class Logger
    {
        private static ILog log = LogManager.GetLogger("LOGGER");

        public static ILog Log
        {
            get { return log; }
        }

        public static void InitLogger()
        {
            XmlConfigurator.Configure();
        }

        static Logger()
        {
            InitLogger();
        }
    }

[assembly: log4net.Config.XmlConfigurator(Watch = true)]

Service as NetworkService


问:
Convert a Unix timestamp to time in JavaScript
I am storing time in a MySQL database as a Unix timestamp and that gets sent to some JavaScript code. How would I get just the time out of it?

For example, in HH/MM/SS format.

答:
function getDateTimeFromTimestamp(unixTimeStamp) {
    let date = new Date(unixTimeStamp);
    return ('0' + date.getDate()).slice(-2) + '/' + ('0' + (date.getMonth() + 1)).slice(-2) + '/' + date.getFullYear() + ' ' + ('0' + date.getHours()).slice(-2) + ':' + ('0' + date.getMinutes()).slice(-2);
}

const myTime = getDateTimeFromTimestamp(1435986900000);
console.log(myTime); // output 01/05/2000 11:00```

ContentLicense: CC BY-SA 4.0


问:
how to add array values to column using excel VBA
I am using below vba code, I have multiple columns for sample I have provided few.
All I am trying is, if I try to make the changes the same value should restore to the deleted column headers.
Below code is working fine if I make any changes to the range "A1" however if I make any changes other than "A1", code is taking too much of time complete and it is looping too many times.

```<code>Private Sub Worksheet_Change(ByVal Target As Range)
Dim headers() As Variant
If Range("A1").Value <> "FIRST" Or Range("B1").Value <> "Second" Or Range("C1").Value <> "Third"  Then
headers() = Array("FIRST", "Second", "Third")
With Sheets("Sheet1")
For i = LBound(headers()) To UBound(headers())
.Cells(1, 1 + i).Value = headers(i)
 Next i
 .Rows(1).Font.Bold = True
End With
End If
</code>```

==============================
Please help me to resolve this issue, appreciate your help in advance.

答:
You have to take care of disabling events before you change the values.
Try the following code:</p>

```<code>Private Sub Worksheet_Change(ByVal Target As Range)
Dim Header As Variant
    If Application.Intersect(Target, Target.Parent.Range("A1:C1")) Is Nothing Then Exit Sub
    Application.EnableEvents = False
    Header = Array("FIRST", "Second", "Third")
    Target.Parent.Range("A1:C1").Value = Header
    Application.EnableEvents = True
End Sub
</code>```

Body:
I am using below vba code, I have multiple columns for sample I have provided few.
All I am trying is, if I try to make the changes the same value should restore to the deleted column headers.
Below code is working fine if I make any changes to the range "A1" however if I make any changes other than "A1", code is taking too much of time complete and it is looping too many times.

Private Sub Worksheet_Change(ByVal Target As Range)
Dim headers() As Variant
If Range("A1").Value <> "FIRST" Or Range("B1").Value <> "Second" Or Range("C1").Value <> "Third"  Then
headers() = Array("FIRST", "Second", "Third")
With Sheets("Sheet1")
For i = LBound(headers()) To UBound(headers())
.Cells(1, 1 + i).Value = headers(i)
 Next i
 .Rows(1).Font.Bold = True
End With
End If

==============================
Please help me to resolve this issue, appreciate your help in advance.

Body:
You have to take care of disabling events before you change the values.
Try the following code:

Private Sub Worksheet_Change(ByVal Target As Range)
Dim Header As Variant
    If Application.Intersect(Target, Target.Parent.Range("A1:C1")) Is Nothing Then Exit Sub
    Application.EnableEvents = False
    Header = Array("FIRST", "Second", "Third")
    Target.Parent.Range("A1:C1").Value = Header
    Application.EnableEvents = True
End Sub


问:
Beginner Java - Changing String from First Middle Last to Last, First Middle
Trying to work out a homework problem that demands:
Changes a name so that the last name comes first.
Example: "Mary Jane Lee" will return "Lee, Mary Jane".
If name has no spaces, it is returned without change.

After doing some research it seems I can do this with the Split method, but we've not learned that yet.

The thing is I've worked out the code and it seems to work when spaces
 and a full name is entered, but when there's no middle name or no spaces to separate the character, I get the error:

when the name entered is simply: Harry Smith

```<code>java.lang.StringIndexOutOfBoundsException: String index out of range: -7
</code>```

and

```<code>java.lang.StringIndexOutOfBoundsException: String index out of range: -1
</code>```

when the name is Sarah

This is my code, but I'm not sure how to fix it:

```<code>public class Names {
    public static String lastNameFirst(String name) {
        int firstIndex = name.indexOf(" ");
        int secondIndex = name.indexOf(" ", firstIndex + 1);
        String firstName = name.substring(0, name.indexOf(" "));
        String middleName = name.substring(firstIndex + 1, secondIndex);
        String lastName = name.substring(secondIndex + 1);
        String result = "";
        result = lastName + ", " + firstName + " " + middleName;
        return result;
    }
}
</code>```

Thanks in advance!!

答:
Your code assumes that the input String contains at least two spaces. When that assumption is wrong (as in the inputs "Harry Smith" and "Sarah"), you get an exception.

You must check whether firstIndex and secondIndex are positive before using their values.

Body:
Trying to work out a homework problem that demands:
Changes a name so that the last name comes first.
Example: "Mary Jane Lee" will return "Lee, Mary Jane".
If name has no spaces, it is returned without change.

After doing some research it seems I can do this with the Split method, but we've not learned that yet.

The thing is I've worked out the code and it seems to work when spaces
 and a full name is entered, but when there's no middle name or no spaces to separate the character, I get the error:

when the name entered is simply: Harry Smith

java.lang.StringIndexOutOfBoundsException: String index out of range: -7

and

java.lang.StringIndexOutOfBoundsException: String index out of range: -1

when the name is Sarah

This is my code, but I'm not sure how to fix it:

public class Names {
    public static String lastNameFirst(String name) {
        int firstIndex = name.indexOf(" ");
        int secondIndex = name.indexOf(" ", firstIndex + 1);
        String firstName = name.substring(0, name.indexOf(" "));
        String middleName = name.substring(firstIndex + 1, secondIndex);
        String lastName = name.substring(secondIndex + 1);
        String result = "";
        result = lastName + ", " + firstName + " " + middleName;
        return result;
    }
}

Thanks in advance!!


问:
What is the LINQ to XML equivalent for this XPath
I wondering what the "best practice" way (in C#) is to implement this xpath query with LINQ:

```<code>/topNode/middleNode[@filteringAttribute='filterValue']/penultimateNode[@anotherFilterAttribute='somethingElse']/nodesIWantReturned
</code>```

I would like an IEnumerable list of the 'nodesIWantReturned', but only from a certain section of the XML tree, dependent on the value of ancestor attributes.

答:
In addition to the Linq methods shown, you can also import the System.Xml.XPath namespace and then use the XPathSelectElements extension method to use your XPath query directly.

It is noted in the class that these methods are slower than 'proper' Linq-to-XML, however a lot of the time this isn't too important, and sometimes it's easier just to use XPath (it's certainly a lot terser!).

```<code>var result = doc.XPathSelectElements("your xpath here");
</code>```

OwnerDisplayName: Handleman

Body:
I wondering what the "best practice" way (in C#) is to implement this xpath query with LINQ:

/topNode/middleNode[@filteringAttribute='filterValue']/penultimateNode[@anotherFilterAttribute='somethingElse']/nodesIWantReturned

I would like an IEnumerable list of the 'nodesIWantReturned', but only from a certain section of the XML tree, dependent on the value of ancestor attributes.

Body:
In addition to the Linq methods shown, you can also import the System.Xml.XPath namespace and then use the XPathSelectElements extension method to use your XPath query directly.

It is noted in the class that these methods are slower than 'proper' Linq-to-XML, however a lot of the time this isn't too important, and sometimes it's easier just to use XPath (it's certainly a lot terser!).

var result = doc.XPathSelectElements("your xpath here");

OwnerDisplayName: Greg Beech


问:
valid fragment of this code in c++
what is valid form of this code in  visual c++? this does not work i took it from microsoft</p>

```<code>using namespace System;
int main() {
   Console::WriteLine(__CLR_VER);
}
</code>```

答:
I think this is a good standard C++ approximation:</p>

```<code>#include <iostream>
int main() {
    std::cout << __cplusplus << std::endl;
}
</code>```

Title: valid fragment of this code in c++

Body:
what is valid form of this code in  visual c++? this does not work i took it from microsoft

using namespace System;
int main() {
   Console::WriteLine(__CLR_VER);
}

Body:
I think this is a good standard C++ approximation:

#include <iostream>
int main() {
    std::cout << __cplusplus << std::endl;
}


问:
Does python static method consume less memory than instance method
I have several instance methods that use self within them, but only in a couple places.

I can pass the objects to these methods directly and make them staticmethods. Does that consume less memory?

答:
You are micro-optimising here for no benefit.

Yes, a regular method involves a new method object that is created to handle the binding between function and instance, but that's only a bit of memory (2 pointers plus some Python metadata) used only during the duration of the call or if you stored the bound method *. A staticmethod object doesn't create a new method object, but that's offset by the about the same amount of memory needed for the staticmethod object:

```<code>>>> import sys
>>> class Foo:
...     def bar(self): pass
...     @staticmethod
...     def staticbar(): pass
...
>>> sys.getsizeof(Foo().bar)   # bound method object size
64
>>> sys.getsizeof(Foo.__dict__['staticbar'])  # staticmethod size
56
</code>```

So using a staticmethod object saves you 8 bytes (on Mac OS X, on another OS the byte count could differ slightly), but you don't usually keep a bound method (you'd use instance.method(), which creates the method object then discards it again after calling).

So, unless you are storing a large number of bound methods, this is not going to make enough difference to justify making your code unreadable by passing in the instance manually everywhere.

* Note that as of Python 3.7, for common cases Python doesn't even create method objects anymore. See the Optimisations section of the 3.7 What's New notes:

Method calls are now up to 20% faster due to the bytecode changes which avoid creating bound method instances.

This applies to <expr>.attribute_name(...) call sequences, so an attribute name lookup followed directly by a call, in the same overall expression, provided only positional arguments are used. Special bytecodes are generated that validate that attribute_name resolves to a method name on the class, then calls the underlying function directly with the result of <expr> prepended. Python uses LOAD_METHOD followed by CALL_METHOD opcodes instead of LOAD_ATTR and CALL_FUNCTION opcodes, but falls back to the behaviour of the latter two if the optimisation doesn't apply.

Body:
You are micro-optimising here for no benefit.

Yes, a regular method involves a new method object that is created to handle the binding between function and instance, but that's only a bit of memory (2 pointers plus some Python metadata) used only during the duration of the call or if you stored the bound method *. A staticmethod object doesn't create a new method object, but that's offset by the about the same amount of memory needed for the staticmethod object:

>>> import sys
>>> class Foo:
...     def bar(self): pass
...     @staticmethod
...     def staticbar(): pass
...
>>> sys.getsizeof(Foo().bar)   # bound method object size
64
>>> sys.getsizeof(Foo.__dict__['staticbar'])  # staticmethod size
56

So using a staticmethod object saves you 8 bytes (on Mac OS X, on another OS the byte count could differ slightly), but you don't usually keep a bound method (you'd use instance.method(), which creates the method object then discards it again after calling).

So, unless you are storing a large number of bound methods, this is not going to make enough difference to justify making your code unreadable by passing in the instance manually everywhere.

* Note that as of Python 3.7, for common cases Python doesn't even create method objects anymore. See the Optimisations section of the 3.7 What's New notes:

Method calls are now up to 20% faster due to the bytecode changes which avoid creating bound method instances.

This applies to <expr>.attribute_name(...) call sequences, so an attribute name lookup followed directly by a call, in the same overall expression, provided only positional arguments are used. Special bytecodes are generated that validate that attribute_name resolves to a method name on the class, then calls the underlying function directly with the result of <expr> prepended. Python uses LOAD_METHOD followed by CALL_METHOD opcodes instead of LOAD_ATTR and CALL_FUNCTION opcodes, but falls back to the behaviour of the latter two if the optimisation doesn't apply.


问:
How to install opencv library in python 3.5?
I've created a project in Pycharm IDE. I've used python 3.5, tensorflow library. Now I want to install opencv in this.

I have tried so many videos available on youtube and some tutorials in the internet. But when import open cv in python shell it gives me following error. How can I fix it?

import code

```<code>import cv2
</code>```

Error message

Traceback (most recent call last):
    File "", line 1, in
      import cv2
  ImportError: Module use of python27.dll conflicts with this version of Python.

I have noticed that python 2.7 is used to install opencv. Is it a must o use 2.7 version?

Also as I know tensorflow will not support if I use another version of python(other than 3.5)

答:
Did you download open cv for Python 3? Try this:

Make sure you have numpy installed

Download open cv for Python 3 from here: http://www.lfd.uci.edu/~gohlke/pythonlibs/#opencv
(not sure if this will work with Python 3.5, should work with 3.2)

Run pip install opencv_python-your_verison_here.whl

Body:
I've created a project in Pycharm IDE. I've used python 3.5, tensorflow library. Now I want to install opencv in this.

I have tried so many videos available on youtube and some tutorials in the internet. But when import open cv in python shell it gives me following error. How can I fix it?

import code

import cv2

Error message

Traceback (most recent call last):
    File "", line 1, in
      import cv2
  ImportError: Module use of python27.dll conflicts with this version of Python.

I have noticed that python 2.7 is used to install opencv. Is it a must o use 2.7 version?

Also as I know tensorflow will not support if I use another version of python(other than 3.5)


问:
RegEx question - HTML tag content
I want to replace all "i" character in  with "I" by JavaScript.
(for example:
Hi! it!
 should change to
HI! It!
).
I know I must use regular expressions. but I don't know what I should write.
Can you help me?
Thanks ..

答:
I just answered a similar question which may help you: JQuery/Javascript - Search DOM for text and insert HTML

For this particular case, you can simplify.

UPDATE

I've added a filter parameter to allow you to filter out descendants of particular nodes. This should be a function that takes a single DOM node parameter and returns a Boolean: true to replace text within the node and its descendants and false to ignore the node and its descendants.

```<code>function replaceText(node, regex, replacementText, filter) {
    if (node.nodeType == 3) {
        node.data = node.data.replace(regex, replacementText);
    } else if (!filter || filter(node)) {
        var child = node.firstChild;
        while (child) {
            replaceText(child, regex, replacementText, filter);
            child = child.nextSibling;
        }
    }
}

function scriptAndStyleFilter(node) {
    return node.nodeType != 1 || !/SCRIPT|STYLE/i.test(node.nodeName);
}

replaceText(document.body, /i/g, "I", scriptAndStyleFilter);
</code>```

Title: RegEx question - HTML tag content

Body:
I just answered a similar question which may help you: JQuery/Javascript - Search DOM for text and insert HTML

For this particular case, you can simplify.

UPDATE

I've added a filter parameter to allow you to filter out descendants of particular nodes. This should be a function that takes a single DOM node parameter and returns a Boolean: true to replace text within the node and its descendants and false to ignore the node and its descendants.

function replaceText(node, regex, replacementText, filter) {
    if (node.nodeType == 3) {
        node.data = node.data.replace(regex, replacementText);
    } else if (!filter || filter(node)) {
        var child = node.firstChild;
        while (child) {
            replaceText(child, regex, replacementText, filter);
            child = child.nextSibling;
        }
    }
}

function scriptAndStyleFilter(node) {
    return node.nodeType != 1 || !/SCRIPT|STYLE/i.test(node.nodeName);
}

replaceText(document.body, /i/g, "I", scriptAndStyleFilter);


问:
Can't bind to 'ngIf'
Can't bind to ngIf since it isn't a known property

```<code><AddWrkFrcePopUp *ngIf="showWrkFrcePop === true" (closeWrfFrcePop)="_closeWrkFrcePop()">
</AddWrkFrcePopUp>
</code>```

答:
If you are using RC5 then import this:

```

    import { CommonModule } from '@angular/common';
    import { BrowserModule } from '@angular/platform-browser';

```

and be sure to import CommonModule from the module that is providing your component.

```<code>@NgModule({
   imports: [CommonModule],
   declarations: [MyComponent]
   ...
 })
class MyComponentModule {}
</code>```

Title: Can't bind to 'ngIf'

Body:
Can't bind to ngIf since it isn't a known property

<AddWrkFrcePopUp *ngIf="showWrkFrcePop === true" (closeWrfFrcePop)="_closeWrkFrcePop()">
</AddWrkFrcePopUp>

Body:
If you are using RC5 then import this:

    import { CommonModule } from '@angular/common';
    import { BrowserModule } from '@angular/platform-browser';

and be sure to import CommonModule from the module that is providing your component.

@NgModule({
   imports: [CommonModule],
   declarations: [MyComponent]
   ...
 })
class MyComponentModule {}


问:
SQL request on MS-Access with Like statement seems to be never working
I tried several "Like" syntax on one request, (I'm using VB.NET and a MS-ACCESS 2010 database), and none of them could get any other result than throwing an exception.Why? I'm not having any idea about that.

I did this workaround : Instead of

```<code>SELECT dbFieldDisplayName FROM dbTableName WHERE dbFieldSearchName Like 'A*'
</code>```

(I also tried with 'A%' instead of 'A*')

I Used:

```<code>SELECT dbFieldDisplayName
FROM dbTableName
WHERE dbFieldSearchName >='A' AND dbFieldSearchName <'AZZZ'
</code>```

Does anybody know why my Like statement always triggers exception? Any better workaround ?

Thanks in advance.

答:
Finally, what a strange behaviour of my MS-ACCESS...

I uninstalled all my office components (including MS-ACCESS), and  installed it all again, and now the 'Like' statement works fine, with a % as a wildcard.

The request:

SELECT dbFieldDisplayName FROM dbTableName WHERE dbFieldSearchName Like 'A%'

works now fine, as it was supposed to be working.

Body:
I tried several "Like" syntax on one request, (I'm using VB.NET and a MS-ACCESS 2010 database), and none of them could get any other result than throwing an exception.Why? I'm not having any idea about that.

I did this workaround : Instead of

SELECT dbFieldDisplayName FROM dbTableName WHERE dbFieldSearchName Like 'A*'

(I also tried with 'A%' instead of 'A*')

I Used:

SELECT dbFieldDisplayName
FROM dbTableName
WHERE dbFieldSearchName >='A' AND dbFieldSearchName <'AZZZ'

Does anybody know why my Like statement always triggers exception? Any better workaround ?

Thanks in advance.


问:
Custom JVM Language: Creating workable stack traces?
How do stack traces on the JVM work?

Is it possible to transform classfiles to have stack traces that relate back to the parent language, rather then pseudo java files?

To be specific, could this Mixin Library https://github.com/SpongePowered/Mixin be modified, so that when it overwrites / injects code into methods, that if an error occurred, it would point to the correct mixin pseudo class in the source?

答:
There is no need to have Java source code files at all.

There are only two relevant attributes.

The SourceFile class attribute which specifies the name of the source code file, which doesn’t have to be a .java file.

The LineNumberTable attribute applied to Code attributes, telling how the byte code instructions map to source code lines.

The stack trace just reports the class and method names together with the source file name and line number as reported by the two attributes named above. There is no additional semantic behind it.

These attribute are already sufficient to do step debugging, as the debugger only needs to load the specified file (assuming it to be text based) and highlight the particular line. I already stepped through an XSLT file this way, which had been dynamically compiled to byte code by the XSLT processor. If you want to make local variables inspectable, you also have to add a LocalVariableTable attribute to the code.

I also used them in the way, you intend, to have generated code whose meta information point to the original code which triggered the code generation. It even happens when ordinary Java source code gets compiled, as the synthetic methods generated for lambda expressions have line number tables pointing to the lambda expression within the source code level method defining it.


问:
Scrollbars in TextView
I just didn't want to use ScrollView. So I have a textview with enabled vertical scrollbars.

```<code><TextView
    android:id="@+id/tv_service_ticketinfo_details"
    android:layout_width="fill_parent"
    android:layout_height="150dp"
    android:textColor="@color/black"
    android:autoLink="web"
    android:scrollbars="vertical"
    android:text="empty"
    android:background="@drawable/custom_shape_grey">
</TextView>
</code>```

The problem is, that scrollbars are scrollable only for texts, which contain a web-links. For other texts I see a scrollbar, but can't scroll.

I can't explain it. And you?

UPD:

Another strange thing:
once I set the text with links, then I can replace it by another one without links and the textView stays scrollable

答:
add this in your code(may be in onCreate)

```<code>//textView.setMovementMethod(ScrollingMovementMethod.getInstance());
tv_service_ticketinfo_details.setMovementMethod(ScrollingMovementMethod.getInstance());
</code>```

and test.

Title: Scrollbars in TextView

Body:
I just didn't want to use ScrollView. So I have a textview with enabled vertical scrollbars.

<TextView
    android:id="@+id/tv_service_ticketinfo_details"
    android:layout_width="fill_parent"
    android:layout_height="150dp"
    android:textColor="@color/black"
    android:autoLink="web"
    android:scrollbars="vertical"
    android:text="empty"
    android:background="@drawable/custom_shape_grey">
</TextView>

The problem is, that scrollbars are scrollable only for texts, which contain a web-links. For other texts I see a scrollbar, but can't scroll.

I can't explain it. And you?

UPD:

Another strange thing:
once I set the text with links, then I can replace it by another one without links and the textView stays scrollable

Body:
add this in your code(may be in onCreate)

//textView.setMovementMethod(ScrollingMovementMethod.getInstance());
tv_service_ticketinfo_details.setMovementMethod(ScrollingMovementMethod.getInstance());

and test.


问:
Best way to store EditText data to a file/place to be accessed later?
I have created the example code below to explain myself. I have a few EditText fields that need the data stored as "entries" for later use. My question is, what is the best way to store these three variables to be "listed" in another activity. (liAmount, liAccount, and vID). I was just going to use shared preferences, but even with this, I will have multiple entries on the same EditTexts so I don't really know how to properly serialize them...

```<code>float liAmount;
String liAccount;
String vID;

btnSaveLineItem.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {

        if(etLineItemAmount.length() == 0 || etAccountName.length() == 0) {
            Toast.makeText(NewLineActivity.this, "Fill all fields.", Toast.LENGTH_LONG).show();
        } else {
            saveLineItem();
            createVID();
        }

    }
});

public void createVID(){
    vID = String.valueOf(liAccount.charAt(0) + liAccount.charAt(1) + liAccount.charAt(2) + liAmount);
}

public void saveLineItem(){
    liAmount = Float.valueOf(etLineItemAmount.getText().toString());
    liAccount = etAccountName.getText().toString();
}
</code>```

EDIT: I should clarify, I do want these data files to be stored long-term. These are essentially going to be used in a separate activity file to show a list of all previous entries.

答:
You can use SharedPreferences to store the data with a key value pair and then later retrieve the same when required. Here's a sample code.

```<code>Editor editor = sharedpreferences.edit();
editor.putString("key", "value");
editor.commit();
</code>```

To Get the stored value use something like this

```<code>SharedPreferences prefs = getSharedPreferences(this);
String restoredText = prefs.getString("key", null);
</code>```

Body:
I have created the example code below to explain myself. I have a few EditText fields that need the data stored as "entries" for later use. My question is, what is the best way to store these three variables to be "listed" in another activity. (liAmount, liAccount, and vID). I was just going to use shared preferences, but even with this, I will have multiple entries on the same EditTexts so I don't really know how to properly serialize them...

float liAmount;
String liAccount;
String vID;

btnSaveLineItem.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {

        if(etLineItemAmount.length() == 0 || etAccountName.length() == 0) {
            Toast.makeText(NewLineActivity.this, "Fill all fields.", Toast.LENGTH_LONG).show();
        } else {
            saveLineItem();
            createVID();
        }

    }
});

public void createVID(){
    vID = String.valueOf(liAccount.charAt(0) + liAccount.charAt(1) + liAccount.charAt(2) + liAmount);
}

public void saveLineItem(){
    liAmount = Float.valueOf(etLineItemAmount.getText().toString());
    liAccount = etAccountName.getText().toString();
}

EDIT: I should clarify, I do want these data files to be stored long-term. These are essentially going to be used in a separate activity file to show a list of all previous entries.

Body:
You can use SharedPreferences to store the data with a key value pair and then later retrieve the same when required. Here's a sample code.

Editor editor = sharedpreferences.edit();
editor.putString("key", "value");
editor.commit();

To Get the stored value use something like this

SharedPreferences prefs = getSharedPreferences(this);
String restoredText = prefs.getString("key", null);


问:
Return parent workbook range of particular sheet
using vlookup function one workbook to another workbook, this code " & Rg.Parent.Parent.Name & "!" & Rg.Address(ReferenceStyle:=xlR1C1) return the range from first sheet of the wb2, eventhough have set the rage (Rg) from third sheet of wb2 Set Rg = wb2.Sheets(3).Range("A3:Z10000") .. why the rage (Rg) not returning of the third sheet of wb2 and how to return the rage of specific sheet of wb2 ?

```<code>Sub Vlkuprangcall()
Dim strColumn As String
Dim Rg As Range
Dim wb2 As Workbook

Set wb2 = Workbooks.Open("C:\Users\ashokkumar.d\Desktop\Test\IC Raphael\Janalakshmi\MIS\MIS.xlsx")
Set Rg = wb2.Sheets(3).Range("A3:Z10000")

Application.Workbooks(2).Activate
With ActiveSheet
    a = ActiveCell.Column
    lastrow = 100
    strColumn = Split(ActiveCell.Address, "$")(1)
    ActiveCell.FormulaR1C1 = "=vlookup(RC[-15]," & Rg.Parent.Parent.Name & "!" & Rg.Address(ReferenceStyle:=xlR1C1) & ",6,False)"
    ActiveCell.AutoFill Destination:=Range(ActiveCell, Range(strColumn & lastrow))

end Sub
</code>```

答:
Using the Address is easier, but to address your question, Rg.Parent or Rg.Worksheet gets a reference to the worksheet containing the range. You used Rg.Parent.Parent which is a reference to the workbook. You need both for the formula, assuming you are using a cross-workbook formula.

```<code>ActiveCell.FormulaR1C1 = "=vlookup(RC[-15],'[" & Rg.Parent.Parent.Name & "]" & rg.Worksheet.Name & "'!" & Rg.Address(ReferenceStyle:=xlR1C1) & ",6,False)"
</code>```

Body:
using vlookup function one workbook to another workbook, this code " & Rg.Parent.Parent.Name & "!" & Rg.Address(ReferenceStyle:=xlR1C1) return the range from first sheet of the wb2, eventhough have set the rage (Rg) from third sheet of wb2 Set Rg = wb2.Sheets(3).Range("A3:Z10000") .. why the rage (Rg) not returning of the third sheet of wb2 and how to return the rage of specific sheet of wb2 ?

Sub Vlkuprangcall()
Dim strColumn As String
Dim Rg As Range
Dim wb2 As Workbook

Set wb2 = Workbooks.Open("C:\Users\ashokkumar.d\Desktop\Test\IC Raphael\Janalakshmi\MIS\MIS.xlsx")
Set Rg = wb2.Sheets(3).Range("A3:Z10000")

Application.Workbooks(2).Activate
With ActiveSheet
    a = ActiveCell.Column
    lastrow = 100
    strColumn = Split(ActiveCell.Address, "$")(1)
    ActiveCell.FormulaR1C1 = "=vlookup(RC[-15]," & Rg.Parent.Parent.Name & "!" & Rg.Address(ReferenceStyle:=xlR1C1) & ",6,False)"
    ActiveCell.AutoFill Destination:=Range(ActiveCell, Range(strColumn & lastrow))

end Sub

Body:
Using the Address is easier, but to address your question, Rg.Parent or Rg.Worksheet gets a reference to the worksheet containing the range. You used Rg.Parent.Parent which is a reference to the workbook. You need both for the formula, assuming you are using a cross-workbook formula.

ActiveCell.FormulaR1C1 = "=vlookup(RC[-15],'[" & Rg.Parent.Parent.Name & "]" & rg.Worksheet.Name & "'!" & Rg.Address(ReferenceStyle:=xlR1C1) & ",6,False)"


问:
Why doesn't this ES6 default argument value give the desired result?
I found this ES6 code in a book:

```<code>let value = 5;

function getValue() {
    return value++;
}

function add(first, second = getValue()) {
    return first + second;
}

console.log(add(1, 1));     // 2
console.log(add(1));        // 6
</code>```

Why does running console.log(add(1)); return 6 as the value, which means it is taking the parameter second as 5 although my code explicitly specifies that the getValue function should return value++ - which means the first time it is run, the getValue function should be returning 6 and add should be returning 7. I am running this code in the Firefox console - am I missing something?

答:
Hi this is called 'Default value' for parameters. It's mean that you can set Default value for each parameters in function definition .

```<code>function add(first, second = getValue()) {
    return first + second;
}
</code>```

in this case 'second = getValue()', 'getValue()' is defulat value for 'second 'parameter.

when you do

```<code>console.log(add(1, 1));     // 2
</code>```

because

first==>1
second==>1

```<code>console.log(add(1));        // 6
</code>```

because
first==>1
second==>getValue()  ===> 6

Body:
I found this ES6 code in a book:

let value = 5;

function getValue() {
    return value++;
}

function add(first, second = getValue()) {
    return first + second;
}

console.log(add(1, 1));     // 2
console.log(add(1));        // 6

Why does running console.log(add(1)); return 6 as the value, which means it is taking the parameter second as 5 although my code explicitly specifies that the getValue function should return value++ - which means the first time it is run, the getValue function should be returning 6 and add should be returning 7. I am running this code in the Firefox console - am I missing something?

Body:
Hi this is called 'Default value' for parameters. It's mean that you can set Default value for each parameters in function definition .

function add(first, second = getValue()) {
    return first + second;
}

in this case 'second = getValue()', 'getValue()' is defulat value for 'second 'parameter.

when you do

console.log(add(1, 1));     // 2

because

first==>1
second==>1

console.log(add(1));        // 6

because
first==>1
second==>getValue()  ===> 6


问:
Foreground service not receiving location updates in Doze mode in Android O
I have a foreground service that needs to get a single location update.

It is started by a specific broadcast, and upon starting it simply does a request on our backend. When it receives another broadcast, it requests a location update (once), does another backend request and then stops itself.

Edit: to clarify, the service itself does the location updates and backend requests. It is independent from the main app in that regard.

This works well on Lollipop and Marshmallow, both when the phone is awake or in Doze mode. But for some reason, on Android O the service never gets location updates when in Doze mode. Networking works fine as its first request goes through in both situations. Also, if I wake up the phone while the location request it running, it will get the update. Same if I put it in maintenance window.

Android O does introduce some limitations on background location but as the page mentions, the foreground app behavior (app visible or foreground service running) should be preserved and be similar to previous versions of Android.

Is this an issue in the developer preview or a restriction that I missed?

答:
Take a look on LocationUpdatesForegroundService Sample: Code Samples for Android O, maybe you do something wrong.

LocationUpdatesForegroundService Sample - Shows how to use a
  foreground service to get location updates when the app activities are
  not visible. For apps running on Android O (even apps that target
  Android 7.0 (API level 24) or lower), background updates are limited
  to only a few times per hour. Using a foreground service is a way to
  receive more frequent updates.

Get it on GitHub: Java


问:
Is there any alternate to acquire dependencies without using POM.xml?
My question is, I don't want to write XML code for dependencies in the POM.xml again and again.
For example, I want to use the log4j JAR in my project. instead of writing XML code is there any option to download the related JAR files?

答:
Alternate method is downloading the jars from sites like maven or java2s.com and add them to your build path.
You can add a jar in Eclipse by right-clicking on the Project → Build Path → Configure Build Path. Under Libraries tab, click Add Jars or Add External JARs and give the Jar.
Hope that helps


问:
PHP/MySQL Show first X results, hide the rest
Does anyone know how to bring in all of a mysql tables' results, only show the first X, (say 10), and then hide the rest using jquery? I just need to know how to show only the first X results in one page, then the rest in a seperate page using href.

My aim is to only show the first 10 results, but provide a link at the bottom of the page allowing the user to show all of the results. Was thinking the hyperlink could just re-execute the query but thought it would be easier to show/hide using jquery.Thanks

答:
It might be "easier", but it's a lot less resource efficient to load all the data (and then optionally show it) in the manner you're describing.

I'd really recommend using multiple queries (perhaps via Ajax/lazy loading) rather than using the approach you're discussing.


答:
using split and a switch would be a lot easier</p>

```<code>    String name = "Mary Jane Lee";
    String arr[] = name.split (" ");

    switch (arr.length) {
        case 1:
            System.out.println(name);
            break;
        case 2:
            System.out.println(arr[1] + ", " + arr[0]);
            break;
        default:
            System.out.println(arr[2] + ", " + arr[0] + " " + arr[1]);
    }
</code>```

Title: Beginner Java - Changing String from First Middle Last to Last, First Middle

Body:
Trying to work out a homework problem that demands:
Changes a name so that the last name comes first.
Example: "Mary Jane Lee" will return "Lee, Mary Jane".
If name has no spaces, it is returned without change.

After doing some research it seems I can do this with the Split method, but we've not learned that yet.

The thing is I've worked out the code and it seems to work when spaces
 and a full name is entered, but when there's no middle name or no spaces to separate the character, I get the error:

when the name entered is simply: Harry Smith

java.lang.StringIndexOutOfBoundsException: String index out of range: -7

and

java.lang.StringIndexOutOfBoundsException: String index out of range: -1

when the name is Sarah

This is my code, but I'm not sure how to fix it:

public class Names {
    public static String lastNameFirst(String name) {
        int firstIndex = name.indexOf(" ");
        int secondIndex = name.indexOf(" ", firstIndex + 1);
        String firstName = name.substring(0, name.indexOf(" "));
        String middleName = name.substring(firstIndex + 1, secondIndex);
        String lastName = name.substring(secondIndex + 1);
        String result = "";
        result = lastName + ", " + firstName + " " + middleName;
        return result;
    }
}

Thanks in advance!!

Body:
using split and a switch would be a lot easier

    String name = "Mary Jane Lee";
    String arr[] = name.split (" ");

    switch (arr.length) {
        case 1:
            System.out.println(name);
            break;
        case 2:
            System.out.println(arr[1] + ", " + arr[0]);
            break;
        default:
            System.out.println(arr[2] + ", " + arr[0] + " " + arr[1]);
    }


问:
ASP.Net redirecting to local host after authentication VSTS CI Build
I have a build task setup for a Development branch in my VSTS which publishes my ASP.Net Web application to a specific (dev) deployment slot.

The application uses AAD Authentication. When debugging locally i am able to authenticate with my AAD and am then redirected to the main page (https://localhost:44354/)

When i build to the slot and attempt to login the exact same happens, upon authentication i am redirected to https://localhost:44354/

I have had a similar issue in the past when using one click deployment which was solved by specifying the domain in the publish wizard as explained here
This specific build is for a development branch which as stated above, builds to the Development Slot (with a slightly different URL to the production site)

So the question is, how can i specify this setting within my build configuration in VSTS to accommodate for Development and Production slots?

Or is there an alternative method?

Thanks

答:
You can use Azure App Service Deploy task in your build definition to deploy the app to development slot.

After specify Azure subscription and Azure App service, you can select Deploy to slot to set the slot you want to deploy.

Note: If the option deploy to slot is not selected, then the Azure App Service will be deployed to the Production slot.


问:
EntityFramework is caching old outdated data, and I don't know how to stop it
I'm creating a communication app  (using .net core 1.1 mvc and signalr/knockout ) and I have the following pocos:

room
user
post
postRevision

posts is a container of postRevision, which for convenience has a reference to the latest revision

everything else is as you would imagine it. I'm omitting a lot of details obviously.

My user has an avatar property.
When I update the user's avatar I delete their old avatar, and update to the new one. Then in the room the posts (postRevisions really) by said user no-longer have a friendly avatar, now they have a broken image icon. I'm still developing, so this is not happening in a multi-user scenario. This is just me jumping from the mvc controller that changes avatars to the signalr/knockout page that displays posts.

When I stop and run the server the images are fixed.
It looks like entity framework is caching the results and not updating.

in my controller I have this code snippet:

```<code>user.Avatar = imageId.ToString();
_context.Entry(user).State = EntityState.Modified;
await _context.SaveChangesAsync();

_context.Entry(user).State = EntityState.Detached;
return new JsonResult(new { status = "sucess" });
</code>```

in my hub I have this snippet for fetching a page of posts:

```<code>data =  await _context.Posts
    .Include(x=> x.LatestRevision)
    .Include(x => x.LatestRevision.Blob)
    .Include(x => x.LatestRevision.Creator)
    .Where(x=> x.Room.Id == roomId
        && x.Id < currentPostId)
    .OrderByDescending(x => x.Id)
    .Take(_roomPageSize).ToListAsync();
</code>```

I'm not sure how to tell the signalr context to update, especially since that page isn't open, and in theory that page is out of scope, so that context isn't even created yet.
This is the relevant portion of my Startup.cs

```<code>services.AddDbContext<ApplicationDbContext>(options =>
    options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

services.AddIdentity<ApplicationUser, IdentityRole>()
    .AddEntityFrameworkStores<ApplicationDbContext>();
</code>```

答:
I wound up squashing this by adding

```<code>ServiceLifetime.Transient
</code>```

to my AddDbContext call, making the DB context have a transient lifespan. So a new context is created every time it is requested from the service container.

https://learn.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection?view=aspnetcore-3.1#service-lifetimes

```<code>services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")), ServiceLifetime.Transient);
</code>```

Body:
I'm creating a communication app  (using .net core 1.1 mvc and signalr/knockout ) and I have the following pocos:

room
user
post
postRevision

posts is a container of postRevision, which for convenience has a reference to the latest revision

everything else is as you would imagine it. I'm omitting a lot of details obviously.

My user has an avatar property.
When I update the user's avatar I delete their old avatar, and update to the new one. Then in the room the posts (postRevisions really) by said user no-longer have a friendly avatar, now they have a broken image icon. I'm still developing, so this is not happening in a multi-user scenario. This is just me jumping from the mvc controller that changes avatars to the signalr/knockout page that displays posts.

When I stop and run the server the images are fixed.
It looks like entity framework is caching the results and not updating.

in my controller I have this code snippet:

user.Avatar = imageId.ToString();
_context.Entry(user).State = EntityState.Modified;
await _context.SaveChangesAsync();

_context.Entry(user).State = EntityState.Detached;
return new JsonResult(new { status = "sucess" });

in my hub I have this snippet for fetching a page of posts:

data =  await _context.Posts
    .Include(x=> x.LatestRevision)
    .Include(x => x.LatestRevision.Blob)
    .Include(x => x.LatestRevision.Creator)
    .Where(x=> x.Room.Id == roomId
        && x.Id < currentPostId)
    .OrderByDescending(x => x.Id)
    .Take(_roomPageSize).ToListAsync();

I'm not sure how to tell the signalr context to update, especially since that page isn't open, and in theory that page is out of scope, so that context isn't even created yet.
This is the relevant portion of my Startup.cs

services.AddDbContext<ApplicationDbContext>(options =>
    options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

services.AddIdentity<ApplicationUser, IdentityRole>()
    .AddEntityFrameworkStores<ApplicationDbContext>();

Body:
I wound up squashing this by adding

ServiceLifetime.Transient

to my AddDbContext call, making the DB context have a transient lifespan. So a new context is created every time it is requested from the service container.

https://learn.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection?view=aspnetcore-3.1#service-lifetimes

services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")), ServiceLifetime.Transient);


问:
unchecked checkbox with "Input::old()"
I'm creating a checkbox in a view:

```<code>Form::checkbox('test', 'true', Input::old('test', true));
</code>```

After unchecking the box, submitting the form and being redirected back:

```<code>return Redirect::back()->withInput()->withErrors($validation);
</code>```

The checkbox is still checked - presumably because 'test' doesn't exist in "Input::old" so it is reverting back to the default value.

Any suggestions on how best to achieve this?

Edit:

I've come up with a somewhat hacky way of getting the results I want:

```<code>$isChecked = true; // The default state
// Check if the form has been returned "withInput"
if(Input::old())
{
    $isChecked = Input::old('test', false); // If the field has old data available use that, otherwise it is unchecked
}
echo Form::checkbox('test', 'true', $isChecked);
</code>```

I'll write this into a function for reuse, but it seems a bit painful so any comments/suggestions would be great

Edit 2
Sorry if not clear - to clarify:

Form is loaded with checkbox checked

I uncheck the checkbox and submit the form

The form doesn't validate so I'm returned to the form

The checkbox has re-checked itself - I would expect it to be unchecked, as per the user submitted data

I assume this happens because if a checkbox isn't checked the element isn't included in the post data

答:
I had the same problem. I end up with creating this helper function:

```<code>function is_checked(string $name, $value, $default) : string
{
    $current_defaults = Input::old() ? old($name, 0) : $default;
    return ($value == $current_defaults) ? 'checked' : '';
}

<input type="checkbox" name="is_acrive" value="1"
       {{ is_checked('is_active', 1, $user->is_active) }}>
</code>```

Multiple checkbox version:

```<code>function is_checked_multiple(string $name, $value, $defaults) : string
{
    $current_defaults = Input::old() ? old($name, []) : (array)$defaults;
    return in_array($value, $current_defaults) ? 'checked' : '';
}

@foreach ($plans as $plan)
    <input type="checkbox" name="plans[]" value="{{ $plan->id }}"
           {{ is_checked_multiple('plans', $plan->id, $user->plans->pluck('id') }}>
@endforeach
</code>```

Title: unchecked checkbox with "Input::old()"

Body:
I'm creating a checkbox in a view:

Form::checkbox('test', 'true', Input::old('test', true));

After unchecking the box, submitting the form and being redirected back:

return Redirect::back()->withInput()->withErrors($validation);

The checkbox is still checked - presumably because 'test' doesn't exist in "Input::old" so it is reverting back to the default value.

Any suggestions on how best to achieve this?

Edit:

I've come up with a somewhat hacky way of getting the results I want:

$isChecked = true; // The default state
// Check if the form has been returned "withInput"
if(Input::old())
{
    $isChecked = Input::old('test', false); // If the field has old data available use that, otherwise it is unchecked
}
echo Form::checkbox('test', 'true', $isChecked);

I'll write this into a function for reuse, but it seems a bit painful so any comments/suggestions would be great

Edit 2
Sorry if not clear - to clarify:

Form is loaded with checkbox checked

I uncheck the checkbox and submit the form

The form doesn't validate so I'm returned to the form

The checkbox has re-checked itself - I would expect it to be unchecked, as per the user submitted data

I assume this happens because if a checkbox isn't checked the element isn't included in the post data

Body:
I had the same problem. I end up with creating this helper function:

function is_checked(string $name, $value, $default) : string
{
    $current_defaults = Input::old() ? old($name, 0) : $default;
    return ($value == $current_defaults) ? 'checked' : '';
}

<input type="checkbox" name="is_acrive" value="1"
       {{ is_checked('is_active', 1, $user->is_active) }}>

Multiple checkbox version:

function is_checked_multiple(string $name, $value, $defaults) : string
{
    $current_defaults = Input::old() ? old($name, []) : (array)$defaults;
    return in_array($value, $current_defaults) ? 'checked' : '';
}

@foreach ($plans as $plan)
    <input type="checkbox" name="plans[]" value="{{ $plan->id }}"
           {{ is_checked_multiple('plans', $plan->id, $user->plans->pluck('id') }}>
@endforeach


问:
How to validate email address by domain using PHP?
I want to validate the e-mail domain using php, because some users trying to submit contact form using dummy email ids like: aa@bb.com</p>

答:
If you don't want to go through all the hassle of doing the validations by yourself, just use the free API plan from MailboxValidator.

They have some sample codes to help you with integration.

http://www.mailboxvalidator.com/api-single-validation

```<code><?php
$apiKey = 'Enter_License_Key';
$params['format']           = 'json';
$params['email']     = 'Enter_Email';

$query = '';

foreach($params as $key=>$value){
    $query .= '&' . $key . '=' . rawurlencode($value);
}

$try = 0;
do {
    ////////////
    //For https request, please make sure you have enabled php_openssl.dll extension.
    //
    //How to enable https
    //- Uncomment ;extension=php_openssl.dll by removing the semicolon in your php.ini, and restart the apache.
    //
    //In case you have difficulty to modify the php.ini, you can always make the http request instead of https.
    ////////////
    $result = file_get_contents('https://api.mailboxvalidator.com/v1/validation/single?key=' . $apiKey . $query);
} while(!$result && $rty++ < 3);

$data = json_decode($result);

print_r($data);
?>
</code>```

Body:
If you don't want to go through all the hassle of doing the validations by yourself, just use the free API plan from MailboxValidator.

They have some sample codes to help you with integration.

http://www.mailboxvalidator.com/api-single-validation

<?php
$apiKey = 'Enter_License_Key';
$params['format']           = 'json';
$params['email']     = 'Enter_Email';

$query = '';

foreach($params as $key=>$value){
    $query .= '&' . $key . '=' . rawurlencode($value);
}

$try = 0;
do {
    ////////////
    //For https request, please make sure you have enabled php_openssl.dll extension.
    //
    //How to enable https
    //- Uncomment ;extension=php_openssl.dll by removing the semicolon in your php.ini, and restart the apache.
    //
    //In case you have difficulty to modify the php.ini, you can always make the http request instead of https.
    ////////////
    $result = file_get_contents('https://api.mailboxvalidator.com/v1/validation/single?key=' . $apiKey . $query);
} while(!$result && $rty++ < 3);

$data = json_decode($result);

print_r($data);
?>


问:
Krakenex API multiple pairs query
I am trying to use the Krakenex python library to query the order book for multiple currency pairs at once. When I do it for a single currency is works, like this:

```<code>con = krakenex.API()
con.load_key('kraken.key')
con.query_public('Depth', {'pair':'GNOETH'})
</code>```

However, if I do:

```<code>con = krakenex.API()
con.load_key('kraken.key')
con.query_public('Depth', {'pair':['GNOETH', 'GNOEUR']})
</code>```

I get {'error': ['EQuery:Unknown asset pair']}. I assume that the syntax is incorrect but can't figure out the correct one. This is the first time that I use an API and the example provided are not covering enough info yet.

答:
Spent a lot of time trying different combos, finally figured it out.

try con.query_public('Depth', {'pair':'GNOETH, GNOEUR'})

Title: Krakenex API multiple pairs query

Body:
I am trying to use the Krakenex python library to query the order book for multiple currency pairs at once. When I do it for a single currency is works, like this:

con = krakenex.API()
con.load_key('kraken.key')
con.query_public('Depth', {'pair':'GNOETH'})

However, if I do:

con = krakenex.API()
con.load_key('kraken.key')
con.query_public('Depth', {'pair':['GNOETH', 'GNOEUR']})

I get {'error': ['EQuery:Unknown asset pair']}. I assume that the syntax is incorrect but can't figure out the correct one. This is the first time that I use an API and the example provided are not covering enough info yet.


问:
How to upload picture on c9 server via website
Im using IDE Cloud9 and Angular, I can't figure out how do I upload pictures on my c9, like, I have input, so when user uploads the image, it goes on c9 server and keeps in some 'uploads' folder</p>

答:
Omni,
you can use multer npm for uploading file with angular js and node api. Please refer below link for more details,

https://www.npmjs.com/package/multer

nodejs + multer + angularjs for uploading without redirecting

https://ciphertrick.com/2015/12/07/file-upload-with-angularjs-and-nodejs/


问:
Prevent page reload when blank link is clicked?
I have a web page to download files using a button.But for some cases the files does not exit and download links are blank...So whenever the user clicks the link page just reloads.It would have been great if i could somehow disable the page reload and display an alert that says file not yet available..

This is the download link button code.row["slink"] gives the download link and may become empty sometime.

```<code>'<a href="'+row["slink"]+'"><button type="button" class="btn btn-info " data-row-id="' + row.id + '">Download</buttn></a> ';
</code>```

答:
Check if row['slink'] is present, else replace href with javascript:alert(...)(This won't do page reload for blank href, and show an alert):

```<code>var href = row["slink"].trim().length > 0 ? row["slink"] : "javascript:alert('File Not Yet Available')"

'<a href="'+href+'"><button type="button" class="btn btn-info " data-row-id="' + row.id + '">Download</buttn></a> ';
</code>```

Body:
I have a web page to download files using a button.But for some cases the files does not exit and download links are blank...So whenever the user clicks the link page just reloads.It would have been great if i could somehow disable the page reload and display an alert that says file not yet available..

This is the download link button code.row["slink"] gives the download link and may become empty sometime.

'<button type="button" class="btn btn-info " data-row-id="' + row.id + '">Download</buttn> ';

Body:
Check if row['slink'] is present, else replace href with javascript:alert(...)(This won't do page reload for blank href, and show an alert):

var href = row["slink"].trim().length > 0 ? row["slink"] : "javascript:alert('File Not Yet Available')"

'<a href="'+href+'"><button type="button" class="btn btn-info " data-row-id="' + row.id + '">Download</buttn></a> ';


答: I'd do this with a LIMIT statement in the Select-statement of your SQL query. In most cases there's no need to send all the data to the client and then let javascript hide the data you don't wanna show. </p>

Title: PHP/MySQL Show first X results, hide the rest

Body:
Does anyone know how to bring in all of a mysql tables' results, only show the first X, (say 10), and then hide the rest using jquery? I just need to know how to show only the first X results in one page, then the rest in a seperate page using href.

My aim is to only show the first 10 results, but provide a link at the bottom of the page allowing the user to show all of the results. Was thinking the hyperlink could just re-execute the query but thought it would be easier to show/hide using jquery.Thanks


问:
Haxe - How do you implement async await for Flash Targets
I currently have this code:

```<code>package sage.sys;

import com.dongxiguo.continuation.Async;

#if flash
import flash.net.URLLoader;
import flash.net.URLRequest;
import flash.net.URLLoaderDataFormat;
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.events.SecurityErrorEvent;
#end

class FileSystem implements Async
{
    public static function fetchText(url:String, callback:String->Void) : Void
    {
        var urlLoader = new URLLoader();
        var onLoaderError = function(e : Event) : Void {
        callback(e.type);
    };

    urlLoader.addEventListener(Event.COMPLETE, function(_) : Void {
        callback(Std.string(urlLoader.data));
    });

    urlLoader.addEventListener(IOErrorEvent.IO_ERROR, onLoaderError);
    urlLoader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onLoaderError);

    try {
        urlLoader.dataFormat = URLLoaderDataFormat.TEXT;
        urlLoader.load(new URLRequest(url));
    }
    catch (e : Dynamic)
    {
        callback(Std.string(e));
    }
}

@async
public static function fetch(url:String):String
{
    var result = @await fetchText(url);
    return result;
}
}
</code>```

When I try to run it, it doesn't wait at the await, and returns from the function. How can I make the @await actually enforce itself and and stop running outside the function till the value is resolved from the async call?

Lib used: https://github.com/proletariatgames/haxe-continuation

答:
How did you use the fetch function?

I suppose you should put a callback to it:

FileSystem.fetch(url, function(result) trace(result));

The fetch call itself should return immediately, because it is async and the result will be passed to the callback.

I don't think it is possible to make flash block at the fetch call.

Body:
I currently have this code:

package sage.sys;

import com.dongxiguo.continuation.Async;

#if flash
import flash.net.URLLoader;
import flash.net.URLRequest;
import flash.net.URLLoaderDataFormat;
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.events.SecurityErrorEvent;
#end

class FileSystem implements Async
{
    public static function fetchText(url:String, callback:String->Void) : Void
    {
        var urlLoader = new URLLoader();
        var onLoaderError = function(e : Event) : Void {
        callback(e.type);
    };

    urlLoader.addEventListener(Event.COMPLETE, function(_) : Void {
        callback(Std.string(urlLoader.data));
    });

    urlLoader.addEventListener(IOErrorEvent.IO_ERROR, onLoaderError);
    urlLoader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onLoaderError);

    try {
        urlLoader.dataFormat = URLLoaderDataFormat.TEXT;
        urlLoader.load(new URLRequest(url));
    }
    catch (e : Dynamic)
    {
        callback(Std.string(e));
    }
}

@async
public static function fetch(url:String):String
{
    var result = @await fetchText(url);
    return result;
}
}

When I try to run it, it doesn't wait at the await, and returns from the function. How can I make the @await actually enforce itself and and stop running outside the function till the value is resolved from the async call?

Lib used: https://github.com/proletariatgames/haxe-continuation


问:
Preemptive authorization in Delphi with Indy or Soap
I would like to make a preemptive authorization to a server, but I cannot find any solution for this in Delphi.
Please share your solution if You have one.

```<code>HTTP/1.1 401 Authorization Required
<!doctype html public "-//IETF//DTD HTML 2.0//EN">
<html>
    <head><title>401 Authorization Required</title></head>
    <body>
        <h1> 401 Authorization Required </h1>
        <hr>
        <address>SQLAnywhere/12.0.1.4436</address>
    </body>
</html>
</code>```

Regards, Tamas

答: The problem was i got a bad user name and pwd for the project so its solved now :)</p>

Body:
I would like to make a preemptive authorization to a server, but I cannot find any solution for this in Delphi.
Please share your solution if You have one.

HTTP/1.1 401 Authorization Required
<!doctype html public "-//IETF//DTD HTML 2.0//EN">

    <title>401 Authorization Required</title>

 401 Authorization Required

        <address>SQLAnywhere/12.0.1.4436</address>

Regards, Tamas


问:
Rails + PostgreSQL + rbenv-vars: fe_sendauth: no password supplied using environment variables
I'm working on a Rails project which uses PostgreSQL and I want to store the database login details in a file and access them with environment variables using rbenv-vars. I'm running Ubuntu 16.10.

Considering the following files:

pg_hba.conf

```<code># Database administrative login by Unix domain socket
local   all             postgres                                peer

# TYPE  DATABASE        USER            ADDRESS                 METHOD

# "local" is for Unix domain socket connections only
local   all             all                                     md5
# IPv4 local connections:
host    all             all             127.0.0.1/32            md5
# IPv6 local connections:
host    all             all             ::1/128                 md5
# Allow replication connections from localhost, by a user with the
# replication privilege.
#local   replication     postgres                                peer
#host    replication     postgres        127.0.0.1/32            md5
#host    replication     postgres        ::1/128                 md5
</code>```

database.yml

```<code>default: &default
  adapter: postgresql
  encoding: unicode
  host: localhost
  pool: 5
  username: consul
  password: <% ENV['CONSUL_DATABASE_PASSWORD'] %>
</code>```

.rbenv-vars

```<code>SECRET_KEY_BASE=(secret key)
CONSUL_DATABASE_PASSWORD=(database password)
</code>```

When I try to create the database for the project using the rake db:create command I get this error:

```<code>fe_sendauth: no password supplied
</code>```

I tried storing the password in cleartext and it works, but as you can imagine, I don't want to do that.

答:
fe_sendauth: no password supplied

```<code><% ENV['CONSUL_DATABASE_PASSWORD'] %>
</code>```

should be

```<code><%= ENV['CONSUL_DATABASE_PASSWORD'] %>
</code>```

Body:
I'm working on a Rails project which uses PostgreSQL and I want to store the database login details in a file and access them with environment variables using rbenv-vars. I'm running Ubuntu 16.10.

Considering the following files:

pg_hba.conf

# Database administrative login by Unix domain socket
local   all             postgres                                peer

# TYPE  DATABASE        USER            ADDRESS                 METHOD

# "local" is for Unix domain socket connections only
local   all             all                                     md5
# IPv4 local connections:
host    all             all             127.0.0.1/32            md5
# IPv6 local connections:
host    all             all             ::1/128                 md5
# Allow replication connections from localhost, by a user with the
# replication privilege.
#local   replication     postgres                                peer
#host    replication     postgres        127.0.0.1/32            md5
#host    replication     postgres        ::1/128                 md5

database.yml

default: &default
  adapter: postgresql
  encoding: unicode
  host: localhost
  pool: 5
  username: consul
  password: <% ENV['CONSUL_DATABASE_PASSWORD'] %>

.rbenv-vars

SECRET_KEY_BASE=(secret key)
CONSUL_DATABASE_PASSWORD=(database password)

When I try to create the database for the project using the rake db:create command I get this error:

fe_sendauth: no password supplied

I tried storing the password in cleartext and it works, but as you can imagine, I don't want to do that.

Body:
fe_sendauth: no password supplied

<% ENV['CONSUL_DATABASE_PASSWORD'] %>

should be

<%= ENV['CONSUL_DATABASE_PASSWORD'] %>