date
stringlengths 10
10
| nb_tokens
int64 60
629k
| text_size
int64 234
1.02M
| content
stringlengths 234
1.02M
|
---|---|---|---|
2018/03/22 | 1,144 | 4,063 | <issue_start>username_0: I'm using ASM 6.1 in my project to generate Class files dynamically. But I have a problem when assembling a fat jar.
```
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-shade-plugin:2.4.3:shade (default-cli) on project uetlx: Error creating shaded jar: null: IllegalArgumentException -> [Help 1]
org.apache.maven.lifecycle.LifecycleExecutionException: Failed to execute goal org.apache.maven.plugins:maven-shade-plugin:2.4.3:shade (default-cli) on project uetlx: Error creating shaded jar: null
at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:212)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:153)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:145)
at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:116)
at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:80)
at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build(SingleThreadedBuilder.java:51)
at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:128)
at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:307)
at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:193)
at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:106)
at org.apache.maven.cli.MavenCli.execute(MavenCli.java:863)
at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:288)
at org.apache.maven.cli.MavenCli.main(MavenCli.java:199)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:289)
at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:229)
at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:415)
at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:356)
Caused by: org.apache.maven.plugin.MojoExecutionException: Error creating shaded jar: null
at org.apache.maven.plugins.shade.mojo.ShadeMojo.execute(ShadeMojo.java:540)
at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:134)
at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:207)
... 20 more
Caused by: java.lang.IllegalArgumentException
at org.objectweb.asm.ClassReader.(Unknown Source)
at org.objectweb.asm.ClassReader.(Unknown Source)
at org.objectweb.asm.ClassReader.(Unknown Source)
at org.apache.maven.plugins.shade.DefaultShader.addRemappedClass(DefaultShader.java:415)
at org.apache.maven.plugins.shade.DefaultShader.shadeSingleJar(DefaultShader.java:219)
at org.apache.maven.plugins.shade.DefaultShader.shadeJars(DefaultShader.java:179)
at org.apache.maven.plugins.shade.DefaultShader.shade(DefaultShader.java:104)
at org.apache.maven.plugins.shade.mojo.ShadeMojo.execute(ShadeMojo.java:454)
... 22 more
```
What does it mean? Some confliting `objectweb.asm` version? What is the solution?<issue_comment>username_1: I ran into the same issue with version 2.4.3. Upgrading to the latest version of the plugin (currently 3.2.1) took care of it.
Upvotes: 6 [selected_answer]<issue_comment>username_2: Just to sort of pile on, the upgrade to the latest version of the plugin also fixed the issue for me. My problem was that the example I had found used the older version and I wasn't thinking about upgrading it, just getting the configuration to solve my issue. Now I will be more conscientious about finding the latest upgrade plus the new configuration.
Upvotes: 1 |
2018/03/22 | 267 | 1,136 | <issue_start>username_0: I'm new with VueJs.
I have a question about which is the best practice about import components in A Vue Template Project.
I have some components used in some views. Then I dowloaded a admin template, and the samples always import the components in the view. Included Vue declaration. So I think that could be better import as global components. But I don't know if it have advantages or inconveniencies ( about the speed or the weight).
Then my questions is about it. Which is the best practice? To the project works fine.
Thank you<issue_comment>username_1: I ran into the same issue with version 2.4.3. Upgrading to the latest version of the plugin (currently 3.2.1) took care of it.
Upvotes: 6 [selected_answer]<issue_comment>username_2: Just to sort of pile on, the upgrade to the latest version of the plugin also fixed the issue for me. My problem was that the example I had found used the older version and I wasn't thinking about upgrading it, just getting the configuration to solve my issue. Now I will be more conscientious about finding the latest upgrade plus the new configuration.
Upvotes: 1 |
2018/03/22 | 233 | 872 | <issue_start>username_0: Hellow I want to ad eg admin in front of specific name.
```
@echo off
echo Enter ID
set /p input=""
cls
echo Welocme %input%
pause
```
In this script i want to add if i write eg Modman I want to in front of it be admin but if I write eg Bartek it wont be there<issue_comment>username_1: I ran into the same issue with version 2.4.3. Upgrading to the latest version of the plugin (currently 3.2.1) took care of it.
Upvotes: 6 [selected_answer]<issue_comment>username_2: Just to sort of pile on, the upgrade to the latest version of the plugin also fixed the issue for me. My problem was that the example I had found used the older version and I wasn't thinking about upgrading it, just getting the configuration to solve my issue. Now I will be more conscientious about finding the latest upgrade plus the new configuration.
Upvotes: 1 |
2018/03/22 | 224 | 895 | <issue_start>username_0: I am trying to make validates\_length only occur if no pictures are present but have no clue ...
```
class Post < ApplicationRecord
validates_attachment_content_type :pictures, content_type: /\Aimage\/.*\z/
validates_length_of :description, :minimum => 3, :maximum => 200
end
```<issue_comment>username_1: I ran into the same issue with version 2.4.3. Upgrading to the latest version of the plugin (currently 3.2.1) took care of it.
Upvotes: 6 [selected_answer]<issue_comment>username_2: Just to sort of pile on, the upgrade to the latest version of the plugin also fixed the issue for me. My problem was that the example I had found used the older version and I wasn't thinking about upgrading it, just getting the configuration to solve my issue. Now I will be more conscientious about finding the latest upgrade plus the new configuration.
Upvotes: 1 |
2018/03/22 | 1,412 | 5,425 | <issue_start>username_0: I am having issues accessing data from a DAC that has any amount of customization with it. I have a DAC with a few more complicated modifications, so I will start with the simple one. I have modified the **External Reference** field of `SO.SOOrder`. This is the only change to the DAC.
**Originial Attributes**
```
[PXDBString(40, IsUnicode = true)]
[PXUIField(DisplayName = "External Reference")]
```
**Customize Attributes (Replace Original)**
```
[PXDBString(40, IsUnicode = true)]
[PXUIField(DisplayName = "Some Text Here")]
```
Now, when I attempt to access any `SalesOrder` via the REST API:
```
GET https://site.acumatica.com/entity/Default/17.200.001/SalesOrder/SO000123
```
The following error is returned:
```json
{
"message": "An error has occurred.",
"exceptionMessage": "Operation is not valid due to the current state of the object.",
"exceptionType": "System.InvalidOperationException",
"stackTrace": " at PX.Api.ContractBased.EntityService.FillEntityImplWithKeys(String version, String name, EntityImpl entity, String[] keys)
at PX.Api.ContractBased.SystemContracts.V2.SoapFacade.PX.Api.ContractBased.IRestGate.FillEntityImplWithKeys(EntityImpl entity, String[] keys)
at PX.Api.ContractBased.SystemContracts.V2.RestController.CreateEntityFromKeys(String objectName, String idsString)
at lambda_method(Closure , Object , Object[] )
at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c__DisplayClass10.b\_\_9(Object instance, Object[] methodParameters)
at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ExecuteAsync(HttpControllerContext controllerContext, IDictionary`2 arguments, CancellationToken cancellationToken)
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Web.Http.Controllers.ApiControllerActionInvoker.d\_\_0.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Web.Http.Filters.ActionFilterAttribute.d\_\_5.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Web.Http.Filters.ActionFilterAttribute.d\_\_5.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Web.Http.Filters.ActionFilterAttribute.d\_\_0.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Web.Http.Controllers.ActionFilterResult.d\_\_2.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Web.Http.Filters.AuthorizationFilterAttribute.d\_\_2.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Web.Http.Controllers.ExceptionFilterResult.d\_\_0.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Web.Http.Controllers.ExceptionFilterResult.d\_\_0.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Web.Http.Dispatcher.HttpControllerDispatcher.d\_\_1.MoveNext()"
}
```
Now, I'm not certain if this is occurring because of my DAC modification or not, but I cannot find anything else linking this and my other troubled DAC `CustomerLocation` to the same error message.
Where do I go from here to identify what what the *bad state* is?<issue_comment>username_1: Since this screen contains multiple key fields (Order Type and Order Nbr.), you need to put them all in the URL.
```
GET https://site.acumatica.com/entity/Default/17.200.001/SalesOrder/SO000123
```
gets changed into if this is a type SO Sales Order
```
GET https://site.acumatica.com/entity/Default/17.200.001/SalesOrder/SO/000123
```
SO is order type and 00123 is Order number
Upvotes: 3 [selected_answer]<issue_comment>username_2: This exception message can also result from having a slash character at the end of the Request URL, after the Key field(s)
Exception:
<http://site.acuamtica.com/entity/Default/17.200.001/SalesOrder/SO/SO123456/>
Successful:
<http://site.acuamtica.com/entity/Default/17.200.001/SalesOrder/SO/SO123456>
Upvotes: 1 |
2018/03/22 | 1,085 | 3,502 | <issue_start>username_0: This is actually for the thread on [unknown error: call function result missing 'value' for Selenium Send Keys even after chromedriver upgrade](https://stackoverflow.com/questions/49162667/unknown-error-call-function-result-missing-value-for-selenium-send-keys-even)
but I guess my reputation isn't high enough to participate(lame).
I got the error:
```
WebDriverException: Message: unknown error: call function result missing 'value'
(Session info: chrome=65.0.3325.162)
(Driver info: chromedriver=2.33.506106
platform=Mac OS X 10.13.3 x86_64)
```
when running this line:
```
driver.execute_script('window.scrollTo(0, %s)' % scroll_to)
```
I updated and everything else but that error still popped up, however the code actually executed before raising the error, so simply passing the exception allowed me to accomplish my goal, kinda sloppy so it'd be cool if I could make the error go away for real, but this is working for now:
```
driver.get('https://www.azcentral.com/search/trump/')
page_height = int(driver.get_window_size()['height'])
scroll_to = 0
start_time = time.time()
wait = 90
while True:
scroll_to += page_height
try:
driver.execute_script('window.scrollTo(0, %s)' % scroll_to)
except:
time.sleep(1)
pass
end_time = time.time()
uptime = timedelta(seconds=int(end_time - start_time))
if uptime > timedelta(seconds=wait):
break
```<issue_comment>username_1: I think you can use such code for this:
```
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
```
Hope it helps you!
Upvotes: 2 <issue_comment>username_2: The error says it all :
```
WebDriverException: Message: unknown error: call function result missing 'value'
(Session info: chrome=65.0.3325.162)
(Driver info: chromedriver=2.33.506106
```
Your main issue is the **version compatibility** between the binaries you are using as follows :
* You are using *chromedriver=2.33*
* Release Notes of [*chromedriver=2.33*](https://chromedriver.storage.googleapis.com/2.33/notes.txt) clearly mentions the following :
>
> Supports **Chrome v60-62**
>
>
>
* You are using *chrome=65.0*
* Release Notes of [*ChromeDriver v2.37*](https://chromedriver.storage.googleapis.com/2.37/notes.txt) clearly mentions the following :
>
> Supports **Chrome v64-66**
>
>
>
* Your *Selenium Client* version is unknown to us.
So there is a clear mismatch between the *ChromeDriver* version (*v2.33*) and the *Chrome Browser* version (*v65.0*)
Solution
--------
* Upgrade *Selenium* to current levels [**Version 3.11.0**](https://docs.seleniumhq.org/download/).
* Upgrade *ChromeDriver* to current [**ChromeDriver v2.37**](https://sites.google.com/a/chromium.org/chromedriver/downloads) level.
* Keep *Chrome* version in between ***Chrome v64.x-66.x*** levels. ([as per ChromeDriver v2.37 release notes](https://chromedriver.storage.googleapis.com/2.37/notes.txt))
* *Clean* your *Project Workspace* through your *IDE* and *Rebuild* your project with required dependencies only.
* Use [*CCleaner*](https://www.ccleaner.com/ccleaner) tool to wipe off all the OS chores before and after the execution of your *test Suite*.
* If your base *Web Client* version is too old, then uninstall it through [*Revo Uninstaller*](https://www.revouninstaller.com/revo_uninstaller_free_download.html) and install a recent GA and released version of *Web Client*.
* Execute your `@Test`.
Upvotes: 3 [selected_answer] |
2018/03/22 | 1,249 | 6,253 | <issue_start>username_0: I know there are tons of posts about stack overflow errors and i understand why my specific one is happening, my question is basically how to move away from recursion in this specific case. I have a class which establishes and maintains a client connection (for HL7 messaging specifically but it's essentially a glorified client connection) to another system which hosts corresponding server connections. This class' constructor starts a new thread and runs the following method :
```
@Override
public void connect()
{
try
{
setStatus("Connecting");
connection = context.newClient(intfc.getIp(), port, false);
connected = true;
setStatus("Connected");
logEntryService.logInfo(LogEntry.CONNECTIVITY, "Successfully connected " + connectionType + " client connection to "
+ intfc.getName() + "(" + intfc.getIp() + ") on port " + port);
monitor();
}
catch (HL7Exception ex)
{
connected = false;
setStatus("Disconnected");
try
{
TimeUnit.SECONDS.sleep(connectionRetryIntervalInSeconds);
connect();
}
catch (InterruptedException ex2)
{}
}
}
```
Upon successfully connecting with the server, the monitor method simply checks, in yet another thread, if the connection is still up at a given interval. If it goes down, the monitoring thread is interrupted and the connect() method is called again.
I did not anticipate this at first but you can quickly see why the connect() method is causing stack overflow errors after several days running. I'm struggling to think of a way to get the same functionality to work without the connect method calling itself again every time the connection fails.
Any suggestions would be appreciated.
Thanks!<issue_comment>username_1: When I had to deal with this issue in c# I used a Stack, and added new classes to it, instead of using recursion. Then a second loop would check to see if there were any objects in the stack that needed dealing with. That avoided stack overflow when I would have had huge amounts of recursion otherwise. Is there a similar Stack collection in Java?
Upvotes: 0 <issue_comment>username_2: Typically you'd use a `Stack` object to emulate recursion when required.
However, in your case, why are you using recursion at all? A `while` loop fits the purpose.
```
while(true /**or some relevant condition**/){
try{ //try to connect
....
catch(HL7Exception ex){
//sleep
}
}
```
I'm not sure of the purpose of your application, but there are may be better methods than sleeping. You could use a [ScheduledExecutorService](https://docs.oracle.com/javase/6/docs/api/java/util/concurrent/ScheduledExecutorService.html), but if it's a single threaded program with one purpose it's probably unnecessary.
Upvotes: 2 [selected_answer]<issue_comment>username_3: Why are you calling the `monitor()` method in the first place? You mention that it is launched in a separate thread, then can't you just launch it in a new thread when the application comes up? Then there won't be a recursive call.
Upvotes: 0 <issue_comment>username_4: I changed my code to an iterative approach as suggested, works beautifully!
```
@Override
public void initThread()
{
initConnectionEntity();
mainThread = new Thread()
{
@Override
public void run()
{
while (running)
{
if (!connected)
{
try
{
connect();
}
catch (HL7Exception ex)
{
connected = false;
setStatus("Disconnected");
try
{
TimeUnit.SECONDS.sleep(connectionRetryIntervalInSeconds);
}
catch (InterruptedException ex2)
{}
}
}
try
{
TimeUnit.MILLISECONDS.sleep(500);
}
catch (InterruptedException ex2)
{}
}
}
};
mainThread.setName(intfc.getName() + " " + connectionType + " Main Thread");
mainThread.start();
}
@Override
public void connect() throws HL7Exception
{
setStatus("Connecting");
connection = context.newClient(intfc.getIp(), port, false);
connected = true;
setStatus("Connected");
logEntryService.logInfo(LogEntry.CONNECTIVITY, "Successfully connected " + connectionType + " client connection to "
+ intfc.getName() + "(" + intfc.getIp() + ") on port " + port);
monitor();
}
private void monitor()
{
monitoringThread = new Thread()
{
@Override
public void run()
{
try
{
while (running)
{
if (!connection.isOpen())
{
if (connected == true)
{
logEntryService.logWarning(LogEntry.CONNECTIVITY, "Lost " + connectionType + " connection to "
+ intfc.getName() + "(" + intfc.getIp() + ") on port " + port);
}
connected = false;
setStatus("Disconnected");
monitoringThread.interrupt();
}
else
{
connected = true;
}
TimeUnit.SECONDS.sleep(connectionMonitorIntervalInSeconds);
}
}
catch (InterruptedException ex)
{
logEntryService.logDebug(LogEntry.CONNECTIVITY, "Monitoring thread for " + connectionType
+ " connection to " + intfc.getName() + " interrupted");
}
}
};
monitoringThread.setName(intfc.getName() + " " + connectionType + " Monitoring Thread");
monitoringThread.start();
}
```
Upvotes: 0 |
2018/03/22 | 4,677 | 13,304 | <issue_start>username_0: I am using JavaScript native reduce, however I want to slightly change in the grouping to get my desired result.
I have an array as follows:
```
const people = [
{name: "John", age: 23, city: "Seattle", state: "WA"},
{name: "Mark", age: 25, city: "Houston", state: "TX"},
{name: "Luke", age: 26, city: "Seattle", state: "WA"},
{name: "Paul", age: 28, city: "Portland", state: "OR"},
{name: "Matt", age: 21, city: "Oakland", state: "CA"},
{name: "Sam", age: 24, city: "Oakland", state: "CA"}
]
```
I want to group it and change it to this:
```
const arranged = [
{
city: "Seattle",
state: "WA",
persons: [
{ name: "John", age: 23 },
{name: "Luke", age: 26}
]
},
{
city: "Houston",
state: "TX",
persons: [
{name: "Mark", age: 25}
]
},
{
city: "Portland",
state: "OR",
persons : [
{name: "Paul", age: 28}
]
},
{
city: "Oakland",
state: "CA",
persons: [
{name: "Matt", age: 21},
{name: "Sam", age: 24}
]
}
]
```<issue_comment>username_1: You can use the function `reduce` to group and build the desired output.
```js
const people = [ {name: "John", age: 23, city: "Seattle", state: "WA"}, {name: "Mark", age: 25, city: "Houston", state: "TX"}, {name: "Luke", age: 26, city: "Seattle", state: "WA"}, {name: "Paul", age: 28, city: "Portland", state: "OR"}, {name: "Matt", age: 21, city: "Oakland", state: "CA"}, {name: "Sam", age: 24, city: "Oakland", state: "CA"}]
const result = Object.values(people.reduce((a, {name, age, city, state}) => {
var key = [city, state].join('|');
(a[key] || (a[key] = {city, state, persons: []})).persons.push({name, age});
return a;
}, {}));
console.log(result);
```
```css
.as-console-wrapper { max-height: 100% !important; top: 0; }
```
Upvotes: 1 [selected_answer]<issue_comment>username_2: Try this. I use **[`Array.prototype.forEach`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach)** and **[`Array.prototype.push`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push)**
```js
const people = [
{name: "John", age: 23, city: "Seattle", state: "WA"},
{name: "Mark", age: 25, city: "Houston", state: "TX"},
{name: "Luke", age: 26, city: "Seattle", state: "WA"},
{name: "Paul", age: 28, city: "Portland", state: "OR"},
{name: "Matt", age: 21, city: "Oakland", state: "CA"},
{name: "Sam", age: 24, city: "Oakland", state: "CA"}
];
var arranged=[];
people.forEach(function(e){
var exist=false;
arranged.forEach(function(e1){
if(e1.state===e.state){
exist=true;
e1.persons.push({name:e.name,age:e.age});
}
});
if(!exist){
arranged.push({state:e.state,city:e.city,persons:[{name:e.name,age:e.age}]});
}
});
console.log(arranged);
```
Upvotes: 1 <issue_comment>username_3: You could use a [`Map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) and a stringified object as key for grouping.
Later render the wanted array with objects of the keys and the grouped persons.
```js
var people = [{ name: "John", age: 23, city: "Seattle", state: "WA" }, { name: "Mark", age: 25, city: "Houston", state: "TX" }, { name: "Luke", age: 26, city: "Seattle", state: "WA" }, { name: "Paul", age: 28, city: "Portland", state: "OR" }, { name: "Matt", age: 21, city: "Oakland", state: "CA" }, { name: "Sam", age: 24, city: "Oakland", state: "CA" }],
arranged = Array.from(
people.reduce((m, o) => {
var key = JSON.stringify(Object.assign(...['city', 'state'].map(k => ({ [k]: o[k] }))));
return m.set(key, (m.get(key) || []).concat({ name: o.name, age: o.age }));
}, new Map),
([key, persons]) => Object.assign(JSON.parse(key), { persons })
);
console.log(arranged);
```
```css
.as-console-wrapper { max-height: 100% !important; top: 0; }
```
Upvotes: 2 <issue_comment>username_4: This is not a trivial problem. You first have to define *what* constitutes a grouping, and you also have to define *how* like terms will be combined. You problem is exacerbated by the need to group by a *non-primitive* value: city *and* state. Ie, we can't just group based on `city` alone; [more than half the states in the US](https://en.wikipedia.org/wiki/Oakland_(disambiguation)) have a city named Oakland. Other answers solve this by serializing the city and state in a string, but I will show you a more generic solution that works for compound data of any type.
This is tagged with functional programming, so I'll start with a module for separating our subtasks
```
const DeepMap =
{ has: (map, [ k, ...ks ]) =>
ks.length === 0
? map.has (k)
: map.has (k)
? DeepMap.has (map.get (k), ks)
: false
, set: (map, [ k, ...ks ], value) =>
ks.length === 0
? map.set (k, value)
: map.has (k)
? (DeepMap.set (map.get (k), ks, value), map)
: map.set (k, DeepMap.set (new Map, ks, value))
, get: (map, [ k, ...ks ]) =>
ks.length === 0
? map.get (k)
: map.has (k)
? DeepMap.get (map.get (k), ks)
: undefined
}
```
Now we can define our generic `groupBy` function
```
const identity = x =>
x
const { has, set, get } =
DeepMap
const groupBy = (key = identity, value = identity, xs = []) =>
xs.reduce
((m, x) =>
has (m, key (x))
? set ( m
, key (x)
, [ ...get (m, key (x)), value (x) ]
)
: set ( m
, key (x)
, [ value (x) ]
)
, new Map
)
```
We use `groupBy` by specifying a `key` and `value` functions – The *key* function specifies what an item is grouped by, and the *value* functions specifies the value to be added to the group
```
const people =
[ { name: "John", age: 23, city: "Seattle", state: "WA" }
, { name: "Mark", age: 25, city: "Houston", state: "TX" }
, { name: "Luke", age: 26, city: "Seattle", state: "WA" }
, { name: "Paul", age: 28, city: "Portland", state: "OR" }
, { name: "Matt", age: 21, city: "Oakland", state: "CA" }
, { name: "Sam", age: 24, city: "Oakland", state: "CA" }
]
const res =
groupBy ( k => [ k.state, k.city ]
, v => ({ name: v.name, age: v.age })
, people
)
console.log (res.get ('WA'))
// Map { 'Seattle' => [ { name: 'John', age: 23 }, { name: 'Luke', age: 26 } ] }
console.log (res.get ('WA') .get ('Seattle'))
// [ { name: 'John', age: 23 }, { name: 'Luke', age: 26 } ]
```
We can see how this intermediate result would be useful. It provides incredibly efficient lookup thanks to `Map`. Of course you'll want to iterate thru the deep map in more meaningful ways though. Let's add an `entries` procedure to our module
```
const DeepMap =
{ ...
, entries: function* (map, fields = [])
{
const loop = function* (m, path, [ f, ...fields ])
{
if (fields.length === 0)
for (const [ key, value ] of m)
yield [ { ...path, [ f ]: key }, value ]
else
for (const [ key, value ] of m)
yield* loop (value, { ...path, [ f ]: key }, fields)
}
yield* loop (map, {}, fields)
}
}
for (const [ key, value ] of DeepMap.entries (res, [ 'state', 'city' ]))
console.log (key, value)
// { state: 'WA', city: 'Seattle' } [ { name: 'John', age: 23 }, { name: 'Luke', age: 26 } ]
// { state: 'TX', city: 'Houston' } [ { name: 'Mark', age: 25 } ]
// { state: 'OR', city: 'Portland' } [ { name: 'Paul', age: 28 } ]
// { state: 'CA', city: 'Oakland' } [ { name: 'Matt', age: 21 }, { name: 'Sam', age: 24 } ]
```
Now that our deep map is iterable, we can easily produce your desired output using `Array.from`
```
const arranged =
Array.from ( entries (res, [ 'state', 'city' ])
, ([ key, persons ]) => ({ ...key, persons })
)
console.log (arranged)
// [
// {
// city: "Seattle",
// state: "WA",
// persons: [
// { name: "John", age: 23 },
// { name: "Luke", age: 26 }
// ]
// },
// {
// city: "Houston",
// state: "TX",
// persons: [
// { name: "Mark", age: 25 }
// ]
// },
// {
// city: "Portland",
// state: "OR",
// persons : [
// { name: "Paul", age: 28 }
// ]
// },
// {
// city: "Oakland",
// state: "CA",
// persons: [
// { name: "Matt", age: 21 },
// { name: "Sam", age: 24 }
// ]
// }
// ]
```
Program demonstration
```js
const DeepMap =
{ has: (map, [ k, ...ks ]) =>
ks.length === 0
? map.has (k)
: map.has (k)
? DeepMap.has (map.get (k), ks)
: false
, set: (map, [ k, ...ks ], value) =>
ks.length === 0
? map.set (k, value)
: map.has (k)
? (DeepMap.set (map.get (k), ks, value), map)
: map.set (k, DeepMap.set (new Map, ks, value))
, get: (map, [ k, ...ks ]) =>
ks.length === 0
? map.get (k)
: map.has (k)
? DeepMap.get (map.get (k), ks)
: undefined
, entries: function* (map, fields = [])
{
const loop = function* (m, path, [ f, ...fields ])
{
if (fields.length === 0)
for (const [ key, value ] of m)
yield [ { ...path, [ f ]: key }, value ]
else
for (const [ key, value ] of m)
yield* loop (value, { ...path, [ f ]: key }, fields)
}
yield* loop (map, {}, fields)
}
}
const identity = x =>
x
const { has, set, get, entries } =
DeepMap
const groupBy = (key = identity, value = identity, xs = []) =>
xs.reduce
((m, x) =>
has (m, key (x))
? set ( m
, key (x)
, [ ...get (m, key (x)), value (x) ]
)
: set ( m
, key (x)
, [ value (x) ]
)
, new Map
)
const people =
[ { name: "John", age: 23, city: "Seattle", state: "WA" }
, { name: "Mark", age: 25, city: "Houston", state: "TX" }
, { name: "Luke", age: 26, city: "Seattle", state: "WA" }
, { name: "Paul", age: 28, city: "Portland", state: "OR" }
, { name: "Matt", age: 21, city: "Oakland", state: "CA" }
, { name: "Sam", age: 24, city: "Oakland", state: "CA" }
]
const res =
groupBy ( k => [ k.state, k.city ]
, v => ({ name: v.name, age: v.age })
, people
)
for (const [ key, value ] of entries (res, [ 'state', 'city' ]))
console.log (key, value)
// { state: 'WA', city: 'Seattle' } [ { name: 'John', age: 23 }, { name: 'Luke', age: 26 } ]
// { state: 'TX', city: 'Houston' } [ { name: 'Mark', age: 25 } ]
// { state: 'OR', city: 'Portland' } [ { name: 'Paul', age: 28 } ]
// { state: 'CA', city: 'Oakland' } [ { name: 'Matt', age: 21 }, { name: 'Sam', age: 24 } ]
const arranged =
Array.from ( entries (res, [ 'state', 'city '])
, ([ key, persons ]) => ({ ...key, persons })
)
console.log ('arranged', arranged)
// arranged [
// {
// city: "Seattle",
// state: "WA",
// persons: [
// { name: "John", age: 23 },
// { name: "Luke", age: 26 }
// ]
// },
// {
// city: "Houston",
// state: "TX",
// persons: [
// { name: "Mark", age: 25 }
// ]
// },
// {
// city: "Portland",
// state: "OR",
// persons : [
// { name: "Paul", age: 28 }
// ]
// },
// {
// city: "Oakland",
// state: "CA",
// persons: [
// { name: "Matt", age: 21 },
// { name: "Sam", age: 24 }
// ]
// }
// ]
```
Upvotes: 1 <issue_comment>username_5: I have built a generic group by reducer, you pass it the keys by which you want to group and it gives you a custom reducer function. This reducer gives you an object indexed by a (composed or simple) key containing an array of items that share this key. You can reuse it to have it grouped by the key(s) you want to.
Here are two examples.
```js
const people = Object.freeze([{
name: "John",
age: 23,
city: "Seattle",
state: "WA"
}, {
name: "Mark",
age: 25,
city: "Houston",
state: "TX"
}, {
name: "Luke",
age: 26,
city: "Seattle",
state: "WA"
}, {
name: "Paul",
age: 28,
city: "Portland",
state: "OR"
}, {
name: "Matt",
age: 21,
city: "Oakland",
state: "CA"
}, {
name: "Sam",
age: 24,
city: "Oakland",
state: "CA"
}]);
const groupByReducer = (group) =>
(result, row) => {
const keygroup = group.map((v) => row[v]);
const key = keygroup.join(':');
if (result[key])
result[key].push(row);
else
result[key] = [row];
return result;
};
const byCityState = people.reduce(
groupByReducer(['city', 'state']), {});
const byState = people.reduce(groupByReducer(['state']), {});
console.log(byCityState);
console.log(byState);
```
```css
.as-console-wrapper {
max-height: 100% !important;
top: 0;
}
```
Upvotes: 0 |
2018/03/22 | 569 | 2,174 | <issue_start>username_0: I am struggling to get a simple maven project running on Jenkins, which runs on my new Ubuntu server (16.04.)
I have installed Jenkins onto an Ubuntu, installed Maven and JDK.
I can connect to bitbucket and access my remote repository and get hold of my code. However, when I try to build I get the message
```
cannot run program "mvn" (in directory "/var/snap/jenkins/workspace/project") no such file or directory
```
I have added $JAVA\_HOME and $MAVEN\_HOME to my /etc/environment as variables and also into my path.
I have looked at the Global Tool Configuration, but this seems to be no help.
When I set the Maven installer to point at Maven home I get a message
/usr/share/maven is not a directory on the jenkins master
When I try to get Jenkins to install maven for me I get
```
Failed to install apache-maven-3.5.3.bin.zip to /var/snap/jenkins/6/tools
...
Caused by: java.security.InvalidAlgorithmParameterException: the trustAnchors parameter must not be empty
```
I think I have hit a dead end. What could I be missing, or how can I get past these obstacles ?
Many Thanks<issue_comment>username_1: Go to Manage Jenkins -> Global Tool Configuration. I always elect to have Jenkins install and manage Maven, vs install and bring my own.
[![enter image description here](https://i.stack.imgur.com/xLsZU.png)](https://i.stack.imgur.com/xLsZU.png)
Upvotes: 2 <issue_comment>username_2: It has taken a long time to get to the bottom of this.
By default the
```
sudo apt-get install jenkins
```
seems to install a **Snap** version of Jenkins.
This **snap** version holds data in different locations (which is why I struggled to find the initialAdminpassword
Additionally, the snap setup only has a JRE, which cannot be overridden to a JDK, and therefore does not seem to work properly with Maven.
Eventually, I completely uninstalled Jenkins, and then followed the instructions on the official Jenkins site:
<https://pkg.jenkins.io/debian-stable/>
This overrides the base apt-get packages, and points to the jenkins.io packages.
From here on in, it all behaved as per the documentation.
Upvotes: 2 [selected_answer] |
2018/03/22 | 1,681 | 5,256 | <issue_start>username_0: Evening Internet World,
First post here so be gentle, i've learnt a lot from this site thus far.. and now I seek help..
I've tried a few variations of code like $when & $then, function in function, but I can't get the result I seek, it doesn't combine results. So thought best to ask away here and show my code.. Please help..
**html**
```
#### **Ether contributed**
—
#### **Contributions in USD**
—
#### **Tokens issued**
—
```
**js**
```
var token = '0xa74476443119A942dE498590Fe1f2454d7D4aC0d';
var address = '0xda0aed568d9a2dbdcbafc1576fedc633d28eee9a';
$.get("https://api.tokenbalance.com/token/" + token + "/" + address +'', function(data) {
$("#eth_balance").html(Math.round(data.eth_balance).toFixed(2) + " ETH");
$("#token_amount").html(Math.round(data.balance).toFixed(2) + " " + data.symbol);
});
$.get("https://api.etherscan.io/api?module=stats&action=ethprice", function(data) {
$("#token_usd").html("$ " + Math.round(data.result.ethusd).toFixed(2));
// Ideally I'd like to get [ data.result.ethusd x data.eth_balance ] to replace #token_usd, all wrapped in one function
alert(data.result.ethusd)
});
```
**Or you can play here**
<https://jsfiddle.net/4zwvo90n/8/><issue_comment>username_1: You can move the second ajax call inside the first, and store values from `data` in a variable that will be available to the inner function too.
Like so (second call won't work here or in a fiddle):
```js
var token = '0xa74476443119A942dE498590Fe1f2454d7D4aC0d';
var address = '0xda0aed568d9a2dbdcbafc1576fedc633d28eee9a';
$.get("https://api.tokenbalance.com/token/" + token + "/" + address + '', function (data) {
var eth_balance = data.eth_balance;
$("#eth_balance").html(Math.round(data.eth_balance).toFixed(2) + " ETH");
$("#token_amount").html(Math.round(data.balance).toFixed(2) + " " + data.symbol);
$.get("https://api.etherscan.io/api?module=stats&action=ethprice", function (data) {
$("#token_usd").html("$ " + Math.round(data.result.ethusd * eth_balance).toFixed(2));
// Ideally I'd like to get [ data.result.ethusd x data.eth_balance ] to replace #token_usd, all wrapped in one function
alert(data.result.ethusd)
});
});
```
```html
####
**Ether contributed**
—
####
**Contributions in USD**
—
####
**Tokens issued**
—
```
Upvotes: 1 [selected_answer]<issue_comment>username_2: It sounds like what you're looking for is `Promise.all()` (in vanilla JavaScript) or `$.when()` (in jQuery).
Here's an updated jQuery fiddle: <https://jsfiddle.net/j5L54100/10/>
A working vanilla version: <https://jsfiddle.net/6Lwo7rs4/8/>
In jQuery:
```js
var promise1 = $.get("https://api.tokenbalance.com/token/" + token + "/" + address);
var promise2 = $.get("https://api.etherscan.io/api?module=stats&action=ethprice");
$.when(promise1, promise2).then(function(p1Data, p2Data) {
// do stuff with the data
}).catch(function (error) {
// error handling
});
```
Vanilla JS (note, using JSON like this you'll also need `response.json()`, see the fiddle and <https://developer.mozilla.org/en-US/docs/Web/API/Body/json>):
```js
var promise1 = fetch("https://api.tokenbalance.com/token/" + token + "/" + address);
var promise2 = fetch("https://api.etherscan.io/api?module=stats&action=ethprice");
Promise.all([promise1, promise2]).then(function(combinedData) {
// do stuff with the data
}).catch(function (error) {
// error handling
});
```
Basically what's going on is that `$.get` and `fetch` return promises (an object that represents an asynchronous action's state with callbacks to handle different responses such as `success` or `failure`). `when`/`all` itself is a promise that waits for the fulfillment of all the promises it's given or the first promise failure. If the promises it's given are successful, it calls the `then` function. If one of the promises it's given fail, it calls the `catch` function.
Another option is to chain the requests:
```js
var url1 = "https://api.tokenbalance.com/token/" + token + "/" + address;
var url2 = "https://api.etherscan.io/api?module=stats&action=ethprice";
fetch(url1)
.then(function(data1) {
return fetch(url2);
})
.then(function(data2) {
// do stuff with data1 and data2
})
.catch(function (error) {
// handle errors
});
```
Which looks great in ES6:
```js
const url1 = `https://api.tokenbalance.com/token/${token}/${address}`;
const url2 = 'https://api.etherscan.io/api?module=stats&action=ethprice';
fetch(url1)
.then(data1 => fetch(url2))
.then(data2 => /* do stuff with data1 and data2 */)
.catch(error => /* handle errors */);
```
Promises are super awesome and very confusing. I recommend looking at the resources for fetch to get the general idea before diving further into promises.
Fetch: <https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch>
Promise: <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise>
Promise.all(): <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all>
jQuery.when(): <https://api.jquery.com/jquery.when/>
Upvotes: -1 |
2018/03/22 | 303 | 905 | <issue_start>username_0: I want to be able to pass a comma (`,`) to a `call` statement and use it as a variable, but the below doesn't seem to work:
```
:example
@echo off
call :test ,
echo %output%
pause
:test
set "output=%1"
goto :eof
```<issue_comment>username_1: ```
@echo off
REM Pass the , with Quotes around it.
call :test ","
echo %output%
pause
:test
REM Using ~ to remove the quotes
set "output=%~1"
goto :eof
```
---
**Output**
```
,
Press any key to continue . . .
```
Upvotes: 1 <issue_comment>username_2: ```
@echo off
call :test ","
echo %output%
pause
goto :eof
:test
set "output=%~1"
goto :eof
```
`,` is a separator, so if you want to pass it as a literal, you need to `"enclose it in quotes"`.
To remove enclosing quotes from a parameter, use `~`.
Note the extra `goto :eof`. This skips over the `:test` code once the `pause` is released.
Upvotes: 3 [selected_answer] |
2018/03/22 | 1,331 | 4,918 | <issue_start>username_0: I am new to Django. Would be really helpful if someone can tell the difference between @cached\_property and @lru\_cache decorator in Django.
Also when should I use which decorator in Django. Use cases would be really helpful.
Thanks.<issue_comment>username_1: They serve different purposes.
`lru_cache` saves the least recent uses - you should specify `maxsize` which distinguishes how many computations of your function you can save. Once you surpass this number, the 'oldest' result is discarded and the new one is saved.
`cached_property` just computes the result and saves it. It doesn't take arguments unlike `lru_cache` (you can think of it as a `lru_cache` on an object type with maxsize = 1 with no arguments).
Upvotes: 3 <issue_comment>username_2: First and foremost, `lru_cache` is a decorator provided by the Python language itself as of version 3.4; `cached_property` is a decorator provided by Django for many years, while only being added to the Python language in version 3.8 in October 2019. That being said, they are similar.
`lru_cache` is specifically useful in functional programming. What it does is saves the results of function calls with a certain set of parameters. When a function decorated with `lru_cache` is called multiple times with the same parameters, the decorator will just return a cached result of the function result. This employs a method of programming called [dynamic programming](https://en.wikipedia.org/wiki/Dynamic_programming), and more specifically, [memoization](https://en.wikipedia.org/wiki/Memoization). Using these methods, you can drastically speed up code which repeatedly calls functions that are computationally expensive.
Python also provides another similar decorator called `lfu_cache`. Both of these decorators accomplish memoization, however with different [replacement policies](https://en.wikipedia.org/wiki/Page_replacement_algorithm). `lru_cache` (least recently used) will fill it's cache and have to kick something out during the next decorated function call. This replacement policy dictates that the least recently used entry gets replaced by the new data. `lfu_cache` (least frequently used) dictates that replacements happen based on which entries are used the least.
`cached_property` *is* similar to `lru_cache` in the sense that it caches the result of expensive function calls. The only difference here is that it can only be used on *methods*, meaning the functions belong to an object. Furthermore, they can only be used on methods that have no other parameters aside from `self`. You would specifically want to use this during django development for a method on a class that hits the database. The [Django docs](https://docs.djangoproject.com/en/2.0/ref/utils/#django.utils.functional.cached_property) mention its usage on a model class which has a property method `friends`. This method presumably hits the database to gather a set of people who are friends of that instance of `Person`. Because calls to the database are expensive, we'd want to cache that result for later use.
Upvotes: 5 <issue_comment>username_3: 1. A major difference is that `lru_cache` will keep alive the objects in the cache, which might lead to memory leak, especially if the instance in which the lru\_cache is applied is big (see: <https://bugs.python.org/issue19859>)
```py
class A:
@property
@functools.lru_cache(maxsize=None)
def x(self):
return 123
for _ in range(100):
A().x # Call lru_cache on 100 different `A` instances
# The instances of `A()` are never garbage-collected:
assert A.x.fget.cache_info().currsize == 100
```
With `cached_property`, there is no cache, so no memory leak.
```py
class B:
@functools.cached_property
def x(self):
return 123
b = B()
print(vars(b)) # {}
b.x
print(vars(b)) # {'x': 123}
del b # b is garbage-collected
```
2. Another difference is that `@property` are read-only while `@cached_property` are not. `cache_property` allows writes to the attributes [Refer Python docs](https://docs.python.org/3/library/functools.html#functools.cached_property)
```
A().x = 123
Traceback (most recent call last):
File "", line 1, in
AttributeError: can't set attribute
```
```
B().x = 123 # Works
```
This is due to the fact that `@cached_property` are replacing the attribute, so the second call to `b.x` bypass the `B.x.get` descriptor call.
3. Another difference which likely don't matter in most cases is that `cached_property` is more performant if you access the same attribute multiple times, while `lru_cache` has overhead for the function call and attribute lookup. Note the difference is only visible with huge numbers.
```py
[A().x for _ in range(10_000)]
[B().x for _ in range(10_000)]
a = A()
b = B()
print(timeit.timeit(lambda: a.x, number=1_000_000)) # ~0.83
print(timeit.timeit(lambda: b.x, number=1_000_000)) # ~0.57
```
Upvotes: 4 |
2018/03/22 | 501 | 1,487 | <issue_start>username_0: I need to use grep from the command line to match a string with the following format
```
_ADFADF_ASFDSAFD_AFDSADF_
```
Should not match on
```
ASDFASDF_ASFDASDF_AFSDASFD
_ASDFASDF_ASDFASDF_ASDFAS
ASDFASD_ASDFSADF_ASFDASD_
```
Match should be only for a string begining and ending with an underscore and underscores may be in the middle of the string. String may be located in middle of line for instance....
```
SetODBCServerOverride.port=_CLIENT_ODBC_TUNNEL_PORT_
```
In the following example, I need to match \_THIS\_MATCHES\_RIGHT\_HERE\_ and not match THIS\_DOES\_NOT\_MATCH
Blah Blah Blah "**\_THIS\_MATCHES\_RIGHT\_HERE\_**" so it's good
Yadda Yadda THIS\_DOES\_NOT\_MATCH and it isn't good. \_THIS\_ALSO\_DOES\_NOT\_MATCH so...<issue_comment>username_1: You can use `^` and `$` to specify the beginning and end of a line respectively:
```
$ grep '^_.*_$' file.txt
```
**EDIT:**
Now that the requirement have been clarified - you can use the special `\<` and `\>` characters to specify the beginning and end of a word, respectively, and `\S` to specify non-whitespace characters (so you don't match strings like `_ABC DEF_`:
```
$ grep '\<_\S*_\>' file.txt
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: this should work
```
grep ^_ | grep _$
```
or you can use REGEX
```
grep -E "^_[A-Z_]+_$"
```
Upvotes: 1 <issue_comment>username_3: ```
grep -E "([^a-zA-Z0-9]|^)_[A-Za-z0-9_]*_([^a-zA-Z0-9]|$)" filename
```
Upvotes: 2 |
2018/03/22 | 729 | 2,652 | <issue_start>username_0: This might be a dumb question but I am new to Angular and haven't gotten an answer for this.
I was following a tutorial and have my routes set up like this for my Angular 5 project:
```
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { PageComponent } from './page/page.component';
const appRoutes: Routes = [
{path: '', redirectTo: '/home', pathMatch: 'full'},
{path: 'home', component: PageComponent, data: {
page: 'home'
}},
{path: 'about', component: PageComponent, data: {
page: 'about'
}},
{path: 'contact', component: PageComponent, data: {
page: 'contact'
}},
{path: 'facebook', component: PageComponent, data: {
page: 'facebook'
}},
{path: '**', redirectTo: '/home', pathMatch: 'full'}
];
@NgModule({
imports: [RouterModule.forRoot(appRoutes)],
exports: [RouterModule]
})
export class AppRoutingModule {
}
```
Let's say I want to route the "facebook" path to my facebook page. I am not sure how to route to pages outside of the Angular Application.
Any help would be appreciated!<issue_comment>username_1: @Rafael Has left the correct answer as a comment.
You would just create a link tag pointing to facebook
```
[Facebook](www.facebook.com/yourpage)
```
The routes that you are setting up are all for local paths.
In other words, all of those routes are for what is displayed on www.yoursite.com/route1, and what is displayed on www.yoursite.com/route2.
But notice that they will all have yoursite.com for the domain.
If you want to create a link to a site outside of your domain, then you do not want to mess with the angular routing, but instead create a link.
So what you're really asking is how can you show www.facebook.com's page on www.yourpage.com/facebook, which is not really possible.
Without an iframe you cannot display a different website within your own site, even with a route.
If that is really what you're trying to do, then you might want to look into iframes.
Upvotes: 5 [selected_answer]<issue_comment>username_2: Just use a regular anchor href.
```
[Add Vehicle](http://facebook.com)
```
or for javascript:
```
window.location.href = 'http://facebook.com';
```
Upvotes: 3 <issue_comment>username_3: For anyone who are looking for a solution on how to implement
the solution mention above using TypeScript here is an example below
```
const link = document.createElement('a');
link.href = 'http://facebook.com/'
link.target = '_blank';
link.click()
```
And if you are finding on how to download from external link just add
```
link.download = 'download';
```
Upvotes: 1 |
2018/03/22 | 752 | 2,494 | <issue_start>username_0: I am not sure if latest version of eclipse i.e. Oxygen supports java 10 or not. I configured the JRE for java 10 from preferences on my mac machine.
[![enter image description here](https://i.stack.imgur.com/vl7ik.png)](https://i.stack.imgur.com/vl7ik.png)
Also, I tried adding maven compiler plugin as below to my pom.xml:-
```
org.apache.maven.plugins
maven-compiler-plugin
10
10
10
true
/Library/Java/JavaVirtualMachines/jdk-10.jdk/Contents/Home
```
I also tried after setting the Run Configurations as below:-
[![enter image description here](https://i.stack.imgur.com/fflNa.png)](https://i.stack.imgur.com/fflNa.png)
Anybody knows how could I make it work for java-10.
I tried running code below:-
```
public class App {
public static void main(String[] args) {
var list = new ArrayList();
System.out.println("Hello World!");
}
}
```
**Update:-** I applied the suggested patch in comment and it still fails.
Screenshot below:-
[![enter image description here](https://i.stack.imgur.com/jt95N.png)](https://i.stack.imgur.com/jt95N.png)
Also, I followed [this](https://stackoverflow.com/questions/49398894/unable-to-compile-simple-java-10-project-with-maven) post to make it compile. So, compilation actually worked from eclipse (`maven install`) but it still fails when I try to run the application.<issue_comment>username_1: So, I requested eclipse to look into it and see why the patch don't work.
[Here](http://marketplace.eclipse.org/comment/5284#comment-5284) is the answer I got
Below is the exact comment from Eclipse community:-
>
> *Note:* This feature patch is disabled. It was originally intended to be
> installed on top of 4.7.3 builds. Now, the Java 10 support is available on
> the downloads page via the 4.7.3a builds. The earliest build that is
> supporting this feature can be downloaded from
>
>
>
So download the supporting build from [here](http://download.eclipse.org/eclipse/downloads/drops4/M-4.7.3aRC1-201803231030/). And see the new features of Eclipse with java 10 [here](https://wiki.eclipse.org/Java10/Examples).
Hope it helps!
**Edit:** The patch support was temporary and has been removed. So, now you need to install the latest eclipse version and it's having the support for java 10
Upvotes: 4 [selected_answer]<issue_comment>username_2: The Eclipse IDE versions, and supported Java versions by IDE, listed over here:
* <https://wiki.eclipse.org/Eclipse/Installation>
Upvotes: 0 |
2018/03/22 | 384 | 1,168 | <issue_start>username_0: How to get and echo number of records in row?this is my code
```
$b = "SELECT COUNT(Users) FROM room";
$r= mysqli_query($connection,$b);
$c = mysqli_fetch_array($r);
echo $c['Users'];
```
I get this error while i have it in `room` table
>
> Notice: Undefined index: ID in C:\xampp\htdocs\php\blog0\rooms.php on
> line 31
>
>
><issue_comment>username_1: Pretty simple answer (And one I made in the past)
You forgot to name the count, it's becomes a system variable and very hard to remember
Change the select to
```
SELECT COUNT(Users) AS Users FROM room
```
Upvotes: 2 [selected_answer]<issue_comment>username_2: Instead of letting MySQL do the counting, get the data and let php [count()](http://php.net/manual/en/function.count.php) do the work.
Change:
```
$b = "SELECT COUNT(Users) FROM room";
$r= mysqli_query($connection,$b);
$c = mysqli_fetch_array($r);
echo $c['Users'];
```
To:
```
$b = "SELECT `Users` FROM room";
$r= mysqli_query($connection,$b);
$c = mysqli_fetch_array($r);
echo count($c['Users']);
```
removed `COUNT(Users)` and replaced it with `Users` and added `count()` to `count($c['Users']);`
Upvotes: 0 |
2018/03/22 | 2,764 | 11,191 | <issue_start>username_0: I have an application with a datagridview on the bottom half of the page and textboxes, combo-boxes, buttons, etc... on the top half.
When the user changes the highlighted row in the grid then it displays all of the information for that row in the objects on the top half.
If user wants to change the data in a row then he clicks an edit button which enables the textboxes etc... and allows the user to edit the data.
(All of the above works fine).
When he wants to save the changes then he clicks the save button.
This should update the datasource to the grid and show the changes in the grid.
However, I have been unable to get it do this.
Any Help appreciated.
Code below:
```
Imports System.Data.SqlClient
Public Class frmEmployeeInformation
Public SQL As New SQLControl()
Dim strEditType As String
Private Sub frmEmployeeInformation_Load(sender As Object, e As EventArgs) Handles MyBase.Load
LoadGrid()
End Sub
Public Sub LoadGrid(Optional query As String = "")
If query = "" Then
SQL.ExecuteQuery("Select * from EmployeeInformation;")
Else
SQL.ExecuteQuery(query)
End If
If SQL.HasException(True) Then Exit Sub
dgvEmployeeInformation.DataSource = SQL.DBDS.Tables(0)
dgvEmployeeInformation.Rows(0).Selected = True
SQL.DBDA.UpdateCommand = New SqlClient.SqlCommandBuilder(SQL.DBDA).GetUpdateCommand
End Sub
Private Sub DisplayValues()
If dgvEmployeeInformation.RowCount > 2 Then
If dgvEmployeeInformation.Rows(dgvEmployeeInformation.CurrentRow.Index).Cells("FirstName").Value <> Nothing Then
txtFirstName.Text = dgvEmployeeInformation.Rows(dgvEmployeeInformation.CurrentRow.Index).Cells("FirstName").Value.ToString 'EmployeeInformation.FirstName
End If
If dgvEmployeeInformation.Rows(dgvEmployeeInformation.CurrentRow.Index).Cells("LastName").Value <> Nothing Then
txtLastName.Text = dgvEmployeeInformation.Rows(dgvEmployeeInformation.CurrentRow.Index).Cells("LastName").Value.ToString 'EmployeeInformation.LastName
End If
If dgvEmployeeInformation.Rows(dgvEmployeeInformation.CurrentRow.Index).Cells("SSN").Value IsNot Nothing Then
txtSSN.Text = dgvEmployeeInformation.Rows(dgvEmployeeInformation.CurrentRow.Index).Cells("SSN").Value.ToString 'EmployeeInformation.SSN
End If
If dgvEmployeeInformation.Rows(dgvEmployeeInformation.CurrentRow.Index).Cells("EmployeeInformationID").Value <> Nothing Then
txtEmployeeID.Text = dgvEmployeeInformation.Rows(dgvEmployeeInformation.CurrentRow.Index).Cells("EmployeeInformationID").Value.ToString 'EmployeeInformation.EmployeeInformationID
End If
'If dgvEmployeeInformation.Rows(dgvEmployeeInformation.CurrentRow.Index).Cells("ADPID").Value <> Nothing Then
'txtADPID.Text = dgvEmployeeInformation.Rows(dgvEmployeeInformation.CurrentRow.Index).Cells("ADPID").Value.ToString 'EmployeeInformation.ADPID
'End If
'If dgvEmployeeInformation.Rows(dgvEmployeeInformation.CurrentRow.Index).Cells("VP").Value <> Nothing Then
'cboVP.Text = dgvEmployeeInformation.Rows(dgvEmployeeInformation.CurrentRow.Index).Cells("VP").Value.ToString 'EmployeeInformation.VP
'End If
If dgvEmployeeInformation.Rows(dgvEmployeeInformation.CurrentRow.Index).Cells("Default_LocationID").Value <> Nothing Then
cboDefaultLocation.Text = dgvEmployeeInformation.Rows(dgvEmployeeInformation.CurrentRow.Index).Cells("Default_LocationID").Value.ToString 'EmployeeInformation.DefaultLocation
End If
If dgvEmployeeInformation.Rows(dgvEmployeeInformation.CurrentRow.Index).Cells("SystemTableID").Value <> Nothing Then
txtTableID.Text = dgvEmployeeInformation.Rows(dgvEmployeeInformation.CurrentRow.Index).Cells("SystemTableID").Value.ToString 'EmployeeInformation.TableID
End If
If dgvEmployeeInformation.Rows(dgvEmployeeInformation.CurrentRow.Index).Cells("EmployeeActive").Value <> Nothing Then
chkbxActive.Checked = dgvEmployeeInformation.Rows(dgvEmployeeInformation.CurrentRow.Index).Cells("EmployeeActive").Value.ToString 'EmployeeInformation.EmployeeActive
End If
If dgvEmployeeInformation.Rows(dgvEmployeeInformation.CurrentRow.Index).Cells("PrimaryFile").Value <> Nothing Then
chkbxPrimaryFile.Checked = dgvEmployeeInformation.Rows(dgvEmployeeInformation.CurrentRow.Index).Cells("PrimaryFile").Value.ToString 'EmployeeInformation.PrimaryFile
End If
If dgvEmployeeInformation.Rows(dgvEmployeeInformation.CurrentRow.Index).Cells("UnallocatedTime").Value <> Nothing Then
chkbxUnallocatedTime.Checked = dgvEmployeeInformation.Rows(dgvEmployeeInformation.CurrentRow.Index).Cells("UnallocatedTime").Value.ToString 'EmployeeInformation.UnallocatedTime
End If
End If
End Sub
Private Sub ChangeButtons()
btnClose.Enabled = Not btnClose.Enabled
btnSave.Enabled = Not btnSave.Enabled
btnClear.Enabled = Not btnClear.Enabled
btnFind.Enabled = Not btnFind.Enabled
btnCancel.Enabled = Not btnCancel.Enabled
btnEdit.Enabled = Not btnEdit.Enabled
btnAdd.Enabled = Not btnAdd.Enabled
btnCopy.Enabled = Not btnCopy.Enabled
End Sub
Private Sub ChangeFields()
chkbxActive.Enabled = Not chkbxActive.Enabled
chkbxPrimaryFile.Enabled = Not chkbxPrimaryFile.Enabled
chkbxUnallocatedTime.Enabled = Not chkbxUnallocatedTime.Enabled
txtTableID.Enabled = Not txtTableID.Enabled
txtADPID.Enabled = Not txtADPID.Enabled
cboVP.Enabled = Not cboVP.Enabled
cboDefaultLocation.Enabled = Not cboDefaultLocation.Enabled
End Sub
Private Sub btnClose_Click(sender As Object, e As EventArgs) Handles btnClose.Click
Me.Close()
End Sub
Private Sub btnFind_Click(sender As Object, e As EventArgs) Handles btnFind.Click
If txtEmployeeID.Text <> "" Then
SQL.AddParam("@EmployeeInformationID", txtEmployeeID.Text)
LoadGrid("select * from EmployeeInformation where EmployeeInformationID = @EmployeeInformationID;")
ElseIf txtSSN.Text <> "" Then
SQL.AddParam("@SSN", txtSSN.Text)
LoadGrid("select * from EmployeeInformation where SSN = @SSN;")
ElseIf txtFirstName.Text <> "" And txtLastName.Text <> "" Then
SQL.AddParam("@FirstName", txtFirstName.Text)
SQL.AddParam("@LastName", txtLastName.Text)
LoadGrid("select * from EmployeeInformation where FirstName = @FirstName and LastName = @LastName;")
Else
LoadGrid("Select * from EmployeeInformation;")
End If
End Sub
Private Sub btnClear_Click(sender As Object, e As EventArgs) Handles btnClear.Click
txtFirstName.Text = ""
txtLastName.Text = ""
txtSSN.Text = ""
txtEmployeeID.Text = ""
txtADPID.Text = ""
cboVP.Text = ""
cboDefaultLocation.Text = ""
txtTableID.Text = ""
chkbxActive.Checked = "False"
chkbxPrimaryFile.Checked = "False"
chkbxUnallocatedTime.Checked = "False"
End Sub
Private Sub dgvEmployeeInformation_DoubleClick(sender As Object, e As EventArgs) Handles dgvEmployeeInformation.DoubleClick
DisplayValues()
ChangeFields()
ChangeButtons()
End Sub
Private Sub dgvEmployeeInformation_SelectionChanged(sender As Object, e As EventArgs) Handles dgvEmployeeInformation.SelectionChanged
DisplayValues()
End Sub
Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
If strEditType = "Edit" Then
' The code below updates the grid but the changes are not saved to the database. Probably not the way to go
dgvEmployeeInformation.Rows(dgvEmployeeInformation.CurrentRow.Index).Cells("FirstName").Value = txtFirstName.Text 'EmployeeInformation.FirstName
dgvEmployeeInformation.Rows(dgvEmployeeInformation.CurrentRow.Index).Cells("LastName").Value = txtLastName.Text 'EmployeeInformation.LastName
dgvEmployeeInformation.Rows(dgvEmployeeInformation.CurrentRow.Index).Cells("SSN").Value = txtSSN.Text 'EmployeeInformation.SSN
dgvEmployeeInformation.Rows(dgvEmployeeInformation.CurrentRow.Index).Cells("EmployeeInformationID").Value = txtEmployeeID.Text 'EmployeeInformation.EmployeeInformationID
dgvEmployeeInformation.Rows(dgvEmployeeInformation.CurrentRow.Index).Cells("Default_LocationID").Value = cboDefaultLocation.Text 'EmployeeInformation.DefaultLocation
dgvEmployeeInformation.Rows(dgvEmployeeInformation.CurrentRow.Index).Cells("SystemTableID").Value = txtTableID.Text 'EmployeeInformation.TableID
dgvEmployeeInformation.Rows(dgvEmployeeInformation.CurrentRow.Index).Cells("EmployeeActive").Value = chkbxActive.Checked 'EmployeeInformation.EmployeeActive
dgvEmployeeInformation.Rows(dgvEmployeeInformation.CurrentRow.Index).Cells("PrimaryFile").Value = chkbxPrimaryFile.Checked 'EmployeeInformation.PrimaryFile
dgvEmployeeInformation.Rows(dgvEmployeeInformation.CurrentRow.Index).Cells("UnallocatedTime").Value = chkbxUnallocatedTime.Checked 'EmployeeInformation.UnallocatedTime
' The code above updates the grid but the changes are not saved to the database.
dgvEmployeeInformation.EndEdit()
SQL.DBDS.Tables(0).AcceptChanges()
SQL.DBDA.Update(SQL.DBDS)
'txtADPID.Text = dgvEmployeeInformation.Rows(dgvEmployeeInformation.CurrentRow.Index).Cells("ADPID").Value.ToString 'EmployeeInformation.ADPID
'cboVP.Text = dgvEmployeeInformation.Rows(dgvEmployeeInformation.CurrentRow.Index).Cells("VP").Value.ToString 'EmployeeInformation.VP
End If
ChangeFields()
ChangeButtons()
strEditType = ""
'LoadGrid()
End Sub
Private Sub btnCancel_Click(sender As Object, e As EventArgs) Handles btnCancel.Click
ChangeFields()
ChangeButtons()
strEditType = ""
End Sub
Private Sub btnEdit_Click(sender As Object, e As EventArgs) Handles btnEdit.Click
dgvEmployeeInformation_DoubleClick(Nothing, EventArgs.Empty)
strEditType = "Edit"
End Sub
Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click
btnClear_Click(Nothing, EventArgs.Empty)
txtFirstName.Focus()
strEditType = "Add"
ChangeFields()
ChangeButtons()
End Sub
Private Sub btnCopy_Click(sender As Object, e As EventArgs) Handles btnCopy.Click
cboDefaultLocation.Focus()
strEditType = "Copy"
ChangeFields()
ChangeButtons()
End Sub
End Class
```<issue_comment>username_1: Pretty simple answer (And one I made in the past)
You forgot to name the count, it's becomes a system variable and very hard to remember
Change the select to
```
SELECT COUNT(Users) AS Users FROM room
```
Upvotes: 2 [selected_answer]<issue_comment>username_2: Instead of letting MySQL do the counting, get the data and let php [count()](http://php.net/manual/en/function.count.php) do the work.
Change:
```
$b = "SELECT COUNT(Users) FROM room";
$r= mysqli_query($connection,$b);
$c = mysqli_fetch_array($r);
echo $c['Users'];
```
To:
```
$b = "SELECT `Users` FROM room";
$r= mysqli_query($connection,$b);
$c = mysqli_fetch_array($r);
echo count($c['Users']);
```
removed `COUNT(Users)` and replaced it with `Users` and added `count()` to `count($c['Users']);`
Upvotes: 0 |
2018/03/22 | 1,037 | 3,036 | <issue_start>username_0: I need an algorithm that can round a corner between a line and an arc. The start information that I have is P0-start point, P-corner point, P2-end point, R2-radius of the arc between P and P2 and R-radius of the rounded corner(on the second picture).
[![Corner between line and arc](https://i.stack.imgur.com/wkm7o.jpg)](https://i.stack.imgur.com/wkm7o.jpg)
Output or wanted points are cross sections C0 and C2 and center point of the rounding circle-O
[![Rounded corner between line and arc](https://i.stack.imgur.com/QGKLC.jpg)](https://i.stack.imgur.com/QGKLC.jpg)<issue_comment>username_1: There isn't enough specification to choose a unique arc. You need to figure out what endpoints you want. Then solve for the ellipse that is tangent to both of those points. See [Wikipedia/ellipse](https://en.wikipedia.org/wiki/Ellipse) for the equations. I recommend a math package (e.g. SciKit) to solve for you.
Upvotes: 0 <issue_comment>username_2: In my sketch BF is part of given segment (F is not known yet), C is center of given arc, B is point of rough conjugation. `c` is line, parallel to BF, `|GF|=|GH| = r` - radius of small arc.
To make smooth conjugation, tangent to small arc in point F should be collinear with BF direction, so GF is perpendicular to BF, and tangents to both arcs in point H should coincide - so radius-vectors CH and GH lie on the same line.
[![enter image description here](https://i.stack.imgur.com/ZVxF8.png)](https://i.stack.imgur.com/ZVxF8.png)
Let unit direction vector of BF segment is `ud=(dx,dy)`, so unit normal is `un=(-dy, dx)`. (Negate normal for arcs at another side of BF)
Center of small arc G has coordinates (where t is unknown parameter - length of BF)
```
G = B + ud * t + un * r
```
and distance GC is difference of arcs radii, so
```
|G - C| = |R - r|
or in coordinates:
(B.x + dx * t - dy * r - C.x)^2 + (B.y + dy * t + dx * r - C.y)^2 = (R - r)^2
```
Open parentheses, solve quadratic equation for unknown t. If solutions exist, choose right root, and you'll get coordinates of center of conjugation arc G and its ends
quick check1:
Line Y=5, big arc with R=5, we want small arc with r=2
```
B=(5,5)
ud=(-1,0)
un=(0,-1)
(5-t)^2 + (5-2-5)^2 = (5-2)^2
solution gives
t = 5 +/- Sqrt(5), the second root is valid
E = (5 - (5 - Sqrt(5)), 3) = (2.23, 3)
```
Resulting smooth arc is `c-f`
[![enter image description here](https://i.stack.imgur.com/3hKhX.png)](https://i.stack.imgur.com/3hKhX.png)
quick check2:
Line Y=5, big arc with R=5, we want small arc with r=2
```
B=(5,5)
big arc center (H here) = (1,2)
ud=(-1,0)
un=(0,-1)
(4-t)^2 + (5-2-2)^2 = (5-2)^2
solution gives
t = 4 +/- Sqrt(8), the second root is valid
E = (5 - (4 - Sqrt(8)), 3) = (3.83, 3)
```
Resulting smooth arc is `F-G`
(In both cases larger root corresponds to conjugation with complementary part of big arc)
[![enter image description here](https://i.stack.imgur.com/V37H2.png)](https://i.stack.imgur.com/V37H2.png)
Upvotes: 3 [selected_answer] |
2018/03/22 | 1,920 | 3,833 | <issue_start>username_0: I have a dataset that looks like this:
```
user_id day_session rank day_diff
xyz789 2017-11-19 1 1
abc123 2017-11-19 1 1
abc123 2017-11-20 2 1
abc123 2017-11-21 3 1
abc123 2017-11-22 4 1
abc123 2017-11-23 5 1
abc123 2017-11-24 6 1
abc123 2017-11-25 7 1
abc123 2017-11-26 8 1
abc123 2017-11-27 9 1
abc123 2017-11-28 10 1
abc123 2017-11-29 11 1
abc123 2017-11-30 12 1
abc123 2017-12-01 13 1
abc123 2017-12-02 14 1
def456 2017-11-19 1 1
def456 2017-11-20 2 1
def456 2017-11-21 3 1
def456 2017-11-22 4 1
def456 2017-11-23 5 1
def456 2017-11-24 6 1
def456 2017-11-25 7 1
def456 2017-11-26 8 1
def456 2017-11-27 9 1
def456 2017-11-28 10 1
def456 2017-11-29 11 1
def456 2017-11-30 12 1
def456 2017-12-01 13 1
def456 2017-12-02 14 1
def456 2017-12-03 15 1
def456 2017-12-04 16 1
def456 2017-12-05 17 1
def456 2017-12-06 18 1
def456 2017-12-07 19 1
def456 2017-12-08 20 1
def456 2017-12-09 21 1
def456 2017-12-10 22 1
def456 2017-12-11 23 1
def456 2017-12-12 24 1
def456 2017-12-13 25 1
def456 2017-12-14 26 1
def456 2017-12-15 27 1
def456 2017-12-16 28 1
def456 2017-12-17 29 1
def456 2017-12-18 30 1
def456 2017-12-19 31 1
def456 2017-12-20 32 1
def456 2017-12-21 33 1
def456 2017-12-22 34 1
def456 2017-12-23 35 1
def456 2017-12-24 36 1
def456 2017-12-25 37 1
def456 2017-12-26 38 5
def456 2017-12-31 39 1
def456 2018-01-01 40 1
def456 2018-01-02 41 1
def456 2018-01-03 42 1
def456 2018-01-04 43 1
```
I'd like to calculate the number of consecutive day sessions each user\_id has from the earliest day\_session in the dataset. So user xyz789 would return 1, abc123 would return 14 and def456 would return 38. TIA<issue_comment>username_1: Based on your data, you can just do:
```
select t.user, count(*)
from t left join
(select user, min(day_session) as minds
from t
where day_diff > 1
group by user
) tt
on t.user = tt.user
where tt.minds is null or t.day_session < tt.minds
group by t.user;
```
Upvotes: 2 [selected_answer]<issue_comment>username_2: For what it's worth, here is a solution using SQL Server:
```
declare @order table (rowid int identity, user_id varchar(max), day_session datetime, isconsecutive int)
insert @order
select distinct user_id, day_session,
case
when
lag(user_id, 1,0) over (order by user_id desc, day_session)=user_id and
lag(day_session, 1,0) over
(order by user_id desc, day_session)=dateadd(dd,-1,day_session)
then 1
else 0
end
from #temp
order by user_id desc, day_session
declare @holding table (user_id varchar(max), consday int, day_session datetime)
declare @iterator int=1
declare @userid varchar(max)
declare @userid2 varchar(max)
declare @isconsecutive int=1
while @iterator<=(select max(rowid) from @order)
begin
select @userid=user_id, @isconsecutive=isconsecutive
from @order
where rowid=@iterator
if @isconsecutive=0 and
(select user_id from @order where rowid=@iterator-1)=
(select user_id from @order where rowid=@iterator)
select @userid2=@userid+'_'+cast(@iterator as varchar)
if (select user_id from @order where rowid=@iterator-1)<>(select user_id from @order where rowid=@iterator)
select @userid2=null
insert @holding
select isnull(@userid2, @userid) , isconsecutive, day_session
from @order
where rowid=@iterator
set @iterator=@iterator+1
end
select user_id, max(cnt) maxconsdays from(
select substring(user_id, 1, len(user_id)-charindex('_', reverse(user_id)))user_id, sum(consday)+1 cnt from @holding
group by user_id)a
group by user_id
order by user_id desc
```
Upvotes: 0 |
2018/03/22 | 1,351 | 4,148 | <issue_start>username_0: I'm trying to take the output of our scheduling software for a TV station and get rid of anything for given times. Unfortunately the output of the scheduling software creates a text field for time, not a field that can be formatted to time. I haven't done any real programming in over a decade and this is frustrating me. Here's a sample of the first few rows of the sheet - every day of the month contains entries for each program from 6:00a to the next day at 5:30a.
[![enter image description here](https://i.stack.imgur.com/DC8W1.jpg)](https://i.stack.imgur.com/DC8W1.jpg)
The code I've got so far is:
```
Sub delete_extraneous()
Dim rng As Range
Dim j As Integer
Dim m As Integer
m = 1
j = 3
Goto ActiveSheet.Cells(j, m)
With ActiveSheet
lastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
End With
For m = 1 To lastRow
If rng = "6:30a" Or "7:00a" Or "7:30a" Or "8:00a" Or "8:30a" Or "9:00a" Or "9:30a" Or "10:00a" Or "10:30a" Or "11:00a" Or "11:30a" Then
ActiveCell.EntireRow.Delete Shift:=xlShiftUp
End If
Next m
End Sub
```<issue_comment>username_1: Use an array of text-that-looks-like-time and match against it.
```
Sub delete_extraneous()
dim tms as variant, lastRow as long
tms = array("6:30a", "7:00a", "7:30a", "8:00a", "8:30a", "9:00a", "9:30a", _
"10:00a", "10:30a", "11:00a", "11:30a")
with activesheet
lastRow = .Cells(.Rows.Count, "C").End(xlUp).Row
For m = lastRow to 1 step-1
If not iserror(application.match(.Cells(m, "C").value, tms, 0)) Then
.rows(m).EntireRow.Delete Shift:=xlShiftUp
End If
Next m
.
end with
end sub
```
Upvotes: 1 <issue_comment>username_2: You don't state what your specific issue is in the code, but I can tell you a few problems you have.
**1)** This is not valid syntax `Goto ActiveSheet.Cells(j, m)`. There is a `GoTo` statement in VBA, but only use when absolutely necessary. (this case does not require it).
**2)** Don't rely on `ActiveSheet`. Instead reference the selected worksheet you desire to work with directly.
**3)** You never actually define `rng` so it's meaningless and your code will always bypass range. Using `Option Explicit` at the top of your modules can help avoid this issue.
**4)** Using active cell is also dangerous and may produce unintended consequences. In your case it will delete the same cell over and over and over again since you never activate any other cell. It's not needed.
See this code below. It also checks for row deletion and loads into a range for one delete statement later (which will be faster than deleting line by line, and doesn't require backwards looping).
```
Option Explicit
Sub delete_extraneous()
Dim mySheet As Worksheet
Set mySheet = Worksheets("mySheet") 'replace as needed
Dim lastRow As Long
lastRow = mySheet.Cells(mySheet.Rows.Count, 1).End(xlUp).Row
Dim m As Long
For m = 1 To lastRow
Select Case mySheet.Cells(m, 3).Value 'check each row against column C
Case Is = "6:30a", "7:00a", "7:30a", "8:00a", "8:30a", "9:00a", "9:30a", "10:00a", "10:30a", "11:00a", "11:30a"
Dim deleteRng As Range
If deleteRng Is Nothing Then
Set deleteRng = mySheet.Cells(m, 3)
Else
Set deleteRng = Union(deleteRng, mySheet.Cells(m, 3))
End If
End Select
Next
deleteRng.EntireRow.Delete
End Sub
```
Upvotes: 1 [selected_answer]<issue_comment>username_3: You could use Autofilter():
```
Sub test()
Dim hours As Variant
hours = Array("6:30a", "7:00a", "7:30a", "8:00a", "8:30a", "9:00a", "9:30a", "10:00a", "10:30a", "11:00a", "11:30a")
With Range("C1", Cells(Rows.Count, 3).End(xlUp))
.AutoFilter Field:=1, Criteria1:=hours, Operator:=xlFilterValues
.Offset(1, 0).SpecialCells(xlCellTypeVisible).EntireRow.Delete
If Not IsError(Application.Match(.Cells(1, 1).value, hours, 0)) Then .Rows(1).Delete
End With
ActiveSheet.AutoFilterMode = False
End Sub
```
Upvotes: 1 |
2018/03/22 | 911 | 2,772 | <issue_start>username_0: I'm trying to add to my bash profile something that will set my node version to a specific version, and if the node version is not installed then install it. What I have so far is:
```
. /usr/local/opt/nvm/nvm.sh
if [[ $(nvm use v6.9.1) == "" ]]; then
nvm install v6.9.1
fi
```
However, the problem is that the `$(nvm use v6.9.1)` is run in a subshell and my node version doesn't get switched.
a) Is there any way to have `$(nvm use v6.9.1)` run in the current shell?
b) Is there a better way of doing this?
Previously I was just running `nvm install v6.9.1` but this was kinda slow which was an issue as it runs each time I open a new terminal.
Thanks Matt!<issue_comment>username_1: Have you tried grepping nvm ls?
```
. /usr/local/opt/nvm/nvm.sh
if [[ $(nvm ls | grep v6.9.1) == "" ]]; then
nvm install v6.9.1
else
nvm use v6.9.1
fi
```
Is it any faster than using `nvm install v6.9.1` for you?
EDIT: You can also set a default version that will always be loaded by default. You can do it by running `nvm alias default 6.9.1`.
You can try changing your script to this:
```
if [[ $(node -v) != "v6.9.5" ]]; then
nvm install v6.9.5
nvm alias default v6.9.5
fi
```
It will take a little long, but just for the first time
Upvotes: 3 [selected_answer]<issue_comment>username_2: This works. If `use` failed, it will execute `install`.
```
#!/bin/sh
nvm use 14.18.1 || nvm install 14.18.1
# or if you don't need the warning
nvm use 14.18.1 2>/dev/null || nvm install 14.18.1
```
[![execute example](https://i.stack.imgur.com/OhAjy.png)](https://i.stack.imgur.com/OhAjy.png)
Upvotes: -1 <issue_comment>username_3: I have a bash alias I use for this that works for multiple versions:
```sh
alias nvmuse='nvm use || nvm install $(cat .nvmrc)'
```
Upvotes: 3 <issue_comment>username_4: In the current version of nvm, `nvm install` does not reinstall node if it's already installed.
Examples:
```none
$ nvm install v16.0.4
v16.14.2 is already installed.
# The same if you have put the version in your project's .nvmrc
$ nvm install
v16.0.4 is already installed.
```
Note however, if you specify an *ambiguous* version such as `v16` and a *newer version* of v16 is available, then nvm will download and install the newer version, ignoring your older version of v16.
```none
$ node --version
v16.0.4
$ nvm install v16
Downloading and installing node v16.14.2...
```
So specifying `v16` is good if you always want to be up-to-date, and have the latest security patches. But eventually you might end up with lots of versions of node installed!
To keep just one version installed (to save disk space, or to keep packages you previously installed globally with npm) then specify the full version `v16.0.4`.
Upvotes: 1 |
2018/03/22 | 1,423 | 5,229 | <issue_start>username_0: I have a simple REST API and I would like to implement filtering on a specific endpoint.
Imagine I have an endpoint like this:
```
localhost:5000/api/items?color="red"
```
Which handles request like this:
```
const items = await Items.find({color: req.query.color})
```
This works when the `color` parameter is present. However, if the `color` parameter is omitted then the query searches for items where the `color` is `undefined`. This is not the behaviour I need.
In my case, I would like to add **multiple filter parameters** which are ignored if they are not present. Do I have to create a separate query for each case or is there an option to tell Mongoose not to search for a field (in this case `color`) if it is null or undefined?<issue_comment>username_1: You can unpack the variables in req.query using a '[destructuring assignment](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Object_destructuring)'.
```
const { color } = req.query;
if(color) {
const items = await Items.find({ color })
}
```
If you have multiple filters, you can use the variables from above. For example, you may have `color` and `type` parameters. With this, you can build up an object to pass to the find method.
```
const { color, type } = req.query;
let query = {};
if(color) {
query.color = color;
}
if(type) {
query.type = type;
}
const items = await Items.find(query);
```
If `color` or `type` is not in the original query, they will be *undefined* or [*falsy*](https://developer.mozilla.org/en-US/docs/Glossary/Falsy) and so will skip the if statement for that parameter.
Hope it works!
Upvotes: 5 [selected_answer]<issue_comment>username_2: I just hit the same issue, if you are using ES6 supported node version, you should be able to use spread. it automatically takes care of the undefined
```
var filters = {
colour: "red",
size: undefined
}
Items.find({...filters})
// only colour is defined, so it becomes
Items.find({colour:"red"})
```
NOTE if you are using Babel. you might need to define a object first.
```
var query = {...filters}
Items.find(query)
```
Upvotes: 4 <issue_comment>username_3: You may **remove undefined keys** from object before passing that object.
```
Object.keys(filter).forEach(key => filter[key] === undefined && delete filter[key])
```
Put the above code inside util and reuse it everywhere.
Upvotes: 2 <issue_comment>username_4: You can use `ignoreUndefined` in your connection options when connecting to MongoDB so that in your queries all undefined keys are skipped when they are serialized to BJSON. You can see the options on this [page](https://mongodb.github.io/node-mongodb-native/2.2/api/MongoClient.html#connect)
Upvotes: 1 <issue_comment>username_5: As stated by username_4, you can achieve this without performing any manual checks by using `ignoreUndefined` in connection options:
```
const mongoose = require('mongoose');
mongoose.connect(mongoDb, { ignoreUndefined: true });
```
Alternatively, you can use `reduce` to explicitly specify the options that you're looking for in the query as an array and construct the filter object with only the fields that are not `undefined`:
```
const query = { color: 'red', price: 2, hello: 'world' };
const fields = ['color', 'price', 'size'];
function getFilter(query, fields) {
return fields.reduce((filter, field) => {
if (query[field] !== undefined)
return {
[field]: query[field],
...filter,
};
return filter;
}, {});
}
const filter = getFilter(query, fields); // { price: 2, color: 'red' }
```
In this case the function doesn't add the "hello" field to the object because "hello" is not in the array. It also ignores "size" because it's not in the query. You can use the returned object like this:
```
const items = await Items.find(filter);
```
You can shorten this function using implicit return and ternary operator:
```
const getFilter = (query, fields) => fields.reduce(
(filter, field) => query[field] !== undefined ? {
[field]: query[field],
...filter,
} : filter, {}
);
```
Cool albeit arguably less readable.
Upvotes: 2 <issue_comment>username_6: I'm also got this issue. this is my solution:
* add the ignoreUndefined in the connect settings
* I'm using nestjs
```js
MongooseModule.forRootAsync({
imports: [ConfigModule],
inject: [ConfigService],
useFactory: async (configService: ConfigService) => ({
uri: configService.get('MONGO\_URI'),
useCreateIndex: true,
useNewUrlParser: true,
useFindAndModify: false,
useUnifiedTopology: true,
ignoreUndefined: true, // add this to the option
connectionFactory: (connection) => {
connection.plugin(require('mongoose-autopopulate'));
return connection;
},
})
```
* this is the query log:
```js
Mongoose: entry.find({ field: undefined })
```
* then I got all the entrys
Upvotes: 3 <issue_comment>username_7: ```
const query = Object.fromEntries(Object.entries(req.query).filter(([_,value]) => !!value))
Items.find({...query})
```
This will create your a useful query object and also help in the situation where parameter is an empty string
Upvotes: 0 |
2018/03/22 | 1,418 | 4,023 | <issue_start>username_0: I am facing the following error:
```
Warning: the environment variable LANG is not set!
We recommend setting this in ~/.profile (or equivalent) for proper expected behavior.
Creating a virtualenv for this project…
Using /usr/local/opt/python/bin/python3.6 (3.6.4) to create virtualenv…
⠋Traceback (most recent call last):
File "/usr/local/Cellar/python/3.6.4_4/Frameworks/Python.framework/Versions/3.6/lib/python3.6/runpy.py", line 193, in _run_module_as_main
"__main__", mod_spec)
File "/usr/local/Cellar/python/3.6.4_4/Frameworks/Python.framework/Versions/3.6/lib/python3.6/runpy.py", line 85, in _run_code
exec(code, run_globals)
File "/usr/local/lib/python3.6/site-packages/pipenv/pew/__main__.py", line 8, in
import pew
File "/usr/local/lib/python3.6/site-packages/pipenv/patched/pew/\_\_init\_\_.py", line 1, in
from . import pew
File "/usr/local/lib/python3.6/site-packages/pipenv/patched/pew/pew.py", line 41, in
from pew.\_utils import (check\_call, invoke, expandpath, own, env\_bin\_dir,
File "/usr/local/lib/python3.6/site-packages/pipenv/patched/pew/\_utils.py", line 22, in
encoding = locale.getlocale()[1] or 'ascii'
File "/usr/local/Cellar/python/3.6.4\_4/Frameworks/Python.framework/Versions/3.6/lib/python3.6/locale.py", line 581, in getlocale
return \_parse\_localename(localename)
File "/usr/local/Cellar/python/3.6.4\_4/Frameworks/Python.framework/Versions/3.6/lib/python3.6/locale.py", line 490, in \_parse\_localename
raise ValueError('unknown locale: %s' % localename)
ValueError: unknown locale: UTF-8
```
Virtualenv location:
```
Creating a Pipfile for this project…
Traceback (most recent call last):
File "/usr/local/bin/pipenv", line 11, in
sys.exit(cli())
File "/usr/local/lib/python3.6/site-packages/pipenv/vendor/click/core.py", line 722, in \_\_call\_\_
return self.main(\*args, \*\*kwargs)
File "/usr/local/lib/python3.6/site-packages/pipenv/vendor/click/core.py", line 697, in main
rv = self.invoke(ctx)
File "/usr/local/lib/python3.6/site-packages/pipenv/vendor/click/core.py", line 1066, in invoke
return \_process\_result(sub\_ctx.command.invoke(sub\_ctx))
File "/usr/local/lib/python3.6/site-packages/pipenv/vendor/click/core.py", line 895, in invoke
return ctx.invoke(self.callback, \*\*ctx.params)
File "/usr/local/lib/python3.6/site-packages/pipenv/vendor/click/core.py", line 535, in invoke
return callback(\*args, \*\*kwargs)
File "/usr/local/lib/python3.6/site-packages/pipenv/cli.py", line 366, in install
selective\_upgrade=selective\_upgrade,
File "/usr/local/lib/python3.6/site-packages/pipenv/core.py", line 1761, in do\_install
skip\_requirements=skip\_requirements,
File "/usr/local/lib/python3.6/site-packages/pipenv/core.py", line 636, in ensure\_project
ensure\_pipfile(validate=validate, skip\_requirements=skip\_requirements)
File "/usr/local/lib/python3.6/site-packages/pipenv/core.py", line 289, in ensure\_pipfile
project.create\_pipfile(python=python)
File "/usr/local/lib/python3.6/site-packages/pipenv/project.py", line 518, in create\_pipfile
'python\_version': python\_version(required\_python)[: len('2.7')]
TypeError: 'NoneType' object is not subscriptable
```
I tried setting the `LANG` in `~/.profile` and `~/.bash_profile`. Both didn't work.<issue_comment>username_1: What worked for me on Mac OS X Sierra is adding the following into my `~/.bash_profile` file:
```
export LANG="en_US.UTF-8"
export LC_ALL="en_US.UTF-8"
export LC_CTYPE="en_US.UTF-8"
```
Then I reloaded the bash profile with: `source ~/.bash_profile`
For those who use zsh shell, you must add those lines to your `~/.zshrc`
```
export LANG="en_US.UTF-8"
export LC_ALL="en_US.UTF-8"
export LC_CTYPE="en_US.UTF-8"
```
Then I reload the bash profile with: `source ~/.zshrc`
Upvotes: 7 [selected_answer]<issue_comment>username_2: For those who use zsh you must add those lines to your ~/.zshrc
```
export LANG="en_US.UTF-8"
export LC_ALL="en_US.UTF-8"
export LC_CTYPE="en_US.UTF-8"
```
Upvotes: 3 |
2018/03/22 | 896 | 3,332 | <issue_start>username_0: I have the following situation:
```
$var: mobiConfig;
@media (min-width: 750px) {
$var: deskConfig;
}
```
I am trying to change the sass variable within a media query and somehow it is always returning `deskConfig`
Is this the expected behavior?<issue_comment>username_1: Sass variable scope is a little bid different than other implementations:
* Always set global variables and do not reset them throughout the
stylesheet
* Make use of !default flag
For more info:
<https://anotheruiguy.gitbooks.io/sassintherealworld_book-i/handy-tools/variable-scoping.html>
Upvotes: 0 <issue_comment>username_2: This is an unusual instance of a common mistake: you are mixing *server-side* and *client-side* logic.
The `@media (min-width: 750px) { ... }` block is a directive which is passed onto the web browser to evaluate at run time, and conditionally apply rules. As you resize the browser window or viewport, the browser will continuously re-check this condition, and decide whether to apply the CSS rules it contains.
The `$var: deskConfig;` assignment, on the other hand, is a directive to the SASS/SCSS compiler. This runs over the entire file, processes it, and returns the result, which will probably be saved to disk, and served to every browser which visits. The compiler cannot know what size window someone will browse the site in.
The only thing SASS can do with `@media` queries is decide where to echo them in the resulting CSS. For instance, you can nest things "inside out", like `.foo { @media(min-width: 750px) { color: red; } }`, and SASS will generate the correct CSS `@media(min-width: 750px) { .foo { color: red; } }`.
I guess it would theoretically be possible for the compiler to detect that the assignment was in an `@media` block, and generate two versions of *every single rule which mentioned that variable*, so that `.foo { color: $var; }` automatically became `.foo { color: red; } @media(min-width: 750px) { .foo { color: red; } }`. But that would be incredibly complicated, and frankly rather confusing.
Upvotes: 4 [selected_answer]<issue_comment>username_3: I have tried this then i fixed my issue. It will calculate all media-breakpoint automatically by given rate (base-size/rate-size)
Visit [Using media-queries to set variable values using Sass](https://stackoverflow.com/questions/49436927/using-media-queries-to-set-variable-values-using-sass/54188992#54188992)
Upvotes: 0 <issue_comment>username_4: Solution:
```
$var: mobiConfig;
@media (min-width: 750px) {
$var: deskConfig !global;
xxx: $var; // = deskConfig
$var: mobiConfig !global;
}
yyy: $var; // = mobiConfig
```
Upvotes: 0 <issue_comment>username_5: If I understand what you're trying to do correctly, you can achieve that desired behavior using css variables instead. You can define css variables for different media queries in one sass file, and then use those same variables to calculate different things in another file, provided that the file defining the variable, is imported before the file using the variable. Css variables are client side, so they will respond to the screen size change, unlike sass variables.
Here's how to change css variables on different screen sizes: <https://www.w3schools.com/css//css3_variables_mediaqueries.asp>
Upvotes: 1 |
2018/03/22 | 752 | 1,796 | <issue_start>username_0: I have a list containing hundreds of ip addresses and masks in this format:
```
['10.10.10.0/255.255.255.0', '10.10.20.0/255.255.255.192']
```
I would like to convert this list to this format:
```
['10.10.10.0/24', '10.10.20.0/26']
```
Here is my code:
```
# List already containing all ip/mask (format: 10.10.10.0/255.255.255.0') shown above
print ip_mask_list
#hardcoded mask for testing
netmask = "255.255.248.0"
#convert mask to CIDR
cidr = sum([bin(int(x)).count('1') for x in netmask.split('.')])
print cidr # prints 21
```
I can convert a mask to CIDR but how would I do it so instead of passing hardcoded netmask variable, I can pass `ip_mask_list` and it goes thru all masks and convert the to CIDR as shown above. Maybe create a next list where all `255.x.x.x` are converted to `/xx`.
Thanks
Damon<issue_comment>username_1: You can use regex:
```
import re
s = ['10.10.10.0/255.255.255.0', '10.10.20.0/255.255.255.192']
final_ips = ['{}/{}'.format(a, sum([bin(int(x)).count('1') for x in b.split('.')])) for a, b in map(lambda x:re.findall('[\d\.]+', x), s)]
```
Output:
```
['10.10.10.0/24', '10.10.20.0/26']
```
Upvotes: 1 <issue_comment>username_2: This one splits the original IP address in an IP and a mask part. The IP Address is used as before while the `cidr_suffix` is calculated based on the number of set bits in the `ip_mask`.
```
ips = ['10.10.10.0/255.255.255.0', '10.10.20.0/255.255.255.192']
def append_cidr_suffix(full_ip):
address_and_mask = full_ip.split('/')
prefix = address_and_mask[0]
ip_mask = address_and_mask[1]
suffix = sum(bin(int(sub_part)).count('1') for sub_part in ip_mask.split('.'))
return prefix + '/' + str(suffix)
cidr_ips = [append_cidr_suffix(i) for i in ips]
```
Upvotes: 0 |
2018/03/22 | 226 | 886 | <issue_start>username_0: I am looking to monitor an Oracle database.
Do you have an idea about the metrics useful that I have to monitor?
Thank you in advance for your help.<issue_comment>username_1: I think:
* CPU occupation
* Memory occupation
* Number of open sessions
Upvotes: 0 <issue_comment>username_2: As an administration question, this is probably not the right site for this question. However, Oracle provides excellent documentation. Which metrics you monitor depends on your objective: Just keeping the database running (e.g., memory, CPU, storage limits being reached), making it run fast (e.g., optimizing pl/sql code, looking for the longest queries in v$sql, missing indexes/full table scans), etc.
Check out: [https://docs.oracle.com/database/121/TGDBA/title.htm](https://docs.oracle.com/database/121/TGDBA/title.htm "Oracle's Performance Tuning Guide")
Upvotes: 1 |
2018/03/22 | 1,501 | 5,654 | <issue_start>username_0: I am trying to challenge my learning by creating a simple project using rails forms, however I have gotten really stuck and can't find any information that seems to help online.
**What I am trying to do:**
I want to create a rails application with no model (so no persistence of data). Simply put I want a user to enter a Soundcloud URL which then gets transferred to the controller where I can do more logic. Essentially I am really trying to understand the connection between the Rails form and the controller in rails. I have spent all day reading about HTML forms, as well as googling this exact question without really fully getting it.
I understand there are different form helpers, but what I cannot seem to understand is how to use these without a model. My biggest hang up right now is I cannot get the form values transferred to the controller. I thought I understood RESTful routes, PUT/GET etc.. but this has made me super frustrated that I cannot seem to get my head around this. Any advice is super appreciated.
**The code:**
Below is the specific code I am struggling with, currently when I get submit the form it crashes giving me an error based on routes, and that's where I am stuck.
Problem code is found in the `_form.html.erb` file in views:
```
<%= form_tag '/show' do %>
<%= label_tag(:soundcloud_url, "Please enter a valid Soundcloud Artist URL:") %>
<%= text_field_tag(:soundcloud_url) %>
<%= submit_tag("Let's go!") %>
<% end %>
```
Routes.rb:
```
Rails.application.routes.draw do
resources :soundcloud_query
root 'soundcloud_query#index'
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
end
```
Error:
```
Routing Error
No route matches [POST] "/show"
```
rake routes output:
```
Prefix Verb URI Pattern Controller#Action
soundcloud_query_index GET /soundcloud_query(.:format) soundcloud_query#index
POST /soundcloud_query(.:format) soundcloud_query#create
new_soundcloud_query GET /soundcloud_query/new(.:format) soundcloud_query#new
edit_soundcloud_query GET /soundcloud_query/:id/edit(.:format) soundcloud_query#edit
soundcloud_query GET /soundcloud_query/:id(.:format) soundcloud_query#show
PATCH /soundcloud_query/:id(.:format) soundcloud_query#update
PUT /soundcloud_query/:id(.:format) soundcloud_query#update
DELETE /soundcloud_query/:id(.:format) soundcloud_query#destroy
root GET / soundcloud_query#index
```
Github link:
<https://github.com/gaelant/simple_soundcloud_app/commit/09c4c4df524bb721a0f472b4378cd8c1ff18177f>
Note: I understand this is a basic question but I have just gotten really confused with this. I know the way the code above is written is not correct, but I have tried so many different things and I just don't understand what is going on, or if this is even possible without a model.<issue_comment>username_1: I think in this case you should not use the url in the form\_tag but the controller action.
Let's say you've got a view called my\_form.html.erb and a submit\_form method in your soundcloud\_controller.rb
```
def submit_form
params[:soundcloud_url] your logic
end
```
I'd set up the routes like this:
```
get 'soundcloud_query' => 'soundcloud_query#my_form' // didn't want to use 'resources' but it doesn't matter
post 'soundcloud_query' => 'soundcloud_query#submit_form'
```
The form would then look like:
```
<%= form_for :this_doesnt_matter, action: :submit_form do |f| %>
<%= f.text_field :soundcloud_url %>
<%= f.submit %>
<% end %>
```
Upvotes: 1 <issue_comment>username_2: Your `/show` form action points to nowhere. `rails routes` shows you which url is valid and to which `controller#action` each of them lead.
The correct form action would be
```
<%= form_tag '/soundcloud_query' do %>
<%= label_tag(:soundcloud_url, "Please enter a valid Soundcloud Artist URL:") %>
<%= text_field_tag(:soundcloud_url) %>
<%= submit_tag("Let's go!") %>
<% end %>
```
A far more better way is to use the url\_helpers available through your defined ressource in `Routes.rb`
Doing so your form action would look like this
```
<%= form_tag soundcloud_query_index_path do %>
<%= label_tag(:soundcloud_url, "Please enter a valid Soundcloud Artist URL:") %>
<%= text_field_tag(:soundcloud_url) %>
<%= submit_tag("Let's go!") %>
<% end %>
```
The hardcoded and the url\_helper based solution will route your request to a controller class named `SoundcloudQuery` where the action `create` will be called. Inside this action you have to put all needed logic.
It's also possible do define that `/show` should point to a specifc controller and action. This would look like this.
```
post '/show', to: 'mycontroller#myaction', as: 'mypathnameforhelper'
```
A much more better explanation with many examples about routes and how to use them can be found in this quite good guide.
[Rails Routing from the Outside In](http://guides.rubyonrails.org/routing.html)
**Hint:** You should stay close to the ROR naming conventions. Controllers should have pluralized names. So you should define your routes like this:
```
Rails.application.routes.draw do
ressources :soundcloud_queries
root 'soundcloud_queries#index'
end
```
and then rename your controller class and file accordingly into `SoundcloudQueries` and `soundcloud_queries.rb`. But this is not mandatory.
Upvotes: 4 [selected_answer] |
2018/03/22 | 922 | 3,170 | <issue_start>username_0: Why i get division by zero in this SQL?
I tried so much, like cast, NULLIF and that things but nothing works.
```
$sql = "SELECT *, (cast(price as numeric(20, 4))*100)/cast(pricebefore as numeric(20, 4)) - 100 AS discount FROM products ORDER BY CAST(price AS Float) asc LIMIT $no_of_records_per_page OFFSET $offset";
```
If i kick out
```
(cast(price as numeric(20, 4))*100)/cast(pricebefore as numeric(20, 4)) - 100 AS discount
```
than its working.
But its also working if i kick out
```
ORDER BY CAST(price AS Float) asc
```
But i need them all two... i tried so much but cannot fix it...<issue_comment>username_1: I think in this case you should not use the url in the form\_tag but the controller action.
Let's say you've got a view called my\_form.html.erb and a submit\_form method in your soundcloud\_controller.rb
```
def submit_form
params[:soundcloud_url] your logic
end
```
I'd set up the routes like this:
```
get 'soundcloud_query' => 'soundcloud_query#my_form' // didn't want to use 'resources' but it doesn't matter
post 'soundcloud_query' => 'soundcloud_query#submit_form'
```
The form would then look like:
```
<%= form_for :this_doesnt_matter, action: :submit_form do |f| %>
<%= f.text_field :soundcloud_url %>
<%= f.submit %>
<% end %>
```
Upvotes: 1 <issue_comment>username_2: Your `/show` form action points to nowhere. `rails routes` shows you which url is valid and to which `controller#action` each of them lead.
The correct form action would be
```
<%= form_tag '/soundcloud_query' do %>
<%= label_tag(:soundcloud_url, "Please enter a valid Soundcloud Artist URL:") %>
<%= text_field_tag(:soundcloud_url) %>
<%= submit_tag("Let's go!") %>
<% end %>
```
A far more better way is to use the url\_helpers available through your defined ressource in `Routes.rb`
Doing so your form action would look like this
```
<%= form_tag soundcloud_query_index_path do %>
<%= label_tag(:soundcloud_url, "Please enter a valid Soundcloud Artist URL:") %>
<%= text_field_tag(:soundcloud_url) %>
<%= submit_tag("Let's go!") %>
<% end %>
```
The hardcoded and the url\_helper based solution will route your request to a controller class named `SoundcloudQuery` where the action `create` will be called. Inside this action you have to put all needed logic.
It's also possible do define that `/show` should point to a specifc controller and action. This would look like this.
```
post '/show', to: 'mycontroller#myaction', as: 'mypathnameforhelper'
```
A much more better explanation with many examples about routes and how to use them can be found in this quite good guide.
[Rails Routing from the Outside In](http://guides.rubyonrails.org/routing.html)
**Hint:** You should stay close to the ROR naming conventions. Controllers should have pluralized names. So you should define your routes like this:
```
Rails.application.routes.draw do
ressources :soundcloud_queries
root 'soundcloud_queries#index'
end
```
and then rename your controller class and file accordingly into `SoundcloudQueries` and `soundcloud_queries.rb`. But this is not mandatory.
Upvotes: 4 [selected_answer] |