date
stringlengths 10
10
| nb_tokens
int64 60
629k
| text_size
int64 234
1.02M
| content
stringlengths 234
1.02M
|
---|---|---|---|
2018/03/14
| 444 | 1,770 |
<issue_start>username_0: I followed this tutorial to enable gitlab as a repository of docker images, then I executed docker push of the image and it is loaded in gitlab correctly.
<http://clusterfrak.com/sysops/app_installs/gitlab_container_registry/>
If I go to the Project registry option in Gitlab, the image appears there, but the problem occurs when I restart the coupler engine or the container where gitlab is located and when I re-enter the option to register the project in gitlab, all the images they are eliminated
That could be happening.<issue_comment>username_1: >
> the problem occurs when I restart the coupler engine or the container where gitlab is located and when I re-enter the option to register the project in gitlab, all the images they are eliminated
>
>
>
That means the path where GitLab is storing docker images is part of the container, and is not persistent, ie is not [a volume or a bind mount](https://docs.docker.com/storage/bind-mounts/).
From the tutorial, you have the configuration:
```
################
# Registry #
################
gitlab_rails['registry_enabled'] = true
gitlab_rails['gitlab_default_projects_features_container_registry'] = false
gitlab_rails['registry_path'] = "/mnt/docker_registry"
gitlab_rails['registry_api_url'] = "https://localhost:5000"
```
You need to make sure, when starting the GitLab container, that it mounts a volume or host local path (which is persistent) to the container internal path `/mnt/docker_registry`.
*Then*, restarting GitLab would allow you to find back all the images you might have stored in the GitLAb-managed Docker registry.
Upvotes: 1 <issue_comment>username_2: I have created the volume where the images are and now it works.
thank you very much
Upvotes: 0
|
2018/03/14
| 1,475 | 5,743 |
<issue_start>username_0: When I run `php artisan migrate`, I am getting an error like this:
```
In 2017_12_26_045926_create_table_articles.php line 41:
Parse error: syntax error, unexpected 'public' (T_PUBLIC), expecting ',' or
')'
```
This is my **articles tables**:
```
public function up()
{
Schema::create('articles', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id');
$table->integer('category_id');
$table->string('title');
$table->text('content');
$table->boolean('is_show')->default(false);
$table->boolean('is_active')->default(false);
$table->integer('page_showing')->default(0);
$table->string('header_pic');
$table->softDeletes();
$table->timestamps();
Schema::table('articles', function($table){
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('articles');
}
}
```
I am adding foreign key for articles and comments, but the articles tables when migrate is giving errors like above. What's wrong?<issue_comment>username_1: You're missing the closure on `Schema::create`
```
Schema::create('articles', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id');
$table->integer('category_id');
$table->string('title');
$table->text('content');
$table->boolean('is_show')->default(false);
$table->boolean('is_active')->default(false);
$table->integer('page_showing')->default(0);
$table->string('header_pic');
$table->softDeletes();
$table->timestamps();
});
```
Upvotes: 0 <issue_comment>username_2: You dont need to alter table when you are creating the table to put foreigns.
```
Schema::create('articles', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned(); // Or $table->unsignedInteger('user_id');
$table->integer('category_id')->unsigned();
$table->string('title');
$table->text('content');
$table->boolean('is_show')->default(0);
$table->boolean('is_active')->default(0);
$table->integer('page_showing')->default(0);
$table->string('header_pic');
$table->softDeletes();
$table->timestamps();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade');
});
```
However, you can do that correctly with this code
```
Schema::create('articles', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->integer('category_id')->unsigned();
$table->string('title');
$table->text('content');
$table->boolean('is_show')->default(0);
$table->boolean('is_active')->default(0);
$table->integer('page_showing')->default(0);
$table->string('header_pic');
$table->softDeletes();
$table->timestamps();
});
Schema::table('articles', function($table){
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade');
});
```
Upvotes: 1 [selected_answer]<issue_comment>username_3: The error is because you are using the schema class again which is missing the closing tag ")};" and there is no need to use Schema class again you can use the same object to add a foreign key to the table.
Try the below code :
```
public function up()
{
Schema::create('articles', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id');
$table->integer('category_id');
$table->string('title');
$table->text('content');
$table->boolean('is_show')->default(false);
$table->boolean('is_active')->default(false);
$table->integer('page_showing')->default(0);
$table->string('header_pic');
$table->softDeletes();
$table->timestamps();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('articles');
}
```
OR
```
public function up()
{
Schema::create('articles', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id');
$table->integer('category_id');
$table->string('title');
$table->text('content');
$table->boolean('is_show')->default(false);
$table->boolean('is_active')->default(false);
$table->integer('page_showing')->default(0);
$table->string('header_pic');
$table->softDeletes();
$table->timestamps();
Schema::table('articles', function($table){
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade');
}); //closing Schema class tag
}); //closing Schema class tag
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('articles');
}
```
Upvotes: 1
|
2018/03/14
| 4,472 | 17,572 |
<issue_start>username_0: **UPDATE**: The latest version of Intellij IDEA [implements](https://www.jetbrains.com/help/idea/tutorial-java-debugging-deep-dive.html#async_stacktraces) exactly what I'm looking for. The question is how to implement this outside of the IDE (so I can to dump async stack traces to log files), ideally without the use of an instrumenting agent.
---
Ever since I converted my application from a synchronous to asynchronous model I am having problems debugging failures.
When I use synchronous APIs, I always find my classes in exception stacktraces so I know where to begin looking if something goes wrong. With asynchronous APIs, I am getting stacktraces that do not reference my classes nor indicate what request triggered the failure.
I'll give you a concrete example, but I'm interested in a general solution to this kind of problem.
Concrete example
----------------
I make an HTTP request using [Jersey](https://jersey.github.io/):
```
new Client().target("http://test.com/").request().rx().get(JsonNode.class);
```
where `rx()` indicates that the request should take place asynchronously, returning a `CompletionStage` instead of a `JsonNode` directly. If this call fails, I get this stacktrace:
```
javax.ws.rs.ForbiddenException: HTTP 403 Authentication Failed
at org.glassfish.jersey.client.JerseyInvocation.convertToException(JerseyInvocation.java:1083)
at org.glassfish.jersey.client.JerseyInvocation.translate(JerseyInvocation.java:883)
at org.glassfish.jersey.client.JerseyInvocation.lambda$invoke$1(JerseyInvocation.java:767)
at org.glassfish.jersey.internal.Errors.process(Errors.java:316)
at org.glassfish.jersey.internal.Errors.process(Errors.java:298)
at org.glassfish.jersey.internal.Errors.process(Errors.java:229)
at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:414)
at org.glassfish.jersey.client.JerseyInvocation.invoke(JerseyInvocation.java:765)
at org.glassfish.jersey.client.JerseyInvocation$Builder.method(JerseyInvocation.java:456)
at org.glassfish.jersey.client.JerseyCompletionStageRxInvoker.lambda$method$1(JerseyCompletionStageRxInvoker.java:70)
at java.util.concurrent.CompletableFuture$AsyncSupply.run(CompletableFuture.java:1590)
```
Notice:
* The stacktrace does not reference user code.
* The exception message does not contain contextual information about the HTTP request that triggered the error (HTTP method, URI, etc).
As a result, I have no way of tracking the exception back to its source.
Why this is happening
---------------------
If you dig under the hood, you will discover that [Jersey is invoking](https://github.com/jersey/jersey/blob/12e5d8bdf22bcd2676a1032ed69473cf2bbc48c7/core-client/src/main/java/org/glassfish/jersey/client/JerseyCompletionStageRxInvoker.java#L69):
```
CompletableFuture.supplyAsync(() -> getSyncInvoker().method(name, entity, responseType))
```
for `rx()` invocations. Because the supplier is constructed by Jersey, there is no reference back to user code.
What I've tried
---------------
[I tried filing a bug report](https://github.com/eclipse/jetty.project/issues/2310#issue-303972082) against Jetty for an unrelated async example, and was subsequently turned down on security grounds.
Instead, I've been adding contextual information as follows:
```
makeHttpRequest().exceptionally(e ->
{
throw new RuntimeException(e);
});
```
Meaning, I am manually adding `exceptionally()` after every single HTTP request in my code. Any exceptions thrown by Jersey are wrapped in a secondary exception that references my code. The resulting stacktrace looks like this:
```
java.lang.RuntimeException: javax.ws.rs.ForbiddenException: HTTP 403 Authentication Failed
at my.user.code.Testcase.lambda$null$1(Testcase.java:25)
at java.util.concurrent.CompletableFuture.uniExceptionally(CompletableFuture.java:870)
... 6 common frames omitted
Caused by: javax.ws.rs.ForbiddenException: HTTP 403 Authentication Failed
at org.glassfish.jersey.client.JerseyInvocation.convertToException(JerseyInvocation.java:1083)
at org.glassfish.jersey.client.JerseyInvocation.translate(JerseyInvocation.java:883)
at org.glassfish.jersey.client.JerseyInvocation.lambda$invoke$1(JerseyInvocation.java:767)
at org.glassfish.jersey.internal.Errors.process(Errors.java:316)
at org.glassfish.jersey.internal.Errors.process(Errors.java:298)
at org.glassfish.jersey.internal.Errors.process(Errors.java:229)
at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:414)
at org.glassfish.jersey.client.JerseyInvocation.invoke(JerseyInvocation.java:765)
at org.glassfish.jersey.client.JerseyInvocation$Builder.method(JerseyInvocation.java:456)
at org.glassfish.jersey.client.JerseyCompletionStageRxInvoker.lambda$method$1(JerseyCompletionStageRxInvoker.java:70)
at java.util.concurrent.CompletableFuture$AsyncSupply.run(CompletableFuture.java:1590)
... 3 common frames omitted
```
I don't like this approach because it is error prone and decreases the readability of the code. If I mistakenly omit this for some HTTP request I will end up with a vague stacktrace and spend a lot time tracking it down.
Further, if I want to hide this trick behind a utility class then I have to instantiate an exception outside of a `CompletionStage`; otherwise, the utility class will show up in the stacktrace instead of the actual call site. Instantiating an exception outside of a `CompletionStage` is extremely expensive because this code runs even if no exception is ever thrown by the async call.
My question
-----------
Is there a robust, easy-to-maintain approach to add contextual information to asynchronous calls?
Alternatively, is there an efficient approach to track stacktraces back to their source without this contextual information?<issue_comment>username_1: Seeing as this question has not received any answers in almost a month, I'm going to post the best solution I've found to date:
**DebugCompletableFuture.java**:
```
/**
* A {@link CompletableFuture} that eases debugging.
*
* @param the type of value returned by the future
\*/
public final class DebugCompletableFuture extends CompletableFuture
{
private static RunMode RUN\_MODE = RunMode.DEBUG;
private static final Set CLASS\_PREFIXES\_TO\_REMOVE = ImmutableSet.of(DebugCompletableFuture.class.getName(),
CompletableFuture.class.getName(), ThreadPoolExecutor.class.getName());
private static final Set> EXCEPTIONS\_TO\_UNWRAP = ImmutableSet.of(AsynchronousException.class,
CompletionException.class, ExecutionException.class);
private final CompletableFuture delegate;
private final AsynchronousException asyncStacktrace;
/\*\*
\* @param delegate the stage to delegate to
\* @throws NullPointerException if any of the arguments are null
\*/
private DebugCompletableFuture(CompletableFuture delegate)
{
requireThat("delegate", delegate).isNotNull();
this.delegate = delegate;
this.asyncStacktrace = new AsynchronousException();
delegate.whenComplete((value, exception) ->
{
if (exception == null)
{
super.complete(value);
return;
}
exception = Exceptions.unwrap(exception, EXCEPTIONS\_TO\_UNWRAP);
asyncStacktrace.initCause(exception);
filterStacktrace(asyncStacktrace, element ->
{
String className = element.getClassName();
for (String prefix : CLASS\_PREFIXES\_TO\_REMOVE)
if (className.startsWith(prefix))
return true;
return false;
});
Set newMethods = getMethodsInStacktrace(asyncStacktrace);
if (!newMethods.isEmpty())
{
Set oldMethods = getMethodsInStacktrace(exception);
newMethods.removeAll(oldMethods);
if (!newMethods.isEmpty())
{
// The async stacktrace introduces something new
super.completeExceptionally(asyncStacktrace);
return;
}
}
super.completeExceptionally(exception);
});
}
/\*\*
\* @param exception an exception
\* @return the methods referenced by the stacktrace
\* @throws NullPointerException if {@code exception} is null
\*/
private Set getMethodsInStacktrace(Throwable exception)
{
requireThat("exception", exception).isNotNull();
Set result = new HashSet<>();
for (StackTraceElement element : exception.getStackTrace())
result.add(element.getClassName() + "." + element.getMethodName());
for (Throwable suppressed : exception.getSuppressed())
result.addAll(getMethodsInStacktrace(suppressed));
return result;
}
/\*\*
\* @param the type returned by the delegate
\* @param delegate the stage to delegate to
\* @return if {@code RUN\_MODE == DEBUG} returns an instance that wraps {@code delegate}; otherwise, returns {@code delegate}
\* unchanged
\* @throws NullPointerException if any of the arguments are null
\*/
public static CompletableFuture wrap(CompletableFuture delegate)
{
if (RUN\_MODE != RunMode.DEBUG)
return delegate;
return new DebugCompletableFuture<>(delegate);
}
/\*\*
\* Removes stack trace elements that match a filter. The exception and its descendants are processed recursively.
\*
\* This method can be used to remove lines that hold little value for the end user (such as the implementation of utility functions).
\*
\* @param exception the exception to process
\* @param elementFilter returns true if the current stack trace element should be removed
\*/
private void filterStacktrace(Throwable exception, Predicate elementFilter)
{
Throwable cause = exception.getCause();
if (cause != null)
filterStacktrace(cause, elementFilter);
for (Throwable suppressed : exception.getSuppressed())
filterStacktrace(suppressed, elementFilter);
StackTraceElement[] elements = exception.getStackTrace();
List keep = new ArrayList<>(elements.length);
for (StackTraceElement element : elements)
{
if (!elementFilter.test(element))
keep.add(element);
}
exception.setStackTrace(keep.toArray(new StackTraceElement[0]));
}
@Override
public CompletableFuture thenApply(Function super T, ? extends U fn)
{
return wrap(super.thenApply(fn));
}
@Override
public CompletableFuture thenApplyAsync(Function super T, ? extends U fn)
{
return wrap(super.thenApplyAsync(fn));
}
@Override
public CompletableFuture thenApplyAsync(Function super T, ? extends U fn, Executor executor)
{
return wrap(super.thenApplyAsync(fn, executor));
}
@Override
public CompletableFuture thenAccept(Consumer super T action)
{
return wrap(super.thenAccept(action));
}
@Override
public CompletableFuture thenAcceptAsync(Consumer super T action)
{
return wrap(super.thenAcceptAsync(action));
}
@Override
public CompletableFuture thenAcceptAsync(Consumer super T action, Executor executor)
{
return wrap(super.thenAcceptAsync(action, executor));
}
@Override
public CompletableFuture thenRun(Runnable action)
{
return wrap(super.thenRun(action));
}
@Override
public CompletableFuture thenRunAsync(Runnable action)
{
return wrap(super.thenRunAsync(action));
}
@Override
public CompletableFuture thenRunAsync(Runnable action, Executor executor)
{
return wrap(super.thenRunAsync(action, executor));
}
@Override
public CompletableFuture thenCombine(CompletionStage extends U other,
BiFunction super T, ? super U, ? extends V fn)
{
return wrap(super.thenCombine(other, fn));
}
@Override
public CompletableFuture thenCombineAsync(CompletionStage extends U other,
BiFunction super T, ? super U, ? extends V fn)
{
return wrap(super.thenCombineAsync(other, fn));
}
@Override
public CompletableFuture thenCombineAsync(CompletionStage extends U other,
BiFunction super T, ? super U, ? extends V fn,
Executor executor)
{
return wrap(super.thenCombineAsync(other, fn, executor));
}
@Override
public CompletableFuture thenAcceptBoth(CompletionStage extends U other,
BiConsumer super T, ? super U action)
{
return wrap(super.thenAcceptBoth(other, action));
}
@Override
public CompletableFuture thenAcceptBothAsync(CompletionStage extends U other,
BiConsumer super T, ? super U action)
{
return wrap(super.thenAcceptBothAsync(other, action));
}
@Override
public CompletableFuture thenAcceptBothAsync(CompletionStage extends U other,
BiConsumer super T, ? super U action,
Executor executor)
{
return wrap(super.thenAcceptBothAsync(other, action, executor));
}
@Override
public CompletableFuture runAfterBoth(CompletionStage other, Runnable action)
{
return wrap(super.runAfterBoth(other, action));
}
@Override
public CompletableFuture runAfterBothAsync(CompletionStage other, Runnable action)
{
return wrap(super.runAfterBothAsync(other, action));
}
@Override
public CompletableFuture runAfterBothAsync(CompletionStage other, Runnable action, Executor executor)
{
return wrap(super.runAfterBothAsync(other, action, executor));
}
@Override
public CompletableFuture applyToEither(CompletionStage extends T other, Function super T, U fn)
{
return wrap(super.applyToEither(other, fn));
}
@Override
public CompletableFuture applyToEitherAsync(CompletionStage extends T other, Function super T, U fn)
{
return wrap(super.applyToEitherAsync(other, fn));
}
@Override
public CompletableFuture applyToEitherAsync(CompletionStage extends T other, Function super T, U fn,
Executor executor)
{
return wrap(super.applyToEitherAsync(other, fn, executor));
}
@Override
public CompletableFuture acceptEither(CompletionStage extends T other, Consumer super T action)
{
return wrap(super.acceptEither(other, action));
}
@Override
public CompletableFuture acceptEitherAsync(CompletionStage extends T other, Consumer super T action)
{
return wrap(super.acceptEitherAsync(other, action));
}
@Override
public CompletableFuture acceptEitherAsync(CompletionStage extends T other, Consumer super T action,
Executor executor)
{
return wrap(super.acceptEitherAsync(other, action, executor));
}
@Override
public CompletableFuture runAfterEither(CompletionStage other, Runnable action)
{
return wrap(super.runAfterEither(other, action));
}
@Override
public CompletableFuture runAfterEitherAsync(CompletionStage other, Runnable action)
{
return wrap(super.runAfterEitherAsync(other, action));
}
@Override
public CompletableFuture runAfterEitherAsync(CompletionStage other, Runnable action, Executor executor)
{
return wrap(super.runAfterEitherAsync(other, action, executor));
}
@Override
public CompletableFuture thenCompose(Function super T, ? extends CompletionStage<U> fn)
{
return wrap(super.thenCompose(fn));
}
@Override
public CompletableFuture thenComposeAsync(Function super T, ? extends CompletionStage<U> fn)
{
return wrap(super.thenComposeAsync(fn));
}
@Override
public CompletableFuture thenComposeAsync(Function super T, ? extends CompletionStage<U> fn,
Executor executor)
{
return wrap(super.thenComposeAsync(fn, executor));
}
@Override
public CompletableFuture exceptionally(Function fn)
{
return wrap(super.exceptionally(fn));
}
@Override
public CompletableFuture whenComplete(BiConsumer super T, ? super Throwable action)
{
return wrap(super.whenComplete(action));
}
@Override
public CompletableFuture whenCompleteAsync(BiConsumer super T, ? super Throwable action)
{
return wrap(super.whenCompleteAsync(action));
}
@Override
public CompletableFuture whenCompleteAsync(BiConsumer super T, ? super Throwable action,
Executor executor)
{
return wrap(super.whenCompleteAsync(action, executor));
}
@Override
public CompletableFuture handle(BiFunction super T, Throwable, ? extends U fn)
{
return wrap(super.handle(fn));
}
@Override
public CompletableFuture handleAsync(BiFunction super T, Throwable, ? extends U fn)
{
return wrap(super.handleAsync(fn));
}
@Override
public CompletableFuture handleAsync(BiFunction super T, Throwable, ? extends U fn,
Executor executor)
{
return wrap(super.handleAsync(fn, executor));
}
@Override
public boolean complete(T value)
{
return delegate.complete(value);
}
@Override
public boolean completeExceptionally(Throwable ex)
{
return delegate.completeExceptionally(ex);
}
}
```
**RunMode.java**:
```
/**
* Operational modes.
*/
public enum RunMode
{
/**
* Optimized for debugging problems (extra runtime checks, logging of the program state).
*/
DEBUG,
/**
* Optimized for maximum performance.
*/
RELEASE
}
```
**AsynchronousException.java**
```
/**
* Thrown when an asynchronous operation fails. The stacktrace indicates who triggered the operation.
*/
public final class AsynchronousException extends RuntimeException
{
private static final long serialVersionUID = 0L;
public AsynchronousException()
{
}
}
```
Usage:
```
DebugCompletableFuture.wrap(CompletableFuture.supplyAsync(this::expensiveOperation));
```
Upside: you'll get relatively clean asynchronous stack traces.
Downside: Constructing a new `AsynchronousException` every time a future is created is extremely expensive. Specifically, if you're generating a lot of futures, this generates a lot of garbage on the heap and the GC overhead becomes noticeable.
I am still hopeful that someone will come up with a better-performing approach.
Upvotes: 4 [selected_answer]<issue_comment>username_2: This is probably due to the [JVM update](https://www.oracle.com/technetwork/java/javase/relnotes-139183.html#hotspot) when it finds that the stack is exhausted of emitting the same log so it starts to omit it.
And the solution is using `-XX:-OmitStackTraceInFastThrow` flag to prevent JVM from optimizing built-in exceptions stack trace.
Upvotes: 0
|
2018/03/14
| 3,894 | 16,402 |
<issue_start>username_0: I am using Eclipse for RCP and RAP Developers (Oxygen). Upon opening palette it is empty. Even though I have my code in edit mode in the source tab.
In the below image palette is empty
As Suggested added the code below.
On opening the Design tab, the palette is empty.
```
package com.jcg.rca.main;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CLabel;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
//import org.eclipse.wb.swt.SWTResourceManager;
public class MainWindow {
protected Shell shlLogin;
private Text userNameTxt;
private Text passwordTxt;
private String userName = null;
private String password = <PASSWORD>;
/**
* Launch the application.
*
* @param args
*/
public static void main(String[] args) {
try {
MainWindow window = new MainWindow();
window.open();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Open the window.
*/
public void open() {
Display display = Display.getDefault();
createContents();
shlLogin.open();
shlLogin.layout();
while (!shlLogin.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
}
/**
* Create contents of the window.
*/
protected void createContents() {
shlLogin = new Shell(SWT.CLOSE | SWT.TITLE | SWT.MIN);
shlLogin.setSize(450, 300);
shlLogin.setText("Login");
CLabel label = new CLabel(shlLogin, SWT.NONE);
//label.setImage(SWTResourceManager.getImage(MainWindow.class, "/com/jcg/rca/main/eclipse_logo.png"));
label.setBounds(176, 10, 106, 70);
label.setText("");
Label lblUsername = new Label(shlLogin, SWT.NONE);
lblUsername.setBounds(125, 115, 55, 15);
lblUsername.setText("Username");
Label lblPassword = new Label(shlLogin, SWT.NONE);
lblPassword.setBounds(125, 144, 55, 15);
lblPassword.setText("<PASSWORD>");
userNameTxt = new Text(shlLogin, SWT.BORDER);
userNameTxt.setBounds(206, 109, 173, 21);
passwordTxt = new Text(shlLogin, SWT.BORDER | SWT.PASSWORD);
passwordTxt.setBounds(206, 144, 173, 21);
Button btnLogin = new Button(shlLogin, SWT.NONE);
btnLogin.setBounds(206, 185, 75, 25);
btnLogin.setText("Login");
btnLogin.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event event) {
userName = userNameTxt.getText();
password = <PASSWORD>.getText();
if (userName == null || userName.isEmpty() || password == null || password.isEmpty()) {
String errorMsg = null;
MessageBox messageBox = new MessageBox(shlLogin, SWT.OK | SWT.ICON_ERROR);
messageBox.setText("Alert");
if (userName == null || userName.isEmpty()) {
errorMsg = "Please enter username";
} else if (password == null || password.isEmpty()) {
errorMsg = "Please enter password";
}
if (errorMsg != null) {
messageBox.setMessage(errorMsg);
messageBox.open();
}
} else {
MessageBox messageBox = new MessageBox(shlLogin, SWT.OK | SWT.ICON_WORKING);
messageBox.setText("Info");
messageBox.setMessage("Valid");
messageBox.open();
}
}
});
}}
```

.........................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................<issue_comment>username_1: Seeing as this question has not received any answers in almost a month, I'm going to post the best solution I've found to date:
**DebugCompletableFuture.java**:
```
/**
* A {@link CompletableFuture} that eases debugging.
*
* @param the type of value returned by the future
\*/
public final class DebugCompletableFuture extends CompletableFuture
{
private static RunMode RUN\_MODE = RunMode.DEBUG;
private static final Set CLASS\_PREFIXES\_TO\_REMOVE = ImmutableSet.of(DebugCompletableFuture.class.getName(),
CompletableFuture.class.getName(), ThreadPoolExecutor.class.getName());
private static final Set> EXCEPTIONS\_TO\_UNWRAP = ImmutableSet.of(AsynchronousException.class,
CompletionException.class, ExecutionException.class);
private final CompletableFuture delegate;
private final AsynchronousException asyncStacktrace;
/\*\*
\* @param delegate the stage to delegate to
\* @throws NullPointerException if any of the arguments are null
\*/
private DebugCompletableFuture(CompletableFuture delegate)
{
requireThat("delegate", delegate).isNotNull();
this.delegate = delegate;
this.asyncStacktrace = new AsynchronousException();
delegate.whenComplete((value, exception) ->
{
if (exception == null)
{
super.complete(value);
return;
}
exception = Exceptions.unwrap(exception, EXCEPTIONS\_TO\_UNWRAP);
asyncStacktrace.initCause(exception);
filterStacktrace(asyncStacktrace, element ->
{
String className = element.getClassName();
for (String prefix : CLASS\_PREFIXES\_TO\_REMOVE)
if (className.startsWith(prefix))
return true;
return false;
});
Set newMethods = getMethodsInStacktrace(asyncStacktrace);
if (!newMethods.isEmpty())
{
Set oldMethods = getMethodsInStacktrace(exception);
newMethods.removeAll(oldMethods);
if (!newMethods.isEmpty())
{
// The async stacktrace introduces something new
super.completeExceptionally(asyncStacktrace);
return;
}
}
super.completeExceptionally(exception);
});
}
/\*\*
\* @param exception an exception
\* @return the methods referenced by the stacktrace
\* @throws NullPointerException if {@code exception} is null
\*/
private Set getMethodsInStacktrace(Throwable exception)
{
requireThat("exception", exception).isNotNull();
Set result = new HashSet<>();
for (StackTraceElement element : exception.getStackTrace())
result.add(element.getClassName() + "." + element.getMethodName());
for (Throwable suppressed : exception.getSuppressed())
result.addAll(getMethodsInStacktrace(suppressed));
return result;
}
/\*\*
\* @param the type returned by the delegate
\* @param delegate the stage to delegate to
\* @return if {@code RUN\_MODE == DEBUG} returns an instance that wraps {@code delegate}; otherwise, returns {@code delegate}
\* unchanged
\* @throws NullPointerException if any of the arguments are null
\*/
public static CompletableFuture wrap(CompletableFuture delegate)
{
if (RUN\_MODE != RunMode.DEBUG)
return delegate;
return new DebugCompletableFuture<>(delegate);
}
/\*\*
\* Removes stack trace elements that match a filter. The exception and its descendants are processed recursively.
\*
\* This method can be used to remove lines that hold little value for the end user (such as the implementation of utility functions).
\*
\* @param exception the exception to process
\* @param elementFilter returns true if the current stack trace element should be removed
\*/
private void filterStacktrace(Throwable exception, Predicate elementFilter)
{
Throwable cause = exception.getCause();
if (cause != null)
filterStacktrace(cause, elementFilter);
for (Throwable suppressed : exception.getSuppressed())
filterStacktrace(suppressed, elementFilter);
StackTraceElement[] elements = exception.getStackTrace();
List keep = new ArrayList<>(elements.length);
for (StackTraceElement element : elements)
{
if (!elementFilter.test(element))
keep.add(element);
}
exception.setStackTrace(keep.toArray(new StackTraceElement[0]));
}
@Override
public CompletableFuture thenApply(Function super T, ? extends U fn)
{
return wrap(super.thenApply(fn));
}
@Override
public CompletableFuture thenApplyAsync(Function super T, ? extends U fn)
{
return wrap(super.thenApplyAsync(fn));
}
@Override
public CompletableFuture thenApplyAsync(Function super T, ? extends U fn, Executor executor)
{
return wrap(super.thenApplyAsync(fn, executor));
}
@Override
public CompletableFuture thenAccept(Consumer super T action)
{
return wrap(super.thenAccept(action));
}
@Override
public CompletableFuture thenAcceptAsync(Consumer super T action)
{
return wrap(super.thenAcceptAsync(action));
}
@Override
public CompletableFuture thenAcceptAsync(Consumer super T action, Executor executor)
{
return wrap(super.thenAcceptAsync(action, executor));
}
@Override
public CompletableFuture thenRun(Runnable action)
{
return wrap(super.thenRun(action));
}
@Override
public CompletableFuture thenRunAsync(Runnable action)
{
return wrap(super.thenRunAsync(action));
}
@Override
public CompletableFuture thenRunAsync(Runnable action, Executor executor)
{
return wrap(super.thenRunAsync(action, executor));
}
@Override
public CompletableFuture thenCombine(CompletionStage extends U other,
BiFunction super T, ? super U, ? extends V fn)
{
return wrap(super.thenCombine(other, fn));
}
@Override
public CompletableFuture thenCombineAsync(CompletionStage extends U other,
BiFunction super T, ? super U, ? extends V fn)
{
return wrap(super.thenCombineAsync(other, fn));
}
@Override
public CompletableFuture thenCombineAsync(CompletionStage extends U other,
BiFunction super T, ? super U, ? extends V fn,
Executor executor)
{
return wrap(super.thenCombineAsync(other, fn, executor));
}
@Override
public CompletableFuture thenAcceptBoth(CompletionStage extends U other,
BiConsumer super T, ? super U action)
{
return wrap(super.thenAcceptBoth(other, action));
}
@Override
public CompletableFuture thenAcceptBothAsync(CompletionStage extends U other,
BiConsumer super T, ? super U action)
{
return wrap(super.thenAcceptBothAsync(other, action));
}
@Override
public CompletableFuture thenAcceptBothAsync(CompletionStage extends U other,
BiConsumer super T, ? super U action,
Executor executor)
{
return wrap(super.thenAcceptBothAsync(other, action, executor));
}
@Override
public CompletableFuture runAfterBoth(CompletionStage other, Runnable action)
{
return wrap(super.runAfterBoth(other, action));
}
@Override
public CompletableFuture runAfterBothAsync(CompletionStage other, Runnable action)
{
return wrap(super.runAfterBothAsync(other, action));
}
@Override
public CompletableFuture runAfterBothAsync(CompletionStage other, Runnable action, Executor executor)
{
return wrap(super.runAfterBothAsync(other, action, executor));
}
@Override
public CompletableFuture applyToEither(CompletionStage extends T other, Function super T, U fn)
{
return wrap(super.applyToEither(other, fn));
}
@Override
public CompletableFuture applyToEitherAsync(CompletionStage extends T other, Function super T, U fn)
{
return wrap(super.applyToEitherAsync(other, fn));
}
@Override
public CompletableFuture applyToEitherAsync(CompletionStage extends T other, Function super T, U fn,
Executor executor)
{
return wrap(super.applyToEitherAsync(other, fn, executor));
}
@Override
public CompletableFuture acceptEither(CompletionStage extends T other, Consumer super T action)
{
return wrap(super.acceptEither(other, action));
}
@Override
public CompletableFuture acceptEitherAsync(CompletionStage extends T other, Consumer super T action)
{
return wrap(super.acceptEitherAsync(other, action));
}
@Override
public CompletableFuture acceptEitherAsync(CompletionStage extends T other, Consumer super T action,
Executor executor)
{
return wrap(super.acceptEitherAsync(other, action, executor));
}
@Override
public CompletableFuture runAfterEither(CompletionStage other, Runnable action)
{
return wrap(super.runAfterEither(other, action));
}
@Override
public CompletableFuture runAfterEitherAsync(CompletionStage other, Runnable action)
{
return wrap(super.runAfterEitherAsync(other, action));
}
@Override
public CompletableFuture runAfterEitherAsync(CompletionStage other, Runnable action, Executor executor)
{
return wrap(super.runAfterEitherAsync(other, action, executor));
}
@Override
public CompletableFuture thenCompose(Function super T, ? extends CompletionStage<U> fn)
{
return wrap(super.thenCompose(fn));
}
@Override
public CompletableFuture thenComposeAsync(Function super T, ? extends CompletionStage<U> fn)
{
return wrap(super.thenComposeAsync(fn));
}
@Override
public CompletableFuture thenComposeAsync(Function super T, ? extends CompletionStage<U> fn,
Executor executor)
{
return wrap(super.thenComposeAsync(fn, executor));
}
@Override
public CompletableFuture exceptionally(Function fn)
{
return wrap(super.exceptionally(fn));
}
@Override
public CompletableFuture whenComplete(BiConsumer super T, ? super Throwable action)
{
return wrap(super.whenComplete(action));
}
@Override
public CompletableFuture whenCompleteAsync(BiConsumer super T, ? super Throwable action)
{
return wrap(super.whenCompleteAsync(action));
}
@Override
public CompletableFuture whenCompleteAsync(BiConsumer super T, ? super Throwable action,
Executor executor)
{
return wrap(super.whenCompleteAsync(action, executor));
}
@Override
public CompletableFuture handle(BiFunction super T, Throwable, ? extends U fn)
{
return wrap(super.handle(fn));
}
@Override
public CompletableFuture handleAsync(BiFunction super T, Throwable, ? extends U fn)
{
return wrap(super.handleAsync(fn));
}
@Override
public CompletableFuture handleAsync(BiFunction super T, Throwable, ? extends U fn,
Executor executor)
{
return wrap(super.handleAsync(fn, executor));
}
@Override
public boolean complete(T value)
{
return delegate.complete(value);
}
@Override
public boolean completeExceptionally(Throwable ex)
{
return delegate.completeExceptionally(ex);
}
}
```
**RunMode.java**:
```
/**
* Operational modes.
*/
public enum RunMode
{
/**
* Optimized for debugging problems (extra runtime checks, logging of the program state).
*/
DEBUG,
/**
* Optimized for maximum performance.
*/
RELEASE
}
```
**AsynchronousException.java**
```
/**
* Thrown when an asynchronous operation fails. The stacktrace indicates who triggered the operation.
*/
public final class AsynchronousException extends RuntimeException
{
private static final long serialVersionUID = 0L;
public AsynchronousException()
{
}
}
```
Usage:
```
DebugCompletableFuture.wrap(CompletableFuture.supplyAsync(this::expensiveOperation));
```
Upside: you'll get relatively clean asynchronous stack traces.
Downside: Constructing a new `AsynchronousException` every time a future is created is extremely expensive. Specifically, if you're generating a lot of futures, this generates a lot of garbage on the heap and the GC overhead becomes noticeable.
I am still hopeful that someone will come up with a better-performing approach.
Upvotes: 4 [selected_answer]<issue_comment>username_2: This is probably due to the [JVM update](https://www.oracle.com/technetwork/java/javase/relnotes-139183.html#hotspot) when it finds that the stack is exhausted of emitting the same log so it starts to omit it.
And the solution is using `-XX:-OmitStackTraceInFastThrow` flag to prevent JVM from optimizing built-in exceptions stack trace.
Upvotes: 0
|
2018/03/14
| 3,018 | 12,309 |
<issue_start>username_0: I'm having many buttons with the same id but different name.But I'm unable to get the name attribute value in `jquery` for a clicked button.I searched in StackOverflow and got many suggestions about my issue.But still, I'm unable to fix my problem. Anyone, please help.
I'm giving only my `jquery` code here:
```js
$(document).click('#grant',function(){
$name=$(this).attr("name");
alert($name);
});
```
Here grant is the id given for the buttons. I want to fetch only the name attr of clicked button. I tried with `this` operator. But alert box shows `undefined`.
Need help. Thanks in advance<issue_comment>username_1: Seeing as this question has not received any answers in almost a month, I'm going to post the best solution I've found to date:
**DebugCompletableFuture.java**:
```
/**
* A {@link CompletableFuture} that eases debugging.
*
* @param the type of value returned by the future
\*/
public final class DebugCompletableFuture extends CompletableFuture
{
private static RunMode RUN\_MODE = RunMode.DEBUG;
private static final Set CLASS\_PREFIXES\_TO\_REMOVE = ImmutableSet.of(DebugCompletableFuture.class.getName(),
CompletableFuture.class.getName(), ThreadPoolExecutor.class.getName());
private static final Set> EXCEPTIONS\_TO\_UNWRAP = ImmutableSet.of(AsynchronousException.class,
CompletionException.class, ExecutionException.class);
private final CompletableFuture delegate;
private final AsynchronousException asyncStacktrace;
/\*\*
\* @param delegate the stage to delegate to
\* @throws NullPointerException if any of the arguments are null
\*/
private DebugCompletableFuture(CompletableFuture delegate)
{
requireThat("delegate", delegate).isNotNull();
this.delegate = delegate;
this.asyncStacktrace = new AsynchronousException();
delegate.whenComplete((value, exception) ->
{
if (exception == null)
{
super.complete(value);
return;
}
exception = Exceptions.unwrap(exception, EXCEPTIONS\_TO\_UNWRAP);
asyncStacktrace.initCause(exception);
filterStacktrace(asyncStacktrace, element ->
{
String className = element.getClassName();
for (String prefix : CLASS\_PREFIXES\_TO\_REMOVE)
if (className.startsWith(prefix))
return true;
return false;
});
Set newMethods = getMethodsInStacktrace(asyncStacktrace);
if (!newMethods.isEmpty())
{
Set oldMethods = getMethodsInStacktrace(exception);
newMethods.removeAll(oldMethods);
if (!newMethods.isEmpty())
{
// The async stacktrace introduces something new
super.completeExceptionally(asyncStacktrace);
return;
}
}
super.completeExceptionally(exception);
});
}
/\*\*
\* @param exception an exception
\* @return the methods referenced by the stacktrace
\* @throws NullPointerException if {@code exception} is null
\*/
private Set getMethodsInStacktrace(Throwable exception)
{
requireThat("exception", exception).isNotNull();
Set result = new HashSet<>();
for (StackTraceElement element : exception.getStackTrace())
result.add(element.getClassName() + "." + element.getMethodName());
for (Throwable suppressed : exception.getSuppressed())
result.addAll(getMethodsInStacktrace(suppressed));
return result;
}
/\*\*
\* @param the type returned by the delegate
\* @param delegate the stage to delegate to
\* @return if {@code RUN\_MODE == DEBUG} returns an instance that wraps {@code delegate}; otherwise, returns {@code delegate}
\* unchanged
\* @throws NullPointerException if any of the arguments are null
\*/
public static CompletableFuture wrap(CompletableFuture delegate)
{
if (RUN\_MODE != RunMode.DEBUG)
return delegate;
return new DebugCompletableFuture<>(delegate);
}
/\*\*
\* Removes stack trace elements that match a filter. The exception and its descendants are processed recursively.
\*
\* This method can be used to remove lines that hold little value for the end user (such as the implementation of utility functions).
\*
\* @param exception the exception to process
\* @param elementFilter returns true if the current stack trace element should be removed
\*/
private void filterStacktrace(Throwable exception, Predicate elementFilter)
{
Throwable cause = exception.getCause();
if (cause != null)
filterStacktrace(cause, elementFilter);
for (Throwable suppressed : exception.getSuppressed())
filterStacktrace(suppressed, elementFilter);
StackTraceElement[] elements = exception.getStackTrace();
List keep = new ArrayList<>(elements.length);
for (StackTraceElement element : elements)
{
if (!elementFilter.test(element))
keep.add(element);
}
exception.setStackTrace(keep.toArray(new StackTraceElement[0]));
}
@Override
public CompletableFuture thenApply(Function super T, ? extends U fn)
{
return wrap(super.thenApply(fn));
}
@Override
public CompletableFuture thenApplyAsync(Function super T, ? extends U fn)
{
return wrap(super.thenApplyAsync(fn));
}
@Override
public CompletableFuture thenApplyAsync(Function super T, ? extends U fn, Executor executor)
{
return wrap(super.thenApplyAsync(fn, executor));
}
@Override
public CompletableFuture thenAccept(Consumer super T action)
{
return wrap(super.thenAccept(action));
}
@Override
public CompletableFuture thenAcceptAsync(Consumer super T action)
{
return wrap(super.thenAcceptAsync(action));
}
@Override
public CompletableFuture thenAcceptAsync(Consumer super T action, Executor executor)
{
return wrap(super.thenAcceptAsync(action, executor));
}
@Override
public CompletableFuture thenRun(Runnable action)
{
return wrap(super.thenRun(action));
}
@Override
public CompletableFuture thenRunAsync(Runnable action)
{
return wrap(super.thenRunAsync(action));
}
@Override
public CompletableFuture thenRunAsync(Runnable action, Executor executor)
{
return wrap(super.thenRunAsync(action, executor));
}
@Override
public CompletableFuture thenCombine(CompletionStage extends U other,
BiFunction super T, ? super U, ? extends V fn)
{
return wrap(super.thenCombine(other, fn));
}
@Override
public CompletableFuture thenCombineAsync(CompletionStage extends U other,
BiFunction super T, ? super U, ? extends V fn)
{
return wrap(super.thenCombineAsync(other, fn));
}
@Override
public CompletableFuture thenCombineAsync(CompletionStage extends U other,
BiFunction super T, ? super U, ? extends V fn,
Executor executor)
{
return wrap(super.thenCombineAsync(other, fn, executor));
}
@Override
public CompletableFuture thenAcceptBoth(CompletionStage extends U other,
BiConsumer super T, ? super U action)
{
return wrap(super.thenAcceptBoth(other, action));
}
@Override
public CompletableFuture thenAcceptBothAsync(CompletionStage extends U other,
BiConsumer super T, ? super U action)
{
return wrap(super.thenAcceptBothAsync(other, action));
}
@Override
public CompletableFuture thenAcceptBothAsync(CompletionStage extends U other,
BiConsumer super T, ? super U action,
Executor executor)
{
return wrap(super.thenAcceptBothAsync(other, action, executor));
}
@Override
public CompletableFuture runAfterBoth(CompletionStage other, Runnable action)
{
return wrap(super.runAfterBoth(other, action));
}
@Override
public CompletableFuture runAfterBothAsync(CompletionStage other, Runnable action)
{
return wrap(super.runAfterBothAsync(other, action));
}
@Override
public CompletableFuture runAfterBothAsync(CompletionStage other, Runnable action, Executor executor)
{
return wrap(super.runAfterBothAsync(other, action, executor));
}
@Override
public CompletableFuture applyToEither(CompletionStage extends T other, Function super T, U fn)
{
return wrap(super.applyToEither(other, fn));
}
@Override
public CompletableFuture applyToEitherAsync(CompletionStage extends T other, Function super T, U fn)
{
return wrap(super.applyToEitherAsync(other, fn));
}
@Override
public CompletableFuture applyToEitherAsync(CompletionStage extends T other, Function super T, U fn,
Executor executor)
{
return wrap(super.applyToEitherAsync(other, fn, executor));
}
@Override
public CompletableFuture acceptEither(CompletionStage extends T other, Consumer super T action)
{
return wrap(super.acceptEither(other, action));
}
@Override
public CompletableFuture acceptEitherAsync(CompletionStage extends T other, Consumer super T action)
{
return wrap(super.acceptEitherAsync(other, action));
}
@Override
public CompletableFuture acceptEitherAsync(CompletionStage extends T other, Consumer super T action,
Executor executor)
{
return wrap(super.acceptEitherAsync(other, action, executor));
}
@Override
public CompletableFuture runAfterEither(CompletionStage other, Runnable action)
{
return wrap(super.runAfterEither(other, action));
}
@Override
public CompletableFuture runAfterEitherAsync(CompletionStage other, Runnable action)
{
return wrap(super.runAfterEitherAsync(other, action));
}
@Override
public CompletableFuture runAfterEitherAsync(CompletionStage other, Runnable action, Executor executor)
{
return wrap(super.runAfterEitherAsync(other, action, executor));
}
@Override
public CompletableFuture thenCompose(Function super T, ? extends CompletionStage<U> fn)
{
return wrap(super.thenCompose(fn));
}
@Override
public CompletableFuture thenComposeAsync(Function super T, ? extends CompletionStage<U> fn)
{
return wrap(super.thenComposeAsync(fn));
}
@Override
public CompletableFuture thenComposeAsync(Function super T, ? extends CompletionStage<U> fn,
Executor executor)
{
return wrap(super.thenComposeAsync(fn, executor));
}
@Override
public CompletableFuture exceptionally(Function fn)
{
return wrap(super.exceptionally(fn));
}
@Override
public CompletableFuture whenComplete(BiConsumer super T, ? super Throwable action)
{
return wrap(super.whenComplete(action));
}
@Override
public CompletableFuture whenCompleteAsync(BiConsumer super T, ? super Throwable action)
{
return wrap(super.whenCompleteAsync(action));
}
@Override
public CompletableFuture whenCompleteAsync(BiConsumer super T, ? super Throwable action,
Executor executor)
{
return wrap(super.whenCompleteAsync(action, executor));
}
@Override
public CompletableFuture handle(BiFunction super T, Throwable, ? extends U fn)
{
return wrap(super.handle(fn));
}
@Override
public CompletableFuture handleAsync(BiFunction super T, Throwable, ? extends U fn)
{
return wrap(super.handleAsync(fn));
}
@Override
public CompletableFuture handleAsync(BiFunction super T, Throwable, ? extends U fn,
Executor executor)
{
return wrap(super.handleAsync(fn, executor));
}
@Override
public boolean complete(T value)
{
return delegate.complete(value);
}
@Override
public boolean completeExceptionally(Throwable ex)
{
return delegate.completeExceptionally(ex);
}
}
```
**RunMode.java**:
```
/**
* Operational modes.
*/
public enum RunMode
{
/**
* Optimized for debugging problems (extra runtime checks, logging of the program state).
*/
DEBUG,
/**
* Optimized for maximum performance.
*/
RELEASE
}
```
**AsynchronousException.java**
```
/**
* Thrown when an asynchronous operation fails. The stacktrace indicates who triggered the operation.
*/
public final class AsynchronousException extends RuntimeException
{
private static final long serialVersionUID = 0L;
public AsynchronousException()
{
}
}
```
Usage:
```
DebugCompletableFuture.wrap(CompletableFuture.supplyAsync(this::expensiveOperation));
```
Upside: you'll get relatively clean asynchronous stack traces.
Downside: Constructing a new `AsynchronousException` every time a future is created is extremely expensive. Specifically, if you're generating a lot of futures, this generates a lot of garbage on the heap and the GC overhead becomes noticeable.
I am still hopeful that someone will come up with a better-performing approach.
Upvotes: 4 [selected_answer]<issue_comment>username_2: This is probably due to the [JVM update](https://www.oracle.com/technetwork/java/javase/relnotes-139183.html#hotspot) when it finds that the stack is exhausted of emitting the same log so it starts to omit it.
And the solution is using `-XX:-OmitStackTraceInFastThrow` flag to prevent JVM from optimizing built-in exceptions stack trace.
Upvotes: 0
|
2018/03/14
| 1,051 | 5,392 |
<issue_start>username_0: I need to add a **Custom Header** in all my RestTemplate Client requests. So I implemented `ClientHttpRequestInterceptor`. And I add the interceptor in my `RestTemplateBuilder` config like shown below. The problem is that when the RestTemplate makes the HTTP call it throws following exception:
```
java.lang.ClassCastException: org.springframework.http.client.InterceptingClientHttpRequestFactory cannot be cast to org.springframework.http.client.HttpComponentsClientHttpRequestFactory
```
RestTemplate Bean Creation :
```
@Bean
public RestTemplate restTemplate(RestTemplateBuilder restTemplateBuilder) {
PoolingHttpClientConnectionManager poolingConnectionManager = new PoolingHttpClientConnectionManager();
poolingConnectionManager.setMaxTotal(restTemplateProps.getMaxConnectionsPerPool());
poolingConnectionManager.setDefaultMaxPerRoute(restTemplateProps.getMaxDefaultConnectionPerRoute());
CloseableHttpClient client = HttpClientBuilder.create().setConnectionManager(poolingConnectionManager).build();
ClientHttpRequestFactory clientHttpRequestFactory = new HttpComponentsClientHttpRequestFactory(client);
restTemplateBuilder = restTemplateBuilder.additionalInterceptors(new MyClientHttpRequestInterceptor());
return restTemplateBuilder.requestFactory(clientHttpRequestFactory).build();
}
```
Also, I am updating the timeouts later in below code:
```
protected void setRestTemplateTimeouts() {
HttpComponentsClientHttpRequestFactory rf =
(HttpComponentsClientHttpRequestFactory) restTemplate.getRequestFactory();
rf.setConnectTimeout(restTemplateProps.getConnectionTimeout());
rf.setReadTimeout(restTemplateProps.getSocketTimeout());
}
```
Can anyone help me fix this?<issue_comment>username_1: The problem was, I was trying to set the **connect and read timeouts** after setting the `ClientHttpRequestInterceptor`.
In my `setRestTemplateTimeouts()` method when I try to fetch & typecast `requestFactory` to `HttpComponentsClientHttpRequestFactory`, I get the `ClassCastException` exception because `restTemplate.getRequestFactory()` returns `InterceptingClientHttpRequestFactory` instead of `HttpComponentsClientHttpRequestFactory`. This is because I added an **interceptor** in my **restTemplate** object.
Solution is to **set the timeouts before setting** **interceptor** because you can't set timeouts after setting an interceptor. Refer the code below:
```
@Bean
public RestTemplate restTemplate(RestTemplateBuilder restTemplateBuilder) {
PoolingHttpClientConnectionManager poolingConnectionManager = new PoolingHttpClientConnectionManager();
poolingConnectionManager.setMaxTotal(restTemplateProps.getMaxConnectionsPerPool());
poolingConnectionManager.setDefaultMaxPerRoute(restTemplateProps.getMaxDefaultConnectionPerRoute());
CloseableHttpClient client = HttpClientBuilder.create().setConnectionManager(poolingConnectionManager).build();
HttpComponentsClientHttpRequestFactory clientHttpRequestFactory = new HttpComponentsClientHttpRequestFactory(client);
clientHttpRequestFactory.setConnectTimeout(restTemplateProps.getConnectionTimeout());
clientHttpRequestFactory.setReadTimeout(restTemplateProps.getSocketTimeout());
restTemplateBuilder = restTemplateBuilder.additionalInterceptors(new MyClientHttpRequestInterceptor());
return restTemplateBuilder.requestFactory(clientHttpRequestFactory).build();
}
```
Upvotes: 4 [selected_answer]<issue_comment>username_2: This is how i manage to get the interceptor to log both request and response without throwing exception - Attempted read from closed stream.
```
@Bean
public RestTemplate getRestTemplateConfig()
throws KeyStoreException, IOException, UnrecoverableKeyException, CertificateException, NoSuchAlgorithmException, KeyManagementException {
SSLContext context = SSLContextBuilder
.create()
.loadKeyMaterial(ResourceUtils.getFile("/opt/cert/keystore.jks"),
"<PASSWORD>".toCharArray(),
"<PASSWORD>".toCharArray())
.build();
HttpClient client = HttpClients
.custom()
.setSSLContext(context)
.build();
HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
requestFactory.setHttpClient(client);
RestTemplate restTemplate = new RestTemplate(requestFactory);
//Provide a buffer for the outgoing/incoming stream, allowing the response body to be read multiple times
// (if not configured, the interceptor reads the Response stream, and then returns body=null when responding to the data)
restTemplate.setRequestFactory(new BufferingClientHttpRequestFactory(requestFactory));
restTemplate.setErrorHandler(new RestTemplateResponseErrorHandler());
restTemplate.setInterceptors(Collections.singletonList(
new RestTemplateInterceptor()));
restTemplate.getMessageConverters().add(jacksonSupportsMoreTypes());
return restTemplate;
}
private HttpMessageConverter jacksonSupportsMoreTypes() {
MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
converter.setSupportedMediaTypes(Arrays.asList( MediaType.APPLICATION\_OCTET\_STREAM));
return converter;
}
```
Upvotes: 1
|
2018/03/14
| 551 | 2,205 |
<issue_start>username_0: I thought up an idea for a website that would involve some video editing happening on the web server. Microsoft UWP [has a library](https://learn.microsoft.com/en-us/windows/uwp/audio-video-camera/media-compositions-and-editing) that does the video editing functions I'm looking to perform... Amazing!!
My problem is I don't know if it's possible to get my website to run UWP code on Azure. Web Jobs seem like what I'd prefer to use to kick off this code, but web jobs don't appear to be able to run UWP code and without UWP code I don't see a library that can perform the video editing I'd like to do. Does anybody know if it's possible to run UWP code on Azure? If so, how?<issue_comment>username_1: I don't think WebJobs are especially suited for this scenario. They are part of the WebApp platform as a service offering that abstracts the underlying operating system for you to be able to focus on building the code itself and deploy as easily as possible.
UWP on the other hand is a **Windows-specific** app platform which has many requirements including running on **Windows 10**. Because you don't know which concrete operating system the web app will run on, it is not easy to say if the APIs would work.
That said, you could theoretically use UWP APIs in a web app as well, because there is a [`UwpDesktop` NuGet package](https://blogs.windows.com/buildingapps/2017/01/25/calling-windows-10-apis-desktop-application/) that allows it mainly targeted for desktop apps. It is a long shot but you can certainly try it.
As a preferable solution, I would still look to find another library that suits your needs, as the choice on NuGet is pretty broad and one of those should be sufficient.
Upvotes: 2 [selected_answer]<issue_comment>username_2: I would suggest taking a look at [azure functions](https://learn.microsoft.com/en-us/azure/azure-functions/functions-create-your-first-function-visual-studio)
These have about the same working as webjobs, however expand beyond the limitations of webjobs. These are also more versatile in what they can do and how they can be created.
[webjobs vs functions](https://stackify.com/azure-webjobs-vs-azure-functions/)
Upvotes: 0
|
2018/03/14
| 735 | 2,667 |
<issue_start>username_0: I've been tasked with reading a text file and counting the wins of superbowl teams from 1967 to 1977. So far my program only prints the occurrences of each line and counts it as 1 because they all have different years attached to the team names. I don't know how to remove the years from the team names. So far I have
```
def word_count():
city_list = []
city_file = open('win_count.txt', 'r')
for city in city_file:
city = city.rstrip('\n')
city = city.split('\n')
city_list.append(city)
my_dict = {}
city_file.close()
for item in city_list:
for city in item:
if city in my_dict:
my_dict[city] += 1
else:
my_dict[city] = 1
print('city\t\tCount')
for key, value in my_dict.items():
print(key,'\t', ':' , '\t', value)
word_count()
```
This is the win\_count.txt file
```
1977 Oakland
1976 Pittsburgh
1975 Pittsburgh
1974 Miami
1973 Miami
1972 Dallas
1971 Baltimore
1970 Kansas City
1969 New York Jets
1968 Green Bay
1967 Green Bay
```<issue_comment>username_1: I don't think WebJobs are especially suited for this scenario. They are part of the WebApp platform as a service offering that abstracts the underlying operating system for you to be able to focus on building the code itself and deploy as easily as possible.
UWP on the other hand is a **Windows-specific** app platform which has many requirements including running on **Windows 10**. Because you don't know which concrete operating system the web app will run on, it is not easy to say if the APIs would work.
That said, you could theoretically use UWP APIs in a web app as well, because there is a [`UwpDesktop` NuGet package](https://blogs.windows.com/buildingapps/2017/01/25/calling-windows-10-apis-desktop-application/) that allows it mainly targeted for desktop apps. It is a long shot but you can certainly try it.
As a preferable solution, I would still look to find another library that suits your needs, as the choice on NuGet is pretty broad and one of those should be sufficient.
Upvotes: 2 [selected_answer]<issue_comment>username_2: I would suggest taking a look at [azure functions](https://learn.microsoft.com/en-us/azure/azure-functions/functions-create-your-first-function-visual-studio)
These have about the same working as webjobs, however expand beyond the limitations of webjobs. These are also more versatile in what they can do and how they can be created.
[webjobs vs functions](https://stackify.com/azure-webjobs-vs-azure-functions/)
Upvotes: 0
|
2018/03/14
| 389 | 1,515 |
<issue_start>username_0: I have a Drawer layout. I have placed a ViewPager for sliding Image and Tab Layout for dots, after I want a TextView and a ListView Again a TextView and again ListView, it goes for 4 times. So, I want my whole screen to be scroll-able. Here is the issue, if I am fixing the height of ListView app, it is starting from Bottom, If I am using match parent then list view does not scroll and it act like Linear layout and anything below this doesn't shows up. If I am using wrap content in height, the list view is scroll-able but nothing shows up after list view because whole screen is not scrolling.
MainActivity.xml
```
xml version="1.0" encoding="utf-8"?
```
If I am using above xml, then Enterntainment TextView and List View following is not showing. Please Help. I am making a news app.<issue_comment>username_1: Change the `ScrollView` with `NestedScrollView` and `ListView` with `RecyclerView`
```
```
>
> [here is link for migrate from ListView to RecyclerView](http://traversoft.com/2016/01/31/replace-listview-with-recyclerview)
>
>
>
Upvotes: 3 [selected_answer]<issue_comment>username_2: Please use NestedScrollView instead, it is similar to ScrollView, but it will support acting as both a nested scrolling parent and child. Please check this for more information and samples.
<https://inducesmile.com/android-tips/android-recyclerview-inside-nestedscrollview-example/>
Upvotes: 0 <issue_comment>username_3: change your scrollview to nestedscrollview
Upvotes: 0
|
2018/03/14
| 922 | 3,029 |
<issue_start>username_0: This is my dockerfile :
```
FROM node:6-onbuild
RUN mkdir -p /usr/src/app
WORKDIR /usr/src/app
COPY package.json /usr/src/app/
RUN npm install
COPY . /usr/src/app
ENV PORT 80
EXPOSE ${PORT}
CMD [ "npm","run", "start" ]
```
and in package.json I do have this :
```
"scripts": {
"start": "node start.js",
"stagestart": "NODE_ENV=content-staging node start.js"
}
```
the `start` script is for production, now I want a way to run the staging script in dockerfile. is there a way to read NODE\_ENV inside dockerfile, so I can have one dockerfile which handle staging and production.<issue_comment>username_1: You can use the ENV instruction to get the environment variable as an environment variable inside container. Have an entry point script that injects the available environment variable (perhaps something as simple as sed) in place of a placeholder variable name that is in your package.json file. Then start your node application. Obviously this will require you to make a few changes to your Dockerfile in regards to entrypoint script etc.
That is how I have achieved such things in the past.
Upvotes: -1 <issue_comment>username_2: Here is two possible implementation.
>
> FYI: you don't need to mention NODE\_ENV in package.json if you
> already set NODE\_ENV at the system level or set NODE\_ENV during build time or runtime in docker.
>
>
>
Here `Dockerfile` as same but I used to `alpine` base image
```
FROM node:alpine
RUN mkdir -p /usr/src/app
WORKDIR /usr/src/app
COPY package.json /usr/src/app/
RUN npm install
COPY . /usr/src/app
ENV PORT 3000
ARG DOCKER_ENV
ENV NODE_ENV=${DOCKER_ENV}
RUN if [ "$DOCKER_ENV" = "stag" ] ; then echo your NODE_ENV for stage is $NODE_ENV; \
else echo your NODE_ENV for dev is $NODE_ENV; \
fi
EXPOSE ${PORT}
CMD [ "npm","run", "start" ]
```
when you build this Dockerfile with this command
```
docker build --build-arg DOCKER_ENV=stag -t test-node .
```
You will see at layer
```
---> Running in a6231eca4d0b your NODE_ENV for stage is stag
```
When you run this docker container and run this command your output will be
```
/usr/src/app # echo $NODE_ENV
stag
```
**Simplest Approch** same image and but set environment variable at run time
Your Dockerfile
```
FROM node:alpine
RUN mkdir -p /usr/src/app
WORKDIR /usr/src/app
COPY package.json /usr/src/app/
RUN npm install
COPY . /usr/src/app
ENV PORT 3000
EXPOSE ${PORT}
CMD [ "npm","run", "start" ]
```
Run this docker image with this command
```
docker build -t test-node .
docker run --name test -e NODE_ENV=content-staging -p 3000:3000 --rm -it test-node ash
```
So when you run this command at container you will see
```
/usr/src/app # echo $NODE_ENV
content-staging
```
So this is how you can start your node application with **NODE\_ENV** without setting environment variable at package.json. So if your nodejs configuration is based on **NODE\_ENV** it should pick configuration according to **NODE\_ENV** .
Upvotes: 6 [selected_answer]
|
2018/03/14
| 487 | 1,552 |
<issue_start>username_0: How can I display 2 decimal places (padding) on a float even if the trailing number is a 0. So, if I sum only the :cost values in the example below I would like it to return 23.00
```ruby
items = [
{customer: "John", item: "Soup", cost:("%.2f"% 8.50)},
{customer: "Sarah", item: "Pasta", cost:("%.2f"% 12.00)},
{customer: "John", item: "Coke", cost:("%.2f" % 2.50)}
]
```
PROBLEM:
I have success displaying cost: values with two decimal places. However, the result returns a "string". I have tried ***("%.2f" % 2.50).to\_f*** with no such luck. I need a float so that I can complete the following inject code.
```
totalcost = items.inject(0) {|sum, hash| sum + hash[:cost]}
puts totalcost
```
When running this to sum the total cost I receive the following error because I cannot convert the string to a float successfully. **String can't be coerced into Integer (TypeError)**<issue_comment>username_1: hash[:cost] is still returns a String. you could just cover it to a float before adding it to sum
```
totalcost = items.inject(0) {|sum, hash| sum + hash[:cost].to_f}
```
Upvotes: 0 <issue_comment>username_2: You can calculate the sum of cost values after converting it to number(Integer/Float).
```
totalcost = items.map { |x| x[:cost].to_f }.sum
```
The value of `totalcost` can be formatted with [sprintf method](http://ruby-doc.org/core-2.0.0/Kernel.html#method-i-sprintf) in whatever way we want to display.
```
sprintf("%.2f", totalcost)
```
Hope it helps !
Upvotes: 3 [selected_answer]
|
2018/03/14
| 835 | 2,953 |
<issue_start>username_0: I am writing a simple Python program to store user inputted lap times in a list and then have a few functions performed on that list.
My problem is, despite explicitly declaring the lap times as 'float' before appending them into the list, they are still getting stored as strings. This means I cannot perform functions like sum() on the list as I am getting error messages such as: TypeError: unsupported operand type(s) for +: 'int' and 'str'.
Here is the code:
```
lapTimes = []
count = 0
while True:
count += 1
lap = input("Enter lap time " + str(count) + ": ")
if lap == 'x':
break
else:
float(lap)
print(type(lap))
lapTimes.append(lap)
print(type(lapTimes[-1]))
print("Fastest Lap time was: ", min(lapTimes))
print("Slowest lap time was: ", max(lapTimes))
```
After declaring 'lap' as a float in the else clause, I have written written a line to print the data type of 'lap', and when run I get told it's a string!
I have done the same thing with the print(type(lapTimes[-1])) line just to make sure, and yep I still get told the data is a string.
There are supposed to be more lines of code on the bottom printing the sum of the list and the average lap time, which will not work because of this problem.<issue_comment>username_1: Because you are not assigning the value of `float(lap)`. Write
```
lap=float(lap)
```
or better
```
lap = float(input("Enter lap time " + str(count) + ": "))
```
Upvotes: 1 <issue_comment>username_2: you should write `lap = float(lap)`. Just writing `float(lap)` does nothing to the original lap variable.
Upvotes: 0 <issue_comment>username_3: >
> My problem is, despite explicitly declaring the lap times as 'float'
> before appending them into the list, they are still getting stored as
> strings.
>
>
>
You have done no such thing. Python *doesn't have variable declarations*. You have simply called the `float` type constructor and passed it a string as an argument. It *returns* the `float` value you are expecting, but you never capture its output, and it is immediately discarded. Instead, do:
```
lapTimes.append(float(lap))
```
Upvotes: 2 <issue_comment>username_4: ```
lapTimes = []
count = 0
while True:
count += 1
lap = input("Enter lap time " + str(count) + ": ")
if lap == 'x':
break
else:
lap = float(lap)
print(type(lap))
lapTimes.append(lap)
print(type(lapTimes[-1]))
print("Fastest Lap time was: ", min(lapTimes))
print("Slowest lap time was: ", max(lapTimes))
```
You missed assignment of lap after converting to float. That's why saw error.
Upvotes: 0 <issue_comment>username_5: Please check documentation about `float()`
<https://docs.python.org/3/library/functions.html#float>
The return value of `float()` is a float.
In else block, you need write codes like this:
```
else:
lap = float(lap)
print(type(lap))
lapTimes.append(lap)
```
Upvotes: 1
|
2018/03/14
| 323 | 1,039 |
<issue_start>username_0: My android studio project wasn't able to sync with the gradle, I got the following error:
>
> Error:Execution failed for task ':app:processDebugManifest'.
> Manifest merger failed : Attribute meta-data#android.support.VERSION@value value=(26.0.0-beta1) from [com.android.support:design:26.0.0-beta1] AndroidManifest.xml:28:13-41
> is also present at [com.android.support:appcompat-v7:26.1.0] AndroidManifest.xml:28:13-35 value=(26.1.0).
> Suggestion: add 'tools:replace="android:value"' to element at AndroidManifest.xml:26:9-28:44 to override.
>
>
>
Can anyone help?<issue_comment>username_1: Just ensure your dependencies have same version number. Example;
```
implementation 'com.android.support:appcompat-v7:26.1.0'
implementation 'com.android.support:design:26.1.0'
```
Upvotes: 1 <issue_comment>username_2: Please write this line tools:replace="android:value" into Android Manifest file, if you are face this problem again so please enable androidX after that this issue will resolve.
Upvotes: 0
|
2018/03/14
| 1,900 | 7,028 |
<issue_start>username_0: I need to upload a large generated pdf file to the server and show uploading progress to the user. But the problem is the percentage I got from OutputStream is not the real progress because after 100% progress of OutputStream, still cannot get response code from the server (need to wait for more)
Please help me with this problem. Thank you.
\*\* For more information: the total uploading time is 15 minutes but the progress percentage finish in a second.
```
class UploadPdf extends AsyncTask {
private Activity activity;
private String orderId = "";
private String filenamepdf = "";
private String filenamezip = "";
private int dpi = 640;
public ImageCreator mImageCreator;
public UploadPdf(Activity activity) {
this.activity = activity;
}
@Override
protected String doInBackground(String... strings) {
orderId = strings[0];
filenamepdf = orderId + ".pdf";
String uploadStatus = uploadFileToServer();
return uploadStatus;
}
@Override
protected void onProgressUpdate(Integer... progress) {
//Update progress
updateProgress(progress[0]);
}
@Override
protected void onPostExecute(String result) {
//Show result
try {
JSONObject obj = new JSONObject(result);
if(obj.getString("status").equals("success")) {
uploadSuccess();
} else {
errorContainer.setVisibility(View.VISIBLE);
}
} catch (Exception ex) {
errorContainer.setVisibility(View.VISIBLE);
}
}
private String uploadFileToServer() {
Log.d(LOGTAG, "uploadFileToServer");
String urlString = Constants.API\_BASE\_URL + Constants.API\_CREATE\_UPLOAD\_FILE;
String response = null;
String attachmentName = "attachment";
String attachmentFileName = "attachment";
String crlf = "\r\n";
String twoHyphens = "--";
String boundary = "\*\*\*\*\*";
try {
File file = new File(filenamepdf);
MultipartUtility multipart = new MultipartUtility(urlString, "UTF-8", getApplicationContext());
multipart.addFormField("order\_id", orderId);
multipart.addFilePart("album\_image\_path", file);
List responseReturn = multipart.finish();
Log.e(LOGTAG, "SERVER REPLIED:");
response = "";
for (String line : responseReturn) {
Log.e(LOGTAG, "Upload Files Response:::" + line);
response += line;
}
} catch (Exception ex) {
Log.e(LOGTAG, "Failed:" + ex.getMessage());
}
Log.e(LOGTAG, "Response:" + response);
return response;
}
public class MultipartUtility {
private final String LOGTAG = "MultipartUtility";
private final String boundary;
private static final String LINE\_FEED = "\r\n";
private HttpURLConnection httpConn;
private String charset;
private OutputStream outputStream;
private PrintWriter writer;
Context context;
/\*\*
\* This constructor initializes a new HTTP POST request with content type
\* is set to multipart/form-data
\*
\* @param requestURL
\* @param charset
\* @throws IOException
\*/
public MultipartUtility(String requestURL, String charset, Context context)
throws IOException {
this.charset = charset;
this.context = context;
// creates a unique boundary based on time stamp
boundary = "===" + System.currentTimeMillis() + "===";
URL url = new URL(requestURL);
httpConn = (HttpURLConnection) url.openConnection();
httpConn.setUseCaches(false);
httpConn.setDoOutput(true); // indicates POST method
httpConn.setDoInput(true);
httpConn.setRequestProperty("Content-Type",
"multipart/form-data; boundary=" + boundary);
outputStream = httpConn.getOutputStream();
writer = new PrintWriter(new OutputStreamWriter(outputStream, charset),
true);
}
/\*\*
\* Adds a form field to the request
\*
\* @param name field name
\* @param value field value
\*/
public void addFormField(String name, String value) {
Log.d(LOGTAG, "name: " + name + ", value: " + value);
writer.append("--" + boundary).append(LINE\_FEED);
writer.append("Content-Disposition: form-data; name=\"" + name + "\"")
.append(LINE\_FEED);
writer.append("Content-Type: text/plain; charset=" + charset).append(
LINE\_FEED);
writer.append(LINE\_FEED);
writer.append(value).append(LINE\_FEED);
writer.flush();
}
/\*\*
\* Adds a upload file section to the request
\*
\* @param fieldName name attribute in
\* @param uploadFile a File to be uploaded
\* @throws IOException
\*/
public void addFilePart(String fieldName, File uploadFile) throws IOException {
String fileName = uploadFile.getName();
Log.d(LOGTAG, fieldName);
writer.append("--" + boundary).append(LINE\_FEED);
writer.append(
"Content-Disposition: form-data; name=\"" + fieldName
+ "\"; filename=\"" + fileName + "\"")
.append(LINE\_FEED);
writer.append(
"Content-Type: "
+ URLConnection.guessContentTypeFromName(fileName))
.append(LINE\_FEED);
writer.append("Content-Transfer-Encoding: binary").append(LINE\_FEED);
writer.append(LINE\_FEED);
writer.flush();
FileInputStream inputStream = new FileInputStream(uploadFile);
byte[] bytes = new byte[(int) uploadFile.length()];
int byteLength = bytes.length;
byte[] buffer = new byte[4096];
int bytesRead = -1;
int sendByte = 0;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
sendByte += bytesRead;
int progress = (int)(sendByte / (float) byteLength \* 100);
Log.d(LOGTAG, "bytesRead: " + bytesRead + ", byteLength: " + byteLength + ", progress: " + progress);
publishProgress(progress);
}
outputStream.flush();
Log.d(LOGTAG, "Read byte finish");
outputStream.close();
Log.d(LOGTAG, "Close output stream");
inputStream.close();
Log.d(LOGTAG, "Close input stream");
writer.append(LINE\_FEED);
writer.flush();
Log.d(LOGTAG, "Writer flushed");
}
public void addHeaderField(String name, String value) {
writer.append(name + ": " + value).append(LINE\_FEED);
writer.flush();
}
public List finish() throws IOException {
Log.d(LOGTAG, "Finishing");
List response = new ArrayList();
writer.append(LINE\_FEED).flush();
Log.d(LOGTAG, "Line feed flushed");
writer.append("--" + boundary + "--").append(LINE\_FEED);
Log.d(LOGTAG, "Last line flushed");
writer.close();
Log.d(LOGTAG, "Writer closed");
// checks server's status code first
int status = httpConn.getResponseCode();
Log.d(LOGTAG, "Server returned status: " + status);
if (status == HttpURLConnection.HTTP\_OK) {
BufferedReader reader = new BufferedReader(new InputStreamReader(
httpConn.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null) {
response.add(line);
}
reader.close();
httpConn.disconnect();
} else {
throw new IOException("Server returned non-OK status: " + status);
}
return response;
}
}
}
```<issue_comment>username_1: Just ensure your dependencies have same version number. Example;
```
implementation 'com.android.support:appcompat-v7:26.1.0'
implementation 'com.android.support:design:26.1.0'
```
Upvotes: 1 <issue_comment>username_2: Please write this line tools:replace="android:value" into Android Manifest file, if you are face this problem again so please enable androidX after that this issue will resolve.
Upvotes: 0
|
2018/03/14
| 905 | 3,070 |
<issue_start>username_0: I am currently self-teaching myself C++ using Bjarne Stroustrup's book (2nd ed). In one of the examples, he uses a range-for-loop to read the elements in a vector. When I wrote and compiled the code for myself I get this warning. When I run the code, it seems to be working and calculates the mean. Why am I receiving this warning and should I ignore it? Also, why is the range-for using int instead of double in the example, but still returns a double?
```
temp_vector.cpp:17:13: warning: range-based for loop is a C++11
extension [-Wc++11-extensions]
```
This is the code
```
#include
#include
using namespace std;
int main ()
{
vector temps; //initialize a vector of type double
/\*this for loop initializes a double type vairable and will read all
doubles until a non-numerical input is detected (cin>>temp)==false \*/
for(double temp; cin >> temp;)
temps.push\_back(temp);
//compute sum of all objects in vector temps
double sum = 0;
//range-for-loop: for all ints in vector temps.
for(int x : temps)
sum += x;
//compute and print the mean of the elements in the vector
cout << "Mean temperature: " << sum / temps.size() << endl;
return 0;
}
```
On a similar note: how should I view the range-for in terms of a standard for loop?<issue_comment>username_1: Pass `--std=c++11` to the compiler; your (ancient) compiler is defaulting to C++03 and warning you that it is accepting some newer C++ constructs as extensions.
---
Ranged base for is expanded into an iterator-based for loop, but with less opportunities for typos.
Upvotes: 4 <issue_comment>username_2: This is because you are using `for (int x: temps)` which is a c++11 construct. Try the following if you are using eclipse:
* Right-click on the the project and select "Properties"
* Navigate to C/C++ Build -> Settings
* Select the Tool Settings tab.
* Navigate to GCC C++ Compiler -> Miscellaneous
* In the option setting labeled Other Flags add -std=c++11
Now rebuild your project.
**Update:** For Atom follow below steps:
Go to ~/.atom/packages/script/lib/grammers.coffee
Go to the C++ section (ctrl-f c++):
Then change this line:
```
args: (context) -> ['-c', "xcrun clang++ -fcolor-diagnostics -Wc++11-extensions // other stuff
```
to this:
```
args: (context) -> ['-c', "xcrun clang++ -fcolor-diagnostics -std=c++11 -stdlib=libc++ // other stuff
```
i.e. add `-std=c++11 -stdlib=libc++` and remove `-Wc++11-extensions`
Hope this helps!
Upvotes: 1 <issue_comment>username_3: Since nobody is showing *how* to use C++ 11 with g++, it looks like this...
```
g++ -std=c++11 your_file.cpp -o your_program
```
Hopefully this saves Google visitors an extra search.
Upvotes: 5 <issue_comment>username_4: For those who use code runner extension on VS code, go to code runner extension settings.
find -> Code-runner:Executer map. Click on edit in `settings.json` and find cpp script for terminal and set it like follows:
```
"cpp": "cd $dir && g++ -std=c++11 $fileName -o $fileNameWithoutExt && $dir$fileNameWithoutExt"
```
Upvotes: 3
|
2018/03/14
| 3,611 | 10,643 |
<issue_start>username_0: Anyone that could help me out, much appreciated!
------------------------------------------------
I'd like this code to be as minimized as possible - however, I'd like it to display the exact same stuff.
Specifically, on how to remove some of the repetitions made within the code (such as "if, else if") etc. using other statements or making the compiler go through it faster, as I feel like I lack the experience and the knowledge to do this without messing up everything (such as using switch & case).
For example, when I test for "tf", I'd like not to be forced to repeat the "average" depending on whether or not we add the "TEZA" grade.
Thanks a lot, of course, I am willing to share more details if there's a need or if I'm not clear enough.
*I apologize in advance in case I'm not clear enough.*
---
```
#include
using namespace std;
int main()
{
string sub, tf;
int m1, m2, m3, m4, sum, TEZA;
double avg, tzm;
cout << "SIMPLE AVERAGE CALCULATOR";
cout << "\n" << "\n" << "Subject at hand?: ";
cin >> sub;
cout << "\n" << "Input the FOUR marks you'd like verified: " << "\n";
cout << "\n" << "M1: ";
cin >> m1;
cout << "\n" << "M2: ";
cin >> m2;
cout << "\n" << "M3: ";
cin >> m3;
cout << "\n" << "M4: ";
cin >> m4;
cout << "\n" << "Would you like to include the TEZA grade?(Y/N): ";
cin >> tf;
sum = m1 + m2 + m3 + m4;
avg = (double) sum / 4;
if (tf == "Y" | tf == "y")
{
cout << "What is the TEZA grade?: ";
cin >> TEZA;
int tzm = ((double) avg \* 3 + TEZA) / 4;
cout << "\n" << "Your average grade at " << sub << " is " << tzm << "\n"
<< "\n";
cout << "You got the following mark: ";
if (tzm >= 9 && tzm <= 10)
cout << "A" << "\n";
else if (tzm >= 8 && tzm <= 9)
cout << "B" << "\n";
else if (tzm >= 7 && tzm <= 8)
cout << "C" << "\n";
else if (tzm >= 6 && tzm <= 7)
cout << "D" << "\n";
else if (tzm >= 5 && tzm <= 6)
cout << "E" << "\n";
else if (tzm < 5)
cout << "F" << "\n";
if (tzm >= 5)
{
cout << "DO YOU PASS: " << "\n";
cout << "Yes." << "\n";
}
else
cout << "No." << "\n";
}
else
{
cout << "\n" << "Average at " << sub << " is " << avg << "\n" << "\n";
cout << "You got the following mark: ";
if (avg >= 9 && avg <= 10)
cout << "A" << "\n";
else if (avg >= 8 && avg <= 9)
cout << "B" << "\n";
else if (avg >= 7 && avg <= 8)
cout << "C" << "\n";
else if (avg >= 6 && avg <= 7)
cout << "D" << "\n";
else if (avg >= 5 && avg <= 6)
cout << "E" << "\n";
else if (avg < 5)
cout << "F" << "\n";
cout << "\n" << "DO YOU PASS?: " << "\n";
if (avg >= 5)
cout << "Yes." << "\n";
else
cout << "No." << "\n";
}
}
```<issue_comment>username_1: You can shorten the parts of the M using an array and a loop
```
#include
using namespace std;
int main()
{
string sub, tf;
int m[4], TEZA, sum;
double avg, tzm;
cout << "SIMPLE AVERAGE CALCULATOR";
cout << "\n" << "\n" << "Subject at hand?: "; cin >> sub;
cout << "\n" << "Input the FOUR marks you'd like verified: " << "\n";
for(int i = 1; i < 5; i++)
{
cout<<"\n"<<"M"<>m[i-1];
}
cout << "\n" << "Would you like to include the TEZA grade?(Y/N): "; cin >> tf;
sum = m[0] + m[1] + m[2] + m[3];
avg = (double) sum / 4;
if (tf == "Y" | tf == "y")
{
cout << "What is the TEZA grade?: "; cin >> TEZA;
int tzm = ((double) avg \* 3 + TEZA) / 4;
cout << "\n" << "Your average grade at " << sub << " is " << tzm << "\n" << "\n";
cout << "You got the following mark: ";
if (tzm >= 9 && tzm <= 10) cout << "A" << "\n";
else if (tzm >= 8 && tzm <= 9) cout << "B" << "\n";
else if (tzm >= 7 && tzm <= 8) cout << "C" << "\n";
else if (tzm >= 6 && tzm <= 7) cout << "D" << "\n";
else if (tzm >= 5 && tzm <= 6) cout << "E" << "\n";
else if (tzm < 5) cout << "F" << "\n";
cout << "DO YOU PASS: " << "\n";
if (tzm >= 5) cout << "Yes." << "\n";
else cout << "No." << "\n";
}
else
{
cout << "\n" << "Average at " << sub << " is " << avg << "\n" << "\n";
cout << "You got the following mark: ";
if (avg >= 9 && avg <= 10) cout << "A" << "\n";
else if (avg >= 8 && avg <= 9) cout << "B" << "\n";
else if (avg >= 7 && avg <= 8) cout << "C" << "\n";
else if (avg >= 6 && avg <= 7) cout << "D" << "\n";
else if (avg >= 5 && avg <= 6) cout << "E" << "\n";
else if (avg < 5) cout << "F" << "\n";
cout << "\n" << "DO YOU PASS?: " << "\n";
if (avg >= 5) cout << "Yes." << "\n";
else cout << "No." << "\n";
}
}
```
Upvotes: 0 <issue_comment>username_2: 1. Instead of repeating code, have methods such as `PrintGrade()` and `VerifyPassFail()` and call them each time you want to use that chunk of code.
2. Do not declare `int TEZA` earlier, declare it when the `if condition` passes, because only then would you really need to use it.
3. Like the other answer mentioned, you can use a container to hold `m1,m2,m3 and m4`. I would suggest a `std::vector`. If you want to expand to more subjects, all you would have to do is to increase the range of the loop.
4. Additional remark would be not use `using namespace std`, instead go with prefixing the `std` tag such as `std::vector`, `std::cout` etc..
```
#include
#include
#include
void PrintGrade( int inInput )
{
std::cout << "You got the following mark: ";
if (inInput >=9 && inInput <=10)
std::cout<<"A"<<"\n";
else if (inInput >=8 && inInput <=9)
std::cout<<"B"<<"\n";
else if (inInput >=7 && inInput <=8)
std::cout<<"C"<<"\n";
else if (inInput >=6 && inInput <=7)
std::cout<<"D"<<"\n";
else if (inInput >=5 && inInput <=6)
std::cout<<"E"<<"\n";
else if(inInput <5)
std::cout<<"F"<<"\n";
}
void VerifyPassFail( int inInput )
{
std::cout<<"\n"<<"DO YOU PASS?: "<<"\n";
if (inInput >=5)
std::cout<<"Yes."<<"\n";
else
std::cout<<"No."<<"\n";
}
int main()
{
std::string sub, tf;
int sum = 0;
int TEZA;
std::vector marksList;
double avg, tzm;
std::cout << "SIMPLE AVERAGE CALCULATOR";
std::cout << "\n" << "\n" << "Subject at hand?: ";
std::cin >> sub;
std::cout << "\n" << "Input the FOUR marks you'd like verified: " << "\n";
for(int i = 1; i < 5; i++)
{
int marks;
std::cout<<"\n"<<"M"<>marks;
marksList.push\_back(marks);
}
std::cout << "\n" << "Would you like to include the TEZA grade?(Y/N): ";
std::cin >> tf;
for( int i : marksList )
{
sum += i;
}
avg = (double) sum / 4;
if (tf == "Y" | tf == "y")
{
std::cout << "What is the TEZA grade?: ";
std::cin >> TEZA;
int tzm = ((double) avg \* 3 + TEZA) / 4;
std::cout << "\n" << "Your average grade at " << sub << " is " << tzm << "\n"
<< "\n";
std::cout << "You got the following mark: ";
PrintGrade(tzm);
VerifyPassFail(tzm);
}
else
{
std::cout << "\n" << "Average at " << sub << " is " << avg << "\n" << "\n";
PrintGrade(avg);
VerifyPassFail(avg);
}
}
```
Upvotes: 1 [selected_answer]<issue_comment>username_3: If I wanted it to be short, I'd probably write something like this:
```
#include
#include
#include
#include
#include
template T get(std::string const &prompt) {
std::cout << prompt;
T ret;
std::cin >> ret;
return ret;
}
int main() {
auto sub = get("SIMPLE AVERAGE CALCULATOR\n\nSubject at hand?: ");
std::cout << "\nPlease enter the FOUR marks you'd like verified:\n";
std::vector m;
for (int i = 0; i < 4; i++)
m.push\_back(get("M" + std::to\_string(i + 1) + ": "));
if (std::toupper(get("\nWould you like to include the TEZA grade?(Y/N): ")) == 'Y')
m.push\_back(get("What is the TEZA grade?: "));
auto tzm = std::accumulate(m.begin(), m.end(), 0.0) / m.size();
char const \*yn[] = { "No", "Yes" };
std::cout << "\nYour average grade at " << sub << " is " << tzm
<< "\n\nYou got the following mark: " << "FFFFFEDCBAA"[(int)tzm]
<< "\nDo you pass?\n" << yn[tzm >= 5] << "\n";
}
```
I definitely wouldn't turn this in for homework though--I'd not only get a lousy grade, but probably be thrown in an insane asylum as well.
Although the preceding code overdoes some good things, there are some good things hidden in that mess. First of all, using a vector instead of an array. There's almost no circumstance in which it makes real sense to use a raw array in C++. You can use `std::array` or you can use `std::vector` (or any number of other collections), but a raw rarely makes much sense. In this case, we might be dealing with either of two different sizes of collections (i.e., grades including or not including a TEZA grade), so a `vector` makes more sense.
Since a vector keeps track of its own size, we can simplify the code to compute the average by collecting all the grades, *then* computing the average based on the number of grades collected.
We can simplify computation quite a bit by starting with some array-like object of the letter grades, and using the computed numeric grade to index into those letter grades. Using `"FFFFFEDCBAA"[(int)tzm]` is going overboard with terseness. In real life, something like this is more appropriate:
```
std::string letter_grades = ""FFFFFEDCBAA";
std::cout << letter_grades[static_cast(tzm)];
```
At a higher level, the code does quite a bit of the same basic sequence of operations: print out a prompt to the user, then read in a value of some sort. Moving that sequence into a function so we can avoid repeating nearly identical code for the same sequence is (again) quite a good thing to do.
The code in the question also breaks things that can be defined as a single string literal into multiple individual pieces for no apparent reason. I guess *somebody* might find it more understandable that way, but I'm uncertain about who would, or why--it doesn't look like an improvement to me.
It can make sense to break things down on a line-by-line basis, something like this:
```
auto sub = get(
"SIMPLE AVERAGE CALCULATOR\n"
"\n"
"Subject at hand?: ");
```
The compiler with merge adjacent string literals like this into a single literal, so this ends up exactly like the code shown above--but some find it more readable. Another possibility is to use a raw string:
```
auto sub = get(
R"("SIMPLE AVERAGE CALCULATOR
Subject at hand?: )");
```
A raw string literal takes everything exactly as-is, including new-line characters, so we can represent a new-line as an actual new-line instead of encoding it as `\n`. I don't find it a huge benefit in this particular situation, but I can see where some people might prefer it.
In the final analysis, the *length* of code is rarely very relevant--but having (for example) repetition in the code does matter--a lot. Getting rid of repetition is definitely a good thing.
Likewise, to the extent we can represent the task in terms of data rather than control flow, that's almost always a win as well.
Upvotes: 1
|
2018/03/14
| 1,132 | 3,385 |
<issue_start>username_0: Below is the response from my `API`
```
"attributes": {
"original-data": "{\"name\":\"Foobarz\",\"updated_at\":\"2018-02-27
08:06:14 UTC\"}",
"new-data": "{\"name\":\"Foobar\",\"updated_at\":\"2018-02-27
10:55:17 UTC\"}",
"event-name": "update",
"ip-address": "172.16.58.3",
"user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_2)
AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.167
Safari/537.36",
"created-at": "2018-02-27T10:55:17.477Z",
"updated-at": "2018-02-27T10:55:17.477Z"
},
```
Below is my model hook on my `route.js`
```
model() {
return this.store.findRecord('audit-trail', 41, {include: 'audit-trailable'});
}
```
When i do `{{model.eventName}}` it show the event-name information which is `update`. However, when i did the `{{model.newData}}` it retrun a `[object Object]`. My question is, how can I display the `new-data` attribute filed value `name` and `updated_at`?
[](https://i.stack.imgur.com/DXsEM.png)<issue_comment>username_1: Hy there. The best, if you can afford it, is to use <https://github.com/lytics/ember-data-model-fragments>
and so : models/audit-trial.js
```
import DS from 'ember-data';
import MF from 'ember-data-model-fragments';
export default DS.Model.extend({
whatever_simple_attr: DS.attr(),
new_data: Mf.fragment('new-data'),
});
```
with : models/new-data.js
```
import MF from 'ember-data-model-fragments';
import DS from 'ember-data';
export default MF.Fragment.extend({
name: attr(),
updated_at: attr('date')
});
```
*edit : adding serializers* , again : not really tested, but the idea is here ->
serializers/new-data.js (using underscore.js lib)
>
> important : I'm using snake\_case attributes in my models, maybe your code will be different if you are using lowerCamelCase.
>
>
>
```
import JSONSerializer from 'ember-data/serializers/json';
/* global _ */
export default JSONSerializer.extend({
normalize(typeClass, hash) {
_.forEach(hash, (value, key) => {
hash[key.underscore()] = value;
// prevent kinda twins (my_key and my-key)
if (key.underscore() !== key) {
delete hash[key];
}
});
return this._super.apply(this, arguments);
}
});
```
serializers/audit-trial.js
```
import DS from 'ember-data';
export default DS.JSONAPISerializer.extend({
normalize(_, data) {
data.attributes["new-data"] = JSON.parse(data.attributes["new-data"])
// maybe this too, with associated model and serializer
data.attributes["original-data"] = JSON.parse(data.attributes["original-data"])
return this._super(...arguments);
},
});
```
Upvotes: 2 <issue_comment>username_2: Ember-data-model-fragments are ok. Or you can use model like:
```
DS.Model.extend({
originalData: DS.attr("string"),
newData: DS.attr("string"),
...
```
and then use in your component (or controller):
```
originalData = JSON.stringify(model.get("originalData"))
```
in your template:
```
{{originalData}}
```
Upvotes: 0 <issue_comment>username_3: If you do a `{{model.newData.name}}` in your template do things work? Ember Data’s default approach to to any object is to just make it available as you send it from the backend. That means it will have underscored keys (I.e. `model.newData.updated_at`) but should work.
Upvotes: 0
|
2018/03/14
| 989 | 3,083 |
<issue_start>username_0: I have a simple ellipse (red) and I want to rotate the ellipse.
The following code only return flatten ellipse (blue) but it does not rotate:
import tkinter as tk
import numpy as np
import math
```
def rotate(points, angle):
new_points = list(points)
rad = angle * (math.pi/180)
cos_val = math.cos(rad)
sin_val = math.sin(rad)
for coords in new_points:
x_val = coords[0]
y_val = coords[1]
coords[0] = x_val * cos_val - y_val * sin_val
coords[1] = x_val * sin_val + y_val * cos_val
return new_points
window = tk.Tk()
window.geometry("500x300")
canvas = tk.Canvas(window, height=300, width=500)
canvas.grid(row=0, column=0, sticky='w')
# draw ellipse
size=80
x0,y0=100,100
width,height=0.25*size,0.5*size
x1,y1=x0+width,y0+height
xc=x0+width/2
yc=y0+height/2
ellipse = canvas.create_oval([x0, y0, x1,y1],fill='blue')
#draw rotated ellipse
coord1=canvas.coords(ellipse)
points=[[coord1[0],coord1[1]],[coord1[2],coord1[3]]]
point2=rotate(points,30)
coord2 = [item for sublist in point2 for item in sublist]
ellipse2 = canvas.create_oval(coord2,fill='red')
window.mainloop ()
```
Here is the result:
[](https://i.stack.imgur.com/2LDk0.jpg)
The red ellipse supposed to be rotated by 30 degree but instead of rotated, it just get flattened.
Question: How to rotate the ellipse in tkinter canvas?
Notes:
* I am using python 3.6
* I checked stackoverflow on [similar question](https://stackoverflow.com/questions/47122065/tkinter-py3-how-to-make-a-rotation-animation) and it has no correct answer.
* unlike polygon that we can simply rotate each vertices, ellipse has no vertex.<issue_comment>username_1: There are 2 ways that I know of 1) plot every point on the edge of the ellipse. There are pages on the web that show how to calculate all of the points 2) save as an image and use tkinter's PIL library to rotate the image.
Upvotes: 0 <issue_comment>username_2: The `oval` item of tkinter canvas is not rotatable as an `oval`.
If you look at the docs, like effbot.org, you'll see that some items are created with a first `position` arg (a single point, like `text`), some with a `bbox` arg (two points, like `rectangle` and `oval`), and some with `coords` (variable, two or more points, like `line` and `polygon`).
You can rotate the `coords` items by (1) calculating new coords and (2) updating the item with the new coords, using the `coords()` method.
For the rest of the items, you're out of luck, except for `text` which supports an `angle` attribute which you can set with `itemconfig(item, angle=new_angle)`
But all hope is not lost. You can convert a `rectangle` or `oval` into a `polygon` (by creating a new `polygon` to replace your old `bbox` item, and then you'll be able to rotate the new item. With `rectangle`, it's easy-peasy. With `oval`, it's much trickier, as you have to simulate the `oval` using many, many `polygon` coordinates for it to look good.
Upvotes: 1
|
2018/03/14
| 508 | 1,962 |
<issue_start>username_0: ```
import java.util.Scanner;
public class Box {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int length;
int width;
int rectangle;
// input and output here
System.out.print("Input the width of the box: ");
width = keyboard.nextInt();
System.out.print("Input the length of the box: ");
length = keyboard.nextInt();
// use nested for loops here
}
}
```
This is just what the base of my program is, I need a program that prints a solid rectangle out of asterisks using nested for loops.<issue_comment>username_1: There are 2 ways that I know of 1) plot every point on the edge of the ellipse. There are pages on the web that show how to calculate all of the points 2) save as an image and use tkinter's PIL library to rotate the image.
Upvotes: 0 <issue_comment>username_2: The `oval` item of tkinter canvas is not rotatable as an `oval`.
If you look at the docs, like effbot.org, you'll see that some items are created with a first `position` arg (a single point, like `text`), some with a `bbox` arg (two points, like `rectangle` and `oval`), and some with `coords` (variable, two or more points, like `line` and `polygon`).
You can rotate the `coords` items by (1) calculating new coords and (2) updating the item with the new coords, using the `coords()` method.
For the rest of the items, you're out of luck, except for `text` which supports an `angle` attribute which you can set with `itemconfig(item, angle=new_angle)`
But all hope is not lost. You can convert a `rectangle` or `oval` into a `polygon` (by creating a new `polygon` to replace your old `bbox` item, and then you'll be able to rotate the new item. With `rectangle`, it's easy-peasy. With `oval`, it's much trickier, as you have to simulate the `oval` using many, many `polygon` coordinates for it to look good.
Upvotes: 1
|
2018/03/14
| 593 | 2,955 |
<issue_start>username_0: Is it wrong to use `notifyAll()` inside the loop in a multiple producer-consumer problem in Java?
Here is the code snippet which I am talking about.
```
public void run() {
while(producer_counter <= 64) {
synchronized(list) {
threadId1 = "Producer " + Thread.currentThread().getName();
//Buffer size is 8
while(list.size() >= 8) {
System.out.println( "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
System.out.println(threadId1+ " found the buffer is full & waiting for a Consumer to consume.");
System.out.println( "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
try {
list.wait();
list.notifyAll();
}
catch (InterruptedException ie) {
ie.printStackTrace();
}
}
System.out.println(threadId1+ " produced item " + producer_counter);
//Adding the items produced to the list.
list.add(producer_counter);
producer_counter++;
//Invoking notify
list.notifyAll();
}
}
}
}
```<issue_comment>username_1: You should not use list.notifyAll() in while loop.After adding the items produced to the list list.add(producer\_counter) you can use notify all.
```
// producer thread waits while list is full
while (list.size() >= 8){
list.wait();
}
// to insert the jobs in the list and plus 1 the counter
list.add(producer_counter);
producer_counter++;
// notifies the consumer threads that now it can start
//consuming
list.notifyAll();
```
Upvotes: 0 <issue_comment>username_2: `notifyAll()` is to notify all parties about changes in the state of the synchronized object. The first call, which is after `wait()`, is redundant because no state change happened. This call does not make the program wrong, but only causes waste of CPU cycles: when the buffer is full, `notifyAll()` is called and all other threads, waiting for the buffer's availability, go to processor only to call `notifyAll()` again and then call `wait()`. As a result, one processor in your machine will be always busy making unnecessary work.
BTW, you should not catch `InterruptedException` (or any other exception) if you don't know why it happened and what to do about it. If, like here, you cannot write `public void run() throws InterruptedException`, then write
```
} catch (InterruptedException ie) {
throw new RuntimeException(ie);
}
```
Instead of `RuntimeException`, better declare your own unchecked exception.
Upvotes: 1
|
2018/03/14
| 566 | 1,848 |
<issue_start>username_0: I came across this piece of code in Underscore.js, I want to convert this to vanilla javascript. Any idea on how to do that ?
```js
var makeLetters = function(word) {
return _.map(word.split(''), function(character) {
return { name: character, chosen: false };
});
}
```
This is the current output from the above function, I want to retain the same structure, except I want to accomplish this in regular javascript.
```
0: {name: "s", chosen: false, $$hashKey: "003"}
1: {name: "c", chosen: false, $$hashKey: "004"}
2: {name: "o", chosen: false, $$hashKey: "005"}
3: {name: "p", chosen: false, $$hashKey: "006"}
4: {name: "e", chosen: false, $$hashKey: "007"}
```<issue_comment>username_1: In ES 2015+
```
function makeLetters(word) {
return word.split('').map(v => { name: v, chosen: false });
}
```
In pre ES 5
```
function makeLetters(word) {
return word.split('').map(function(v) {
return { name: v, chosen: false };
});
}
```
Upvotes: -1 <issue_comment>username_2: ```js
// Your current Underscore code:
/*
var makeLetters = function(word) {
return _.map(word.split(''), function(character) {
return { name: character, chosen: false };
});
*/
// New ES6+ code:
const makeLetters = (word) => word.split('').map(character => ({ name: character, chosen: false }));
// If you aren't using ES6+:
var makeLetters = function(word) {
return word.split('')
.map(function(character) {
return { name: character, chosen: false };
});
};
```
Upvotes: 4 [selected_answer]<issue_comment>username_3: ```js
var makeLetterWord="scope";
var makeLettersSplit = makeLetterWord.split('').map(function(character) {
return { name: character, chosen: false };
});
console.log(makeLettersSplit );
```
Upvotes: 0
|
2018/03/14
| 690 | 2,801 |
<issue_start>username_0: I am having issues with Android Emulator since 7-8 days. At first it was not runing at all now reinstalling the emulator solved that issue but giving birth to new one.
Whenever I run the emulator it takes alot of time, almost 5-6 minutes and then shows an error: `Cold Boot: Snapshot doesn't exist`
After restarting several times now emulator runs but still shows the error in the beginning.<issue_comment>username_1: Quick Boot is not reliable when software rendering is enabled. If Quick Boot does not work, click Edit this AVD from the AVD Manager and change Graphics from either Automatic or Software to Hardware.
Source:
<https://developer.android.com/studio/run/emulator.html#quickboot-troubleshooting>
Upvotes: 3 <issue_comment>username_2: Resolve issue by:
\* Clean your project
\* Go to Window>AVD Manager>Delete and create a new AVD
\* Relaunch application, emulator will take a few minutes to load.
Upvotes: 1 <issue_comment>username_3: Today I have tried all methods, all stucks me.
1. I don't launch Android SDK Manager GUI, using `android` command is deprecated.
2. Android Studio does not open for disabling Cold Boot.
At last I found a solution, using CLI command:
```
emulator -avd YOUR_AVD_DEVICE_NAME -no-snapshot-save
```
Upvotes: 2 <issue_comment>username_4: I too faced this issue for a while and recently resolved it. Through reading other SO posts it definitely seems to be related to the snapshot that the Emulator is trying to boot from - as eluded to by **@username_1's** answer. Although I don't fully understand the cause for why this is happening (it happened to all of the AVDs I had saved) I've resolved it by configuring my AVD to perform a "cold boot" instead of a "quick boot" whenever I launch it. This solves the "Snapshot doesn't exist" message & the emulator boots as expected, allowing you to run and test your application.
**Steps to fix the issue:**
1. Open the Android Virtual Device Manager (Tools -> AVD Manager)
2. Select the Virtual Device you'd like to use & click "Edit this AVD" (the Pencil icon)
3. The "Virtual Device Configuration" window should now be open. Click the "Show Advanced Settings" button at the bottom of the window and scroll to the "Emulated Performance" section
4. You'll see an option called "Boot option" which is typically set to "Quick Boot" by default - switch this to "Cold boot" and click "Finish".
Start the Virtual Device now (close it if you previously had it running whilst making these changes so that they take effect). The "Snapshot doesn't exist" message won't appear and your emulator will start as expected.
The only downside to this option is that the state of the device when you last used it won't be stored i.e. your apps you previously had open.
Upvotes: 5 [selected_answer]
|
2018/03/14
| 1,541 | 4,495 |
<issue_start>username_0: I've been searching for a simpler way to do this, but i'm not sure what search parameters to use. I have a floating point number, that i would like to round, convert to a string, then specify a custom format on the string. I've read through the .format docs, but can't see if it's possible to do this using normal string formatting.
The output i want is just a normal string, with spaces every three chars, except for the last ones, which should have a space four chars before the end.
For example, i made this convoluted function that does what i want in an inefficient way:
```
def my_formatter(value):
final = []
# round float and convert to list of strings of individual chars
c = [i for i in '{:.0f}'.format(value)]
if len(c) > 3:
final.append(''.join(c[-4:]))
c = c[:-4]
else:
return ''.join(c)
for i in range(0, len(c) // 3 + 1, 1):
if len(c) > 2:
final.insert(0, ''.join(c[-3:]))
c = c[:-3]
elif len(c) > 0:
final.insert(0, ''.join(c))
return(' '.join(final))
```
e.g.
```
>>> my_formatter(123456789.12)
>>> '12 345 6789'
>>> my_formatter(12345678912.34)
>>> '1 234 567 8912'
```
Would really appreciate guidance on doing this in a simpler / more efficient way.<issue_comment>username_1: Here is a pretty simple solution using a loop over the elements in the reverse order such that counting the indices is easier:
```
num = 12345678912.34
temp = []
for ix, c in enumerate(reversed(str(round(num)))):
if ix%3 == 0 and ix !=0: temp.extend([c, ' '])
else: temp.extend(c)
''.join(list(reversed(temp)))
```
Output:
>
> '1 234 567 8912'
>
>
>
Using list comprehensions we can do this in a single very confusing line as
```
num = 12345678912.34
''.join(list(reversed(list(''.join([c+' ' if(ix%3 == 0 and ix!=0) else c for ix, c in enumerate(reversed(str(round(num))))])))))
```
>
> '1 234 567 8912'
>
>
>
Upvotes: 2 <issue_comment>username_2: Took a slightly different angle but this uses a third party function [`partition_all`](https://toolz.readthedocs.io/en/latest/api.html#toolz.itertoolz.partition_all). In short, I use it to group the string into groups of 3 plus the final group if there are less than 3 chars. You may prefer this as there are no for loops or conditionals but it's basically cosmetic differences.
```
from toolz.itertoolz import partition_all
def simpleformat(x):
x = str(round(x))
a, b = x[:-4], x[-4:]
strings = [''.join(x[::-1]) for x in reversed(list(partition_all(3, a[::-1])))]
return ' '.join(strings + [b])
```
Upvotes: 2 <issue_comment>username_3: Try this:
```
def my_formatter(x):
# round it as text
txt = "{:.0f}".format(x)
# find split indices
splits = [None] + list(range(-4, -len(txt), -3)) + [None]
# slice and rejoin
return " ".join(
reversed([txt[i:j] for i, j in zip(splits[1:], splits[:-1])]))
```
Then
```
>>> my_formatter(123456789.1)
12 345 6789
>>> my_formatter(1123456789.1)
112 345 6789
>>> my_formatter(11123456789.1)
1 112 345 6789
```
Upvotes: 2 <issue_comment>username_4: Another approch is to use locale if available on your system of course, and use format.
```
import locale
for v in ('fr_FR.UTF-8', 'en_GB.UTF-8'):
locale.setlocale(locale.LC_NUMERIC, v)
print(v, '>> {:n}'.format(111222333999))
```
Upvotes: 2 <issue_comment>username_5: May as well share another slightly different variant, but still can't shake the feeling that there's some sublime way that we just can't see. Haven't marked any answers as correct yet, because i'm convinced python can do this in a simpler way, somehow. What's also driving me crazy is that if i remember correctly VB's format command can handle this (with a pattern like "### ####0"). Maybe it's just a case of not understanding how to use Python's .format correctly.
The below accepts a float or decimal and a list indicating split positions. If there are still digits in the string after consuming the last split position, it re-applies that until it reaches the start of the string.
```
def format_number(num, pat, sep=' '):
fmt = []
strn = "{:.0f}".format(num)
while strn:
p = pat.pop() if pat else p
fmt.append(strn[-p:])
strn = strn[:-p] if len(strn) > p else ''
return sep.join(fmt[::-1])
>>> format_number(123456789, [3, 4])
>>> '12 345 6789'
>>> format_number(1234567890, [3])
>>> '1 234 567 890'
```
Upvotes: 1
|
2018/03/14
| 907 | 3,286 |
<issue_start>username_0: Initially my table has no data and I get "No data available in table" which is the expected functionality.
I'd like to have no text or row created as I will be populating the table via Ajax depending on user action.
Is there a setting to stop the display of this row in the table? I can't seem to find one. This code works but the first row reads "No data available in table". This is the jQuery code:
```
$.ajax({
type: 'GET',
url: '/Home/postInformationofConferenceTitle',
dataType: "JSON",
success: function (data) {
$.post("/Home/selectRooms", { xtitle: data.xglobalTitle }, function (data) {
var ndx = 0;
$.each(data.xroom_name, function (key, value) {
var Xroom_name = data.xroom_name[ndx];
var Xroom_plan = data.xroom_plan[ndx];
var column =
('|' +
' ' +
'' +
'...' +
'' +
' |' +
' ' + Xroom\_name + ' |' +
' ' +
'' +
'' +
' |' +
'
');
document.getElementById('colmn').innerHTML = document.getElementById('colmn').innerHTML + column;
ndx++;
});
});
}
})
```<issue_comment>username_1: I guess you might be looking at the language settings of datatables.
```
language : {
"zeroRecords": " "
},
```
(Note the space between " ". (Its a hack but found it to be useful for now.)
```js
$(document).ready(function () {
var serverData = [
]
var table = $('#example').DataTable({
language : {
"zeroRecords": " "
},
data: serverData,
columns: [
{ data: "name" },
{ data: "age" },
{ data: "isActive" },
{ data: "friends" },
],
'columnDefs': [{
'targets': 2,
'render': function (data, type, full, meta) {
let checked = ''
if (data) {
return '';
}
else {
return '';
}
return data;
}
},
{
'targets': 3,
"render": function (data, type, full, meta) {
var selectInitial = "";
var selectClosing = "";
var options = '';
$.each(data, function (key, value) {
options = options+""+value.name+"";
});
return selectInitial+options+selectClosing;
}
}
],
});
});
```
```html
| name | age | isActive | friends |
| --- | --- | --- | --- |
```
Upvotes: 4 <issue_comment>username_2: It works for me.
```
var someTableDT = $("#some-table").on("draw.dt", function () {
$(this).find(".dataTables_empty").parents('tbody').empty();
}).DataTable(/*init object*/);
```
Upvotes: 3 [selected_answer]<issue_comment>username_3: Below worked for me:
```
$(document).ready(function () {
$("#TABLE_ID").DataTable();
$(".dataTables_empty").empty();
});
```
Upvotes: 1 <issue_comment>username_4: Next CSS worked for me to totally hide that block (not only delete text):
```
.dataTables_empty
{
display:none;
}
```
Upvotes: 0 <issue_comment>username_5: ```
$('#table').dataTable({
//initialization params as usual
fnInitComplete: function () {
if ($(this).find(".dataTables_empty").length == 1) {
$(this).parent().hide();
}
}
});
```
This will hide only in that case when there is no data.
Upvotes: 0
|
2018/03/14
| 507 | 1,796 |
<issue_start>username_0: Code is working for first 3 but not for last 3. What can be possible reasons?
```js
$(document).ready(function(){
$("section[class^='steps-']").hide();
});
```
```html
Hidden
======
hidden
======
not hiding
==========
not hiding
==========
```<issue_comment>username_1: The reason it those two elements also contain another class.
In this case [attribute-contains-selector](https://api.jquery.com/attribute-contains-selector/) selector that will check if a value contains a given substring.
```js
$(document).ready(function() {
$("section[class*='steps-']").hide();
});
```
```html
Hidden
======
hidden
======
not hiding
==========
not hiding
==========
```
Upvotes: 2 <issue_comment>username_2: You should use `*`, it will check the contains query in the class names string,
```js
$(document).ready(function(){
$("section[class*='steps-']").hide();
});
```
```html
Hidden
======
hidden
======
not hiding
==========
not hiding
==========
```
Upvotes: 0 <issue_comment>username_3: classes that starts with `steps-`
```
$("section[class^='steps-']").hide();
```
classes that contain `steps-`
```
$("section[class*='steps-']").hide();
```
classes that contain `steps-` but not start with `steps-`
```
$("section[class*=' steps-']").hide();//observe the space
```
and you need contains:
```js
$(document).ready(function(){
$("section[class*='steps-']").hide();
});
```
```html
Hidden
======
hidden
======
not hiding
==========
not hiding
==========
```
Upvotes: 1 <issue_comment>username_4: ```js
$(document).ready(function(){
$("section[class^='steps-']").hide();
});
```
```html
Hidden
======
hidden
======
not hiding
==========
not hiding
==========
```
Upvotes: 0
|
2018/03/14
| 638 | 1,947 |
<issue_start>username_0: In pd.Grouper we can group by time, for example using 10s
```
Time Count
10:05:03 2
10:05:04 3
10:05:05 4
10:05:11 3
10:05:12 4
```
Will provide the result of:
```
Time Count
10:05:10 9
10:05:20 7
```
---
I'm looking for the other way around. Can I group the time by count, for example, using 5
```
Count Time (s)
5 (4-3)=1s
5 (11-5)=6s
5 (12-11)=1s
```
---
Thanks a bunch!<issue_comment>username_1: The reason it those two elements also contain another class.
In this case [attribute-contains-selector](https://api.jquery.com/attribute-contains-selector/) selector that will check if a value contains a given substring.
```js
$(document).ready(function() {
$("section[class*='steps-']").hide();
});
```
```html
Hidden
======
hidden
======
not hiding
==========
not hiding
==========
```
Upvotes: 2 <issue_comment>username_2: You should use `*`, it will check the contains query in the class names string,
```js
$(document).ready(function(){
$("section[class*='steps-']").hide();
});
```
```html
Hidden
======
hidden
======
not hiding
==========
not hiding
==========
```
Upvotes: 0 <issue_comment>username_3: classes that starts with `steps-`
```
$("section[class^='steps-']").hide();
```
classes that contain `steps-`
```
$("section[class*='steps-']").hide();
```
classes that contain `steps-` but not start with `steps-`
```
$("section[class*=' steps-']").hide();//observe the space
```
and you need contains:
```js
$(document).ready(function(){
$("section[class*='steps-']").hide();
});
```
```html
Hidden
======
hidden
======
not hiding
==========
not hiding
==========
```
Upvotes: 1 <issue_comment>username_4: ```js
$(document).ready(function(){
$("section[class^='steps-']").hide();
});
```
```html
Hidden
======
hidden
======
not hiding
==========
not hiding
==========
```
Upvotes: 0
|
2018/03/14
| 983 | 2,911 |
<issue_start>username_0: I have data below :
```
Array(
[A] => Array
(
[AA] => 10
)
[B] => Array
(
[BA] => 5
[BB] => 1
[BC] => -2
)
[C] => Array
(
[CA] => 3
[CB] => 0
)
)
```
I want to sum the value of second element my array (BA,BB,BC, etc) like this :
```
Array(
[A] => 10
[B] => 4
[C] => 3
)
```
I've tried to do with foreach (I'm using php as my platform) but the result is wrong, can someone give me explanation and the logic to solve this? thanks<issue_comment>username_1: You can loop thru your array and use `array_sum`
```
$arr = array(
"A" => array
(
"AA" => 10,
),
"B" => array
(
"BA" => 5,
"BB" => 1,
"BC" => -2
),
"C" => array
(
"CA" => 3,
"CB" => 0
)
);
$result = array();
foreach( $arr as $key => $val ){
$result[$key] = array_sum ( $val );
}
echo "
```
";
print_r( $result );
echo "
```
";
```
This will result to:
```
Array
(
[A] => 10
[B] => 4
[C] => 3
)
```
Doc: <http://php.net/manual/en/function.array-sum.php>
Upvotes: 3 [selected_answer]<issue_comment>username_2: This should work for arrays like the one of your example:
```
$arr = array(
"A" => array
(
"AA" => 10,
),
"B" => array
(
"BA" => 5,
"BB" => 1,
"BC" => -2
),
"C" => array
(
"CA" => 3,
"CB" => 0
)
);
$res = array();
foreach($arr as $key => $value) {
foreach($value as $number) {
(!isset($res[$key])) ?
$res[$key] = $number :
$res[$key] += $number;
}
}
echo "
```
";
print_r( $res );
echo "
```
";
```
This is working without using an inbuilt function.
Upvotes: 1 <issue_comment>username_3: **if you want sum column**
```
php
$array = array
(
"A"=array
(
"AA" => 10,
),
"B"=>array
(
"BA" => 5,
"BB" => 1,
"BC" => -2
),
"C"=>array
(
"CA" => 3,
"CB" => 0
)
);
foreach ($array as $key=>$value)
{
$mehrdad[]=$key;
}
foreach ($mehrdad as $key1=>$value1)
{
$arrays=$array[$value1];
foreach ($arrays as $key2=>$value2)
{
$mehrdadi[]=$key2;
}
}
$mehrdadend=array_unique($mehrdadi);
$mehrdadis = array();
foreach ($mehrdadend as $key3=>$value3)
{
$sum=array_sum(array_column($array, $value3));
$mehrdadis[$value3] = $sum;
}
print_r($mehrdadis);
?>
```
**Result**
```
Array
(
[AA] => 10
[BA] => 5
[BB] => 1
[BC] => -2
[CA] => 3
[CB] => 0
)
```
Upvotes: 0
|
2018/03/14
| 1,413 | 5,937 |
<issue_start>username_0: I have the following class method for creating a Twig environment object.
```
public function getView($filename,
array $customFunctions = null,
array $customFunctionArgs = null,
$debug = false) {
$loader = new \Twig_Loader_Filesystem('/App/Views/Templates/Main');
$twig = new \Twig_Environment($loader);
if (isset($customFunctions)) {
foreach ($customFunctions as $customFunction) {
$customFunction['name'] = new \Twig_SimpleFunction($customFunction['name'],
function ($customFunctionArgs) {
return $customFunction['method']($customFunctionArgs);
});
$twig->addFunction($customFunction['name']);
}
}
// Check debugging option
if ($debug == true && !$twig->isDebug()) {
$twig->enableDebug();
$twig->addExtension(new \Twig_Extension_Debug());
} elseif (!$debug && $twig->isDebug()) {
$twig->disableDebug();
}
$template = $twig->load($filename);
return $template;
}
```
Problem is, I don't understand how to pass values in order to make this work dynamically and keep all the objects in context and scope. For instance, here is how I'm trying to use it but can't pass the variables as a reference I guess?
```
$customFunctions = ['name' => 'customFunctionName',
'method' => $Class->method($arg)];
$customFunctionArgs = [$arg];
$template = $View->getView('template.html.twig', $customFunctions, $customFunctionArgs, true);
```
My environment is PHP 5.6 & Twig 1.35.0. I suppose this is not a Twig specific question per se, but more of how to use class objects within other classes/methods.<issue_comment>username_1: There are slight flaws in how you construct the custom functions data array and the loop that injects them into the template.
* The custom functions should be a three dimensional array
```
$customFunctions = [
[ // notice the extra level, allowing you to access the name
'name' => 'customFunctionName',
'method' => function() { return 'wat'; }
// you need to pass a callable, not the result of a call
]
];
```
---
* The scope is not inherited like you seem to think it is, you need to `use()` variables you intend to access. I personnally would not overwrite the 'name' value of the array, but that's uncanny paranoia of internal side effects, it seems to work in practice.
```
if (isset($customFunctions)) {
foreach ($customFunctions as $customFunction) {
$customFunction['name'] = new \Twig_SimpleFunction(
$customFunction['name'],
function () use ($customFunctionArgs, $customFunction) {
return $customFunction['method']($customFunctionArgs);
});
$twig->addFunction($customFunction['name']);
}
}
```
---
* You might need to add looping over `$args` so that the correct args are sent to the correct function (send `$args[0]` to `$customFunctions[0]` etc.).
Note that this prevents you from sending a parameter into your custom function unless you add it in the loop:
```
function ($templateArg) use ($customFunctionArgs, $customFunction) {
return $customFunction['method']($customFunctionArgs, $templateArg);
}
```
Here is a [gist](https://gist.github.com/Zvax/99a032a3787de582a433f635590c265e) with tests if you're interested.
Upvotes: 1 [selected_answer]<issue_comment>username_2: <NAME>'s answer helped me find a solution to this problem. However, I feel the need to post an answer with all the missing pieces to the puzzle for anyone that needs a solution for this.
I believe it will make more sense if I start at the end and explain to the beginning. When creating your array, there are several things to consider.
1. Any class objects that are needed for the function have to be declared inside a `use()` with the closure.
2. Any arguments for the custom function must be declared as a function parameter for the closure. This will allow you to declare them later.
3. I ended up adding a sub-array with the arguments I needed for each custom function, that way I don't need to iterate over them separately.
```
$customFunctions = [
[
'name' => 'customFunction',
'method' => function($arg1, $arg2) use($Class) {
return $Class->customFunction($arg1, $arg2);
},
'arguments' =>
[
'arg1', 'arg2'
]
]
];
$template = $View->getView(
'template.html.twig',
true,
$customFunctions
);
echo $View->renderView($template);
```
Based on this code (reflective of question above), I had to make some notable modifications.
```
if (isset($customFunctions)) {
foreach ($customFunctions as $index => $customFunction) {
if (isset($customFunctions['arguments'])) {
$arguments = $customFunctions['arguments'];
} else {
$arguments = [];
}
$twigFunction = new \Twig_SimpleFunction(
$customFunction['name'],
function (...$arguments) use ($customFunction) {
return $customFunction['method'](...$arguments);
});
$twig->addFunction($twigFunction);
}
}
```
You can do this whatever way works for you, but there are important things to consider which I struggled with. Once again, your arguments MUST go into the function parameters. `function (...$arguments) use ($customFunction)`. Your custom function will be passed in the `use()`. In order to actually pass the arguments in the closure, you must use `...` to unpack them (as an array). This applies to PHP 5.6+. It allows the arguments to be dynamically expanded to the correct amount, otherwise you will get `missing argument` errors.
Upvotes: 1
|
2018/03/14
| 645 | 1,519 |
<issue_start>username_0: I have a dictionary that looks like:
```
the 117
to 77
. 77
, 56
a 47
is 46
and 41
that 39
...
```
I wanted to divide each number in the dictionary by the max value.. so I did this:
```
count_values = (count.values())
newValues = [x / max(count_values) for x in count_values]
```
I want to replace the values in the dictionary with newValues.
How can I do that?<issue_comment>username_1: Try using dictionary comprehension.
```
old_values = {'the': 117, 'to': 77, '.': 77, ',': 56, 'a': 46, 'is': 46, 'and': 41, 'that': 39}
m = max(old_values.values())
new_values = {k: v / m for k, v in old_values.items()}
```
This produces a dictionary like this:
```
{'the': 1.0,
'to': 0.6581196581196581,
'.': 0.6581196581196581,
',': 0.47863247863247865,
'a': 0.39316239316239315,
'is': 0.39316239316239315,
'and': 0.3504273504273504,
'that': 0.3333333333333333}
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: First, you probably don't want to compute `max(count_values)` over and over for each element, so do that once up-front:
```
max_value = max(count.values())
```
Now, if you actually need to modify the dict in-place, do it like this:
```
for key in count:
count[key] /= max_value
```
However, if you don't need to do that, it's usually cleaner to make a new dict via a comprehension, as in [username_1's great answer](https://stackoverflow.com/a/49269969/908494):
```
count = {key: value / max_value for key, value in count.items()}
```
Upvotes: 0
|
2018/03/14
| 2,030 | 6,985 |
<issue_start>username_0: Why is this program not working?
```
available_toppings = ["mushrooms", "olives", "green peppers", "pepperoni", "pineapple", "extra cheese"]
requested_toppings = ['mushrooms', 'olives', 'extra cheese']
if requested_toppings in available_toppings:
for requested_topping in requested_toppings:
print("Adding " + requested_topping.title() + ".")
print("Finalising your order.")
else:
print("sorry we dont have these toppings")
```
and the output is
```
sorry we dont have these toppings
```<issue_comment>username_1: It looks like you switched the order of the `for` loop and the `if` condition. Maybe you wanted the following:
* For each requested topping, check if it is in available toppings
Instead of checking if the whole requested list is in the other available list, you can try the following:
```
available_toppings = ["mushrooms", "olives", "green peppers", "pepperoni", "pineapple", "extra cheese"]
requested_toppings = ['mushrooms', 'olives', 'extra cheese']
for requested_topping in requested_toppings:
if requested_topping in available_toppings:
print("Adding " + requested_topping.title() + ".")
else:
print("sorry we dont have these toppings")
print("Finalising your order.")
```
Upvotes: 1 <issue_comment>username_2: You want to check that `requested_toppings` list is a subset of `available_toppings`.
You could use `set.issubset()` function.
```
available_toppings = ["mushrooms", "olives", "green peppers", "pepperoni", "pineapple", "extra cheese"]
requested_toppings = ['mushrooms', 'olives', 'extra cheese']
if set(requested_toppings).issubset(available_toppings):
for requested_topping in requested_toppings:
print("Adding " + requested_topping.title() + ".")
print("Finalising your order.")
else:
print("sorry we dont have these toppings")
```
This would result in
```
Adding Mushrooms.
Adding Olives.
Adding Extra Cheese.
Finalising your order.
```
If you replace, say, `olives` with `shrimps` in `requested_toppings` you would get
```
sorry we dont have these toppings
```
as expected.
Upvotes: 3 [selected_answer]<issue_comment>username_3: try this:
```
available_toppings = ["mushrooms", "olives", "green peppers", "pepperoni", "pineapple", "extra cheese"]
requested_toppings = ['mushrooms', 'olives', 'extra cheese']
hasItem = True
for requested_topping in requested_toppings:
if requested_topping not in available_toppings:
hasItem = False
if hasItem:
for requested_topping in requested_toppings:
print("Adding " + requested_topping.title() + ".")
print("Finalising your order.")
else:
print("sorry we dont have these toppings")
```
Upvotes: 0 <issue_comment>username_4: There are two beautiful functions in python, `all()` and `any()`. Try to use `all()`:
```
available_toppings = ["mushrooms", "olives", "green peppers", "pepperoni", "pineapple", "extra cheese"]
requested_toppings = ['mushrooms', 'olives', 'extra cheese']
if all(topping in available_toppings for topping in requested_toppings):
for requested_topping in requested_toppings:
print("Adding " + requested_topping.title() + ".")
print("Finalising your order.")
else:
print("sorry we dont have these toppings")
```
What's wrong with your code? You checking if list is an **element** of another list, like:
```
>>> [1,2] in [1,2,3]
False
>>> [1,2] in [[1,2],3]
True
```
Upvotes: 1 <issue_comment>username_5: Not exactly What you wanted, but very easy to adapt.
```
available_toppings = ["mushrooms", "olives", "green peppers", "pepperoni", "pineapple", "extra cheese"]
requested_toppings = ["mushrooms", "olives", "extra cheese", "onions"]
RQ = []
for requested in requested_toppings:
RQ.append(requested)
for available in available_toppings:
for R in RQ:
if R in available:print "We have :",R
if R not in available:print "Do not Have : ",R
```
```
RESULTS:
We have : mushrooms
We have : olives
We have : extra cheese
Do not Have : onions
```
Upvotes: 0 <issue_comment>username_6: For a different approach—probably not *better* than the existing answers, in fact probably *worse*—but it does demonstrate an interesting ideas in a simple way.
```
try:
output = []
# Notice that we're not pre-checking here. So this will
# work even if requested_toppings is a one-shot iterator.
for requested_topping in requested_toppings:
if requested_topping in available_toppings:
# Don't actually print, because that's irreversible;
# do it "off to the side" or "in a transaction" that we
# can "commit" or "rollback".
output.append("Adding " + requested_topping.title() + ".")
else:
# Here's where we "rollback"
raise KeyError(requested_topping)
except KeyError:
# Discard the "transaction" by just not doing anything with it.
# And now we're out of the "pure" section of the code, so we
# can do I/O without worrying.
print("sorry we dont have these toppings")
else:
# "Commit" by just printing the output.
print(*output, sep='\n')
# And again, we're out of the pure code now, so just print
print("Finalising your order.")
```
To explain a bit more:
The only tricky part of this problem is that you don't want to start adding toppings if you don't have all of them (because then you'd give the customer false hope—and you might have to throw away a whole pizza).
The obvious solution is just to check whether you have all the toppings in advance, by using a subset test (as in [<NAME>'s answer](https://stackoverflow.com/a/49269941/908494)) or an `all` loop (as in [username_4's](https://stackoverflow.com/a/49270015/908494)) or just a `for` statement. That works fine in this case, so that's what you should probably do.
But there are some problems where you can't do that. Maybe `requested_toppings` is an iterator that you either can't repeat, or would be very expensive to repeat. Or maybe it's very hard to test in advance, and all you can do is try all the operations and see if one of them fails. For those problems, you need some way to avoid doing expensive and irreversible things like adding pizza toppings or launching the missiles. That's when you use a solution like this one.
Of course you could do the same thing without an exception, just by using `break` for rollback and a `else` clause on the `for` for commit, but it seems like more people find `for`…`else` confusing than exceptions.
One last thing: All of the solutions, including mine, are a little better if you turn `available_toppings` into a set instead of a list. The only thing you're ever going to do with it is `in` tests, and that's what sets are made for. (And it's not only a conceptual difference, but a performance one—you can do `in` tests on a set in constant time, while with a list, it has to check all of the values for each test.)
Upvotes: 0
|
2018/03/14
| 217 | 727 |
<issue_start>username_0: For example we have:
```
name fruit
-------------
bill apple
bill orange
lily apple
emma orange
```
I only want to output a list of people who have apple as their ONLY attribute. so the list would only include Lily.
How would I do that?
Thanks guys!<issue_comment>username_1: You just need `GROUP BY`
```
SELECT name FROM
table t
GROUP BY name
HAVING COUNT (*) = 1 and
SUM(CASE WHEN fruit = 'apple' THEN 1 ELSE 0 END) = 1
```
Upvotes: 1 <issue_comment>username_2: Following code will be helpful to you,
```
select distinct name
from your_table_name a
where fruit = 'apple' and name not in (select name from your_table_name b where b.name = a.name and b.fruit!='apple')
```
Upvotes: 0
|
2018/03/14
| 819 | 3,223 |
<issue_start>username_0: I have next code. I am doing count to perform persist operation and fix transformations above. But I noticed that DAG and stages for 2 different count Jobs calls first persist twice (when I expect second persist method to be called in second count call)
```
val df = sparkSession.read
.parquet(bigData)
.filter(row => dateRange(row.getLong(5), lowerTimeBound, upperTimeBound))
.as[SafegraphRawData]
// So repartition here to be able perform shuffle operations later
// another transformations and minor filtration
.repartition(nrInputPartitions)
// Firstly persist here since objects not fit in memory (Persist 67)
.persist(StorageLevel.MEMORY_AND_DISK)
LOG.info(s"First count = " + df.count)
val filter: BaseFilter = new BaseFilter()
LOG.info(s"Number of partitions: " + df.rdd.getNumPartitions)
val rddPoints= df
.map(parse)
.filter(filter.IsValid(_, deviceStageMetricService, providerdevicelist, sparkSession))
.map(convert)
// Since we will perform count and partitionBy actions, compute all above transformations/ Second persist
val dsPoints = rddPoints.persist(StorageLevel.MEMORY_AND_DISK)
val totalPoints = dsPoints.count()
LOG.info(s"Second count = $totalPoints")
```
[](https://i.stack.imgur.com/uKZkG.png)
[](https://i.stack.imgur.com/QlAcM.png)<issue_comment>username_1: Here's is the whole scenario.
persist and cache are also the transformation in Spark. After applying any one of the stated transformation, one should use any action in order to cache an RDD or DF to the memory.
Secondly, The unit of cache or persist is "partition". When cache or persist gets executed it will save only those partitions which can be hold in the memory. The remaining partition which cannot be saved on the memory- whole DAG will be executed again once any new action will be encountered.
Upvotes: 0 <issue_comment>username_2: When you say StorageLevel.MEMORY\_AND\_DISK spark tries to fit all the data into the memory and if it doesn't fit it spills to disk.
Now you are doing multiple persists here. In spark the memory cache is LRU so the later persists will overwrite the previous cached data.
Even if you specify `StorageLevel.MEMORY_AND_DISK` when the data is evicted from cache memory by another cached data spark doesn't spill that to the disk. So when you do the next count it needs to revaluate the DAG so that it can retrieve the partitions which aren't present in the cache.
I would suggest you to use StorageLevel.DISK\_ONLY to avoid such re-computation.
Upvotes: 3 <issue_comment>username_3: try
```
val df = sparkSession.read
.parquet(bigData)
.filter(row => dateRange(row.getLong(5), lowerTimeBound, upperTimeBound))
.as[SafegraphRawData]
// So repartition here to be able perform shuffle operations later
// another transformations and minor filtration
.repartition(nrInputPartitions)
// Firstly persist here since objects not fit in memory (Persist 67)
df.persist(StorageLevel.MEMORY_AND_DISK)
```
Upvotes: -1
|
2018/03/14
| 310 | 1,245 |
<issue_start>username_0: In my work I have been told that need to use Fedora, I use vs code and when I want to update I got redirected to download a `.tar.gz` file.
What is the right way to install the newer version?<issue_comment>username_1: I'm having the same issue on OpenSuse 42.3. I did locate an RPM which updated the version but VS code continues to tell me that there is an available update. I used the instructions to add the repository and then install for my first install but Yast (update manager) does not suggest there is a update available. So I used a RPM I found on the MS site.
Hope someone can solve this issue for the both of us!
Upvotes: 0 <issue_comment>username_2: Well it seems I have found the answer for my particular issue according to [this issue](https://github.com/Microsoft/vscode/issues/45500) from the official github repository it seems that there is a delay with the RPM packages, so waiting for them to upload the packages, a few days usually, and then run `dnf upgrade code` will do the trick
Upvotes: 5 [selected_answer]<issue_comment>username_3: Download the latest `.rpm` from the official website. And run `rpm -Uvh xxx.rpm` to update vs code.
I just used this method to update my vs code.
Upvotes: 3
|
2018/03/14
| 1,291 | 4,669 |
<issue_start>username_0: I am trying to retrieve a single document from a firestore sub collection:
database/users/uid/animal/docID
I am able to get the docID parsed from another component successfully but I am struggling with retrieving the information to display in html:
```
import { Component, OnInit } from '@angular/core';
import { AuthService } from '../core/auth.service';
import { AngularFireAuth} from 'angularfire2/auth';
import { AngularFirestore, AngularFirestoreCollection, AngularFirestoreDocument } from 'angularfire2/firestore';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/mergeMap';
import { Router, ActivatedRoute } from '@angular/router';
interface Animal {
name: string;
age: number;
sex: string;
breed: string;
colour: string;
}
interface animID extends Animal {
id: string;
}
@Component({
selector: 'app-detail-animal',
templateUrl: './detail-animal.component.html',
styleUrls: ['./detail-animal.component.css']
})
export class DetailAnimalComponent implements OnInit {
curUser: any; // This used to maintain the logged in user.
animalDoc: AngularFirestoreDocument;
animalCol: AngularFirestoreCollection;
animalInfo: any;
petID: Observable;
constructor(
public auth: AuthService,
private afs: AngularFirestore,
private afAuth: AngularFireAuth,
private router: Router,
public route: ActivatedRoute
) {
const petID: string = route.snapshot.paramMap.get('id');
console.log('AnimId from route: ', petID)
const user: any = this.afAuth.authState
}
private curPetID: string = this.route.snapshot.paramMap.get('id');
ngOnInit() {
this.afAuth.auth.onAuthStateChanged((user) => {
if (user) {
// get the current user
this.curUser = user.uid;
console.log('Animal ID:', this.curPetID )
console.log('Current User: ', this.curUser);
// Specify the Collection
this.animalInfo = this.afs.collection(`users/${this.curUser}/animals/`,
ref => ref.where('id', "==", this.curPetID)
.limit(1))
.valueChanges()
.flatMap(result => result)
console.log('Got Docs:', this.animalInfo);
}
});
}
}
```
Then in my HTML(only getting it display for now):
```
**Name: {{ (animalInfo | async)?.name }}**
Breed: {{ (animalInfo | async)?.breed }}
Animal System ID: {{ (animalInfo | async)?.id }}
```
When I run the code, in console.log('GotDocs: ', this.animalInfo) returns undefined.
```
Got Docs:
Observable {_isScalar: false, source: Observable, operator: MergeMapOperator}
operator:MergeMapOperator {project: ƒ, resultSelector: undefined, concurrent:
Infinity}
source:Observable {_isScalar: false, source: Observable, operator: MapOperator}
_isScalar:false
__proto__:
Object
```
I am not sure if having the above code in ngOnInit() is the right way to go about this either.
Any help greatly appreciated.
Michael<issue_comment>username_1: animalInfo is observable type.
Angular2+ supports '| async' pipeline to show observable type directly.
So, if you want to get real data value, you should use subscribe like this:
```
const collection$: Observable = collection.valueChanges()
collection$.subscribe(data => console.log(data) )
```
I hope this would be helpful :)
Upvotes: 0 <issue_comment>username_2: There is an easier approach for reading a single document. You already have the ID, so you can point to that specific document inside ngOnInit:
```
const docRef = this.afs.doc(`users/${this.curUser}/animals/${this.curPetID}`)
this.animalInfo = docRef.valueChanges()
```
Ideally, you unwrap this data in the HTML and set a template variable.
```
Hello {{ animal.name }}
```
Or you can subscribe to it in the component TypeScript.
```
animalInfo.subscribe(console.log)
```
Upvotes: 4 [selected_answer]<issue_comment>username_3: Like @username_2 said:
you want to do the "(animalInfo | async) as animal" in an ngIf (recommended solution)
then you do not need the async pipe anymore in your html, do remember to use the new name in the brackets {{}}. if you forgot the names that you gave to your object just use the {{ animal | json }} this will show the Object as json text.
```
const ref = 'location in db';
const animalInfo$: Observable;
constructor(private service: Firestore) {
this.animalInfo$ = this.service.doc(ref).valueChanges();
}
```
or you could do the async part in the constructor()/onInit() (backup solution)
```
const ref = 'location in db';
const animalInfo: Item;
constructor(private service: Firestore) {
this.service.doc(ref).subscribe(item => {
this.animalInfo = item;
console.log(item);
);
}
```
then you can do this again in your html
{{ animalInfo | json }}
Upvotes: 0
|
2018/03/14
| 448 | 1,528 |
<issue_start>username_0: I need to get **x, y values** of the each "**.spot**" element and **store into array or object**. This is what I have done so far.
```
function getPosition() {
let loc = document.getElementsByClassName("spot");
for (let i = 0; i < loc.length; i++) {
let offsets = loc[i].getBoundingClientRect();
let id = loc[i].id;
let y = offsets.top;
let x = offsets.left;
drawLines(x, y);
}
}
function drawLines(x, y) {
//store values in a array or object
}
```<issue_comment>username_1: Try this snippet
```
var store=[];
function drawLines(x, y) {
var data={};
data.x=x;
data.y=y;
store.push(data);
}
```
Upvotes: 1 <issue_comment>username_2: If you are using **ES6** Syntax, you could do this.
```
let data = [];
function drawLines(x, y) {
data.push({x, y});
}
```
This would form an array of objects with x and y as its properties.
Upvotes: 0 <issue_comment>username_3: better use closure rather defining the variable globally.
```
let drawLines = ((x, y) => {
let store = [];
return (x, y) => {store.push({x: x, y: y}); return store;}
})();
```
or you can have only one function to return the array of objects.
```
function getPosition() {
let locs = document.getElementsByClassName("spot");
return locs.map((loc) => {
let offsets = loc.getBoundingClientRect();
let id = loc[i].id;
return {x: offsets.left, y: offsets.top};
});
}
```
Upvotes: 0
|
2018/03/14
| 497 | 1,535 |
<issue_start>username_0: I'm working on core php,i need how to convert PHP array to Javascript array please help me,below the my example code this there please check it.
I tried from long time to debug but not getting any leads. please help me in resolving this issue
Here my php array data:
```
Array
(
[0] => 001-1234567
[1] => 1234567
[2] => 12345678
[3] => 12345678
[4] => 12345678
)
```
Here javascript array:
```
var cities = [
"Aberdeen",
"Ada",
"Adamsville",
"Addyston",
"Adelphi"
];
```<issue_comment>username_1: Try this snippet
```
var store=[];
function drawLines(x, y) {
var data={};
data.x=x;
data.y=y;
store.push(data);
}
```
Upvotes: 1 <issue_comment>username_2: If you are using **ES6** Syntax, you could do this.
```
let data = [];
function drawLines(x, y) {
data.push({x, y});
}
```
This would form an array of objects with x and y as its properties.
Upvotes: 0 <issue_comment>username_3: better use closure rather defining the variable globally.
```
let drawLines = ((x, y) => {
let store = [];
return (x, y) => {store.push({x: x, y: y}); return store;}
})();
```
or you can have only one function to return the array of objects.
```
function getPosition() {
let locs = document.getElementsByClassName("spot");
return locs.map((loc) => {
let offsets = loc.getBoundingClientRect();
let id = loc[i].id;
return {x: offsets.left, y: offsets.top};
});
}
```
Upvotes: 0
|
2018/03/14
| 686 | 2,457 |
<issue_start>username_0: I am trying to do a "Try-it yourself" editor but without using frames.
So I added 2 textareas, one for code and one to show the result. I also added a "Run" button.
I wrote the following function to execute the code in the first text area and show the result in the second text area:
```
function RunCode() {
var Code= document.getElementById('code').value;
document.getElementById('result').innerHTML= eval(Code);
}
```
But all i get in the result text area is : undefined.
Sorry for my stupid questions but I am really a beginner. So:
* Does the eval function works only on javascript code?
* Is it right to do the result part as a text area?<issue_comment>username_1: Yes, eval works only on JavaScript code. To render your code as HTML, just assign it to innerHTML without the eval:
```
document.getElementById('result').innerHTML=Code;
```
To show the result, you should use a `div`, not a `textarea`.
Upvotes: 0 <issue_comment>username_2: 1. Make sure your code in "code" textarea return a value. And make a call if you define a function. E.g. try this in your "code": `function a() { return 1 }; a();`
2. Should be `document.getElementById('result').value = eval(Code);`
Upvotes: 0 <issue_comment>username_3: >
> Does the eval function works only on javascript code?
>
>
>
Yes, It only works on JavScript code. When the JavaScript code is written as a string, to execute that code we use `eval()` And this is only applicable to JavaScript. We don't use `eval()` in HTML since the HTML on browser works even if it is a string
eg,
```js
function looseJsonParse(obj) {
return eval(obj);
}
console.log(looseJsonParse(
"{a:(4-1), b:function(){}, c:new Date()}"
))
```
>
> Is it right to do the result part as a text area?
>
>
>
NO, is a input element, which means it contains the `value`. Inner HTML works on other elements.
So for above, `document.getElementById('result').val = Code`should work.
Note: If the value contains HTML then it will be treated as text and will not execute on the browser.
Bonus: Defining a variable with Capital letter is bad practice. Best practice says the variable should start with a small letter and it can be camel case.
Footnote: [JavaScript eval()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval) && [textarea value](https://www.w3schools.com/html/html_elements.asp)
I hope this helps!
Upvotes: 3 [selected_answer]
|
2018/03/14
| 1,107 | 3,779 |
<issue_start>username_0: Is there a way to run a list of functions in a method from another method while skipping over 1 specified function in the list?
For example, I have the contentList method:
```
def contentList(self):
methods = [self.title, self.containerDIV, self.heading, self.stopSection, self.offlineSection, self.onlineSection, self.endDIV, self.otherImages]
for m in methods:
m()
def test(self):
self.contentList()
# skip over stopSection
```
Is there a way to run those methods from test method while skipping over or not running the self.stopSection?
**UPDATE**
Here is more on what I am trying:
```
#**************************** BEGIN OF HTML CONTENT ****************************
def title(self):
self.wfile.write(bytes("", "utf8"))
def containerDIV(self):
self.wfile.write(bytes("", "utf8"))
#\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\* END OF HTML CONTENT \*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*
def contentList(self, skip\_name): # All content functions in list
methods = [self.title, self.containerDIV, self.endDIV]
for m in methods:
if m.\_\_name\_\_ != skip\_name:
m()
def narrow(self):
try:
self.contentList('title') # removed title
return
# GET
def do\_GET(self):
try:
self.contentList('none') # I added none here because I want to keep title
return
```<issue_comment>username_1: Depending on your scope you can temporary change the definition of the function before it executes.
**Global Scope**
```
def t1():
print('t1')
def t2():
print('t2')
def contentList():
methods = [t1, t2]
for m in methods:
m()
def test():
global t1
def fake(): pass
temp = t1
t1 = fake
contentList()
t1 = temp
test()
```
**Class Scope**
```
def test(self):
def fake(): pass
temp = self.stopSection
self.stopSection = fake
self.contentList()
self.stopSection = temp
```
Upvotes: 2 <issue_comment>username_2: You may check the function name by it's `__name__` attribute. So, in your case, you could do something like:
```
class SomeClass:
def contentList(self, skip_method_name):
methods = [self.title, self.containerDIV, self.heading, self.stopSection, self.offlineSection, self.onlineSection, self.endDIV, self.otherImages]
for m in methods:
if m.__name__ != skip_method_name:
m()
def test(self):
self.contentList('stopSection')
```
Let me provide a more concise example
```
class SomeClass:
def method_a(self):
print('method_a')
def method_b(self):
print('method_b')
def method_runner(self, skip_name):
for m in [self.method_a, self.method_b]:
if m.__name__ != skip_name:
m()
```
Sample usage:
```
>>> some_obj = SomeClass()
>>> some_obj.method_runner('')
method_a
method_b
>>> some_obj.method_runner('method_a')
method_b
>>> some_obj.method_runner('method_b')
method_a
```
As @Jeronimo pointed out, we may use the actual function in the `method_runner` method and bypass the `__name__` call at all. Using this aproach my example looks like this:
```
class SomeClass:
def method_a(self):
print('method_a')
def method_b(self):
print('method_b')
def method_runner(self, skip_method):
for m in [self.method_a, self.method_b]:
if m != skip_method:
m()
```
A sample usage:
```
>>> some_obj = SomeClass()
>>> some_obj.method_runner(None)
method_a
method_b
>>> some_obj.method_runner(some_obj.method_a)
method_b
>>> some_obj.method_runner(some_obj.method_b)
method_a
```
Upvotes: 2 [selected_answer]
|
2018/03/14
| 1,695 | 6,091 |
<issue_start>username_0: I am unable to stop a python script from running using `os.system()` but I am able to make it run with `os.system()`. When I run the same command on the terminal to kill the process, it works.
I have this code snippet from my `web_plants.py` script to deploy it in html using Flask:
```
@app.route("/auto/water/")
def auto\_water(toggle):
running = False
if toggle == "ON":
templateData = template(text = "Auto Watering On")
for process in psutil.process\_iter():
try:
if process.cmdline()[1] == 'auto\_water.py':
templateData = template(text = "Already running")
running = True
except:
pass
if not running:
os.system("python auto\_water.py")
else:
templateData = template(text = "Auto Watering Off")
os.system("pkill -f water.py")
return render\_template('main.html', \*\*templateData)
if \_\_name\_\_ == "\_\_main\_\_":
app.run(host='0.0.0.0', port=80, debug=True)
```
I have a `water.py` script that contains the `auto_water` function for the button on my html page. But the function works fine, so I suppose that's not an issue.
```
def auto_water(pump_pin = 38):
init_output(pump_pin)
print("Reading Soil Humidity values from ADS1115")
try:
while True:
m = adc.read_adc(0, gain=GAIN)
print('Moisture Level:{0:>6}'.format(m))
time.sleep(1)
if m>23000:
#GPIO.output(pump_pin, GPIO.LOW)
print "relay on"
else:
#GPIO.output(pump_pin, GPIO.HIGH)
print "relay off"
except KeyboardInterrupt:
GPIO.cleanup()
except Exception as e:
print (e)
```
And I have this `auto_water.py` file that imports `water` and calls the `auto_water()` function to run it. The purpose of using this file is to be able to kill the file while it is running when I click on the "Stop" button.
```
import water
#From the water.py script, call the auto_water function and run it as a process
if __name__ == "__main__":
water.auto_water()
```
The script keeps running and I have to kill it using `sudo pkill -f water.py` from the terminal in order to make it stop. But the same command doesn't work on the `web_plants.py` file, which I have used to stop it when I press the "Stop" button. However when I kill it, the webpage does register it and displays the text "Auto Watering OFF" as in the following lines from the `web_plants.py` file:
```
templateData = template(text="Auto Watering Off")
os.system("pkill -f water.py")
```<issue_comment>username_1: Can you use `os.kill()` instead?
```
import os
import signal
os.kill(pid, signal.SIGTERM)
```
If you don't have the `pid` readily available, use `subprocess.check_output` to acquire it. (Use `subprocess.run` instead if you're using Python 3.5+.)
```
import os
import signal
import subprocess
def get_water_pid():
return int(subprocess.check_output(['pgrep', '-f', 'water.py']).strip())
def kill_water_process():
pid = get_water_pid()
os.kill(pid, signal.SIGTERM)
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: Assuming the script is only ever started by your server, you can store the script's PID when you start it, and then use that to kill it.
It looks like your existing code is not spinning up the script in the background; it's leaving a Flask thread tied up forever waiting on the `os.system` to return. That's a bit weird, but I'll do the same thing for now.
Also, I'll just write bare functions, which you can Flask up as appropriate, and store the PID in a global, which you can replace with whatever persistent storage you're using.
```
autowater_pid = None
def start():
global pid
p = subprocess.Popen(["python", "auto_water.py"])
pid = p.pid
p.wait()
def stop():
global pid
if pid is not None:
os.kill(pid)
pid = None
```
---
You can expand on this in many ways. For example, if we already have a `pid`, we can skip starting a new copy. Or we can even check that it's still running, and start a new one if it's died somehow:
```
def start():
global pid
if pid is not None:
try:
os.kill(pid, 0) # check that it's still running
return
except ProcessLookupError:
pass
p = subprocess.Popen(["python", "auto_water.py"])
pid = p.pid
p.wait()
```
---
But back to that problem with waiting forever for the process to finish. Not only are you permanently tying up a thread, you're also making it so that that if the Flask process goes down for any reason (upgrade, load balancer, unhandled exception, whatever), the script will be killed by the OS. You should consider daemonizing the script in some way. That's way too big a topic to include in a side note to an answer, but you should be able to find enough information from searching to get started (or, at least, to come up with a good separate question to ask on SO).
---
Another alternative—and the one more commonly used by daemons—is to have the script itself (or a daemonizing wrapper) write its own pid to a file in a known location at startup. Like this:
```
with open('/var/run/auto_water.pid', 'w') as f:
f.write(f'{os.getpid()}\n')
```
And you can `os.remove('/var/run/auto_water.pid')` on exit.
And then your server can read that number out of the file to know the PID to kill. And again, you can put in code to handle the case where the process died without erasing its pidfile, etc.
However, to do it properly, you're going to want to read up on locking pidfiles, the right behavior for handling unexpected existing ones, etc.
Or, better, just get a pidfile-handling library off PyPI.
Or, maybe even better, get a daemon-handling library that does the daemonizing and the pidfile and the error handling all in one.
Upvotes: 2 <issue_comment>username_3: The system call blocks the execution. The function wont return anything back to the browser until the execution is complete.
Try this:
```
os.system("python auto_water.py&")
```
& spawns the process and return immediately.
Upvotes: 1
|
2018/03/14
| 1,093 | 3,629 |
<issue_start>username_0: I have using `jQuery` validation plug in for one of my forms. The validation rules are working fine.
But my question is if validation success, after click submit button show gif loader.
Can someone please point me in the right direction of how to get this to work?
```js
$( "#myform" ).validate({
rules: {
fullname: {
required: true
},
mobile:{
required:true,
minlength: 10,
number:true
},
email:{
required:true,
email:true
}
},
messages: {
fullname: {
required: "Please enter your name"
},
mobile:{
required: "Please enter your mobile number",
minlength:"Minumum length 10 digits"
},
email:{
required: "Please enter your email-id",
email: "Invalid email-id"
}
}
});
```
```css
.gif-loader
{
display:none;
}
```
```html

Select Demo Date
20th Mar 2018
21st Mar 2018
22nd Mar 2018
23rd Mar 2018
Select Time
10:00 AM
04:00 PM
```<issue_comment>username_1: Have you tried binding the submit event? There's a submitHandler in the plugin
To submit, add `$('#myform').submit()`.
**Edit**;
instead of the submit event I would send it via Ajax, like
```
submitHandler: function() {
$('.gif-loader').show();
$.post("insert.php", $("#myform").serialize(), function(data) {
alert(data);
$('.gif-loader').hide();
});
}
```
However, you may need to change the way `insert.php` works in that case.
```js
$( "#myform" ).validate({
//this bit is new.
submitHandler: function() {
$('.gif-loader').show();
},
rules: {
fullname: {
required: true
},
mobile:{
required:true,
minlength: 10,
number:true
},
email:{
required:true,
email:true
}
},
messages: {
fullname: {
required: "Please enter your name"
},
mobile:{
required: "Please enter your mobile number",
minlength:"Minumum length 10 digits"
},
email:{
required: "Please enter your email-id",
email: "Invalid email-id"
}
}
});
```
```css
.gif-loader
{
display:none;
}
```
```html

Select Demo Date
20th Mar 2018
21st Mar 2018
22nd Mar 2018
23rd Mar 2018
Select Time
10:00 AM
04:00 PM
```
Upvotes: 1 <issue_comment>username_2: Use this [fiddle](https://jsfiddle.net/410unv4m/3/)
You need to add submit handler for that...
```
submitHandler: function() { $(".gif-loader").show(); }
```
```js
$( "#myform" ).validate({
rules: {
fullname: {
required: true
},
mobile:{
required:true,
minlength: 10,
number:true
},
email:{
required:true,
email:true
}
},
messages: {
fullname: {
required: "Please enter your name"
},
mobile:{
required: "Please enter your mobile number",
minlength:"Minumum length 10 digits"
},
email:{
required: "Please enter your email-id",
email: "Invalid email-id"
}
},
submitHandler: function() { $(".gif-loader").show(); $('#myform').submit();}
});
```
```css
.gif-loader
{
display:none;
}
```
```html

Select Demo Date
20th Mar 2018
21st Mar 2018
22nd Mar 2018
23rd Mar 2018
Select Time
10:00 AM
04:00 PM
```
Upvotes: 3 [selected_answer]
|
2018/03/14
| 642 | 2,602 |
<issue_start>username_0: if I call monthEndUpdate(); in my BankAccount class, in the setBalance line after it getBalance() gets the balance it adds getMonthlyFeesAndInterest() but in the BankAccount class getMonthlyFeesAndInterest is abstract. So would it do anything? Or would it go to the ChequingAccount class that extends BankAccount and go to it's protected getMonthlyFeesAndInterest method?
```
public abstract class BankAccount{
public void monthEndUpdate() {
setBalance(getBalance() + getMonthlyFeesAndInterest());
}
protected abstract double getMonthlyFeesAndInterest();
}
public class ChequingAccount extends BankAccount{
protected double getMonthlyFeesAndInterest() {
if(getBalance() >=0)
{
return 0.0;
} else
{
return getBalance() * .20;
}
}
```<issue_comment>username_1: Your Bank account class needs to be abstract; abstract methods are not allowed in concrete classes.
Edit:
In Java an object variable has a declared type and a runtime type. If you look for example at `BankAccount account = new ChequeingAccount()`, the declared type is BankAccount and the runtime type is ChequeingAccount. At run-time the actual method that is called depends on the actual type of the object, which leads to getMonthlyFeesAndInterest() of ChequeingAccount beeing called.
For more detailed information search for Polymorphism or checkout [this link](http://ice-web.cc.gatech.edu/ce21/1/static/JavaReview-RU/OOBasics/ooPoly.html).
Upvotes: -1 <issue_comment>username_2: Since `BankAccount` is abstract, you can't instantiate one directly. Instead you will have to instantiate a `ChequingAccount` instance:
```
ChequingAccount chequingAccount = new ChequingAccount();
```
When you call `chequingAccount.monthEndUpdate()`, the `monthEndUpdate` method declared in `BankAccount` will be called (because you haven't overridden it in your `ChequingAccount` subclass).
That method will then call `getMonthlyFeesAndInterest` from the class that your reference is an instance of (the `ChequingAccount`).
**Edit:** One way of thinking about it is that unless explicitly specified otherwise, methods calls are implicitly preceded by `this.`:
```
public void monthEndUpdate() {
this.setBalance(this.getBalance() + this.getMonthlyFeesAndInterest());
}
```
In our case, the `this` refers to an object of real type `ChequingAccount`, so that's where the JVM will look first for the implementation of the method. If it can't find the implementation, it starts searching up the inheritance chain to find the first implementation that matches the method signature.
Upvotes: 0
|
2018/03/14
| 421 | 1,530 |
<issue_start>username_0: I set constraints for tabar but its image and title is showing like this only on iPhone X. Also, it is working properly on other devices like the 8, 6, and 5 series. It is not in proper format, Please suggest what I can do for it.
<issue_comment>username_1: I tend to use the view inspector to look at the frames to see what is going on.
It looks like you might be doing something at the wrong time in the views life cycle. So that objects have not had time to layout.
You could also try moving the tab bar up one pixel like Uday said.
Last tip when dealing with view issues. Make sure to delete the app from the simulator on say the iPhone 8. As well as Derived Data. I have spent a lot of time trying to diagnose an issue. Only to find out I was looking at a cached storyboard.
Upvotes: 3 [selected_answer]<issue_comment>username_2: I found the easiest way to fix the Tabbar design for all size of iPhone.
you can use `setItems:animated`: method of the tab bar as like below:
```
func setItems(_ items: [UITabBarItem]?, animated: Bool) {
UIIImage * image0 = UIImage(named: "search_icon")
let item0 = UITabBarItem(title: tabBar.items[0]?.title, image: image0, tag: 0)
// And so on or in a loop
let items = [item0]
// Add all items here
tabBar.setItems(items, animated: false)
}
```
For more details you can read apple documentation here:
<https://developer.apple.com/documentation/uikit/uitabbar?language=objc>
Upvotes: 0
|
2018/03/14
| 638 | 2,390 |
<issue_start>username_0: So I am a beginner to Java and while reading a book, and I had a question about polymorphism. It seems that there are two distinct meanings of polymorphism: one being the polymorphic nature of inheritance hierarchies (like type compatibility), and the other being choosing the right method to call during runtime, as different levels of inheritance may have different overridden methods. Which one do people refer to when talking about polymorphism? Or is it a general umbrella term for both?
An example of type compatibility would be something like
```
Animal a = new Mammal();
```
Or
```
ArrayList animalList = new ArrayList();
animalList.add(0, new Mammal());
animalList.add(1, new Vertebrate());
```
whereas dynamically binded method selection at runtime is like
```
Student s = null;
Student g = new Graduate();
Student u = new UnderGrad();
... (after reading user input, call a method based on what the user chooses)
if(inputstr.equals("g"))
s = g;
else if(inputstr.equals("u"))
s = u;
else
s = new Student();
s.displayGrade(); //this method is different based on if they are undergrad, grad, or student
```<issue_comment>username_1: I tend to use the view inspector to look at the frames to see what is going on.
It looks like you might be doing something at the wrong time in the views life cycle. So that objects have not had time to layout.
You could also try moving the tab bar up one pixel like Uday said.
Last tip when dealing with view issues. Make sure to delete the app from the simulator on say the iPhone 8. As well as Derived Data. I have spent a lot of time trying to diagnose an issue. Only to find out I was looking at a cached storyboard.
Upvotes: 3 [selected_answer]<issue_comment>username_2: I found the easiest way to fix the Tabbar design for all size of iPhone.
you can use `setItems:animated`: method of the tab bar as like below:
```
func setItems(_ items: [UITabBarItem]?, animated: Bool) {
UIIImage * image0 = UIImage(named: "search_icon")
let item0 = UITabBarItem(title: tabBar.items[0]?.title, image: image0, tag: 0)
// And so on or in a loop
let items = [item0]
// Add all items here
tabBar.setItems(items, animated: false)
}
```
For more details you can read apple documentation here:
<https://developer.apple.com/documentation/uikit/uitabbar?language=objc>
Upvotes: 0
|
2018/03/14
| 610 | 2,434 |
<issue_start>username_0: While searching for something else, I found this code
```
$x = "foo";
function foo(){ echo "wtf"; }
$x(); # "wtf"
```
and when I searched google for this, I got only C results not PHP, while I know that under the PHP hood is C, I would really like some explanation about that.
What is that called?
and how it is interpreted by PHP zend? is it some sort of callable?
and is it still available in PHP 7+ ?<issue_comment>username_1: This is called variable functions in PHP : <http://php.net/manual/en/functions.variable-functions.php>
Basically, when there is a variable before the `()`, first the variable get resolved and interpreter get the value of it and try to find the function with that value. If the function exists, it calls or function not found exception will be thrown.
Upvotes: 3 <issue_comment>username_2: A variable function. The variable x is simply holding a value which is equal to function name. Calling variable that way results to calling the function.
Upvotes: 0 <issue_comment>username_3: 1. It is a callable (variable function: <http://php.net/manual/en/functions.variable-functions.php> )
2. Zend just treats it as a callable and calls the function.
3. It is an old and stable language feature, and still available in PHP7+ (and it will be available as long as possible)
The callable types and normalizations are given in the table below:
<http://php.net/manual/en/language.types.callable.php#118032>
```
Callable | Normalization | Type
--------------------------------+---------------------------------+--------------
function (...) use (...) {...} | function (...) use (...) {...} | 'closure'
$object | $object | 'invocable'
"function" | "function" | 'function'
"class::method" | ["class", "method"] | 'static'
["class", "parent::method"] | ["parent of class", "method"] | 'static'
["class", "self::method"] | ["class", "method"] | 'static'
["class", "method"] | ["class", "method"] | 'static'
[$object, "parent::method"] | [$object, "parent::method"] | 'object'
[$object, "self::method"] | [$object, "method"] | 'object'
[$object, "method"] | [$object, "method"] | 'object'
```
Upvotes: 3 [selected_answer]
|
2018/03/14
| 1,040 | 3,665 |
<issue_start>username_0: I have written code for multi window form but there is an error shown in image
[](https://i.stack.imgur.com/U4UnY.png)
i am new to JavaScript can you please help me, ask me anything you need besides from this
```
function fixStepIndicator(n) {
// This function removes the "active" class of all steps...
var i, x = document.getElementsByClassName("step");
for (i = 0; i < x.length; i++) {
x[i].className = x[i].className.replace(" active", "");
}
//... and adds the "active" class to the current step:
x[n].className += " active";
}
```<issue_comment>username_1: this how you can remove class name
```
var element = document.getElementById("myDIV");
element.classList.remove("classname");
```
for adding class do this
```
document.getElementById("myDIV").classList.add("classname");
```
Ref : <https://caniuse.com/#search=classList>
Note : I am assuming you are getting elements by this line `x = document.getElementsByClassName("step");`
Upvotes: 2 <issue_comment>username_2: You can use `document.querySelector()`.
The Document method **querySelector()** returns the first Element within the document that matches the specified selector, or group of selectors. If no matches are found, null is returned.
In your case you want to add `active` class on `img` tag, so before to add `class` you need to check first is already `active` is already added or not like this
```
//This function will call on image click
function onImgClik(event) {
var activeImg = document.querySelector('img.active');
if (activeImg) {
activeImg.classList.remove('active');
}
event.target.classList.add('active');
document.querySelector('button').disabled = false;
}
```
```js
function onImgClik(event) {
var activeImg = document.querySelector('img.active');
if (activeImg) {
activeImg.classList.remove('active');
}
event.target.classList.add('active');
document.querySelector('button').disabled = false;
}
```
```css
.container{
display: grid;
}
.imageCnt{
display: inline-flex;
}
.imageCnt img{
height: 100px;
border-radius: 50%;
border: 2px solid #316eb5;
margin: 5px;
}
.reg{
background: green;
color: #fff;
border: 0px;
padding: 8px;
width: 138px;
margin: 0 auto;
font-weight: bold;
border-radius: 0.3em;
cursor: pointer;
}
.active{
border-color: orange !important;
}
```
```html




Register
```
Upvotes: 0 <issue_comment>username_3: Longtime lurker, making my first small contribution <3
Arrived at this question by trying to find a solution for the exact same error. I reckon this comes from modifying the Multi-Step form used as example [here](https://www.w3schools.com/howto/howto_js_form_steps.asp)
This might not be the best solution, please know that I'm only a beginner.
To everyone that's trying to modify the example and getting this same error, just make sure that if you've added extra steps to the form, you've also added them to this part of the HTML code before :
```
/\*This extra step added manually fixed the error for us\*/
```
Upvotes: 1 <issue_comment>username_4: Run fixStepIndicator(n) fuction loop from the value of n
Upvotes: 0
|
2018/03/14
| 936 | 3,152 |
<issue_start>username_0: My script I have been writing has been working great. I just added the option so it would open a profile on chrome using this code.
```
options = webdriver.ChromeOptions
browser = webdriver.Chrome(executable_path=r"C:\Users\princess\AppData\Local\Programs\Python\Python36-32\chromedriver.exe", chrome_options=options)
options.add_argument(r'user-data-dir=C:\Users\princess\AppData\Local\Google\Chrome\User Data')
options.add_argument('--profile-directory=Profile 1')
```
When used, I get this error code.
```
C:\Users\Princess\Desktop>CHBO.py
Traceback (most recent call last):
File "C:\Users\Princess\Desktop\CHBO.py", line 12, in
browser = webdriver.Chrome(executable\_path=r"C:\Users\princess\AppData\Local\Programs\Python\Python36-32\chromedriver.exe", chrome\_options=options)
File "C:\Users\Princess\AppData\Local\Programs\Python\Python36-32\lib\site-packages\selenium\webdriver\chrome\webdriver.py", line 59, in \_\_init\_\_
desired\_capabilities = options.to\_capabilities()
TypeError: to\_capabilities() missing 1 required positional argument: 'self'
```
How can I fix this?<issue_comment>username_1: You can use `options = Options()` or `options = webdriver.ChromeOptions()` at place of `options = webdriver.ChromeOptions`
Otherwise you are pointing at an object (namely `webdriver.ChromeOptions`), and not making an *instance* of that object by including the needed parenthesis
Upvotes: 2 <issue_comment>username_2: To *create* and *open* a new *Chrome Profile* you need to follow the following steps :
* Open *Chrome* browser, click on the *Side Menu* and click on *Settings* on which the *url* `chrome://settings/` opens up.
* In *People* section, click on *Manage other people* on which a popup comes up.
* Click on *ADD PERSON*, provide the *person name*, select an *icon*, keep the item *Create a desktop shortcut for this user* checked and click on *ADD* button.
* Your new profile gets created.
* Snapshot of a new profile **SeLeNiUm**

* Now a desktop icon will be created as **SeLeNiUm - Chrome**
* From the properties of the desktop icon **SeLeNiUm - Chrome** get the name of the profile directory. e.g. **--profile-directory="Profile 2"**

* Get the absolute path of the *profile-directory* in your system as follows :
```
C:\\Users\\Otaku_Wiz\\AppData\\Local\\Google\\Chrome\\User Data\\Profile 2
```
* Now pass the value of *profile-directory* through an instance of *Options* with `add_argument()` method along with key *user-data-dir* as follows :
```
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
options = Options()
options.add_argument("user-data-dir=C:\\Users\\AtechM_03\\AppData\\Local\\Google\\Chrome\\User Data\\Profile 2")
driver = webdriver.Chrome(executable_path=r'C:\path\to\chromedriver.exe', chrome_options=options)
driver.get("https://www.google.co.in")
```
* Execute your `Test`
* Observe *Chrome* gets initialized with the *Chrome Profile* as **SeLeNiUm**

Upvotes: 4
|
2018/03/14
| 5,289 | 26,755 |
<issue_start>username_0: I'm working with a webRCT project. I'm Using Janus webRtc gateway video room function and a RestAPI + Mysql database to handle camera details and AngularJs to stream video and and a client application to capture videos.
I've created a HomeController.js to handle camera details. and a janusController.js to handle streaming video.
Now in current situation I can stream a video from single camera.and multiple camera also supporting if I create multiple div in the html5 page manually. but that's not what I want to do. I want to create div s in the htlm5 page with angularJs "ng-repeat" and I want to give unique Id for each divs.
Here important parts of my is my codes.
HomeController.js
```
$scope.getPeripheralList = function (devHardwareId){
HomeService.getPeripheralList(devHardwareId)
.then (function success(response){
$scope.peripheralDetails = response.data;
$scope.errorMessage = '';
},
function error(response) {
$mdDialog.show(
$mdDialog.alert()
.parent(angular.element(document.querySelector('#popupContainer')))
.clickOutsideToClose(true)
.title('Error occured!!!!!!')
.textContent(response.data.message)
.ariaLabel('')
.ok('Ok')
);
});
}
```
Response of above call.
```
[{"peripheralId":7,"perHardwareId":"Logitech HD Webcam C270","peripheralName":"Logitech HD Webcam C270","peripheralType":"Video","isActive":true,"device":{"deviceId":13,"deviceName":"DESKTOP-NJ02GI1","devHardwareId":"0A0027000007","isActive":true,"deviceIp":"192.168.2.19","creationDate":"2018-03-09T10:54:40.000+0000","lastModifiedDate":"2018-03-09T10:54:40.000+0000"}},{"peripheralId":8,"perHardwareId":"A4TECH USB2.0 PC Camera","peripheralName":"A4TECH USB2.0 PC Camera","peripheralType":"Video","isActive":true,"device":{"deviceId":13,"deviceName":"DESKTOP-NJ02GI1","devHardwareId":"0A0027000007","isActive":true,"deviceIp":"192.168.2.19","creationDate":"2018-03-09T10:54:40.000+0000","lastModifiedDate":"2018-03-09T10:54:40.000+0000"}}]
```
JanusController.js
```
'use strict';
App.controller('JanusController', ['$scope', 'HomeService','uiGridConstants',"$mdDialog", function($scope, HomeService,uiGridConstants,$mdDialog) {
var server = null;
if(window.location.protocol === 'http:')
server = "http://" + "192.168.2.10" + ":8088/janus";
else
server = "https://" +"192.168.2.10" + ":8089/janus";
var janus = null;
var sfutest = null;
var opaqueId = "videoroomtest-"+Janus.randomString(12);
var started = false;
var myroom = 1234; // Demo room
var myusername = null;
var myid = null;
var mystream = null;
// We use this other ID just to map our subscriptions to us
var mypvtid = null;
var feeds = [];
var bitrateTimer = [];
var doSimulcast = (getQueryStringValue("simulcast") === "no" || getQueryStringValue("simulcast") === "false");
// Initialize the library (all console debuggers enabled)
Janus.init({debug: "all", callback: function() {
started = true;
if(!Janus.isWebrtcSupported()) {
bootbox.alert("No WebRTC support... ");
return;
}
// Create session
janus = new Janus(
{
server: server,
success: function() {
// Attach to video room test plugin
janus.attach(
{
plugin: "janus.plugin.videoroom",//the unique package name of the plugin
opaqueId: opaqueId, // an optional opaque string meaningful to application
success: function(pluginHandle) { //the handle was successfully created and is ready to be used;
sfutest = pluginHandle;
Janus.log("Plugin attached! (" + sfutest.getPlugin() + ", id=" + sfutest.getId() + ")");
Janus.log(" -- This is a publisher/manager");
registerUsername()
angular.element('#start').removeAttr('disabled').html("Stop")
.click(function() {
$(this).attr('disabled', true);
janus.destroy();
});
},
error: function(error) { //the handle was NOT successfully created;
Janus.error(" -- Error attaching plugin...", error);
bootbox.alert("Error attaching plugin... " + error);
},
mediaState: function(medium, on) {
Janus.log("Janus " + (on ? "started" : "stopped") + " receiving our " + medium);
},
webrtcState: function(on) {
Janus.log("Janus says our WebRTC PeerConnection is " + (on ? "up" : "down") + " now");
//write codes to change bitrate here.
},
onmessage: function(msg, jsep) { //a message/event has been received from the plugin;
Janus.debug(" ::: Got a message (publisher) :::");
Janus.debug(msg);
var event = msg["videoroom"];
Janus.debug("Event: " + event);
if(event != undefined && event != null) {
if(event === "joined") {
// Publisher/manager created, negotiate WebRTC and attach to existing feeds, if any
myid = msg["id"];
mypvtid = msg["private_id"];
Janus.log("Successfully joined room " + msg["room"] + " with ID " + myid);
publishOwnFeed(false); //not publishing a video
// Any new feed to attach to?
if(msg["publishers"] !== undefined && msg["publishers"] !== null) {
var list = msg["publishers"];
Janus.debug("Got a list of available publishers/feeds:");
Janus.debug(list);
for(var f in list) {
var id = list[f]["id"];
var display = list[f]["display"];
var audio = list[f]["audio_codec"];
var video = list[f]["video_codec"];
Janus.debug(" >> [" + id + "] " + display + " (audio: " + audio + ", video: " + video + ")");
newRemoteFeed(id, display, audio, video);
}
}
} else if(event === "destroyed") {
// The room has been destroyed
Janus.warn("The room has been destroyed!");
bootbox.alert("The room has been destroyed", function() {
window.location.reload();
});
} else if(event === "event") {
// Any new feed to attach to?
if(msg["publishers"] !== undefined && msg["publishers"] !== null) {
var list = msg["publishers"];
Janus.debug("Got a list of available publishers/feeds:");
Janus.debug(list);
for(var f in list) {
var id = list[f]["id"];
var display = list[f]["display"];
var audio = list[f]["audio_codec"];
var video = list[f]["video_codec"];
Janus.debug(" >> [" + id + "] " + display + " (audio: " + audio + ", video: " + video + ")");
newRemoteFeed(id, display, audio, video);
}
} else if(msg["leaving"] !== undefined && msg["leaving"] !== null) {
// One of the publishers has gone away?
var leaving = msg["leaving"];
Janus.log("Publisher left: " + leaving);
var remoteFeed = null;
for(var i=1; i<6; i++) {
if(feeds[i] != null && feeds[i] != undefined && feeds[i].rfid == leaving) {
remoteFeed = feeds[i];
break;
}
}
if(remoteFeed != null) {
Janus.debug("Feed " + remoteFeed.rfid + " (" + remoteFeed.rfdisplay + ") has left the room, detaching");
//$('#remote'+remoteFeed.rfindex).empty().hide();
$('#videoremote'+remoteFeed.rfindex).empty();
feeds[remoteFeed.rfindex] = null;
remoteFeed.detach();
}
} else if(msg["unpublished"] !== undefined && msg["unpublished"] !== null) {
// One of the publishers has unpublished?
var unpublished = msg["unpublished"];
Janus.log("Publisher left: " + unpublished);
if(unpublished === 'ok') {
// That's us
sfutest.hangup();
return;
}
var remoteFeed = null;
for(var i=1; i<6; i++) {
if(feeds[i] != null && feeds[i] != undefined && feeds[i].rfid == unpublished) {
remoteFeed = feeds[i];
break;
}
}
if(remoteFeed != null) {
Janus.debug("Feed " + remoteFeed.rfid + " (" + remoteFeed.rfdisplay + ") has left the room, detaching");
// $('#remote'+remoteFeed.rfindex).empty().hide();
$('#videoremote'+remoteFeed.rfindex).empty();
//document.getElementById('videoremote'+remoteFeed.rfindex).empty();
feeds[remoteFeed.rfindex] = null;
remoteFeed.detach();
}
}
else if(msg["error"] !== undefined && msg["error"] !== null) {
bootbox.alert(msg["error_code" + "error"]);
}
}
}
if(jsep !== undefined && jsep !== null) {
Janus.debug("Handling SDP as well...");
Janus.debug(jsep);
sfutest.handleRemoteJsep({jsep: jsep});
}
},
onlocalstream: function(stream) {
//we don't publish our stream here
},
onremotestream: function(stream) {
// The publisher stream is sendonly, we don't expect anything here
},
oncleanup: function() {
//
}
});
},
error: function(error) {
Janus.error(error);
bootbox.alert(error, function() {
window.location.reload();
});
},
destroyed: function() {
window.location.reload();
}
});
}
});
/////////////////////////////////////////////////////////
function registerUsername() {
var username = "stream";
var register = { "request": "join", "room": myroom, "ptype": "publisher", "display": username };
myusername = username;
sfutest.send({"message": register});
}
//////////////////////////////////////////////////////////
function publishOwnFeed(useAudio) {
// Publish our stream
//$('#publish').attr('disabled', true).unbind('click');
sfutest.createOffer(
{
// Add data:true here if you want to publish datachannels as well
media: { audioRecv: false, videoRecv: false, audioSend: false, videoSend: false }, // Publishers are sendonly
simulcast: doSimulcast,
success: function(jsep) {
Janus.debug("Got publisher SDP!");
Janus.debug(jsep);
var publish = { "request": "configure", "audio": useAudio, "video": true };
sfutest.send({"message": publish, "jsep": jsep});
},
error: function(error) {
Janus.error("WebRTC error:", error);
if (useAudio) {
publishOwnFeed(false);
} else {
bootbox.alert("WebRTC error... " + JSON.stringify(error));
angular.element('#publish').removeAttr('disabled').click(function() { publishOwnFeed(true); });
}
}
});
}
function toggleMute() {
//to mute
}
function unpublishOwnFeed() {
// Unpublish our stream
}
function newRemoteFeed(id, display, audio, video) {
// A new feed has been published, create a new plugin handle and attach to it as a listener
var remoteFeed = null;
janus.attach(
{
plugin: "janus.plugin.videoroom",
opaqueId: opaqueId,
success: function(pluginHandle) {
remoteFeed = pluginHandle;
Janus.log("Plugin attached! (" + remoteFeed.getPlugin() + ", id=" + remoteFeed.getId() + ")");
// We wait for the plugin to send us an offer
var listen = { "request": "join", "room": myroom, "ptype": "listener", "feed": id, "private_id": mypvtid };
// In case you don't want to receive audio, video or data, even if the
// publisher is sending them, set the 'offer_audio', 'offer_video' or
// 'offer_data' properties to false (they're true by default), e.g.:
// listen["offer_video"] = false;
// For example, if the publisher is VP8 and this is Safari, let's avoid video
if(video !== "h264" && Janus.webRTCAdapter.browserDetails.browser === "safari") {
if(video)
video = video.toUpperCase()
toastr.warning("Publisher is using " + video + ", but Safari doesn't support it: disabling video");
listen["offer_video"] = false;
}
remoteFeed.send({"message": listen});
},
error: function(error) {
Janus.error(" -- Error attaching plugin...", error);
bootbox.alert("Error attaching plugin... " + error);
},
onmessage: function(msg, jsep) {
Janus.debug(" ::: Got a message (listener) :::");
Janus.debug(msg);
var event = msg["videoroom"];
Janus.debug("Event: " + event);
if(msg["error"] !== undefined && msg["error"] !== null) {
bootbox.alert(msg["error"]);
}
else if(event != undefined && event != null) {
if(event === "attached") {
// Subscriber created and attached
for(var i=1;i<6;i++) {
if(feeds[i] === undefined || feeds[i] === null) {
feeds[i] = remoteFeed;
remoteFeed.rfindex = i;
break;
}
}
remoteFeed.rfid = msg["id"];
remoteFeed.rfdisplay = msg["display"];
Janus.log("Successfully attached to feed " + remoteFeed.rfid + " (" + remoteFeed.rfdisplay + ") in room " + msg["room"]);
} else if(msg["error"] !== undefined && msg["error"] !== null) {
Janus.error(msg["error"]);
} else {
// What has just happened?
}
}
if(jsep !== undefined && jsep !== null) {
Janus.debug("Handling SDP as well...");
Janus.debug(jsep);
// Answer and attach
remoteFeed.createAnswer(
{
jsep: jsep,
// Add data:true here if you want to subscribe to datachannels as well
// (obviously only works if the publisher offered them in the first place)
media: { audioSend: false, videoSend: false }, // We want recvonly audio/video
success: function(jsep) {
Janus.debug("Got SDP!");
Janus.debug(jsep);
var body = { "request": "start", "room": myroom };
remoteFeed.send({"message": body, "jsep": jsep});
},
error: function(error) {
Janus.error("WebRTC error:", error);
bootbox.alert("WebRTC error... " + JSON.stringify(error));
}
});
}
},
webrtcState: function(on) {
Janus.log("Janus says this WebRTC PeerConnection (feed #" + remoteFeed.rfindex + ") is " + (on ? "up" : "down") + " now");
},
onlocalstream: function(stream) {
// The subscriber stream is recvonly, we don't expect anything here
},
onremotestream: function(stream) {
Janus.debug("Remote feed #" + remoteFeed.rfindex);
if(angular.element('#remotevideo'+remoteFeed.rfindex).length > 0) {
// Been here already: let's see if anything changed
var videoTracks = stream.getVideoTracks();
if(videoTracks && videoTracks.length > 0 && !videoTracks[0].muted) {
$('#novideo'+remoteFeed.rfindex).remove();
if($("#remotevideo"+remoteFeed.rfindex).get(0).videoWidth)
$('#remotevideo'+remoteFeed.rfindex).show();
}
return;
}
// No remote video yet
$('#videoremote'+remoteFeed.rfindex).append('');
$('#videoremote'+remoteFeed.rfindex).append('');
$('#videoremote'+remoteFeed.rfindex).append(
'' +
'');
// Show the video, hide the spinner and show the resolution when we get a playing event
$("#remotevideo"+remoteFeed.rfindex).bind("playing", function () {
if(remoteFeed.spinner !== undefined && remoteFeed.spinner !== null)
remoteFeed.spinner.stop();
remoteFeed.spinner = null;
$('#waitingvideo'+remoteFeed.rfindex).remove();
if(this.videoWidth)
$('#remotevideo'+remoteFeed.rfindex).removeClass('hide').show();
var width = this.videoWidth;
var height = this.videoHeight;
$('#curres'+remoteFeed.rfindex).removeClass('hide').text(width+'x'+height).show();
if(Janus.webRTCAdapter.browserDetails.browser === "firefox") {
// Firefox Stable has a bug: width and height are not immediately available after a playing
setTimeout(function() {
var width = $("#remotevideo"+remoteFeed.rfindex).get(0).videoWidth;
var height = $("#remotevideo"+remoteFeed.rfindex).get(0).videoHeight;
$('#curres'+remoteFeed.rfindex).removeClass('hide').text(width+'x'+height).show();
}, 2000);
}
});
Janus.attachMediaStream($('#remotevideo'+remoteFeed.rfindex).get(0), stream);
var videoTracks = stream.getVideoTracks();
if(videoTracks === null || videoTracks === undefined || videoTracks.length === 0 || videoTracks[0].muted) {
// No remote video
$('#remotevideo'+remoteFeed.rfindex).hide();
$('#videoremote'+remoteFeed.rfindex).append(
'' +
'' +
'No remote video available' +
'');
}
if(Janus.webRTCAdapter.browserDetails.browser === "chrome" || Janus.webRTCAdapter.browserDetails.browser === "firefox" ||
Janus.webRTCAdapter.browserDetails.browser === "safari") {
$('#curbitrate'+remoteFeed.rfindex).removeClass('hide').show();
bitrateTimer[remoteFeed.rfindex] = setInterval(function() {
// Display updated bitrate, if supported
var bitrate = remoteFeed.getBitrate();
$('#curbitrate'+remoteFeed.rfindex).text(bitrate);
// Check if the resolution changed too
var width = $("#remotevideo"+remoteFeed.rfindex).get(0).videoWidth;
var height = $("#remotevideo"+remoteFeed.rfindex).get(0).videoHeight;
if(width > 0 && height > 0)
$('#curres'+remoteFeed.rfindex).removeClass('hide').text(width+'x'+height).show();
}, 1000);
}
},
oncleanup: function() {
Janus.log(" ::: Got a cleanup notification (remote feed " + id + ") :::");
if(remoteFeed.spinner !== undefined && remoteFeed.spinner !== null)
remoteFeed.spinner.stop();
remoteFeed.spinner = null;
$('#remotevideo'+remoteFeed.rfindex).remove();
$('#waitingvideo'+remoteFeed.rfindex).remove();
$('#novideo'+remoteFeed.rfindex).remove();
$('#curbitrate'+remoteFeed.rfindex).remove();
$('#curres'+remoteFeed.rfindex).remove();
if(bitrateTimer[remoteFeed.rfindex] !== null && bitrateTimer[remoteFeed.rfindex] !== null)
clearInterval(bitrateTimer[remoteFeed.rfindex]);
bitrateTimer[remoteFeed.rfindex] = null;
remoteFeed.simulcastStarted = false;
$('#simulcast'+remoteFeed.rfindex).remove();
}
});
}
}]);
```
from home.html
```
{{$parent.p.perHardwareId}}
|
```
I'm a newbie to these all technologies and this is my university project. I must demonstrate this within this week. so I need help from someone expert.
if I use this div then it creating a div with periticular peripheral id.
```
{{$parent.p.perHardwareId}}
|
```
this is the janus.js file <https://github.com/meetecho/janus-gateway/blob/master/html/janus.js><issue_comment>username_1: If home.html code works for you then you can just loop over that using ng-repeat
```
{{item.perHardwareId}}
|`
```
And you can get the componenet using `videoremote_{{perHardwareId}}`
For example, if your `peripheralId is 7` then the element id will be `videoremote_7`
Upvotes: 1 <issue_comment>username_2: This is the woking answer for me.
```
### {{p.perHardwareId}}
Start
Stop
```
And I've set the stream id in the JanusController.js to same as the `id="videoremote_{{p.peripheralId}}`.
Upvotes: 0
|
2018/03/14
| 220 | 961 |
<issue_start>username_0: I have released my app on Google play store open beta testing channel 2 days before.It is visible to users,but some devices shows purchase options dialog even it is free app.Uninstall old app cache also not works.<issue_comment>username_1: This sounds like a bug. If you can reproduce it on a device, then can you take a screenshot (and ideally a bug report too) and contact Play developer support through the Play Console help section.
Upvotes: 2 <issue_comment>username_2: I've seen the same behavior today when trying to install on S7 Edge an app that installs another app. For example, an app that says "Uses ARCore - this will be installed as part of the installation process" (A good example is Figment AR).
This might not be the answer, but I hope it helps. If I installed the ARCore prior to the main installation then the main install worked just fine. Note that I did try and few AR apps before figuring this out.
Upvotes: 1
|
2018/03/14
| 1,052 | 2,554 |
<issue_start>username_0: I wrote this code but only works at first operation for example 1 2 + and it prints 3 as result but I need to give it an expression like this: 1 2 + 3 4 - \* and it must have to return the value 3.
Instead of that, my code prints 2115.
```
#include
#include
#include
using namespace std;
int main() {
float op1,op2,value;
string expression;
cin>>expression;
stackp;
for (int i=0;i
```<issue_comment>username_1: Here is the correct solution for your problem:
```
#include
#include
#include
#include //Header file for isdigit() function
using namespace std;
int main() {
float op1,op2,value;
string expression;
cin>>expression;
stackp;
for (int i=0;i
```
Upvotes: 0 <issue_comment>username_2: some modified
```
#include
#include
#include
#include
#include
using namespace std;
int main() {
float op1,op2,value;
string inputs ;
stack p;
vector nodes ;
op1=op2=value=0 ; // initialize to zero.
getline(cin, inputs) ;
cout << "input :" << inputs << endl ;
// tokenning by space
stringstream ss(inputs) ;
string item ;
while (getline(ss, item, ' ') ) {
nodes.push\_back(item) ;
cout << "token : "<<item << endl ;
}
for (int i=0;i<nodes.size();i++){
string node = nodes[i] ;
if ( isdigit(node[0]) ) {
p.push(stof(node));
cout << "push(num) :" << node << endl;
continue ;
}
if (node == "+"){
op2=p.top(); p.pop();
op1=p.top(); p.pop();
value=op1+op2;
cout << "add : "<<op1 << " " << op2 << "="<<value << endl;
p.push(value);
}
if (node == "-"){
op2=p.top(); p.pop();
op1=p.top(); p.pop();
value=op1-op2;
cout << "minus : "<<op1 << " " << op2 << "="<<value << endl;
p.push(value);
}
if (node=="\*"){
op2=p.top(); p.pop();
op1=p.top(); p.pop();
value=op1\*op2;
p.push(value);
cout << "mul : "<<op1 << " " << op2 << "="<<value << endl;
}
if (node=="/"){
op2=p.top(); p.pop();
op1=p.top(); p.pop();
value=op1/op2;
p.push(value);
cout << "div : "<<op1 << " " << op2 << "="<<value << endl;
}
}
cout<< "result="<< value<<endl;
}
</code>
```
output test
```
$ ./a.out
1 2 + 3 4 - *
input :1 2 + 3 4 - *
token : 1
token : 2
token : +
token : 3
token : 4
token : -
token : *
push(num) :1
push(num) :2
add : 1 2=3
push(num) :3
push(num) :4
minus : 3 4=-1
mul : 3 -1=-3
result=-3
$ ./a.out
4.5 1.5 + 9.0 3.0 / +
input :4.5 1.5 + 9.0 3.0 / +
token : 4.5
token : 1.5
token : +
token : 9.0
token : 3.0
token : /
token : +
push(num) :4.5
push(num) :1.5
add : 4.5 1.5=6
push(num) :9.0
push(num) :3.0
div : 9 3=3
add : 6 3=9
result=9
```
Upvotes: 2 [selected_answer]
|
2018/03/14
| 1,090 | 2,684 |
<issue_start>username_0: I have to create a regular expression which, for a given string s, captures the trimmed version of s into group 1. That is, for any string s, calling str\_replace(s, re1, "\1") should produce the same output as str\_trim(s). This is what I have to pass as the test case. I'm not sure where to begin..
```
for (s in c(
" this will be trimmed ",
"\t\nso will this\n\t ",
"and this too "
)) {
stopifnot(identical(
str_replace(s, re6, "\\1"),
str_trim(s)))
}
```
My regular expression is re6 = "..."
Thanks!<issue_comment>username_1: Here is the correct solution for your problem:
```
#include
#include
#include
#include //Header file for isdigit() function
using namespace std;
int main() {
float op1,op2,value;
string expression;
cin>>expression;
stackp;
for (int i=0;i
```
Upvotes: 0 <issue_comment>username_2: some modified
```
#include
#include
#include
#include
#include
using namespace std;
int main() {
float op1,op2,value;
string inputs ;
stack p;
vector nodes ;
op1=op2=value=0 ; // initialize to zero.
getline(cin, inputs) ;
cout << "input :" << inputs << endl ;
// tokenning by space
stringstream ss(inputs) ;
string item ;
while (getline(ss, item, ' ') ) {
nodes.push\_back(item) ;
cout << "token : "<<item << endl ;
}
for (int i=0;i<nodes.size();i++){
string node = nodes[i] ;
if ( isdigit(node[0]) ) {
p.push(stof(node));
cout << "push(num) :" << node << endl;
continue ;
}
if (node == "+"){
op2=p.top(); p.pop();
op1=p.top(); p.pop();
value=op1+op2;
cout << "add : "<<op1 << " " << op2 << "="<<value << endl;
p.push(value);
}
if (node == "-"){
op2=p.top(); p.pop();
op1=p.top(); p.pop();
value=op1-op2;
cout << "minus : "<<op1 << " " << op2 << "="<<value << endl;
p.push(value);
}
if (node=="\*"){
op2=p.top(); p.pop();
op1=p.top(); p.pop();
value=op1\*op2;
p.push(value);
cout << "mul : "<<op1 << " " << op2 << "="<<value << endl;
}
if (node=="/"){
op2=p.top(); p.pop();
op1=p.top(); p.pop();
value=op1/op2;
p.push(value);
cout << "div : "<<op1 << " " << op2 << "="<<value << endl;
}
}
cout<< "result="<< value<<endl;
}
</code>
```
output test
```
$ ./a.out
1 2 + 3 4 - *
input :1 2 + 3 4 - *
token : 1
token : 2
token : +
token : 3
token : 4
token : -
token : *
push(num) :1
push(num) :2
add : 1 2=3
push(num) :3
push(num) :4
minus : 3 4=-1
mul : 3 -1=-3
result=-3
$ ./a.out
4.5 1.5 + 9.0 3.0 / +
input :4.5 1.5 + 9.0 3.0 / +
token : 4.5
token : 1.5
token : +
token : 9.0
token : 3.0
token : /
token : +
push(num) :4.5
push(num) :1.5
add : 4.5 1.5=6
push(num) :9.0
push(num) :3.0
div : 9 3=3
add : 6 3=9
result=9
```
Upvotes: 2 [selected_answer]
|
2018/03/14
| 533 | 1,422 |
<issue_start>username_0: On my return response i am getting `start_time` like `10:00:00` in 24 hours format.I want to convert it in to two variables on `var a ="10:00"` and on `var b = "PM"` i tried it several times but not succeed. How can i do this.
Code on my php function :
```
$time = $actData->start_time; // 14:00:00
$startTime = date('h:i', strtotime($time)); // 02:00
$amPm = date('a', strtotime($time)); // PM
```
Same i want to do with scripts . How can i do this?<issue_comment>username_1: Here's how you could implement the time conversion:
```js
function convertFromMilitaryToStandard(time) {
var hour = time.slice(0,2),
pm = hour > 12,
hour12 = hour - (pm ? 12 : 0);
//Per the request of the OP, we keep them seperate:
var a = (hour12 < 10 ? "0" : "") + hour12 + time.slice(2,5);
var b = (pm ? "PM" : "AM");
return [a,b];
}
console.log(convertFromMilitaryToStandard("10:00:00"))
console.log(convertFromMilitaryToStandard("14:00:00"))
```
Upvotes: 2 [selected_answer]<issue_comment>username_2: Try this one
```
function parseTime(timeString)
{
if (timeString == '') return null;
var d = new Date();
var time = timeString.match(/(\d+)(:(\d\d))?\s*(p?)/i);
hrs = parseInt(time[1],10) + ( ( parseInt(time[1],10) < 12 && time[4] ) ? 12 : 0);
return amPm = hrs > 11 ? 'pm' : 'am';
}
time = '14:00:00';
var date = parseTime(time);
print(date);
```
Upvotes: 0
|
2018/03/14
| 642 | 2,550 |
<issue_start>username_0: I have a Multi branch pipeline project in Jenkins. I want to disable a branch while it is listed in pipeline project. I can add an exception to surpass scm triggering. But I want to disable all the triggering including manual triggering. If I used "Disable this project" under "Build triggers" in job created for a branch, that option is not selected when I reload the page(There are no save/apply buttons which is available for single branch pipelines). It only keeps follwing configuration that was configured in Jenkinsfile.
```
pipelineTriggers([
snapshotDependencies(),
]),
```
Are there any way to specify "Disable this project" in Jenkinsfile<issue_comment>username_1: True, **you cannot disable the project from Jenkins Job as multibranch pipeline doesn't give control to change the settings from the job**.
Two ways to stop your branch from building.
>
> 1) **Disable the Branch**
>
>
>
To get control of the settings, go to **PROJECT(project you want to modify the settings) > Configure > Projects( enable advanced settings)**
[](https://i.stack.imgur.com/wrwvE.png)
Enter the branch in **"Exclude branch"** and save the settings.
>
> 2) **Rename Jenkinsfile**
>
>
>
**If you don't have control of the project settings, the easy way is to rename the Jenkinsfile in the project/branch**.
[](https://i.stack.imgur.com/suyqy.png)
This configuration will define to trigger a build if a branch/project has "Jenkinsfile" in it. Hence, renaming it will not trigger a build.
Hope this helps..
**UPDATE** : AFAIK, **you can't disable the project from Jenkisfile**, but as workaround you can configure the cronjob as follows:
```
properties([pipelineTriggers([cron('')])])
```
**If configuration is not available in cron, the build will not trigger at all.**
Upvotes: 4 [selected_answer]<issue_comment>username_2: You can do something like this:
```
stages {
stage('Build') {
when {
not {
branch 'master'
}
}
steps {
...
}
}
}
```
Which isn't quite the same as not running the pipeline at all, but at least, it runs very quickly, and doesn't actually do the build, which is useful to have it not fail - say, if you are using a maven / gitflow pattern, where the master branch should not be built more than once, since the deployment would fail...
Upvotes: 2
|
2018/03/14
| 1,084 | 3,193 |
<issue_start>username_0: I am new to gstreamer, I want to record both audio and video save it into .mp4 format, Recording video using webcam and audio using MIC
Here this is my pipeline
>
> gst-launch-1.0 -e v4l2src ! queue ! x264enc ! h264parse ! queue ! qtmux0. alsasrc ! 'audio/x-raw,rate=44100,depth=24' ! audioconvert ! audioresample ! voaacenc ! aacparse ! qtmux ! filesink location=test.mp4
>
>
>
When i am executing it the video is recording only for 10sec the audio not even recording, Its giving some message like
>
> WARNING: from element /GstPipeline:pipeline0/GstAlsaSrc:alsasrc0: Can't record audio fast enough
> Additional debug info:
> gstaudiobasesrc.c(866): gst\_audio\_base\_src\_create (): /GstPipeline:pipeline0/GstAlsaSrc:alsasrc0:
> Dropped 425565 samples. This is most likely because downstream can't keep up and is consuming samples too slowly.
>
>
>
Help me get over through this Thank You in advance<issue_comment>username_1: got the pipeline now it is recording audio and video perfectly
Here the pipeline
>
> gst-launch-1.0 -e v4l2src ! 'video/x-raw,width=960,height=720,framerate=30/1' ! queue ! x264enc tune=zerolatency ! mux. alsasrc ! audio/x-raw,width=16,depth=16,rate=44100,channel=1 ! queue ! audioconvert ! audioresample ! voaacenc ! aacparse ! qtmux name=mux ! filesink location=test.mp4 sync=false
>
>
>
if still anything incorrect in the pipeline let me know
Upvotes: 0 <issue_comment>username_2: try with the following pipeline to record audio and video into one file.
```
gst-launch-1.0 -e v4l2src device="/dev/video0" ! videoconvert ! queue ! x264enc tune=zerolatency ! mux. alsasrc device="hw:2" ! queue ! audioconvert ! audioresample ! voaacenc ! aacparse ! qtmux name=mux ! filesink location=test.mp4 sync=false
```
Upvotes: 3 <issue_comment>username_3: I ended up using that one (adapted from a random response from the web, sorry i lost the source)
`raspivid -t 0 --vflip --hflip -w 1920 -h 1080 -fps 30 --bitrate 14000000 --profile baseline -3d sbs --intra 30 --inline --flush --awb auto --exposure auto --sharpness 0 --contrast -15 --digitalgain 0.0 -o - | gst-launch-1.0 -ve fdsrc num-buffers=-1 ! video/x-h264,width=1920,height=1080,framerate=30/1 ! h264parse ! queue ! smux.video alsasrc device=hw:2,0 ! audio/x-raw,format=S32LE,rate=48000,channel=2 ! audioconvert ! avenc_aac ! aacparse ! queue ! smux.audio_0 splitmuxsink name=smux location=video.mp4 muxer=mpegtsmux`
Note it's for capturing steroscopic image, you can drop "-3d sds" and adapt width for single cam. You can also safely drop the -ve which is only useful for debug and change your audio device hw to the number for your capture card (`$ arecord -l` to find out the id of your card).
I would prefer to use qtmux but it fails due to missing PTS info in the h264 stream made by raspivid. mpegtsmux is happy tho.
As of now, the resulting mpeg is half broken, and cannot be read by all players (quicktime fails, while vlc is happy). Reencoding with ffmpeg : `ffmpeg -vcodec mpeg4 -b:v 7561k -qscale:v 2 -acodec aac -ac 2 -async 1 -strict experimental ./video2.mp4 -threads 0 -i video.mp4` fixed the file.
Hope this is helpful to someone.
Upvotes: 0
|
2018/03/14
| 1,222 | 3,246 |
<issue_start>username_0: I have a file like this
```
name AD01392 AV93289 AG98023 A723928
xyb323 232 3232 8992 3278
xyb897 343 434 344 3434
xyvg87 439 3434 2434 43434
```
I need to extract the information in this file to 4 separate files that extract
column 1 and iterate over columns 2,3 and 4 then add another column with the header of the extracted column Like so
File 1
```
name AD01392
xyb323 232 AD01392
xyb897 343 AD01392
xyvg87 439 AD01392
```
File 2
```
name AV93289
xyb323 3232 AV93289
xyb897 434 AV93289
xyvg87 3434 AV93289
```
and so on for the other 2 files.
I can extract the columns with
```
awk '{print $1,$2}' file.tsv > file1.tsv
awk '{print $1,$3}' file.tsv > file2.tsv
awk '{print $1,$4}' file.tsv > file3.tsv
awk '{print $1,$5}' file.tsv > file5.tsv
```
but not sure how I can extract the first row from each column and add that as a column to all rows.
Thank you a lot for your help and contributions.<issue_comment>username_1: got the pipeline now it is recording audio and video perfectly
Here the pipeline
>
> gst-launch-1.0 -e v4l2src ! 'video/x-raw,width=960,height=720,framerate=30/1' ! queue ! x264enc tune=zerolatency ! mux. alsasrc ! audio/x-raw,width=16,depth=16,rate=44100,channel=1 ! queue ! audioconvert ! audioresample ! voaacenc ! aacparse ! qtmux name=mux ! filesink location=test.mp4 sync=false
>
>
>
if still anything incorrect in the pipeline let me know
Upvotes: 0 <issue_comment>username_2: try with the following pipeline to record audio and video into one file.
```
gst-launch-1.0 -e v4l2src device="/dev/video0" ! videoconvert ! queue ! x264enc tune=zerolatency ! mux. alsasrc device="hw:2" ! queue ! audioconvert ! audioresample ! voaacenc ! aacparse ! qtmux name=mux ! filesink location=test.mp4 sync=false
```
Upvotes: 3 <issue_comment>username_3: I ended up using that one (adapted from a random response from the web, sorry i lost the source)
`raspivid -t 0 --vflip --hflip -w 1920 -h 1080 -fps 30 --bitrate 14000000 --profile baseline -3d sbs --intra 30 --inline --flush --awb auto --exposure auto --sharpness 0 --contrast -15 --digitalgain 0.0 -o - | gst-launch-1.0 -ve fdsrc num-buffers=-1 ! video/x-h264,width=1920,height=1080,framerate=30/1 ! h264parse ! queue ! smux.video alsasrc device=hw:2,0 ! audio/x-raw,format=S32LE,rate=48000,channel=2 ! audioconvert ! avenc_aac ! aacparse ! queue ! smux.audio_0 splitmuxsink name=smux location=video.mp4 muxer=mpegtsmux`
Note it's for capturing steroscopic image, you can drop "-3d sds" and adapt width for single cam. You can also safely drop the -ve which is only useful for debug and change your audio device hw to the number for your capture card (`$ arecord -l` to find out the id of your card).
I would prefer to use qtmux but it fails due to missing PTS info in the h264 stream made by raspivid. mpegtsmux is happy tho.
As of now, the resulting mpeg is half broken, and cannot be read by all players (quicktime fails, while vlc is happy). Reencoding with ffmpeg : `ffmpeg -vcodec mpeg4 -b:v 7561k -qscale:v 2 -acodec aac -ac 2 -async 1 -strict experimental ./video2.mp4 -threads 0 -i video.mp4` fixed the file.
Hope this is helpful to someone.
Upvotes: 0
|
2018/03/14
| 923 | 3,132 |
<issue_start>username_0: I have read <https://developers.google.com/admob/android/quick-start?hl=en-US#import_the_mobile_ads_sdk>
I need to initialize MobileAds using Code A in order to display AdMob AD.
I have some activities which need to display ADs, do I need to add code A in my all activities?
And more, why can the AdMob Ad be displayed correctly even if I remove
```
MobileAds.initialize(this, "YOUR_ADMOB_APP_ID")
```
**Code A**
```
import com.google.android.gms.ads.MobileAds;
class MainActivity : AppCompatActivity() {
...
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// Sample AdMob app ID: ca-app-pub-3940256099942544~3347511713
MobileAds.initialize(this, "YOUR_ADMOB_APP_ID")
}
...
}
```<issue_comment>username_1: From the [docs](https://developers.google.com/android/reference/com/google/android/gms/ads/MobileAds.html#initialize(android.content.Context,%20java.lang.String)) of `MobileAds.initialize()`:
>
> This method should be called as early as possible, and **only once per
> application launch**.
>
>
>
The proper way to do this would be to call it in the `onCreate()` method of the `Application` class.
If you don't have an `Application` class, simply create one, something like this:
```
class YourApp: Application() {
override fun onCreate() {
super.onCreate()
MobileAds.initialize(this, "YOUR_ADMOB_APP_ID")
}
}
```
You have to reference this class in *AndroidManifest.xml*, by setting the `android:name` attribute of the `application` tag:
```
```
And regarding your question:
>
> why can the AdMob Ad be displayed correctly even if I remove
>
>
>
> ```
> MobileAds.initialize(this, "YOUR_ADMOB_APP_ID")
>
> ```
>
>
[Quote](https://groups.google.com/d/msg/google-admob-ads-sdk/kayQ3VZJqkU/QDewNIFpBAAJ) from **<NAME>** of the Mobile Ads SDK team:
>
> The Mobile Ads SDK take a few milliseconds to initialize itself and we
> now have provided this method to call it way before you even call your
> first ad. Once that is done, there would not be any added load time
> for your first request. If you do not call this, then your very first
> AdRequest would take a few milliseconds more as it first needs to
> initialize itself.
>
>
>
So basically if you do not call `MobileAds.initialize()`, then the first `AdRequest` will call it implicitly.
Upvotes: 6 [selected_answer]<issue_comment>username_2: Initializing MobileAds in Aplication context will cause error with InMobi mediation adapter
```
"Adapter Initialization status: Not Ready"
```
Tested with AdMob Test Suite.
Solution is to initialize MobileAds in Activity context.
Upvotes: 0 <issue_comment>username_3: `MobileAds.initialize(this, "YOUR-APP-ID")` has deprecated.
Use the below code instead.
```
import android.app.Application
import com.google.android.gms.ads.MobileAds
class MyApp: Application() {
override fun onCreate() {
MobileAds.initialize(applicationContext)
super.onCreate()
}
}
```
Upvotes: 2
|
2018/03/14
| 810 | 2,811 |
<issue_start>username_0: I have a table called total\_table in which the sum of the amount which has spent by a user will be stored, but every time when a new data enters it will create duplicate values to total table.
[](https://i.stack.imgur.com/7OsSy.png)
please check the above image where employee 10 added 100 so the total will be 610, now i need to delete the old data automatically when a new data inserts i.e 510 row must be deleted from the table.<issue_comment>username_1: From the [docs](https://developers.google.com/android/reference/com/google/android/gms/ads/MobileAds.html#initialize(android.content.Context,%20java.lang.String)) of `MobileAds.initialize()`:
>
> This method should be called as early as possible, and **only once per
> application launch**.
>
>
>
The proper way to do this would be to call it in the `onCreate()` method of the `Application` class.
If you don't have an `Application` class, simply create one, something like this:
```
class YourApp: Application() {
override fun onCreate() {
super.onCreate()
MobileAds.initialize(this, "YOUR_ADMOB_APP_ID")
}
}
```
You have to reference this class in *AndroidManifest.xml*, by setting the `android:name` attribute of the `application` tag:
```
```
And regarding your question:
>
> why can the AdMob Ad be displayed correctly even if I remove
>
>
>
> ```
> MobileAds.initialize(this, "YOUR_ADMOB_APP_ID")
>
> ```
>
>
[Quote](https://groups.google.com/d/msg/google-admob-ads-sdk/kayQ3VZJqkU/QDewNIFpBAAJ) from **<NAME>** of the Mobile Ads SDK team:
>
> The Mobile Ads SDK take a few milliseconds to initialize itself and we
> now have provided this method to call it way before you even call your
> first ad. Once that is done, there would not be any added load time
> for your first request. If you do not call this, then your very first
> AdRequest would take a few milliseconds more as it first needs to
> initialize itself.
>
>
>
So basically if you do not call `MobileAds.initialize()`, then the first `AdRequest` will call it implicitly.
Upvotes: 6 [selected_answer]<issue_comment>username_2: Initializing MobileAds in Aplication context will cause error with InMobi mediation adapter
```
"Adapter Initialization status: Not Ready"
```
Tested with AdMob Test Suite.
Solution is to initialize MobileAds in Activity context.
Upvotes: 0 <issue_comment>username_3: `MobileAds.initialize(this, "YOUR-APP-ID")` has deprecated.
Use the below code instead.
```
import android.app.Application
import com.google.android.gms.ads.MobileAds
class MyApp: Application() {
override fun onCreate() {
MobileAds.initialize(applicationContext)
super.onCreate()
}
}
```
Upvotes: 2
|
2018/03/14
| 988 | 3,339 |
<issue_start>username_0: I am using `fromHtml` to display formatted text (bold italic etc) in `TextView`. However, I found it's behaviour is different on JellyBean (4.1.2) and KitKat(4.4.2)
Here is code:
```
String myHtml = "**hello**😄";
Spanned spanned = Html.fromHtml(myHtml, null, null);
```
Here html string has `😄` which is unicode for an emoji. Now after calling `fromHtml` it returns following value on KitKat (and above):
```
spanned = hello
```
Here is screenshot of Android Studio for the same:
[](https://i.stack.imgur.com/uIASJ.png)
This is expected behaviour as we can see corresponding emoji in `spanned`.
But on JellyBean the same call returns following value:
```
spanned = hello��
```
Here is screenshot:
[](https://i.stack.imgur.com/c1aAQ.png)
This is indeed not expected and driving me nuts. I don't know what I am doing wrong. If anyone having idea please can you help?<issue_comment>username_1: From the [docs](https://developers.google.com/android/reference/com/google/android/gms/ads/MobileAds.html#initialize(android.content.Context,%20java.lang.String)) of `MobileAds.initialize()`:
>
> This method should be called as early as possible, and **only once per
> application launch**.
>
>
>
The proper way to do this would be to call it in the `onCreate()` method of the `Application` class.
If you don't have an `Application` class, simply create one, something like this:
```
class YourApp: Application() {
override fun onCreate() {
super.onCreate()
MobileAds.initialize(this, "YOUR_ADMOB_APP_ID")
}
}
```
You have to reference this class in *AndroidManifest.xml*, by setting the `android:name` attribute of the `application` tag:
```
```
And regarding your question:
>
> why can the AdMob Ad be displayed correctly even if I remove
>
>
>
> ```
> MobileAds.initialize(this, "YOUR_ADMOB_APP_ID")
>
> ```
>
>
[Quote](https://groups.google.com/d/msg/google-admob-ads-sdk/kayQ3VZJqkU/QDewNIFpBAAJ) from **<NAME>** of the Mobile Ads SDK team:
>
> The Mobile Ads SDK take a few milliseconds to initialize itself and we
> now have provided this method to call it way before you even call your
> first ad. Once that is done, there would not be any added load time
> for your first request. If you do not call this, then your very first
> AdRequest would take a few milliseconds more as it first needs to
> initialize itself.
>
>
>
So basically if you do not call `MobileAds.initialize()`, then the first `AdRequest` will call it implicitly.
Upvotes: 6 [selected_answer]<issue_comment>username_2: Initializing MobileAds in Aplication context will cause error with InMobi mediation adapter
```
"Adapter Initialization status: Not Ready"
```
Tested with AdMob Test Suite.
Solution is to initialize MobileAds in Activity context.
Upvotes: 0 <issue_comment>username_3: `MobileAds.initialize(this, "YOUR-APP-ID")` has deprecated.
Use the below code instead.
```
import android.app.Application
import com.google.android.gms.ads.MobileAds
class MyApp: Application() {
override fun onCreate() {
MobileAds.initialize(applicationContext)
super.onCreate()
}
}
```
Upvotes: 2
|
2018/03/14
| 3,982 | 11,513 |
<issue_start>username_0: Consider:
[](https://i.stack.imgur.com/s00Uy.png)
I am trying to find the area of an n-interesting polygon, where (n=1, A=1, n=2, A=5, n=3, A=13, n=4, A=25, and so on). So the formula for an n-interesting polygon is the area of an (n-1)-interesting polygon+(n-1)\*4. When running the program, a hidden test shows that the code is wrong. What is wrong with my code?
```
def shapeArea(n):
if n == 0:
return 0
if n == 1:
return 1
for i in range(2, n+1):
return (shapeArea(n-1) + (n-1)*4)
```<issue_comment>username_1: I found the formula without the recursion. The test went through fine.
```
def shapeArea(n):
if n>=10**4 or n<1:
return False
return (n**2+(n-1)**2)
```
Upvotes: 6 [selected_answer]<issue_comment>username_2: Like an alternative, I found a solution using a *for* loop.
```
def shapeArea(n):
return sum([( num * 4 ) for num in range(1, n)]) + 1
```
Upvotes: 1 <issue_comment>username_3: I think the last part where you have written the 'for' loop is dodgy. If you're already using recursion why do you need a 'for' loop? Nonetheless, I did it this way without using recursion:
```
def shapeArea(n):
if n == 1:
return 1
return n**2 + (n-1)**2
```
Upvotes: 3 <issue_comment>username_4: The easiest solution to the problem in JavaScript:
```
function shapeArea(n) {
if(n<0) {
return false
}
return (n*n) + ((n-1)*(n-1))
}
console.log(shapeArea(1))
```
Upvotes: 3 <issue_comment>username_5: This passed all the tests without performance issues:
```
def IncreasingSequence(sequence):
for x in range(0, len(sequence) - 1):
if sequence[y] >= sequence[x + 1]:
alt1 = sequence.copy()
alt2 = sequence.copy()
alt1.pop(x)
alt2.pop(x+1)
return (False, alt1, alt2)
return (True, sequence, sequence)
def almostIncreasingSequence(sequence):
boo, nl1, nl2 = IncreasingSequence(sequence)
if boo == False:
boo1, ll, ll1 = IncreasingSequence(nl1)
if boo1 == False:
boo2, l1, l2 =IncreasingSequence(nl2)
return boo2
return True
```
Upvotes: 1 <issue_comment>username_6: For C#, use this code:
```csharp
if (n == 0) {
return 0;
}
if (n == 1) {
return 1;
}
return Convert.ToInt32(Math.Pow((2*n - 1),2) - 2 * n * (n - 1));
// Math.Pow is used to calculate a number raise to the power of some other number
```
Upvotes: 0 <issue_comment>username_7: Use:
```
def shapeArea(n):
sum = 0
i = 1
while(n>1):
sum = sum + 2*i
n = n - 1
i = 2 + i
sum = sum + i
return sum
```
Try to calculate the sum of row wise squares (twice 2\*i) and add the middle row at the end.
Upvotes: 1 <issue_comment>username_8: An easy-to-understand solution in [Ruby](https://en.wikipedia.org/wiki/Ruby_%28programming_language%29) without recursion:
```rb
def shapeArea(n)
total = 0
(1..n-1).each do |column|
total += column + (column-1)
end
(total*2) + (n+(n-1))
end
```
* Both sides will have equal amounts of squares, except the center column that does not repeat. So we calculate the sides using the `(1..n-1)` loop, and the number of squares will be always `column + (column - 1)`;
* After that we just need to multiply this by 2 to get the sum of both sides `(total*2)` and add the center column `(n+(n-1))`.
Upvotes: 1 <issue_comment>username_9: As there are already coding examples, I will explain why the formula is n \* n + (n-1) \* (n-1)
1. You need to see the graph diagonally
2. You will notice that the sides are always n
3. For example, if n=4, the shape has for 4 squares on each side, thus
n \* n
4. However, if you notice, n \* n does not account for all the squares.
There are squares in between the once you accounted for
5. Take away the square you have accounted with n \* n, you will notice
now that the side of the shape is now n-1
6. Thus, you take into account of the squares in between,
the formula is n \* n + (n-1) \* (n-1)
7. Example: if n = 4, the outer square is 4 \* 4 = 16. Then take away the area you have just calculated, the inner squares is 3 \* 3 = 9. Add together, you get 25.
Upvotes: 5 <issue_comment>username_10: This is a formula to find an area of polygon for given n
```
def shapeArea(n):
return (n**2)+((n-1)**2)
shapeArea(3)
```
Output
```
13
```
Upvotes: 1 <issue_comment>username_11: This may be a solution:
```
function shapeArea(n) {
return ((n-1) * (n*2)) + 1;
}
```
Upvotes: 2 <issue_comment>username_12: ```
def shapeArea(n):
if n == 1:
return 1
square_side = n+n-1
outer_square_area = square_side**2
white_pieces = 4*(1/2)*n*(n+1)
area = outer_square - white_pieces
return area
```
A different approach to the problem:
If you notice, each n-interesting polygon can be contained in a surrounding square that has sides of length 2n-1. One could take this "outter square" and subtract the area of the missing white spaces.
Coming up with a formula for the white pieces is tricky because you have to add up these weird stair-step-like pieces on each of the 4 sides. The area for these weird pieces can actually be calculated using the formula for consecutive integers or `1/2*N(N+1)` (For this problem N=n-1)
This can easily be seen for for the n=2, the larger surrounding square side is 2+(2-1)=3 so the total area will be 9 - 4 = 5.
To better understand how the connection to how the white area is calculated see [the visualization behind the formula](http://jwilson.coe.uga.edu/EMAT6680Fa2013/Hendricks/Essay%202/Essay2.html). Notice how counting the area of these triangular blocks is similar to adding up integers from 1...n
Upvotes: 2 <issue_comment>username_13: If we see the given example,
when n=1, poly = 1
when n=2, poly = 5
when n=3, poly = 13
when n=4, poly = 25
the next pattern could be found by formula 2*n*(n-1) + 1:
```
def shapeArea(n):
return 2 * n * (n - 1) + 1;
```
Upvotes: 1 <issue_comment>username_14: **This works (Python 3):**
```
def shapeArea(n):
area = n*n + (n-1)*(n-1)
return area
print(shapeArea(5))
```
Upvotes: 1 <issue_comment>username_15: I initially read the problem wrong. I thought we need to find the outside edges.
Let's first see how we can do that...and then it will lead to a more intuitive solution later for this problem.
For the number of edges, I was looking at the outermost diagonal and see 2\*(n-1) edges on each of the four diagonals. It doesn't include the main four edges which are also present when n = 1.
So the total number of edges is (4 + 4 \* 2 \* (n-1))
Note that since we do not want to calculate number of edges, but the area, we will only use n-1 for the area rather than 2 \* (n-1).
Also, we need to subtract one since we were looking at outer edges...or how many additional squares the next iteration will need...so we will use (n-1)-1
Now let’s use this to calculate the area:
```none
n = 1 is 1
n = 2 we need to add 4 + 4* ((n-1)-1) squares or 4 + 4 * (n-2) squares
n = 3 we need to add an additional 4 + 4 * (n-2) squares
n = 4 we need to add an additional 4 + 4 * (n-2) squares
```
```
if n == 1:
return 1
area = 1
for n in range (1, n+1):
area += 4 + 4*(n-2)
return area
```
Upvotes: 0 <issue_comment>username_16: In Python:
In every increasing n, the 4's table is added to the previous one's polygon number:
```
def solution(n):
if n == 1:
return 1
else:
c = 0
for i in range(1, n):
c += 4*i
return c + 1
```
Upvotes: 0 <issue_comment>username_17: Here's an approach one can use to derive a formula.
The shapes always have a horizontal line across the middle. If you draw a rectangle that emcompasses both the top square and the horizontal line, there will always be a void of white squares within it large enough to be partially filled by the squares below the line.
Imagine that you fill that void above the line with the squares below the line. With the exception of n=1, your shape will be changed to a rectangle that still has some white squares in it. Let's look at a few.
```
n=2 n=3 n=4
. X . X X . . . X . . X X X . . . . . X . . . X X X X . . .
X X X X X X . X X X . X X X X X . . X X X . . X X X X X X X
. X . . . . X X X X X X X X X X . X X X X X . X X X X X X X
. X X X . . . . . . X X X X X X X X X X X X X X
. . X . . . . . . . . X X X X X . . . . . . . .
. . X X X . . . . . . . . .
. . . X . . . . . . . . . .
```
The new shape can be characterized with the formula: `area = height * width - gap`
If we chart that out to look for patterns, it looks like this:
```
n | height | width | gap
1 | 1 | 1 | 0
2 | 2 | 3 | 1
3 | 3 | 5 | 2
4 | 4 | 7 | 3
```
Both height and gap are counting by one, and width is skip-counting by 2. You can always characterize that linear trend as `n*skipValue +/- constant`. In this case,
```
height=n
width=2n-1
gap=n-1
```
Plugging those terms back into our formula for the area of the gapped rectangles,
`area = height * width - gap` becomes `area = n * (2n - 1) - (n - 1)`
Upvotes: 3 <issue_comment>username_18: How can we find the formula if we don't see the partitioning trick? The definition `f(1) = 1; f(n) = f(n-1) + 4*n for n > 1` relates an area to a length. We may therefore hypothesize that f(n) is quadratically related to n: `a*n*n + b*b +c`. We can determine the coefficients algebraically from the first 3 pairs: f(1) = 1, f(2) = 5, f(3) = 13, which give us 3 equations in 3 unknowns:
```
a + b + c = 1
4a + 2b + c = 5
9a + 3b + c = 13
```
Eliminating c = 1 - a - b first, we get
```
3a + b = 4
8a + 2b = 12
```
Eliminating b = 4 - 3a next, we get
```
2a = 4
```
Hence a = 2, b = -2, c = 1, so `f(n) = 2*n*(n-1) + 1`. We can verify by induction.
Note: Getting the formula for the sum of counts, `f(0) = 0; f(n) = f(n-1) + n for n > 0`, is even simpler because the first equation is `c = 0`. The remaining pair
```
a + b = 1
4a + 2b = 3
```
is easily solved to get a = b = 1/2, giving f(n) = n\*(n+1)/2.
Upvotes: 0 <issue_comment>username_19: ```
/**
Break down:
1= 1. 1 + 0
2 = 5. 1 + 4
3 = 13. 5 + 8
4 = 29 13 + 16
5 = 49 29 + 20
**/
int solution(int n) {
int area = poly(n);
System.out.println(area);
return area;
}
int poly(int n){
if(n == 1 ){
return 1;
}
else{
return poly(n-1) + side(n);
}
}
int side(int n){
if(n == 1 ){
return 0;
}
else{
return (n-1) * 4;
}
}
```
Upvotes: 0 <issue_comment>username_20: These worked fine for me.
```
n*n + (n-1) * (n-1)
n * (2*n - 1) - (n-1)
```
Upvotes: 1 <issue_comment>username_21: ```
int solution(int n) {
int nSquared = n * n;
int nTimesTwo = n * 2;
int leadingCoeficient = nSquared * 2;
int area = 0;
if (n == 1) {
area = n;
} else if (n == 2){
area = 5;
} else {
area = (leadingCoeficient-nTimesTwo)+1;
}
return area;
}
```
Upvotes: 0 <issue_comment>username_22: With JS:
```js
function solution(n) {
if (n >= Math.pow(10, 4) || n < 1) {
return false;
}
return Math.pow(n, 2) + Math.pow(n - 1, 2);
}
```
Upvotes: 0
|
2018/03/14
| 3,988 | 11,746 |
<issue_start>username_0: This code working fine. It throws errors and displayed to the webpage. But now i want to pick individual errors and display to the webpage.
```
// request.body validation
req.checkBody('email', 'Email is required.').notEmpty();
req.checkBody('name', 'Name is required.').notEmpty();
req.checkBody('phone', 'Phone is required.').isMobilePhone('en-IN');
req.checkBody('password1', 'Password is required.').isLength({min:6});
req.checkBody('password2', 'Password not same, try again!!').equals(password1);
var errors = req.validationErrors();
if (errors) {
console.log(req.body.params.errors);
res.render('form', {
errors: errors,
isForm: true,
register: true
});
} else {
console.log('PASSED');
}
```
What will be the code to console.log individual params of the errors?<issue_comment>username_1: I found the formula without the recursion. The test went through fine.
```
def shapeArea(n):
if n>=10**4 or n<1:
return False
return (n**2+(n-1)**2)
```
Upvotes: 6 [selected_answer]<issue_comment>username_2: Like an alternative, I found a solution using a *for* loop.
```
def shapeArea(n):
return sum([( num * 4 ) for num in range(1, n)]) + 1
```
Upvotes: 1 <issue_comment>username_3: I think the last part where you have written the 'for' loop is dodgy. If you're already using recursion why do you need a 'for' loop? Nonetheless, I did it this way without using recursion:
```
def shapeArea(n):
if n == 1:
return 1
return n**2 + (n-1)**2
```
Upvotes: 3 <issue_comment>username_4: The easiest solution to the problem in JavaScript:
```
function shapeArea(n) {
if(n<0) {
return false
}
return (n*n) + ((n-1)*(n-1))
}
console.log(shapeArea(1))
```
Upvotes: 3 <issue_comment>username_5: This passed all the tests without performance issues:
```
def IncreasingSequence(sequence):
for x in range(0, len(sequence) - 1):
if sequence[y] >= sequence[x + 1]:
alt1 = sequence.copy()
alt2 = sequence.copy()
alt1.pop(x)
alt2.pop(x+1)
return (False, alt1, alt2)
return (True, sequence, sequence)
def almostIncreasingSequence(sequence):
boo, nl1, nl2 = IncreasingSequence(sequence)
if boo == False:
boo1, ll, ll1 = IncreasingSequence(nl1)
if boo1 == False:
boo2, l1, l2 =IncreasingSequence(nl2)
return boo2
return True
```
Upvotes: 1 <issue_comment>username_6: For C#, use this code:
```csharp
if (n == 0) {
return 0;
}
if (n == 1) {
return 1;
}
return Convert.ToInt32(Math.Pow((2*n - 1),2) - 2 * n * (n - 1));
// Math.Pow is used to calculate a number raise to the power of some other number
```
Upvotes: 0 <issue_comment>username_7: Use:
```
def shapeArea(n):
sum = 0
i = 1
while(n>1):
sum = sum + 2*i
n = n - 1
i = 2 + i
sum = sum + i
return sum
```
Try to calculate the sum of row wise squares (twice 2\*i) and add the middle row at the end.
Upvotes: 1 <issue_comment>username_8: An easy-to-understand solution in [Ruby](https://en.wikipedia.org/wiki/Ruby_%28programming_language%29) without recursion:
```rb
def shapeArea(n)
total = 0
(1..n-1).each do |column|
total += column + (column-1)
end
(total*2) + (n+(n-1))
end
```
* Both sides will have equal amounts of squares, except the center column that does not repeat. So we calculate the sides using the `(1..n-1)` loop, and the number of squares will be always `column + (column - 1)`;
* After that we just need to multiply this by 2 to get the sum of both sides `(total*2)` and add the center column `(n+(n-1))`.
Upvotes: 1 <issue_comment>username_9: As there are already coding examples, I will explain why the formula is n \* n + (n-1) \* (n-1)
1. You need to see the graph diagonally
2. You will notice that the sides are always n
3. For example, if n=4, the shape has for 4 squares on each side, thus
n \* n
4. However, if you notice, n \* n does not account for all the squares.
There are squares in between the once you accounted for
5. Take away the square you have accounted with n \* n, you will notice
now that the side of the shape is now n-1
6. Thus, you take into account of the squares in between,
the formula is n \* n + (n-1) \* (n-1)
7. Example: if n = 4, the outer square is 4 \* 4 = 16. Then take away the area you have just calculated, the inner squares is 3 \* 3 = 9. Add together, you get 25.
Upvotes: 5 <issue_comment>username_10: This is a formula to find an area of polygon for given n
```
def shapeArea(n):
return (n**2)+((n-1)**2)
shapeArea(3)
```
Output
```
13
```
Upvotes: 1 <issue_comment>username_11: This may be a solution:
```
function shapeArea(n) {
return ((n-1) * (n*2)) + 1;
}
```
Upvotes: 2 <issue_comment>username_12: ```
def shapeArea(n):
if n == 1:
return 1
square_side = n+n-1
outer_square_area = square_side**2
white_pieces = 4*(1/2)*n*(n+1)
area = outer_square - white_pieces
return area
```
A different approach to the problem:
If you notice, each n-interesting polygon can be contained in a surrounding square that has sides of length 2n-1. One could take this "outter square" and subtract the area of the missing white spaces.
Coming up with a formula for the white pieces is tricky because you have to add up these weird stair-step-like pieces on each of the 4 sides. The area for these weird pieces can actually be calculated using the formula for consecutive integers or `1/2*N(N+1)` (For this problem N=n-1)
This can easily be seen for for the n=2, the larger surrounding square side is 2+(2-1)=3 so the total area will be 9 - 4 = 5.
To better understand how the connection to how the white area is calculated see [the visualization behind the formula](http://jwilson.coe.uga.edu/EMAT6680Fa2013/Hendricks/Essay%202/Essay2.html). Notice how counting the area of these triangular blocks is similar to adding up integers from 1...n
Upvotes: 2 <issue_comment>username_13: If we see the given example,
when n=1, poly = 1
when n=2, poly = 5
when n=3, poly = 13
when n=4, poly = 25
the next pattern could be found by formula 2*n*(n-1) + 1:
```
def shapeArea(n):
return 2 * n * (n - 1) + 1;
```
Upvotes: 1 <issue_comment>username_14: **This works (Python 3):**
```
def shapeArea(n):
area = n*n + (n-1)*(n-1)
return area
print(shapeArea(5))
```
Upvotes: 1 <issue_comment>username_15: I initially read the problem wrong. I thought we need to find the outside edges.
Let's first see how we can do that...and then it will lead to a more intuitive solution later for this problem.
For the number of edges, I was looking at the outermost diagonal and see 2\*(n-1) edges on each of the four diagonals. It doesn't include the main four edges which are also present when n = 1.
So the total number of edges is (4 + 4 \* 2 \* (n-1))
Note that since we do not want to calculate number of edges, but the area, we will only use n-1 for the area rather than 2 \* (n-1).
Also, we need to subtract one since we were looking at outer edges...or how many additional squares the next iteration will need...so we will use (n-1)-1
Now let’s use this to calculate the area:
```none
n = 1 is 1
n = 2 we need to add 4 + 4* ((n-1)-1) squares or 4 + 4 * (n-2) squares
n = 3 we need to add an additional 4 + 4 * (n-2) squares
n = 4 we need to add an additional 4 + 4 * (n-2) squares
```
```
if n == 1:
return 1
area = 1
for n in range (1, n+1):
area += 4 + 4*(n-2)
return area
```
Upvotes: 0 <issue_comment>username_16: In Python:
In every increasing n, the 4's table is added to the previous one's polygon number:
```
def solution(n):
if n == 1:
return 1
else:
c = 0
for i in range(1, n):
c += 4*i
return c + 1
```
Upvotes: 0 <issue_comment>username_17: Here's an approach one can use to derive a formula.
The shapes always have a horizontal line across the middle. If you draw a rectangle that emcompasses both the top square and the horizontal line, there will always be a void of white squares within it large enough to be partially filled by the squares below the line.
Imagine that you fill that void above the line with the squares below the line. With the exception of n=1, your shape will be changed to a rectangle that still has some white squares in it. Let's look at a few.
```
n=2 n=3 n=4
. X . X X . . . X . . X X X . . . . . X . . . X X X X . . .
X X X X X X . X X X . X X X X X . . X X X . . X X X X X X X
. X . . . . X X X X X X X X X X . X X X X X . X X X X X X X
. X X X . . . . . . X X X X X X X X X X X X X X
. . X . . . . . . . . X X X X X . . . . . . . .
. . X X X . . . . . . . . .
. . . X . . . . . . . . . .
```
The new shape can be characterized with the formula: `area = height * width - gap`
If we chart that out to look for patterns, it looks like this:
```
n | height | width | gap
1 | 1 | 1 | 0
2 | 2 | 3 | 1
3 | 3 | 5 | 2
4 | 4 | 7 | 3
```
Both height and gap are counting by one, and width is skip-counting by 2. You can always characterize that linear trend as `n*skipValue +/- constant`. In this case,
```
height=n
width=2n-1
gap=n-1
```
Plugging those terms back into our formula for the area of the gapped rectangles,
`area = height * width - gap` becomes `area = n * (2n - 1) - (n - 1)`
Upvotes: 3 <issue_comment>username_18: How can we find the formula if we don't see the partitioning trick? The definition `f(1) = 1; f(n) = f(n-1) + 4*n for n > 1` relates an area to a length. We may therefore hypothesize that f(n) is quadratically related to n: `a*n*n + b*b +c`. We can determine the coefficients algebraically from the first 3 pairs: f(1) = 1, f(2) = 5, f(3) = 13, which give us 3 equations in 3 unknowns:
```
a + b + c = 1
4a + 2b + c = 5
9a + 3b + c = 13
```
Eliminating c = 1 - a - b first, we get
```
3a + b = 4
8a + 2b = 12
```
Eliminating b = 4 - 3a next, we get
```
2a = 4
```
Hence a = 2, b = -2, c = 1, so `f(n) = 2*n*(n-1) + 1`. We can verify by induction.
Note: Getting the formula for the sum of counts, `f(0) = 0; f(n) = f(n-1) + n for n > 0`, is even simpler because the first equation is `c = 0`. The remaining pair
```
a + b = 1
4a + 2b = 3
```
is easily solved to get a = b = 1/2, giving f(n) = n\*(n+1)/2.
Upvotes: 0 <issue_comment>username_19: ```
/**
Break down:
1= 1. 1 + 0
2 = 5. 1 + 4
3 = 13. 5 + 8
4 = 29 13 + 16
5 = 49 29 + 20
**/
int solution(int n) {
int area = poly(n);
System.out.println(area);
return area;
}
int poly(int n){
if(n == 1 ){
return 1;
}
else{
return poly(n-1) + side(n);
}
}
int side(int n){
if(n == 1 ){
return 0;
}
else{
return (n-1) * 4;
}
}
```
Upvotes: 0 <issue_comment>username_20: These worked fine for me.
```
n*n + (n-1) * (n-1)
n * (2*n - 1) - (n-1)
```
Upvotes: 1 <issue_comment>username_21: ```
int solution(int n) {
int nSquared = n * n;
int nTimesTwo = n * 2;
int leadingCoeficient = nSquared * 2;
int area = 0;
if (n == 1) {
area = n;
} else if (n == 2){
area = 5;
} else {
area = (leadingCoeficient-nTimesTwo)+1;
}
return area;
}
```
Upvotes: 0 <issue_comment>username_22: With JS:
```js
function solution(n) {
if (n >= Math.pow(10, 4) || n < 1) {
return false;
}
return Math.pow(n, 2) + Math.pow(n - 1, 2);
}
```
Upvotes: 0
|
2018/03/14
| 3,784 | 11,006 |
<issue_start>username_0: Unable to show hint in edit text view when using `inputtype = textWebPassword` in layout.<issue_comment>username_1: I found the formula without the recursion. The test went through fine.
```
def shapeArea(n):
if n>=10**4 or n<1:
return False
return (n**2+(n-1)**2)
```
Upvotes: 6 [selected_answer]<issue_comment>username_2: Like an alternative, I found a solution using a *for* loop.
```
def shapeArea(n):
return sum([( num * 4 ) for num in range(1, n)]) + 1
```
Upvotes: 1 <issue_comment>username_3: I think the last part where you have written the 'for' loop is dodgy. If you're already using recursion why do you need a 'for' loop? Nonetheless, I did it this way without using recursion:
```
def shapeArea(n):
if n == 1:
return 1
return n**2 + (n-1)**2
```
Upvotes: 3 <issue_comment>username_4: The easiest solution to the problem in JavaScript:
```
function shapeArea(n) {
if(n<0) {
return false
}
return (n*n) + ((n-1)*(n-1))
}
console.log(shapeArea(1))
```
Upvotes: 3 <issue_comment>username_5: This passed all the tests without performance issues:
```
def IncreasingSequence(sequence):
for x in range(0, len(sequence) - 1):
if sequence[y] >= sequence[x + 1]:
alt1 = sequence.copy()
alt2 = sequence.copy()
alt1.pop(x)
alt2.pop(x+1)
return (False, alt1, alt2)
return (True, sequence, sequence)
def almostIncreasingSequence(sequence):
boo, nl1, nl2 = IncreasingSequence(sequence)
if boo == False:
boo1, ll, ll1 = IncreasingSequence(nl1)
if boo1 == False:
boo2, l1, l2 =IncreasingSequence(nl2)
return boo2
return True
```
Upvotes: 1 <issue_comment>username_6: For C#, use this code:
```csharp
if (n == 0) {
return 0;
}
if (n == 1) {
return 1;
}
return Convert.ToInt32(Math.Pow((2*n - 1),2) - 2 * n * (n - 1));
// Math.Pow is used to calculate a number raise to the power of some other number
```
Upvotes: 0 <issue_comment>username_7: Use:
```
def shapeArea(n):
sum = 0
i = 1
while(n>1):
sum = sum + 2*i
n = n - 1
i = 2 + i
sum = sum + i
return sum
```
Try to calculate the sum of row wise squares (twice 2\*i) and add the middle row at the end.
Upvotes: 1 <issue_comment>username_8: An easy-to-understand solution in [Ruby](https://en.wikipedia.org/wiki/Ruby_%28programming_language%29) without recursion:
```rb
def shapeArea(n)
total = 0
(1..n-1).each do |column|
total += column + (column-1)
end
(total*2) + (n+(n-1))
end
```
* Both sides will have equal amounts of squares, except the center column that does not repeat. So we calculate the sides using the `(1..n-1)` loop, and the number of squares will be always `column + (column - 1)`;
* After that we just need to multiply this by 2 to get the sum of both sides `(total*2)` and add the center column `(n+(n-1))`.
Upvotes: 1 <issue_comment>username_9: As there are already coding examples, I will explain why the formula is n \* n + (n-1) \* (n-1)
1. You need to see the graph diagonally
2. You will notice that the sides are always n
3. For example, if n=4, the shape has for 4 squares on each side, thus
n \* n
4. However, if you notice, n \* n does not account for all the squares.
There are squares in between the once you accounted for
5. Take away the square you have accounted with n \* n, you will notice
now that the side of the shape is now n-1
6. Thus, you take into account of the squares in between,
the formula is n \* n + (n-1) \* (n-1)
7. Example: if n = 4, the outer square is 4 \* 4 = 16. Then take away the area you have just calculated, the inner squares is 3 \* 3 = 9. Add together, you get 25.
Upvotes: 5 <issue_comment>username_10: This is a formula to find an area of polygon for given n
```
def shapeArea(n):
return (n**2)+((n-1)**2)
shapeArea(3)
```
Output
```
13
```
Upvotes: 1 <issue_comment>username_11: This may be a solution:
```
function shapeArea(n) {
return ((n-1) * (n*2)) + 1;
}
```
Upvotes: 2 <issue_comment>username_12: ```
def shapeArea(n):
if n == 1:
return 1
square_side = n+n-1
outer_square_area = square_side**2
white_pieces = 4*(1/2)*n*(n+1)
area = outer_square - white_pieces
return area
```
A different approach to the problem:
If you notice, each n-interesting polygon can be contained in a surrounding square that has sides of length 2n-1. One could take this "outter square" and subtract the area of the missing white spaces.
Coming up with a formula for the white pieces is tricky because you have to add up these weird stair-step-like pieces on each of the 4 sides. The area for these weird pieces can actually be calculated using the formula for consecutive integers or `1/2*N(N+1)` (For this problem N=n-1)
This can easily be seen for for the n=2, the larger surrounding square side is 2+(2-1)=3 so the total area will be 9 - 4 = 5.
To better understand how the connection to how the white area is calculated see [the visualization behind the formula](http://jwilson.coe.uga.edu/EMAT6680Fa2013/Hendricks/Essay%202/Essay2.html). Notice how counting the area of these triangular blocks is similar to adding up integers from 1...n
Upvotes: 2 <issue_comment>username_13: If we see the given example,
when n=1, poly = 1
when n=2, poly = 5
when n=3, poly = 13
when n=4, poly = 25
the next pattern could be found by formula 2*n*(n-1) + 1:
```
def shapeArea(n):
return 2 * n * (n - 1) + 1;
```
Upvotes: 1 <issue_comment>username_14: **This works (Python 3):**
```
def shapeArea(n):
area = n*n + (n-1)*(n-1)
return area
print(shapeArea(5))
```
Upvotes: 1 <issue_comment>username_15: I initially read the problem wrong. I thought we need to find the outside edges.
Let's first see how we can do that...and then it will lead to a more intuitive solution later for this problem.
For the number of edges, I was looking at the outermost diagonal and see 2\*(n-1) edges on each of the four diagonals. It doesn't include the main four edges which are also present when n = 1.
So the total number of edges is (4 + 4 \* 2 \* (n-1))
Note that since we do not want to calculate number of edges, but the area, we will only use n-1 for the area rather than 2 \* (n-1).
Also, we need to subtract one since we were looking at outer edges...or how many additional squares the next iteration will need...so we will use (n-1)-1
Now let’s use this to calculate the area:
```none
n = 1 is 1
n = 2 we need to add 4 + 4* ((n-1)-1) squares or 4 + 4 * (n-2) squares
n = 3 we need to add an additional 4 + 4 * (n-2) squares
n = 4 we need to add an additional 4 + 4 * (n-2) squares
```
```
if n == 1:
return 1
area = 1
for n in range (1, n+1):
area += 4 + 4*(n-2)
return area
```
Upvotes: 0 <issue_comment>username_16: In Python:
In every increasing n, the 4's table is added to the previous one's polygon number:
```
def solution(n):
if n == 1:
return 1
else:
c = 0
for i in range(1, n):
c += 4*i
return c + 1
```
Upvotes: 0 <issue_comment>username_17: Here's an approach one can use to derive a formula.
The shapes always have a horizontal line across the middle. If you draw a rectangle that emcompasses both the top square and the horizontal line, there will always be a void of white squares within it large enough to be partially filled by the squares below the line.
Imagine that you fill that void above the line with the squares below the line. With the exception of n=1, your shape will be changed to a rectangle that still has some white squares in it. Let's look at a few.
```
n=2 n=3 n=4
. X . X X . . . X . . X X X . . . . . X . . . X X X X . . .
X X X X X X . X X X . X X X X X . . X X X . . X X X X X X X
. X . . . . X X X X X X X X X X . X X X X X . X X X X X X X
. X X X . . . . . . X X X X X X X X X X X X X X
. . X . . . . . . . . X X X X X . . . . . . . .
. . X X X . . . . . . . . .
. . . X . . . . . . . . . .
```
The new shape can be characterized with the formula: `area = height * width - gap`
If we chart that out to look for patterns, it looks like this:
```
n | height | width | gap
1 | 1 | 1 | 0
2 | 2 | 3 | 1
3 | 3 | 5 | 2
4 | 4 | 7 | 3
```
Both height and gap are counting by one, and width is skip-counting by 2. You can always characterize that linear trend as `n*skipValue +/- constant`. In this case,
```
height=n
width=2n-1
gap=n-1
```
Plugging those terms back into our formula for the area of the gapped rectangles,
`area = height * width - gap` becomes `area = n * (2n - 1) - (n - 1)`
Upvotes: 3 <issue_comment>username_18: How can we find the formula if we don't see the partitioning trick? The definition `f(1) = 1; f(n) = f(n-1) + 4*n for n > 1` relates an area to a length. We may therefore hypothesize that f(n) is quadratically related to n: `a*n*n + b*b +c`. We can determine the coefficients algebraically from the first 3 pairs: f(1) = 1, f(2) = 5, f(3) = 13, which give us 3 equations in 3 unknowns:
```
a + b + c = 1
4a + 2b + c = 5
9a + 3b + c = 13
```
Eliminating c = 1 - a - b first, we get
```
3a + b = 4
8a + 2b = 12
```
Eliminating b = 4 - 3a next, we get
```
2a = 4
```
Hence a = 2, b = -2, c = 1, so `f(n) = 2*n*(n-1) + 1`. We can verify by induction.
Note: Getting the formula for the sum of counts, `f(0) = 0; f(n) = f(n-1) + n for n > 0`, is even simpler because the first equation is `c = 0`. The remaining pair
```
a + b = 1
4a + 2b = 3
```
is easily solved to get a = b = 1/2, giving f(n) = n\*(n+1)/2.
Upvotes: 0 <issue_comment>username_19: ```
/**
Break down:
1= 1. 1 + 0
2 = 5. 1 + 4
3 = 13. 5 + 8
4 = 29 13 + 16
5 = 49 29 + 20
**/
int solution(int n) {
int area = poly(n);
System.out.println(area);
return area;
}
int poly(int n){
if(n == 1 ){
return 1;
}
else{
return poly(n-1) + side(n);
}
}
int side(int n){
if(n == 1 ){
return 0;
}
else{
return (n-1) * 4;
}
}
```
Upvotes: 0 <issue_comment>username_20: These worked fine for me.
```
n*n + (n-1) * (n-1)
n * (2*n - 1) - (n-1)
```
Upvotes: 1 <issue_comment>username_21: ```
int solution(int n) {
int nSquared = n * n;
int nTimesTwo = n * 2;
int leadingCoeficient = nSquared * 2;
int area = 0;
if (n == 1) {
area = n;
} else if (n == 2){
area = 5;
} else {
area = (leadingCoeficient-nTimesTwo)+1;
}
return area;
}
```
Upvotes: 0 <issue_comment>username_22: With JS:
```js
function solution(n) {
if (n >= Math.pow(10, 4) || n < 1) {
return false;
}
return Math.pow(n, 2) + Math.pow(n - 1, 2);
}
```
Upvotes: 0
|
2018/03/14
| 458 | 1,544 |
<issue_start>username_0: I'm trying to pass arguments into a mongo query - if I type the literal, it works fine, however, when I try to replace the literal with the variable (argument), it fails
imagine a data set with "things"
```
{"thing": {"name":"book","label":"Bobs"}}
{"thing": {"name":"blanket","label":"Bobs"},
{"thing": {"name":"books","label":"Jills"},
{"thing": {"name":"blankets","label":"Jills"},
```
I have a method to find "Book" "book" "Books" "books" or "blankets"
If I do this with the literal 'Book' - it works
```
function( name, callback ) {
Catalog
.find({ 'thing.name': {"$regex": /Book/, "$options": "i" }})
.exec(callback);
}
```
However - I want the argument 'name' to be used.
```
function( name, callback ) {
Catalog
.find({ 'thing.name': {"$regex": /name/, "$options": "i" } })
.exec(callback);
}
```
But this doesn't work, it appears to be looking for the literal 'name' not the passed in value. how to i escape this?<issue_comment>username_1: Create an instance of `RegExp` class. It also allows you to remove `$options` property from the query, like below:
```
function( name, callback ) {
var regexName = new RegExp(name, "i");
Catalog
.find({ 'thing.name': { "$regex": regexName } })
.exec(callback);
}
```
Upvotes: 1 <issue_comment>username_2: Could be done like this:-
```js
function( name, callback ) {
Catalog
.find({ "thing.name": { $regex: name, $options: "i" }})
.exec(callback);
}
```
Upvotes: 2
|
2018/03/14
| 601 | 2,272 |
<issue_start>username_0: I'm trying to make a game with react native and I want to show a different options when i change the picker value.
basically when I select the first option on the picker a component has to appear and when I select the second one another component.
I tried this function but not working
```
pickerOptionText = () => {
if (this.state.PickerValueHolder==this.state.filter[0]) {
return (
{instructions[2]}
);
}else {
return (
{instructions[1]}
);
}
return null;
}
```
here is my code
===============
```
export default class Facil extends Component {
constructor(props)
{
super(props);
this.state = {
isLoading: true,
PickerValueHolder : '',
filter: [
{
"option":"Palabras por categoria"
},
{
"option":"Palabras por caracteres"
}
],
dataSource:[]
}
}
componentDidMount() {
return fetch(API_URL)
.then((response) => response.json())
.then((responseJson) => {
this.setState({
isLoading: false,
dataSource: responseJson
})
})
.catch((error) => {
console.error(error);
});
}
render() {
const resizeMode = 'stretch';
pickerOptionText = () => {
if (this.state.PickerValueHolder==this.state.filter[0]) {
return (
{instructions[2]}
);
}else {
return (
{instructions[1]}
);
}
return null;
}
return (
MODO FACIL
{instructions[0]}
this.setState({PickerValueHolder: itemValue})} >
{ this.state.filter.map((item, key)=>(
)
)}
[dynamic options]
{pickerOptionText}
Play!
);
}
}
```<issue_comment>username_1: Create an instance of `RegExp` class. It also allows you to remove `$options` property from the query, like below:
```
function( name, callback ) {
var regexName = new RegExp(name, "i");
Catalog
.find({ 'thing.name': { "$regex": regexName } })
.exec(callback);
}
```
Upvotes: 1 <issue_comment>username_2: Could be done like this:-
```js
function( name, callback ) {
Catalog
.find({ "thing.name": { $regex: name, $options: "i" }})
.exec(callback);
}
```
Upvotes: 2
|
2018/03/14
| 1,240 | 4,742 |
<issue_start>username_0: I encountered the Unsupported Image Type error due to an incompatible colour profile using `com.sun.imageio.plugins.jpeg.JPEGImageReader`. I later found the TwelveMonkeys plugins that are proven to fix this issue and have referenced the dependent .jars in my project classpath. I downloaded them from the TwelveMonkeys github repository. Note i'm using version 3.0.2 because I'm running on Java 6 with JDK 1.6.0\_45. These are the .jars I've added to my project:
```
common-lang-3.0.2.jar
common-io-3.0.2.jar
common-image-3.0.2.jar
imageio-core-3.0.2.jar
imageio-metadata-3.0.2.jar
imageio-jpeg-3.0.2.jar
```
I was able to test the library is installed and working using the following test:
```
Iterator readers = ImageIO.getImageReadersByFormatName("JPEG");
while (readers.hasNext()) {
System.out.println("reader: " + readers.next());
}
```
Which outputs:
```
reader: com.twelvemonkeys.imageio.plugins.jpeg.JPEGImageReader@4102799c
reader: com.sun.imageio.plugins.jpeg.JPEGImageReader@33d6f122
```
When i run my code, it is still trying to read the JPEG with `com.sun.imageio.plugins.jpeg.JPEGImageReader` and continues to throw the IIOException. Any ideas?
UPDATE:
Its looking like iTextPDF is causing the issue which is a library used by the project. I setup a barebone test application that converts a CMYK JPEG to a `BufferedImage` and then calls `ImageIO.read(img)` and it works fine. I'm struggling to see a reason why iText wouldn't be finding the TwelveMonkeys plugin when it calls `ImageIO.read(img)` when they're in the same project and classpath, but that's probably due to my limited knowledge. I should also add that the application i'm working on is part of a web service API.<issue_comment>username_1: As often is the case, when an ImageIO plugin isn't used at run-time from a web application, the cause is that the service provider isn't found because `ImageIO` is already initialized, and has invoked `scanForPlugins()` before the web app's libraries were available to the JVM.
From [Deploying [ImageIO] plugins in a web app](https://github.com/haraldk/TwelveMonkeys#deploying-the-plugins-in-a-web-app):
>
> Because the ImageIO plugin registry (the `IIORegistry`) is "VM global", it doesn't by default work well with servlet contexts. This is especially evident if you load plugins from the `WEB-INF/lib` or `classes` folder. Unless you add `ImageIO.scanForPlugins()` somewhere in your code, the plugins might never be available at all.
>
>
> In addition, servlet contexts dynamically loads and unloads classes (using a new class loader per context). If you restart your application, old classes will by default remain in memory forever (because the next time `scanForPlugins` is called, it's another `ClassLoader` that scans/loads classes, and thus they will be new instances in the registry). If a read is attempted using one of the remaining "old" readers, weird exceptions (like `NullPointerExceptions` when accessing static final initialized fields or `NoClassDefFoundErrors` for uninitialized inner classes) may occur.
>
>
> To work around both the discovery problem and the resource leak, it is strongly recommended to use the `IIOProviderContextListener` that implements dynamic loading and unloading of ImageIO plugins for web applications.
>
>
>
The `IIOProviderContextListener` is contained in the `twelvemonkeys-servlet.jar`, and must be registered in your application's `web.xml` (or similar if using Spring or other framework). See the above link for details.
Another safe alternative to using the context listener, is to place the JAR files in the application server's shared or common lib folder, instead of the `WEB-INF/lib` folder inside your web application.
PS: The above problem/solution applies to ImageIO plugins in general, not just the TwelveMonkeys plugins. Because of this, the context listener has no dependencies to the TwelveMonkeys ImageIO plugins, and may be used with JAI ImageIO or other ImageIO plugins as well.
Upvotes: 3 [selected_answer]<issue_comment>username_2: For Spring Boot applications where there is no web.xml, you need to register the `IIOProviderContextListener` in your `@SpringBootApplication` class which should extend `SpringBootServletInitializer`:
```
@Override
public void onStartup(final ServletContext servletContext) throws ServletException {
super.onStartup(servletContext);
// Register the listener from Twelvemonkeys to support CMYK image handling with ImageIO
servletContext.addListener(IIOProviderContextListener.class);
}
```
Also see [this issue](https://github.com/haraldk/TwelveMonkeys/issues/16#issuecomment-326128071) where this is explained in more detail.
Upvotes: 0
|
2018/03/14
| 657 | 2,586 |
<issue_start>username_0: I'm trying to code a function that will enable me to change the console color quicker.
It would be something like:
```
public static void setColor(string color)
{
Console.ForegroundColor = ConsoleColor.color;
}
```
and then instead of typing out the middle part I would be able to quickly set the color by just typing setColor(blue).
Is this possible in any way?<issue_comment>username_1: You could use [`Enum.Parse`](https://msdn.microsoft.com/en-us/library/kxydatf9(v=vs.110).aspx) and just look for the color in the [ConsoleColor Enumeration](https://msdn.microsoft.com/en-us/library/system.consolecolor(v=vs.110).aspx)
>
> Specifies constants that define foreground and background colors for
> the console.
>
>
>
**Exmaple**
```
public static void setColor(string color)
{
try
{
Console.ForegroundColor = (ConsoleColor)Enum.Parse(typeof(ConsoleColor), color, true);
}
catch (Exception)
{
//catch error for an invalid color
}
}
```
Upvotes: 0 <issue_comment>username_2: I don't know what "quicker" means to you here. But if you feel the need to do this, you're probably using your tools wrong.
Even ignoring the fact the you can't pass the string "blue" and have it work there (since it's a string, not a piece of code), there's really nothnig quicker in writing `setColor("blue")` than writing `Console.ForegroundColor = ConsoleColor.Blue`, even if your typing speed is very slow.
Instead of creating additional layers of abstractions that do nothing but save very, very few keystrokes, learn to use the tools you have better. Learn to use the IDE's autocomplete and intellisense, so that your can start typing "Console", see when intellisense matches it, then simply press `.` and start typing "Foreground" and see how many keys you need for it to be caught (hint: very few).
The disadvantages of creating a wrapper method is that it masks what is actually happening (wait, is it setting foreground color or background color?) and a month from now, you might not remember. It means *other* developers won't know what's going on - this might be a personal project, but it's a bad habit to have going forward. And it means that this method now needs to be available everywhere, in every class you write, which is also messy.
This method adds almost nothing. I would avoid using it, and look for other ways to "increase productivity" - because saving a few keystrokes *isn't* the way. Most of your time as a developer is spent thinking and looking things up, not *typing*.
Upvotes: 2
|
2018/03/14
| 1,097 | 4,946 |
<issue_start>username_0: Imagine a situation when the application layer opens a new transaction and you want to perform 2 repository operations under this transaction. Let's say I want to add a new User with IUserRepository and afterwards save all events that were generated during User domain model state change. I open a new transaction in ApplicationLayer (TransactionScope), then perform these 2 operations. But what if tommorow I want to change the repository implementation to FileBasedRepository or HttpCloudRepository. Repositories don't know about the fact that they are running under some transaction, or should they?
The main question is about abstractions. We all strive to write code based on abstractions. What I see is if I implemented a unit of work and I update 2 aggregates using 2 repositories in application layer(repositories work with MSSql), tommorow I can't change one of the repositories implementations to httpbased or in memory based. The question is about how to write such code. Seems like I have to create an abstraction over transaction and implement rollbacks by my own for HttpUnitOfWork. Feels like my initial unit of work is tightly coupled to db and shoould be renamed DbUnitOfWork. But that's wrong again, cause there are no sql databased which don't support transactions at all.<issue_comment>username_1: **Repositories and transaction**
To me, a Repository shouldn't know about the ambient transaction - there should be a Unit of Work-like container that keeps track of updated entities and commits the transaction when you declare the Unit of Work Complete.
**Repositories with alternative sources**
It shouldn't be a problem to mix data coming from repositories with different origins in the same unit of work. *Ideally*, the UoW would know which persistence mechanism goes with which type of entity and sort it all out in the end.
For practical reasons though, you might want to limit your UoW to a single persistent store (usually a database via an ORM) and add to repositories that have different, transaction-illiterate data sources methods like `Update(entity)` that save directly to the source when called.
Upvotes: 1 <issue_comment>username_2: >
> Repositories don't know about the fact that they are running under some transaction, or should they?
>
>
>
Here's what Evan's wrote, in the [Blue Book](http://a.co/jknnUpq)
>
> The REPOSITORY concept is adaptable to many situations. The possibilities of implementation are so diverse that I can only list some concerns to keep in mind....
> *Leave transaction control to the client*. Although the REPOSITORY will insert and delete from the database, it will ordinarily not commit anything.... Transaction management will be simpler if the REPOSITORY keeps its hands off.
>
>
>
To be absolutely honest, I find this notion difficult to reconcile with other writings from the same chapter.
>
> For each type of object that needs global access, create ( a REPOSITORY ) that can provide the illusion of an in-memory collection of all objects of that set.
>
>
>
In the languages that I normally use, in-memory collections typically manage their own state. Doesn't that imply that transaction control should be behind the collection interface, rather than left to the client?
An additional point is that our persistence solutions have gotten a lot more complex; for Evans, the domain model was only managing writes to a single database, which supported transactions that could span multiple aggregates (ie, an RDBMS). But if you change that assumption, then a lot of things start to become more complicated.
[cqrs](/questions/tagged/cqrs "show questions tagged 'cqrs'") offers some hints, here. *Reading* from repositories is beautiful; you take all of the complexity of the implementation and hide it behind some persistence agnostic facade. Writing can be trickier -- if your domain model needs support for saving multiple aggregates together (same transaction), then your "repository" interface should make that explicit.
These days, you are likely to see more support for the idea that modifications of aggregates should always happen in separate transactions. That takes some of the pressure off of repository coordination.
Upvotes: 3 [selected_answer]<issue_comment>username_3: The repository has no knowledge of the context in which it is used. As such, the repository should not be responsible for starting, committing or rollbacking a transaction.
Therefore, I always pass a UnitOfWork / DbSession / whatever to my repository. The repository uses that UnitOfWork, and the transaction is committed outside the repository.
In pseudo code, this looks like this:
```
var uow = DatabaseContext.CreateUnitOfWork();
uow.StartTransaction();
var productRepository = new ProductRepository(uow);
var customerRepository = new CustomerRepository(uow);
// ... do some operations on the repositories.
uow.Commit();
```
Upvotes: 2
|
2018/03/14
| 975 | 4,174 |
<issue_start>username_0: I'm trying to find the correct regex to search a file for **double quoted numbers separated by a comma**. For example I'm trying to find `"27,422,734"` and then replace it in a text editor to correct the comma to be every 4 numbers so the end result would be `"2742,2734"`
I've tried a few examples I found on SO but none are helping me with this scenario like
```
"[^"]+"
'\d+'
```
while the above do find matches, I don't know how to deal with the commas and how what to replace that with.
Thanks for any help!<issue_comment>username_1: **Repositories and transaction**
To me, a Repository shouldn't know about the ambient transaction - there should be a Unit of Work-like container that keeps track of updated entities and commits the transaction when you declare the Unit of Work Complete.
**Repositories with alternative sources**
It shouldn't be a problem to mix data coming from repositories with different origins in the same unit of work. *Ideally*, the UoW would know which persistence mechanism goes with which type of entity and sort it all out in the end.
For practical reasons though, you might want to limit your UoW to a single persistent store (usually a database via an ORM) and add to repositories that have different, transaction-illiterate data sources methods like `Update(entity)` that save directly to the source when called.
Upvotes: 1 <issue_comment>username_2: >
> Repositories don't know about the fact that they are running under some transaction, or should they?
>
>
>
Here's what Evan's wrote, in the [Blue Book](http://a.co/jknnUpq)
>
> The REPOSITORY concept is adaptable to many situations. The possibilities of implementation are so diverse that I can only list some concerns to keep in mind....
> *Leave transaction control to the client*. Although the REPOSITORY will insert and delete from the database, it will ordinarily not commit anything.... Transaction management will be simpler if the REPOSITORY keeps its hands off.
>
>
>
To be absolutely honest, I find this notion difficult to reconcile with other writings from the same chapter.
>
> For each type of object that needs global access, create ( a REPOSITORY ) that can provide the illusion of an in-memory collection of all objects of that set.
>
>
>
In the languages that I normally use, in-memory collections typically manage their own state. Doesn't that imply that transaction control should be behind the collection interface, rather than left to the client?
An additional point is that our persistence solutions have gotten a lot more complex; for Evans, the domain model was only managing writes to a single database, which supported transactions that could span multiple aggregates (ie, an RDBMS). But if you change that assumption, then a lot of things start to become more complicated.
[cqrs](/questions/tagged/cqrs "show questions tagged 'cqrs'") offers some hints, here. *Reading* from repositories is beautiful; you take all of the complexity of the implementation and hide it behind some persistence agnostic facade. Writing can be trickier -- if your domain model needs support for saving multiple aggregates together (same transaction), then your "repository" interface should make that explicit.
These days, you are likely to see more support for the idea that modifications of aggregates should always happen in separate transactions. That takes some of the pressure off of repository coordination.
Upvotes: 3 [selected_answer]<issue_comment>username_3: The repository has no knowledge of the context in which it is used. As such, the repository should not be responsible for starting, committing or rollbacking a transaction.
Therefore, I always pass a UnitOfWork / DbSession / whatever to my repository. The repository uses that UnitOfWork, and the transaction is committed outside the repository.
In pseudo code, this looks like this:
```
var uow = DatabaseContext.CreateUnitOfWork();
uow.StartTransaction();
var productRepository = new ProductRepository(uow);
var customerRepository = new CustomerRepository(uow);
// ... do some operations on the repositories.
uow.Commit();
```
Upvotes: 2
|
2018/03/14
| 437 | 1,590 |
<issue_start>username_0: I am trying to fetch equal number of records from 4 different clients from the same table in db2 database. I need to ensure that each sql fetches distinct set of rows with equal volume. the table has a 18 digit number as a primary key generated randomly. how do I ensure that the record getting select in first sql is not present in any of the other sqls.<issue_comment>username_1: Db2 Federation could be the answer to your question. This would allow a single SQL statement running against four source databases which have been defined in one database. A UNION wold ensure the deduplication of data.
Details can be found [here](https://www.ibm.com/support/knowledgecenter/SSEPGG_11.1.0/FedServer_product_landing.html)
Upvotes: -1 <issue_comment>username_2: This will affect performance but you can use modulus:
```
SELECT ...
FROM table
WHERE MOD(pkey, 4) = 1 --or 2, 3, 0
```
You also said something about having equal result set sizes, you can use `FETCH FIRST x ROWS ONLY` to limit to the same size.
There may be other options depending on the "why" of the question - OLAP functions, hidden columns, functional indexes, views, and other tools could possibly be better answers. MOD is a simple one though.
Upvotes: 2 <issue_comment>username_3: May be you can do it in only query like this:
```
select * from (
select f1.*, rownumber() over(partition by clientid order by f1.pkey, f1.clientid) rang
from yourtable f1
where f1.clientid in (4, 8, 9, 5) --> put your client id here
) f2
where f2.rang<5 --> 5 if you want only 5 rows by client
```
Upvotes: 0
|
2018/03/14
| 413 | 1,300 |
<issue_start>username_0: Using jquery can click based on class and id attributes but can click be invoked based on ref attribute ?
I've based below code on `ref="btFirst"`, but unsure how to access `ref`.
[JSFiddle](http://jsfiddle.net/5DfUy/297/) src:
```
First
$( ".btFirst" ).click(function() {
alert( "Handler for .click() called." );
});
```<issue_comment>username_1: Use CSS attribute selector (nice and thorough CSS Tricks [reference](https://css-tricks.com/almanac/selectors/a/attribute/)):
```js
$('[ref="btFirst"]').on("click", function(e) {
alert( "Handler for .click() called." );
});
```
```html
Click me
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: You can use
```
$('button[ref="btFirst"]').on('click', function(e){
alert('ref button clicked');
});
```
```js
$('button[ref="btFirst"]').on('click', function(e){
alert('ref button clicked');
});
```
```html
First
```
Upvotes: 1 <issue_comment>username_3: If you want to be more specific:
**Html**:
```
First
```
**jQuery**:
```
$(document).ready(function(){
$( "button.ag-paging-button[ref='btFirst']" ).on('click', function() {
alert( "Handler for .click() called." );
});
});
```
You dont need to add `onclick="alert('Hello world!')"` in button tag
Hope this may help you.
Upvotes: 1
|
2018/03/14
| 625 | 2,226 |
<issue_start>username_0: I'm writing a Software that has the following flow:
```
Promise.resolve(updateMongoStatus)
.then(unzipFilesFromS3)
.then(phase4) //example
.then(phase5) //example
.then(processSomething)
.catch(saveErrorToMongo)
```
And I would like to know if it's ok to pass data around from the first function, to the last one, for example:
```
function updateMongoStatus() {
// do something here that updates Mongo and get status of some document
return { status }
}
function unzipFilesFromS3({ status }) {
// do something here to unzip files from s3
return { status, files }
}
function phase4({ status, files }) {
// etc
}
```
Until the `processSomething` finally gets called:
```
function processSomething({ parameterFromOutputOfUpdateMongoStatus, parameterFromPhase4, parameterFromPhase5 }) {
// Do something here
}
```
Is this ok? To pass data around like that?
Thank you.<issue_comment>username_1: No, you will need to pass a promise object from a thenable to the next thenable. If you simply pass a value, it will return the value.
>
> When a value is simply returned from within a then handler, it will effectively return Promise.resolve().
>
>
>
[Promise.prototype.then()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then)
Update as of 14/03/2018: This answer is not correct. Please refer to comment from @Bergi
Upvotes: -1 <issue_comment>username_2: Yes! This is totally ok, and for some people, this is the preferred way to pass data through a Promise chain (because it does not involve any globals / variables outside the scope of the Promise blocks).
In your case, since you want phase4, phase5, and mongo status in your last promise, you could do this:
```
Promise
.resolve(mongoStatus)
.then((mongoResult) => {
return unzipFilesFromS3().then(s3Result => {
return [s3Result, mongoResult];
});
})
.then(([ s3Result, mongoResult ]) => {
return Promise.all([
mongoResult,
s3Result,
phase4(mongoResult, s3Result)
]);
})
// repeat with phase5
.then(([ mongoResult, s3Result, phase4Result /* phase5, etc */ ]) => {
// etc
})
.catch(err => {});
```
Upvotes: 3 [selected_answer]
|
2018/03/14
| 656 | 1,803 |
<issue_start>username_0: i made a program to calculate multiples of 5 between two numbers, when ask for de second numbers the program didn't work normally.
```
#include
int main()
{
int A, B, cont;
printf("\n");
printf("Indique el dominio de los numeros en los que desa saber cuales son multiplos de 5\n");
printf("Primer numero: \n");
scanf("%i",&A);
printf("Segundo numero: \n");
scanf("%i",&B);
if (A < B){
A = B;
//B = A;
}
system("cls");
printf("\n");
printf("Los multiplos de 5 comprendidos entre %i y %i son; \n",A,B);
cont = 0;
while(A < B){
if (A % 5 == 0)
cont++;
A++;
}
if (cont > 0)
printf("Entre los numeros %i y %i hay un total de %i multiplos de 5.\n",A,B,cont);
else
printf("El intervalo no se encuentran multiplos de 5.\n");
getchar();
return 0;
}
```<issue_comment>username_1: Your swapping logic is wrong. Use another variable to do it correctly.
```
int t = A;
A = B;
B = t;
```
Also you would want to swap when `A` is greater than `B`.
```
if( A > B ){
/* swap*/
}
```
Upvotes: 2 <issue_comment>username_2: You have the format backwards
```
scanf("i%",&A);
```
should be
```
scanf("%i",&A);
```
Upvotes: 3 <issue_comment>username_3: ```
#include
int main()
{
int A, B, cont=0;
printf("Program to find the Multiples of 5\n");
printf("First Number \n");
scanf("%d",&A);
printf("Second Number \n");
scanf("%d",&B);
system("cls");
printf("The Multiples of 5 between %d and %d \n", A,B);
if(A=B){
if (A % 5 == 0)
{
cont++;
}
A--;
}
}
if (cont > 0)
printf("The total Multiples of 5 between %d and %d are %d\n",A,B,cont);
else
printf("No Multiple of 5 exists between %d and %d\n",A,B);
getchar();
return 0;
}
```
I try to solve each case. If user enter A>B then your code fails but it works
Upvotes: 0
|
2018/03/14
| 1,304 | 3,784 |
<issue_start>username_0: I have a *Objects of an array of objects* as given below. I am trying to filter out each object within the array where is **quantity is greater than 0** and drop it in a new variable. So via `lodash` I tried to use `_.filter` within `_.(myArr).forEach`. But this always returns an empty array. The console.log within `_.filter` shows `quantity` as it is but it doesn't return any value based on the condition. Am I using it in a proper way here or is there any other way I can use this to filter out?
```js
var data = [
[{
"aid": "1",
"desc": "Desc 1",
"name": "Name 1",
"quantity": 1
}, {
"aid": "2",
"desc": "Desc 2",
"name": "Name 2",
"quantity": 1
}, {
"aid": "3",
"desc": "Desc 3",
"name": "<NAME>",
"quantity": 0
}],
[{
"aid": "4",
"desc": "Desc 4",
"name": "<NAME>",
"quantity": 0
}, {
"aid": "5",
"desc": "Desc 5",
"name": "<NAME>",
"quantity": 1
}],
[{
"aid": "6",
"desc": "Desc 6",
"name": "Name 6",
"quantity": 0
}, {
"aid": "7",
"desc": "Desc 7",
"name": "Name 7",
"quantity": 0
}]
];
var filtered;
_(data).forEach((d) => {
filtered = _.filter(d, (o) => {
return o.quantity > 0;
});
});
console.log(filtered);
```<issue_comment>username_1: You are overwriting `filtered` in each iteration, so its value will represent only what happened in the last iteration of the `forEach` loop.
You should instead accumulate the individual results into an array, for instance with `push` and the spread syntax:
```
var filtered = [];
```
... and in the loop:
```
filtered.push(..._.filter(d, (o) => o.quantity > 0);
```
Note that you can do this in vanilla JavaScript, using array methods like `reduce` and `filter`:
```js
var data = [ [{ "aid": "1", "desc": "Desc 1", "name": "Name 1", "quantity": 1 }, { "aid": "2", "desc": "Desc 2", "name": "Name 2", "quantity": 1 }, { "aid": "3", "desc": "Desc 3", "name": "Name 3", "quantity": 0 }], [{ "aid": "4", "desc": "Desc 4", "name": "Name 4", "quantity": 0 }, { "aid": "5", "desc": "Desc 5", "name": "Name 5", "quantity": 1 }], [{ "aid": "6", "desc": "Desc 6", "name": "Name 6", "quantity": 0 }, { "aid": "7", "desc": "Desc 7", "name": "Name 7", "quantity": 0}]];
var filtered = data.reduce(
(filtered, d) => filtered.concat(d.filter( o => o.quantity > 0 )),
[]
);
console.log(filtered);
```
```css
.as-console-wrapper { max-height: 100% !important; top: 0; }
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: using native js:
```
let filtered = data.reduce((a, e) => a.concat(e)).filter(x => x.quantity > 0);
```
Upvotes: 2 <issue_comment>username_3: Or alternatively you can use `reduce`
```
var output = data.reduce(
( acc, c ) => acc.concat( c.filter(
s => s.quantity > 0 ) ) //filter out quantities > 0
,[]); //initialize accumulator to []
```
**Demo**
```js
var data = [
[{
"aid": "1",
"desc": "Desc 1",
"name": "<NAME>",
"quantity": 1
}, {
"aid": "2",
"desc": "Desc 2",
"name": "<NAME>",
"quantity": 1
}, {
"aid": "3",
"desc": "Desc 3",
"name": "<NAME>",
"quantity": 0
}],
[{
"aid": "4",
"desc": "Desc 4",
"name": "<NAME>",
"quantity": 0
}, {
"aid": "5",
"desc": "Desc 5",
"name": "<NAME>",
"quantity": 1
}],
[{
"aid": "6",
"desc": "Desc 6",
"name": "<NAME>",
"quantity": 0
}, {
"aid": "7",
"desc": "Desc 7",
"name": "<NAME>",
"quantity": 0
}]
];
var output = data.reduce( ( acc, c ) => acc.concat( c.filter( s => s.quantity > 0 ) ) ,[]);
console.log(output);
```
Upvotes: 1
|
2018/03/14
| 183 | 522 |
<issue_start>username_0: How to reverse an `integer array` in swift
eg: `var ab = [1,2,3,4]`
I want to store the array in reverse format.
The result should be
```
ab = [4,3,2,1]
```<issue_comment>username_1: use ab.reversed() function which returns a reversed array.
Upvotes: 4 [selected_answer]<issue_comment>username_2: ```
var ab = [1, 2, 3, 4]
func reverse(_ arr: [Int]) -> [Int] {
return arr.reversed() // we return here
}
print(reverse(ab)) // The answer print as you need! [4, 3, 2, 1]
```
Upvotes: 2
|
2018/03/14
| 498 | 1,453 |
<issue_start>username_0: I wnat to test a field with multiple values against single value, my SQL is like .
```html
WHERE id (1);
```
Database values are like
```html
id
---
1,2
2,3
1,3,4
```
codeigniter
```html
$this->db->select('*');
$this->db->from('content');
$this->db->where('name', $name);
$this->db->where('id', $id);
```
I tried
```html
$this->db->where_in('id', explode(',', $id));
```
but its not working.Please help me to solve this.<issue_comment>username_1: What if you use [**`like()`**](https://www.codeigniter.com/userguide3/database/query_builder.html#looking-for-similar-data) instead of `where()`
```
$this->db->like('id', $id);
// Produces: WHERE `id` LIKE '%2%' ESCAPE '!'
```
>
> **Note:** If 2 is the value `2`,`22`,`222` will pass through this
>
>
>
Upvotes: 3 [selected_answer]<issue_comment>username_2: To find the values from a given set you can use [`FIND_IN_SET`](https://dev.mysql.com/doc/refman/5.7/en/string-functions.html#function_find-in-set)
```
$this->db->where("FIND_IN_SET(".$id.",id) >", 0);
```
Note: This type of design is considered as a bad design and you should normalize your structure, I suggest you to have a look at [Database Normalization](https://en.wikipedia.org/wiki/Database_normalization)
Upvotes: 3 <issue_comment>username_3: Please try this one:
```
$this->db->select('*')->from('table_name')
->where("column_name LIKE '%$key_values%'")->get();
```
Upvotes: 0
|
2018/03/14
| 686 | 2,097 |
<issue_start>username_0: I was just testing my code in play ground(xcode-8.2), using swift tutorial. I came across following sample code:
[One-Sided Ranges](https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/BasicOperators.html#//apple_ref/doc/uid/TP40014097-CH6-ID60)
```
for name in names[2...] {
print(name)
}
```
now my play ground showing an error:

now I feel that my swift version may not be supporting this code!
I looked around this answer but it provide solution for Xcode Project only.
* [How do I see which version of Swift I'm using?](https://stackoverflow.com/questions/30790188/how-do-i-see-which-version-of-swift-im-using)
How can I see swift version of play ground?<issue_comment>username_1: In the terminal run
```
swift -version
```
in all probability playgrounds will be using that version
Upvotes: 0 <issue_comment>username_2: By default Playground use the Swift version based on your Xcode version
You can check the Swift version by Xcode release here
<https://swift.org/download/#releases>
Upvotes: 2 <issue_comment>username_3: Try to find out swift version using following code. (Here I tried this code with Playground of [Xcode 9.3 - beta 4](https://stackoverflow.com/questions/44390162/download-install-xcode-9-1-9-2-9-3-beta-or-xcode-9-version-without-premium-d/44390183#44390183)) and it's providing me correct answer.
```
#if swift(>=5.2)
print("Hello, Swift 5.2")
#elseif swift(>=5.1)
print("Hello, Swift 5.1")
#elseif swift(>=5.0)
print("Hello, Swift 5.0")
#elseif swift(>=4.1)
print("Hello, Swift 4.1")
#elseif swift(>=4.0)
print("Hello, Swift 4.0")
#elseif swift(>=3.0)
print("Hello, Swift 3.x")
#else
print("Hello, Swift 2.2")
#endif
```

>
> **Answer to your question:** I'm not sure but according to result of above code, I can say, Latest Swift version supported by your Xcode tool becomes a version of Playground's Swift Language.
>
>
>
Upvotes: 4
|
2018/03/14
| 702 | 2,016 |
<issue_start>username_0: My code is as shown below:
xyz.html
```
```
xyz.css
```
.home-container {
width: 100vw;
height: 100vh;
overflow-y: scroll;
background: #fcfcfc;
}
.home-container .menu-main {
width: 43%;
height:3000px;
position: absolute;
background-color: red;
left: 300px;
}
```
But somehow, as soon as I insert `position:absolute` in `menu-main`, it looses its scrolling capabilities. So how can I acheive both scrolling and position absolute at the same time?<issue_comment>username_1: try this add a position:relative; for the parent div.
```css
.home-container {
width: 100vw;
height: 100vh;
overflow-y: scroll;
background: #fcfcfc;
}
.home-container .menu-main {
width: 43%;
height:3000px;
position: absolute;
background-color: red;
left: 300px;
}
```
```html
```
Upvotes: 1 <issue_comment>username_2: ```css
body { margin: 0px; }
.home-container {
height: 100vh;
background: #fcfcfc;
margin: 0px auto;
}
.home-container .menu-main {
width: 53%;
height: 100vh;
position: relative;
background-color: red;
margin: 0px auto;
}
```
```html
```
```
body { margin: 0px; }
.home-container {
height: 100vh;
background: #fcfcfc;
margin: 0px auto;
}
.home-container .menu-main {
width: 53%;
height: 100vh;
position: relative;
background-color: red;
margin: 0px auto;
}
`enter code here`
```
Upvotes: 1 <issue_comment>username_3: Add the style property `position:relative;`in your Parent Div(not in container) like below.
```
```
and also if you want horizontal scrolling also add `overflow-x: scroll;` in your CSS. Like below...
```css
.home-container {
width: 100vw;
height: 100vh;
overflow-y: scroll;
overflow-x: scroll;
background: #fcfcfc;
}
.home-container .menu-main {
width: 43%;
height:3000px;
position: absolute;
background-color: red;
left: 300px;
}
```
```html
```
Upvotes: 3 [selected_answer]
|
2018/03/14
| 949 | 3,293 |
<issue_start>username_0: I want to send following data to server. It contains JsonArray of JsonObjects as shown below.
```
{
"users":[
{"user-1":{
"Name":"Amit",
"Age":"32",
"Gender":"male",
"Hobby":"Cricket"
}
"user-2":{
"Name":"Subodh",
"Age":"30",
"Gender":"male",
"Hobby":"Chess"
}
"user-3":{
"Name":"Mala",
"Age":"27",
"Gender":"female",
"Hobby":"Singing"
}
}
]
}
```
This is how I wrote json code for the same.
```
JSONObject userObject = new JSONObject();
JSONArray userArray = new JSONArray();
JSONObject user1 = new JSONObject();
try {
user1.put("Name", "Amit");
user1.put("Age", "32");
user1.put("Gender", "Male");
user1.put("Hobby", "Cricket");
} catch (JSONException e) {
e.printStackTrace();
}
JSONObject user2 = new JSONObject();
try {
user2.put("Name", "Subodh");
user2.put("Age", "30");
user2.put("Gender", "Male");
user2.put("Hobby", "Chess");
} catch (JSONException e) {
e.printStackTrace();
}
JSONObject user3 = new JSONObject();
try {
user3.put("Name", "Mala");
user3.put("Age", "27");
user3.put("Gender", "Female");
user3.put("Hobby", "Singing");
} catch (JSONException e) {
e.printStackTrace();
}
userArray.put(user1);
userArray.put(user2);
userArray.put(user3);
try {
userObject.put("user", userArray);
} catch (JSONException e) {
e.printStackTrace();
}
```
However I am not able to figure out how to give name to Objects (user-1, user-2 etc.) in the JsonArray. Can someone help to do that. I want to give Heading to each JsonObject in the JsonArray.<issue_comment>username_1: Write the JSON object name like below code in every JSONObject creation :-
```
JSONObject jsonobj = new JSONObject("user1 ");
try {
jsonobj.put("Name", "Amit");
jsonobj.put("Age", "32");
jsonobj.put("Gender", "Male");
jsonobj.put("Hobby", "Cricket");
} catch (JSONException e) {
e.printStackTrace();
}
```
Upvotes: -1 <issue_comment>username_2: Your JSON is invalid.
Elements in *JSON arrays* don't have keys ("headings", as you call them). Only values in *JSON objects* have keys.
So, this is wrong:
```
{
"users": [
"user-1": {
"Name": "Amit",
"Age": "32",
"Gender": "male",
"Hobby": "Cricket"
}
]
}
```
While this is correct:
```
{
"users": {
"user-1": {
"Name": "Amit",
"Age": "32",
"Gender": "male",
"Hobby": "Cricket"
}
}
}
```
To get the correct JSON, simply use a `JSONObject` instead of a `JSONArray`:
```
JSONObject resultObject = new JSONObject();
JSONObject usersObject = new JSONObject();
JSONObject user1 = new JSONObject();
user1.put("Name", "Amit");
user1.put("Age", "32");
user1.put("Gender", "Male");
user1.put("Hobby", "Cricket");
usersObject.put("user-1", user1);
// repeat for user 2, 3, 4, ...
resultObject.put("users", usersObject);
```
Upvotes: 2 [selected_answer]
|
2018/03/14
| 649 | 2,262 |
<issue_start>username_0: I'm trying to use getters and setters to adjust data initially set with a class constructor. The getter seems to work:
```
class myClass {
constructor(sth) {
this.data = {
sth,
timestamp: new Date()
}
}
create(createData) {
const newData = Object.assign({}, this.theData, {
/* this getter seems to work ^^^^^^^^^^^^ */
createData
})
console.log(newData) // looks good
// set'ter new data
this.theData(newData)
return this
}
get theData() {
return this.data
}
set theData(newData) {
console.log('setting')
this.data = newData;
}
}
const Instance = new myClass('construct data')
.create({createData: 'some data'})
```
But this gets the error
>
> zakeyumidu.js:27 Uncaught TypeError: this.theData is not a function
>
>
> at myClass.create
>
>
>
creating a non-`setter` method seems to work as I can just do
```
setTheData(newData) {
this.data = newData // yep, that works
}
```
But I get the idea that `getters`/`setters` are preferred.
### Is it okay to set instance data like this within class methods like my example that works? If not, why is my setter not working?<issue_comment>username_1: Instead of `this.theData(newData)` you should write `this.theData = newData`
```js
class myClass {
constructor(sth) {
this.data = {
sth,
timestamp: new Date()
}
}
create(createData) {
const newData = Object.assign({}, this.theData, {
/* this getter seems to work ^^^^^^^^^^^^ */
createData
})
console.log(newData) // looks good
// set'ter new data
this.theData = newData;
return this
}
get theData() {
return this.data
}
set theData(newData) {
console.log('setting')
this.data = newData;
}
}
const Instance = new myClass('construct data')
.create({createData: 'some data'})
```
Upvotes: 2 <issue_comment>username_2: `this.theData(newData)` would be accessing `theData`'s *getter*. Since `.data` is not a function at the time that line executes (or ever), that is why you are getting that error.
To fix the problem, you should actually use the setter:
```
this.theData = newData;
```
Upvotes: 3 [selected_answer]
|
2018/03/14
| 755 | 3,017 |
<issue_start>username_0: I have a C++ project in which comments of source code are in Chinese language, now I want to convert them into English.
I tried to solve using google translator but got an Issue: Whole CPP files or header didn't get converted, also I have found the name of the struct, class etc gets changed. Sometimes code also gets modified.
Note: Each .cpp or .h file is less than 1000 lines of code.But there are multiple C++ projects each having around 10 files. Thus I have around 50 files for which I need to translate Chinese text to English.<issue_comment>username_1: Extracting comments is a [lexical](https://en.wikipedia.org/wiki/Lexing) issue, and mostly a quite simple one.
In a few hours, you could write (e.g. with [flex](https://github.com/westes/flex)) some simple command line program extracting them. And a good editor (such as [GNU emacs](https://www.gnu.org/software/emacs/)) could even be configured to run that filter on selected code chunks.
(handling a few corner cases, such as [raw string literals](http://en.cppreference.com/w/cpp/language/string_literal), might be slightly more difficult, but these don't happen often and you might handle them manually)
BTW, if you are assigned to work on that code, you'll need to understand it, and that takes much more time than copy&pasting or editing each comments manually.
At last, I am not sure of the quality of automatic translation of code comments. You might be disappointed. Also, the code names (of functions, of classes, of variables, etc...) matter a lot more.
Perhaps *adding* your comments in English could be wiser.
Don't forget to use some version control system. You really need one (e.g. [`git`](http://git-scm.com/))
(I am not convinced that extracting comments for automatic translation would help your work)
Upvotes: 2 <issue_comment>username_2: Well, what did you expect? Google Translate doesn't know what a CPP file is and how to treat it. You'll have to write your own program that extracts comments from them (not that hard), runs just those through Google Translate, and then puts them back in.
Mind you, if there is commented out code, or the comments reference variable names, those will get translated too. Detecting and handling these cases is a lot harder already.
Upvotes: 2 <issue_comment>username_3: First separate both comment and code part in different file using python script as below,
```
import sys
file=sys.argv[1]
f=open(file,"r")
lines=f.readlines()
f.close()
comment=open("comment.txt","w+")
code=open("code.txt","w+")
for l in lines:
if "//" in l:
comment.write(l)
code.write("\n")
else:
code.write(l)
comment.write("\n")
comment.close()
code.close()
```
Now translate comment.txt with google translator and then use
```
paste code.txt comment_en > source
```
where comment\_en is translated comment in english.
Upvotes: 2
|
2018/03/14
| 906 | 3,233 |
<issue_start>username_0: I am not able to use localhost with xamarin.android application.
I have executed Web project & Service project(not mobile app) on Chrome Browser.
[](https://i.stack.imgur.com/6CLaz.png)
The displayed port number I tried browsing in Android Studio emulators & Genymotion emulators by appending 10.0.2.2: & 10.0.3.2: respectively, I got result *Bad Request-Invalid Hostname*. Even I have tried **Service project port number**, both not working.
Web Project: ASP.NET project using Visual Studio 2017 & Having service project in the same solution.<issue_comment>username_1: Open your solution folder. You might have several projects inside 1 folder, you don't need project's folder but the root one. Inside you'd have `.vs/config/applicationhost.config` file, open it.
find inside you'll have sites that you are running, might have several, if you switch startup projects in one solution. The name will be corresponding to one displayed by IIS in taskbar when you right-click it's icon. The tag could be, for example, .
Now you need to add a line to bind external connections to your machine ip, for example
```
...
...
```
Set appropriate port number and protocol, what matters here is just map them to `127.0.0.1`, not "localhost" then they will be available for android emulator via `10.0.2.2:60424` (the port number 60424 is just from the example above, use yours)
Upvotes: 6 <issue_comment>username_2: I have answered this on another stackoverflow question, using third party software **`ngrock`**
Check this [Android emulator not connecting to localhost api](https://stackoverflow.com/questions/52618330/android-emulator-not-connecting-to-localhost-api/52626534#52626534)
Upvotes: 1 [selected_answer]<issue_comment>username_3: You can use our free extension Conveyor <https://marketplace.visualstudio.com/items?itemName=vs-publisher-1448185.ConveyorbyKeyoti>
If the IP that Conveyor gives you doesn't work, just substitute it with 10.0.2.2. Using Conveyor solves the problem of needing to make IIS Express bind to other hostnames. It also has some other features too.
Upvotes: 2 <issue_comment>username_4: A shoutout to the [Top answer](https://stackoverflow.com/a/50991257/1298503) for putting me on the right track. In my configuration I certainly needed to change the binding to `127.0.0.1` instead of `localhost` in the solution config file.
Since I'm using Rider, the config file was in a different location. Check it out:
[](https://i.stack.imgur.com/ey8kF.png)
Under run/debug configurations, click the link `open in editor` next to (a checked by default) `Generate applicationhost.config`. This opens up the config file for editing.
*In addition to the above*, I also had to update the `applicationUrl` property in that same project's `launchsettings.json` file to use the loopback IP instead of `localhost`:
[](https://i.stack.imgur.com/xQXbN.png)
Restarting the service (and afterward the client) should go without saying, but one can never be too careful.
Upvotes: 1
|
2018/03/14
| 777 | 2,822 |
<issue_start>username_0: there are different conditions for same design file. i can't use if-else in same class file to differentiate them. because manage all conditions are difficult. is there any way to change class at dynamic time.<issue_comment>username_1: Open your solution folder. You might have several projects inside 1 folder, you don't need project's folder but the root one. Inside you'd have `.vs/config/applicationhost.config` file, open it.
find inside you'll have sites that you are running, might have several, if you switch startup projects in one solution. The name will be corresponding to one displayed by IIS in taskbar when you right-click it's icon. The tag could be, for example, .
Now you need to add a line to bind external connections to your machine ip, for example
```
...
...
```
Set appropriate port number and protocol, what matters here is just map them to `127.0.0.1`, not "localhost" then they will be available for android emulator via `10.0.2.2:60424` (the port number 60424 is just from the example above, use yours)
Upvotes: 6 <issue_comment>username_2: I have answered this on another stackoverflow question, using third party software **`ngrock`**
Check this [Android emulator not connecting to localhost api](https://stackoverflow.com/questions/52618330/android-emulator-not-connecting-to-localhost-api/52626534#52626534)
Upvotes: 1 [selected_answer]<issue_comment>username_3: You can use our free extension Conveyor <https://marketplace.visualstudio.com/items?itemName=vs-publisher-1448185.ConveyorbyKeyoti>
If the IP that Conveyor gives you doesn't work, just substitute it with 10.0.2.2. Using Conveyor solves the problem of needing to make IIS Express bind to other hostnames. It also has some other features too.
Upvotes: 2 <issue_comment>username_4: A shoutout to the [Top answer](https://stackoverflow.com/a/50991257/1298503) for putting me on the right track. In my configuration I certainly needed to change the binding to `127.0.0.1` instead of `localhost` in the solution config file.
Since I'm using Rider, the config file was in a different location. Check it out:
[](https://i.stack.imgur.com/ey8kF.png)
Under run/debug configurations, click the link `open in editor` next to (a checked by default) `Generate applicationhost.config`. This opens up the config file for editing.
*In addition to the above*, I also had to update the `applicationUrl` property in that same project's `launchsettings.json` file to use the loopback IP instead of `localhost`:
[](https://i.stack.imgur.com/xQXbN.png)
Restarting the service (and afterward the client) should go without saying, but one can never be too careful.
Upvotes: 1
|
2018/03/14
| 208 | 891 |
<issue_start>username_0: I have a network application which uses Vxworks TCP stack. Here if we have network loop in network.
I am aware of network loop causes broad cast storm. How do I detect this programmatically?
Thanks for the help<issue_comment>username_1: You can't (really). Your application using TCP is above layer 4.
A bridge loop is a layer 2 configuration issue and needs to be dealt with on the layer 2 level i.e. on the involved switches. The most common method is to implement the rapid spanning tree protocol (RSTP).
(You can check the system counters for broadcasts and examine the frequency, everything above a certain frequency can be considered broadcast storm.)
Upvotes: 1 <issue_comment>username_2: HP Switches Detect Network Loops automatically. Once it's found a loop it blocks it for ten minutes and then unblocks it. It does this until it is resolved
Upvotes: 0
|
2018/03/14
| 461 | 1,471 |
<issue_start>username_0: I have this code but it displays first 3 letters of month in english. How can I change it to spanish?
```
if (secondsPast > 86400) {
var date = new Date(timestamp);
var currentDate = new Date(now);
var day = date.getDate();
var month = date.toDateString().match(/ [a-zA-Z]*/)[0].replace(' ', '');
var year = date.getFullYear() == currentDate.getFullYear() ? '' : ', ' + date.getFullYear();
return month + ' ' + day + ' ' + year;
}
```<issue_comment>username_1: **In PHP:**
From the DateTime format page:
>
> This method does not use locales. All output is in English.
>
>
>
If you need locales look into [strftime](http://us2.php.net/manual/en/function.strftime.php) Example:
```
setlocale(LC_ALL,"es_ES");
$string = "24/11/2014";
$date = DateTime::createFromFormat("d/m/Y", $string);
echo strftime("%A",$date->getTimestamp());
```
Upvotes: -1 <issue_comment>username_2: You can use `toLocaleDateString()`.
The toLocaleDateString() method returns a string with a language sensitive representation of the date portion of this date.
Please read more about it at [moz wiki](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString)
Example:
```js
var event = new Date(Date.UTC(2012, 11, 20, 3, 0, 0));
var options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
console.log(event.toLocaleDateString('es-ES', options));
```
Upvotes: 5
|
2018/03/14
| 346 | 1,137 |
<issue_start>username_0: [](https://i.stack.imgur.com/Fl9fF.png)
How do I format this in a HTML page? What is the tag for it? I don’t know how to get this 1 written above the text.<issue_comment>username_1: Probably the element for *superscript* text.
Likethis.
```
Likethis
```
There's also for subscript text:
Likethis.
```
Likethis
```
Note that these elements are meant for actual textual superscript and subscript text. Remember that HTML is semantic: it describes what the content is, not what the content looks like (that's what CSS is for).
In CSS you can do this the simple way by setting `vertical-align: super` with `font-size: 80%` on an *inline-element* (like but not , a *block-element*).
Another approach is to do it manually with creative use of `margin` or `position: relative` - in which case it depends on your application.
Upvotes: 3 [selected_answer]<issue_comment>username_2: Using the [SuperScript tag](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/sup)
```
Kasparov1
```
Kasparov1
Upvotes: 1
|
2018/03/14
| 571 | 1,797 |
<issue_start>username_0: I want to understand how arithmetic operation happen on different data type,
```
#include
#include
#include
using namespace std;
void newprintf(int, int, long, char \*);
int main()
{
int i = 22;
newprintf(14, 30, (long) i, "9,999");
getch();
return 0;
}
void newprintf(int r, int c, long val, char \*format)
{
char \*p, str[20];
int len, i, j, lstr;
len = strlen(format);
\_itoa(val, str, 10);
lstr = strlen(str);
p = str;
c += len;
p = str + lstr -1;
format = format + len - 1;
cout << "The value in p : " << p << endl;
cout << "The format is : " << format << endl;
}
```
Basically this program doesn't have a specific functionality, i just wanted to understand how the value of 'p' and 'format' are calculated, This program is compiled on Visual Studio.
Can anyone explain me how the value are calculated in **detail** ?
On running i get,
p = 2 and format = 9
**Thanks in advance**<issue_comment>username_1: Probably the element for *superscript* text.
Likethis.
```
Likethis
```
There's also for subscript text:
Likethis.
```
Likethis
```
Note that these elements are meant for actual textual superscript and subscript text. Remember that HTML is semantic: it describes what the content is, not what the content looks like (that's what CSS is for).
In CSS you can do this the simple way by setting `vertical-align: super` with `font-size: 80%` on an *inline-element* (like but not , a *block-element*).
Another approach is to do it manually with creative use of `margin` or `position: relative` - in which case it depends on your application.
Upvotes: 3 [selected_answer]<issue_comment>username_2: Using the [SuperScript tag](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/sup)
```
Kasparov1
```
Kasparov1
Upvotes: 1
|
2018/03/14
| 448 | 1,464 |
<issue_start>username_0: I am familiar with the usual mod result but not for negative numbers. What is the logic?<issue_comment>username_1: Taken from <https://docs.python.org/3/reference/expressions.html>
>
> The % (modulo) operator yields the remainder from the division of the first argument by the second. The numeric arguments are first converted to a common type. A zero right argument raises the ZeroDivisionError exception. The arguments may be floating point numbers, e.g., 3.14%0.7 equals 0.34 (since 3.14 equals 4\*0.7 + 0.34.) The modulo operator always yields a result with the same sign as its second operand (or zero); the absolute value of the result is strictly smaller than the absolute value of the second operand [1].
>
>
>
Looks like modulus operator always yields results with same sign as second operator.
Hence for -11 mod 5 will yield positive (4) result.
```
>>> -11 % 5
4
```
While 11 mod -5 will yield negative (-4) result.
```
>>> 11 % -5
-4
```
Upvotes: 2 <issue_comment>username_2: To find `−b mod N`, just keep adding `N` to `−b` until the number is between `0` and `N`
In your case, `N = 5, b = −11`. Add `5` to `-11`, you get `-6`, again you get `-1`, and again you get `4`.
So, `−11 mod 5 = 4`.
Upvotes: 1 <issue_comment>username_3: Python's modulo operator (%) always return a number having the same sign as the denominator (divisor)
In `-11%5` as 5 is a positive number, the output you got is positive
Upvotes: 0
|
2018/03/14
| 792 | 2,818 |
<issue_start>username_0: In .Net Core, you can PInvoke with [DllImport],
But if you want to dynamically load and map native api calls, DllImport doesn't solve the problem.
On windows we handled this with a DllImport to LoadModule. Then you could use GetProcAddress to map an address to a delegate which you could then call, effectively dynamically loading api calls.
Is there any way to do this in .Net Core out of the box so that your logic doing the loading works cross platform on Linux, Mac OSX, and Windows?
This can be built, but I'm trying to see if there's a way to do this before I chase that rabbit.<issue_comment>username_1: After opening an issue on the .NetCore Repo, I was informed this is slated to be added to .Net Core, but won't be in 2.1.
Currently there is a Prototype Implementation created by a user on github located here:
<https://github.com/mellinoe/nativelibraryloader>
Upvotes: 2 <issue_comment>username_2: One potential solution is related to [my answer](https://stackoverflow.com/a/52286329/10176713) to the SO question [Load unmanaged static dll in load context](https://stackoverflow.com/questions/43049370/load-unmanaged-static-dll-in-load-context):
You can use [AssemblyLoadContext](https://learn.microsoft.com/en-us/dotnet/api/system.runtime.loader.assemblyloadcontext?view=netcore-2.1) in [System.Runtime.Loader](https://www.nuget.org/packages/System.Runtime.Loader/) package.
Your implementation for `LoadUnmanagedDll()` contains the logic to load platform dependent native libraries:
```
string arch = Environment.Is64BitProcess ? "-x64" : "-x86";
if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
var fullPath = Path.Combine(assemblyPath, "runtimes", "osx" + arch, "native", "libnng.dylib");
return LoadUnmanagedDllFromPath(fullPath);
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
{
var fullPath = Path.Combine(assemblyPath, "runtimes", "linux" + arch, "native", "libnng.so");
return LoadUnmanagedDllFromPath(fullPath);
}
else // RuntimeInformation.IsOSPlatform(OSPlatform.Windows)
{
var fullPath = Path.Combine(assemblyPath, "runtimes", "win" + arch, "native", "nng.dll");
return LoadUnmanagedDllFromPath(fullPath);
}
```
The `runtimes/platform/native/` is the [nupkg convention](https://learn.microsoft.com/en-us/nuget/create-packages/creating-a-package#from-a-convention-based-working-directory) but you can use any path you like.
Your pinvoke methods will be similar to:
```
[DllImport("nng", CallingConvention = CallingConvention.Cdecl)]
public static extern int nng_aio_alloc(out nng_aio aio, AioCallback callback, IntPtr arg);
```
Calling a native method like `nng_aio_alloc` through the shared interface will trigger then load of `nng` library and your `LoadUnmanagedDll()` function will get called.
Upvotes: 3
|
2018/03/14
| 549 | 1,725 |
<issue_start>username_0: I have an Object containing multiple arrays like this
```
someObj = {
array1:['a', 'b'],
array2:['a', 'b', 'c'],
array3:['a', 'b', 'c', 'd']
}
```
Is there any built-in method or property in JS/ES6 which returns the largest array or length of the largest array? Please suggest<issue_comment>username_1: You can use `Object.values` to get all of the values for any object. Here's a neat oneshot which will return the longest list in combination with `reduce`:
```
const longestList = Object.values(someObj)
.reduce((longest, list) => list.length > longest.length ? list : longest)
```
* Object.values: <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/values>
* reduce: <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce>
Upvotes: 1 <issue_comment>username_2: You can use `Array.prototype.reduce` and check the value of accumulator with the array length.
Use `Object.values()` to get all the values of the array.
```js
var someObj = {
array1:['a', 'b'],
array2:['a', 'b', 'c'],
array3:['a', 'b', 'c', 'd'],
array4:['a', 'b', 'c']
}
var maxLength = Object.values(someObj).reduce((a,e) => { return a > e.length ? a:e.length}, 0);
console.log(maxLength);
```
Upvotes: 2 <issue_comment>username_3: You can simply use a for loop and iterate through it comparing the length of the arrays.
```js
var someObj = {
array1:['a', 'b'],
array2:['a', 'b', 'c'],
array3:['a', 'b', 'c', 'd']
}
var max=0;
for(x in someObj){
someObj[x].length > max ? max=someObj[x].length : max;
}
console.log(max);
```
Upvotes: 1 [selected_answer]
|
2018/03/14
| 1,879 | 4,612 |
<issue_start>username_0: The data I want to insert into the database likes this:
```
datalist =[['2012', '1', '3', '1', '832.0', '261.0', '100.00'],
['2012', '1', '5', '1', '507.0', '193.0', '92.50'],
['2012', '2', '3', '1', '412.0', '200.0', '95.00'],
['2012', '2', '5', '1', '560.0', '335.0', '90.00'],
['2012', '3', '3', '1', '584.0', '205.0', '100.00'],
['2012', '3', '5', '1', '595.0', '162.0', '92.50'],
['2012', '4', '3', '1', '504.0', '227.0', '100.00'],
['2012', '4', '5', '1', '591.0', '264.0', '92.50']]
```
But in fact, there are 500,000 rows in datalist. So I just listed a part of it.
The code I insert into the database likes this:
```
import pymssql
server = '127.0.0.1'
user = "test"
password = "<PASSWORD>"
database='SQLTest'
datalist = [['2012', '1', '3', '1', '832.0', '261.0', '100.00'],
['2012', '1', '5', '1', '507.0', '193.0', '92.50'],
['2012', '2', '3', '1', '412.0', '200.0', '95.00'],
['2012', '2', '5', '1', '560.0', '335.0', '90.00'],
['2012', '3', '3', '1', '584.0', '205.0', '100.00'],
['2012', '3', '5', '1', '595.0', '162.0', '92.50'],
['2012', '4', '3', '1', '504.0', '227.0', '100.00'],
['2012', '4', '5', '1', '591.0', '264.0', '92.50']]
#But in fact, there are 500,000 rows in datalist
try:
conn = pymssql.connect(server, user, password, database)
cursor = conn.cursor()
for one_row in datalist:
val1 = one_row[4]
val2 = one_row[5]
val3 = one_row[6]
sql = "insert into table_for_test values(col1, col2, col3)" % (val1, val2,val3)
cursor.execute(sql)
conn.commit()
except Exception as ex:
conn.rollback()
raise ex
finally:
conn.close()
```
**Because of the amount of data is too large,So I want to insert data in batchs,how to modify the code?**<issue_comment>username_1: One way to do this is to use the BULK INSERT statement.
<https://learn.microsoft.com/en-us/sql/t-sql/statements/bulk-insert-transact-sql>
The input should be from a file (e.g CSV).
So for example if the data is in CSV file
```
BULK INSERT table_for_test
FROM C:\user\admin\downloads\mycsv.csv
WITH (
FIRSTROW=1
, FIELDTERMINATOR=','
, ROWTERMINATOR='\n'
)
```
Upvotes: 0 <issue_comment>username_2: Now I know how to do it.
Use `executeMany`.The element must be tuple in the list.
```
import pymssql
server = '127.0.0.1'
user = "test"
password = "<PASSWORD>"
database='SQLTest'
datalist = [('2012', '1', '3', '1', '832.0', '261.0', '100.00'),
('2012', '1', '5', '1', '507.0', '193.0', '92.50'),
('2012', '2', '3', '1', '412.0', '200.0', '95.00'),
('2012', '2', '5', '1', '560.0', '335.0', '90.00'),
('2012', '3', '3', '1', '584.0', '205.0', '100.00'),
('2012', '3', '5', '1', '595.0', '162.0', '92.50'),
('2012', '4', '3', '1', '504.0', '227.0', '100.00'),
('2012', '4', '5', '1', '591.0', '264.0', '92.50')]
try:
conn = pymssql.connect(server, user, password, database)
cursor = conn.cursor()
sql = "insert into table_for_test values(col1, col2, col3, col4, col5, col6, col7) values(%s, %s, %s, %s, %s, %s, %s)"
cursor.executemany(sql, datalist)
conn.commit()
except Exception as ex:
conn.rollback()
raise ex
finally:
conn.close()
```
Upvotes: 3 [selected_answer]<issue_comment>username_3: Executemany() is slow because it's using the for loop and in that it's using the execute() function itself.
the easiest way which i found it is to use the execute() command itself in range of 1000.
for e.g i have data like this => data = [(1,"test1","123"),(2,"test2","543"),(3,"test3","876"),(4,"test4","098")]
so you can insert in this way
```
def bulk_batch_insertion(self,data,tablename):
print("Data==============>",len(data))
start = 0
end = 1000
while data[start:end]:
print("start ",start,'end ',end)
new_data = ','.join(data[start:end])
print("length of new data =========>",len(data[start:end]))
query = f"INSERT INTO {tablename} VALUES {new_data}"
print("Insert QUERY ====> ",query)
self.cursor.execute(query)
self.conn.commit()
print("Successfully Inserted the data ")
start = end
end = start + 1000
print("Execution successfulll=======endss=====>>")
```
Note : I'm not using BULK insert because I have some encoding and some manipulations to be done before passing it into the database.
Upvotes: 0
|
2018/03/14
| 1,064 | 2,981 |
<issue_start>username_0: ```
execute 'install_insatller' do
cwd "abc"
command reg_cmd
ignore_failure true
log 'STDERROR'
only_if { ::File.exist?('abc') }
end
```
this is just an expample code
I want to print the log message only if the failure occurs else continue the installation.<issue_comment>username_1: One way to do this is to use the BULK INSERT statement.
<https://learn.microsoft.com/en-us/sql/t-sql/statements/bulk-insert-transact-sql>
The input should be from a file (e.g CSV).
So for example if the data is in CSV file
```
BULK INSERT table_for_test
FROM C:\user\admin\downloads\mycsv.csv
WITH (
FIRSTROW=1
, FIELDTERMINATOR=','
, ROWTERMINATOR='\n'
)
```
Upvotes: 0 <issue_comment>username_2: Now I know how to do it.
Use `executeMany`.The element must be tuple in the list.
```
import pymssql
server = '127.0.0.1'
user = "test"
password = "<PASSWORD>"
database='SQLTest'
datalist = [('2012', '1', '3', '1', '832.0', '261.0', '100.00'),
('2012', '1', '5', '1', '507.0', '193.0', '92.50'),
('2012', '2', '3', '1', '412.0', '200.0', '95.00'),
('2012', '2', '5', '1', '560.0', '335.0', '90.00'),
('2012', '3', '3', '1', '584.0', '205.0', '100.00'),
('2012', '3', '5', '1', '595.0', '162.0', '92.50'),
('2012', '4', '3', '1', '504.0', '227.0', '100.00'),
('2012', '4', '5', '1', '591.0', '264.0', '92.50')]
try:
conn = pymssql.connect(server, user, password, database)
cursor = conn.cursor()
sql = "insert into table_for_test values(col1, col2, col3, col4, col5, col6, col7) values(%s, %s, %s, %s, %s, %s, %s)"
cursor.executemany(sql, datalist)
conn.commit()
except Exception as ex:
conn.rollback()
raise ex
finally:
conn.close()
```
Upvotes: 3 [selected_answer]<issue_comment>username_3: Executemany() is slow because it's using the for loop and in that it's using the execute() function itself.
the easiest way which i found it is to use the execute() command itself in range of 1000.
for e.g i have data like this => data = [(1,"test1","123"),(2,"test2","543"),(3,"test3","876"),(4,"test4","098")]
so you can insert in this way
```
def bulk_batch_insertion(self,data,tablename):
print("Data==============>",len(data))
start = 0
end = 1000
while data[start:end]:
print("start ",start,'end ',end)
new_data = ','.join(data[start:end])
print("length of new data =========>",len(data[start:end]))
query = f"INSERT INTO {tablename} VALUES {new_data}"
print("Insert QUERY ====> ",query)
self.cursor.execute(query)
self.conn.commit()
print("Successfully Inserted the data ")
start = end
end = start + 1000
print("Execution successfulll=======endss=====>>")
```
Note : I'm not using BULK insert because I have some encoding and some manipulations to be done before passing it into the database.
Upvotes: 0
|
2018/03/14
| 256 | 995 |
<issue_start>username_0: For some reason, the following form will not make a post request when it gets submitted:
```
Hospital Patient Scenario
```
This form; however, is in the same project, and it works:
```
Username:
Password:
```
Why is the first form not making a post request on submit?
To provide more detail, the routes /login and /join are defined in two separate routes documents that are both required by the server. I tried moving the /join route to the routes document with the /login route and it still didn't work.<issue_comment>username_1: Try this
```
Hospital Patient
Scenario
```
Upvotes: -1 <issue_comment>username_2: It seems as though another form or perhaps another script I was using was interfering with the form's post request. I have removed that code, and I'll be debugging by trying to see which part of my other code interferes.
Thank you.
Upvotes: 0 <issue_comment>username_3: you should replace:
```
```
by:
```
Submit
```
Upvotes: -1
|
2018/03/14
| 1,293 | 2,227 |
<issue_start>username_0: I have written a for loop to display names in python idle as shown below.
```
1.SRA-D12-TY2-2017WW22.4.129
2.SRA-D12-TY2-2017WW27.5.168
3.SRA-D12-TY2-2017WW16.5.92
4.SRA-D12-TY2-2017WW20.2.115
5.SRA-D12-TY2-2017WW25.2.149
6.SRA-D12-TY2-2017WW29.5.188
7.SRA-D12-TY2-2017WW36.1.234
8.SRA-D12-TY2-2017WW31.3.201
```
The code I have written to display the above items is
```
for i in data.get('files'):
new_data = i.get('uri').strip('/')
platform_display = "{}.{}".format(count,new_data)
platform_dict[count] = new_data
count += 1
print platform_display
```
I want it to be displayed as
```
1.SRA-D12-TY2-2017WW36.1.234
2.SRA-D12-TY2-2017WW31.3.201
3.SRA-D12-TY2-2017WW29.5.188
```
etc in descending order
Please let me know how can I sort the names<issue_comment>username_1: Just use `reversed sort`.
Lets say all your item in the list called `l`,
```
l=['SRA-D12-TY2-2017WW22.4.129',
'SRA-D12-TY2-2017WW27.5.168',
'SRA-D12-TY2-2017WW16.5.92',
'SRA-D12-TY2-2017WW20.2.115',
'SRA-D12-TY2-2017WW25.2.149',
'SRA-D12-TY2-2017WW29.5.188',
'SRA-D12-TY2-2017WW36.1.234',
'SRA-D12-TY2-2017WW31.3.201']
sorted(l, reverse=True)
```
Upvotes: 0 <issue_comment>username_2: ```
l1=[
'SRA-D12-TY2-2017WW22.4.129',
'SRA-D12-TY2-2017WW27.5.168',
'SRA-D12-TY2-2017WW16.5.92',
'SRA-D12-TY2-2017WW20.2.115',
'SRA-D12-TY2-2017WW25.2.149',
'SRA-D12-TY2-2017WW29.5.188',
'SRA-D12-TY2-2017WW36.1.234',
'SRA-D12-TY2-2017WW31.3.201'
]
l1=sorted(l1, key=lambda x: x.split("WW")[-1],reverse=True)
for i in l1:
print(i)
```
Output:
```
SRA-D12-TY2-2017WW36.1.234
SRA-D12-TY2-2017WW31.3.201
SRA-D12-TY2-2017WW29.5.188
SRA-D12-TY2-2017WW27.5.168
SRA-D12-TY2-2017WW25.2.149
SRA-D12-TY2-2017WW22.4.129
SRA-D12-TY2-2017WW20.2.115
SRA-D12-TY2-2017WW16.5.92
```
Upvotes: 3 [selected_answer]<issue_comment>username_3: Try this:
```
from operator import itemgetter
platform_list = []
for i in data.get('files'):
new_data = i.get('uri').strip('/')
platform_list.append([new_data.split("WW")[-1],new_data])
first_item = itemgetter(0)
new_list = sorted(platform_list, key = first_item)
counter = 0
for i in new_list:
counter += 1
print "%d.%s" %(counter,i[1])
```
Upvotes: 0
|
2018/03/14
| 1,048 | 3,756 |
<issue_start>username_0: Consider a scenario, I have a function "REFRESH TOKEN", this function is called by different methods simultaneously, let's say the methods are "A", "B", "C".
If method "A" calls "REFRESH TOKEN" firstly then methods "B" and "C" should wait until it finishes.
Does anybody have a sample swift code?
How can I attain this scenario? Appreciate your help!
```
let serialQueue = DispatchQueue(label: "serialQueue")
var myFlag = false
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.refresh(param: 1)
self.refresh(param: 2)
self.refresh(param: 3)
}
func refresh(param: NSInteger) -> Void {
let absolutePath = "MY SAMPLE API"
var headers: [String: String] = Dictionary();
headers["Content-Type"] = "application/json"
serialQueue.sync {
print("\nEntered ", param)
Alamofire.request(absolutePath, method: .get, parameters: nil, encoding: JSONEncoding.default, headers: headers).responseString {
response in
switch response.result {
case .success:
print("SUCCESS")
break
case .failure(let error):
print(error)
}
}
```
}}
Output:
```
Entered 1
Entered 2
Entered 3
SUCCESS
SUCCESS
SUCCESS
```
I need an output like this:
```
Entered 1
SUCCESS
Entered 2
SUCCESS
Entered 3
SUCCESS
```<issue_comment>username_1: Request chaining is one way. If you find that you have to do this a lot then maybe look into futures and promises. Another way is to use Dispatch Group.
Request Chain example
```
Alamofire.request(.GET, "http://httpbin.org/get", parameters: ["foo": "bar"]).response { (_, _, data, error) in
if error == nil {
Alamofire.request(.GET, "http://httpbin.org/get2\(data.something)", parameters: ["foo": "bar"]).response { (_, _, something, error) in
fulfill(something)
}
} else {
reject(error)
}
}
```
Dispatch Group Example:
```
DispatchQueue.global(qos: .userInitiated).async {
var storedError: NSError?
let downloadGroup = DispatchGroup()
downloadGroup.enter()
Alamofire.request(.GET, "http://httpbin.org/get", parameters: ["foo":
"bar"]).response { (_, _, data, error) in
downloadGroup.leave()
}
downloadGroup.wait()
downloadGroup.enter()
Alamofire.request(.GET, "http://httpbin.org/get", parameters: ["foo":
"bar"]).response { (_, _, data, error) in
downloadGroup.leave()
}
downloadGroup.wait()
downloadGroup.notify(queue: DispatchQueue.main) {
completion?(storedError)
}
}
```
If you want to look into Futures and Promises Alamofire made a lib
<https://github.com/PromiseKit/Alamofire->
Upvotes: 0 <issue_comment>username_2: * You can make use of DispatchGroup.
```
let dispatchGroup = DispatchGroup()
dispatchGroup.enter()
Method A {
//Refresh Token code here
dispatchGroup.leave()
}
dispatchGroup.wait()
dispatchGroup.enter()
Method B {
//Refresh Token code here
dispatchGroup.leave()
}
dispatchGroup.wait()
dispatchGroup.notify(queue: .main) {
print("Both functions are invoked one after other")
}
```
Upvotes: 2 <issue_comment>username_3: The easy and nasty way is to set a flag and check the flag on calling the function and changing flag on returning.
A better way, as far as I found out, is using [operation queue](https://developer.apple.com/documentation/foundation/operationqueue "Operation queue").
Upvotes: 0 <issue_comment>username_4: You should create a dispatchQueue(Serial) and put that code in sync of that queue.
```
//Create a dispatch Queue
var dispatchQueue:DispatchQueue
func refreshToken() {
dispatchQueue.sync {
//whatever code is there in refreshToken method
}
}
```
Upvotes: 0
|
2018/03/14
| 2,727 | 10,214 |
<issue_start>username_0: I'm learning web.api from asp.net. The problem is, my delete and put method not working right now. I think there's something wrong with my code :\*
**Here's my controller for delete:**
```
[ResponseType(typeof(Location))]
public IHttpActionResult DeleteLocation(Guid id)
{
Location location = _locationRepository.GetSingle(e => e.Id == id);
if (location == null)
{
return NotFound();
}
_locationRepository.Delete(location);
return Ok(location);
}
```
**and these are my put:**
```
[HttpPost]
[ResponseType(typeof(LocationViewModel))]
public async Task PutLocation(Guid id, LocationViewModel location)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (id != location.Id)
{
return BadRequest();
}
location.Id = id;
try
{
await \_locationRepository.EditAsync(location.ToModel());
}
catch (DbUpdateConcurrencyException)
{
if (!LocationExist(id))
{
return NotFound();
}
else
{
throw;
}
}
return StatusCode(HttpStatusCode.NoContent);
}
```
This confusing me..
My get and post things works perfectly.
I'm using postman to test the method and it said:
[](https://i.stack.imgur.com/3Pe51.png)
405 method not allowed.. and I have no idea. And these are my generic repository. maybe something wrong with this too..
```
public abstract class GenericRepository :IGenericRepository where T : class,ISoftDelete where C : DbContext, new()
//public abstract class GenericRepository : IGenericRepository where T : class, ISoftDelete
{
//protected readonly ShopDiaryProject.EF.ShopDiaryDbContext \_entities;
private C \_entities = new C();
public C Context
{
get { return \_entities; }
set { \_entities = value; }
}
public virtual IQueryable GetAll()
{
IQueryable query = \_entities.Set().Where(i => i.IsDeleted == false);
return query;
}
public virtual IQueryable FindBy(System.Linq.Expressions.Expression> predicate)
{
IQueryable query = \_entities.Set().Where(i => i.IsDeleted == false).Where(predicate);
return query;
}
public virtual T GetSingle(System.Linq.Expressions.Expression> predicate)
{
T data = \_entities.Set().Where(i => i.IsDeleted == false).FirstOrDefault(predicate);
return data;
}
public virtual bool Add(T entity)
{
try
{
\_entities.Set().Add(entity);
this.Save();
return true;
}
catch (System.Data.Entity.Validation.DbEntityValidationException dbEx)
{
foreach (var validationErrors in dbEx.EntityValidationErrors)
{
foreach (var validationError in validationErrors.ValidationErrors)
{
string message = string.Format("{0}:{1}",
validationErrors.Entry.Entity.ToString(),
validationError.ErrorMessage);
}
}
return false;
}
}
public virtual bool AddRange(IEnumerable entity)
{
try
{
\_entities.Set().AddRange(entity);
this.Save();
return true;
}
catch (System.Data.Entity.Validation.DbEntityValidationException dbEx)
{
foreach (var validationErrors in dbEx.EntityValidationErrors)
{
foreach (var validationError in validationErrors.ValidationErrors)
{
string message = string.Format("{0}:{1}",
validationErrors.Entry.Entity.ToString(),
validationError.ErrorMessage);
}
}
return false;
}
}
public virtual bool Delete(T entity)
{
try
{
entity.IsDeleted = true;
entity.DeletedDate = DateTime.Now;
Edit(entity);
this.Save();
return true;
}
catch (System.Data.Entity.Validation.DbEntityValidationException dbEx)
{
foreach (var validationErrors in dbEx.EntityValidationErrors)
{
foreach (var validationError in validationErrors.ValidationErrors)
{
string message = string.Format("{0}:{1}",
validationErrors.Entry.Entity.ToString(),
validationError.ErrorMessage);
}
}
return false;
}
}
public virtual bool Edit(T entity)
{
try
{
entity.ModifiedDate = DateTime.Now;
\_entities.Entry(entity).State = EntityState.Modified;
this.Save();
return true;
}
catch (System.Data.Entity.Validation.DbEntityValidationException dbEx)
{
foreach (var validationErrors in dbEx.EntityValidationErrors)
{
foreach (var validationError in validationErrors.ValidationErrors)
{
string message = string.Format("{0}:{1}",
validationErrors.Entry.Entity.ToString(),
validationError.ErrorMessage);
}
}
return false;
}
}
public virtual bool Save()
{
try
{
\_entities.SaveChanges();
return true;
}
catch (System.Data.Entity.Validation.DbEntityValidationException dbEx)
{
foreach (var validationErrors in dbEx.EntityValidationErrors)
{
foreach (var validationError in validationErrors.ValidationErrors)
{
string message = string.Format("{0}:{1}",
validationErrors.Entry.Entity.ToString(),
validationError.ErrorMessage);
}
}
return false;
}
}
private bool \_disposed = false;
protected virtual void Dispose(bool disposing)
{
if (!\_disposed)
{
if (disposing)
{
\_entities.Dispose();
}
}
\_disposed = true;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
public int Count(Expression> match)
{
return \_entities.Set().Count(match);
}
public async virtual Task AddAsync(T entity)
{
try
{
\_entities.Set().Add(entity);
await this.SaveAsync();
return true;
}
catch (System.Data.Entity.Validation.DbEntityValidationException dbEx)
{
foreach (var validationErrors in dbEx.EntityValidationErrors)
{
foreach (var validationError in validationErrors.ValidationErrors)
{
string message = string.Format("{0}:{1}",
validationErrors.Entry.Entity.ToString(),
validationError.ErrorMessage);
}
}
return false;
}
}
public async virtual Task AddRangeAsync(IEnumerable entity)
{
try
{
\_entities.Set().AddRange(entity);
await this.SaveAsync();
return true;
}
catch (System.Data.Entity.Validation.DbEntityValidationException dbEx)
{
foreach (var validationErrors in dbEx.EntityValidationErrors)
{
foreach (var validationError in validationErrors.ValidationErrors)
{
string message = string.Format("{0}:{1}",
validationErrors.Entry.Entity.ToString(),
validationError.ErrorMessage);
}
}
return false;
}
}
public async virtual Task DeleteAsync(T entity)
{
try
{
entity.IsDeleted = true;
entity.DeletedDate = DateTime.Now;
Edit(entity);
await this.SaveAsync();
return true;
}
catch (System.Data.Entity.Validation.DbEntityValidationException dbEx)
{
foreach (var validationErrors in dbEx.EntityValidationErrors)
{
foreach (var validationError in validationErrors.ValidationErrors)
{
string message = string.Format("{0}:{1}",
validationErrors.Entry.Entity.ToString(),
validationError.ErrorMessage);
}
}
return false;
}
}
public async virtual Task EditAsync(T entity)
{
try
{
entity.ModifiedDate = DateTime.Now;
\_entities.Entry(entity).State = EntityState.Modified;
await this.SaveAsync();
return true;
}
catch (System.Data.Entity.Validation.DbEntityValidationException dbEx)
{
foreach (var validationErrors in dbEx.EntityValidationErrors)
{
foreach (var validationError in validationErrors.ValidationErrors)
{
string message = string.Format("{0}:{1}",
validationErrors.Entry.Entity.ToString(),
validationError.ErrorMessage);
}
}
return false;
}
//catch (Exception e)
//{
// return false;
//}
}
public async virtual Task SaveAsync()
{
try
{
await \_entities.SaveChangesAsync();
return true;
}
catch (System.Data.Entity.Validation.DbEntityValidationException dbEx)
{
foreach (var validationErrors in dbEx.EntityValidationErrors)
{
foreach (var validationError in validationErrors.ValidationErrors)
{
string message = string.Format("{0}:{1}",
validationErrors.Entry.Entity.ToString(),
validationError.ErrorMessage);
}
}
return false;
}
}
```
Maybe someone here can help me :)
Thanks in advance<issue_comment>username_1: Request chaining is one way. If you find that you have to do this a lot then maybe look into futures and promises. Another way is to use Dispatch Group.
Request Chain example
```
Alamofire.request(.GET, "http://httpbin.org/get", parameters: ["foo": "bar"]).response { (_, _, data, error) in
if error == nil {
Alamofire.request(.GET, "http://httpbin.org/get2\(data.something)", parameters: ["foo": "bar"]).response { (_, _, something, error) in
fulfill(something)
}
} else {
reject(error)
}
}
```
Dispatch Group Example:
```
DispatchQueue.global(qos: .userInitiated).async {
var storedError: NSError?
let downloadGroup = DispatchGroup()
downloadGroup.enter()
Alamofire.request(.GET, "http://httpbin.org/get", parameters: ["foo":
"bar"]).response { (_, _, data, error) in
downloadGroup.leave()
}
downloadGroup.wait()
downloadGroup.enter()
Alamofire.request(.GET, "http://httpbin.org/get", parameters: ["foo":
"bar"]).response { (_, _, data, error) in
downloadGroup.leave()
}
downloadGroup.wait()
downloadGroup.notify(queue: DispatchQueue.main) {
completion?(storedError)
}
}
```
If you want to look into Futures and Promises Alamofire made a lib
<https://github.com/PromiseKit/Alamofire->
Upvotes: 0 <issue_comment>username_2: * You can make use of DispatchGroup.
```
let dispatchGroup = DispatchGroup()
dispatchGroup.enter()
Method A {
//Refresh Token code here
dispatchGroup.leave()
}
dispatchGroup.wait()
dispatchGroup.enter()
Method B {
//Refresh Token code here
dispatchGroup.leave()
}
dispatchGroup.wait()
dispatchGroup.notify(queue: .main) {
print("Both functions are invoked one after other")
}
```
Upvotes: 2 <issue_comment>username_3: The easy and nasty way is to set a flag and check the flag on calling the function and changing flag on returning.
A better way, as far as I found out, is using [operation queue](https://developer.apple.com/documentation/foundation/operationqueue "Operation queue").
Upvotes: 0 <issue_comment>username_4: You should create a dispatchQueue(Serial) and put that code in sync of that queue.
```
//Create a dispatch Queue
var dispatchQueue:DispatchQueue
func refreshToken() {
dispatchQueue.sync {
//whatever code is there in refreshToken method
}
}
```
Upvotes: 0
|
2018/03/14
| 1,014 | 3,408 |
<issue_start>username_0: We have the following code:
```
public class A
{
protected virtual void Method()
{
Console.Write("A");
}
}
public class B : A
{
protected override void Method()
{
Console.Write("B");
}
}
public class C : B
{
public void Some()
{
//How to call Method() from class A?
}
}
```
How to call `Method()` from class A in `Some()` method from class C?
**We will assume that A and B are classes from the library and we can not change them.**
Solution: <https://stackoverflow.com/a/438952/8081796><issue_comment>username_1: `B` overrides `Method()` and `A` its marked as virtual and protected, the only way to call it (in its current format) is if `B` calls it somehow
```
public class B : A
{
protected override void Method()
{
base.Method();
Console.Write("B");
}
}
```
Or derived from `A` directly
```
public class C : A
{
public void Some()
{
Method();
}
}
```
[virtual (C# Reference) | Microsoft Docs](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/virtual)
>
> The virtual keyword is used to modify a method, property, indexer, or
> event declaration and allow for it to be overridden in a derived
> class. For example, this method can be overridden by any class that
> inherits it:
>
>
>
**Furthermore**
>
> When a virtual method is invoked, the run-time type of the object is
> checked for an overriding member. The overriding member in the most
> derived class is called, which might be the original member, if no
> derived class has overridden the member.
>
>
>
[protected (C# Reference)](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/protected)
>
> A protected member is accessible within its class and by derived class
> instances.
>
>
>
Upvotes: 3 [selected_answer]<issue_comment>username_2: If you `really` want `Method` of `A` to be called here (without changing implementation of `A` or `B`'s `Method`), you have to make below changes.
1. Change access specifier of `Method` of `B` class to `new` from `override`.
>
> `override` will override the base class method. Making it `new` won't do it.
>
>
>
2. Change access specifier of `A` and `B` class `Method`s to `public` instead of `protected`
>
> `protected` members of `A` won't be accessible inside your `C` class.
>
>
>
With this changes, check out below code. You will see that `Method` from class `A` is getting called.
```
static void Main()
{
var c = new C();
c.Some();
Console.ReadKey();
}
public class A
{
public virtual void Method()
{
Console.Write("A");
}
}
public class B : A
{
public new void Method()
{
Console.Write("B");
}
}
public class C : B
{
public void Some()
{
//How to call Method() from class A?
((A)this).Method();
}
}
```
*If you cannot make the changes described as above, then I'm afraid you can't call `A`'s `Method` :O .*
Upvotes: 0 <issue_comment>username_3: This is impossible, because
>
> The implementation of a virtual member can be changed by an overriding
> member in a derived class.
>
>
>
`B` change implementation of `A`, therefore `C` have only `B` implementation as `base` and have not implementation of `A`.
Solution: <https://stackoverflow.com/a/438952/8081796>
Upvotes: 0
|
2018/03/14
| 765 | 2,170 |
<issue_start>username_0: I am wondering what should I use in SQL Server 2016 or 2017 (CTE, LOOP, JOINS, CURSOR, REPLACE, etc) to match (replace) **every value** in **every row** in temp table? What is the best solution from **performance perspective**?
Source Table
------------
```
|id |id2|
| 1 | 2 |
| 2 | 1 |
| 1 | 1 |
| 2 | 2 |
```
Mapping Table
-------------
```
|id |newid|
| 1 | 3 |
| 2 | 4 |
```
Expected result
---------------
```
|id |id2|
| 3 | 4 |
| 4 | 3 |
| 3 | 3 |
| 4 | 4 |
```<issue_comment>username_1: You may join the second table to the first table *twice*:
```
WITH cte AS (
SELECT
t1.id AS id_old,
t1.id2 AS id2_old,
t2a.newid AS id_new,
t2b.newid AS id2_new
FROM table1 t1
LEFT JOIN table2 t2a
ON t1.id = t2a.id
LEFT JOIN table2 t2b
ON t1.id2 = t2b.id
)
UPDATE cte
SET
id_old = id_new,
id2_old = id2_new;
```
[](https://i.stack.imgur.com/SO2aT.png)
[Demo
----](http://rextester.com/QLFK77482)
Not sure if you want just a select here, or maybe an update, or an insert into another table. In any case, the core logic I gave above should work for all these cases.
Upvotes: 2 [selected_answer]<issue_comment>username_2: Do the `self join` only
```
SELECT t1.id2 as id, t2.id2
FROM table1 t
INNER JOIN table2 t1 on t1.id = t.id
INNER JOIN table2 t2 on t2.id = t.id2
```
Upvotes: 0 <issue_comment>username_3: You'd need to apply joins on update query. Something like this:
```
Update tblA set column1 = 'something', column2 = 'something'
from actualName tblA
inner join MappingTable tblB
on tblA.ID = tblB.ID
```
this query will compare eachrow with ids and if matched then it will update/replace the value of the column as you desire. :)
Upvotes: 0 <issue_comment>username_4: This may have best performance from solutions posted here if you have indexes set appropriately:
```
select (select [newid] from MappingTable where id = [ST].[id]) [id],
(select [newid] from MappingTable where id = [ST].[id2]) [id2]
from SourecTable [ST]
```
Upvotes: 0
|
2018/03/14
| 405 | 1,459 |
<issue_start>username_0: It seems there is no difference between intializing a char with 0 and '\0' in generated binary code in C. If so, why do we have '\0' in C and not just 0 for ending string?<issue_comment>username_1: The only thing I can think of is readability, as `'\0'` is a better indication to people who read your code that you want a char here.
Aside from that, I have to admit there's no difference at all. In fact, readability isn't even an issue for experienced C programmers.
Upvotes: 3 <issue_comment>username_2: Yeah, there's no difference in initializing a single character. But the purpose of `\0` is to allow you to embed a null character into a string literal:
```
"foo\0bar"
```
Just like any other escape sequence. The fact it's identical to 0 for a single character is just a happy (designed) coincidence. You are naming an octal value with the escape sequence.
Upvotes: 2 <issue_comment>username_3: You can use a variety of escape sequences in string literals:
```
"\n \t \x0a \123"
// symbolic, hex, octal
```
All of these can also be used in character literals:
```
'\n', '\t', '\x0a', '\123'
```
So why exclude `'\0'` (a particular octal value) specifically? Why wouldn't it be valid in character literals?
---
While there is no semantic difference between `0` and `'\0'`, they can be used to express the programmer's intent: `0` could be any integer zero, but `'\0'` is generally only used for NUL bytes.
Upvotes: 2
|
2018/03/14
| 426 | 1,431 |
<issue_start>username_0: I am using PrimeNG Quill `p-editor` in angular. By default, quill trimmed extra space. How can I preserve the extra space in editor in quill?
E.g. - model binding property - text = " Hi I am Angular"
Output in editor - "Hi I am Angular"
expected in editor - " Hi I am Angular"
---
Example of full text :
```
Data & control
* Comply with Our Code, How do we manage business
* Provide proactive identification and effective management and/or escalation of conduct risk to deliver key customer outcomes
* Own, manage and supervise risks within the business area, ensuring mechanisms are in place to identify
* Ensure risk practices and behaviour are consistent with the target risk culture where work collaboratively with others
```<issue_comment>username_1: There's maybe an option in Quill configuration but if not, you can replace spaces in front of your string model with :
```
this.text = " <NAME>
* value 1
* Value 2
* Value 3
*
";
this.text = this.text.replace(/\s/g, ' ');
```
See [Plunker](https://plnkr.co/edit/rzY3l1P2478dRUzpXJuV?p=preview)
Upvotes: 0 <issue_comment>username_2: You can use quill parameter preserveWhitespace.
set preserveWhitespace to true.
```
```
Upvotes: 2 <issue_comment>username_3: Try this on
```
.ql-editor {
white-space: normal !important;
}
```
copied from <https://github.com/quilljs/quill/issues/1752#issuecomment-428407357>
Upvotes: 0
|
2018/03/14
| 745 | 2,074 |
<issue_start>username_0: I am using this syntax for date format in codeigniter model
```
$this->db->where(DATE_FORMAT(`RD`.`CREATED_TS =`,'%Y-%m-%d'), $from);
$this->db->where(DATE_FORMAT(`RD`.`CREATED_TS =`,'%Y-%m-%d'), $to);
```
but it returns this error
```
Message: date_format() expects parameter 1 to be DateTimeInterface, string given
```
and when am executing the query the query returns as below the CREATED\_TS is represented by 0 how can i assign the name for CREATED\_TS
```
SELECT `EP`.`EMPLOYEE_ID`, `EP`.`EMPLOYEENAME`, `RD`.`RETAILER_CODE`, `RD`.`RETAILER_NAME`, `RD`.`AREA_NAME`, `RD`.`LOCALITY`, `RD`.`DISTRICT`, `RD`.`STATE`, `RD`.`PINCODE`, `RD`.`MOBILE_NUMBER`, `P`.`PATCH`, `RD`.`CREATED_TS` FROM `PATIENT_PRIMARY` `P` LEFT JOIN `RETAILER_DETAILS` `RD` ON `P`.`PATIENT_CODE` = `RD`.`PATIENT_CODE` LEFT JOIN `HHCL_EMPLOYEEMASTER`.`EMPLOYEE_PRIMARY` `EP` ON `P`.`CREATED_BY` = `EP`.`EMPLOYEE_ID` WHERE `P`.`CREATED_BY` NOT IN(7777) AND `RD`.`MOBILE_NUMBER` NOT IN(8985180306) AND 0 IS NULL AND 0 IS NULL
```<issue_comment>username_1: use [**`DATE_CREATE`**](http://php.net/manual/en/function.date-create.php) to format string date will solve this issue
```
$this->db->where(DATE_FORMAT(DATE_CREATE(`RD`.`CREATED_TS`), 'Y-m-d'), $from);
$this->db->where(DATE_FORMAT(DATE_CREATE(`RD`.`CREATED_TS`), 'Y-m-d'), $to);
```
>
> **Note:** This will produce `=` in where, if you want to use `BETWEEN` then place `>=` and `<=` accordingly
>
>
>
---
**Edit 01**
```
$this->db->where("DATE(RD.CREATED_TS)", DATE_FORMAT(DATE_CREATE($from), 'Y-m-d'));
$this->db->where("DATE(RD.CREATED_TS)", DATE_FORMAT(DATE_CREATE($to), 'Y-m-d'));
```
Upvotes: 2 [selected_answer]<issue_comment>username_2: You should declare **RD.CREATED\_TS** using **as** and use them in DATE\_FORMAT() function.
**You should do like this :**
```
$this->db->select("RD.CREATED_TS as created_ts");
$this->db->where(DATE_FORMAT('created_ts','%Y-%m-%d'), $from);
$this->db->where(DATE_FORMAT('created_ts','%Y-%m-%d'), $to);
```
Comment please if am i wrong.
Upvotes: -1
|
2018/03/14
| 895 | 2,721 |
<issue_start>username_0: Below is my JSON array and I want to find if `contact` array has specific value or not.
```
data = [ { _id: 5a67294923aba20014e2fe5a,
customerLocation: '473 Victoria St, Singapore 198371',
customerName: 'UNIVERSAL',
id: 'UNI3L2',
customerType: 'customer',
contact:
[ '<NAME>',
'<NAME>',
'<NAME>',
'<NAME>',
'<NAME>' ] } ];
```
`JAVASCRIPT`
```
function findContact(data,con){
return data.contact.find(item => {
return item.data.contact == con;
})
}
console.log('Contact Name :', findContact(data,'<NAME>'));
```<issue_comment>username_1: You can use `data.contact` for contact data shown
Upvotes: 0 <issue_comment>username_2: Use `indexOf`.Since it is only one object `data[0]` is used to get the first object, if it is an array of object you can use forEach method
```js
var data = [{
_id: '5a67294923aba20014e2fe5a',
customerLocation: '473 Victoria St, Singapore 198371',
customerName: 'UNIVERSAL',
id: 'UNI3L2',
customerType: 'customer',
contact: ['<NAME>',
'<NAME>',
'<NAME>',
'<NAME>',
'<NAME>'
]
}];
function findContact(data, con) {
if (data[0].contact.indexOf(con) !== -1) {
return 'found';
} else {
return 'not found';
}
}
console.log('Contact Name :', findContact(data, '<NAME>'));
```
Upvotes: -1 [selected_answer]<issue_comment>username_3: You can use `array#find` with `array#includes` to check if a name exists in the `contact` property of the object.
```js
var data = [ { _id: '5a67294923aba20014e2fe5a', customerLocation: '473 Victoria St, Singapore 198371', customerName: 'UNIVERSAL', id: 'UNI3L2', customerType: 'customer', contact: [ '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>'] } ];
var result = data.find(o => o.contact.includes('<NAME>'));
console.log(result);
```
Upvotes: 0 <issue_comment>username_4: `item` doesn't have `data.contact` property and your `data` response it an array, so you have to specify an index do work with:
```
function findContact(data,con){
return data[0].contact.find(item => {
return item == con;
})
}
```
Upvotes: 2 <issue_comment>username_5: This one returns all the objects matching the name criteria in the array.
```
function filterName(data, srchName) {
return data.filter((obj) => {
return obj.contact.indexOf(srchName) !== -1
})
}
console.log(filterName(data, '<NAME>'));
```
Upvotes: 0
|
2018/03/14
| 2,394 | 8,435 |
<issue_start>username_0: I have an Object ArrayList and I need to use the **toString()** method of the *Motor* object, which is a parameter of the *Vehicle* object. My vehicle objects are in an ArrayList which is iterated through with a for-loop (I know a foreach loop would be easier, but this is part of the assignment)
Here is the code for the loop:
```
for (int i = 0; i < VehicleList.size(); i++) {
System.out.println();
String info = VehicleList.get(i).toString();
Motor m = VehicleList.get(i).motor;
String motorInfo = m.toString();
System.out.println(info);
System.out.println(m);
}
```
There is an error that says "***motor cannot be resolved or is not a field***".
All of the classes should allow this to work, unless of course there is a simple mistake I am missing.
Here is the Motor class:
```
public class Motor {
protected String name;
protected int cylinders;
protected int bhp;
protected double displacement;
public Motor(String name, int cylinders, int bhp, double displacement) {
this.name = name;
this.cylinders = cylinders;
this.bhp = bhp;
this.displacement = displacement;
}
public String toString() {
return "Motor name= " + name + ", cylinders= " + cylinders + ", bhp=
" + bhp + ", displacement= " + displacement;
}
}
```
Motors and Vehicles are intitialized here (In the TestVehicle class):
```
//Motors
Motor EcoBoost = new Motor("EcoBoost", 6, 310, 2.3);
Motor Hemi = new Motor("Hemi", 8, 707, 5.7);
Motor P90D = new Motor("P90D", 0, 762, 0.0);
//Vehicles
Vehicle v0 = new PassCar("Ford", "Mustang", 2016, 44500.0, 5, true, EcoBoost);
Vehicle v1 = new PassCar("Tesla", "Model S", 2016, 121000.0, 2, true, P90D);
Vehicle v2= new Truck("Dodge", "Ram", 2016, 46000.0, "pickup", 1500, Hemi);
```
*PassCar* and *Truck* are inherited classes of Vehicle with a few more attributes. I can post the PassCar or Truck class if needed but I do not think that is where the problem is arising from. I believe it is coming from the For-Loop, specifically the line ***Motor m = VehicleList.get(i).motor;*** but I am not sure of how to fix it.
Vehicle Class:
```
public class Vehicle {
protected String make;
protected String model;
protected int year;
protected double price;
public Vehicle(String make, String model, int year, double price) {
this.make = make;
this.model = model;
this.year = year;
this.price = price;
}
public void description() {
System.out.println("Description");
}
public String toString() {
return "make= " + make + ", model= " + model + ", year= " + year +
", price= " + price;
}
}
```
EDIT: There cannot be any Getters or Setters as per the assignment requirements, and it must be an ArrayList, not a regular List. When I switch to I get the error "Type mismatch: cannot convert from ArrayList to ArrayList
Here is an image of the classes:
[](https://i.stack.imgur.com/LjIth.png)<issue_comment>username_1: Create an interface `IMotor` which is used by `Vehicle` class and Implemented in `PassCar` and other implementation of vehicle.
**IMotor.java**
```
public interface IMotor {
public Motor getMotor();
}
```
**Motor.java**
```
public class Motor {
protected String name;
protected int cylinders;
protected int bhp;
protected double displacement;
public Motor(String name, int cylinders, int bhp, double displacement) {
this.name = name;
this.cylinders = cylinders;
this.bhp = bhp;
this.displacement = displacement;
}
public String toString() {
return "Motor name= " + name + ", cylinders= " + cylinders + ", bhp=" + bhp + ", displacement= " + displacement;
}
}
```
**Vehicle.java**
```
public abstract class Vehicle implements IMotor{
protected String make;
protected String model;
protected int year;
protected double price;
public Vehicle(String make, String model, int year, double price) {
this.make = make;
this.model = model;
this.year = year;
this.price = price;
}
public String toString() {
return "make= " + make + ", model= " + model + ", year= " + year +
", price= " + price;
}
}
```
**PassCar**
```
public class PassCar extends Vehicle{
protected Motor motor;
public PassCar(String make, String model, int year, double price, Motor motor) {
super(make, model, year, price);
this.motor = motor;
}
public Motor getMotor() {
return motor;
}
}
```
**Test.java**
```
import java.util.Arrays;
import java.util.List;
public class Test {
public static void main(String[] args) {
Motor EcoBoost = new Motor("EcoBoost", 6, 310, 2.3);
Vehicle v0 = new PassCar("Ford", "Mustang", 2016, 44500.0, EcoBoost);
List vehicles = Arrays.asList(v0);
System.out.println(vehicles.get(0).getMotor());
}
}
```
Upvotes: 0 <issue_comment>username_2: First, mind the naming convention. Variables should be named in `camcelCase` e.g. vehicleList`instead of`VehicleList`
>
> I have an Object ArrayList
>
>
>
I believe you mean declaration of `vehicleList` looks like `ArrayList vehicleList`
Then behavior is expected because compiler only knows that `VehicleList.get(i)` is going to return you an `Object` reference. It can be a `Vehicle`, but it can also be anything else. So it won't allow you to access the `motor` field, as there is simply no such field in `Object`.
Change your declaration to something like `List vehicleList`
---
However, as mentioned in other answer, it is not a good idea to access the field directly because of various reason. A slightly less evil way is to have getter of `motor`. (A better way is to provide meaningful behaviors instead of providing access to internal data)
Upvotes: 0 <issue_comment>username_3: >
>
> ```
> ArrayList VehicleList = new ArrayList<>(Arrays.asList(vehicles));
>
> ```
>
>
`VehicleList` is declared to contain instances of `Object`, so the compiler will only let you access methods and fields it knows exist on all instances of `Object`.
Change it to `ArrayList`.
Upvotes: 1 <issue_comment>username_4: Thanks to the help of all of your comments and my Java textbook, I managed to piece it together. Here is how I got it to work:
```
for (int i = 0; i < vehicleList.size(); i++) {
String motorInfo = "";
String info = "";
System.out.println();
if (vehicleList.get(i) instanceof PassCar) {
info = ((PassCar)vehicleList.get(i)).toString();
**motorInfo = ((PassCar)vehicleList.get(i)).motor.toString();**
}
else if(vehicleList.get(i) instanceof Truck) {
info = ((Truck)vehicleList.get(i)).toString();
**motorInfo = ((Truck)vehicleList.get(i)).motor.toString();**
}
```
Basically I had to use a polymorphic call and check if it was an instance of a PassCar or Truck.
And as for the Array and ArrayList used during the Class, I edited them like this:
```
Vehicle [] vehicles = new Vehicle [3];
vehicles[0] = v0;
vehicles[1] = v1;
vehicles[2] = v2;
showVehicle(vehicles);
ArrayList vehicleList = new ArrayList(Arrays.asList(vehicles));
System.out.println();
System.out.println("Output from ArrayList in main: ");
```
Thank you for the help everyone!
Upvotes: -1 <issue_comment>username_5: Your problem is that `motor` is not a member of the `Vehicle` class, but you are trying to access it through an expression of type `Vehicle` - namely `vehicleList.get(i)`. This is forbidden, because the compiler has no way of knowing that every possible kind of `Vehicle` has a `motor`. After all, what would happen if you added a `Bicycle` class?
To make this work, you should remove `motor` from the `Truck` and `PassCar` classes, and add it to the `Vehicle` class. That way, `vehicleList.get(i).motor` would actually make sense, since the `Vehicle` expression would be guaranteed to refer to a `Vehicle` with a `Motor`.
It would also be recommended to use a getter for the `motor` field - that is, have `motor` as a `private` field of the `Vehicle` class, and write a method `getMotor()` to return it. You could then write `vehicleList.get(i).getMotor()` to get the `Motor` object associated with one `Vehicle` in the list.
Upvotes: 0
|