date
stringlengths 10
10
| nb_tokens
int64 60
629k
| text_size
int64 234
1.02M
| content
stringlengths 234
1.02M
|
---|---|---|---|
2018/03/19 | 1,258 | 5,247 | <issue_start>username_0: I have been trying to write an MsBuild task to automatically get Nuget packages from a feed url and automatically update the packages.config to update to the latest version.
```
// ---- Download and install a package at a desired path ----
var sourceUri = new Uri("FEED URL");
// ---- Update the ‘packages.config’ file ----
var packageReferenceFile = new PackageReferenceFile("../../packages.config");
string packagesPath = "../../packages";
IPackageRepository sourceRepository = PackageRepositoryFactory.Default.CreateRepository(sourceUri.ToString());
PackageManager packageManager = new PackageManager(sourceRepository, packagesPath);
foreach (var sourcePackage in sourceRepository.GetPackages().Where(x => x.IsLatestVersion))
{
if (!packageReferenceFile.EntryExists(sourcePackage.Id + " " + sourcePackage.Version, sourcePackage.Version))
{
var oldPackage = packageReferenceFile.GetPackageReferences().FirstOrDefault(x => x.Id.Contains(sourcePackage.Id));
if (oldPackage != null)
{
packageReferenceFile.DeleteEntry(oldPackage.Id, oldPackage.Version);
}
packageManager.InstallPackage(sourcePackage.Id, SemanticVersion.Parse(sourcePackage.Version.ToFullString()));
// Get the target framework of the current project to add --> targetframework="net452" attribute in the package.config file
var currentTargetFw = Assembly.GetExecutingAssembly()
.GetCustomAttributes(typeof(TargetFrameworkAttribute), false);
var targetFrameworkAttribute = ((TargetFrameworkAttribute[]) currentTargetFw).FirstOrDefault();
// Update the packages.config file
packageReferenceFile.AddEntry(sourcePackage.GetFullName(),
SemanticVersion.Parse(sourcePackage.Version.ToFullString()), false,
new FrameworkName(targetFrameworkAttribute.FrameworkName));
}
}
```
This is working fine as a console app and is automatically reading the file correctly and updating the necessary references.
When i try to run this as an MsBuild task I keep running into errors.
* An error has occurred during compilation. c:\Users\user\AppData\Local\Temp\dkkg20ya.0.cs(22,11) : error CS0246: The type or namespace name 'NuGet' could not be found (are you missing a using directive or an assembly reference?)
* The task factory "CodeTaskFactory" could not be loaded from the assembly "C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\15.0\Bin\Microsoft.Build.Tasks.v15.0.dll". The task factory must return a value for the "TaskType" property.
This is the code I have put in the csproj (also moved to the nuget.targets to test)
```
`try {
// ---- Download and install a package at a desired path ----
var sourceUri = new Uri("FEED URL");
// ---- Update the ‘packages.config’ file ----
var packageReferenceFile = new PackageReferenceFile("../../packages.config");
string packagesPath = "../../packages";
IPackageRepository sourceRepository = PackageRepositoryFactory.Default.CreateRepository(sourceUri.ToString());
PackageManager packageManager = new PackageManager(sourceRepository, packagesPath);
foreach (var sourcePackage in sourceRepository.GetPackages().Where(x => x.IsLatestVersion))
{
if (!packageReferenceFile.EntryExists(sourcePackage.Id + " " + sourcePackage.Version, sourcePackage.Version))
{
var oldPackage = packageReferenceFile.GetPackageReferences().FirstOrDefault(x => x.Id.Contains(sourcePackage.Id));
if (oldPackage != null)
{
packageReferenceFile.DeleteEntry(oldPackage.Id, oldPackage.Version);
}
packageManager.InstallPackage(sourcePackage.Id, SemanticVersion.Parse(sourcePackage.Version.ToFullString()));
// Get the target framework of the current project to add targetframework="net452" attribute in the package.config file
currentTargetFw = Assembly.GetExecutingAssembly()
.GetCustomAttributes(typeof(TargetFrameworkAttribute), false);
var targetFrameworkAttribute = ((TargetFrameworkAttribute[]) currentTargetFw).FirstOrDefault();
// Update the packages.config file
packageReferenceFile.AddEntry(sourcePackage.GetFullName(),
SemanticVersion.Parse(sourcePackage.Version.ToFullString()), false,
new FrameworkName(targetFrameworkAttribute.FrameworkName));
}
}
return true;
}
catch (Exception ex) {
Log.LogErrorFromException(ex);
return false;
}`
```
Any ideas on how to resolve this as cannot seem to find a solution.
Overall what to run this a pre step on a CI build to keep nugets up to date.
Thanks
Tim<issue_comment>username_1: Just call
```
nuget restore "your_solution.sln"
```
Don't reinvent the wheel by writing it in C# code.
Upvotes: 1 <issue_comment>username_2: >
> Nuget Update Packages.config in MSBuild BeforeBuild Step
>
>
>
Not sure where your code issue comes from. It may be simpler just use `NuGet.exe` to restore and update the solution instead of trying to use C# code.
So you could add following nuget command line in the MSBuild BeforeBuild Step
```
```
Note: If you are using Visual Studio, Visual Studio will automatically check the missing packages during the build and restore them: [Package Restore](https://learn.microsoft.com/en-us/nuget/consume-packages/package-restore).
Hope this helps.
Upvotes: 0 |
2018/03/19 | 803 | 3,082 | <issue_start>username_0: I am trying to implement a simple program that contains the router in react. I am using 'react-router-dom' for it.
Here's how my App.jsx looks like
```
import React from 'react';
import { BrowserRouter, Switch, Route } from 'react-router-dom';
import { Headerbar } from './HeaderBar.jsx';
import Home from './Home.jsx';
import About from './About.jsx';
export default class App extends React.Component {
render() {
return (
);
}
}
```
This is being called from the index.js which reads something like this
```
import './styles/global.scss';
import React from 'react';
import ReactDOM from 'react-dom';
import App from './components/App.jsx';
ReactDOM.render(, document.getElementById('root'));
```
Now the components that I am trying to render are very simple one'. One of them 'About.jsx' reads something like this:
```
import React from 'react';
export default class About extends React.Component {
constructor() {
super();
console.log('about component');
}
render(){
return (
About page
==========
[Go back to home](/)
);
}
}
```
something similar is the code for the Home component.
Following here is the HeaderBar.jsx which contains the link that changes the route.
```
import '../styles/components/headerBar.scss';
import React from 'react';
export class Headerbar extends React.Component {
render () {
return (
Simple User List
================
[About](/about)
[Home](/)
);
}
}
```
Any help in this respect is much appreciated. Also if you could point out the best practise that could be followed while creating such code blocks.
Thanks in advance.<issue_comment>username_1: You have bad path on this line.
```
```
Just change to
```
```
Upvotes: 1 <issue_comment>username_2: No route matches your root path
either you can change one of your path to `"/"` or you can redirect to one of your route, just add this inside switch statement in App.jsx
```
()} />
```
Upvotes: 0 <issue_comment>username_3: Starting with the initial thing,
instead of Route `path='/home'` you should have `path='/'`
```
export default class App extends React.Component {
render() {
return (
);
}
}
```
or use `Redirect`
```
export default class App extends React.Component {
render() {
return (
);
}
}
```
and
Secondly instead of using `anchor tag`, use `Link` to change the route
```
import { Link } from 'react-router-dom';
export default class About extends React.Component {
constructor() {
super();
console.log('about component');
}
render(){
return (
About page
==========
Go back to home
);
}
}
```
and
```
export class Headerbar extends React.Component {
render () {
return (
Simple User List
================
About
Home
);
}
}
```
Upvotes: 0 <issue_comment>username_4: Please update the about component route as follows in your App component
Instead of
Since browser by default points to '/' initially.
Upvotes: 0 |
2018/03/19 | 688 | 1,451 | <issue_start>username_0: Is there an easy way to transform a datetime column in python to a format of `YYYYQx`, for example `2018Q1`, `2018Q2` etc?
I've tried this line but returns nothing
```
zip([list(DF_A['period'].dt.year), ['Q']*length_of_DF, list(DF_A['period'].dt.quarter)])
```<issue_comment>username_1: You can convert datetimes to quarter period by [`to_period`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.dt.to_period.html) and for custom strings use [`strftime`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.PeriodIndex.strftime.html):
```
d = ['2015-01-01','2016-05-01','2015-07-01','2015-10-01','2015-04-01']
df = pd.DataFrame({ 'Date': pd.to_datetime(d)})
print (df)
Date
0 2015-01-01
1 2016-05-01
2 2015-07-01
3 2015-10-01
4 2015-04-01
print (df['Date'].dt.to_period('Q'))
0 2015Q1
1 2016Q2
2 2015Q3
3 2015Q4
4 2015Q2
Name: Date, dtype: object
print (df['Date'].dt.to_period('Q').dt.strftime('%Yq%q'))
0 2015q1
1 2016q2
2 2015q3
3 2015q4
4 2015q2
Name: Date, dtype: object
```
Upvotes: 5 [selected_answer]<issue_comment>username_2: Here is one way.
```
df = pd.DataFrame({'A': ['2017-01-01', '2017-04-01', '2017-12-01']})
df['A'] = pd.to_datetime(df['A'])
df['B'] = df['A'].dt.year.astype(str) + 'Q' + df['A'].dt.quarter.astype(str)
```
Result:
```
A B
0 2017-01-01 2017Q1
1 2017-04-01 2017Q2
2 2017-12-01 2017Q4
```
Upvotes: 2 |
2018/03/19 | 751 | 1,642 | <issue_start>username_0: Any way to combine splits?
I have two splits, `dfa` and `dfb`.
`dfa` is a Large list (4 elements) with 4 variables i.e. `dfa[[1]]` selects the first split
`dfb` is also a Large list (11 elements) with the same 4 variables.
Is there any way to make it as follows:
`dfc` Large List (15 elements)
I want `dfc[[1]]` to be the same as `dfa[[1]]` and `dfc[[5]]` to be the same as `dfb[[1]]`.
I have tried to bind these but `cbind`/`rbind` does not work.<issue_comment>username_1: You can convert datetimes to quarter period by [`to_period`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.dt.to_period.html) and for custom strings use [`strftime`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.PeriodIndex.strftime.html):
```
d = ['2015-01-01','2016-05-01','2015-07-01','2015-10-01','2015-04-01']
df = pd.DataFrame({ 'Date': pd.to_datetime(d)})
print (df)
Date
0 2015-01-01
1 2016-05-01
2 2015-07-01
3 2015-10-01
4 2015-04-01
print (df['Date'].dt.to_period('Q'))
0 2015Q1
1 2016Q2
2 2015Q3
3 2015Q4
4 2015Q2
Name: Date, dtype: object
print (df['Date'].dt.to_period('Q').dt.strftime('%Yq%q'))
0 2015q1
1 2016q2
2 2015q3
3 2015q4
4 2015q2
Name: Date, dtype: object
```
Upvotes: 5 [selected_answer]<issue_comment>username_2: Here is one way.
```
df = pd.DataFrame({'A': ['2017-01-01', '2017-04-01', '2017-12-01']})
df['A'] = pd.to_datetime(df['A'])
df['B'] = df['A'].dt.year.astype(str) + 'Q' + df['A'].dt.quarter.astype(str)
```
Result:
```
A B
0 2017-01-01 2017Q1
1 2017-04-01 2017Q2
2 2017-12-01 2017Q4
```
Upvotes: 2 |
2018/03/19 | 429 | 1,819 | <issue_start>username_0: Long story short, our git server (gitlab if it matters) which hosts about 100 repos got reverted to 3 weeks ago state. We (developers) apparently have all changes made after that on our local computers - that's how GIT works, right? How do we sync them back to the server? The problem I see is that the changes are marked as "pushed" (i.e. in *origin* branch) locally. Will git understand that, and we only need to do push again? how is that going to work with multiple branches? or multiple developers working on the same branch? Any advise or link would be appreciated.<issue_comment>username_1: Pushing again to the server updates the servers state, as git calculates the diff between the server & client on push
Make sure to push all local branches from your local environment to the server.
*Skip this if your git flow specifies to never checkout to the master branch*
```
git push --all
```
---
In some cases, this might not restore the latest master/develop branch, as some workflows specify that you should never checkout to the master branch at all, if this is your workflow, you should manually push every branch after checking out to the remote version of it. The workflow for recovery then goes like:
```
git checkout master
git merge origin/master
# Don't use pull here or the client will realize the server has "reverted"
git push
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: Stepping back a bit, it sounds like the remote tracking branches on the local (dev) repos being out of sync with the state of the remote (server) repository is what is causing the confusion.
Just do a `git fetch --prune` (or whatever incantation of `fetch` you prefer, but *not* `git pull`), the tracking refs will be updated, and things will start making sense again.
Upvotes: 0 |
2018/03/19 | 725 | 2,781 | <issue_start>username_0: I went to do a `sync` in VS 2017 (15.3.5) Team explorer and it says `pull` operation failed. I am using `git` as version control.
This is the error I got:
```
Remote: Microsoft (R) Visual Studio (R) Team Services
Remote:
Remote: Found 18 objects to send. (631 ms)
Pull operation failed.*
```
I've tried several things:
1. Delete the branch and checkout again.
2. Connect to team system again.
Nothing works. expecting expert advice.<issue_comment>username_1: Below steps worked.
1. `git fetch -p`
2. deleting the local branch and check out it again.
But make sure you don't have any commits to sync.
3. Worst case you can delete the local repository and clone again.
red below articles as well. this might be useful.
[More info 1](https://developercommunity.visualstudio.com/content/problem/122161/pull-operation-failed.html)
[More Info 2](https://developercommunity.visualstudio.com/content/problem/19225/error-pull-operation-failed-when-pulling.html)
Upvotes: 3 [selected_answer]<issue_comment>username_2: For me, this happened when I changed the http proxy from the corporate proxy to an external site proxy. I forgot to switch it back, and so it failed. Switched back to the corporate proxy and it worked again.
Upvotes: 0 <issue_comment>username_3: There are various reasons this can happen. I've been frustrated a few times when the only feedback I could see was "Pull operation failed." Here are a couple of steps that have helped me...
* If you have any local changes, try performing a *Commit All* from the *Changes* section of VS Team Explorer. Then try to *Pull* again. If you're able to do this, then chances are there are conflicts you'll have to resolve, but VS/Git should allow you to resolve them at this point.
* If that doesn't work, go to the *Sync* section of VS Team Explorer and try doing a *Fetch.* Hopefully the you see a list of the changes you need to get pulled to your machine. If so, right-click the oldest one and select *Cherry-Pick.* When you do this, VS/Git will show you any problems (at the top of the *Synchronization* tab) with the specific pull. If no issues are listed, then try selecting/cherry-picking the next set of changes you need to pull, and continue this until, hopefully, you find some info that helps you start digging into the source of the problem.
Upvotes: 2 <issue_comment>username_4: I solved just launching the prune command on the git bash
Upvotes: 0 <issue_comment>username_5: In my case the issue probably was that some other process kept files and prevented the pull operation. I just run the command as an administrator and it worked.
Upvotes: 0 <issue_comment>username_6: Creating new branch and merging from origin/master (actual) branch worked for me
Upvotes: 0 |
2018/03/19 | 690 | 1,595 | <issue_start>username_0: I have a data set which contains the list of users and corresponding articles consulted like:
```
A_ID<-c(111,116,111,112,112,114,116,113,114,111,114,116,115,116)
U_ID<-c(221,221,222,222,223,223,223,224,224,225,225,225,226,226)
df_u_a<-data.frame(U_ID,A_ID)
```
I want to build a matrix that show me how many occurrences I have per user like
[](https://i.stack.imgur.com/m4Glz.jpg)
I want to get the same output if I have duplicates, for example, the following should be counted as user 226 has accessed article 116, not like user 226 has accessed article 116 twice:
```
A_ID<-c(116,116)
U_ID<-c(226,226)
df_u_a<-data.frame(U_ID,A_ID)
```
I tried the function matrix, but it seems like I'm just getting a table:
```
m<-as.matrix(df_u_a)
m
```
Maybe I mont using the matrix function correctly or there is another function I should use. Could you please someone advise on how to get a matrix in R as in the image above.<issue_comment>username_1: After using `table`, you could simply convert to `logical`, i.e.:
```
myTab <- table(df_u_a)
myTab[] <- as.integer(as.logical(myTab))
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: Here is one-line solution using `reshape2::dcast`:
```
library(reshape2);
dcast(df_u_a, U_ID ~ A_ID, length);
# U_ID 111 112 113 114 115 116
#1 221 1 0 0 0 0 1
#2 222 1 1 0 0 0 0
#3 223 0 1 0 1 0 1
#4 224 0 0 1 1 0 0
#5 225 1 0 0 1 0 1
#6 226 0 0 0 0 1 1
```
Upvotes: 0 |
2018/03/19 | 503 | 1,681 | <issue_start>username_0: I am trying to know a position of a string (word) in a sentence. I am using the function below. This function is working perfectly for most of the words but for this string `GLC-SX-MM=` in the sentence `I have a lot of GLC-SX-MM= in my inventory list` there is no way to get the match. I tryied scaping - and = but not works. Any idea? I cannot split the sentence using spaces because sometimes I have composed words separated by space.
```
import re
def get_start_end(self, sentence, key):
r = re.compile(r'\b(%s)\b' % key, re.I)
m = r.search(question)
start = m.start()
end = m.end()
return start, end
```<issue_comment>username_1: You need to escape the key when looking for a literal string, and make sure to use unambiguous `(? and `(?!\w)` boundaries:`
```
import re
def get_start_end(self, sentence, key):
r = re.compile(r'(?
```
The `r'(? will build a regex like `(? out of `abc.def=` keyword, and `(? will fail any match if there is a word char immediately to the left of the keyword and `(?!\w)` will fail any match if there is a word char immediately to the right of the keyword.```
Upvotes: 3 [selected_answer]<issue_comment>username_2: This is not actual answer but help to solve the problem.
You can get pattern dynamically to debug.
```
import re
def get_start_end(sentence, key):
r = re.compile(r'\b(%s)\b' % key, re.I)
print(r.pattern)
sentence = "foo-bar is not foo=bar"
get_start_end(sentence, 'o-')
get_start_end(sentence, 'o=')
\b(o-)\b
\b(o=)\b
```
You can then try matching the pattern manually like using <https://regex101.com/> if it matches.
Upvotes: 0 |
2018/03/19 | 1,724 | 5,355 | <issue_start>username_0: Is this possible to have types restricted without `if` by function calls that `never` return for e.g `undefined` like `assert` in Typescript?
Example code:
```
interface Foo { bar(): void }
function getFoo(): Foo | undefined { }
function test() {
const foo = someService.getFoo();
assert(foo);
if (!foo) { // now mandatory because without this foo may be still undefined even if assert protects us from this
return;
}
foo.bar(); // , here foo may be undefined
}
```
I would like to be able to write `assert` in such way that i can skip following `if (!foo)` clause and have `foo` type restricted to plain `Foo`.
Is this possible in Typescript?
I've tried adding overloads with `never` for types that throw:
```
function assertGuard(v: undefined | null | '' | 0 | false): never;
function assertGuard(v: any): void; // i'm not sure which one is captured by TS typesystem here
function assertGuard(v: T | undefined) {
if (v === undefined || v === null || v === '' || v === 0 || v === false) {
throw new AssertionError({message: 'foo'})
}
}
```
This one compiles, but call to `assertGuard(foo)` doesn't recognize that for `undefined` it will return `never` so doesn't restrict `foo` to `Foo`.
I've found possible workarounds but i consider classical `assert` a cleaner approach:
```
function assertResultDefined(v: T|undefined): T | never {
if (v === undefined) {
throw new Error('foo');
}
return v;
}
function die(): never { throw new Error('value expected)}
const foo = assertResultDefined(getFoo()) // foo is Foo, undefined is erased
const foo = getFoo() || die();
// undefined is erased from foo
/ CONS: doesn't play well with types that interpolate to `false` like 0, ''
```<issue_comment>username_1: There is an issue in the typescript backlog for this <https://github.com/Microsoft/TypeScript/issues/8655>. So for now you can't do this.
What you can do, is to use the assertion operator "!". Adding ! after value will assert that the value is neither undefined nor null. Use this is case where you're absolutely sure it cannot lead to a null or undefined reference.
```
function test() {
const foo: (FooType|null) = getFoo();
foo!.bar(); // "!" - asserts that foo is not null nor undefined
}
```
Source: <https://www.typescriptlang.org/docs/handbook/advanced-types.html#type-guards-and-type-assertions>
Upvotes: 3 <issue_comment>username_2: Since `foo` is `Foo | undefined`, its type should be changed to `Foo` somehow.
In the code above, this reasonably can be done with:
```
let foo = getFoo(); // Foo | undefined
foo = assertResultDefined(foo); // Foo
foo.bar();
```
Another option is to use non-null assertion (as another answer suggests):
```
let foo = getFoo();
foo = assertResultDefined(foo);
foo = foo!;
foo.bar();
```
Upvotes: 2 <issue_comment>username_3: this should work for you:
```js
const foo = (a: number | null) => {
a = shouldBe(_.isNumber, a)
a // TADA! a: number
}
const shouldBe = (fn: (t1) => t1 is T, t) => (fn(t) ? t : throwError(fn, t))
const throwError = (fn:Function, t) => {
throw new Error(`not valid, ${fn.name} failed on ${t}`)
}
```
where `_.isNumber` has a type guard `x is number`
This can be used with any function with a type guard.
the key is **you must reassign the variable**, so effectively `assert` is an identity function that throws an error on failed type assertion
Upvotes: 1 <issue_comment>username_4: Typescript 3.7 adds [assertions in control flow analysis](https://github.com/microsoft/TypeScript/pull/32695).
>
> An `asserts` return type predicate indicates that the function returns only when the assertion holds and otherwise throws an exception
>
>
>
Hacks on consumer side are not needed anymore.
```
interface Foo { bar(): void }
declare function getFoo(): Foo | undefined;
function assert(value: unknown): asserts value {
if (value === undefined) {
throw new Error('value must be defined');
}
}
function test() {
const foo = getFoo();
// foo is Foo | undefined here
assert(foo);
// foo narrowed to Foo
foo.bar();
}
```
[Playground](https://www.typescriptlang.org/play/index.html?ssl=16&ssc=2&pln=1&pc=1#code/JYOwLgpgTgZghgYwgAgGIHt3IN7IEZxQAUAlAFzIBu6wAJsgL4BQtECANoSjAK4gJhg6EMgDmEMBnSkKU5AB9kfVjFARaAbiZNe-QcORwAzkehgilOOx4QKfANYh0AdxDlDJs0apWbOJsiByMAwyBa%20KAC80UogKmq0JP5BKchgABZQLsggEM7IAKJQWcQA5JbWKAC2PEZg%20CjxubSlJFopzMw6fAJCIpB1pMlBCMJ1yDCYyJFiElKk7UEA9EsTU8DecorKEKrNyOnQEAFBxqZQ5pPobSeBK2tYIIRZzuppWFK3DwB0BMQ3DCAA)
---
Additionally one can assert that provided parameter is of required type:
```
declare function assertIsArrayOfStrings(obj: unknown): asserts obj is string[];
function foo(x: unknown) {
assertIsArrayOfStrings(x);
return x[0].length; // x has type string[] here
}
```
[Playground](https://www.typescriptlang.org/play/index.html#code/CYUwxgNghgTiAEAzArgOzAFwJYHtXygGdCQYMBJQgQRhigE8B<KEY>SEDMAXyA)
Upvotes: 6 [selected_answer]<issue_comment>username_5: One-liner with type safety:
```ts
function assert(value: T | undefined): T {
if (value === undefined) {
throw new Error('value is undefined');
}
return value;
}
```
Upvotes: 0 |
2018/03/19 | 1,338 | 3,931 | <issue_start>username_0: When I use
```
php bin/console generate:doctrine:crud
```
to create crud in symfony , symfony give me several functions like
```
public function showAction(user $user)
```
and my Q is what is `user $user`? but url is `/{id}/show`
why we don't use $id in showAction function?
and how user $user works?<issue_comment>username_1: There is an issue in the typescript backlog for this <https://github.com/Microsoft/TypeScript/issues/8655>. So for now you can't do this.
What you can do, is to use the assertion operator "!". Adding ! after value will assert that the value is neither undefined nor null. Use this is case where you're absolutely sure it cannot lead to a null or undefined reference.
```
function test() {
const foo: (FooType|null) = getFoo();
foo!.bar(); // "!" - asserts that foo is not null nor undefined
}
```
Source: <https://www.typescriptlang.org/docs/handbook/advanced-types.html#type-guards-and-type-assertions>
Upvotes: 3 <issue_comment>username_2: Since `foo` is `Foo | undefined`, its type should be changed to `Foo` somehow.
In the code above, this reasonably can be done with:
```
let foo = getFoo(); // Foo | undefined
foo = assertResultDefined(foo); // Foo
foo.bar();
```
Another option is to use non-null assertion (as another answer suggests):
```
let foo = getFoo();
foo = assertResultDefined(foo);
foo = foo!;
foo.bar();
```
Upvotes: 2 <issue_comment>username_3: this should work for you:
```js
const foo = (a: number | null) => {
a = shouldBe(_.isNumber, a)
a // TADA! a: number
}
const shouldBe = (fn: (t1) => t1 is T, t) => (fn(t) ? t : throwError(fn, t))
const throwError = (fn:Function, t) => {
throw new Error(`not valid, ${fn.name} failed on ${t}`)
}
```
where `_.isNumber` has a type guard `x is number`
This can be used with any function with a type guard.
the key is **you must reassign the variable**, so effectively `assert` is an identity function that throws an error on failed type assertion
Upvotes: 1 <issue_comment>username_4: Typescript 3.7 adds [assertions in control flow analysis](https://github.com/microsoft/TypeScript/pull/32695).
>
> An `asserts` return type predicate indicates that the function returns only when the assertion holds and otherwise throws an exception
>
>
>
Hacks on consumer side are not needed anymore.
```
interface Foo { bar(): void }
declare function getFoo(): Foo | undefined;
function assert(value: unknown): asserts value {
if (value === undefined) {
throw new Error('value must be defined');
}
}
function test() {
const foo = getFoo();
// foo is Foo | undefined here
assert(foo);
// foo narrowed to Foo
foo.bar();
}
```
[Playground](https://www.typescriptlang.org/play/index.html?ssl=16&ssc=2&pln=1&pc=1#code/JYOwLgpgTgZghgYwgAgGIHt3IN7IEZxQAUAlAFzIBu6wAJsgL4BQtECANoSjAK4gJhg6EMgDmEMBnSkKU5AB9kfVjFARaAbiZNe-QcORwAzkehgilOOx4QKfANYh0AdxDlDJs0apWbOJsiByMAwyBa%20KAC80UogKmq0JP5BKchgABZQLsggEM7IAKJQWcQA5JbWKAC2PEZg%20CjxubSlJFopzMw6fAJCIpB1pMlBCMJ1yDCYyJFiElKk7UEA9EsTU8DecorKEKrNyOnQEAFBxqZQ5pPobSeBK2tYIIRZzuppWFK3DwB0BMQ3DCAA)
---
Additionally one can assert that provided parameter is of required type:
```
declare function assertIsArrayOfStrings(obj: unknown): asserts obj is string[];
function foo(x: unknown) {
assertIsArrayOfStrings(x);
return x[0].length; // x has type string[] here
}
```
[Playground](https://www.typescriptlang.org/play/index.html#code/CYUwxgNghgTiAEAzArgOzAFwJYHtXygGdCQYMBJQgQRhigE8B5RAZQxi1QHNCAKHAEYArAFzw0Aa1Q4A7qgCUYoiTKF4gofCxrC7TlwDaAXQDcAKDMp02PEhw5eADzGTpc+fADeZ+L4LFSCmpaBmY2Dm4+R3lzP3g4DGQYfEcDAAYjADoIEG4MAAsTXwB6YvhHeHyieAx6AAcEXQjDI0rSEDMAXyA)
Upvotes: 6 [selected_answer]<issue_comment>username_5: One-liner with type safety:
```ts
function assert(value: T | undefined): T {
if (value === undefined) {
throw new Error('value is undefined');
}
return value;
}
```
Upvotes: 0 |
2018/03/19 | 768 | 2,547 | <issue_start>username_0: I currently have the following data:
```
const data = [
{
Zone: 'Airport',
Lane: 'AIRDEL',
Capacity: '90',
Status: '80',
Spaces: '10',
LastAuditedOn: 'due',
AuditedBy: 'Ross',
FirstCollection: '-',
LastCollection: '-',
},
{
Zone: 'Arrivals',
Lane: '4',
Capacity: '10',
Status: '0',
Spaces: '10',
LastAuditedOn: '-',
AuditedBy: '-',
FirstCollection: '9:00PM',
LastCollection: '01:00AM',
},
{
Zone: 'Unknown',
Lane: 'BHX_HOLD1',
Capacity: '80',
Status: '40',
Spaces: '40',
LastAuditedOn: 'due',
AuditedBy: 'Max',
FirstCollection: '-',
LastCollection: '-',
},
]
```
and I am currently trying to extract the data based off the properties (zone, lane, capacity) as an example.
```
const multiHeaderBy = 'Zone';
data.forEach((key) => {
console.log(key.find(multiHeaderBy))
});
```
I expect values `arrivals, airport, unknown` to appear in the `console.log` but i get undefined.
Ideas?<issue_comment>username_1: You can do this simply using [`.map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map) and [`.join()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join) methods like:
```js
const data=[{Zone:'Airport',Lane:'AIRDEL',Capacity:'90',Status:'80',Spaces:'10',LastAuditedOn:'due',AuditedBy:'Ross',FirstCollection:'-',LastCollection:'-',},{Zone:'Arrivals',Lane:'4',Capacity:'10',Status:'0',Spaces:'10',LastAuditedOn:'-',AuditedBy:'-',FirstCollection:'9:00PM',LastCollection:'01:00AM',},{Zone:'Unknown',Lane:'BHX_HOLD1',Capacity:'80',Status:'40',Spaces:'40',LastAuditedOn:'due',AuditedBy:'Max',FirstCollection:'-',LastCollection:'-',}];
const multiHeaderBy = 'Zone';
var txt = data.map(x => x[multiHeaderBy]);
console.log(txt.join(', '));
```
Upvotes: 1 <issue_comment>username_2: Use map function to get array using key
```
var valueArr = data.map(e=>e.Zone);
console.log(valueArr) // ["Airport", "Arrivals", "Unknown"]
```
Upvotes: 0 <issue_comment>username_3: You have to use [] backet instead of find function. [] backet is used to get the value from an object using dynamic key.
```
const multiHeaderBy = 'Zone';
data.forEach((key) => {
console.log(key[multiHeaderBy])
});
```
Upvotes: 0 |
2018/03/19 | 448 | 1,418 | <issue_start>username_0: How to position things in css when creating a website so that is more flexible<issue_comment>username_1: You can do this simply using [`.map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map) and [`.join()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join) methods like:
```js
const data=[{Zone:'Airport',Lane:'AIRDEL',Capacity:'90',Status:'80',Spaces:'10',LastAuditedOn:'due',AuditedBy:'Ross',FirstCollection:'-',LastCollection:'-',},{Zone:'Arrivals',Lane:'4',Capacity:'10',Status:'0',Spaces:'10',LastAuditedOn:'-',AuditedBy:'-',FirstCollection:'9:00PM',LastCollection:'01:00AM',},{Zone:'Unknown',Lane:'BHX_HOLD1',Capacity:'80',Status:'40',Spaces:'40',LastAuditedOn:'due',AuditedBy:'Max',FirstCollection:'-',LastCollection:'-',}];
const multiHeaderBy = 'Zone';
var txt = data.map(x => x[multiHeaderBy]);
console.log(txt.join(', '));
```
Upvotes: 1 <issue_comment>username_2: Use map function to get array using key
```
var valueArr = data.map(e=>e.Zone);
console.log(valueArr) // ["Airport", "Arrivals", "Unknown"]
```
Upvotes: 0 <issue_comment>username_3: You have to use [] backet instead of find function. [] backet is used to get the value from an object using dynamic key.
```
const multiHeaderBy = 'Zone';
data.forEach((key) => {
console.log(key[multiHeaderBy])
});
```
Upvotes: 0 |
2018/03/19 | 1,224 | 3,613 | <issue_start>username_0: I was trying to make heapsort using min heap, that too with a Structure that points to a array pointer. Now there is some logical error either in *createHeap* function or in *heapify* function.
Note:Rest of the program need not to be check or edit, **Heapify** and **createHeap** need to modify according to the rest of the program.
```
#include
#include
// Max heap of length len and values stored in array
struct MinHeap{
int size;
int\* array;
};
// Function declarations
void createHeap(struct MinHeap\*);
void heapify(struct MinHeap\* , int );
void heapSort(struct MinHeap\*);
void swap(int\*,int\*);
void printArray(int\*, int);
int main(){
int numelems;
scanf("%d",&numelems);
int \* arr = (int\*) malloc(sizeof(int) \* numelems);
int i;
for(i=0;isize = numelems; // initialize size of heap
minHeap->array = arr; // Assign address of first element of array
createHeap(minHeap);
heapSort(minHeap);
printArray(minHeap->array,numelems);
return 0;
}
// heapSort function
void heapSort(struct MinHeap\* minHeap){
// Repeat following steps while heap size is greater than 1.
while (minHeap->size > 1){
// The smallest item in Heap is stored at the root. Replace it with the last item of the heap followed by reducing the size of heap by 1.
swap(&minHeap->array[0], &minHeap->array[minHeap->size - 1]);
--minHeap->size; // Reduce heap size
// heapify the root of tree.
heapify(minHeap, 0);
}
}
// function swap 2 integers
void swap(int\* num1, int\* num2){
int temp = \*num1;
\*num1 = \*num2;
\*num2 = temp;
}
// prints an array of given size
void printArray(int\* a, int len){
int i;
for (i = len-1; i >=0 ; i--)
printf("%d ", a[i]);
}
void createHeap(struct MinHeap \*heap)
{
int len=heap->size-1,i;
for(i=len;i>=0;i--)
heapify(heap,i);
}
void heapify(struct MinHeap \*heap,int i)
{
int min;
int right=2\*i+2,left=i\*2+1;
if(rightsize-1 && heap->array+i>heap->array+right)
min=right;
else min =i;
if(leftsize-1 && heap->array+i>heap->array+left)
min=left;
if(min!=i)
{
swap(heap->array+i,heap->array+min);
heapify(heap,min);
}
}
```<issue_comment>username_1: In `heapify` function you should compare values not pointers so change
```
heap->array+i>heap->array+right
```
to
```
heap->array[i]>heap->array[right]
```
>
> Note: `array[i]` is just another way of writing `*(array+i)`, so your code would work if changed it to `*(heap->array + i) > *(heap->array + right)` but in general, the brackets makes things much clearer.
>
>
>
In conditions which check if `left`, `right` indices are in range of array you should replace `left < heap->size-1` by `left <= heap->size-1` (to do the same thing with `right` index).
After these lines were executed
```
if(right<=heap->size-1 && heap->array[i]>heap->array[right])
min=right;
else
min =i;
```
you should take `min` value to use in next comparison
```
if(left<=heap->size-1 && heap->array[min]>heap->array[left])
```
Upvotes: 1 [selected_answer]<issue_comment>username_2: // THIS WILL GUARANTEED WORK FOR YOU//
```
void createHeap(struct MinHeap *heap)
{
int len=heap->size-1,i;
for(i=len;i>=0;i--)
heapify(heap,i);
}
void heapify(struct MinHeap *heap,int i)
{
int min;
int right=2*i+2,left=i*2+1;
if(right<=heap->size-1 && *(heap->array + i) > *(heap->array + right))
min=right;
else min =i;
if(left<=heap->size-1 && heap->array[min]>heap->array[left]
{
min=left;
}
if(min!=i)
{
swap(heap->array+i,heap->array+min);
heapify(heap,min);
}
}
```
Upvotes: -1 |
2018/03/19 | 787 | 2,272 | <issue_start>username_0: Iam trying to access [coinbase api](https://developers.coinbase.com/api/v2#list-addresses) to generate address on my ubuntu terminal.
```
curl -k -X GET "https://api.coinbase.com/v2/accounts/3e3835d3----/addresses" -H "CB-VERSION: 2015-04-08" -H "accept: application/json;charset=utf-8" -H "Authorization: Bearer <KEY>"
```
returns below error.
>
> {"errors":[{"id":"invalid\_token","message":"The access token is invalid"}]}
>
>
>
I don't know what to pass as Authorization bearer. I only have API key and API secret. If there is some other step to take or some other documentation please tell me. If you need more info, ask that also.
An example would be helpful. Thanks in advance.<issue_comment>username_1: In `heapify` function you should compare values not pointers so change
```
heap->array+i>heap->array+right
```
to
```
heap->array[i]>heap->array[right]
```
>
> Note: `array[i]` is just another way of writing `*(array+i)`, so your code would work if changed it to `*(heap->array + i) > *(heap->array + right)` but in general, the brackets makes things much clearer.
>
>
>
In conditions which check if `left`, `right` indices are in range of array you should replace `left < heap->size-1` by `left <= heap->size-1` (to do the same thing with `right` index).
After these lines were executed
```
if(right<=heap->size-1 && heap->array[i]>heap->array[right])
min=right;
else
min =i;
```
you should take `min` value to use in next comparison
```
if(left<=heap->size-1 && heap->array[min]>heap->array[left])
```
Upvotes: 1 [selected_answer]<issue_comment>username_2: // THIS WILL GUARANTEED WORK FOR YOU//
```
void createHeap(struct MinHeap *heap)
{
int len=heap->size-1,i;
for(i=len;i>=0;i--)
heapify(heap,i);
}
void heapify(struct MinHeap *heap,int i)
{
int min;
int right=2*i+2,left=i*2+1;
if(right<=heap->size-1 && *(heap->array + i) > *(heap->array + right))
min=right;
else min =i;
if(left<=heap->size-1 && heap->array[min]>heap->array[left]
{
min=left;
}
if(min!=i)
{
swap(heap->array+i,heap->array+min);
heapify(heap,min);
}
}
```
Upvotes: -1 |
2018/03/19 | 762 | 2,589 | <issue_start>username_0: I'm working on a customer support bot which helps business users understand the meaning of certain technical terms or status of some of their requests. A typical sentence looks like below
1. Explain me about Air Compressor/Heating and cooling systems/ Law Of
Thermodynamics
2. Get me the status of Ticket123/HEATER12
***What have I done so far***
I currently use Microsoft LUIS to identify the entities where I upload all the possible entities and LUIS does a string match and return them. The problem with this approach is
* The entity list keeps getting bigger and needs to be updated everyday
* User may type in spelling mistakes - In some cases, the word user types may not be a dictionary word for the spelling to be corrected.
***What's my solution (which doesn't seem to work well)***
I'm currently thinking of an approach to tag the POS and group the noun phrases/nouns but I dont think this will be an effective method.
Also one thing to be noted is that the entities don't follow any pattern. What should be my approach here. Any pointers would be appreciated.<issue_comment>username_1: In `heapify` function you should compare values not pointers so change
```
heap->array+i>heap->array+right
```
to
```
heap->array[i]>heap->array[right]
```
>
> Note: `array[i]` is just another way of writing `*(array+i)`, so your code would work if changed it to `*(heap->array + i) > *(heap->array + right)` but in general, the brackets makes things much clearer.
>
>
>
In conditions which check if `left`, `right` indices are in range of array you should replace `left < heap->size-1` by `left <= heap->size-1` (to do the same thing with `right` index).
After these lines were executed
```
if(right<=heap->size-1 && heap->array[i]>heap->array[right])
min=right;
else
min =i;
```
you should take `min` value to use in next comparison
```
if(left<=heap->size-1 && heap->array[min]>heap->array[left])
```
Upvotes: 1 [selected_answer]<issue_comment>username_2: // THIS WILL GUARANTEED WORK FOR YOU//
```
void createHeap(struct MinHeap *heap)
{
int len=heap->size-1,i;
for(i=len;i>=0;i--)
heapify(heap,i);
}
void heapify(struct MinHeap *heap,int i)
{
int min;
int right=2*i+2,left=i*2+1;
if(right<=heap->size-1 && *(heap->array + i) > *(heap->array + right))
min=right;
else min =i;
if(left<=heap->size-1 && heap->array[min]>heap->array[left]
{
min=left;
}
if(min!=i)
{
swap(heap->array+i,heap->array+min);
heapify(heap,min);
}
}
```
Upvotes: -1 |
2018/03/19 | 427 | 1,442 | <issue_start>username_0: What is wrong with this code? *I want so when the div loads all the -p- tags inside div "story\_L3" are removed leaving the plain text*. simple enough but my code does'nt work, please advice (see example)
```
This is a paragraph inside a p element.
This is a paragraph inside another p element.
.one{background-color: yellow;}
.two{background-color: pink;}
$('#story_L3').load(function(){
$('#story_L3').find('p').contents().unwrap();
});
```
I have also tried:
```
$('#story_L3').load(function(){
($('#story_L3 > p').contents().unwrap();
});
```
and:
```
$('#story_L3').load(function(){
if($('#story_L3').find('p').length !== 0){
$('p').contents().unwrap();
}
});
```<issue_comment>username_1: You don't need to use `.load()`, directly use [`.unwrap()`](https://api.jquery.com/unwrap/) code in document-ready handler
```js
$('#story_L3 p').contents().unwrap();
```
```css
.one {
background-color: yellow;
}
.two {
background-color: pink;
}
```
```html
This is a paragraph inside a p element.
This is a paragraph inside another p element.
```
Upvotes: 2 [selected_answer]<issue_comment>username_2: Try this:
```js
$(document).ready(function () {
$("#story_L3 > p").contents().unwrap();
});
```
```html
This is a paragraph inside a p element.
This is a paragraph inside another p element.
```
Upvotes: 0 |
2018/03/19 | 410 | 1,644 | <issue_start>username_0: I successfully had queued tasks working on a test site, and updated my live site (same server). The live queue is now just filling up without being processed, or attempted. I am using forge, and that is running a queue process. Can anyone help with what I can check next to find out why it wouldn't be working<issue_comment>username_1: I tried many things such as clearing the cache, restarting the worker, and was helped through checking supervisord was running the worker properly etc.
One final question I was asked by the person helping - was if the app was in maintenance mode. I answered no, because my site was live.
However, after reading <https://divinglaravel.com/queue-system/workers> :
>
> If app in maintenance mode you can still process jobs if your worker run with the --force option:
>
>
>
I tried:
```
php artisan queue:work --force
```
I noticed that a job WAS processed, so I tried php artisan:up and everything worked.
Essentially, we have removed the maintenance middleware sometime ago, so the app WAS in maintenance mode technically, but was still live.
So if a queue is not processing at all, try three things:
```
php artisan:up
php artisan config:clear
php artisan queue:restart
```
Upvotes: 4 [selected_answer]<issue_comment>username_2: So this is my first time working with Laravel Queues and the application that I'm building will need several different queues for priority purposes. The queue that I was testing had a name other than default. If you're using a named queue, make sure to add it to the `artisan` command
```
php artisan queue:work --queue=
```
Upvotes: 0 |
2018/03/19 | 476 | 1,754 | <issue_start>username_0: Angular code to load the data
```
constructor(private http: HttpClient , private _title: Title,
private _meta: Meta) {
this.facts = this.http.get('https://non-ssr-angular.firebaseio.com/facts.json');
this.posts = this.http.get(`${this.baseURL}/api/post/ByMemberAsync/0/None`);
}
```
Code to list which is returned API
```html
* {{fact.text}}
* {{post.title}}
```
Please help anyone to fix it<issue_comment>username_1: I tried many things such as clearing the cache, restarting the worker, and was helped through checking supervisord was running the worker properly etc.
One final question I was asked by the person helping - was if the app was in maintenance mode. I answered no, because my site was live.
However, after reading <https://divinglaravel.com/queue-system/workers> :
>
> If app in maintenance mode you can still process jobs if your worker run with the --force option:
>
>
>
I tried:
```
php artisan queue:work --force
```
I noticed that a job WAS processed, so I tried php artisan:up and everything worked.
Essentially, we have removed the maintenance middleware sometime ago, so the app WAS in maintenance mode technically, but was still live.
So if a queue is not processing at all, try three things:
```
php artisan:up
php artisan config:clear
php artisan queue:restart
```
Upvotes: 4 [selected_answer]<issue_comment>username_2: So this is my first time working with Laravel Queues and the application that I'm building will need several different queues for priority purposes. The queue that I was testing had a name other than default. If you're using a named queue, make sure to add it to the `artisan` command
```
php artisan queue:work --queue=
```
Upvotes: 0 |
2018/03/19 | 409 | 1,323 | <issue_start>username_0: In azure functions we create the function route / name, but it Always preceded by /api
on the [documentation](https://learn.microsoft.com/en-us/azure/azure-functions/functions-create-serverless-api) we read:
>
> Note that you did not include the /api base path prefix in the route template, as this is handled by a global setting.
>
>
>
But,
**How to change this base "/api" path ?**<issue_comment>username_1: You are looking for the **routePrefix** specified in the **host.json**:
```
{
"http": {
"routePrefix": "whatever"
}
}
```
You can set this for example using kudu:
```
https://.scm.azurewebsites.net/DebugConsole/?shell=powershell
```
Navigate to `site -> wwwroot` and edit the host.json
---
**Note:** This **does not work for v2**. Please use the [answer from username_2](https://stackoverflow.com/a/52128045/1163423) instead.
Upvotes: 3 [selected_answer]<issue_comment>username_2: Accepted answer does not work for **v2** anymore (source: [Azure-Functions-Host Gitub repo](https://github.com/Azure/azure-functions-host/wiki/host.json-(v2))). For v2 you need to wrap `http` settings inside `extensions` object. Working **host.json** example:
```
{
"version": "2.0",
"extensions": {
"http": {
"routePrefix": "customPrefix"
}
}
}
```
Upvotes: 5 |
2018/03/19 | 623 | 2,135 | <issue_start>username_0: I'm new to React and gulp and I'm trying to build a sample project. I managed to include a React task for gulp, to convert my react entry file (App.js), but the problem is that whenever I insert a rule in my CSS file which is imported in my App.js, I get an error, while everything works fine when the css file is empty!!!
Here's the code
React File:
```
import React, { Component } from 'react';
import Header from './header'
import Footer from './footer'
import Homepage from './homepage'
import style from './css/main.css'
class App extends Component {
render() {
return (
);
}
}
export default App;
```
and this is my gulp file:
```
const browserify = require('browserify');
const babelify = require('babelify');
const source = require('vinyl-source-stream');
const babel = require('gulp-babel');
const sourcemaps = require('gulp-sourcemaps');
const reactify = require('reactify');
gulp.task('react' , function(){
return browserify({
entries: ['./src/App.js'],
})
.transform(babelify , {presets: ["es2015", "react"]})
.bundle()
.pipe(source('bundle.js'))
.pipe(gulp.dest('./src/js'));
});
```<issue_comment>username_1: You are looking for the **routePrefix** specified in the **host.json**:
```
{
"http": {
"routePrefix": "whatever"
}
}
```
You can set this for example using kudu:
```
https://.scm.azurewebsites.net/DebugConsole/?shell=powershell
```
Navigate to `site -> wwwroot` and edit the host.json
---
**Note:** This **does not work for v2**. Please use the [answer from username_2](https://stackoverflow.com/a/52128045/1163423) instead.
Upvotes: 3 [selected_answer]<issue_comment>username_2: Accepted answer does not work for **v2** anymore (source: [Azure-Functions-Host Gitub repo](https://github.com/Azure/azure-functions-host/wiki/host.json-(v2))). For v2 you need to wrap `http` settings inside `extensions` object. Working **host.json** example:
```
{
"version": "2.0",
"extensions": {
"http": {
"routePrefix": "customPrefix"
}
}
}
```
Upvotes: 5 |
2018/03/19 | 693 | 2,283 | <issue_start>username_0: I am using nHapi in c#.net to convert hl7 messages to xml format using the following code.
My code:
```
using System;
using NuGet;
using NHapi.Model;
using NHapi.Model.V231;
using NHapi.Model.V231.Message;
using NHapi.Base.Parser;
using NHapi.Base.Model;
namespace HL7parser
{
class Program
{
static void Main(string[] args)
{
String msg =
"MSH|^~\\&|HIS|RIH|EKG|EKG|199904140038||ADT^A01||P|2.2\r........."
PipeParser parser = new PipeParser();
try {
IMessage mssg =parser.Parse(msg);
XMLParser xMLParser=null;
String str=xMLParser.Encode(mssg);
Console.WriteLine(str);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
Console.WriteLine(e.GetType().Name);
Console.WriteLine(e.StackTrace);
}
Console.WriteLine("\n Press Enter to continue...");
Console.Read();
}}}
```
Now it shows:
```
The type initializer for 'NHapi.Base.PackageManager' threw an exception.
TypeInitializationException
at NHapi.Base.Parser.ParserBase.Parse(String message)
at HL7parser.Program.Main(String[] args) in C:\Users\Administrator\source\repos\HL7parser\HL7parser\Program.cs:line 28
```
Can anyone please tell me why? what is exactly wrong in this?<issue_comment>username_1: You are looking for the **routePrefix** specified in the **host.json**:
```
{
"http": {
"routePrefix": "whatever"
}
}
```
You can set this for example using kudu:
```
https://.scm.azurewebsites.net/DebugConsole/?shell=powershell
```
Navigate to `site -> wwwroot` and edit the host.json
---
**Note:** This **does not work for v2**. Please use the [answer from username_2](https://stackoverflow.com/a/52128045/1163423) instead.
Upvotes: 3 [selected_answer]<issue_comment>username_2: Accepted answer does not work for **v2** anymore (source: [Azure-Functions-Host Gitub repo](https://github.com/Azure/azure-functions-host/wiki/host.json-(v2))). For v2 you need to wrap `http` settings inside `extensions` object. Working **host.json** example:
```
{
"version": "2.0",
"extensions": {
"http": {
"routePrefix": "customPrefix"
}
}
}
```
Upvotes: 5 |
2018/03/19 | 470 | 1,360 | <issue_start>username_0: Width, Height and Depth of small box: `1x1x1`
Width, Height and Depth of big box: `3x3x3`
Number of `1x1x1` that will fit in `3x3x3` box is: `27`
I have an exercise like that using python3 to get the outcome.
I did:
```
sb = input("Width, Height and Depth of small box: ")
s= 'x'
```
And then use `print(s.join(sb))`, but i then create new line with 1x1x1 after type 111 and enter which i do not want. I just want it to be exact on the same line of W, H and D of small box (of course with the join).
But the grading system from my student learning not only decline the answer with newline for 1x1x1, they also stated that the error as "1xxx1xxx1". But it is exactly 1x1x1 on the newline.<issue_comment>username_1: Here is an example of how you can format multiple inputs from one string:
```
sb = input("Width, Height and Depth of small box separated by |: ")
# User enters 3|3|3
s = 'x'.join(sb.split('|'))
print(s)
# 3x3x3
```
We use `|` as an arbitrary delimiter since it is unlikely it will be used for any other purpose.
Upvotes: 1 <issue_comment>username_2: You may try:
```
eval('1x1x1'.replace('x', '*'))
#1
eval('3x3x3'.replace('x', '*'))
#27
```
and then divide these 2 results as:
```
eval('3x3x3'.replace('x', '*')) / eval('1x1x1'.replace('x', '*'))
```
However, it is not a good practice.
Upvotes: 0 |
2018/03/19 | 727 | 2,299 | <issue_start>username_0: I am writing a 3D application where I need to check if a point is inside a capsule. Because a capsule can be divided into two half-ellipsoids and a cylinder, so the problem can be solved by checking a point against the three components. Checking if a point is inside an ellipsoid is easy, but I don't know how to deal with a cylinder?
Therefore, the question becomes:
In 3D space, there is a cylinder whose caps are two ellipses. The axes of the two ellipses are parallel but have different lengths. Given a point, how to check if it is inside this cylinder?
------------------- Additional Information ----------------------
It's not a regular capsule. The two caps of this capsule can be scaled separately along the default coordinate system's axes.
[](https://i.stack.imgur.com/u3JaV.png)<issue_comment>username_1: If you know how to check whether point lies inside ellipsoid, then I don't see a problem.
If ellipsoidal cap is half of ellipsoid, just check that
```
(point is in ellipsoid) or (point is in cylinder)
```
If ellipsoidal cap is less than half of ellipsoid, check that
```
((point is in ellipsoid) and (point lies at outer side of base plane of cylinder)) or
(point is in cylinder)
```
Upvotes: 0 <issue_comment>username_2: Do an axis rotation so the main axis of the cylinder becomes one of the rotated axis (e.g. z axis).
Working with these transformed coordinates a point in the cylinder must:
* be below or on the top ellipsoid, and
* be over or on the low elllipsoid, and
* proyected into a plane perpendicular to cylinder main axis, it must be inside the ellipsoid defined by plane and cylinder.
Upvotes: 2 [selected_answer]<issue_comment>username_3: Suppose you have rotated the 'cylinder' so that it has the z axis as its axis, and that the ellipse at the top (z=h) is
```
sqr( x/a1) + sqr( y/b1) = 1
```
while the ellipse at the bottom (z=0) is
```
sqr( x/a0) + sqr( y/b0) = 1
```
Then at z (0<=z<=h) the ellipse will be
```
sqr( x/az) + sqr( y/bz) = 1
```
where
```
az = a0 + (z/h)*(a1-a0)
bz = b0 + (z/h)*(b1-b0)
```
so that if your test point is (x,y,z) with 0<=z<=h, it is in the cylinder iff
```
sqr( x/az) + sqr( y/bz) <= 1
```
Upvotes: 1 |
2018/03/19 | 768 | 2,875 | <issue_start>username_0: Edit: It was caused by an obscure `height: 34px !important;` made by someone a long time - never trust old code. Commented and worked perfectly. Thanks <NAME> for suggesting a snippet inclusion and <NAME> for bringing the height issue that made me think about it. When trying to reproduce the behavior I thought about `ctrl`+`f`-ing the old css file. I wasn't able to find it on code inspection, though... Sorry for the inconvenience.
Here where I work we use ASP.NET MVC 5, Bootstrap (v3.3.7), jQuery (v2.2.3) and we use the Select2 plugin (v4.0.5). The problem is, when I use and select options enough to make it break a linke, the height does increase, but the parent doesn't follow, making it overlap the next line. Any idea of what's causing this and/or how to fix it?
This is what happens:
Before breaking line:
[](https://i.stack.imgur.com/knK4j.png)
After breaking line:
[](https://i.stack.imgur.com/ieWGM.png)
I looked up on select2 examples and cannot see a difference on implementation, and there it works perfectly... I opened code inspection on both to look for any relevant difference and couldn't find. Maybe I'm missing something.
Markup is this:
```
```
And the script goes like this:
```
$('#contatos').select2({
tags: true,
tokenSeparators: [',', ' ', ';'],
dataMiminumInputLength: 2,
ajax: {
url: '/Gerenciamento/Usuario/PesquisarUsuarios/',
data: function (params) {
return {
termo: params.term
};
},
processResults: function (data) {
var results = [];
$(data).each(function (i, el) {
results.push({
id: el.desEmail,
text: el.desNome + ' | ' + el.desEmail,
codUsuario: el.codUsuario,
desEmail: el.desEmail
});
});
return { results: results }
},
delay: 400
}
});
```
Note: This happens on all uses of select multiple in this application.<issue_comment>username_1: It's css issue have you added select2-bootstrap.css in your page? check it because select2 css is given in it for bootstrap you can check height on line 10. It should be auto
```
.form-control.select2-container {
height: auto !important;
padding: 0;
}
```
Upvotes: 1 <issue_comment>username_2: Turns ou it was a CSS issue... Someone once thought it would be a good idea to use `.select2-container, .select2-selection--single { height: 34px !important; }`. Two problems: `important!` and `height`. If `min-height` was used, this problem wouldn't happen, but the `!important` is unforgivable. Thanks and sorry!
Upvotes: 1 [selected_answer] |
2018/03/19 | 637 | 2,484 | <issue_start>username_0: I create Spring Boot 2.0 Starter project using web and cache dependencies:
```
org.springframework.boot
spring-boot-starter-cache
org.springframework.boot
spring-boot-starter-web
```
Then I updated Spring bootstrap class to test REST services caching:
```
@SpringBootApplication
@EnableCaching
@RestController
@RequestMapping
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@GetMapping
@Cacheable("hello")
public String hello() {
return "1";
}
}
```
and specified simple cache provider in application.properties:
```
spring.cache.type=simple
```
Everything worked as expected. Then I added Caffeine dependency and changed cache type:
```
com.github.ben-manes.caffeine
caffeine
spring.cache.type=caffeine
```
After that application failed to start with exception:
Caused by: java.lang.IllegalArgumentException: No cache manager could be auto-configured, check your configuration (caching type is 'CAFFEINE')
at org.springframework.util.Assert.notNull(Assert.java:193) ~[spring-core-5.0.4.RELEASE.jar:5.0.4.RELEASE]
at org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration$CacheManagerValidator.checkHasCacheManager(CacheAutoConfiguration.java:151) ~[spring-boot-autoconfigure-2.0.0.RELEASE.jar:2.0.0.RELEASE]
I tried to supply cache names in application.properties but it didn't help.
```
spring.cache.cache-names=hello
```
Please advise.<issue_comment>username_1: Add the following dependency:
```
org.springframework
spring-context-support
5.0.8.RELEASE
```
Upvotes: 2 <issue_comment>username_2: The same happened to me, and I also have Redis installed. `spring.cache.type=caffeine` wouldn't work, as well as `spring.cache.caffeine.spec`. It seemed that it tried to use the Redis cache provider, which has precedence over Caffeine, unless you disable Redis auto-configuration explicitly. Otherwise you have to configure Caffeine manually like:
```java
@Configuration
public class CaffeineCacheConfiguration {
@Bean
public CacheManager cacheManager() {
CaffeineCache helloCache = new CaffeineCache("hello",
Caffeine.newBuilder().expireAfterAccess(60, TimeUnit.SECONDS).build());
SimpleCacheManager manager = new SimpleCacheManager();
manager.setCaches(Collections.singletonList(helloCache));
return manager;
}
}
```
Upvotes: 1 |
2018/03/19 | 320 | 1,286 | <issue_start>username_0: I have input xml like this and need to map Value of Complexelement2.value to variable "Access" in output only when Complexelement2.name is "AccessLevel" .
```
SystemType
100
AdminId
606
AccessLevel
200
```
need some suggestion for this conditional traversing for this in Dataweave- Mulesoft.<issue_comment>username_1: Add the following dependency:
```
org.springframework
spring-context-support
5.0.8.RELEASE
```
Upvotes: 2 <issue_comment>username_2: The same happened to me, and I also have Redis installed. `spring.cache.type=caffeine` wouldn't work, as well as `spring.cache.caffeine.spec`. It seemed that it tried to use the Redis cache provider, which has precedence over Caffeine, unless you disable Redis auto-configuration explicitly. Otherwise you have to configure Caffeine manually like:
```java
@Configuration
public class CaffeineCacheConfiguration {
@Bean
public CacheManager cacheManager() {
CaffeineCache helloCache = new CaffeineCache("hello",
Caffeine.newBuilder().expireAfterAccess(60, TimeUnit.SECONDS).build());
SimpleCacheManager manager = new SimpleCacheManager();
manager.setCaches(Collections.singletonList(helloCache));
return manager;
}
}
```
Upvotes: 1 |
2018/03/19 | 773 | 2,013 | <issue_start>username_0: Is it possible to create a Highcharts plot background like the picture below? It's important it will adjust when the plot is zoomed in/out.
E.g. Using radialGradient, but without the "gradient" between the colors.
[](https://i.stack.imgur.com/9l8tA.png)<issue_comment>username_1: The example below is only a starting point using [SVGrenderer](https://api.highcharts.com/class-reference/Highcharts.SVGRenderer#arc):
```js
Highcharts.chart('container', {
chart: {
type: 'scatter'
},
xAxis: {
categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
},
series: [{
data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4]
}]
}, function(chart) {
var yAxis = chart.yAxis[0],
y = yAxis.top+yAxis.height,
x = chart.plotLeft,
h = yAxis.height;
svg = chart.renderer;
svg.arc(x,y,h/3,0,1.5*Math.PI,0)
.attr({
fill: '#dce6f2',
'stroke-width': 0,
zIndex: -1
}).add();
svg.arc(x,y,2*h/3,0,1.5*Math.PI,0)
.attr({
fill: '#c5d8f1',
'stroke-width': 0,
zIndex: -2
}).add();
svg.arc(x,y,h,0,1.5*Math.PI,0)
.attr({
fill: '#95b3d7',
'stroke-width': 0,
zIndex: -3
}).add();
});
```
```html
```
Upvotes: 2 <issue_comment>username_2: If you don't need it to be x/y symmetrical, then it's easy:
```
chart: {
backgroundColor: {
radialGradient: {
cx: 0,
cy: 1,
r: 1
},
stops: [
[0, '#dce6f2'],
[.25, '#dce6f2'],
[.25, '#c5d8f1'],
[.50, '#c5d8f1'],
[.50, '#95b3d7'],
[.75, '#95b3d7'],
[.75, '#fff'],
[1, '#fff']
]
},
type: 'line'
},
```
<http://jsfiddle.net/ndjnx2eh/9/>
This will scale with the size of the chart.
If you need it to always be a quarter circle, it's not so easy.
Upvotes: 2 |
2018/03/19 | 916 | 2,522 | <issue_start>username_0: how To delete physically old image after updating
```
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(Job job, HttpPostedFileBase jobimage)
{
if (ModelState.IsValid)
{
System.IO.File.Delete(Path.Combine(Server.MapPath("~/Uploads"),job.JobImage));
string path = Path.Combine(Server.MapPath("~/Uploads"), jobimage.FileName);
jobimage.SaveAs(path);
job.JobImage = jobimage.FileName;
db.Entry(job).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.CategoryId = new SelectList(db.Categories, "Id", "CategoryName", job.CategoryId);
return View(job);
}
```
this line :
>
> System.IO.File.Delete(Path.Combine(Server.MapPath("~/Uploads"),job.JobImage));
>
>
>
not working any help and thank u<issue_comment>username_1: The example below is only a starting point using [SVGrenderer](https://api.highcharts.com/class-reference/Highcharts.SVGRenderer#arc):
```js
Highcharts.chart('container', {
chart: {
type: 'scatter'
},
xAxis: {
categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
},
series: [{
data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4]
}]
}, function(chart) {
var yAxis = chart.yAxis[0],
y = yAxis.top+yAxis.height,
x = chart.plotLeft,
h = yAxis.height;
svg = chart.renderer;
svg.arc(x,y,h/3,0,1.5*Math.PI,0)
.attr({
fill: '#dce6f2',
'stroke-width': 0,
zIndex: -1
}).add();
svg.arc(x,y,2*h/3,0,1.5*Math.PI,0)
.attr({
fill: '#c5d8f1',
'stroke-width': 0,
zIndex: -2
}).add();
svg.arc(x,y,h,0,1.5*Math.PI,0)
.attr({
fill: '#95b3d7',
'stroke-width': 0,
zIndex: -3
}).add();
});
```
```html
```
Upvotes: 2 <issue_comment>username_2: If you don't need it to be x/y symmetrical, then it's easy:
```
chart: {
backgroundColor: {
radialGradient: {
cx: 0,
cy: 1,
r: 1
},
stops: [
[0, '#dce6f2'],
[.25, '#dce6f2'],
[.25, '#c5d8f1'],
[.50, '#c5d8f1'],
[.50, '#95b3d7'],
[.75, '#95b3d7'],
[.75, '#fff'],
[1, '#fff']
]
},
type: 'line'
},
```
<http://jsfiddle.net/ndjnx2eh/9/>
This will scale with the size of the chart.
If you need it to always be a quarter circle, it's not so easy.
Upvotes: 2 |
2018/03/19 | 1,248 | 2,485 | <issue_start>username_0: I have a list of frequencies (i.e. freq\_lst), which need to be retrieved by a nested list in order to do the calculation. The calculation is done using freq\_lst and r\_freq, illustrated as follows:
```
freq_lst = [0.03571429, 0.03571429, 0.07142857, 0.07142857, 0.10714286, 0.07142857, 0.07142857, 0.03571429, 0.07142857, 0.03571429, 0.03571429, 0.03571429, 0.07142857, 0.03571429, 0.03571429, 0.03571429, 0.03571429, 0.03571429, 0.03571429, 0.03571429]
nested_lst = [['R0','F1','F3','F5','F7','F9','F10'],
['R1','F0','F4','F7','F10','F16'],
['R2','F6','F7','F9','F13','F17','F18'],
['R3','F2','F8','F10','F18','F19'],
['R4','F10','F11','F12','F14','F15','F16']]
r_lst = ['R0','R1','R2','R3','R4']
r_freq = [0.1, 0.2, 0.2, 0.2, 0.3]
def mating_func():
mating = []
for k in range(len(r_lst)):
for k1 in range(len(nested_lst)):
zgt = 0
if r_lst[k] == nested_lst[k1][0]:
print(freq_lst.index(nested_lst[k1][k2+1] for k2 in range(len(nested_lst[k1]))))
zgt += r_freq[k] * freq_lst.index(nested_lst[k1][k2+1] for k2 in range(len(nested_lst[k1])))
mating.append(zgt)
return mating
```
But instead of getting the frequencies, it only printed the following:
```
. at 0x0000020C1D1A8620>
. at 0x0000020C1D1A8620>
. at 0x0000020C1D1A8620>
. at 0x0000020C1D1A8620>
. at 0x0000020C1D1A8620>
```
I've also tried the following:
```
(nested for-loops shown as before)
for k2 in range(len(nested_lst[k1])):
if rnase_list[k] == zygotes[k1][0]
zgt += r_freq[k] * freq_lst.index(nested_lst[k1][k2+1])
```
which rendered the following error:
```
ValueError: 'F1' is not in list
```<issue_comment>username_1: Is this what you're looking for:
```
mating = []
for k in range(len(r_lst)):
for k1 in range(len(nested_lst)):
if r_lst[k] == nested_lst[k1][0]:
zgt = 0
zgt+= sum([r_freq[k] * freq_lst[x] for x in [int(i[1:]) for i in nested_lst[k1][1:]]])
mating.append(zgt)
```
output:
```
[0.028571430000000002,
0.05000000400000001,
0.05000000400000001,
0.050000002,
0.07500000600000001]
```
Upvotes: 2 [selected_answer]<issue_comment>username_2: ```
mating = []
for k in range(len(r_lst)):
for lst in nested_lst:
if r_lst[k] == lst[0]:
zgt = 0
zgt+= sum([r_freq[k] * freq_lst[int(i[1:])] for i in lst[1:]])
mating.append(zgt)
```
Allow me to simplify a little.
Upvotes: 2 |
2018/03/19 | 611 | 1,939 | <issue_start>username_0: Consider the following list:
```
alist = [18,5,22,6,38,43]
```
This list is composed of numbers ranging from 1 to 49. These 49 numbers are divided into 7 groups:
```
oneto49numbers = list(range(1, 50))
grouped = list(zip(*[iter(oneto49numbers)]*7))
```
How can I check the amount of different groups the numbers in alist come from? For alist, manually determined it would be like this:
```
18 from grouped[2]
5 from grouped[0]
22 from grouped[3]
6 from grouped[0]
38 from grouped[5]
43 from grouped[6]
```
So for **alist** this number would be 5, as the numbers of alist come from 5 different groups. Any help is appreciated.<issue_comment>username_1: How do you know which of the groups you put each number into? You floordiv it by 7 and take that as group-number. Put all into a set (count each group once) and count the lenght of the set:
```
def findUsedGroups(groupSize,data):
"""Partitions 1-based number lists into groups of groupSize.
Returns amount of groups needed for a given data iterable."""
return len(set ( (x-1)//groupSize for x in data))
alist = [18,5,22,6,38,43]
print(findUsedGroups(7,alist))
```
Output:
```
5
```
Upvotes: 1 <issue_comment>username_2: You could do something along these lines:
```
import numpy as np
len(np.unique([[i for i, group in enumerate(grouped) if x in group] for x in alist]))
```
Which returns `5`.
If you wanted to use the information, `[[i for i, group in enumerate(grouped) if x in group] for x in alist]` would return the groups each element belongs to in order:
```
[[2], [0], [3], [0], [5], [6]]
```
and `len(np.unique(...` gives you the number of unique groups in that list of lists.
The only advantage I see to this sort of method as opposed to the `[(x - 1) // 7 for x in alist]` strategy outlined in other posts and in comments is that it would hold up for non-evenly sized groups.
Upvotes: 3 [selected_answer] |
2018/03/19 | 656 | 2,436 | <issue_start>username_0: I have followed this official tutorial [Getting Started Centralized Configuration](https://spring.io/guides/gs/centralized-configuration/) using spring boot 2.0.0.RELEASE and spring cloud Finchley.M8
But refreshing properties on the fly (Without restart) is not working.
After Some debugging, I noticed that in method refresh() from ContextRefresher.class, it returns the changed keys correctly, but after reconstructing the bean annotated with @RefreshScope in the next use. It still sees the old value not the updated one.
>
> Note: This was working perfectly with spring boot v 1.5.6 and spring cloud Edgware.RELEASE.
>
>
>
Any help please?
Thanks<issue_comment>username_1: It seems spring.cloud.config.uri in spring boot 2.0.1.RELEASE always looking for port 8888 and not accepting other values, so I put the below configuration (you can ignore it, as it is the default value for the client, and **the server should run on port 8888**)
```
spring:
cloud:
config:
uri: http://localhost:8888
```
I also tried to expose all other services in the client for testing as follows
```
management:
endpoints:
web:
exposure:
include: '*'
```
or use the following to allow only refresh
```
management:
endpoints:
web:
exposure:
include: refresh
```
Then called POST method not GET for refreshing
```
$ curl -X POST localhost:8080/actuator/refresh -d {} -H "Content-Type: application/json"
```
Finally, it works.
Upvotes: 3 <issue_comment>username_2: [](https://i.stack.imgur.com/KVTE3.png)
Instead of Method "POST" , use "OPTIONS" method to call the "actuator/refresh" for spring boot 2.0 or higher.
For lower versions (<2.0), use the endpoint "context/refresh"
Make sure , you have `management.endpoints.web.exposure.include=*` defined in `application.properties.`
Upvotes: 1 <issue_comment>username_3: Use below in application.properties-
```
management.endpoint.refresh.enabled=true
management.endpoint.restart.enabled=true
management.endpoint.health.enabled=true
management.endpoint.health.show-details=always
management.endpoint.info.enabled=true
management.endpoints.web.exposure.include=info,health,refresh
```
Using yaml configuration file it was not working for me and when switched to properties file, it worked with above configuration.
Thanks
Upvotes: 1 |
2018/03/19 | 1,202 | 3,714 | <issue_start>username_0: I want to overlay multiple videos over a single video at specified interval of time.
have tried with different solution but it will not work as i aspect
i am use below command to overlay video over video
```
String[] cmdWorking3 = new String[]{"-i",yourRealPath,"-i",gifVideoFile1,"-i",gifVideoFile2,"-i",gifVideoFile3,
"-filter_complex",
"[0][1]overlay=100:100:enable='between(t,0,2)'[v1];" +
"[v1][2]overlay=130:130:enable='between(t,0,2)'[v2];" +
"[v2][3]overlay=150:150:enable='between(t,5,6)'[v3];",
"-map","[v3]","-map" ,"0:a",
"-preset", "ultrafast", filePath};
```
by using above command first two video completely works fine but last one will not enable
**Edit:**
//Working perfect
```
String[] cmdWorking11 = new String[]
{"-i",
yourRealPath,
"-i",
gifVideoFile1,
"-i",
gifVideoFile2,
"-i",
gifVideoFile3,
"-i",
gifVideoFile4,
"-filter_complex",
"[1]setpts=PTS+3/TB[1d];" +
"[2]setpts=PTS+7/TB[2d];" +
"[3]setpts=PTS+10/TB[3d];" +
"[0][1]overlay=100:100:enable='between(t,0,2)'[v1];" +
"[v1][1d]overlay=130:130:enable='between(t,3,6)'[v2];" +
"[v2][2d]overlay=130:130:enable='between(t,7,9)'[v3];" +
"[v3][3d]overlay=150:150:enable='between(t,10,13)'[v4];" +
"[1]asetpts=PTS+3/TB[1ad];" +
"[2]asetpts=PTS+7/TB[2ad];" +
"[3]asetpts=PTS+10/TB[3ad];" +
"[0:a][1ad][2ad][3ad]amix=4[a]",
"-map", "[v4]", "-map", "[a]", "-ac", "5",
"-preset",
"ultrafast",
filePath};
```
Above command is perfectly works fine but audio from the overlapped video is gone,can you please help me to solve this issue.
**main Video** time Duration is about **00:15 second** and all **overlay videos are about 3 second**.
it would be great to helping out to solve this issue,Thanks in advance.<issue_comment>username_1: You need to delay your 3rd overlay video to start at the time of overlay.
```
String[] cmdWorking3 = new String[]{"-i",yourRealPath,"-i",gifVideoFile1,"-i",gifVideoFile2,"-i",gifVideoFile3,
"-filter_complex",
"[3]setpts=PTS+5/TB[3d];" +
"[0][1]overlay=100:100:enable='between(t,0,2)'[v1];" +
"[v1][2]overlay=130:130:enable='between(t,0,2)'[v2];" +
"[v2][3d]overlay=150:150:enable='between(t,5,6)'[v3]",
"-map","[v3]","-map" ,"0:a",
"-preset", "ultrafast", filePath};
```
---
To keep audio as well, include in filter\_complex
```
[1]adelay=3000|3000[1ad];
[2]adelay=7000|7000[2ad];
[3]adelay=10000|10000[3ad];
[0:a][1ad][2ad][3ad]amix=5[a]
```
Replace `-map 0:a` with `-map '[a]' -ac 2`
Upvotes: 4 [selected_answer]<issue_comment>username_2: ```
ffmpeg -i test.mp4 -i test1.mp4 -itsoffset 2 -i test2.mp4 -i test3.mp4 -filter_complex "overlay=0:0,overlay=0:0:enable='between(t,2,15)',overlay=0:0" output.mp4
```
where -itsoffset 2 mean that test3.mp4 start play at 2s, and enable='between(t,start\_time,end\_time)' mean this video display duration
Upvotes: 1 |
2018/03/19 | 486 | 1,489 | <issue_start>username_0: I created this bit go regex in the regexer website and it worked with the things I entered, I want to to allow upper and lowercase letters but to not allow combinations over 40 characters, this is the regex...
```
^[a-z]|[A-Z]{1,40}$
```
the line of code is...
```
First name:
```<issue_comment>username_1: The paroblem with `^[a-z]|[A-Z]{1,40}$` is that the pattern will get parsed as `/^(?:^[a-z]|[A-Z]{1,40}$)$/` and thus will match a string that only equals a lowercase ASCII letter or 1 to 40 uppercase ASCII letters (without allowing lowercase ones).
You should fix the pattern like this:
```
^^^^^^^^^^^^^^
```
This will only let users input 1 to 40 ASCII letters.
This regex will be parsed as `/^(?:[a-zA-Z]{1,40})$/` by the HTML5 engine where `^` matches the start of input and `$` matches the end of input.
```css
input:invalid {
color: red;
}
input:valid {
color: black;
}
```
```html
```
Another way to control the length with a pattern is to use `required maxlength="40"` and then you may use a `[A-Za-z]+` pattern:
```css
input:invalid {
color: red;
}
input:valid {
color: black;
}
```
```html
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: Try it like this:
[`^[a-zA-Z]{1,40}$`](https://regex101.com/r/dmMh2K/1)
For the [pattern](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input) attribute you could also use `[a-zA-Z]{1,40}`.
Upvotes: 1 |
2018/03/19 | 881 | 3,119 | <issue_start>username_0: I want to print integer numbers from 1 to a random integer number (e.g. to a random integer number < 10 like in the following case). I can use e.g. one from the following ways:
1)
```
val randomNumber=r.nextInt(10)
for (i <- 0 to randomNumber) {println(i)}
```
2)
```
for (i <- 0 to r.nextInt(10)) {println(i)}
```
My question is the following. Is there a difference between 1) and 2) in the sense of computation? It is clear that a random number `r.nextInt(10)` is computed only once and after that it is assigned to
the variable `randomNumber` in the first case but what about the second case? Is the part `r.nextInt(10)` computed only once at the beginnig of the loop or it is computed for each iteration of the loop? If yes then the first variant is better from computation point of view? I know that this proposed example is an easy example but there can be much more complex `for` loops where the optimization can be very helpful. If the expression `r.nextInt(10)` in the second case is computed only once what about expressions which are e.g. functions of variable `i`, something like `for (i <- 0 to fce(i)) {println(i)}`? I guess that Fce(i) should be evaluated in every iteration of loop.
Thanks for help.
Andrew<issue_comment>username_1: No, there are no differences between 1) and 2).
The bound for the for loop will be evaluated once, and then the for loop will repeat this now fixed number of times.
Things would have been very different comparing those two pieces of code :
```
val randomNumber=r.nextInt(10)
for (i <- 0 to 10) {println(randomNumber)}
```
and
```
for (i <- 0 to 10) {println(r.nextInt(10))}
```
The first for loop will print 10 times the same value, the second will print 10 random values.
But you could still rewrite the second as
```
def randomNumber=r.nextInt(10)
for (i <- 0 to 10) {println(randomNumber)}
```
The change from a val to a function will cause a reevaluation every time the loop is executed.
Now, about
```
for (i <- 0 to function(i)) {doSomething()}
```
This doesn't compile. The variable i is only available in the scope between the {} of the for loop, and hence not for computing the loop bounds.
I hope this clarifies things a bit !
Upvotes: 2 <issue_comment>username_2: The two versions do the same thing, and to see why you need to realise that `for` in Scala works very differently from how it works in other languages like `C/C++`.
In Scala, `for` is just a bit of syntax that makes it easier to chain `map/foreach`, `flatMap`, and `withFilter` methods together. It makes functional code appear more like imperative code, but it is still executed in a functional way.
So your second chunk of code
```
for (i <- 0 to r.nextInt(10)) {println(i)}
```
is changed by the compiler into something like
```
(0 to r.nextInt(10)).foreach{ i => println(i) }
```
Looking at it this way, you can see that the range is computed first (using a single call to `nextInt`) and then `foreach` is called on that range. Therefore `nextInt` is called the same number of times as in your first chunk of code.
Upvotes: 1 |
2018/03/19 | 504 | 1,526 | <issue_start>username_0: I'm trying to get this animated svg tree to work in Wordpress. It works fine in codepen, but not at all in a Wordpress page on my localhost.
Can anyone see what is missing/wrong? In the page source code the javascript files are loading.
[svg tree](https://i.stack.imgur.com/oRw7D.png)
```js
var svg = $("#svg-container");
svg.children().find("path:not(.except)").click(function(e) {
$("#Layer_1 path").removeAttr("style");
$this = $(this);
var bbox = this.getBBox();
var centreX = bbox.x + bbox.width / 2;
var centreY = bbox.y + bbox.height / 2;
$this.css("transform-origin", centreX + 'px ' + centreY + 'px');
$this.css("transform", "scale(4)");
$this.css("stroke", "");
$this.css("fill", "");
this.parentElement.appendChild(this);
})
```
```css
#svg-container {
width: 500px;
height: 500px;
}
#svg-container svg {
width: 100%;
height: 100%;
}
@font-face {
font-family: "Amaranth";
src: url('https://fonts.googleapis.com/css?family=Amaranth');
}
```
```html
< ![CDATA[
]] >
The tree
```
<https://codepen.io/paulfadams/pen/PRzMNE?editors=1111><issue_comment>username_1: I had this same issue once.
WordPress ships with its own version of the jQuery library.
Try using "jQuery" instead of just "$" sign.
For example:
var svg = $("#svg-container"); should be replaced with var svg = jQuery("#svg-container");
Upvotes: 1 <issue_comment>username_2: Use jQuery instead of the "$" sign. ex: `jQuery("#svg-container");`
Upvotes: 0 |
2018/03/19 | 239 | 934 | <issue_start>username_0: In `VkSubmitInfo`, when `pWaitDstStageMask[0]` is `VK_PIPLINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT`, **vulkan** implementation executes pipeline stages without waitng for `pWaitSemaphores[0]` until it reaches Color Attachment Stage.
However, if the command buffer has multiple subpasses and multiple draw commands, then does `WaitDstStageMask` mean the stages of all draw commands?
If I want `vulkan` implementation to wait the semaphore when it reaches color attachment output stage of the last subpass, what should I do?<issue_comment>username_1: I had this same issue once.
WordPress ships with its own version of the jQuery library.
Try using "jQuery" instead of just "$" sign.
For example:
var svg = $("#svg-container"); should be replaced with var svg = jQuery("#svg-container");
Upvotes: 1 <issue_comment>username_2: Use jQuery instead of the "$" sign. ex: `jQuery("#svg-container");`
Upvotes: 0 |
2018/03/19 | 406 | 1,406 | <issue_start>username_0: Often after refactoring `throws` sections become unnecessary. IntelliJ highlights them with grey showing that they can be removed, but I'd like to remove them automatically (just like unused imports get removed via `ctrl`+`alt`+`O`).
**Q:** Is there a way to automatically remove unused `throws` sections within a class? Is there a shortcut for that?<issue_comment>username_1: You can use `Alt`+`Enter` and select Cleanup code.
This will remove all unnecessary throws Exception declarations.
Upvotes: 2 <issue_comment>username_2: There are two ways I am aware of:
1. **[Quick Code Cleanup.](https://www.jetbrains.com/help/idea/specify-code-cleanup-scope-dialog.html)**
I use the `^``⇧``⌘``C` combination. There was no default hotkey.
[](https://i.stack.imgur.com/GmPfu.png)
You can specify code cleanup scope. It might be the whole project or a custom scope.
[](https://i.stack.imgur.com/lPqkz.png)
2. **[Removing the redundant clause.](https://www.jetbrains.com/help/idea/applying-intention-actions.html)**
It gets accessible on the focused clause (you put the mouse on the element) with `alt``⏎`.
[](https://i.stack.imgur.com/wAK4A.png)
Upvotes: 4 [selected_answer] |
2018/03/19 | 472 | 1,230 | <issue_start>username_0: Simple question, but I can´t get over it...
I have two arrays:
```
var arrayA = [67.98, "-", 91.77, "-", "-", 8.09];
var arrayB = [3, 4, 9, 1, 12, 77];
```
So, I need to remove all values from arrayB which have the indexes of the value `"-"` in `arrayA`. In this case the result of arrayB should be:
```
arrayB = [3, 9, 77]
```
Many thanks.<issue_comment>username_1: Use `Array.filter()` on `arrayB`, and preserve items that their respective item in `arrayA` is not a dash:
```js
var arrayA = [67.98, "-", 91.77, "-", "-", 8.09];
var arrayB = [3, 4, 9, 1, 12, 77];
var result = arrayB.filter(function(_, i) {
return arrayA[i] !== '-';
});
console.log(result);
```
Upvotes: 4 [selected_answer]<issue_comment>username_2: ```js
var arrayA = [67.98, "-", 91.77, "-", "-", 8.09];
var arrayB = [3, 4, 9, 1, 12, 77];
for (var i = arrayB.length - 1; i >= 0; i--) {
if (arrayA[i] == "-") {
arrayB.splice(i, 1);
}
}
console.log(arrayB);
```
See: [Looping through array and removing items, without breaking for loop](https://stackoverflow.com/questions/9882284/looping-through-array-and-removing-items-without-breaking-for-loop)
Upvotes: 1 |
2018/03/19 | 383 | 1,116 | <issue_start>username_0: I am receiving HTTP requests on a Tibco service using **HTTP Receiver** element, and I would like a way to extract or parse the Soap Body from the Request, without resorting to using the **Soap Event Source element**. Is there a way?<issue_comment>username_1: Use `Array.filter()` on `arrayB`, and preserve items that their respective item in `arrayA` is not a dash:
```js
var arrayA = [67.98, "-", 91.77, "-", "-", 8.09];
var arrayB = [3, 4, 9, 1, 12, 77];
var result = arrayB.filter(function(_, i) {
return arrayA[i] !== '-';
});
console.log(result);
```
Upvotes: 4 [selected_answer]<issue_comment>username_2: ```js
var arrayA = [67.98, "-", 91.77, "-", "-", 8.09];
var arrayB = [3, 4, 9, 1, 12, 77];
for (var i = arrayB.length - 1; i >= 0; i--) {
if (arrayA[i] == "-") {
arrayB.splice(i, 1);
}
}
console.log(arrayB);
```
See: [Looping through array and removing items, without breaking for loop](https://stackoverflow.com/questions/9882284/looping-through-array-and-removing-items-without-breaking-for-loop)
Upvotes: 1 |
2018/03/19 | 912 | 4,087 | <issue_start>username_0: I am creating an API using Spring Boot Rest, I want to restrict the API so only logged in users can access it. Now to test the API I am using postman, but how to pass the user details to the API?
Here is my code:
```
@Configuration
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private AccessDeniedHandler accessDeniedHandler;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers(HttpMethod.GET, "/", "/orders").permitAll()
.antMatchers(HttpMethod.POST, "/order/**").hasAnyRole("ADMIN")
.antMatchers(HttpMethod.DELETE, "/order/**").hasAnyRole("ADMIN")
.and()
.exceptionHandling().accessDeniedHandler(accessDeniedHandler);
}
// create two users, admin and user
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("user").password("<PASSWORD>").roles("USER")
.and()
.withUser("admin").password("<PASSWORD>").roles("ADMIN");
}
}
```
Here is my access denied handler:
```
@Component
public class MyAccessDeniedHandler implements AccessDeniedHandler {
private static Logger logger = LoggerFactory.getLogger(MyAccessDeniedHandler.class);
@Override
public void handle(HttpServletRequest httpServletRequest,
HttpServletResponse httpServletResponse,
AccessDeniedException e) throws IOException, ServletException {
Authentication auth
= SecurityContextHolder.getContext().getAuthentication();
if (auth != null) {
logger.info("User '" + auth.getName()
+ "' attempted to access the protected URL: "
+ httpServletRequest.getRequestURI());
}
httpServletResponse.setContentType("application/json");
ServletOutputStream outputStream = httpServletResponse.getOutputStream();
outputStream.print("Wrong user");
}
}
```
When I try to access the API with URL as `order` and method as `DELETE` using `postman` and passing user login details using `Authorization` tab with `Basic Auth` and passing Username as `admin` and password as `<PASSWORD>`, I am getting `Wrong user` message.
How to pass the user loin details to my API using `postman`?<issue_comment>username_1: Maybe form login is the default auth mechanism and you need to specify that you want to use Basic Auth.
Try this:
```
@Configuration
class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private AccessDeniedHandler accessDeniedHandler;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers(HttpMethod.GET, "/", "/orders").permitAll()
.antMatchers(HttpMethod.POST, "/order/**").hasAnyRole("ADMIN")
.antMatchers(HttpMethod.DELETE, "/order/**").hasAnyRole("ADMIN")
.and()
.exceptionHandling().accessDeniedHandler(accessDeniedHandler)
.and() //added
.httpBasic(); //added
}
// create two users, admin and user
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("user").password("<PASSWORD>").roles("USER")
.and()
.withUser("admin").password("<PASSWORD>").roles("ADMIN");
}
}
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: What you need is the following dependency (You might have it already):
```
org.springframework.boot
spring-boot-starter-security
```
Than you can create a user in your application.properties file:
```
security.user.name=username
security.user.password=<PASSWORD>
```
If you are using Spring 2.0.0 M4 or higher use "spring.security".
Now go to Postman under "Authorization" use "Basic Auth" and fill in the credenrtials you have set in the properties file.
Hope this is what you are looking for. Good luck:)
Upvotes: -1 |
2018/03/19 | 542 | 2,066 | <issue_start>username_0: When I import `tensorflow` in Python I get this error:
>
> C:\Users\Sathsara\Anaconda3\envs\tensorflow\Lib\site-packages\h5py\_\_init\_\_.py:36:
> FutureWarning: Conversion of the second argument of issubdtype from
> float to np.floating is deprecated. In future, it will be treated
> as np.float64 == np.dtype(float).type. from .\_conv import
> register\_converters as \_register\_converters
>
>
><issue_comment>username_1: Maybe form login is the default auth mechanism and you need to specify that you want to use Basic Auth.
Try this:
```
@Configuration
class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private AccessDeniedHandler accessDeniedHandler;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers(HttpMethod.GET, "/", "/orders").permitAll()
.antMatchers(HttpMethod.POST, "/order/**").hasAnyRole("ADMIN")
.antMatchers(HttpMethod.DELETE, "/order/**").hasAnyRole("ADMIN")
.and()
.exceptionHandling().accessDeniedHandler(accessDeniedHandler)
.and() //added
.httpBasic(); //added
}
// create two users, admin and user
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("user").password("<PASSWORD>").roles("USER")
.and()
.withUser("admin").password("<PASSWORD>").roles("ADMIN");
}
}
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: What you need is the following dependency (You might have it already):
```
org.springframework.boot
spring-boot-starter-security
```
Than you can create a user in your application.properties file:
```
security.user.name=username
security.user.password=<PASSWORD>
```
If you are using Spring 2.0.0 M4 or higher use "spring.security".
Now go to Postman under "Authorization" use "Basic Auth" and fill in the credenrtials you have set in the properties file.
Hope this is what you are looking for. Good luck:)
Upvotes: -1 |
2018/03/19 | 1,370 | 2,671 | <issue_start>username_0: I have a pandas data-frame with a column with float numbers. I tried to split each item in a column by dot '.'. Then I want to add first items to second items. I don't know why this sample code is not working.
```
data=
0 28.47000
1 28.45000
2 28.16000
3 28.29000
4 28.38000
5 28.49000
6 28.21000
7 29.03000
8 29.11000
9 28.11000
new_array = []
df = list(data)
for i in np.arange(len(data)):
df1 = df[i].split('.')
df2 = df1[0]+df[1]/60
new_array=np.append(new_array,df2)
```<issue_comment>username_1: Use [`numpy.modf`](https://docs.scipy.org/doc/numpy-1.12.0/reference/generated/numpy.modf.html) with `DataFrame` constructor:
```
arr = np.modf(data.values)
df = pd.DataFrame({'a':data, 'b':arr[1] + arr[0] / 60})
print (df)
a b
0 28.47 28.007833
1 28.45 28.007500
2 28.16 28.002667
3 28.29 28.004833
4 28.38 28.006333
5 28.49 28.008167
6 28.21 28.003500
7 29.03 29.000500
8 29.11 29.001833
9 28.11 28.001833
```
**Detail**:
```
arr = np.modf(data.values)
print(arr)
(array([ 0.47, 0.45, 0.16, 0.29, 0.38, 0.49, 0.21, 0.03, 0.11, 0.11]),
array([ 28., 28., 28., 28., 28., 28., 28., 29., 29., 28.]))
print(arr[0] / 60)
[ 0.00783333 0.0075 0.00266667 0.00483333 0.00633333 0.00816667
0.0035 0.0005 0.00183333 0.00183333]
```
EDIT:
```
df = pd.DataFrame({'a':data, 'b':arr[1] + arr[0]*5/3 })
print (df)
a b
0 28.47 28.783333
1 28.45 28.750000
2 28.16 28.266667
3 28.29 28.483333
4 28.38 28.633333
5 28.49 28.816667
6 28.21 28.350000
7 29.03 29.050000
8 29.11 29.183333
9 28.11 28.183333
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: Your data types are floats, not strings, and so cannot be .split() (*this is a string method*). Instead you can look to use math.modf to 'split' a float into fractional and decimal parts
<https://docs.python.org/3.6/library/math.html>
```
import math
def process(x:float, divisor:int=60) -> float:
"""
Convert a float to its constituent parts. Divide the fractional part by the divisor, and then recombine creating a 'scaled fractional' part,
"""
b, a = math.modf(x)
c = a + b/divisor
return c
df['data'].apply(process)
Out[17]:
0 28.007833
1 28.007500
2 28.002667
3 28.004833
4 28.006333
5 28.008167
6 28.003500
7 29.000500
8 29.001833
9 28.001833
Name: data=, dtype: float64
```
Your other option is to convert them to strings, split, convert to ints and floats again, do some maths and then combine the floats. I'd rather keep the object as it is personally.
Upvotes: 1 |
2018/03/19 | 1,193 | 2,346 | <issue_start>username_0: Where should you put the `API-calls` in **Redux**?
I think they belong in Actions because they are part of the `data` and don't have side-effects.
Does that sound right?
I want to avoid RxJS or ReduxSaga.<issue_comment>username_1: Use [`numpy.modf`](https://docs.scipy.org/doc/numpy-1.12.0/reference/generated/numpy.modf.html) with `DataFrame` constructor:
```
arr = np.modf(data.values)
df = pd.DataFrame({'a':data, 'b':arr[1] + arr[0] / 60})
print (df)
a b
0 28.47 28.007833
1 28.45 28.007500
2 28.16 28.002667
3 28.29 28.004833
4 28.38 28.006333
5 28.49 28.008167
6 28.21 28.003500
7 29.03 29.000500
8 29.11 29.001833
9 28.11 28.001833
```
**Detail**:
```
arr = np.modf(data.values)
print(arr)
(array([ 0.47, 0.45, 0.16, 0.29, 0.38, 0.49, 0.21, 0.03, 0.11, 0.11]),
array([ 28., 28., 28., 28., 28., 28., 28., 29., 29., 28.]))
print(arr[0] / 60)
[ 0.00783333 0.0075 0.00266667 0.00483333 0.00633333 0.00816667
0.0035 0.0005 0.00183333 0.00183333]
```
EDIT:
```
df = pd.DataFrame({'a':data, 'b':arr[1] + arr[0]*5/3 })
print (df)
a b
0 28.47 28.783333
1 28.45 28.750000
2 28.16 28.266667
3 28.29 28.483333
4 28.38 28.633333
5 28.49 28.816667
6 28.21 28.350000
7 29.03 29.050000
8 29.11 29.183333
9 28.11 28.183333
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: Your data types are floats, not strings, and so cannot be .split() (*this is a string method*). Instead you can look to use math.modf to 'split' a float into fractional and decimal parts
<https://docs.python.org/3.6/library/math.html>
```
import math
def process(x:float, divisor:int=60) -> float:
"""
Convert a float to its constituent parts. Divide the fractional part by the divisor, and then recombine creating a 'scaled fractional' part,
"""
b, a = math.modf(x)
c = a + b/divisor
return c
df['data'].apply(process)
Out[17]:
0 28.007833
1 28.007500
2 28.002667
3 28.004833
4 28.006333
5 28.008167
6 28.003500
7 29.000500
8 29.001833
9 28.001833
Name: data=, dtype: float64
```
Your other option is to convert them to strings, split, convert to ints and floats again, do some maths and then combine the floats. I'd rather keep the object as it is personally.
Upvotes: 1 |
2018/03/19 | 566 | 2,002 | <issue_start>username_0: I'm trying to find out how can I set up `row` and `columnspan` of programmatically created `DataGrid`. My code adds it in the first row:
```
private DataGrid CreateTextBoxesDataGrid(string name)
{
DataGrid dataGrid = new DataGrid();
dataGrid.Name = name;
//row ???
dataGrid.Style = Resources["AppSettingsDataGridStyle"] as Style;
dataGrid.Columns.Add(CreateNameColumn());
dataGrid.Columns.Add(CreateTextValueColumn());
dataGrid.Columns.Add(CreateComentColumn());
return dataGrid;
}
...
mainGrid.Children.Add(CreateTextBoxesDataGrid("eeej"));
```<issue_comment>username_1: That's the code:
```
Grid.SetColumnSpan(dataGrid, colSpan);
Grid.SetRow(dataGrid, row);
```
Upvotes: 1 <issue_comment>username_2: To set a ColumnSpan on the DataGrid itself does not really make sense. The ColumnSpan defines how many columns a control on the grid will span across. So as you see, this is something you want to set per control that is INSIDE the grid, not on the grid itself.
Are you intending to set the width of the column of the DataGrid? If that is the case, you can do something like this:
```
column.Width = new DataGridLength(1, DataGridLengthUnitType.Auto);
```
Or like this if you want it based on the entire width of the DataGrid:
```
column.Width = new DataGridLength(1, DataGridLengthUnitType.Star);
```
If you want to add a new row programatically to the DataGrid, you can do this:
```
public class DataGridRow
{
public string Col1 { get; set; }
public string Col2 { get; set; }
}
```
...
```
var row = new DataGridRow{ Col1 = "Column1", Col2 = "Column2" };
dataGrid.Items.Add(row);
```
If you want to set how many columns the DataGrid will span inside it's parent grid, you can use the following:
```
Grid.SetColumnSpan(dataGrid, columnsToSpan);
```
I'm just guessing what you want here, if I did not understand you correctly, feel free to reply to my answer with more details.
Upvotes: 3 [selected_answer] |
2018/03/19 | 1,197 | 4,003 | <issue_start>username_0: I am going to encrypted several fields in existing table. Basically, the following encryption technique is going to be used:
```
CREATE MASTER KEY ENCRYPTION
BY PASSWORD = '<PASSWORD>@'
GO
CREATE CERTIFICATE CERT_01
WITH SUBJECT = 'CERT_01'
GO
CREATE SYMMETRIC KEY SK_01
WITH ALGORITHM = AES_256 ENCRYPTION
BY CERTIFICATE CERT_01
GO
OPEN SYMMETRIC KEY SK_01 DECRYPTION
BY CERTIFICATE CERT_01
SELECT ENCRYPTBYKEY(KEY_GUID('SK_01'), 'test')
CLOSE SYMMETRIC KEY SK_01
DROP SYMMETRIC KEY SK_01
DROP CERTIFICATE CERT_01
DROP MASTER KEY
```
The [ENCRYPTBYKEY](https://stackoverflow.com/questions/37329666/sql-server-truncating-encrypted-values) returns `varbinary` with a maximum size of 8,000 bytes. Knowing the table fields going to be encrypted (for example: `nvarchar(128)`, `varchar(31)`, `bigint`) how can I define the new `varbinary` types length?<issue_comment>username_1: You can see the full specification [here](https://blogs.msdn.microsoft.com/sqlsecurity/2009/03/30/sql-server-encryptbykey-cryptographic-message-description/)
So lets calculate:
* `16` byte key UID
* `_4` bytes header
* `16` byte IV (for AES, a 16 byte block cipher)
Plus then the size of the encrypted message:
* `_4` byte magic number
* `_2` bytes integrity bytes length
* `_0` bytes integrity bytes (warning: may be wrongly placed in the table)
* `_2` bytes (plaintext) message length
* `_m` bytes (plaintext) message
* CBC padding bytes
The CBC padding bytes should be calculated the following way:
```
16 - ((m + 4 + 2 + 2) % 16)
```
as padding is always applied. This will result in a number of padding bytes in the range 1..16. A sneaky shortcut is to just add 16 bytes to the total, but this may mean that you're specifying up to 15 bytes that are never used.
---
We can shorten this to `36 + 8 + m + 16 - ((m + 8) % 16)` or `60 + m - ((m + 8) % 16`. Or if you use the little trick specified above and you don't care about the wasted bytes: `76 + m` where m is the message input.
---
Notes:
* beware that the first byte in the header contains the version number of the scheme; this answer does *not* and *cannot* specify how many bytes will be added or removed if a different internal message format or encryption scheme is used;
* using integrity bytes is highly recommended in case you want to protect your DB fields against change (keeping the amount of money in an account confidential is less important than making sure the amount cannot be changed).
* The example on the page assumes single byte encoding for text characters.
Upvotes: 4 [selected_answer]<issue_comment>username_2: Based upon some tests in SQL Server 2008, the following formula seems to work. Note that @ClearText is VARCHAR():
```
52 + (16 * ( ((LEN(@ClearText) + 8)/ 16) ) )
```
This is roughly compatible with the answer by username_1, except that my tests showed the DATALENGTH(myBinary) to always be of the form `52 + (z * 16)`, where `z` is an integer.
```
LEN(myVarCharString) DATALENGTH(encryptedString)
-------------------- -----------------------------------------
0 through 7 usually 52, but occasionally 68 or 84
8 through 23 usually 68, but occasionally 84
24 through 39 usually 84
40 through 50 100
```
The "myVarCharString" was a table column defined as VARCHAR(50). The table contained 150,000 records. The mention of "occasionally" is an instance of about 1 out of 10,000 records that would get bumped into a higher bucket; very strange. For LEN() of 24 and higher, there were not enough records to get the weird anomaly.
Here is some Perl code that takes a proposed length for "myVarCharString" as input from the terminal and produces an expected size for the EncryptByKey() result. The function "int()" is equivalent to "Math.floor()".
```
while($len = <>) {
print 52 + ( 16 * int( ($len+8) / 16 ) ),"\n";
}
```
You might want to use this formula to calculate a size, then add 16 to allow for the anomaly.
Upvotes: 2 |
2018/03/19 | 1,399 | 5,346 | <issue_start>username_0: >
> When application launched first a vertical surface is detected on one wall than camera focus to the second wall, in the second wall another surface is detected. The first wall is now no more visible to the ARCamera but this code is providing me the anchors of the first wall. but I need anchors of the second wall which is right now Visible/focused in camera.
>
>
>
```
if let anchor = sceneView.session.currentFrame?.anchors.first {
let node = sceneView.node(for: anchor)
addNode(position: SCNVector3Zero, anchorNode: node)
} else {
debugPrint("anchor node is nil")
}
```<issue_comment>username_1: The clue to the answer is in the beginning line of your `if let` statement.
Lets break this down:
When you say `let anchor = sceneView.session.currentFrame?.anchors.first`, you are referencing an optional array of `ARAnchor`, which naturally can have more than one element.
Since your are always calling `first` e.g. index [0], you will always get the 1st `ARAnchor` which was added to the array.
Since you now have 2 anchors, you would naturally need the last (latest) element. As such you can try this as a starter:
```
if let anchor = sceneView.session.currentFrame?.anchors.last {
let node = sceneView.node(for: anchor)
addNode(position: SCNVector3Zero, anchorNode: node)
} else {
debugPrint("anchor node is nil")
}
```
**Update:**
Since another poster has interpreted the question differently, in that they believe the question is *how can I detect if an ARPlaneAnchor is in view?* Let's approach it another way.
First we need to take into consideration that the ARCamera has a Frostrum in which our content is shown:
[](https://i.stack.imgur.com/eAPBs.png)
As such, we would then need to determine whether an ARPlaneAnchor was `inViewOfFrostrum`.
First we will create 2 variables:
```
var planesDetected = [ARPlaneAnchor: SCNNode]()
var planeID: Int = 0
```
The 1st to store the `ARPlaneAnchor` and its associated `SCNNode`, and the 2nd in order to provide a unique ID for each plane.
In the `ARSCNViewDelegate` we can visualise an ARPlaneAnchor and then store it's information e.g:
```
func renderer(_ renderer: SCNSceneRenderer, didAdd node: SCNNode, for anchor: ARAnchor) {
//1. Get The Current ARPlaneAnchor
guard let anchor = anchor as? ARPlaneAnchor else { return }
//2. Create An SCNode & Geometry To Visualize The Plane
let planeNode = SCNNode()
let planeGeometry = SCNPlane(width: CGFloat(anchor.extent.x), height: CGFloat(anchor.extent.z))
planeGeometry.firstMaterial?.diffuse.contents = UIColor.cyan
planeNode.geometry = planeGeometry
//3. Set The Position Based On The Anchors Extent & Rotate It
planeNode.position = SCNVector3(anchor.center.x, anchor.center.y, anchor.center.z)
planeNode.eulerAngles.x = -.pi / 2
//4. Add The PlaneNode To The Node & Give It A Unique ID
node.addChildNode(planeNode)
planeNode.name = String(planeID)
//5. Store The Anchor & Node
planesDetected[anchor] = planeNode
//6. Increment The Plane ID
planeID += 1
}
```
Now we have stored the detected planes, we then of course need to determine if any of these are in view of the ARCamera e.g:
```
/// Detects If An Object Is In View Of The Camera Frostrum
func detectPlaneInFrostrumOfCamera(){
//1. Get The Current Point Of View
if let currentPointOfView = augmentedRealityView.pointOfView{
//2. Loop Through All The Detected Planes
for anchorKey in planesDetected{
let anchor = anchorKey.value
if augmentedRealityView.isNode(anchor, insideFrustumOf: currentPointOfView){
print("ARPlaneAnchor With ID \(anchor.name!) Is In View")
}else{
print("ARPlaneAnchor With ID \(anchor.name!) Is Not In View")
}
}
}
}
```
Finally we then need to access this function which we could do in the following `delegate` method for example `renderer(_ renderer: SCNSceneRenderer, updateAtTime time: TimeInterval)`:
```
func renderer(_ renderer: SCNSceneRenderer, updateAtTime time: TimeInterval) {
detectPlaneInFrostrumOfCamera()
}
```
Hopefully both of these will point in the right direction...
Upvotes: 3 <issue_comment>username_2: In order to get the node that is currently is in point of view you can do something like this:
```
var targettedAnchorNode: SCNNode?
if let anchors = sceneView.session.currentFrame?.anchors {
for anchor in anchors {
if let anchorNode = sceneView.node(for: anchor), let pointOfView = sceneView.pointOfView, sceneView.isNode(anchorNode, insideFrustumOf: pointOfView) {
targettedAnchorNode = anchorNode
break
}
}
if let targettedAnchorNode = targettedAnchorNode {
addNode(position: SCNVector3Zero, anchorNode: targettedAnchorNode)
} else {
debugPrint("Targetted node not found")
}
} else {
debugPrint("Anchors not found")
}
```
If you would like to get all focused nodes, collect them in an array satisfying specified condition
Good luck!
Upvotes: 3 [selected_answer] |
2018/03/19 | 2,040 | 9,095 | <issue_start>username_0: I am working on an IoT app in which there is an on boarding process where the user connects to an access point, which has not internet connectivity, configure the device and then connects to his home Wifi network.
Android 8 devices have been causing some problems, disconnecting from the access point and reconnecting to a previously configured network. I am assuming this is related to the connectivity update which was introduced in Android 8, from section Seamless Connectivity in [this link](https://developer.android.com/about/versions/oreo/android-8.0-changes.html):
>
> On compatible devices, automatic activation of Wi-Fi when a high
> quality saved network is nearby.
>
>
>
My question is how to disable this behaviour as I need to stay connected to the access point, without internet connectivity, and finish the on Boarding process.<issue_comment>username_1: I had the same issue. What I did is adding a step to the boarding process where I invite the user to go to there settings, add manually this network with no data and accept the popup shown by the system.
I have not found a real solution yet.
However, I've seen an app called eWeLink where they manage to do it, but it is not an open source project.
Upvotes: 1 <issue_comment>username_2: I am currently facing the same issue right now for the newer phone with Android 8.+. I am using WifiManager call `bindProcessToNetwork` [here](https://developer.android.com/reference/android/net/ConnectivityManager.html#bindProcessToNetwork(android.net.Network)) this will allows data traffic go through the wifi with no internet access,
here how I connect my phone to the access point
```
//Method to connect to WIFI Network
public boolean connectTo(String networkSSID, String key) {
WifiConfiguration config = new WifiConfiguration();
WifiInfo info = wifi.getConnectionInfo(); //get WifiInfo
int id = info.getNetworkId(); //get id of currently connected network
config.SSID = "\"" + networkSSID + "\"";
if (key.isEmpty()) {
config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
}
int netID = wifi.addNetwork(config);
int tempConfigId = getExistingNetworkId(config.SSID);
if (tempConfigId != -1) {
netID = tempConfigId;
}
boolean disconnect = wifi.disconnect();
wifi.disableNetwork(id); //disable current network
boolean enabled = wifi.enableNetwork(netID, true);
boolean connected = wifi.reconnect();
if (((Build.VERSION.SDK_INT >= Build.VERSION_CODES.M))
|| ((Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
&& !(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M))) {
final ConnectivityManager manager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkRequest.Builder builder;
builder = new NetworkRequest.Builder();
//set the transport type do WIFI
builder.addTransportType(NetworkCapabilities.TRANSPORT_WIFI);
manager.requestNetwork(builder.build(), new ConnectivityManager.NetworkCallback() {
@Override
public void onAvailable(Network network) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
manager.bindProcessToNetwork(network);
} else {
ConnectivityManager.setProcessDefaultNetwork(network);
}
try {
} catch (Exception e) {
e.printStackTrace();
}
manager.unregisterNetworkCallback(this);
}
});
}
```
after connecting to the access point created by the device, it will constantly drop off from it.
Upvotes: 1 <issue_comment>username_3: I had same issue. This is how I fix this issue in Android 8+ devices.
1. Since Android 8+ devices auto switch between WiFI and Cellular devices. I removed below code. i.e. Code to force move to wifi.
```
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
NetworkRequest.Builder request = new NetworkRequest.Builder();
Log.i("forceCellularConnection","request WIFI enable");
request.addCapability(NetworkCapabilities.TRANSPORT_WIFI);
connectivityManager.requestNetwork(request.build(), new ConnectivityManager.NetworkCallback() {
@Override
public void onAvailable(Network network) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
connectivityManager.setProcessDefaultNetwork(network);
connectivityManager.bindProcessToNetwork(network);
}
}
});
}
```
2. Also added below code to forget wifi connection before we make new connection. It takes some time for device to disconnect WiFI. So I added delay before connecting to new WIFI SSID.
```
this.wifiManager.disableNetwork(configuration.networkId);
this.wifiManager.removeNetwork(configuration.networkId);
this.wifiManager.saveConfiguration(); // Not needed in API level 26 and above
```
Workaround which I tried and helped me making connection work are below: In my case also I have to connect WiFi which doesn't have internet on it. Its a peer to peer connection.
1. I Made 2-3 attempts for connection
```
new CountDownTimer(16000, 2000) {
```
2. Also I have written below broadcast receiver to check the state of WiFI. And then made the connection.
```
private final BroadcastReceiver broadcastReceiver = new BroadcastReceiver()
{
@Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
Log.d("WifiReceiver", ">>>>SUPPLICANT_STATE_CHANGED_ACTION<<<<<<");
SupplicantState supl_state = ((SupplicantState) intent
.getParcelableExtra(WifiManager.EXTRA_NEW_STATE));
switch (supl_state) {
case ASSOCIATED:
Log.i("SupplicantState", "ASSOCIATED");
// authMsg = "ASSOCIATED";
break;
case ASSOCIATING:
// authMsg = "ASSOCIATING";
Log.i("SupplicantState", "ASSOCIATING");
break;
case AUTHENTICATING:
// authMsg = "AUTHENTICATING";
Log.i("SupplicantState", "Authenticating...");
break;
case COMPLETED:
authMsg = "CONNECTED";
Log.i("SupplicantState", "Connected");
final ConnectivityManager connection_manager =
(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkRequest.Builder request = new NetworkRequest.Builder();
request.addTransportType(NetworkCapabilities.TRANSPORT_WIFI);
connection_manager.registerNetworkCallback(request.build(), new ConnectivityManager.NetworkCallback() {
@Override
public void onAvailable(Network network) {
ConnectivityManager.setProcessDefaultNetwork(network);
}
});
break;
case DISCONNECTED:
```
Upvotes: 2 <issue_comment>username_4: Just wanted to add a bit to the discussion. I've been using bindProcessToNetwork for a while and it does fix the loss of WiFi when connected to one without a network as described by username_2. This is a heavy handed solution that makes it difficult to use Mobile network at the same time. However, the routing layer is rather broken on Android somewhere around 6 where they started forcing request to mobile even though the routing table indicates the wifi device.
Anyway, you can actually bind at a socket level which I describe below. This may help when the process has been bound to the WiFi network and you still want to use mobile. Instead of looking up WiFi (which is what I was experimenting with instead of binding the process), you look up the mobile 'Network' object and build a socket to it.
What we need is something that indicates to android not to drop the WiFi connection.
HttpUrlConnection doesn't allow you to get the socket so you can use okhttp to do it at the per-connection level. I'm using 2.7.5 of OkHttp but it is very similar for the 3+ version of OkHttp.
You get the current networks then process each to find WiFi network.
```
Network[] networks = connectivityManager.getAllNetworks();
```
Then you build the url like:
```
String url = "http://someurl";
HttpUrlConnection uconn = new OkUrlFactory( new OkHttpClient().setSocketFactory(network.getSocketFactory())).open(url)
```
This all works fine for a few connections and sometimes it works for the series of connections I used. Android is using the knowledge that activity is happening over the network but any pauses and it jumps back to using mobile. Android 9 wifi is just flawed and haven't figured out how to make it sticky using the socket solution. There may be one.
Upvotes: 1 |
2018/03/19 | 2,072 | 8,858 | <issue_start>username_0: I have the below text:
```
PL/SQL: ORA-00904: "TFSE"."PRODUCT_C": invalid identifier
```
I want to get the value PRODUCT\_C, but I am getting TFSE instead
this is my query, usually the text was`ora-00904 PRODUCT_C` so the below was working.
```
select regexp_substr('PL/SQL: ORA-00904: "TFSE"."PRODUCT_C": invalid identifier', '[^"]+', 1, 2) from dual
```
edit:
sometime my message will be like this
`PL/SQL: ORA-00904: "PRODUCT_C": invalid identifier`
or like this
`PL/SQL: ORA-00904: "TFSE"."PRODUCT_C": invalid identifier`
how can i adjust the regex\_substr in a way to have result `
`PRODUCT_C`<issue_comment>username_1: I had the same issue. What I did is adding a step to the boarding process where I invite the user to go to there settings, add manually this network with no data and accept the popup shown by the system.
I have not found a real solution yet.
However, I've seen an app called eWeLink where they manage to do it, but it is not an open source project.
Upvotes: 1 <issue_comment>username_2: I am currently facing the same issue right now for the newer phone with Android 8.+. I am using WifiManager call `bindProcessToNetwork` [here](https://developer.android.com/reference/android/net/ConnectivityManager.html#bindProcessToNetwork(android.net.Network)) this will allows data traffic go through the wifi with no internet access,
here how I connect my phone to the access point
```
//Method to connect to WIFI Network
public boolean connectTo(String networkSSID, String key) {
WifiConfiguration config = new WifiConfiguration();
WifiInfo info = wifi.getConnectionInfo(); //get WifiInfo
int id = info.getNetworkId(); //get id of currently connected network
config.SSID = "\"" + networkSSID + "\"";
if (key.isEmpty()) {
config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
}
int netID = wifi.addNetwork(config);
int tempConfigId = getExistingNetworkId(config.SSID);
if (tempConfigId != -1) {
netID = tempConfigId;
}
boolean disconnect = wifi.disconnect();
wifi.disableNetwork(id); //disable current network
boolean enabled = wifi.enableNetwork(netID, true);
boolean connected = wifi.reconnect();
if (((Build.VERSION.SDK_INT >= Build.VERSION_CODES.M))
|| ((Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
&& !(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M))) {
final ConnectivityManager manager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkRequest.Builder builder;
builder = new NetworkRequest.Builder();
//set the transport type do WIFI
builder.addTransportType(NetworkCapabilities.TRANSPORT_WIFI);
manager.requestNetwork(builder.build(), new ConnectivityManager.NetworkCallback() {
@Override
public void onAvailable(Network network) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
manager.bindProcessToNetwork(network);
} else {
ConnectivityManager.setProcessDefaultNetwork(network);
}
try {
} catch (Exception e) {
e.printStackTrace();
}
manager.unregisterNetworkCallback(this);
}
});
}
```
after connecting to the access point created by the device, it will constantly drop off from it.
Upvotes: 1 <issue_comment>username_3: I had same issue. This is how I fix this issue in Android 8+ devices.
1. Since Android 8+ devices auto switch between WiFI and Cellular devices. I removed below code. i.e. Code to force move to wifi.
```
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
NetworkRequest.Builder request = new NetworkRequest.Builder();
Log.i("forceCellularConnection","request WIFI enable");
request.addCapability(NetworkCapabilities.TRANSPORT_WIFI);
connectivityManager.requestNetwork(request.build(), new ConnectivityManager.NetworkCallback() {
@Override
public void onAvailable(Network network) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
connectivityManager.setProcessDefaultNetwork(network);
connectivityManager.bindProcessToNetwork(network);
}
}
});
}
```
2. Also added below code to forget wifi connection before we make new connection. It takes some time for device to disconnect WiFI. So I added delay before connecting to new WIFI SSID.
```
this.wifiManager.disableNetwork(configuration.networkId);
this.wifiManager.removeNetwork(configuration.networkId);
this.wifiManager.saveConfiguration(); // Not needed in API level 26 and above
```
Workaround which I tried and helped me making connection work are below: In my case also I have to connect WiFi which doesn't have internet on it. Its a peer to peer connection.
1. I Made 2-3 attempts for connection
```
new CountDownTimer(16000, 2000) {
```
2. Also I have written below broadcast receiver to check the state of WiFI. And then made the connection.
```
private final BroadcastReceiver broadcastReceiver = new BroadcastReceiver()
{
@Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
Log.d("WifiReceiver", ">>>>SUPPLICANT_STATE_CHANGED_ACTION<<<<<<");
SupplicantState supl_state = ((SupplicantState) intent
.getParcelableExtra(WifiManager.EXTRA_NEW_STATE));
switch (supl_state) {
case ASSOCIATED:
Log.i("SupplicantState", "ASSOCIATED");
// authMsg = "ASSOCIATED";
break;
case ASSOCIATING:
// authMsg = "ASSOCIATING";
Log.i("SupplicantState", "ASSOCIATING");
break;
case AUTHENTICATING:
// authMsg = "AUTHENTICATING";
Log.i("SupplicantState", "Authenticating...");
break;
case COMPLETED:
authMsg = "CONNECTED";
Log.i("SupplicantState", "Connected");
final ConnectivityManager connection_manager =
(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkRequest.Builder request = new NetworkRequest.Builder();
request.addTransportType(NetworkCapabilities.TRANSPORT_WIFI);
connection_manager.registerNetworkCallback(request.build(), new ConnectivityManager.NetworkCallback() {
@Override
public void onAvailable(Network network) {
ConnectivityManager.setProcessDefaultNetwork(network);
}
});
break;
case DISCONNECTED:
```
Upvotes: 2 <issue_comment>username_4: Just wanted to add a bit to the discussion. I've been using bindProcessToNetwork for a while and it does fix the loss of WiFi when connected to one without a network as described by username_2. This is a heavy handed solution that makes it difficult to use Mobile network at the same time. However, the routing layer is rather broken on Android somewhere around 6 where they started forcing request to mobile even though the routing table indicates the wifi device.
Anyway, you can actually bind at a socket level which I describe below. This may help when the process has been bound to the WiFi network and you still want to use mobile. Instead of looking up WiFi (which is what I was experimenting with instead of binding the process), you look up the mobile 'Network' object and build a socket to it.
What we need is something that indicates to android not to drop the WiFi connection.
HttpUrlConnection doesn't allow you to get the socket so you can use okhttp to do it at the per-connection level. I'm using 2.7.5 of OkHttp but it is very similar for the 3+ version of OkHttp.
You get the current networks then process each to find WiFi network.
```
Network[] networks = connectivityManager.getAllNetworks();
```
Then you build the url like:
```
String url = "http://someurl";
HttpUrlConnection uconn = new OkUrlFactory( new OkHttpClient().setSocketFactory(network.getSocketFactory())).open(url)
```
This all works fine for a few connections and sometimes it works for the series of connections I used. Android is using the knowledge that activity is happening over the network but any pauses and it jumps back to using mobile. Android 9 wifi is just flawed and haven't figured out how to make it sticky using the socket solution. There may be one.
Upvotes: 1 |
2018/03/19 | 1,971 | 6,416 | <issue_start>username_0: I get this strange stacktrace when running `mvn clean verify -P P1`
```
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-failsafe-plugin:2.21.0:verify (default) on project prj-name: There are test failures.
[ERROR]
[ERROR] Please refer to C:\path\to\project\target\failsafe-reports for the individual test results.
[ERROR] Please refer to dump files (if any exist) [date]-jvmRun[N].dump, [date].dumpstream and [date]-jvmRun[N].dumpstream.
[ERROR] org.apache.maven.surefire.booter.SurefireBooterForkException: There was an error in the forked process
[ERROR] sun.reflect.annotation.TypeNotPresentExceptionProxy
[ERROR] at org.apache.maven.plugin.surefire.booterclient.ForkStarter.fork(ForkStarter.java:658)
[ERROR] at org.apache.maven.plugin.surefire.booterclient.ForkStarter.fork(ForkStarter.java:533)
[ERROR] at org.apache.maven.plugin.surefire.booterclient.ForkStarter.run(ForkStarter.java:278)
[ERROR] at org.apache.maven.plugin.surefire.booterclient.ForkStarter.run(ForkStarter.java:244)
[ERROR] at org.apache.maven.plugin.surefire.AbstractSurefireMojo.executeProvider(AbstractSurefireMojo.java:1149)
```
What does it mean?
Maven pom.xml:
```
P1
org.apache.maven.plugins
maven-failsafe-plugin
2.21.0
integration-tests
integration-test
verify
UTF-8
\*\*/integration/\*.java
\*\*/integration/\*/\*.java
-Xmx1024m -XX:MaxPermSize=256m
```
**UPDATE**
There's a surefire dumpstream file
```
ForkStarter IOException: For input string: "1;5".
org.apache.maven.plugin.surefire.booterclient.output.MultipleFailureException: For input string: "1;5"
at org.apache.maven.plugin.surefire.booterclient.output.ThreadedStreamConsumer$Pumper.(ThreadedStreamConsumer.java:58)
at org.apache.maven.plugin.surefire.booterclient.output.ThreadedStreamConsumer.(ThreadedStreamConsumer.java:110)
at org.apache.maven.plugin.surefire.booterclient.ForkStarter.fork(ForkStarter.java:596)
at org.apache.maven.plugin.surefire.booterclient.ForkStarter.fork(ForkStarter.java:533)
at org.apache.maven.plugin.surefire.booterclient.ForkStarter.run(ForkStarter.java:278)
at org.apache.maven.plugin.surefire.booterclient.ForkStarter.run(ForkStarter.java:244)
at org.apache.maven.plugin.surefire.AbstractSurefireMojo.executeProvider(AbstractSurefireMojo.java:1149)
at org.apache.maven.plugin.surefire.AbstractSurefireMojo.executeAfterPreconditionsChecked(AbstractSurefireMojo.java:978)
at org.apache.maven.plugin.surefire.AbstractSurefireMojo.execute(AbstractSurefireMojo.java:854)
at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:137)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:208)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:154)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:146)
at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:117)
at org.apache.maven.lifecycle.internal.builder.multithreaded.MultiThreadedBuilder$1.call(MultiThreadedBuilder.java:200)
at org.apache.maven.lifecycle.internal.builder.multithreaded.MultiThreadedBuilder$1.call(MultiThreadedBuilder.java:196)
at java.util.concurrent.FutureTask.run(FutureTask.java:262)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
at java.util.concurrent.FutureTask.run(FutureTask.java:262)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:745)
```
Because of garbage in string variables and occasional `IndexOutOfBoundsException` / `ConcurrentModificationException` in logs it seems like a concurrency issue.<issue_comment>username_1: This GitHub issue - [[#6254] Maven-failsafe-plugin fails to execute integration tests](https://github.com/spring-projects/spring-boot/issues/6254) - and the related discussion helped me to solve my problem.
It's a bug. It turns out that newer Failsafe plugin versions (2.19.0 and later) don't work well with Spring Boot 1.4 (or later). Workaround is to downgrade the maven-failsafe-plugin to 2.18.1. Here's the updated pom.xml:
```
org.apache.maven.plugins
maven-failsafe-plugin
integration-test
```
Upvotes: 5 [selected_answer]<issue_comment>username_2: I followed the solution proposed here:
<https://github.com/spring-projects/spring-boot/issues/6254#issuecomment-307151464>
Currently, I have failsafe plugin 2.22.0 and I'm able to use this version and not downgrade by explicitly configuring the `classesDirectory` property:
```
${project.build.outputDirectory}
```
Example:
```
org.apache.maven.plugins
maven-failsafe-plugin
2.22.0
...
${project.build.outputDirectory}
...
integration-test
verify
```
Another variant of the workaround is described later in the same Github issue thread: <https://github.com/spring-projects/spring-boot/issues/6254#issuecomment-343470070>
```
${project.build.directory}/${artifactId}.jar.original
```
Note (2020-02-27): `maven-failsafe-plugin` version 3.0.0-M4 still needs these workarounds :-(
Upvotes: 4 <issue_comment>username_3: My testng class was having LoginPageTest.java, I removed .java and worked perfectly fine. :)
```
```
Upvotes: 0 <issue_comment>username_4: I used to get the problem and mostly the problem is initializing instance variables. Check your instance variables that are working in local and if working check when they are running in CI/CD pipeline.
Upvotes: 0 <issue_comment>username_1: Another workaround is to configure a classifier for the repackaged jar. This allows Failsafe to use the original jar:
```xml
org.springframework.boot
spring-boot-maven-plugin
exec
```
>
> This problem is due to a combination of a change in the Failsafe plugin and a change in the layout of a repackaged jar file in Boot 1.4. As of Failsafe 2.19, `target/classes` is no longer on the classpath and the project's built jar is used instead. In the case of a Boot app, that's the repackaged jar. In 1.4, the application's classes were moved from the root of the jar to the `BOOT-INF/classes` directory. This prevents them from being loaded by Failsafe.
>
>
>
src: [GitHub Issues](https://github.com/spring-projects/spring-boot/issues/6254#issuecomment-229600830)
Upvotes: 0 |
2018/03/19 | 1,807 | 6,141 | <issue_start>username_0: I Using the Component's of `NG-ZORRO` . But When I Need to Use List of it Show me This `Error` :
```
Error: Template parse errors:
Can't bind to 'nzDataSource' since it isn't a known property of 'nz-list'.
1. If 'nz-list' is an Angular component and it has 'nzDataSource' input, then verify that it is part of this module.
2. If 'nz-list' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.
3. To allow any property add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component. ("][nzDataSource]="data"
[nzItemLayout]="'vertical'"
[nzRenderItem]="item"
"): ng:///AppModule/MainPageComponent.html@1:2
Can't bind to 'nzItemLayout' since it isn't a known property of 'nz-list'.
1. If 'nz-list' is an Angular component and it has 'nzItemLayout' input, then verify that it is part of this module.
2. If 'nz-list' is a Web Component then add 'CUSTOM\_ELEMENTS\_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.
3. To allow any property add 'NO\_ERRORS\_SCHEMA' to the '@NgModule.schemas' of this component. ("][nzItemLayout]="'vertical'"
[nzRenderItem]="item"
[nzPagination]="pagination">
"): ng:///AppModule/MainPageComponent.html@2:2
Can't bind to 'nzRenderItem' since it isn't a known property of 'nz-list'.
1. If 'nz-list' is an Angular component and it has 'nzRenderItem' input, then verify that it is part of this module.
2. If 'nz-list' is a Web Component then add 'CUSTOM\_ELEMENTS\_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.
3. To allow any property add 'NO\_ERRORS\_SCHEMA' to the '@NgModule.schemas' of this component. ("
[nzDataSource]="data"
[nzItemLayout]="'vertical'"
[ERROR ->][nzRenderItem]="item"
[nzPagination]="pagination">
"): ng:///AppModule/MainPageComponent.html@3:2
Can't bind to 'nzPagination' since it isn't a known property of 'nz-list'.
1. If 'nz-list' is an Angular component and it has 'nzPagination' input, then verify that it is part of this module.
2. If 'nz-list' is a Web Component then add 'CUSTOM\_ELEMENTS\_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.
3. To allow any property add 'NO\_ERRORS\_SCHEMA' to the '@NgModule.schemas' of this component. ("
[nzItemLayout]="'vertical'"
[nzRenderItem]="item"
[ERROR ->][nzPagination]="pagination">
][nzContent]="item.content" [nzActions]="[starAction,likeAction,msgAction]" [nzExtra]="extra">
<"): ng:///AppModule/MainPageComponent.html@6:18
Can't bind to 'nzActions' since it isn't a known property of 'nz-list-item'.
1. If 'nz-list-item' is an Angular component and it has 'nzActions' input, then verify that it is part of this module.
2. If 'nz-list-item' is a Web Component then add 'CUSTOM\_ELEMENTS\_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.
3. To allow any property add 'NO\_ERRORS\_SCHEMA' to the '@NgModule.schemas' of this component. ("gination]="pagination">
][nzActions]="[starAction,likeAction,msgAction]" [nzExtra]="extra">
*][nzExtra]="extra">
2
][nzAvatar]="item.avatar"
[nzTitle]="nzTitle"
[nzDescription]="item.description">
"): ng:///AppModule/MainPageComponent.html@11:8
Can't bind to 'nzTitle' since it isn't a known property of 'nz-list-item-meta'.
1. If 'nz-list-item-meta' is an Angular component and it has 'nzTitle' input, then verify that it is part of this module.
2. If 'nz-list-item-meta' is a Web Component then add 'CUSTOM\_ELEMENTS\_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.
3. To allow any property add 'NO\_ERRORS\_SCHEMA' to the '@NgModule.schemas' of this component. ("
][nzTitle]="nzTitle"
[nzDescription]="item.description">
][nzDescription]="item.description">
[{{item.titl"): ng:///AppModule/MainPageComponent.html@13:8
'nz-list-item-meta' is not a known element:
1. If 'nz-list-item-meta' is an Angular component, then verify that it is part of this module.
2. If 'nz-list-item-meta' is a Web Component then add 'CUSTOM\_ELEMENTS\_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message. ("#msgAction> 2]({{item.href}})
[ERROR ->]
[ERROR ->]]*
```
but i Dont Know Whats the Problem .
this `Html` Code :
```
156
156
2
[{{item.title}}]({{item.href}})

```
`.ts` Code:
```
export class MainPageComponent implements OnInit {
constructor() { }
data = new Array(5).fill({}).map((i, index) => {
return {
href: 'http://ant.design',
title: `ant design part ${index}`,
avatar: 'https://zos.alipayobjects.com/rmsportal/ODTLcjxAfvqbxHnVXCYX.png',
description: 'Ant Design, a design language for background applications, is refined by Ant UED Team.',
content: 'We supply a series of design principles, practical patterns and high quality design resources (Sketch and Axure), to help people create their product prototypes beautifully and efficiently.'
};
});
ngOnInit() {
return this.data;
}
}
```
How can I Solve This Problem ?<issue_comment>username_1: you should import ng-zorro-antd in current module, just like so:
```
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { LoginComponent } from './login/login.component';
import { NgZorroAntdModule } from 'ng-zorro-antd';
@NgModule({
imports: [
CommonModule,
NgZorroAntdModule.forRoot()
],
declarations: [LoginComponent]
})
export class ComponentsModule { }
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: You have to add the ScrollingModule from the Angular CDK to your AppModule or SharedModule:
```
import { ScrollingModule } from '@angular/cdk/scrolling';
@NgModule({
imports: [
NgZorroAntdModule,
ScrollingModule,
...
],
exports: [
NgZorroAntdModule,
ScrollingModule,
...
],
```
Upvotes: 0 <issue_comment>username_3: add FormsModule in your App.Module
```
import { FormsModule } from '@angular/forms';
imports: [
NgZorroAntdModule,
FormsModule,
...
],
```
Upvotes: 0 |
2018/03/19 | 786 | 1,987 | <issue_start>username_0: I use Python 3.6.4. I have multiple lists inside a list, but with the same keys (first element of inner list) for certain elements:
```
[[1, 100],
[1, 250],
[2, 340],
[2, 5200]]
```
Element `0` is the same for the first 2 inner lists. How can I combine those to one list by the same keys to get something like this:
```
[[1, 100, 250],
[2, 340, 5200]]
```
In my case, max count of the same keys is always two.<issue_comment>username_1: One solution is to use `collections.defaultdict` to iterate a list of lists.
Then use a list comprehension to transform your dictionary.
```
from collections import defaultdict
lst = [[1, 100],
[1, 250],
[2, 340],
[2, 5200]]
d = defaultdict(list)
for i, j in lst:
d[i].append(j)
res = [[k]+v for k, v in d.items()]
```
Result:
```
[[1, 100, 250],
[2, 340, 5200]]
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: ```
default_dict = {}
for val_list in data:
key, value = val_list
default_dict.setdefault(key, []).append(value)
print(*[[key, *value] for key, value in default_dict.items()], sep="\n")
```
Upvotes: 0 <issue_comment>username_3: Or something like this:
```
lst=[[1, 100], [1, 250], [2, 340], [2, 5200]]
d={}
for l in lst:
if l[0] in d:
d[l[0]]=[d[l[0]], l[1]]
else:
d[l[0]]=l[1]
out=[]
for k,v in d.items():
v.insert(0, k)
out.append(v)
```
Result:
```
print(out)
[[1, 100, 250], [2, 340, 5200]]
```
Upvotes: 0 <issue_comment>username_4: You can implement your own logic with one loop :
```
data=[[1, 100],
[1, 250],
[2, 340],
[2, 5200]]
combine={}
for i in data:
if i[0] not in combine:
combine[i[0]]=[i[1]]
else:
combine[i[0]].append(i[1])
print(list(map(lambda x:[x,*combine[x]],combine.keys())))
```
output:
```
[[1, 100, 250], [2, 340, 5200]]
```
Upvotes: 0 |
2018/03/19 | 480 | 1,863 | <issue_start>username_0: Example class I'm using:
```
class Vector
{
double val[3];
public:
double & operator [] (const unsigned int & index) {return this->val[index];};
}
```
Then I call it like:
```
Vector Example;
Example[0]=5;
```
Is using operator overloading like this correct or it is against encapsulation and I should use something different? I'm using reference to private value here and I'm not sure about this implementation.<issue_comment>username_1: This is a leak in your abstraction. It exposes the fact you have actual `double`s that can be read from or written to.
If you later wanted to change those `double`s into a remote immediate network connection data or stored in a database, you would be forced to add breaking changes to your interface.
That being said:
It is worth it. You probably will never modify this type to do something that insane, and there are significant compile, design and runtime overheads to unlimited abstraction.
Abstraction and encapsulation serve a purpose and have a cost.
`std::vector`'s `operator[]` is an example of what you can do when reference return types are not ok. There it is used to return sub-byte elements. Note that it is widely considered a design error.
Upvotes: 1 [selected_answer]<issue_comment>username_2: Good so far... You also need one that can read from const objects. Also, there's no reason to pass an array index by const&. Also also, `this->` is implicit. Look at the member function signatures for [std::vector<>](http://en.cppreference.com/w/cpp/container/vector). In particular [operator[]](http://en.cppreference.com/w/cpp/container/vector/operator_at). Push request...
```
class Vector
{
double val[3];
public:
double& operator [] (size_t index) {return val[index];};
const double& operator [] (size_t index) const {return val[index];};
};
```
Upvotes: 1 |
2018/03/19 | 1,325 | 5,022 | <issue_start>username_0: For my application component creating the unit test case, in component used the service to connect the rest api to get the data.
In the component subscribing the observable with success and error case, using mockservice I could achieve the success, error scenario can be covered using spon with return value. But I use both return value test case fails, rather than using mockserive tried with return value for success case but success case also fails.
>
> Component.ts
>
>
>
```
export class KpiComponent implements OnInit {
public info: any[] = [];
servicerError = false;
constructor(private kpisService: KpisService, private activatedRoute: ActivatedRoute) { }
ngOnInit() {
this.activatedRoute.params.subscribe((params: Params) => {
this.kpisService.getKpiDetails().subscribe(
data => {
this.info = data;
console.log('25 - Working');
},
(error) => { console.log('27 - Error'); this.servicerError = true }
);
});
}
}
```
>
> component.spec.ts
>
>
>
```
const info = [{ name: 'kpi' }];
class MockKpisService {
public getKpiDetails(): Observable {
return Observable.of(info);
}
}
describe('KpiComponent', () => {
let component: KpiComponent;
let fixture: ComponentFixture;
let kpisService: KpisService;
let kpisService1: KpisService;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [BrowserAnimationsModule, NoopAnimationsModule, RouterModule, RouterTestingModule, BrowserModule, MatProgressBarModule, TableModule, MultiSelectModule, FormsModule, CalendarModule, DropdownModule, SpinnerModule, TooltipModule, HttpClientModule],
declarations: [KpiComponent, DataTableComponent],
providers: [{ provide: KpisService, useClass: MockKpisService }]
}).compileComponents();
fixture = TestBed.createComponent(KpiComponent);
component = fixture.componentInstance;
kpisService = TestBed.get(KpisService);
kpisService1 = fixture.debugElement.injector.get(KpisService);
fixture.detectChanges();
}));
it('should create', () => {
expect(component).toBeTruthy();
});
it('should List the Attachment', () => {
//spyOn(kpisService, 'getKpiDetails').and.callThrough();
expect(component.info).toBe(info);
expect(component.servicerError).toBe(false);
});
it('should Error log displayed', () => {
spyOn(kpisService, 'getKpiDetails').and.returnValue(Observable.throw({ status: 404 }));
fixture.detectChanges();
expect(component.servicerError).toBe(true);
});
});
```
For the above code error block test failing.
For the blow code success test case failing, also service call happening through the component ngOnInit.
```
const info = [{ name: 'kpi' }];
describe('KpiComponent', () => {
let component: KpiComponent;
let fixture: ComponentFixture;
let kpisService: KpisService;
let kpisService1: KpisService;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [BrowserAnimationsModule, NoopAnimationsModule, RouterModule, RouterTestingModule, BrowserModule, MatProgressBarModule, TableModule, MultiSelectModule, FormsModule, CalendarModule, DropdownModule, SpinnerModule, TooltipModule, HttpClientModule],
declarations: [KpiComponent, DataTableComponent],
providers: [KpisService]
}).compileComponents();
fixture = TestBed.createComponent(KpiComponent);
component = fixture.componentInstance;
kpisService = TestBed.get(KpisService);
kpisService1 = fixture.debugElement.injector.get(KpisService);
fixture.detectChanges();
}));
it('should create', () => {
expect(component).toBeTruthy();
});
it('should List the Attachment', () => {
spyOn(kpisService, 'getKpiDetails').and.returnValue(info);
expect(component.info).toBe(info);
expect(component.servicerError).toBe(false);
});
it('should Error log displayed', () => {
spyOn(kpisService, 'getKpiDetails').and.returnValue(Observable.throw({ status: 404 }));
fixture.detectChanges();
expect(component.servicerError).toBe(true);
});
});
```<issue_comment>username_1: Try this for your error :
```js
it('should Error log displayed', () => {
spyOn(kpisService, 'getKpiDetails').and.returnValue(Observable.throw({ status: 404 }));
kpisService.getKpiDetails().subscribe(response => null, error => {
expect(component.servicerError).toBe(true);
});
fixture.detectChanges();
component.ngOnInit();
});
```
If it doesn't work, rty with a timeout on the `ngOnInit` call.
Upvotes: 0 <issue_comment>username_2: For the first case, you can try with this.
```
it('should Error log displayed', () => {
spyOn(kpisService, 'getKpiDetails').and.returnValue(Observable.throw({ status: 404 }));
component.ngOnInit();
fixture.detectChanges();
expect(component.servicerError).toBe(true);
//verify the spy too
expect(kpisService.getKpiDetails).toHaveBeenCalled();
});
```
You should not be calling your real service in your unit tests. So, second method is not the way to go.
Upvotes: 2 [selected_answer] |
2018/03/19 | 578 | 1,900 | <issue_start>username_0: I am working in Ubuntu and I am trying to delete all blank spaces in my file to get only one long string.
My file has `\t` and `\n` in one text that it is supposed to be a long string made of letters only (it is a genomic sequence). It looks like:
```
AAAAAAAAAAAAAGTCGCTCGGAACCTGCTTCAAG
AGTCTAGCTCGATAAAGCTTAGATCTGATATAGATGAGATAGAGTGA
GGATCTTGATCTTTAGGAG
```
Thus, I want to eliminate ALL the `\n` and `\t` and write a unique string with all pieces written one after the other, with no spaces at all and without deleting any letter only the spaces, to finally get something like this:
```
AAAAAAAAAAAAAGTCGCTCGGAACCTGCTTCAAGAGTCTAGCTCGATAAAGCTTAGATCTGATATAGATGAGATAGAGTGAGGATCTTGATCTTTAGGAG
```
I tried with:
```
tr -d "\t\r\n\v\f" < file_spaces.txt > fileNOspaces.txt
```
but It did not work and I see exactly the same `\n` and `\t`. What am I missing?<issue_comment>username_1: Try this for your error :
```js
it('should Error log displayed', () => {
spyOn(kpisService, 'getKpiDetails').and.returnValue(Observable.throw({ status: 404 }));
kpisService.getKpiDetails().subscribe(response => null, error => {
expect(component.servicerError).toBe(true);
});
fixture.detectChanges();
component.ngOnInit();
});
```
If it doesn't work, rty with a timeout on the `ngOnInit` call.
Upvotes: 0 <issue_comment>username_2: For the first case, you can try with this.
```
it('should Error log displayed', () => {
spyOn(kpisService, 'getKpiDetails').and.returnValue(Observable.throw({ status: 404 }));
component.ngOnInit();
fixture.detectChanges();
expect(component.servicerError).toBe(true);
//verify the spy too
expect(kpisService.getKpiDetails).toHaveBeenCalled();
});
```
You should not be calling your real service in your unit tests. So, second method is not the way to go.
Upvotes: 2 [selected_answer] |
2018/03/19 | 954 | 3,776 | <issue_start>username_0: I have a MVC project. I want to get a simple json response {result: "ok"}. Below is my code
```
using System;
using System.Web.Mvc;
using Microsoft.Xrm.Sdk;
using CRM_WebApp.Models;
using System.Web.Http;
using System.Web.Http.Cors;
using Microsoft.Xrm.Sdk.Query;
using CRM_WebApp.Services;
namespace CRM_WebApp.Controllers
{
[EnableCors(origins: "*", headers: "*", methods: "*")]
public class CallBackFormController : ApiController
{
[System.Web.Mvc.HttpPost]
public JsonResult Post([FromBody] CallBackFormModel CallBackFormModel)
{
ConnectiontoCrm connectiontoCrm = new ConnectiontoCrm();
//connectiontoCrm.GetConnectiontoCrm();
connectiontoCrm.GetConnectiontoCrmCopy();
Entity lead = new Entity("lead");
lead["firstname"] = CallBackFormModel.FirstName;
lead["mobilephone"] = CallBackFormModel.Telephone;
lead["telephone3"] = CallBackFormModel.Telephone;
Guid tisa_callbackformid = connectiontoCrm.organizationservice.Create(callbackform);
return new JsonResult { Data = new { result = "ok" } };
}
}
}
```
My code gives me the following response:
```
{
"ContentEncoding": null,
"ContentType": null,
"Data": {
"result": "ok"
},
"JsonRequestBehavior": 1,
"MaxJsonLength": null,
"RecursionLimit": null
}
```
How can i change my code to get response: {result: "ok"}<issue_comment>username_1: Try this:
```
return Json(new { result = "ok" }, JsonRequestBehavior.AllowGet);
```
Upvotes: 0 <issue_comment>username_2: after some investigation in your code, I really noticed that there are some fundamental errors.
1. When you are Inheriting from `ApiController` so here you are creating WebApiController, not MVC controller (which could be created by inheriting from `Controller` class)
2. You have to be careful about the namespaces you use because there are some classes and attribute which has the same name but in different namespaces, for example, the `HttpPost` attribute exists in the `System.Web.Http` and the `System.Web.Mvc` and according to your code you have to use the one in the former namespace because you are inheriting from the `ApiController`.
Keep in mind that the `System.Web.Mvc` is for ASP.NET MVC and the `System.Web.Http` is for the Web API.
3. You are not using the correct return type for the method (which represent Web API method)
So after fixing all the previous problems, the working code should be like this
```
[System.Web.Http.HttpPost]
public System.Web.Http.IHttpActionResult Post([System.Web.Http.FromBody] CallBackFormModel CallBackFormModel)
{
// your previous code goes here
return Json(new { result = "ok" }, JsonRequestBehavior.AllowGet);
}
```
I recommend you to read about ASP.NET MVC and the Web API and the differences between them to avoid those kinds of problems in the future.
Upvotes: 3 [selected_answer]<issue_comment>username_3: To answer you question I had the same issues because when I return a response I like to return multiple objects/types.
For instance I always return a message result containing some success and error messages. This object is pretty much reused across all my api responses. I then like to return a second object containing any data such as a list of customers or whatever.
This is how I got it working for WebAPI...
```
public IHttpActionResult DeleteEmailTemplate(int id)
{
FormResponse formResponse = new FormResponse("SUCESS MESSAGE HERE");
List strings = new List();
strings.Add("this is a test");
strings.Add("this is another test");
return Json(new { MessageResult = formResponse, TestObject = strings });
}
```
Upvotes: 0 |
2018/03/19 | 515 | 1,979 | <issue_start>username_0: Am having troubles deleting my entities, i have the following partial codes
```
@ManyToOne(type => Comment, comment => comment.replies, {
onDelete: "CASCADE"
})
parent: Comment;
```
and
```
@OneToMany(type => Comment, comment => comment.parent)
replies: Comment[];
```
I have tried `manager.remove(comment)` and
```
await manager
.createQueryBuilder()
.delete()
.from(Comment)
.where("id = :id", { id: comment.id })
.execute();
```
Both don't work, is there something am doing wrong, how do I go about this, here is my select query
```
let comment = await manager
.createQueryBuilder(Comment, "comment")
.leftJoinAndSelect("comment.user", "user")
.where("comment.id = :id", { id: request.body.comment })
.getOne();
```
The error am getting is
```
UnhandledPromiseRejectionWarning: QueryFailedError: ER_ROW_IS_REFERENCED_2: Cannot delete or update a parent row: a foreign key constraint fails
```
Thanks in advance.<issue_comment>username_1: Apparently i had to delete all tables and do a fresh migration for the `onDelete: "CASCADE"` to take effect but worked
Upvotes: 3 <issue_comment>username_2: next time, change property "onDelete" in your models, and create a migration to change it on your database.
Upvotes: 2 <issue_comment>username_3: It could be that you have the following decorator in an entity.
```js
@DeleteDateColumn()
deletedAt: Date;
```
If you have this decorator and then have is turned on in a service. You'll see that it respects the deletedAt time and doesn't actually remove it from the db, but instead the services will automatically not return it if respecting the flag.
```js
{ useSoftDelete: true })
```
Next I would check what is actually set in the database. If you are using synchronize true then it might reflect correctly, but you should use a migration to create everything for production purposes or risk data loss.
Cheers and good luck mate!
Upvotes: 1 |
2018/03/19 | 578 | 2,420 | <issue_start>username_0: I'm really new to API dev and don't have a broad background knowledge. So please bear that in mind if my question looks too simple (stupid). I was playing around with serverless and the AWS lambda to get a better understanding of API's. It was pretty easy to define a simple function and define a http endpoint for a get request. However, with a post event I have my troubles.
As far as I understood and according to the [documentation](https://docs.aws.amazon.com/lambda/latest/dg/python-programming-model-handler-types.html) a typical lambda function is always of the template:
```
def my_function(event, context):
pass
```
If I understand it correctly, the `event` parameter contains the actual input parameters sent to my function. If my API would take a string as input and just capitalize it, the input string would be part of the event object. Is this correct?
Are there any rules how the event object needs to look like, how I can pass parameters to it etc? I wasn't really able to find that information. If someone could provide this information or a link where I can find the resources would be much appreciated.<issue_comment>username_1: Try configuring test events in Lambda console.
It will give a variety of sample event structures which will help you
Upvotes: 2 <issue_comment>username_2: You are correct that `event` is the variable receiving the input (aka *payload*). In most cases this should be a json-friendly `dict`, but it can also be `list`, `str`, `int`, `float`, or `NoneType`.
When you invoke your Lambda, for example from another Python application [using boto3](http://boto3.readthedocs.io/en/latest/reference/services/lambda.html#Lambda.Client.invoke), you simply pass this payload.
If you need to provide an HTTP interface for your Lambda, the best option is probably to use API Gateway with [Lambda Proxy Integration](https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-create-api-as-simple-proxy-for-lambda.html#api-gateway-proxy-integration-lambda-function-python). In this case you can POST json and the API Gateway will automatically parse it to Python `dict` and provide to you in the event. Please note that in this case your return from the Lambda should follow some [basic requirements](https://docs.aws.amazon.com/apigateway/latest/developerguide/handle-errors-in-lambda-integration.html).
Upvotes: 3 [selected_answer] |
2018/03/19 | 406 | 1,363 | <issue_start>username_0: I am appending the following using jQuery:
```
var dateWrapper = ''+kendo.format('{0:dd MMMM yyyy}',new Date(date))+'
'
$('.wrapper').append(dateWrapper)
```
I want the triangle to appear inline or inline-block with the date. Once appended the DIV is placed after the P, and not inside. Cannot fathom why this would happen.<issue_comment>username_1: You can not put div inside p tag. It will automatically put it outside the p tag. You should use..
```
var dateWrapper = ''+kendo.format('{0:dd MMMM yyyy}',new Date(date))+'
';
$('.wrapper').append(dateWrapper);
```
In css
------
```
.triangle{
display:inline;
}
```
Upvotes: 2 <issue_comment>username_2: According to the HTML5 documentation ( and as far as i know it's the same for older versions ) , `p` accepts as children only `pharsing content`
[p element](https://www.w3.org/TR/html/grouping-content.html#the-p-element)
`Pharsing content` means plain text or `pharsing elements` which include ,, etc. but not
[pharsing content](https://www.w3.org/TR/html/dom.html#phrasing-content-2)
So a structure like is not a valid HTML5 structure, so it is automatically converted into .
In conclusion you CAN NOT nest `div` inside `p` and that's why you don't get the desired result. I suggest, in your case, change the triangle from div to span
Upvotes: 3 [selected_answer] |
2018/03/19 | 331 | 1,009 | <issue_start>username_0: Sounds trivial but how can I actually check this? I have the following breakpoints in SASS:
```
$width_breakpoints: (
small: 39.9375em,
medium: 40em,
large: 76em
);
```
Now I want to check the following (Pseudo-Code):
```
if($(window).width() < 39.9375em) {
// add current-mode-mobile class to a certain element
}
```
How can I actually check if the width is smaller than X em or X rem or X percent?<issue_comment>username_1: Here's a solution that does not even needs jQuery.
```
var widthInEm = window.innerWidth /
parseFloat(getComputedStyle(document.querySelector('body'))['font-size'])
if(widthInEm < 39.9375) {
// add current-mode-mobile class to a certain element
}
```
Upvotes: 1 <issue_comment>username_2: For IE10+:
```
if (window.matchMedia("(min-width: 39.9375em)").matches) {
/* the viewport is at least 39.9375 em wide */
} else {
/* the viewport is less than 39.9375 em wide */
}
```
Upvotes: 3 [selected_answer] |
2018/03/19 | 272 | 1,054 | <issue_start>username_0: I want do the following
* Create a VM
* Install Mongo
* Store Mongo DB data in Data disk
* Delete the VM which excludes the Data disk
* Then create a VM and use the above existing Data disk
My goal is goal create and delete the Azure VM, but re-use the single data disk.
How can I achieve it using ARM template?<issue_comment>username_1: hi i think you can buy a extra disk and link it to the vm it and while removing the vm detatch it and you can attach to which ever vm you want it on later please let me know if that is what you wanted.
Upvotes: 0 <issue_comment>username_2: If my understanding is right, on your scenario, you should use Azure Custom Script Extension to do this(Install Mongodb and change Mongodb data path).
You could check this [question:How to change the location that MongoDB uses to store its data?](https://askubuntu.com/questions/257714/how-to-change-the-location-that-mongodb-uses-to-store-its-data).
You need write a script and test it on your VM and then use template to execute it.
Upvotes: 1 |
2018/03/19 | 1,811 | 6,351 | <issue_start>username_0: I want to a script run when I press a button through PyQT.
This is an example of my of buttons I created
```
import sys
from PyQt5.QtWidgets import QMainWindow, QPushButton, QApplication
class AutoTestWindow(QMainWindow):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
btn1 = QPushButton("Test № 1 ", self)
btn1.move(30, 50)
btn2 = QPushButton("Test № 2", self)
btn2.move(150, 50)
btn1.clicked.connect(self.buttonClicked)
btn2.clicked.connect(self.buttonClicked)
self.statusBar()
self.setGeometry(300, 300, 290, 150)
self.setWindowTitle('Запуск тестов')
self.show()
def buttonClicked(self):
sender = self.sender()
self.statusBar().showMessage(sender.text() + ' test started')
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = AutoTestWindow()
sys.exit(app.exec_())
```
[](https://i.stack.imgur.com/hOkt7.png)
And this is a script I wanna run then the button is pressed. It's a auto test that opens a browser and does something.
```
def init_driver():
driver = webdriver.Chrome("/Users/alexeynikitin/Desktop/chromedriver")
driver.wait = WebDriverWait(driver, 5)
return driver
def findelem(driver, query):
driver.get("https://www.yandex.ru/")
try:
box = driver.wait.until(ec.presence_of_element_located(
(By.ID, "text")))
button = driver.wait.until(ec.visibility_of_element_located(
(By.CLASS_NAME, "search2__button")))
box.send_keys(query)
suggestion_box = driver.wait.until(ec.presence_of_element_located((By.CSS_SELECTOR, "body > div.i-bem.popup.suggest2.suggest2_theme_flat.suggest2_size_m.suggest2_adaptive_yes.suggest2_type_advanced.suggest2_ahead_yes.popup_adaptive_yes.popup_animate_no.popup_autoclosable_yes.popup_theme_ffffff.suggest2-detect_js_inited.suggest2_js_inited.popup_js_inited.popup_to_bottom.popup_visibility_visible")))
try:
button.click()
except ElementNotVisibleException:
button = driver.wait.until(ec.visibility_of_element_located(
(By.CLASS_NAME, "search2__button")))
except TimeoutException:
print("ничего не нашел на https://www.yandex.ru/")
if __name__ == "__main__":
driver = init_driver()
findelem(driver, "Тензор")
time.sleep(10)
driver.quit()
```
That should I do to make it happen? I tried to call a function when a button is pressed, but it didn't work<issue_comment>username_1: If i correctly understood your question, it should be enough to connect the clickbutton event to the correct function when you initialize the class (or in your `initUI` method):
```
def __init__(self):
super().__init__()
self.initUI()
btn1.clicked.connect(init_driver)
btn2.clicked.connect(lambda checked :findelem(value1, value2))
```
I corrected the 2nd bind as @eyllanesc suggested
Upvotes: 0 <issue_comment>username_2: An easy way to call a python script is to use `os`.
Assuming your script is located in same folder than your application, you need to add `import os`, then call `os.system('yourscriptname.py')` in your function `buttonClicked`.
Upvotes: 0 <issue_comment>username_3: Try it:
```
from PyQt5.QtWidgets import QMainWindow, QPushButton, QApplication, QStatusBar
class AutoTestWindow(QMainWindow):
def __init__(self):
super().__init__()
self.driver = None # +++
self.query = "Тензор" # +++
self.initUI()
def initUI(self):
btn1 = QPushButton("Test № 1 ", self)
btn1.move(30, 50)
btn2 = QPushButton("Test № 2", self)
btn2.move(150, 50)
#btn1.clicked.connect(self.buttonClicked) # ---
#btn2.clicked.connect(self.buttonClicked) # ---
btn1.clicked.connect(self.init_driver) # +++
btn2.clicked.connect(lambda checked : self.findelem(self.driver, self.query)) # +++
self.statusBar().showMessage('Запуск тестов', 5000)
self.setGeometry(300, 300, 290, 150)
self.setWindowTitle('Запуск тестов')
self.show()
# ---
#def buttonClicked(self):
# sender = self.sender()
# self.statusBar().showMessage(sender.text() + ' test started')
# +++
def init_driver(self):
self.statusBar().showMessage('Test № 1 test started')
#driver = webdriver.Chrome("/Users/alexeynikitin/Desktop/chromedriver")
self.driver = webdriver.Chrome()
self.driver.wait = WebDriverWait(self.driver, 10)
#return self.driver
# +++
def findelem(self, driver, query):
print("\ndriver=`{}`, \nquery=`{}`\n".format(driver, query))
self.statusBar().showMessage('Test № 2 test started')
if driver is not None:
driver.get("https://www.yandex.ru/")
try:
box = driver.wait.until(ec.presence_of_element_located(
(By.ID, "text")))
button = driver.wait.until(ec.visibility_of_element_located(
(By.CLASS_NAME, "search2__button")))
box.send_keys(query)
suggestion_box = driver.wait.until(ec.presence_of_element_located((By.CSS_SELECTOR, "body > div.i-bem.popup.suggest2.suggest2_theme_flat.suggest2_size_m.suggest2_adaptive_yes.suggest2_type_advanced.suggest2_ahead_yes.popup_adaptive_yes.popup_animate_no.popup_autoclosable_yes.popup_theme_ffffff.suggest2-detect_js_inited.suggest2_js_inited.popup_js_inited.popup_to_bottom.popup_visibility_visible")))
try:
button.click()
except ElementNotVisibleException:
button = driver.wait.until(ec.visibility_of_element_located(
(By.CLASS_NAME, "search2__button")))
except TimeoutException:
print("ничего не нашел на https://www.yandex.ru/")
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = AutoTestWindow()
sys.exit(app.exec_())
```
Upvotes: 2 [selected_answer] |
2018/03/19 | 1,105 | 4,167 | <issue_start>username_0: We're caching 404 for images as sometimes our app would be released ahead of the actual images and would like to be able to clear them based on status code rather than ALL the images or specific images one by one.
However I am new to Varnish an unsure whether that is doable as I couldn't find any specific documentation on clearing based on status code.<issue_comment>username_1: If i correctly understood your question, it should be enough to connect the clickbutton event to the correct function when you initialize the class (or in your `initUI` method):
```
def __init__(self):
super().__init__()
self.initUI()
btn1.clicked.connect(init_driver)
btn2.clicked.connect(lambda checked :findelem(value1, value2))
```
I corrected the 2nd bind as @eyllanesc suggested
Upvotes: 0 <issue_comment>username_2: An easy way to call a python script is to use `os`.
Assuming your script is located in same folder than your application, you need to add `import os`, then call `os.system('yourscriptname.py')` in your function `buttonClicked`.
Upvotes: 0 <issue_comment>username_3: Try it:
```
from PyQt5.QtWidgets import QMainWindow, QPushButton, QApplication, QStatusBar
class AutoTestWindow(QMainWindow):
def __init__(self):
super().__init__()
self.driver = None # +++
self.query = "Тензор" # +++
self.initUI()
def initUI(self):
btn1 = QPushButton("Test № 1 ", self)
btn1.move(30, 50)
btn2 = QPushButton("Test № 2", self)
btn2.move(150, 50)
#btn1.clicked.connect(self.buttonClicked) # ---
#btn2.clicked.connect(self.buttonClicked) # ---
btn1.clicked.connect(self.init_driver) # +++
btn2.clicked.connect(lambda checked : self.findelem(self.driver, self.query)) # +++
self.statusBar().showMessage('Запуск тестов', 5000)
self.setGeometry(300, 300, 290, 150)
self.setWindowTitle('Запуск тестов')
self.show()
# ---
#def buttonClicked(self):
# sender = self.sender()
# self.statusBar().showMessage(sender.text() + ' test started')
# +++
def init_driver(self):
self.statusBar().showMessage('Test № 1 test started')
#driver = webdriver.Chrome("/Users/alexeynikitin/Desktop/chromedriver")
self.driver = webdriver.Chrome()
self.driver.wait = WebDriverWait(self.driver, 10)
#return self.driver
# +++
def findelem(self, driver, query):
print("\ndriver=`{}`, \nquery=`{}`\n".format(driver, query))
self.statusBar().showMessage('Test № 2 test started')
if driver is not None:
driver.get("https://www.yandex.ru/")
try:
box = driver.wait.until(ec.presence_of_element_located(
(By.ID, "text")))
button = driver.wait.until(ec.visibility_of_element_located(
(By.CLASS_NAME, "search2__button")))
box.send_keys(query)
suggestion_box = driver.wait.until(ec.presence_of_element_located((By.CSS_SELECTOR, "body > div.i-bem.popup.suggest2.suggest2_theme_flat.suggest2_size_m.suggest2_adaptive_yes.suggest2_type_advanced.suggest2_ahead_yes.popup_adaptive_yes.popup_animate_no.popup_autoclosable_yes.popup_theme_ffffff.suggest2-detect_js_inited.suggest2_js_inited.popup_js_inited.popup_to_bottom.popup_visibility_visible")))
try:
button.click()
except ElementNotVisibleException:
button = driver.wait.until(ec.visibility_of_element_located(
(By.CLASS_NAME, "search2__button")))
except TimeoutException:
print("ничего не нашел на https://www.yandex.ru/")
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = AutoTestWindow()
sys.exit(app.exec_())
```
Upvotes: 2 [selected_answer] |
2018/03/19 | 652 | 2,285 | <issue_start>username_0: I'm Trying to call Partial View Into view i want to call parameterized method which is returing the partial view so how to call it.
My code is below.
**View**
```
@{Html.RenderPartial("~/Views/Appoinment/GetALLAppoinmentMedicine.cshtml",
new List { new HMS.Models.AppointmentViewModel() },
new ViewDataDictionary { { "aid", Model.AppoinmentIDP} });}
```
**Controller**
```
public ActionResult GetALLAppoinmentMedicine(int aid)
{
var idParam = new SqlParameter
{
ParameterName = "APPIDP",
Value = aid
};
var SpResult = DB.Database.SqlQuery("exec uspAppoinmentMedicine\_GetAll @APPIDP", idParam).ToList();
IEnumerable Result = SpResult.Select(s => new AppointmentViewModel
{
MadicineName = s.MadicineName,
PotencyName = s.PotencyName,
SizeofPills = s.SizeofPills,
Dose = s.Dose,
DoseType = s.DoseType,
Repitation = s.Repitation,
Quantity = s.Quantity,
Duration = s.Duration
});
return View(Result);
}
```<issue_comment>username_1: Try to use @{ Html.RenderAction("ChildAction","Home", new {param="abc"}):
It invokes the specified child action method and renders the result inline in the parent view.
Hope this will work.
Upvotes: 2 [selected_answer]<issue_comment>username_2: The return type of Html.RenderAction is void that means it directly render the responses in View where return type of Html.Action is MvcHtmlString you can catch its render view in the controller and modified it also by using following method
```
@{Html.RenderAction("GetALLAppoinmentMedicine", "ControllerName",new {uid= 1})}
```
If you want to use Ajax.ActionLink, replace your Html.ActionLink with:
```
@Ajax.ActionLink(
"Partial",
"GetALLAppoinmentMedicine",
"ControllerName",
new AjaxOptions { aid = 1 }
)
```
and of course you need to include a holder in your page where the partial will be displayed:
```
```
Also don't forget to include:
```
```
in your main view in order to enable Ajax.\* helpers. And make sure that unobtrusive javascript is enabled in your web.config (it should be by default):
Upvotes: 0 <issue_comment>username_3: You can pass parameter or model as per your need..
dont forget to put the reference to the model in partial view
[email protected]("\_SomePartial", Model)
Upvotes: 0 |
2018/03/19 | 346 | 1,550 | <issue_start>username_0: I've just upgraded some projects from Java 6 to Java 8 and one class was implementing [Connection](https://docs.oracle.com/javase/8/docs/api/java/sql/Connection.html) interface. Now `Connection` interface seems to have more methods but I don't want to implement all missing methods, for example: `Connection.getSchema()`. `Connection.getConnectionTimeOut()` and so on.
How I should deal with this issue due to the fact I don't want to make my class abstract or I should implement all the missing methods?<issue_comment>username_1: If the Connection interface does not implement Defaultmethods for the given new Methodes you will have to implement them. If they are not used in your Applicationcontext you might be able to just implement them empty. While that will be a quick fix for your problem i would not recommend that because maybe late some other class will have to use these Functions.
Upvotes: 2 <issue_comment>username_2: You don't have any choice but to implement them.
However, if your custom implementation of Connection is not designed to be general purpose, then you *could* get away with dummy implementations like this:
```
public String getSchema() {
throw new UnsupportedOperationException("Connection::getSchema");
}
```
And if you discover that you do need some of these methods, you can go back and implement them properly.
---
Making the class abstract won't help. That just puts the problem off to a subclass ... where you *will* need to implement the methods.
Upvotes: 2 [selected_answer] |
2018/03/19 | 979 | 2,909 | <issue_start>username_0: I have a table with `id`, `name` and `score` and I am trying to extract the top scoring users. Each user may have multiple entries, and so I wish to SUM the score, grouped by user.
I have looked into `JOIN` operations, but they seem to be used when there are two separate tables, not with two 'views' of a single table.
The issue is that if the `id` field is present, the user will not have a `name`, and vice-versa.
A minimal example can be found at the following link: <http://sqlfiddle.com/#!9/ce0629/11>
Essentially, I have the following data:
```
id name score
--- ----- ------
1 '' 15
4 '' 20
NULL 'paul' 8
NULL 'paul' 11
1 '' 13
4 '' 17
NULL 'simon' 9
NULL 'simon' 12
```
What I want to end up with is:
```
id/name score
-------- ------
4 37
1 28
'simon' 21
'paul' 19
```
I can group by `id` easily, but it treats the NULLs as a single field, when really they are two separate users.
`SELECT id, SUM(score) AS total FROM posts GROUP BY id ORDER by total DESC;`
```
id score
--- ------
NULL 40
4 37
1 28
```
Thanks in advance.
**UPDATE**
The target environment for this query is in Hive. Below is the query and output looking only at the `id` field:
```
hive> SELECT SUM(score) as total, id FROM posts WHERE id is not NULL GROUP BY id ORDER BY total DESC LIMIT 10;
...
OK
29735 87234
20619 9951
20030 4883
19314 6068
17386 89904
13633 51816
13563 49153
13386 95592
12624 63051
12530 39677
```
Running the query below gives the exact same output:
```
hive> select coalesce(id, name) as idname, sum(score) as total from posts group by coalesce(id, name) order by total desc limit 10;
```
Running the following query using the new calculated column name `idname` gives an error:
```
hive> select coalesce(id, name) as idname, sum(score) as total from posts group by idname order by total desc limit 10;
FAILED: SemanticException [Error 10004]: Line 1:83 Invalid table alias or column reference 'idname': (possible column names are: score, id, name)
```<issue_comment>username_1: You could use a COALESCE to get the non-NULL value of either column:
```
SELECT
COALESCE(id, name) AS id
, SUM(score) AS total
FROM
posts
GROUP BY
COALESCE(id, name)
ORDER by total DESC;
```
Upvotes: 1 <issue_comment>username_2: ```
SELECT new_id, SUM(score) FROM
(SELECT coalesce(id,name) new_id, score FROM posts)o
GROUP BY new_id ORDER by total DESC;
```
Upvotes: 1 <issue_comment>username_3: Your `id` looks numeric. In some databases, using `coalesce()` on a numeric and a string can be a problem. In any case, I would suggesting being explicit about the types:
```
select coalesce(cast(id as varchar(255)), name) as id_name,
sum(score) as total
from posts
group by id_name
order by total desc;
```
Upvotes: 2 |
2018/03/19 | 662 | 1,789 | <issue_start>username_0: I have a pandas data frame that looks like:
```
col11 col12
X ['A']
Y ['A', 'B', 'C']
Z ['C', 'A']
```
And another one that looks like:
```
col21 col22
'A' 'alpha'
'B' 'beta'
'C' 'gamma'
```
I would like to replace `col12` base on `col22` in a efficient way and get, as a result:
```
col31 col32
X ['alpha']
Y ['alpha', 'beta', 'gamma']
Z ['gamma', 'alpha']
```<issue_comment>username_1: I'm not sure its the most efficient way but you can turn your `DataFrame` to a `dict` and then use `apply` to map the keys to the values:
Assuming your first `DataFrame` is `df1` and the second is `df2`:
```
df_dict = dict(zip(df2['col21'], df2['col22']))
df3 = pd.DataFrame({"31":df1['col11'], "32": df1['col12'].apply(lambda x: [df_dict[y] for y in x])})
```
or as @jezrael suggested with nested list comprehension:
```
df3 = pd.DataFrame({"31":df1['col11'], "32": [[df_dict[y] for y in x] for x in df1['col12']]})
```
note: `df3` has a default index
```
31 32
0 X [alpha]
1 Y [alpha, beta, gamma]
2 Z [gamma, alpha]
```
Upvotes: 1 <issue_comment>username_2: One solution is to use an indexed series as a mapper with a list comprehension:
```
import pandas as pd
df1 = pd.DataFrame({'col1': ['X', 'Y', 'Z'],
'col2': [['A'], ['A', 'B', 'C'], ['C', 'A']]})
df2 = pd.DataFrame({'col21': ['A', 'B', 'C'],
'col22': ['alpha', 'beta', 'gamma']})
s = df2.set_index('col21')['col22']
df1['col2'] = [list(map(s.get, i)) for i in df1['col2']]
```
Result:
```
col1 col2
0 X [alpha]
1 Y [alpha, beta, gamma]
2 Z [gamma, alpha]
```
Upvotes: 3 [selected_answer] |
2018/03/19 | 1,345 | 4,361 | <issue_start>username_0: I have strings similar to the following:
```
4123499-TESCO45-123
every99999994_54
```
And I want to extract the largest numeric sequence in each string, respectively:
```
4123499
99999994
```
I have previously tried regex (I am using VB6)
```
Set rx = New RegExp
rx.Pattern = "[^\d]"
rx.Global = True
StringText = rx.Replace(StringText, "")
```
Which gets me partway there, but it only removes the non-numeric values, and I end up with the first string looking like:
```
412349945123
```
Can I find a regex that will give me what I require, or will I have to try another method? Essentially, my pattern would have to be anything that isn't the longest numeric sequence. But I'm not actually sure if that is even a reasonable pattern. Could anyone with a better handle of regex tell me if I am going down a rabbit hole? I appreciate any help!<issue_comment>username_1: You cannot get the result by just a regex. You will have to extract all numeric chunks and get the longest one using other programming means.
Here is an example:
```
Dim strPattern As String: strPattern = "\d+"
Dim str As String: str = "4123499-TESCO45-123"
Dim regEx As New RegExp
Dim matches As MatchCollection
Dim match As Match
Dim result As String
With regEx
.Global = True
.MultiLine = False
.IgnoreCase = False
.Pattern = strPattern
End With
Set matches = regEx.Execute(str)
For Each m In matches
If result < Len(m.Value) Then result = m.Value
Next
Debug.Print result
```
The `\d+` with `RegExp.Global=True` will find all digit chunks and then only the longest will be printed after all matches are processed in a loop.
Upvotes: 3 [selected_answer]<issue_comment>username_2: That's not solvable with an RE on its own.
Instead you can simply walk along the string tracking the longest consecutive digit group:
```
For i = 1 To Len(StringText)
If IsNumeric(Mid$(StringText, i, 1)) Then
a = a & Mid$(StringText, i, 1)
Else
a = ""
End If
If Len(a) > Len(longest) Then longest = a
Next
MsgBox longest
```
(first result wins a tie)
Upvotes: 2 <issue_comment>username_3: If the two examples you gave, are of a standard where:
1. `--`
2. `\_`
Are the two formats that the strings come in, there are some solutions.
However, if you are searching any string in any format for the longest number, these will not work.
### Solution 1
```
([0-9]+)[_-].*
```
See the [demo](https://regex101.com/r/r6LDxq/2)
In the first capture group, you should have the longest number for those 2 formats.
**Note**: This assumes that the longest number will be the first number it encounters with an underscore or a hyphen next to it, matching those two examples given.
### Solution 2
```
\d{6,}
```
See the [demo](https://regex101.com/r/r6LDxq/3)
**Note**: This assumes that the shortest number will never exceed 5 characters in length, and the longest number will never be shorter than 6 characters in length
Upvotes: 1 <issue_comment>username_4: Please, try.
Pure VB. **No external libs or objects.**
No brain-breaking regexp's patterns.
No string manipulations, so - speed. **Superspeed. ~30 times faster** than [regexp](https://stackoverflow.com/a/49363651/6698332) :)
Easy transform on variouse needs.
For example, concatenate all digits from the source string to a single string.
Moreover, if target string is only intermediate step,
so it's possible to manipulate with numbers only.
```
Public Sub sb_BigNmb()
Dim sSrc$, sTgt$
Dim taSrc() As Byte, taTgt() As Byte, tLB As Byte, tUB As Byte
Dim s As Byte, t As Byte, tLenMin As Byte
tLenMin = 4
sSrc = "every99999994_54"
sTgt = vbNullString
taSrc = StrConv(sSrc, vbFromUnicode)
tLB = LBound(taSrc)
tUB = UBound(taSrc)
ReDim taTgt(tLB To tUB)
t = 0
For s = tLB To tUB
Select Case taSrc(s)
Case 48 To 57
taTgt(t) = taSrc(s)
t = t + 1
Case Else
If CBool(t) Then Exit For ' *** EXIT FOR ***
End Select
Next
If (t > tLenMin) Then
ReDim Preserve taTgt(tLB To (t - 1))
sTgt = StrConv(taTgt, vbUnicode)
End If
Debug.Print "'" & sTgt & "'"
Stop
End Sub
```
How to handle `sSrc = "ev_1_ery99999994_54"`, please, make by yourself :)
.
Upvotes: 1 |
2018/03/19 | 323 | 1,202 | <issue_start>username_0: It seems like the component from `react-router` only listens to `history.block` which only acts when the URL is changed.
I want to display the same component when user refreshes (F5) or close the window. How can I do that?<issue_comment>username_1: This is how you can prevent page refresh via JS:
```
PromptComponent extends Component {
// Add a listener to prevent browser page refresh
componentWillMount() {
onbeforeunload = e => "Don't leave"
}
// Clear listener
componentWillUnmount() {
onbeforeunload = null
}
}
```
Check out here: [ONLINE](https://codesandbox.io/s/xl7xkv5q3p)
Upvotes: 2 <issue_comment>username_2: I know this is old, but it still seems to get some traffic
```
getSnapshotBeforeUpdate() {
if (this.navigationPrompt()) {
window.onbeforeunload = () => true
} else {
window.onbeforeunload = null
}
return null
}
componentWillUnmount() {
onbeforeunload = null
}
```
is my solution so far, but it shows to default warning -- I'll updated if I figure out how to show my prompt
Note:
`this.navigationPrompt()` is the same logic controller I use in my prompt:
```
```
Upvotes: 0 |
2018/03/19 | 1,305 | 3,820 | <issue_start>username_0: I'm trying to put some state on my comments post who was created with polymorphic association.
in my app/controllers/posts/comments\_controller.rb
```
class Posts::CommentsController < CommentsController
before_action :set_commentable
#after_create :set_post_state
private
def set_commentable
@commentable = Post.find(params[:post_id])
set_post_state
debugger
end
def set_post_state
@commentable.update(state_id: params[:state_id])
end
end
```
As you can see I'm debugging for watch if the state\_id was updated and it wasn't.
```
Started POST "/posts/2/comments" for ::1 at 2018-03-19 13:42:10 +0100
Processing by Posts::CommentsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"<KEY> "comment"=>{"content"=>"test", "state_id"=>"1"}, "commit"=>"Create Comment", "post_id"=>"2"}
Post Load (0.3ms) SELECT "posts".* FROM "posts" WHERE "posts"."id" = ? LIMIT 1 [["id", 2]]
CACHE (0.1ms) SELECT "posts".* FROM "posts" WHERE "posts"."id" = ? LIMIT 1 [["id", "2"]]
(0.3ms) begin transaction
Post Exists (0.2ms) SELECT 1 AS one FROM "posts" WHERE ("posts"."title" = 'Internet Explorer' AND "posts"."id" != 2) LIMIT 1
(0.1ms) commit transaction
Return value is: nil
[6, 15] in /Users/romenigld/ror_workspace/projects/news_city/app/controllers/posts/comments_controller.rb
6:
7: def set_commentable
8: @commentable = Post.find(params[:post_id])
9: set_post_state
10: debugger
=> 11: end
12:
13: def set_post_state
14: @commentable.update(state_id: params[:state_id])
15: end
(byebug) ap @commentable
/Users/romenigld/.rvm/gems/[email protected]/gems/awesome_print-1.7.0/lib/awesome_print/formatters/base_formatter.rb:31: warning: constant ::Fixnum is deprecated
# {
:id => 2,
:title => "Internet Explorer",
:subtitle => "My sample of the subtitle",
:content => "A sample post about Internet Explorer",
:created\_at => Mon, 12 Mar 2018 16:18:28 UTC +00:00,
:updated\_at => Mon, 12 Mar 2018 16:18:28 UTC +00:00,
:author\_id => 1,
:attachment => #, @mounted\_as=:attachment, @storage=#>, @file=#, @versions={:thumb=>#, @mounted\_as=:attachment, @parent\_version=#, @storage=#>, @file=#, @versions={}>, :small\_thumb=>#, @mounted\_as=:attachment, @parent\_version=#, @storage=#>, @file=#, @versions={}>}>,
:state\_id => nil
}
nil
(byebug)
```
in `app/controllers/comments_controller.rb` I add:
```
def comment_params
params.require(:comment).permit(:content, :state_id)
end
```
app/models/comment.rb
```
class Comment < ActiveRecord::Base
belongs_to :author, class_name: "User"
belongs_to :commentable, polymorphic: true
belongs_to :state
```
app/models/post.rb
```
class Post < ActiveRecord::Base
belongs_to :author, class_name: "User"
belongs_to :state
has_many :roles, dependent: :delete_all
has_many :comments, as: :commentable, dependent: :destroy
```
app/models/state.rb
```
class State < ActiveRecord::Base
def to_s
name
end
end
```<issue_comment>username_1: My guess is that `params[:state_id]` is nil but better not guess and instead put a `puts` just before the update and check it out yourself:
`13: def set_post_state
--> puts "Params: #{params}"
14: @commentable.update(state_id: params[:state_id])
15: end`
Upvotes: 1 <issue_comment>username_2: I put like @username_1 put a `puts "Params: #{params}"`
and then I observe the params was needed to put the comment params like this `params[:comment][:state_id]` and now it's recording.
```
def set_post_state
puts "Params: #{params}"
@commentable.update!(state_id: params[:comment][:state_id])
end
```
Thank's for reply @username_1.
Upvotes: 0 |
2018/03/19 | 540 | 1,754 | <issue_start>username_0: A very simple question but couldn't find an answer.
I have a vector of characters (for example - "a" "a" "a" "c" "c" "c" "b" "b" "b").
I would like to group together the elements to "a" "c" "b".
Is there a specific function for that?
Thank you<issue_comment>username_1: Here you go
```
vector <- c("a", "a", "a", "c", "c", "c", "b", "b", "b")
sorted <- sort(vector)
```
Upvotes: -1 <issue_comment>username_2: If you just want the unique elements then there is, well, `unique`.
```
> unique(c("a", "a", "a", "c", "c", "c", "b", "b", "b"), sort=TRUE)
[1] "a" "c" "b"
```
**Update**
With the new description of the problem, this would be my solution
```
shifted <- c(NA, vector[-length(vector)])
vector[is.na(shifted) | vector != shifted]
```
I shift the vector one to the right, putting `NA` at the front because I have no better idea of what to put there, and then pick out the elements that are not `NA` and not equal to the previous element.
If the vector contains `NA`, some additional checks will be needed. It is not obvious how to put something that isn't the first element in the first position of the shifted vector without knowing a bit more. For example, you could extract all the elements form the vector and pick one that isn't the first, but that would fail if the vector only contains identical elements.
Another question now: is there a smarter way to implement the `shift` operation? I couldn't think of one, but there might be an more canonical solution.
Upvotes: -1 <issue_comment>username_3: You can using `sqldf` librayr and using `group by`:
```
require(sqldf)
vector<- data.frame(v=c("a", "a", "a", "c", "c", "c", "b", "b", "b"))
sqldf("SELECT v from vector group by v")
```
Upvotes: 0 |
2018/03/19 | 521 | 1,818 | <issue_start>username_0: My application is built on ASP .NET 5
I used to do a project on .NET Core and everything was OK, there were no problems with logs. But in ASP.NET 5 I do not understand how to do this
I'm trying to write logs to the database using this config:
<https://github.com/nlog/NLog/wiki/Database-target#example-configurations>
This is my config file:
```
xml version="1.0" encoding="utf-8" ?
"Server=localhost\\SQLEXPRESS;Database=LocalDB;User ID=sa;Password=<PASSWORD>;"
insert into dbo.LogExcelWorker (
Application, Logged, Level, Message,
Username,
ServerName, Port, Url, Https,
ServerAddress, RemoteAddress,
Logger, CallSite, Exception
) values (
@Application, @Logged, @Level, @Message,
@Username,
@ServerName, @Port, @Url, @Https,
@ServerAddress, @RemoteAddress,
@Logger, @Callsite, @Exception
);
```
I created the table in the database
I try to make a test call of logs but nothing is written down:
```
public string Index()
{
Logger log = LogManager.GetCurrentClassLogger();
log.Trace( "trace message" );
log.Debug( "debug message" );
log.Info( "info message" );
log.Warn( "warn message" );
log.Error( "error message" );
log.Fatal( "fatal message" );
return "start...";
}
```
But there are no records in the database<issue_comment>username_1: You need to point to the correct target-name
```
```
Upvotes: 0 <issue_comment>username_2: **WriteTog property is wrong**
```
```
should be in your case
```
```
(Change name of target)
General in cases like this enable internal log. This will help you a lot. Here a sample how to enable:
```
internalLogLevel="trace"
internalLogFile="log/internal-nlog.txt"
throwExceptions="true"
throwConfigExceptions="true"
```
Upvotes: 2 [selected_answer] |
2018/03/19 | 536 | 1,903 | <issue_start>username_0: What alternative to an `Inner static Class` can I use in Kotlin Language, if it exists? If not, how can I solve this problem when I need to use a `static class` in Kotlin? See code example below:
```
inner class GeoTask : AsyncTask() {
override fun doInBackground(vararg p0: Util?) {
LocationUtil(this@DisplayMembers).startLocationUpdates()
}
}
```
I've searched a lot, haven't found anything, Thank you very much in advance.<issue_comment>username_1: Just omit the `inner` in Kotlin.
**Inner class (holding reference to outer object)**
Java:
```
class A {
class B {
...
}
}
```
Kotlin:
```
class A {
inner class B {
...
}
}
```
**Static inner class aka nested class (no reference to outer object)**
Java:
```
class A {
static class B {
...
}
}
```
Kotlin:
```
class A {
class B {
...
}
}
```
Upvotes: 8 [selected_answer]<issue_comment>username_2: You can also change the "class" to "object"
```
class OuterA {
object InnerB {
... }
}
```
OR
```
object OuterA {
object InnerB {
... }
}
```
Upvotes: 3 <issue_comment>username_3: In Android world, good practices are:
-Avoid non-static inner classes in activities;
-Use static inner classes with WeakReference so they can be GC-ed (Garbage Collected) when they are not used, as bellow example:
```
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
MySingleton.init(this)
}
}
object MySingleton {
var weakContext: WeakReference? = null
fun init(ctx: Context) {
this.weakContext = WeakReference(ctx)
}
}
```
When the MainActivity instance gets destroyed (onDestroy gets called), this weak reference to its context will get destroyed too; so no memory leaks occur.
:]
Upvotes: 0 |
2018/03/19 | 634 | 2,437 | <issue_start>username_0: I have a `PivotModel` class which I will initialise using the `new` keyword.
```
PivotModel pivotModel = new PivotModel()
```
When `pivotModel` gets initialised, all the dependant fields(model1, model2,cell1,cell2) should get initialised with new object but not to null.
I wanted to initialise all the fields and the fields of dependant classes without using new constructor. I don't want to have boilerplate code.
If you have any standard practice of way doing it, post it here. I am also using `lombok` in my project.
```
public class PivotModel {
@Getter
@Setter
private Model1 model1;
@Getter
@Setter
private Model2 model2;
private Model3 model3 = new Model3() -----> Dont want to initialise this way for these fields
}
public class Model1 {
private Map cell1;
private Map cell2;
private Map cell3;
------ will have some 10 fields here
}
```<issue_comment>username_1: It seems that you are using Lombok project in your java project you can add `@Getter @Setter` above your class Scope, Lombok also provides Constructor Annotation, so Just type above your class Scope `@AllArgsConstructor`
so you class Should be like this
```
@Getter
@Setter
@AllArgsConstructor
public class PivotModel {
private Model1 model1;
private Model2 model2;
}
@Getter
@Setter
@AllArgsConstructor
public class Model1 {
private Map cell1;
private Map cell2;
private Map cell3;
}
```
Upvotes: 2 <issue_comment>username_2: For initialization, I would recommended **Builder Pattern**.
```
//keep your initialization logic in builder class and use build()/create() wherever required. Let's say:
Class Pivot{
// Note: this have only getters for members
//inner builder class
PivotModelBuilder{
//Note: all setter will be part of builder class
/**
* method which return instantiated required object.
*/
public PivotModel build(){
return new PivotModel(this);
}
}
}
//access initilization code as:
PivotModel pivot = new Pivot.PivotModelBuilder().build()
```
Adding referral link: <https://www.javaworld.com/article/2074938/core-java/too-many-parameters-in-java-methods-part-3-builder-pattern.html>
(*You can search more about builder pattern and it's implementation online*)
Limitations:
* However, it's good way to initialize/create bean, but, you might find duplication of member fields in both Parent and builder class.
Upvotes: 2 |
2018/03/19 | 427 | 1,470 | <issue_start>username_0: I'm using Laravel 5.6 and trying to define a blade directive (in the `boot()` method of the service provider):
```
Blade::directive('hello', function () {
return "Hello, World!";
});
```
But in my views, when i write `@hello` it shows `@hello` instead of "hello world" as it should.
I've done `artisan view:clear` (and `cache:clear` too) but still no result.<issue_comment>username_1: I believe you still need to call it. Untested, but try:
```
@hello()
```
Upvotes: 0 <issue_comment>username_2: I use Laravel 5.5 and it works for me.
Inside *boot()* function on ***AppServiceProvider.php*** file.
```
public function boot()
{
\Blade::directive('hello', function ($expression) {
return "php echo 'Hello ' . {$expression}; ?";
});
}
```
And inside view
```
@hello('Unai')
```
Result
```
Hello Unai
```
Upvotes: 2 <issue_comment>username_3: Your expression is ok and @hello on the view is ok too.
Are you using `Illuminate\Support\Facades\Blade` ?
Upvotes: 0 <issue_comment>username_4: You have to do the following
Include this lines
```
use App\TraitsFolder\BladeDirectives;
use Illuminate\Support\Facades\Blade;
```
and in your `AppServiceProvider` class, add this
use BladeDirectives;
If your laravel server is running, stop it and do the following
```
php artisan cache:clear
php artisan config:clear
php artisan view:clear
```
And then start the server again.
Upvotes: 2 |
2018/03/19 | 669 | 2,161 | <issue_start>username_0: Hi my question is how can I store a string value which contails all textfield input into an array with new index every time I press save. I have created some code below however I think its overriding the first index.
```
@IBAction func Save (_ sender: UIButton){
let firstextfield = textfield1.text
let secondtextfield = textfield2.text
let allText = firsttextfield! + "," + secondtextfield!
var myArray = [String]()
var index : Int = 0
while (myArray.count) <= index {
myArray.insert(allText, at: index)
}
index +=
for element in myArray{
print(element)
}
}
```
input: firsttextfield = 9.22 and secondtextfield = 91.2
save button is then pressed.
output:
```
Optional ("9.22,91.2")
Optional ("")
```
if i were to then change the values of my textfields to firsttextfield = 0.2 and secondtextfield = 20.2
I get output :
```
Optional ("0.2,20.2")
Optional ("")
```
I dont want it to overide the array but to add onto it so expected output:
```
Optional ("9.22,91.2")
Optional ("0.2,20.2")
```
Any tips are welcome as I am new to coding.<issue_comment>username_1: I believe you still need to call it. Untested, but try:
```
@hello()
```
Upvotes: 0 <issue_comment>username_2: I use Laravel 5.5 and it works for me.
Inside *boot()* function on ***AppServiceProvider.php*** file.
```
public function boot()
{
\Blade::directive('hello', function ($expression) {
return "php echo 'Hello ' . {$expression}; ?";
});
}
```
And inside view
```
@hello('Unai')
```
Result
```
Hello Unai
```
Upvotes: 2 <issue_comment>username_3: Your expression is ok and @hello on the view is ok too.
Are you using `Illuminate\Support\Facades\Blade` ?
Upvotes: 0 <issue_comment>username_4: You have to do the following
Include this lines
```
use App\TraitsFolder\BladeDirectives;
use Illuminate\Support\Facades\Blade;
```
and in your `AppServiceProvider` class, add this
use BladeDirectives;
If your laravel server is running, stop it and do the following
```
php artisan cache:clear
php artisan config:clear
php artisan view:clear
```
And then start the server again.
Upvotes: 2 |
2018/03/19 | 891 | 3,261 | <issue_start>username_0: I've got a query in eloquent correctly calculating the count as it should here:
```
$query = A::withCount(
['bs' =>
function ($query) use ($from, $to) {
$query->where(function ($query) use ($from) {
$query->whereDate('start', '<', $from)
->whereDate('end', '>', $from);
})->orWhere(function ($query) use ($to) {
$query->whereDate('start', '<', $to)
->whereDate('end', '>', $to);
})->orWhere(function ($query) use ($from, $to) {
$query->whereDate('start', '>', $from)
->whereDate('end', '<', $to);
});
}])
->whereBetween('cmp1', [$min_cmp1, $max_cmp1])
->whereBetween('cmp2', [$min_cmp2, $max_cmp2])
->where('cmp3', '<=', $request->cmp3)
->where('cmp4', '<=', $request->cmp4)
->with('more_relations');
return AResource::collection($query->paginate(5));
```
This goes to an API Controller. I use this for frontend pagination with Vue. I want to use the count to filter out all `A`'s with a `bs_count` of 0, however chaining a where clause does not work as it is an aggregate, and it returns an error for not finding a column named `bs_count`. The solution, I found out, would be to use a `having` clause. I found this code, but when I try to convert it, it doesn't work, returning the same error, not finding a column named `bs_count`.
```
DB::table('bs')
->select('*', DB::raw('COUNT(*) as bs_count'))
->groupBy('a_id')
->having('bs_count', '=' , 0);
```
This is without adding the extra query on the count, as I wanted to try this to see if it works first, which it doesn't.
Is the `having` clause the correct way to go? I think I need to use Eloquent rather than the `DB::table()` syntax as the Resource builder uses the model structure to build the resource response.
In summary, I'm trying to use the count I calculated in my first query, and query against it: `where bs_count = 0`. Is there a way to do this in Laravel and still be able to pass on the results to the API Resource?<issue_comment>username_1: I believe you still need to call it. Untested, but try:
```
@hello()
```
Upvotes: 0 <issue_comment>username_2: I use Laravel 5.5 and it works for me.
Inside *boot()* function on ***AppServiceProvider.php*** file.
```
public function boot()
{
\Blade::directive('hello', function ($expression) {
return "php echo 'Hello ' . {$expression}; ?";
});
}
```
And inside view
```
@hello('Unai')
```
Result
```
Hello Unai
```
Upvotes: 2 <issue_comment>username_3: Your expression is ok and @hello on the view is ok too.
Are you using `Illuminate\Support\Facades\Blade` ?
Upvotes: 0 <issue_comment>username_4: You have to do the following
Include this lines
```
use App\TraitsFolder\BladeDirectives;
use Illuminate\Support\Facades\Blade;
```
and in your `AppServiceProvider` class, add this
use BladeDirectives;
If your laravel server is running, stop it and do the following
```
php artisan cache:clear
php artisan config:clear
php artisan view:clear
```
And then start the server again.
Upvotes: 2 |
2018/03/19 | 507 | 1,810 | <issue_start>username_0: I would like to open my app's settings page inside the Settings app with Swift 4 in iOS 11. Just like the picture shows:
[](https://i.stack.imgur.com/4siJC.png)
The following codes doesn't work, it will only open the Settings app:
```
if let url = URL(string:UIApplicationOpenSettingsURLString) {
if UIApplication.shared.canOpenURL(url) {
UIApplication.shared.open(url, options: [:], completionHandler: nil)
}
}
```
The app shows in the above picture is able to do this. So I wonder if there is any way to custom the URL Scheme to make it happen?<issue_comment>username_1: Oops, it seems it works in iOS 11.4.1:
```
if let url = URL(string:UIApplicationOpenSettingsURLString) {
if UIApplication.shared.canOpenURL(url) {
UIApplication.shared.open(url, options: [:], completionHandler: nil)
}
}
```
Upvotes: 4 [selected_answer]<issue_comment>username_2: Just an update because UIApplicationOpenSettingsURLString changed.
```
guard let url = URL(string: UIApplication.openSettingsURLString) else {
return
}
if UIApplication.shared.canOpenURL(url) {
UIApplication.shared.open(url, options: [:])
}
```
Upvotes: 3 <issue_comment>username_3: You can open your app settings screen using it's bundle id, for example for CAMERA permission, you can use
```
if let bundleId = /* your app's bundle identifier */
let url = URL(string: "\(UIApplication.openSettingsURLString)&path=CAMERA/\(bundleId)"),
UIApplication.shared.canOpenURL(url) {
UIApplication.shared.open(url, options: [:], completionHandler: nil)
}
}
```
Reference: <https://stackoverflow.com/a/61383270/4439983>
Upvotes: 1 |
2018/03/19 | 309 | 1,347 | <issue_start>username_0: I'm starting with AWS and I've been taking my first steps on EC2 and EBS. I've learnt about EBS snapshots but I still don't understand if the backups, once you've created a snapshot, are managed automatically by AWS or I need to do them on my own.<issue_comment>username_1: Snapshots are managed by AWS
snapshot of an EBS volume, can be used as a baseline for new volumes or for data backup. If you make periodic snapshots of a volume, the snapshots are incremental—only the blocks on the device that have changed after your last snapshot are saved in the new snapshot. Even though snapshots are saved incrementally,
the built in durability of EBS is comparable to a RAID in the physical sense. The data itself is mirrored (think more like a RAID stripe though) in the availability zone where the volume exists. Amazon states that the failure rate is somewhere around 0.1-0.5% annually. This is more reliable than most physical RAID setups
Upvotes: 2 [selected_answer]<issue_comment>username_2: AWS just introduced a new feature called Lifecycle Manager (in the EC2 Dashboard, at the bottom left) that allows you to create automated backups for your volumes. Once you configure a policy, AWS will handle the backup process for your volumes.
This is only a couple of weeks old so just wanted to mention here.
Upvotes: 2 |
2018/03/19 | 386 | 1,305 | <issue_start>username_0: I am new to web development. Before asking this question I have gone through all the solutions, but still I was getting some problems so...
Here I have HTML:
```
Agency :
```
and here I have an array:
```
$scope.agency = ["A", "B", "C", "D"];
```
Now I want to have a A as a default value in that dropdown. But currently with this I am getting an empty value.
```
$scope.candidate = {
noticePeriod: '',
ctc: '',
ectc: '',
communication: '',
agency: ''
};
```
This may be a duplicate but I am getting problem so I am asking. Thanks for
the help.<issue_comment>username_1: You should initialize `ngModel` linked variable in the controller instead of using [`ngInit`](https://docs.angularjs.org/api/ng/directive/ngInit)
```js
(function(angular) {
'use strict';
angular.module('myApp', [])
.controller('Controller', ['$scope', function($scope) {
$scope.agency = ["A", "B", "C", "D"];
$scope.candidate = {
agency: $scope.agency[0]
};
}]);
})(window.angular);
```
```html
```
Upvotes: 2 <issue_comment>username_2: Remove the ng-init and use ng-model instead:
Result:
```
$scope.candidate = {
noticePeriod: '',
ctc: '',
ectc: '',
communication: '',
agency: 'A'
};
```
Upvotes: 0 |
2018/03/19 | 388 | 1,350 | <issue_start>username_0: I'm looking at moving from `unittest` to `pytest`. One thing I like to do, is to do a `setup.py install` and then run the tests from the installed modules, rather than directly from the source code. This means that I pick up any files I've forgotten to include in `MANIFEST.in`.
With `unittest`, I can get the test runner to do test discovery by specifying the root test module. e.g. `python -m unittest myproj.tests`
Is there a way to do this with `pytest`?
I'm using the following hack, but I wish there was a built in cleaner way.
```
pytest $(python -c 'import myproj.tests; print(myproj.tests.__path__[0])')
```<issue_comment>username_1: You should initialize `ngModel` linked variable in the controller instead of using [`ngInit`](https://docs.angularjs.org/api/ng/directive/ngInit)
```js
(function(angular) {
'use strict';
angular.module('myApp', [])
.controller('Controller', ['$scope', function($scope) {
$scope.agency = ["A", "B", "C", "D"];
$scope.candidate = {
agency: $scope.agency[0]
};
}]);
})(window.angular);
```
```html
```
Upvotes: 2 <issue_comment>username_2: Remove the ng-init and use ng-model instead:
Result:
```
$scope.candidate = {
noticePeriod: '',
ctc: '',
ectc: '',
communication: '',
agency: 'A'
};
```
Upvotes: 0 |
2018/03/19 | 697 | 2,872 | <issue_start>username_0: I am trying to create an electron desktop app with angular as frontend and .net as backend.
I created a sample angular project in .netcore 2.0 from VS 2017 and followed the steps mentioned [here](https://github.com/ElectronNET/Electron.NET)
I'm having issues with `dotnet electronize init` command. It's giving below error :
```
No executable found matching command "dotnet-electronize"
```
Can someone please let me know if I'm missing anything.
Also if there is any boilerplate code which I can refer to would be really helpful.<issue_comment>username_1: I was using powershell which has some unexpected behavior.Check [here](https://github.com/ElectronNET/Electron.NET/issues/28) for more details.
Upvotes: 4 [selected_answer]<issue_comment>username_2: Angular SPA with Dotnet Core and ElectronNet API
1. Open VS 2017 with Administrator mode
2. Create Asp.Net core Web Application with Angular template
3. Install the ElectronNET.CLI using following command "dotnet tool install ElectronNET.CLI -g"
4. Goto project folder and open cmd
5. Execute the following command "electronize init", it will create electron-manifest.json file in project folder
6. Right click on dependencies, goto Nuget package manager and install ElectronNET.API
7. Add ElectronBootstrap() method in Startup.cs
```
public async void ElectronBootstrap()
{
BrowserWindowOptions options = new BrowserWindowOptions
{
Show = false
};
BrowserWindow mainWindow = await Electron.WindowManager.CreateWindowAsync();
mainWindow.OnReadyToShow += () =>
{
mainWindow.Show();
};
mainWindow.SetTitle("App Name here");
MenuItem[] menu = new MenuItem[]
{
new MenuItem
{
Label = "File",
Submenu=new MenuItem[]
{
new MenuItem
{
Label ="Exit",
Click =()=>{Electron.App.Exit();}
}
}
},
new MenuItem
{
Label = "Info",
Click = async ()=>
{
await Electron.Dialog.ShowMessageBoxAsync("Welcome to App");
}
}
};
Electron.Menu.SetApplicationMenu(menu);
}
```
8. Call that method from Configure() in Startup.cs
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
...
ElectronBootstrap();
}
9. Add UseElectron(args) in Program.cs
public static IWebHostBuilder CreateWebHostBuilder(string[] args)
{
return WebHost.CreateDefaultBuilder(args)
.UseStartup()
.UseElectron(args);
}
10. Build the project
11. Goto project folder, open cmd and execute the following command "electronize start", it will open the desktop application. First time it will take time.
12. Production build for windows: electronize build /target win
Got it from here: <https://github.com/rajeshsuramalla/AngularWithDotNetCoreElectronNET>
Upvotes: 2 |
2018/03/19 | 630 | 2,476 | <issue_start>username_0: Do I need to show my App in UIActivityViewController for my another application without the usage of Extension? Is it possible?
And also need when i tapped on other app which are shown in UIActivity ViewController that transfer me into that app.(If is it Possible?)
I have already looked at the following SO Thread [I need to show my App in UIActivityViewController for All Applications as Action Extension(Default)](https://stackoverflow.com/questions/35268508/i-need-to-show-my-app-in-uiactivityviewcontroller-for-all-applications-as-action), but this is done by extension.
For e.g, In iOS 11.0 and above version it give myfile application which shows the files.In this files when I tapped on pdf it shows the own pdfviewer but when i tapped on share button it provide me another added pdfviewer to read and other function which are supported by that application and transfer me to that app.
Is it possible with Action Extension?
Thank You.<issue_comment>username_1: It depends whether you want to receive documents or data.
If you want to be listed for Open In or Copy To, as for a document type like PDF, then just declare in the Info.plist that you are a viewer for that document type.
Otherwise to receive data directly thru an activity view, use an Action or Share extension to be listed in the activity view.
Upvotes: 1 <issue_comment>username_2: Finally I got the answer
When I use UIDocumentInteractionController this is showing me my other app which are support "pdf" and add the property in info.plist which are provided by @username_1.
Below code used in parent app so when touch button it shows result like below image.
This is my code:-
```
@IBAction func ShareDocAction(_ sender : UIButton){
let fileUrl = Bundle.main.url(forResource: "Terms_Condition", withExtension: "pdf")
self.documentController = UIDocumentInteractionController(url: fileUrl!)
DispatchQueue.main.async {
self.documentController.presentOptionsMenu(from: self.actionButton.frame, in: self.view, animated: true)
}
}
```
and in child app we need to add below code in info.plist:-
```
CFBundleDocumentTypes
CFBundleTypeName
PDF Document
CFBundleTypeRole
Viewer
LSHandlerRank
Alternate
LSItemContentTypes
com.adobe.pdf
```
Here I attach my image show whole scenario
[](https://i.stack.imgur.com/CK5rN.png)
Thank you
Upvotes: 1 [selected_answer] |
2018/03/19 | 852 | 2,747 | <issue_start>username_0: My data looks like:
```
1 1.45
1 1.153
2 2.179
2 2.206
2 2.59
2 2.111
3 3.201
3 3.175
4 4.228
4 4.161
4 4.213
```
The output I want is :
```
1 2 (1 occurs 2 times)
2 4
3 2
4 3
```
For this I run the following code:
```
SubPatent2count = {}
for line in data.split('\n'):
for num in line.split('\t'):
Mapper_data = ["%s\t%d" % (num[0], 1) ]
for line in Mapper_data:
Sub_Patent,count = line.strip().split('\t',1)
try:
count = int(count)
except ValueError:
continue
try:
SubPatent2count[Sub_Patent] = SubPatent2count[Sub_Patent]+count
except:
SubPatent2count[Sub_Patent] = count
for Sub_Patent in SubPatent2count.keys():
print ('%s\t%s'% ( Sub_Patent, SubPatent2count[Sub_Patent] ))
```
At the end I get this error :
```
3 for num in line.split('\t'):
4 #print(num[0])
----> 5 Mapper_data = ["%s\t%d" % (num[0], 1) ]
6 #print(Mapper_data)
7 for line in Mapper_data:
IndexError: string index out of range
```
If you have any Idea how I can deal with this error please Help.
Thank you!<issue_comment>username_1: It depends whether you want to receive documents or data.
If you want to be listed for Open In or Copy To, as for a document type like PDF, then just declare in the Info.plist that you are a viewer for that document type.
Otherwise to receive data directly thru an activity view, use an Action or Share extension to be listed in the activity view.
Upvotes: 1 <issue_comment>username_2: Finally I got the answer
When I use UIDocumentInteractionController this is showing me my other app which are support "pdf" and add the property in info.plist which are provided by @username_1.
Below code used in parent app so when touch button it shows result like below image.
This is my code:-
```
@IBAction func ShareDocAction(_ sender : UIButton){
let fileUrl = Bundle.main.url(forResource: "Terms_Condition", withExtension: "pdf")
self.documentController = UIDocumentInteractionController(url: fileUrl!)
DispatchQueue.main.async {
self.documentController.presentOptionsMenu(from: self.actionButton.frame, in: self.view, animated: true)
}
}
```
and in child app we need to add below code in info.plist:-
```
CFBundleDocumentTypes
CFBundleTypeName
PDF Document
CFBundleTypeRole
Viewer
LSHandlerRank
Alternate
LSItemContentTypes
com.adobe.pdf
```
Here I attach my image show whole scenario
[](https://i.stack.imgur.com/CK5rN.png)
Thank you
Upvotes: 1 [selected_answer] |
2018/03/19 | 1,130 | 4,160 | <issue_start>username_0: I am using flask\_mail to send emails, while this works for text message, I need some help if i need to send a template itself (what does this mean: so I am rendering a report that contains multiple tables and a text area on the top with a submit button, once the user fills the text area and click on submit, I need flask to send the report containing table along with text data ).
This code fetches data from service now incident table
```
def incident():
service_now_url = SERVICE_NOW_URL
request_str = req
user = 'username'
pwd = '<PASSWORD>'
url = service_now_url + request_str
headers = {"Accept": "application/json"}
response = requests.get(url, auth=(user, pwd), headers=headers)
json_str = response.json()
records = json_str['result']
return records
```
This code below is used for rendering the text field and the table.
```
@app.route('/submit', methods=['GET','POST'])
def submit():
rec = incident()
form = Description(request.form)
shift = form.Shift.data
return render_template('index.html', rec=rec, state=STATES, form=form)
```
So for sending the email so far, I have written the function below, this sends an email but with table header only and no data.
```
def send_email(shift):
msg = Message(subject=shift ,recipients=['<EMAIL>'])
msg.html=render_template('index.html')
mail.send(msg)
```
I am not a Flask expert and still, in the learning phase, any help would be greatly appreciated.
@George thanks for your help, but this is not working, I have pasted below the html template with the modification suggested by you.
```
{{ title }} : Graph
{% if sending\_mail %}
{{ get\_resource\_as\_string('static\style\main.css') }}
{% endif %}
{{ shiftsum }}
Task
====
Task Number | Description | State |
{% for records in rec %}
| {{records['number'] }} | {{records['short\_description']}} | {{ state[records['state']]}} |
{% endfor %}
```<issue_comment>username_1: Change the definition of `send_email()` to as given below,
```
def send_email(shift, rec, STATES):
msg = Message(subject=shift ,recipients=['<EMAIL>'])
msg.html=render_template('index.html', rec=rec, state=STATES)
mail.send(msg)
```
And in the `index.html` make sure you enclose the form inside `{% if form %} ... {% endif %}` where `...` indicates your form code.
I hope this helps.
---
Update (for fixing the missing css styles)
Add the following in your flask script below `app = Flask(__name__)` or in respective blueprint file,
```
def get_resource_as_string(name, charset='utf-8'):
with app.open_resource(name) as f:
return f.read().decode(charset)
app.jinja_env.globals['get_resource_as_string'] = get_resource_as_string
```
Add the following in the `index.html`
```
{% if sending_mail %}
{{ get\_resource\_as\_string('static/css/styles.css') }}
{% endif %}
```
Where `static/css/styles.css` should be replaced with path to your css file. If more than one css file is there, just add `{{ get_resource_as_string('static/css/styles.css') }}` for each one of them, with their respective path as argument of `get_resource_as_string()`
Make the following changes in `send_email()`,
```
def send_email(shift, rec, STATES):
msg = Message(subject=shift ,recipients=['<EMAIL>'])
msg.html=render_template('index.html', rec=rec, state=STATES, sending_mail=True)
mail.send(msg)
```
I have added `sending_mail=True` as argument to the render\_template() so whenever sending\_mail is set, the render\_template will add the content from the css files to the `...`.
I hope this fixes the missing css styles.
Upvotes: 1 <issue_comment>username_2: @George thanks for your help, anyways I have found out what was the missing link here,
So the thing is most of the email client doesn't support CSS that are stored locally(this what I found out, could be other things as well), so I used inline CSS and that is working perfectly and now I can see all the formatting that has been done inline in the HTML Template while sending the email.
Upvotes: 0 |
2018/03/19 | 265 | 931 | <issue_start>username_0: I know it's a stupid question but I would like to know if this is possible doing some configurations.
[The VSCode by default show the folders first](https://i.stack.imgur.com/TAa4l.png)<issue_comment>username_1: Yes you can do that. Just add the following entry to your `settings.json`:
```json
"explorer.sortOrder": "filesFirst"
```
An overview of all possible settings can be found [here](https://code.visualstudio.com/docs/getstarted/settings#_default-settings).
Upvotes: 5 [selected_answer]<issue_comment>username_2: If some comes across this, like me looking for the other way around. Having folders first and files second. User `"explorer.sortOrder": "foldersFirst"` in your `settings.json`.
Upvotes: 2 <issue_comment>username_3: `File` > `Preferences` > `Settings` > Search `sort order`
[](https://i.stack.imgur.com/02s7P.png)
Upvotes: 2 |
2018/03/19 | 233 | 833 | <issue_start>username_0: I want to make a checkout on a version of a Git repository in Python.
I am using the following code lines:
```
from git import Git
g = Git(os.getcwd())
g.checkout(row[2])
```
the question is how can I make a forced checkout?<issue_comment>username_1: According to [reference](http://gitpython.readthedocs.io/en/stable/reference.html#git.refs.head.Head.checkout) `checkout` function takes first optional argument force=False `checkout(force=False, **kwargs)`
Therefore, you can just simply call it with first argument force=True, to force the force checkout, like this
`g.checkout(force=True, row[2])`
Upvotes: 0 <issue_comment>username_2: From the documentation, the checkout method takes keyword arguments:
```
g.checkout(row[2], force=True)
```
Should do what you want.
Upvotes: 2 [selected_answer] |
2018/03/19 | 278 | 952 | <issue_start>username_0: I have tried this:
Inside **AddClass.aspx**
```
```
Inside **AddClass.aspx.cs**:
When Button (ID:btnSave) is clicked:
```
protected void btnSave_Click(object sender, EventArgs e)
{
string a=Request.Form["txtClass"];
}
```
And I am not getting value in string 'a' .
Is there any way of getting value of html textbox in .cs code.<issue_comment>username_1: According to [reference](http://gitpython.readthedocs.io/en/stable/reference.html#git.refs.head.Head.checkout) `checkout` function takes first optional argument force=False `checkout(force=False, **kwargs)`
Therefore, you can just simply call it with first argument force=True, to force the force checkout, like this
`g.checkout(force=True, row[2])`
Upvotes: 0 <issue_comment>username_2: From the documentation, the checkout method takes keyword arguments:
```
g.checkout(row[2], force=True)
```
Should do what you want.
Upvotes: 2 [selected_answer] |
2018/03/19 | 1,360 | 5,087 | <issue_start>username_0: We have developed a site with typo3 v8.7.11. We want to display the search box in the sidebar section, for this we installed the indexed\_search extension. B
How to display a search box in all the frontend page sidebar section?<issue_comment>username_1: you have multiple options:
1. copy the HTML of the form from the search plugin in the normal content and insert it in your page-(html-)template.
2. create a special BE-column, insert the search-plugin into this column and render this column inherited in all pages
3. make a special page not visible in FE, where you insert the search-plugin and include this special CE in the rendering of every page (use a CONTENT object in typoscript to select that special CE)
4. include and configure the plugin in typoscript. (see answer of username_2)
I prefer option 2 as it is most flexible and does not need any special page or content IDs, which might change with time (option 3). It also can handle any kind of CE.
Option 1 needs manual fixing if there are changes in the plugin rendering after an update for example.
Option 4 is not possible for each plugin or CEs at all to inherit. If you can configure the plugin with typoscript it is a fine option because you do not need any record (from tt\_content)
for option 2:
```
temp.inheritedContent = CONTENT
temp.inheritedContent {
table = tt_content
select.orderBy = sorting
// -- use your own column id: --
select.where = colPos = 100
select.languageField = sys_language_uid
slide = -1
}
```
Upvotes: 1 <issue_comment>username_2: The easiest way is to copy the given plugin from `indexed_search` to a variable you use in your template.
When you e.g. use FLUIDTEMPLATE:
```
page.10 = FLUIDTEMPLATE
page.10.variable.searchBox < plugin.tx_indexedsearch
```
After that you can assign a separate template and make other modifications by changing `page.10.variable.searchBox` with the possible configuration here: <https://docs.typo3.org/typo3cms/extensions/indexed_search/8.7/Configuration/Index.html>
Upvotes: -1 <issue_comment>username_3: **Edit:**
The `search` and `form` action of the SearchController are both non-cacheable. This means that you would place a non-cacheable plugin on each of your pages, if you used my old answer. This harms performance and could have other side-effects.
Nowadays I usually simply include a search form on each of my pages by including this in my Fluid Template:
```
Search
```
I hand over the searchPid variable via TypoScript like this:
```
page.10.variables.searchPid = TEXT
page.10.variables.searchPid.value =
```
---
Old answer:
My tip would be to create a TypoScript object that actually includes the plugin, like this:
```
lib.headerSearch = USER
lib.headerSearch {
userFunc = TYPO3\CMS\Extbase\Core\Bootstrap->run
extensionName = IndexedSearch
pluginName = Pi2
vendorName = TYPO3\CMS
switchableControllerActions {
Search {
1 = form
2 = search
}
}
features {
requireCHashArgumentForActionArguments = 0
}
view < plugin.tx_indexedsearch.view
view.partialRootPaths.10 = Path/To/Partial/
view.templateRootPaths.10 = Path/To/Template/
settings =< plugin.tx_indexedsearch.settings
}
```
Then, in your template, include it like this
```
```
Note that you should create a new "Search.html" Template in Path/To/Template/Search/ for this TS-Plugin, so that it does not interfere with the regular plugin. Also, be careful if you include the search slot on the same page as the search Plugin itself.
Upvotes: 2 <issue_comment>username_4: Use a TYPO3 extension, which can be a copy (fork) of the newly developed version of [macina\_searchbox](https://github.com/franzholz/macina_searchbox)
**Template Module**: Add "Macina Searchbox" under "include static from extensions" .
Use this or a similar TypoScript to include it, where '6' in this example is the search page. Use your own page id instead.
Constants:
```
lib.macina_searchbox {
pidSearchpage = 6
}
```
Setup:
```
10 = TEMPLATE
10.template = FILE
10.template.file = fileadmin/template/template.html
10.workOnSubpart = DOKUMENT
10.marks {
SUCHE < lib.macina_searchbox
LOGO = TEXT
LOGO.value = [](/ "Startseite")
NAVI= HMENU
NAVI {
```
Then you can edit the Fluid template files in the folders below macina\_searchbox/Resources/Private/ to modify the output of the searchbox. This method is necessary in order that the search result list will not be shown on the page. You must instead insert an Indexed Search plugin on your search page, which has id=6 in this example. SUCHE is the marker in the main template of the website. Use your own marker.
Upvotes: 0 <issue_comment>username_5: Since TYPO3 version 12 the f:form Fluid ViewHelper does not work anymore ("ViewHelper f:form can be used only in extbase context and needs a request implementing extbase RequestInterface."). The solution is a static form with a dynamically generated URL:
```
```
Upvotes: 1 |
2018/03/19 | 1,263 | 3,642 | <issue_start>username_0: I have trouble with vertical alignment of some google icons inside buttons. I tried to play with padding and margin but I could not fix the issue.
This is a screenshot of the problem: as you can see the icon are placed slightly higher:
[](https://i.stack.imgur.com/0P626.png)
This is part of the html, each button is more or less the same:
```
*brush*
```
This is the css for the button:
```
.button {
margin: auto;
display: inline-block;
margin-top: 5px;
color: black;
border: 0px solid grey;
border-radius: 6px;
background-color: #EFEFEF;
text-align: center;
text-decoration: none;
cursor: pointer;
box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);
z-index: 4;
vertical-align: middle;
}
.button {
width: 50px;
height: 40px;
}
.button:hover {
background-color: #aaaaaa !important;
color: white !important;
}
```
And finally the css for the div:
```
#mainToolbar {
position: absolute;
top: 0px;
left: 0px;
height: 520px;
width: 60px;
z-index: 10;
text-align: center;
}
```
How can I put the icon right in the middle of the button (both vertically and horizontally)? Thanks.<issue_comment>username_1: Its Working Fine see snippet
```css
.button {
margin: auto;
display: inline-block;
margin-top: 5px;
color: black;
border: 0px solid grey;
border-radius: 6px;
background-color: #EFEFEF;
text-align: center;
text-decoration: none;
cursor: pointer;
box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);
z-index: 4;
vertical-align: middle;
}
.button {
width: 50px;
height: 40px;
}
.button:hover {
background-color: #aaaaaa !important;
color: white !important;
}
And finally the css for the div:
#mainToolbar {
position: absolute;
top: 0px;
left: 0px;
height: 520px;
width: 60px;
z-index: 10;
text-align: center;
}
```
```html
```
Upvotes: 0 <issue_comment>username_2: You can use absolute positioning along with translate to position the icon right in the middle. Be sure to add a `position:relative` on the `button` so that the icon is positioned w.r.t to the button.
```css
.button {
margin: auto;
display: inline-block;
margin-top: 5px;
color: black;
border: 0px solid grey;
border-radius: 6px;
background-color: #EFEFEF;
text-align: center;
text-decoration: none;
cursor: pointer;
box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);
z-index: 4;
vertical-align: middle;
}
.button {
width: 50px;
height: 40px;
position: relative;
}
.button:hover {
background-color: #aaaaaa !important;
color: white !important;
}
.button:active i{
/*for push effect on click*/
transform: translate(-45%, -45%);
}
.button i {
/*horizontal and vertical centering*/
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
#mainToolbar {
position: absolute;
top: 0px;
left: 0px;
height: 520px;
width: 60px;
z-index: 10;
text-align: center;
}
```
```html
*brush*
```
To explain:
`top:50%` with a `position: absolute` will move the icon down 50% of the parent's height. A translateY with -50% will move the icon up by half its height so that its aligned right in the middle by its center. Similarly with horizontal centering.
Upvotes: 2 [selected_answer] |
2018/03/19 | 353 | 1,402 | <issue_start>username_0: ```
package collections;
public class Construct
{
class Inner
{
void inner()
{
System.out.println("inner class method ");
}
}
public static void main(String[] args)
{
Construct c=new Construct();
}
}
```
How to call a method of the inner class? How to create an object to call a method of the inner class?<issue_comment>username_1: Use this:
```
Inner inner = new Construct().new Inner();
inner.inner();
```
Upvotes: 2 <issue_comment>username_2: Inner class is a nested class. Nested classes can be static or not. If static then its called static nested class and if not its called inner classes.
Non-static nested classes hold a reference to the Outer class that they are nested within.
What you have is an inner nested class, so we need to instantiate the inner class with a reference from the Outer like so:
```
Construct c = new Construct();
Inner inner = c.new Inner(); //using reference to create inner
inner.inner(); //Calling method from inner.
```
Upvotes: 0 <issue_comment>username_3: Depends upon whether your class is static or non-static.
For non-static inner class, use this:
```
Inner inner = new Construct().new Inner();
inner.inner()
```
For static inner-class, use this:
```
InnerStatic inner = new Construct.Inner();
inner.inner()
```
Upvotes: 0 |
2018/03/19 | 820 | 3,199 | <issue_start>username_0: I am currently having an issue regarding CORS (Cross-origin resource sharing) the odd thing being this only seems to happen when i prefix my url using www.
For example when i go to my website using the url: "<http://example.com/index>" everything works fine and all resources are loaded correctly. however when i try to visit my website using the url "<http://www.example.com/index>" i get the error `Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://example.com/index. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).`
The resource i am trying to load is an XML file using the following code:
```js
function loadXML()
{
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
xmlData = xhttp.responseXML;
initStartShot();
}
};
xhttp.open("GET", "http://example.com/XML/someXMLfile.xml", true);
xhttp.send();
}
```
all my resource files are on the same domain as my page.
i have looked around SO for [issues related to mine](https://stackoverflow.com/questions/20035101/why-does-my-javascript-get-a-no-access-control-allow-origin-header-is-present), but most are about CORS in general, and how to get it to work. but seeing the fact i'm not having any CORS issues without "www" prefixed this doesn't seem applicable to my issue.
Unfortunately I am unable to share the url itself, but if you require any other information i'll do my best to provide it.
Any help would be greatly appreciated.
~Remy<issue_comment>username_1: While reviewing my SO post i actually found the issue, so for future reference i will be answering my own question:
In my XML downloader i used a static path `xhttp.open("GET", "http://example.com/XML/someXMLfile.xml", true);` instead of a relative path `../XML/someXMLfile.xml`, I am not yet clear as to why "www.example.com" and "example.com" are handled as different domains, but this solved the issue for me.
EDIT: as per @Daniel\_Gale his comment, using location.hostname will also work.
Upvotes: 0 <issue_comment>username_2: `example.com` and `www.example.com` are different origins. To be the same origin the URL scheme, hostname, and port must be the same. `www.example.com` and `example.com` are not the same hostname.
By *default* it is allowed for JavaScript to access data from the same origin.
You get the error about the missing CORS permissions because you are trying to access one origin from the other.
There are several ways you can resolve this.
* Don't use multiple origins in the first place. Pick one of `example.com` and `www.example.com` to be canonical. Configure your HTTP server to issue 301 redirects from the non-canonical one to the canonical one.
* Use relative URLs. Your absolute URL means that when you are on the wrong origin, it still tries to access the other one. Using a relative URL will keep the request going to the same origin as the page.
* Configure your server to grant permission to the other origin with CORS headers.
I recommend the first of those options.
Upvotes: 4 [selected_answer] |
2018/03/19 | 683 | 2,295 | <issue_start>username_0: I've tried to code a game where the character controlled by the player can move around and shoot things, the problem is, if I press the shoot key he stops walking because only one key can be noticed at once.
How do I make it so multiple keys can be used at once.
I'm very new to code so I may not understand confusing concepts.
Thanks
```
function move(e){
//alert(e.keyCode);
if(e.keyCode==68){
if(over == 0){
if(xPos < 990){
xPos+=10;
}
}
}
if(e.keyCode==65){
if(over == 0){
if(xPos > 0){
xPos-=10;
}
}
}
if(e.keyCode==87){
if(over < 1){
if(yPos > 0){
yPos-=10;
}
}
}
if(e.keyCode==83){
if(over == 0){
if(yPos < 540){
yPos+=10;
}
}
}
```
}
document.onkeydown = move;<issue_comment>username_1: While reviewing my SO post i actually found the issue, so for future reference i will be answering my own question:
In my XML downloader i used a static path `xhttp.open("GET", "http://example.com/XML/someXMLfile.xml", true);` instead of a relative path `../XML/someXMLfile.xml`, I am not yet clear as to why "www.example.com" and "example.com" are handled as different domains, but this solved the issue for me.
EDIT: as per @Daniel\_Gale his comment, using location.hostname will also work.
Upvotes: 0 <issue_comment>username_2: `example.com` and `www.example.com` are different origins. To be the same origin the URL scheme, hostname, and port must be the same. `www.example.com` and `example.com` are not the same hostname.
By *default* it is allowed for JavaScript to access data from the same origin.
You get the error about the missing CORS permissions because you are trying to access one origin from the other.
There are several ways you can resolve this.
* Don't use multiple origins in the first place. Pick one of `example.com` and `www.example.com` to be canonical. Configure your HTTP server to issue 301 redirects from the non-canonical one to the canonical one.
* Use relative URLs. Your absolute URL means that when you are on the wrong origin, it still tries to access the other one. Using a relative URL will keep the request going to the same origin as the page.
* Configure your server to grant permission to the other origin with CORS headers.
I recommend the first of those options.
Upvotes: 4 [selected_answer] |
2018/03/19 | 1,308 | 4,802 | <issue_start>username_0: I'm facing a strange problem in my automated tests written using Protractor. We need to test a bunch of API endpoints that return JSON over HTTP, as opposed to actual websites so instead of relying on Protractor, my team decided to use [Chakram](http://dareid.github.io/chakram/jsdoc/index.html).
I have a page object responsible for accessing the API:
```
const qs = require('querystring')
const chakram = require('chakram');
function MyApi() {
const domain = // read from a configuration file
this.readImportantBusinessData = (queryParams) => {
const serviceUrl = `${domain}/services/seriousBusiness.json`;
const queryString = qs.stringify(queryParams);
const fullUrl = `${serviceUrl}?${queryString}`;
return chakram.get(fullUrl).then((response) => {
return response;
});
};
};
module.exports = new MyApi();
```
then, in one of my specs, I call the `readImportantBusinessData` function to check if it returns the expected data.
```
return MyApi.readImportantBusinessData(validParameters).then((response) => {
chakramExpect(response).to.have.status(HTTP_200_OK);
chakramExpect(response).to.have.json({
"foo" : "bar"
});
});
```
Depending on the enviornment where I run this code, the test passes or fails with an error message that basically means that no response has been received.
```
Failed: Cannot read property 'statusCode' of undefined
```
I can confirm that the server I'm hitting is running and I can get a correct response when using a web browser.
The rquest made in my tests succeeds when I use a shared server hosted in AWS and fails when I use a local server running in VirtualBox.
Why could Chakram not recieve a response at all?<issue_comment>username_1: The root cause
--------------
The calls to `expect` just showed `undefined` but I managed to log the whole response object, as returned by `chakram.get`
```
{ error: { Error: self signed certificate
at TLSSocket. (\_tls\_wrap.js:1103:38)
at emitNone (events.js:106:13)
at TLSSocket.emit (events.js:208:7)
at TLSSocket.finishInit (\_tls\_wrap.js:637:8)
at TLSWrap.ssl.onhandshakedone (\_tls\_wrap.js:467:38) code: 'DEPTH\_ZERO\_SELF\_SIGNED\_CERT' },
response: undefined,
body: undefined,
jar:
RequestJar {
jar: CookieJar { enableLooseMode: true, store: { idx: {} } }
},
url: 'https://www.example.com/myService.json?foo=bar',
responseTime: 29.524212
}
```
This means Chakram had an issue with the self-signed certificate I was using for my local dev environment. The other servers are hosted in the cloud and have their certificates set up properly.
A workaround
------------
A quick Google search returned a lot of suggestions to modify a global parameter that drives this behaviour by setting:
```
process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
```
However, this affects the whole node process, not just my test. These are just tests that I'm running locally and not something that has to do with actual user data. Still, if I am to make the security of these calls more lax, I need this to limit the scope of such a change as much as possible.
Thankfully, [chakram.get](http://dareid.github.io/chakram/jsdoc/module-chakram.html#.get) uses the [request](https://github.com/request/request#requestoptions-callback) library which makes it possible to customize requests quite heavily.
`chakram.get` allows me to pass:
>
> `params` Object optional additional request options, see the popular [request library](https://github.com/request/request#requestoptions-callback) for options
>
>
>
These [options](https://github.com/request/request#requestoptions-callback), in turn allow me to specify:
>
> `agentOptions` - and pass its options. Note: for HTTPS see [tls API doc for TLS/SSL options](http://nodejs.org/api/tls.html#tls_tls_connect_options_callback) and the documentation above.
>
>
>
Finally, in the `agentOptions`, one can pass a `rejectUnauthorized` value that allows the certificate error to be ignored *for the single request being made*.
Therefore, in my page object, I could use:
```
return chakram.get(fullUrl, {
agentOptions : {
//Hack to allow requests to the local env with a self-signed cert
rejectUnauthorized : false
}
}).then((response) => {
return response;
});
```
This allows the test to succeed despite using a self-signed certificate.
The solution
------------
The solution is to provide a valid certificate for every environment and domain in which case the problem does not exist in the first place.
Upvotes: 2 [selected_answer]<issue_comment>username_2: This is because its asynchronous and ur function is getting executed without even completing your chakram request.
wait for request completion to get response.
Upvotes: -1 |
2018/03/19 | 719 | 2,131 | <issue_start>username_0: Hey i'm trying to center my images when someone is using an ipad basically below 780px but i am not able to get them to center no matter what i try? My menu and navigation bar are all centered just these images won't
[This is on normal browser PC](https://i.stack.imgur.com/GWGKz.jpg)
[This is the way it looks on tablet but i want to center it.](https://i.stack.imgur.com/P6IhT.png)
My code here
```
### Current News



```
CSS here
```
@media screen and (max-width:979px){
/*Global */
.container {
width: 95%;
margin: auto;
overflow: hidden;
padding-left: 15px;
padding-right: 15px;
}
.box img{
width: 300px;
height: 300px;
margin: auto;
overflow: hidden;
padding-left: 15px;
padding-right: 15px;
}
.box {
padding-bottom: 15px;
margin: auto;
overflow: hidden;
padding-left: 15px;
padding-right: 15px;
}
}
```<issue_comment>username_1: you can try:
{
```
display:flex;
justify-content:center;
```
}
Upvotes: 3 [selected_answer]<issue_comment>username_2: You can use [flexboxes](https://caniuse.com/#search=flex).
```
.box {
display: flex;
justify-content: center;
justify-items: center;
}
```
<https://developer.mozilla.org/en-US/docs/Learn/CSS/CSS_layout/Flexbox>
Upvotes: 0 <issue_comment>username_3: You should restructure your HTML by adding a container around the boxes:
```
```
Use flexbox for the container and give the boxes equal space in the screen with the `flex` property:
```
/* Only for demo purposes */
body, html {
box-sizing: border-box;
width: 100vw;
max-width: 100%;
overflow-x: hidden;
}
/* Main part: flexbox is added to the container box and the flex property allots them equal space with a margin of 10px as well */
.box-container {
width: 100vw;
display: flex;
}
.box {
flex: 1 0 0;
width: 120px;
height: 120px;
background-color: red;
margin-right: 10px;
}
```
Here is a link to the fiddle: [jsfiddle](https://jsfiddle.net/mpp7ah8m/7/)
Upvotes: 0 |
2018/03/19 | 566 | 2,088 | <issue_start>username_0: I have a problem when i want to get subcollections.
Can anybody help me, please ?
**firestore structure :**
```
questions(collection) -> curretUser.id(doc) -> questions(collection) -> questionIDautoCreated(doc)-> {title: "", description: "" }
```
**And i try to get data:**
```
return (dispatch) => {
firebase.firestore().collection('questions').doc(currentUser.uid)
.collection('questions').get()
.then((documentSnapshot) => {
const value = documentSnapshot.data();
console.log('Value Succeed : ');
console.log(value);
});
};
```
**Error :**
***Possible Unhandled Promise Rejection (id:0)***
**Type Error: documentSnapshot.data is not a function**
Thank You<issue_comment>username_1: Because collection is not a `DocumentSnapshot`, its a `QuerySnapshot`. Collection contains a list of data, it is not an actual document.
If you look in the firestore docs [here](https://firebase.google.com/docs/firestore/query-data/get-data). You can see when querying for collection, you should:
```
querySnapshot.forEach(function(doc) {
console.log(doc.id, " => ", doc.data());
});
```
The exception speaks for it self, the object you receive is not the one you expect.
```
return (dispatch) => {
firebase.firestore().collection('questions').doc(currentUser.uid)
.collection('questions').get()
.then((querySnapshot) => {
querySnapshot.forEach((doc) => {
console.log(doc.id, " => ", doc.data());
});
});
};
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: You can get subcollections like this,
Collections returns docs array, you must access docs data first.
**Quick Example**
```
firebase.firestore().collection('...').get().then(s => console.log(s.docs))
```
**Your solution**
```
return (dispatch) => {
firebase.firestore().collection(`questions/${currentUser.id}/questions`)
.get()
.then(questionSnapshot => questionSnapshot.docs)
.then(questions => {
questions.forEach(question => {
console.log(question)
})
})
}
```
Upvotes: 2 |
2018/03/19 | 574 | 2,153 | <issue_start>username_0: I'm creating a fitness app in Xcode where different activities are worth different points and the user has a total points on the homepage.
I am trying to convert the UILabel (which I have specified the points for each challenge) to an Integer so I can calculate the users total points when they have chosen that challenge.
I believe that I need to do this using Swift and have connected the UILabel to an outlet and given the calculating button an action, however I cannot figure out how to get an Int Value from the UILabel in order to do the calculation.
Please can anyone help with how to do this, or if you can think of a better way of doing so.
Thanks in advance
I've got this, no errors but nothing happens when button is pressed. I'm aiming to add the new points to the current points but trying to get this part working first.
>
> @IBAction func Calculate(\_ sender: Any) {
>
>
>
```
if let NewPointsText = NewPoints.text,
let NewPointsValue = Int(NewPointsText){
print(NewPointsValue)
} else{
print("Not Worked")
}
if let CurrentPointsText = CurrentPoints.text,
let CurrentPointsValue = Int(CurrentPointsText){
print(CurrentPointsValue)
}else{
print("Current Points Not Worked")
}
}
```
}<issue_comment>username_1: You need to first get the `text` from `UILabel`, and the convert it to `Int` value using the `initializer`.
```
if let text = self.label.text, let value = Int(text) {
//Write your code here
}
```
The `initializer` returns `nil` if the `string` cannot be converted into an `Int` value and `non-nil Int value` otherwise, i.e.
1. `Int("hello")` returns `nil`
2. `Int("10")` returns `10`.
Upvotes: 2 <issue_comment>username_2: Using `if let` you can easily try to extract the value:
```
@IBOutlet var label: UILabel!
@IBAction func calculateStuff(sender: UIButton) {
// do stuff
if let labelText = label.text,
let intValue = Int(labelText) {
// use intValue as you want
} else {
// if label did not contain an integer, you can react here
}
}
```
Upvotes: 0 |
2018/03/19 | 436 | 1,528 | <issue_start>username_0: I am trying to parse github api for organisations for this link
[first link](https://api.github.com/orgs/mozilla/repos)
I collected all commit\_url from this link and then I need to save data from each commit link for further cleaning.
e.g I have two commit links as
[commit\_link1](https://api.github.com/repos/mozilla/tuxedo/commits) and [commit\_link2](https://api.github.com/repos/mozilla/zamboni/commits)
As data in both links is again JSON object I tried saving data in JSON file with apend mode but when I open the file to get data I got keyerror: extra data
Any idea how should I save the data in single file as CSV option don't look reasonable.<issue_comment>username_1: You need to first get the `text` from `UILabel`, and the convert it to `Int` value using the `initializer`.
```
if let text = self.label.text, let value = Int(text) {
//Write your code here
}
```
The `initializer` returns `nil` if the `string` cannot be converted into an `Int` value and `non-nil Int value` otherwise, i.e.
1. `Int("hello")` returns `nil`
2. `Int("10")` returns `10`.
Upvotes: 2 <issue_comment>username_2: Using `if let` you can easily try to extract the value:
```
@IBOutlet var label: UILabel!
@IBAction func calculateStuff(sender: UIButton) {
// do stuff
if let labelText = label.text,
let intValue = Int(labelText) {
// use intValue as you want
} else {
// if label did not contain an integer, you can react here
}
}
```
Upvotes: 0 |
2018/03/19 | 1,032 | 3,706 | <issue_start>username_0: few hours I try to know why sometimes my removechild don't work. After reading the forum I see some issue about the fact my removechild array reduce is number each time... But I don't know how to fix this issue... Do you have any idea?
EDIT: I justed updated the snippets
For replicate the issue I invite you to add 4 new div and delete the third one and the try to delete the others... One of them will cause some troubles
```js
function newText() {
var text = prompt("Merci d'entrer une tache");
if (text != "") {
addElement(text);
}
}
function deletediv(id) {
var parent = document.getElementById('ft_list');
parent.removeChild(parent.childNodes[id]);
}
function addElement(text) {
var id = document.getElementById('ft_list').children.length
var ref = document.getElementById(id);
if (id == "")
id = 1;
else
id++;
var newDiv = document.createElement('div');
newDiv.setAttribute('class', "line");
newDiv.setAttribute('id', id);
newDiv.setAttribute('onclick', 'deletediv(this.id);');
var newContent = document.createTextNode(text);
newDiv.appendChild(newContent);
document.getElementById("ft_list").insertBefore(newDiv, ref);
}
```
```css
#ft_list {
border: 1px dashed lightgrey;
min-height: 30vh;
}
.line {
background: lightgrey;
padding: 5px;
margin: 5px
}
input {
background: lightgrey;
width: 150px;
height: 50px;
}
```
```html
```<issue_comment>username_1: You are accessing the element as the `index` of parent's `childNodes` but if you *delete a record and then add again*, it won't skip the added records counter value.
Instead of passing the `id`, pass the element itself
```
newDiv.setAttribute('onclick', 'deletediv(this);');
```
and change the method as
```
function deletediv(el) {
el.parentNode.removeChild(el);
}
```
**Demo**
```js
function newText() {
var text = prompt("Merci d'entrer une tache");
if (text != "") {
addElement(text);
}
}
function deletediv(el) {
el.parentNode.removeChild(el);
}
function addElement(text) {
var id = document.getElementById('ft_list').children.length
var ref = document.getElementById(id);
if (id == "")
id = 1;
else
id++;
var newDiv = document.createElement('div');
newDiv.setAttribute('class', "line");
newDiv.setAttribute('id', id);
newDiv.setAttribute('onclick', 'deletediv(this);');
var newContent = document.createTextNode(text);
newDiv.appendChild(newContent);
document.getElementById("ft_list").insertBefore(newDiv, ref);
}
```
```css
#ft_list {
border: 1px dashed lightgrey;
min-height: 30vh;
}
.line {
background: lightgrey;
padding: 5px;
margin: 5px
}
input {
background: lightgrey;
width: 150px;
height: 50px;
}
```
```html
```
Upvotes: 1 [selected_answer]<issue_comment>username_2: update you function
```
function deletediv(t) {
t.parentElement.removeChild(t);
}
function addElement(text) {
var id = document.getElementById('ft_list').children.length
var ref = document.getElementById(id);
if (id == "")
id = 1;
else
id++;
var newDiv = document.createElement('div');
newDiv.setAttribute('class', "line");
newDiv.setAttribute('id', id);
newDiv.addEventListener('click', function() {
deletediv(newDiv)
});
var newContent = document.createTextNode(text);
newDiv.appendChild(newContent);
document.getElementById("ft_list").insertBefore(newDiv, ref);
}
```
Upvotes: 1 |
2018/03/19 | 311 | 1,121 | <issue_start>username_0: Does anyone know why the Datastore Admin API `export` and `import` operations are not available with APIs explorer?
Just visit the [API page](https://cloud.google.com/datastore/docs/reference/admin/rest/v1/projects/export).
Meanwhile the API for getting long-running operations [is available](https://cloud.google.com/datastore/docs/reference/admin/rest/v1/projects.operations/get).
[](https://i.stack.imgur.com/2jKLG.png)<issue_comment>username_1: We've had a delay pushing the configuration changes to make it appear in the explorer. [Working on it!]
Upvotes: 3 <issue_comment>username_2: Most likely this is because the recently added export/import functionality is still being polished.
The `!` badges with a `New!` popup when hovering over are still visible in the [Exporting and Importing Entities](https://cloud.google.com/datastore/docs/export-import-entities) left-side navigation bar:
[](https://i.stack.imgur.com/C8t7i.png)
Upvotes: 1 |
2018/03/19 | 382 | 1,356 | <issue_start>username_0: I have an sp which is,
```
-- States
select statusid,statusdesc,statustype,isfinal,seq, tstamp from issuestatuslut order by seq
-- PRE states
select a.statusid,a.otherstate,a.statetype,b.statusdesc, a.tstamp
from issuestatetransitionlut a, issuestatuslut b
where a.statetype=0 and a.otherstate=b.statusid
-- POST states
select a.statusid,a.otherstate,a.statetype,b.statusdesc, a.tstamp
from issuestatetransitionlut a, issuestatuslut b
where a.statetype=1 and a.otherstate=b.statusid
```
Now as you can see all 3 returns results with identical column names and for some reason I cant even change a single word in sp.
Now how can I fetch all three select statement in 3 different reader function or something like?<issue_comment>username_1: We've had a delay pushing the configuration changes to make it appear in the explorer. [Working on it!]
Upvotes: 3 <issue_comment>username_2: Most likely this is because the recently added export/import functionality is still being polished.
The `!` badges with a `New!` popup when hovering over are still visible in the [Exporting and Importing Entities](https://cloud.google.com/datastore/docs/export-import-entities) left-side navigation bar:
[](https://i.stack.imgur.com/C8t7i.png)
Upvotes: 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.