date
stringlengths 10
10
| nb_tokens
int64 60
629k
| text_size
int64 234
1.02M
| content
stringlengths 234
1.02M
|
---|---|---|---|
2018/03/20 | 1,011 | 3,383 | <issue_start>username_0: I'm working with angular 4 and asp.net web api. in angular project i'm using a delete method to call web api delete method.when i'm using headers like below it works properly in locally.but after iis hosting it is not working.can i know what is the reason for that.
```
deleteItem(id) {
//debugger;
let headers = new Headers({
'Content-Type': 'application/json',
});
let options = new RequestOptions({ headers: headers });
return this.http
.delete(this.baseUrl +
'BureauStateWorkflowSettings/DeleteBureauStateWorkflowSettingsById/'+id,{
headers: headers })
.map((res: Response)=> this.flashMessage.show(res.text(),{ cssClass:
'alert-success' }))
.catch(this.handleError);
}
```<issue_comment>username_1: I'll assume it has a table as a parent, so you can use the pseudo-selectors `first-of-type`, or `first-child` if the table has no
```css
table tbody:first-of-type .compDetails-row td {
border: 1px solid red;
}
```
```html
| Row1 Column1 | Row1 Column2 | Row1 Column3 |
| Row2 Column1 | Row2 Column2 | Row2 Column3 |
| View Details |
| Row1 Column1 | Row1 Column2 | Row1 Column3 |
| View Details |
```
Upvotes: -1 <issue_comment>username_2: Unfortunately `:first-of-type` literally only checks the tag name (in this case, `tr`) and currently there's no `:first-of-class` pseudo-class. Ideally, you'd be able to modify the table markup at runtime if there's more than one `.compDetails-row`, if not - your best bet is some JavaScript.
You have access to the CSS/SASS, do you not have access to the JavaScript? This question is tagged for CSS only, but as I mentioned it's not really feasible without changing your markup.
Provided you're able to access the JavaScript files, or add a JavaScript tag to the footer of the website, here's a simple pure/vanilla JavaScript way to do it that adds a class `multiple` to the `.compDetails-row` if there's more than one in the same `tbody`.
```js
// Grab all the `` elements in the document as an array
var tbodies = document.querySelectorAll('tbody');
// Loop through the ``'s we grabbed
for( i = 0; i < tbodies.length; i++ ){
// Grab all the `.compDetails-row` elements that exist in the current
rows = tbodies[i].querySelectorAll('.compDetails-row');
// If there's more than one `.compDetails-row`
if( rows.length > 1 ){
// Loop through the `.compDetails-row` elements
rows.forEach(function(item){
// Add the `multiple` class to them
item.classList.add('multiple');
});
}
}
```
```css
.compDetails-row {
position: relative;
}
.compDetails-row.multiple:before {
content: '';
display: inline-block;
height: 100%;
border-left: 1px solid grey;
float: right;
position: absolute;
right: 20%;
}
```
```html
| Row1 Column1 | Row1 Column2 | Row1 Column3 |
| Row2 Column1 | Row2 Column2 | Row2 Column3 |
| View Details |
| Row1 Column1 | Row1 Column2 | Row1 Column3 |
| View Details |
```
Upvotes: 2 [selected_answer]<issue_comment>username_3: Using [the `:has()` pseudo-class](https://developer.mozilla.org/en-US/docs/Web/CSS/:has), [which is currently a working draft and behind a flag in Firefox](https://caniuse.com/css-has), this is achievable with CSS only.
```
tbody:not(:has(.compDetails-row ~ .compDetails-row)) .compDetails-row::before {
border: none;
}
```
[JSFiddle](https://jsfiddle.net/67mo5bdj/)
Upvotes: 0 |
2018/03/20 | 659 | 2,041 | <issue_start>username_0: I'm trying to produce aar file by run command gomobile bind as per below :
>
> gomobile bind -target=android golang.org/x/mobile/example/bind/hello
>
>
>
But always, getting error like below :
>
> gomobile: gobind -lang=go,java -outdir=/<KEY>T/gomobile-work-931510225 golang.org/x/mobile/example/bind/hello failed: exec: "gobind": executable file not found in $PATH
>
>
>
I already tried to specified path inside class `GobindExtension` in `GobindPlugin.groovy` as per below:
```
class GobindExtension {
// Package to bind. Separate multiple packages with spaces. (required)
def String pkg = "golang.org/x/mobile/example/bind/hello"
// GOPATH: necessary for gomobile tool. (required)
def String GOPATH = System.getenv("GOPATH")
// GO: path to go tool. (can omit if 'go' is in the paths visible by Android Studio)
def String GO = "/usr/local/opt/go/libexec/bin"
// GOMOBILE: path to gomobile binary. (can omit if 'gomobile' is under GOPATH)
def String GOMOBILE = "/Users/vierdamila1/Desktop/go-workspace/bin/gomobile"
}
```
And this is my GOPATH :
>
> export GOPATH="/Users/vierdamila1/Desktop/go-workspace"
>
>
>
But still not working. Did I missed something here? Really appreciate for any kind help.<issue_comment>username_1: I think I found the solution, I put here for someone who might need the answer.
Actually the error is showing up because I haven't install gobind. So before you do gomobile bind, don't forget to install gobind by run below command :
>
> go install golang.org/x/mobile/cmd/gobind
>
>
>
after that call the bind command :
>
> gomobile bind -target=android golang.org/x/mobile/example/bind/hello
>
>
>
The bind command will generate hello.aar file and you can put it inside your Android project libs folder.
Upvotes: 2 <issue_comment>username_2: 1. gobind package install
`$ go get golang.org/x/mobile/cmd/gobind`
2. init
`$ gomobile init`
3. build
`$ gomobile ...`
Upvotes: 0 |
2018/03/20 | 1,131 | 2,853 | <issue_start>username_0: Below is my table:
```
-----------------------------------
Sl. No. : File No. :
:-----------------------
: Subject1 :
-------------------------------------
1. : 1/2/34-gr :
:----------------------
:Nice table :
----------------------------------------
2. : 1/2/34-gr :
:----------------------
:Nice table :
----------------------------------------
```
and so on.......
Now I want color the background of every odd Sl. No., but since the 2nd column has two rows, I can't achieved it by using n-th even.
What other method can be used? (using CSS,HTML or JS)<issue_comment>username_1: ```css
tr tr:nth-child(odd) {
background-color: red;
}
```
```html
| | | | |
| --- | --- | --- | --- |
|
SL. No.
|
| |
| --- |
| Fil No. |
| Subject 1 |
|
|
1
|
| |
| --- |
| 1/2/34-gr |
| Nice table |
|
|
2
|
| |
| --- |
| 1/2/34-gr |
| Nice table |
|
```
If your markup is like this:
```
| | | | |
| --- | --- | --- | --- |
|
SL. No.
|
| |
| --- |
| Fil No. |
| Subject 1 |
|
|
1
|
| |
| --- |
| 1/2/34-gr |
| Nice table |
|
|
2
|
| |
| --- |
| 1/2/34-gr |
| Nice table |
|
```
then this CSS will work
```
tr tr:nth-child(odd) {
background-color: red;
}
```
Upvotes: 0 <issue_comment>username_2: You can use CSS [`:nth-child()`](https://developer.mozilla.org/en-US/docs/Web/CSS/%3Anth-child) pseudo-class selector.
```
/* for selecting first row in combined sl*/
table tbody tr:nth-child(4n + 1),
/* for selecting second row in combined sl*/
table tbody tr:nth-child(4n + 2)
{
background: red
}
```
```css
table tbody tr:nth-child(4n + 1),
table tbody tr:nth-child(4n + 2)
{
background: red
}
```
```html
| Sl No | 1 |
| 2 |
| 1 | 1 |
| 1 |
| 2 | 1 |
| 1 |
| 3 | 1 |
| 1 |
| 4 | 1 |
| 1 |
| 5 | 1 |
| 1 |
```
Upvotes: 3 <issue_comment>username_3: Why not you just take another Table inside column ?
```css
table tr:nth-child(even) td{
background-color: red
}
/*callback*/
table tr:nth-child(odd) td {
background-color: transparent;
}
```
```html
| | |
| --- | --- |
| 1 | 1 |
| 2 |
| |
| --- |
| 1 |
| 2 |
|
| 3 | 1 |
| 4 |
| |
| --- |
| 1 |
| 2 |
|
| 5 |
| |
| --- |
| 1 |
| 2 |
|
```
Upvotes: 0 <issue_comment>username_4: ```css
table tr:nth-child(even) td{
background-color: #ccc
}
table tr:nth-child(odd) td {
background-color: #ggg;
}
```
```html
| | | | |
| --- | --- | --- | --- |
| Sl. No. |
| |
| --- |
| File No. |
| Subject1 |
|
| 1. |
| |
| --- |
| 1/2/34-gr |
| Nice table |
|
| 2. |
| |
| --- |
| 1/2/34-gr |
| Nice table |
|
```
Upvotes: 0 |
2018/03/20 | 1,057 | 3,905 | <issue_start>username_0: This question may be asked several times but I have seen almost all of them but still unable to get an answer.
The flow is simple. A user has been issued `sims`. When sims are issued I am inserting the count of sims against that user in a table called `sim_balance`.
[](https://i.stack.imgur.com/1QwHJ.png)
Now There is a use-case for `SIM Return`. While returning the sim I am updating the above table. As in above image, one can see that total 8 sims have been issued to the same user but with different date time. The code for updating table is below
**Sim Return Create**
```
$model = new SimReturn();
$result = 0;
$returned_by = 0;
try{
if (isset($_REQUEST['selected_imsi'])) {
foreach ($_REQUEST['selected_imsi'] as $k => $v) {
$count = $_REQUEST['selected_imsi'];
$result = count($count);
.
.
.
$returned_by = $m->return_by;
.
.
.
if($m->save())
{
// code...
}
}
// below function call is updating the record
SimBalance::update_Record($returned_by,$result);
return $this->redirect(Url::toRoute('/simreturn'));
}catch (Exception $ex)
{
{
return $this->redirect(['index']);
}
}
```
**update\_Record**
```
public static function update_Record($user_id,$count){
$sims = SimBalance::find()->where(['user_id'=>$user_id])->one();
$sims->sims_count = $count;
$sims->balance_date_time = date('Y-m-d h:i:s');
return $sims->save();
}
```
Now, if the `SIMs` returned are from the same `id` then the record is updated perfectly.
But when I try to return the SIM from different `id`, let say I have returned `2` sims from id `1` and `2` sims from id `2` so as they both are for same `user_id` so both the `sims_count` should be updated. But it's just updating the record for id `1`.
**Update 1**
As per suggestion is given, now I am using `update()` by looking into this [link](http://www.yiiframework.com/doc-2.0/yii-db-activerecord.html#updateAll()-detail).
```
public static function update_Record($user_id,$count){
$sims = SimBalance::find()->where(['user_id'=>$user_id])->all();
foreach ($sims as $sim)
{
$model = SimBalance::find()->where(['id'=>$sim->id])->one();
$model->sims_count = $count;
$model->balance_date_time = date('Y-m-d h:i:s');
return $model->save();
}
}
```
But still, it's not working for me, else it places an additional count.
How can I update the record simultaneously for both the `ids`?
Any help would be highly appreciated.<issue_comment>username_1: The problem here is that you're returning $model->update(). This means that the foreach will exit in the first loop.
Use instead:
```
public static function update_Record($user_id,$count){
$sims = SimBalance::find()->where(['user_id'=>$user_id])->all();
foreach ($sims as $model)
{
$model->sims_count = $count;
$model->balance_date_time = date('Y-m-d h:i:s');
$model->update();
}
return $sims;
}
```
Upvotes: 2 <issue_comment>username_2: The problem is that you need to have a single record against the user in the `sim_balance` table as you won't be able to track which row to decrement against the given sims, for instance you are getting 2 sims with id `1` and `2` which belong to the same user now how will you determine that you have decrement-only one of those 2 records or both of them , keep the counter in one single record against the user and decrement it by determining the sims belong to that user
Upvotes: 2 [selected_answer] |
2018/03/20 | 729 | 3,034 | <issue_start>username_0: I added animation to push one controller to another controller.here is my code to push view.this animation is taking 2 second in iPhone 5S and taking 5 seconds in iPhone 5.i am not able to figure out what is exact issue.i want this animation for 1 second.here is my code.
```
DetailVC *detailObj = [[DetailVC alloc] initWithNibName:@"DetailVC" bundle:nil];
detailObj.dataGift = data;
detailObj.view.transform = CGAffineTransformScale(CGAffineTransformIdentity, 2.0, 2.0);
[UIView animateWithDuration:1.0
animations:^{
CATransition* transition = [CATransition animation];
transition.duration = 0.75;
transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn];
transition.type = kCATransitionFade;
[self.navigationController.view.layer addAnimation:transition forKey:nil];
[self.navigationController pushViewController:detailObj animated:false];
detailObj.view.transform = CGAffineTransformScale(CGAffineTransformIdentity, 1.0, 1.0);
} completion:^(BOOL finished) {
}];
});
```<issue_comment>username_1: You are performing animation inside animation block so your duration is increased
Replace your code with
```
DetailVC *detailObj = [[DetailVC alloc] initWithNibName:@"DetailVC" bundle:nil];
detailObj.dataGift = data;
detailObj.view.transform = CGAffineTransformScale(CGAffineTransformIdentity, 2.0, 2.0);
CATransition* transition = [CATransition animation];
transition.duration = 0.75;
transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn];
transition.type = kCATransitionFade;
[self.navigationController.view.layer addAnimation:transition forKey:nil];
[self.navigationController pushViewController:detailObj animated:false];
detailObj.view.transform = CGAffineTransformScale(CGAffineTransformIdentity, 1.0, 1.0);
```
And make sure you perform that in Main Queue
Hope it is helpful
Upvotes: 1 <issue_comment>username_2: issue was in home detail screen,heavy task was happening in viewdidload.i check line by line,commenting each line in view didload which activity is taking more time.and i put time consuming activity in main thread and my issue is resolved.
here is my code of animation
```
gameDetailObj.view.transform = CGAffineTransformScale(CGAffineTransformIdentity, 2.0, 2.0);
[UIView animateWithDuration:1.0
animations:^{
[self.navigationController pushViewControllerSafetly:gameDetailObj animated:NO];
gameDetailObj.view.transform = CGAffineTransformScale(CGAffineTransformIdentity, 1.0, 1.0);
} completion:^(BOOL finished) {
}];
```
Upvotes: 0 |
2018/03/20 | 1,020 | 3,117 | <issue_start>username_0: I have a dataset with `7k records [telecom dataset]`.
I want to split that dataset into 4 range based on one particular column `["tenure column"]`, which contains 1 to 72 number.
Need to split the whole data based on this tenure column like:-
>
> 1 to 18 Range [1-dataset], 19 to 36 Range [2-dataset], 37 to 54 Range [3-dataset], 55 to 72 Range[4-dataset]
>
>
>
My sample dataset with head(5)
```
out.head(5)
Out[51]:
customerID Date gender age region SeniorCitizen Partner \
0 9796-BPKIW 1/2/2008 1 57 1 1 0
1 4298-OYIFC 1/4/2008 1 50 2 0 1
2 9606-PBKBQ 1/6/2008 1 85 0 1 1
3 1704-NRWYE 1/9/2008 0 55 0 1 0
4 9758-MFWGD 1/6/2008 0 52 1 1 1
Dependents tenure PhoneService ... DeviceProtection TechSupport \
0 0 8 1 ... 0 0
1 0 15 1 ... 1 1
2 0 32 1 ... 0 0
3 0 9 1 ... 0 0
4 1 48 0 ... 0 0
StreamingTV StreamingMovies Contract PaperlessBilling PaymentMethod \
0 0 0 0 1 1
1 1 1 0 1 2
2 0 1 0 1 2
3 1 0 0 1 2
4 0 0 1 0 0
MonthlyCharges TotalCharges Churn
0 69.95 562.70 0
1 103.45 1539.80 0
2 85.00 2642.05 1
3 80.85 751.65 1
4 29.90 1388.75 0
```<issue_comment>username_1: Easy to understand code
```
i = 1
m = 0
out["tenure column"] = out["tenure column"].astype(int)
df = [None]*4
while i<72:
df[m] = out[(out["tenure column"]>=i) & (out["tenure column"]<=(i+17))]
m += 1
i += 18
```
Hope this solves your problem
Upvotes: 0 <issue_comment>username_2: Use pandas to easily do this thing.
```
import pandas as pd
df = pd.read_csv('your_dataset_file.csv', sep=',', header=0)
# Sort it according to tenure
df.sort_values(by=['tenure'], inplace=True)
# Create bin edges
step_size = int(df.tenure.max()/4)
bin_edges = list(range(0,df.tenure.max()+step_size, step_size))
lbls = ['a','b','c','d']
df['bin'] = pd.cut(df.tenure,bin_edges, labels= lbls)
# Create separate dataframes from it
df1 = df[df.bin == 'a']
df2 = df[df.bin == 'b']
df3 = df[df.bin == 'c']
df4 = df[df.bin == 'd']
```
Upvotes: 2 [selected_answer]<issue_comment>username_3: I will create list of datasets
```
dflist = [df[df["tenure column"].isin(range(i*18 + 1,(i+1)*18+1))] for i in range(4)]
```
Upvotes: 1 |
2018/03/20 | 680 | 1,946 | <issue_start>username_0: I have a text file, **`C:\text\sample.txt`**. How can I search through this text file , and numbering all instances of a given string (***using regular expression***), for example, word that starts with 'h' and ends with 'y' ?
**What the `sample.txt` looks like: (For this sample file, the regular expression I used is `\bh.+y\b` it'll match happy and history.)**
```
When a happy new history ...
Are you happy ...
How history ... very happy ...
...
```
**The numbering effect I hope to achieve:**
```
When a 1>happy new 2>history ...
Are you 3>happy ...
How 4>history ... very 5>happy ...
...
```
I'm new to python programming. How can I achieve this with python code?
Currently, I only come up with the following codes:
```
import fileinput
import re
for line in fileinput.input('sample.txt',inplace=1):
line = re.sub(r'\bh.+y\b',r'\bh.+y\b', line.rstrip())
```<issue_comment>username_1: Easy to understand code
```
i = 1
m = 0
out["tenure column"] = out["tenure column"].astype(int)
df = [None]*4
while i<72:
df[m] = out[(out["tenure column"]>=i) & (out["tenure column"]<=(i+17))]
m += 1
i += 18
```
Hope this solves your problem
Upvotes: 0 <issue_comment>username_2: Use pandas to easily do this thing.
```
import pandas as pd
df = pd.read_csv('your_dataset_file.csv', sep=',', header=0)
# Sort it according to tenure
df.sort_values(by=['tenure'], inplace=True)
# Create bin edges
step_size = int(df.tenure.max()/4)
bin_edges = list(range(0,df.tenure.max()+step_size, step_size))
lbls = ['a','b','c','d']
df['bin'] = pd.cut(df.tenure,bin_edges, labels= lbls)
# Create separate dataframes from it
df1 = df[df.bin == 'a']
df2 = df[df.bin == 'b']
df3 = df[df.bin == 'c']
df4 = df[df.bin == 'd']
```
Upvotes: 2 [selected_answer]<issue_comment>username_3: I will create list of datasets
```
dflist = [df[df["tenure column"].isin(range(i*18 + 1,(i+1)*18+1))] for i in range(4)]
```
Upvotes: 1 |
2018/03/20 | 910 | 3,491 | <issue_start>username_0: I have a web service running in springboot on port 8080. when I hit below url it works fine:
<http://localhost:8080/app> , i redirect the url to below:
<http://localhost:8080/myHome/home>
now when i refresh the page I am getting 404
below is the content of my index.html:
```
```
package.json:
```
"scripts": {
"ng": "ng",
"start": "ng serve --proxy-config proxy.conf.json",
"build": "ng build --dev --deploy-url=\"/app/\"",
"test": "ng test",
"lint": "ng lint",
"e2e": "protractor"
},
```
I had tried using LocationStrategy mentioned in
[Angular 2: 404 error occur when I refresh through the browser](https://stackoverflow.com/questions/35284988/angular-2-404-error-occur-when-i-refresh-through-the-browser) , but its not working for me.<issue_comment>username_1: It error occur cause by spring check resource /myHome/home in but there not found
resource location is /app so you can fix -
```
1) Use hashRouting in angular application
```
or
```
2) Redirect to '/' in springboot aplication when requesting came from another url /**
```
Upvotes: 1 <issue_comment>username_2: I had the same problem in spring boot 2. I have added resources resolver location as static directory and if not matched with any file then load index.html
```java
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/**/*")
.addResourceLocations("classpath:/static/")
.resourceChain(true)
.addResolver(new PathResourceResolver() {
@Override
protected Resource getResource(String resourcePath, Resource location) throws IOException {
Resource requestedResource = location.createRelative(resourcePath);
return requestedResource.exists() && requestedResource.isReadable() ? requestedResource : new ClassPathResource("/static/index.html");
}
});
}
```
Upvotes: 4 <issue_comment>username_3: Add { useHash:true } to your routerModule, it worked for me :
imports: [RouterModule.forRoot(routes, { useHash:true})]
Upvotes: 2 <issue_comment>username_4: This was the solution I found which works: This is in `Kotlin` though. But not hard to change between.
<https://github.com/emmapatterson/webflux-kotlin-angular/blob/master/README.md>
Hope this helps!
The main code is:
```java
import org.springframework.context.annotation.Configuration
import org.springframework.web.server.ServerWebExchange
import org.springframework.web.server.WebFilter
import org.springframework.web.server.WebFilterChain
import reactor.core.publisher.Mono
private const val INDEX_FILE_PATH = "/index.html"
@Configuration
internal class StaticContentConfiguration(): WebFilter {
override fun filter(exchange: ServerWebExchange, chain: WebFilterChain): Mono {
val path = exchange.request.uri.path
if (pathMatchesWebAppResource(path)) {
return redirectToWebApp(exchange, chain)
}
return chain.filter(exchange)
}
private fun redirectToWebApp(exchange: ServerWebExchange, chain: WebFilterChain) =
chain.filter(exchange.mutate()
.request(exchange.request.mutate().path(INDEX\_FILE\_PATH).build())
.build())
private fun pathMatchesWebAppResource(path: String) =
!path.startsWith("/api") && path.matches("[^\\\\.]\*".toRegex())
}
```
Upvotes: 1 |
2018/03/20 | 937 | 3,470 | <issue_start>username_0: My inner most nested for loop is not counting correctly. It turns into an infinite loop and I'm not seeing why. Does it have something to do with
```
studentScores.Add(intScore);
```
being inside the nested for loop?
```
class Program
{
static void Main(string[] args)
{
string studentCount = string.Empty;
string examCount = string.Empty;
Console.WriteLine("Please enter the number of students you will enter.");
studentCount = Console.ReadLine();
int totalStudents = Convert.ToInt32(studentCount);
Console.WriteLine(string.Empty);
Console.WriteLine("Please enter the number of exams to be entered for each student.");
examCount = Console.ReadLine();
int totalExams = Convert.ToInt32(examCount);
Console.WriteLine(string.Empty);
Dictionary> studentMap = new Dictionary>();
List studentScores = new List();
for (int students = 0; students < totalStudents; students++)
{
for (int scores = 0; scores < totalExams; scores++)
{
string score = string.Empty;
Console.WriteLine("Enter exam");
score = Console.ReadLine();
int intScore = Convert.ToInt32(score);
studentScores.Add(intScore);
}
}
}
}
```<issue_comment>username_1: ```
List studentScores = new List();
for (int students = 0; students < totalStudents; students++)
{
for (int scores = 0; scores < totalExams; scores++)
{
string score = string.Empty;
Console.WriteLine("Enter exam");
score = Console.ReadLine();
int intScore = Convert.ToInt32(score);
studentScores.Add(intScore);
}
}
```
should likely be:
```
for (int students = 0; students < totalStudents; students++)
{
List studentScores = new List();
for (int scores = 0; scores < totalExams; scores++)
{
string score = string.Empty;
Console.WriteLine("Enter exam");
score = Console.ReadLine();
int intScore = Convert.ToInt32(score);
studentScores.Add(intScore);
}
studentMap[students] = studentScores;
}
```
This will mean each entry in the `Dictionary` will have a subset of the `studentScores` data. This is different to your existing code, which lumps all of the `studentScores` data in a single `List`.
Upvotes: 1 <issue_comment>username_2: As per the clarifications that you provided in the comment, you should try something like this:
```
Dictionary> studentMap = new Dictionary>();
for (int student = 0; student < totalStudents; student++)
{
studentMap.Add(student, new List());
for (int scores = 0; scores < totalExams; scores++)
{
string score = string.Empty;
Console.WriteLine("Enter exam");
score = Console.ReadLine();
int intScore = Convert.ToInt32(score);
studentMap[student].Add(intScore);
}
}
```
Upvotes: 0 <issue_comment>username_3: You can use following code snippet. See [here for full working code](https://ideone.com/ZrRf2M):
```
Dictionary> studentMap = new Dictionary>();
for (int students = 0; students < totalStudents; students++)
{
//Create List here for each student
List studentScores = new List();
for (int scores = 0; scores < totalExams; scores++)
{
//Read and save scores of student in each subject
string score = string.Empty;
Console.WriteLine("Enter exam");
score = Console.ReadLine();
int intScore = Convert.ToInt32(score);
studentScores.Add(intScore);
}
//Add this in dictonary. Key as the `index` and
//value as the scores saved in `studentScores`
studentMap.Add(students, studentScores);
}
```
Upvotes: 2 [selected_answer] |
2018/03/20 | 790 | 2,593 | <issue_start>username_0: **Note : I retrieved $dateString from my excel**
```
$dateString = "29/07/2008 7:51:00 PM";
$timestamp = date('Y-m-d h:i a', strtotime(str_replace('/','-', $dateString)));
echo $timestamp;
```
>
> Output I get
> **2029-07-08 12:00 am**
>
>
>
But I need output something like this. Please assist me
**2008-07-29 7:51:00**<issue_comment>username_1: ```
List studentScores = new List();
for (int students = 0; students < totalStudents; students++)
{
for (int scores = 0; scores < totalExams; scores++)
{
string score = string.Empty;
Console.WriteLine("Enter exam");
score = Console.ReadLine();
int intScore = Convert.ToInt32(score);
studentScores.Add(intScore);
}
}
```
should likely be:
```
for (int students = 0; students < totalStudents; students++)
{
List studentScores = new List();
for (int scores = 0; scores < totalExams; scores++)
{
string score = string.Empty;
Console.WriteLine("Enter exam");
score = Console.ReadLine();
int intScore = Convert.ToInt32(score);
studentScores.Add(intScore);
}
studentMap[students] = studentScores;
}
```
This will mean each entry in the `Dictionary` will have a subset of the `studentScores` data. This is different to your existing code, which lumps all of the `studentScores` data in a single `List`.
Upvotes: 1 <issue_comment>username_2: As per the clarifications that you provided in the comment, you should try something like this:
```
Dictionary> studentMap = new Dictionary>();
for (int student = 0; student < totalStudents; student++)
{
studentMap.Add(student, new List());
for (int scores = 0; scores < totalExams; scores++)
{
string score = string.Empty;
Console.WriteLine("Enter exam");
score = Console.ReadLine();
int intScore = Convert.ToInt32(score);
studentMap[student].Add(intScore);
}
}
```
Upvotes: 0 <issue_comment>username_3: You can use following code snippet. See [here for full working code](https://ideone.com/ZrRf2M):
```
Dictionary> studentMap = new Dictionary>();
for (int students = 0; students < totalStudents; students++)
{
//Create List here for each student
List studentScores = new List();
for (int scores = 0; scores < totalExams; scores++)
{
//Read and save scores of student in each subject
string score = string.Empty;
Console.WriteLine("Enter exam");
score = Console.ReadLine();
int intScore = Convert.ToInt32(score);
studentScores.Add(intScore);
}
//Add this in dictonary. Key as the `index` and
//value as the scores saved in `studentScores`
studentMap.Add(students, studentScores);
}
```
Upvotes: 2 [selected_answer] |
2018/03/20 | 857 | 2,903 | <issue_start>username_0: How to set up a proxy with puppeteer? I tried the following:
```
(async () => {
const browser = await puppeteer.launch({
headless: false,
args: [
'--proxy-server=http://username:[email protected]:22225'
]
});
const page = await browser.newPage();
await page.goto('https://www.whatismyip.com/');
await page.screenshot({ path: 'example.png' });
//await browser.close();
})();
```
But it does not work and I get the message:
```
Error: net::ERR_NO_SUPPORTED_PROXIES at https://www.whatismyip.com/
```
on the console. How to use the proxy correctly?
I also tried the following:
```
const browser = await puppeteer.launch({
headless: false,
args: [
'--proxy-server=zproxy.luminati.io:22225'
]
});
const page = await browser.newPage();
page.authenticate({
username: 'username',
password: '<PASSWORD>'
})
await page.goto('https://www.whatismyip.com/');
```
but the same result.<issue_comment>username_1: ```
(async () => {
// install proxy-chain "npm i proxy-chain --save"
const proxyChain = require('proxy-chain');
// change username & password
const oldProxyUrl = 'http://lum-customer-USERNAMEOFLUMINATI-zone-static-country-us:PASSW<PASSWORD>[email protected]:22225';
const newProxyUrl = await proxyChain.anonymizeProxy(oldProxyUrl);
const browser = await puppeteer.launch({
headless: false,
args: [
'--no-sandbox',
'--disable-setuid-sandbox',
`--proxy-server=${newProxyUrl}`
]
});
const page = await browser.newPage();
await page.goto('https://www.whatismyip.com/');
await page.screenshot({ path: 'example.png' });
await browser.close();
})();
```
Upvotes: 4 <issue_comment>username_2: After removing the double quotes from the `args` worked fine for me.
<https://github.com/puppeteer/puppeteer/issues/1074#issuecomment-359427293>
Upvotes: 1 <issue_comment>username_3: Chrome can not handle username and password in proxy URLs. The second option which uses `page.authenticate` should work
```
(async () => {
const browser = await puppeteer.launch({
headless: false,
args: [
'--proxy-server=zproxy.luminati.io:22225'
]
});
const page = await browser.newPage();
// do not forget to put "await" before async functions
await page.authenticate({
username: 'username',
password: '<PASSWORD>'
})
await page.goto('https://www.whatismyip.com/');
...
})();
```
Upvotes: 4 <issue_comment>username_4: Take care of quoting issues:
I had in Selenium (`chromediver`, same arguments):
```
"--proxy-server='http://1.1.1.1:8888'"
```
**This is wrong! This gives me the reported error.**
You need:
```
"--proxy-server=http://1.1.1.1:8888"
```
Upvotes: 0 |
2018/03/20 | 418 | 1,416 | <issue_start>username_0: I'm a high school student studying Prolog and am getting an error on a goal.
I have the following facts:
```
character(jim).
character(jenny).
character_type(jim, prince).
charcter_type(jenny, princess).
skill(fly).
skill(invisibility).
has_skill(jim, fly).
has_skill(jenny_invisibility).
pet(jim, horse).
pet(jenny, bird).
animal(horse).
animal(bird).
```
I would like to get all the pets of characters who are princesses. I am trying:
```
pet(character_type(_, princess), X).
```
Without successful results. Any help is appreciated.<issue_comment>username_1: you can not use prolog predicate like C-Function
```
character_type(_, princess)
```
returns nothing.
I think this is what you intend to do.
```
character_type(C, princess),pet(C, X).
```
Upvotes: 1 <issue_comment>username_2: In Prolog, arguments to predicates and functions can only be terms. A term is combinations of variables, constants, and functions. Terms cannot contain predicates.The Predicates are names for functions that are true or false.The functions are something that return non-Boolean values.
The argument passed in pet predicate i.e character\_type is a predicate, thus cannot be written as pet(character\_type(\_, princess), X).
Instead writing the query as
**character\_type(X,princess), pet(X,Y).** will give you the desired result.
X= jenny
Y = bird.
Upvotes: 3 [selected_answer] |
2018/03/20 | 792 | 3,176 | <issue_start>username_0: Im fairly new to JavaScript and I'm having difficulty in understanding this syntax.
```
document.querySelector('dice').style.display='none';
```
My understanding is we are calling the querySelector method on the document object - this returns a selection. Now we call the style method on this selection - this returns a style object. Next we change its display property to 'none' to hide it.
If this is correct, shouldn't it be `.style().display = 'none'?`
If indeed style is a method, shouldn't brackets be required when invoking it?<issue_comment>username_1: `style` is used in css. You shouldn't use`style()`. When you are typing`element.style.dispaly`, you are allowing the browser to know that you want to change the css property of the element.
Upvotes: 0 <issue_comment>username_2: <https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/style>
>
> While getting, it returns a CSSStyleDeclaration object that contains a list of all styles properties for that element...
>
>
>
It just happens to be accessed as a plain property that references an object, rather than a function that returns an object.
Also note
>
> `document.querySelector('dice')`
>
>
>
probably isn't valid unless `dice` is a special HTML tag. You might be looking for `.querySelector('.dice')` (class selection) or `.querySelector('$dice')` (id selection) instead.
Upvotes: 0 <issue_comment>username_3: `Style` is the `property` of the DOM Object and not the `method`.
So it is as good as using following syntax:
```
const person = {
name: {
first: 'ABC'
}
}
person.name.first = 'CDE';
```
Which is similar to
`document.querySelector('dice').style.display='none';`
Upvotes: 0 <issue_comment>username_4: The querySelector() method returns the first element that matches a specified CSS selector(s) in the document.
**Note:** The querySelector() method only returns the first element that matches the specified selectors. To return all the matches, use the querySelectorAll() method instead.
If the selector matches an ID in document that is used several times (Note that an "id" should be unique within a page and should not be used more than once), it returns the first matching element.
Click [here](https://www.w3schools.com/jsref/met_document_queryselector.asp) to know more about query selector.
The 'style' property is used to apply some inline style to a dom element through the script. According to the example which you have mentioned,**document.querySelector('dice').style.display='none';** that simply hide a first dom element 'dice'.
Upvotes: 1 <issue_comment>username_5: `document.querySelector()` is a method. Which means it is a function which is stored as an object property. When you call the method `document.querySelector('div')` it returns the first div element in your document. The returned value will be an object which contains attributes from the object.
[Link to a jsBin that displays document.querySelector output](https://jsbin.com/lapipog/edit?html,js,console).
So `document.querySelector('div').style` will display its styles. And you can take a particular value from it and change its style.
Upvotes: 0 |
2018/03/20 | 1,069 | 2,912 | <issue_start>username_0: I have a list with elements like
```
["xyz", "abc", "123,123,123", 456.78 , "pqr"]
```
I want to join only the elements that are strings into a single string, and convert numeric strings into numbers, like
```
[ "xyzabcpqr", 123123123, 456.78]
```
How can this be done in a pythonic way?<issue_comment>username_1: you can use [`isinstance()`](https://docs.python.org/2/library/functions.html#isinstance):
it goes like this:
```
import numbers
mylist = ["xyz", "abc", "123,123,123", 456.78 , "pqr"]
for i in mylist:
if(isinstance(i , numbers.Number)):
pass
else:
print (i)
```
**IMPORTANT**: i copied your list items and checked that out , result was like this :
```
'xyz' , 'abc' , '123,123,123' , 'pqr'
```
you can see that it prints 123,123,123 as it is , that's because you passed that element in array as a string (**"123,123,123"**) if you pass that as a int number like **123123123** the for loop will pass that too.
**Edited**
for that case you can tweak that code a little bit to this:
```
import numbers
mylist = ["xyz", "abc", "123,123,123", 456.78 , "pqr"]
for i in mylist:
# check if there is a number as element
if(isinstance(i , numbers.Number)):
pass
# check if there is a string element in array that includes any digits
elif(any(element.isdigit() for element in i)):
pass
# after filters that we applied , then print the element
else:
print (i)
```
the result will be `xyz , abc , pqr`
i think you asked for join the elements in array , and for that you can use `join(yourList)` instead of `print(i)` or what ever functionality you want...
hope it help you to figure that out.
Upvotes: 0 <issue_comment>username_2: Maybe this is not very beautiful but it works
```
import numbers
L_in = ["xyz", "abc", "123,123,123", 456.78 , "pqr"]
L_out = []
char_str = ""
for i in L_in:
if(isinstance(i , numbers.Number)):
L_out.append(i)
elif any(c.isdigit() for c in i):
L_out.append(int(''.join([c for c in i if c.isdigit()])))
else:
char_str += i
L_out = [char_str]+L_out
```
Result:
```
['xyzabcpqr', 123123123, 456.78]
```
Upvotes: 2 [selected_answer]<issue_comment>username_3: You can try regex with one loop:
```
data=["xyz", "abc", "123,123,123", 456.78 , "pqr",11111111]
import re
string_pattern=r'[a-zA-Z]+'
num_pattern1=r'[0-9.,]+'
s_=[]
i_=[]
for i in data:
a=re.search(string_pattern,str(i))
b=re.search(num_pattern1,str(i))
if a!=None:
s_.append(a.group())
elif b!=None:
if '.' in b.group():
i_.append(float(b.group()))
elif ',' in b.group():
i_.append(int(b.group().replace(',','')))
else:
i_.append(int(b.group()))
print(["".join(s_)]+i_)
```
output:
```
['xyz<PASSWORD>', 123123123, 456.78, 11111111]
```
Upvotes: 0 |
2018/03/20 | 296 | 921 | <issue_start>username_0: It seems Internet-Draft provides a link to download a XML file (e.g. <https://tools.ietf.org/id/draft-ietf-oauth-v2-31.xml>), but I couldn't find a way to download a RFC (e.g. <https://www.rfc-editor.org/rfc/rfc6749>) in XML. Is there any way to do it?
I want to re-format some RFCs to make it easy to read.<issue_comment>username_1: Even though it's not officially documented, it seems you can download some RFCs from `https://www.rfc-editor.org/authors/rfcXXXX.xml`. E.g. <https://www.rfc-editor.org/authors/rfc7230.xml>. Older RFCs can be found at <https://xml2rfc.tools.ietf.org/public/rfc/xml/>
Upvotes: 1 <issue_comment>username_2: You can get RFCs in a "preprocessed" XML format from <https://www.rfc-editor.org/retrieve/bulk/>, while the actual source of the various RFCs is at <https://www.rfc-editor.org/in-notes/prerelease/>. This only applies to RFC 8650 and newer though.
Upvotes: 2 |
2018/03/20 | 1,553 | 4,621 | <issue_start>username_0: I have an input that will open when clicked on and close when clicked anywhere on the page except the div itself. I use a function that changes the inputs background color when clicking on the input, but I can't figure out how to "undo" the color change when the user closes the input div by clicking elsewhere on the page.
```js
function makeRed() {
var p = document.querySelector('input');
p.style.background = 'red';
}
```
```css
* {
box-sizing: border-box;
}
body {
background-color: black;
}
input[type=text] {
cursor: pointer;
position: relative;
padding: 15px 25px 15px 20px;
width: 20px;
color: #525252;
text-transform: uppercase;
font-size: 16px;
font-weight: 100;
letter-spacing: 2px;
border: none;
border-radius: 5px;
background: linear-gradient(to right, #FFFFFF 0%, #464747 #F9F9F9 100%);
transition: width 0.4s ease;
outline: none;
}
input[type=text]:focus {
width: 300px;
}
i {
position: relative;
left: -37px;
color: #000;
cursor: pointer;
pointer-events: none;
}
```
```html
```<issue_comment>username_1: to reset a css property, set it to an empty string:
```js
var p = document.querySelector('input');
function makeRed(el) {
el.style.background = 'red';
}
function resetBackground(el){
el.style.background = '';
}
p.addEventListener('click', function(){
makeRed(this);
}, false);
p.addEventListener('blur', function(){
resetBackground(this);
}, false);
```
call resetBackground inside a blur event.
[addEventListener](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener)
[blur event](https://developer.mozilla.org/en-US/docs/Web/Events/blur)
Upvotes: -1 <issue_comment>username_2: You can also use `onfocus` and `onfocusout`
```js
var p = document.querySelector('input');
function makeRed() {
p.style.background = 'red';
}
function removeRed(){
p.style.background = 'initial';
}
```
```html
```
Upvotes: -1 <issue_comment>username_3: You want to end the handler `onfocusout` on the input to call a function when the input is unfocused (when ANYTHING else is clicked or unfocused on mobile)
```
onfocusout="revertColor()"
```
Upvotes: 0 <issue_comment>username_4: Try yo use **[focus](https://developer.mozilla.org/en-US/docs/Web/Events/focus)** and **[blur](https://developer.mozilla.org/en-US/docs/Web/Events/blur)** event listener
```js
var x = document.querySelector('input');
x.addEventListener("focus", function() {
this.style.background = 'red';
})
x.addEventListener("blur", function() {
this.style.background = 'white';
})
```
```css
* {
box-sizing: border-box;
}
body {
background-color: black;
}
input[type=text] {
cursor: pointer;
position: relative;
padding: 15px 25px 15px 20px;
width: 20px;
color: #525252;
text-transform: uppercase;
font-size: 16px;
font-weight: 100;
letter-spacing: 2px;
border: none;
border-radius: 5px;
background: linear-gradient(to right, #FFFFFF 0%, #464747 #F9F9F9 100%);
transition: width 0.4s ease;
outline: none;
}
input[type=text]:focus {
width: 300px;
}
i {
position: relative;
left: -37px;
color: #000;
cursor: pointer;
pointer-events: none;
}
```
```html
```
Upvotes: 3 [selected_answer]<issue_comment>username_5: add a blur function to input tag
```
function makeWhite() {
var p = document.querySelector('input');
p.style.background = 'white';
}
function makeRed() {
var p = document.querySelector('input');
p.style.background = 'red';
}
```
Upvotes: 0 <issue_comment>username_6: Instead of a JavaScript function, you can achieve the expected output using CSS.
Let us know if anything else you are doing in the function which is affecting the style.
Remove JS function and update your CSS to
```
input[type=text]:focus {
width: 300px;
background-color:red;
}
```
```css
* {
box-sizing: border-box;
}
body {
background-color: black;
}
input[type=text] {
cursor: pointer;
position: relative;
padding: 15px 25px 15px 20px;
width: 20px;
color: #525252;
text-transform: uppercase;
font-size: 16px;
font-weight: 100;
letter-spacing: 2px;
border: none;
border-radius: 5px;
background: linear-gradient(to right, #FFFFFF 0%, #464747 #F9F9F9 100%);
transition: width 0.4s ease;
outline: none;
}
input[type=text]:focus {
width: 300px;
background-color:red;
}
i {
position: relative;
left: -37px;
color: #000;
cursor: pointer;
pointer-events: none;
}
```
```html
```
Upvotes: 0 |
2018/03/20 | 862 | 2,985 | <issue_start>username_0: I have a Django application on gitlab and I am trying to add CI/CD using gitlab-ci. I started a server on EC2 and installed gitlab-runner on it.
I added `.gitlab-ci.yml` file to my project and pushed the latest changes. I can see the pipeline running and dependencies being installed. But When the script tries to run tests, I get an error like this:
>
> django.db.utils.OperationalError: could not connect to server: Connection refused
>
>
> Is the server running on host "localhost" (::1) and accepting
> TCP/IP connections on port 5432?
>
>
> could not connect to server: Connection refused
>
>
> Is the server running on host "localhost" (127.0.0.1) and accepting
> TCP/IP connections on port 5432?
>
>
>
Below is my `.gitlab-ci.yaml` script:
```
image: python:3-jessie
services:
- postgres:latest
before_script:
- python -V
- apt-get -y update
- apt-get install -y python-dev python-pip
- pip install --upgrade pip
stages:
- build
build:
type: build
variables:
DATABASE_URL: postgres://postgres:@postgres:5432/opensys_erp
script:
- pip install -r requirements.txt
- python manage.py test
only:
- branches
```
Why is my application unable to connect to postgres server?<issue_comment>username_1: If I interpret the [docs](https://www.postgresql.org/docs/current/static/libpq-connect.html#LIBPQ-CONNSTRING) correct, you should remove the `:` after the `postgres` user:
`postgresql://[user[:password]@][netloc][:port][/dbname][?param1=value1&...]`
So your string would be:
`postgres://postgres@postgres:5432/opensys_erp`
Upvotes: 0 <issue_comment>username_2: As your container try to connect postgres on their own localhost that's why you getting connection refused. `127.0.0.1` this localhost is the localhost of `Django application` container. To connect with postgress using localhost you need to **link** your docker container.
>
> Docker also has a linking system that allows you to link multiple containers together and send connection information from one to another. When containers are linked, information about a source container can be sent to a recipient container.
>
>
>
**How services are linked to the job**
>
> To summarize, if you add mysql as service to your application, the image will then be used to create a container that is **linked** to the job container.
>
>
> The service container for MySQL will be accessible under the hostname
> mysql. So, in order to access your database service you have to
> connect to the host named mysql instead of a socket or localhost.
>
>
>
A day before I post a detailed answer for the same sort of question you check this as well.
<https://stackoverflow.com/a/49342027/3288890>
You can check some links
<https://docs.docker.com/network/links/>
<https://docs.gitlab.com/ce/ci/docker/using_docker_images.html>
<https://docs.gitlab.com/ce/ci/docker/using_docker_images.html#accessing-the-services>
Upvotes: 2 [selected_answer] |
2018/03/20 | 601 | 2,003 | <issue_start>username_0: Can someone explain to me why the output would be:
```
[[8, 0]]
[[8, 0], [8, 0], [8, 0]]
```
**This is the function that is confusing me**
```
x = [[0,0]]
y = x * 3
i = 10
for inner in y:
inner[0] = i
i -= 1
print(x)
print(y)
```<issue_comment>username_1: If I interpret the [docs](https://www.postgresql.org/docs/current/static/libpq-connect.html#LIBPQ-CONNSTRING) correct, you should remove the `:` after the `postgres` user:
`postgresql://[user[:password]@][netloc][:port][/dbname][?param1=value1&...]`
So your string would be:
`postgres://postgres@postgres:5432/opensys_erp`
Upvotes: 0 <issue_comment>username_2: As your container try to connect postgres on their own localhost that's why you getting connection refused. `127.0.0.1` this localhost is the localhost of `Django application` container. To connect with postgress using localhost you need to **link** your docker container.
>
> Docker also has a linking system that allows you to link multiple containers together and send connection information from one to another. When containers are linked, information about a source container can be sent to a recipient container.
>
>
>
**How services are linked to the job**
>
> To summarize, if you add mysql as service to your application, the image will then be used to create a container that is **linked** to the job container.
>
>
> The service container for MySQL will be accessible under the hostname
> mysql. So, in order to access your database service you have to
> connect to the host named mysql instead of a socket or localhost.
>
>
>
A day before I post a detailed answer for the same sort of question you check this as well.
<https://stackoverflow.com/a/49342027/3288890>
You can check some links
<https://docs.docker.com/network/links/>
<https://docs.gitlab.com/ce/ci/docker/using_docker_images.html>
<https://docs.gitlab.com/ce/ci/docker/using_docker_images.html#accessing-the-services>
Upvotes: 2 [selected_answer] |
2018/03/20 | 814 | 2,633 | <issue_start>username_0: I have defined a function which calculates the mean of a column `Test 1` in my dataframe between two time limits.
The dataframe is -:-
```
df = pd.DataFrame({'Time':[0.0, 0.25, 0.5, 0.68, 0.94, 1.25, 1.65, 1.88,
2.05, 2.98, 3.45, 3.99, 4.06],'Test 1':[5, 9, 4, 6, 4, 1, 6, 8, 2, 9, 3, 9, 4]})
```
And the function is -:-
```
def custom_mean(x,y):
return df.loc[df['Time'].between(x,y), 'Test 1'].mean()
```
The function `custom_mean(x,y)` calculates the mean between the two time limits `x` and `y`. How can I define a function or write a piece of code which does exactly the same thing (calculates mean between two limits) when the parameters are passed and calculates the mean of whole column starting from the very first value till the last if no parameters are passed (e.g. mean of the values corresponding to the time limit from 0.00 to 4.06 in my dataframe)?<issue_comment>username_1: If I interpret the [docs](https://www.postgresql.org/docs/current/static/libpq-connect.html#LIBPQ-CONNSTRING) correct, you should remove the `:` after the `postgres` user:
`postgresql://[user[:password]@][netloc][:port][/dbname][?param1=value1&...]`
So your string would be:
`postgres://postgres@postgres:5432/opensys_erp`
Upvotes: 0 <issue_comment>username_2: As your container try to connect postgres on their own localhost that's why you getting connection refused. `127.0.0.1` this localhost is the localhost of `Django application` container. To connect with postgress using localhost you need to **link** your docker container.
>
> Docker also has a linking system that allows you to link multiple containers together and send connection information from one to another. When containers are linked, information about a source container can be sent to a recipient container.
>
>
>
**How services are linked to the job**
>
> To summarize, if you add mysql as service to your application, the image will then be used to create a container that is **linked** to the job container.
>
>
> The service container for MySQL will be accessible under the hostname
> mysql. So, in order to access your database service you have to
> connect to the host named mysql instead of a socket or localhost.
>
>
>
A day before I post a detailed answer for the same sort of question you check this as well.
<https://stackoverflow.com/a/49342027/3288890>
You can check some links
<https://docs.docker.com/network/links/>
<https://docs.gitlab.com/ce/ci/docker/using_docker_images.html>
<https://docs.gitlab.com/ce/ci/docker/using_docker_images.html#accessing-the-services>
Upvotes: 2 [selected_answer] |
2018/03/20 | 769 | 2,372 | <issue_start>username_0: I have the following code for a recursive function to convert binary to int:
```
public static int binaryToInt( String b ) {
if(b.length() < 2) {
return 0;
}
return b.charAt(0) * (int) Math.pow(2, b.length()) + binaryToInt(b.substring(1));
}
```
I am not getting the correct values for example: "101" I get 584.
I thought my logic is correct but can someone please point out where i am going wrong?<issue_comment>username_1: There are quite a few problems
1. `b.charAt(0) * ...` - You are multiplying the ASCII value of the character and an int. Change it to `b.charAt(0) - '0'` to get the actual integer.
2. `Math.pow(2, b.length())` - It has to `Math.pow(2, b.length() - 1)`. Working for a few samples with a pen and paper will explain this.
3. The base condition is wrong. You need to return when there are no more characters left. So, it must be `if(b.length() == 0)`
Upvotes: 3 [selected_answer]<issue_comment>username_2: **First:**
I changed your base criteria to allow all of the bits in calculation:
```
if(b.length() <= 0) {
return 0;
}
```
**Second:** `b.charAt(0)` return the ASCII value not the integer, so make it integer by using: `(b.charAt(0) - '0')`
**Third:** The power of each position will be `length-1`, so changed as following:
```
Math.pow(2, b.length()-1)
```
>
> **Final solution:**
>
>
>
Please check the final solution:
```
public static int binaryToInt( String b ) {
if(b.length() <= 0) {
return 0;
}
return (b.charAt(0) - '0') * (int) Math.pow(2, b.length()-1) + binaryToInt(b.substring(1));
}
```
Upvotes: 1 <issue_comment>username_3: The code you have has the following errors:
1. b.charAt(0)- returns the ASCII value of the character that means result is
calculated as ASCCI value (i.e if b.charAt(0) returns 1 then its corresponding
ASCII value is 49).
2. if (b.length() < 2)- You are not checking the value of string what if the value is 1 still it returns 0.
3. the Math.pow(2, b.length()) to be modified as Math.pow(2, b.length()-1)
Here is the code:
```
public static int binaryToInt( String b ) {
if(b.length() < 2) {
if(b.charAt(0)=='1')
return 1;
return 0;
}
return Character.getNumericValue(b.charAt(0)) * (int) Math.pow(2, b.length()-1) + binaryToInt(b.substring(1));
}
```
Upvotes: 0 |
2018/03/20 | 1,683 | 6,019 | <issue_start>username_0: I am loading a website with WkWebview and the website contains some javascript actions. For iPhone, it is working fine because the confirmPanel would not allow user to touch outside the panel until user choose the available actions in the panel. However, for iPad it does not do the same things as iPhone. Whenever
i try to touch outside of the alert panel, it will crash. Please see the crash logs below the code. I tried using UITapGestureRecognizer, but it is still not working.
```
func webView(_ webView: WKWebView, runJavaScriptConfirmPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (Bool) -> Void) {
let alertController = UIAlertController(title: nil, message: message, preferredStyle: .actionSheet)
alertController.addAction(UIAlertAction(title: "OK", style: .default, handler: { (action) in
completionHandler(true)
}))
alertController.addAction(UIAlertAction(title: "Cancel", style: .default, handler: { (action) in
completionHandler(false)
}))
if UIDevice.current.userInterfaceIdiom != .phone {
if let popoverController = alertController.popoverPresentationController {
popoverController.sourceView = self.view
popoverController.sourceRect = CGRect(x: self.view.bounds.midX, y: self.view.bounds.midY, width: 0, height: 0)
popoverController.permittedArrowDirections = []
}
}
self.present(alertController, animated: true, completion: nil)
}
```
Error message,
>
> Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Completion handler passed to -[webViewios.MainVC webView:runJavaScriptConfirmPanelWithMessage:initiatedByFrame:completionHandler:] was not called'
> \*\*\* First throw call stack:
> (0x21a2f91b 0x211cae17 0x21a2f861 0x287d7293 0x288111b9 0x2886db69 0x21603ac3 0xccd4c 0x8d9e1f 0xcc6d8 0x8d9e1f 0xd1718 0x21603ac3 0x26400cd1 0x263ff26b 0x211e53a9 0x2193ef89 0x219f006f 0x2193f229 0x2193f015 0x22f2fac9 0x26013189 0xd8824 0x215e7873)
> libc++abi.dylib: terminating with uncaught exception of type NSException
>
>
><issue_comment>username_1: Present your `UIAlertController` if `UIViewController` with `WKWebView` is visible. If not visible, execute `completionHandler` directly and return.
```
func webView(_ webView: WKWebView, runJavaScriptConfirmPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (Bool) -> Void) {
let alertController = UIAlertController(title: nil, message: message, preferredStyle: .actionSheet)
alertController.addAction(UIAlertAction(title: "OK", style: .default, handler: { (action) in
completionHandler(true)
}))
alertController.addAction(UIAlertAction(title: "Cancel", style: .default, handler: { (action) in
completionHandler(false)
}))
if UIDevice.current.userInterfaceIdiom != .phone {
if let popoverController = alertController.popoverPresentationController {
popoverController.sourceView = self.view
popoverController.sourceRect = CGRect(x: self.view.bounds.midX, y: self.view.bounds.midY, width: 0, height: 0)
popoverController.permittedArrowDirections = []
}
}
if self.viewIfLoaded?.window != nil {
self.present(alertController, animated: true, completion: nil)
}
else {
completionHandler()
}
}
```
Upvotes: 0 <issue_comment>username_2: In the iPad, when you present the action sheet cancel action is automatically mapped to the tap outside the control panel of the action sheet. You need to make a change in the way you are showing `Cancel` button of your `UIAlertController`.
**Updated Code without Cancel button on iPad**
```
func webView(_ webView: WKWebView, runJavaScriptConfirmPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (Bool) -> Void) {
let alertController = UIAlertController(title: nil, message: message, preferredStyle: .actionSheet)
alertController.addAction(UIAlertAction(title: "OK", style: .default, handler: { (action) in
completionHandler(true)
}))
alertController.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: { (action) in
completionHandler(false)
}))
if UIDevice.current.userInterfaceIdiom != .phone {
if let popoverController = alertController.popoverPresentationController {
popoverController.sourceView = self.view
popoverController.sourceRect = CGRect(x: self.view.bounds.midX, y: self.view.bounds.midY, width: 0, height: 0)
popoverController.permittedArrowDirections = []
}
}
self.present(alertController, animated: true, completion: nil)
}
```
**Code with Cancel button on iPad**
```
func webView(_ webView: WKWebView, runJavaScriptConfirmPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (Bool) -> Void) {
let alertController = UIAlertController(title: nil, message: message, preferredStyle: .actionSheet)
alertController.addAction(UIAlertAction(title: "OK", style: .default, handler: { (action) in
completionHandler(true)
}))
alertController.addAction(UIAlertAction(title: "Cancel", style: .default, handler: { (action) in
completionHandler(false)
}))
if UIDevice.current.userInterfaceIdiom != .phone {
alertController.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: { (action) in
completionHandler(false)
}))
if let popoverController = alertController.popoverPresentationController {
popoverController.sourceView = self.view
popoverController.sourceRect = CGRect(x: self.view.bounds.midX, y: self.view.bounds.midY, width: 0, height: 0)
popoverController.permittedArrowDirections = []
}
}
self.present(alertController, animated: true, completion: nil)
}
```
Upvotes: 2 [selected_answer] |
2018/03/20 | 313 | 1,258 | <issue_start>username_0: I have added a migration using `Add-Migration`, Now If I run `Remove-Migration`, it reverts the migration and remove the generated migration file successfully, but gives the error in Package Manager Console also. I could not figure out the exact reason behind it and side effect of it. Is this EF Core bug?
**Package Manager Output:**
>
> PM> Remove-Migration Removing migration
> '20180320052521\_testMigration'. Reverting model snapshot. Done.
> Exception calling "Remove" with "0" argument(s): "The given key was
> not present in the dictionary." PM>
>
>
>
**EF Core Version:** 2.0.1<issue_comment>username_1: When you're adding or removing a migration, the application is build. So, most likely you have a collection where you're trying to remove an item with a wrong key and the compiler goes through that piece of code while removing the migration.
Upvotes: 0 <issue_comment>username_2: The Application is always building when a migration is added to the Project as mentioned in the previous answers.
This one is not actually a Solution, its more a workaround which is working for me at most.
Try to remove your Migration mit following Command
```
Remove-Migration NameOfMigration
```
Upvotes: 2 [selected_answer] |
2018/03/20 | 270 | 1,080 | <issue_start>username_0: I am trying to output a very basic program which says 'hello world'
My web.php
```
php
Route::get('/',function() {
return view('welcome');
});
</code
```
My `welcome.blade.php` file
```
{{ 'Hello World' }}
```
The `welcome.blade.php` is inside the views folder, but when I give `localhost/laravel/public/` I am getting an error stating `"The page you're looking for cannot be found"`
Please Help me out.<issue_comment>username_1: When you're adding or removing a migration, the application is build. So, most likely you have a collection where you're trying to remove an item with a wrong key and the compiler goes through that piece of code while removing the migration.
Upvotes: 0 <issue_comment>username_2: The Application is always building when a migration is added to the Project as mentioned in the previous answers.
This one is not actually a Solution, its more a workaround which is working for me at most.
Try to remove your Migration mit following Command
```
Remove-Migration NameOfMigration
```
Upvotes: 2 [selected_answer] |
2018/03/20 | 801 | 2,403 | <issue_start>username_0: I have saved roles of an user in an array in db. The roles array looks like this.
```
{
"_id" : ObjectId("5708a54c8becc5b357ad82bb"),
"__v" : 2,
"active" : true,
"adminReports" : [],
"created" : ISODate("2016-04-09T06:46:36.814Z"),
"displayName" : "Admin Local",
"email" : "<EMAIL>",
"firstName" : "Admin",
"groups" : [],
"lastLogin" : ISODate("2016-12-29T13:34:48.592Z"),
"lastName" : "Local",
"password" : "j<KEY>
"profileImageURL" : "modules/users/client/img/profile/default.png",
"provider" : "local",
"roles" : [
"superAdmin", "admin","manager","user"
],
"salt" : "1v/XyKlUdhNqgEBPaAPSeA==",
"userWeeklyReport" : true,
"username" : "admin"
}
```
When i have to check if logged in user is manager or admin then I am checking it with **indexOf** which is the right way to do it but my code does not looks good. Here is a snippet if i have to check if logged in user is either **admin**, **CEO** or **manager**.
```
if(req.user.roles.indexOf('admin') !== -1 || req.user.roles.indexOf('manager') !== -1 || req.user.roles.indexOf('CEO') !== -1){
//some code goes here
}
```
There is a lot of indexOf and it doesn't looks good. Can anyone tell me what is the right way to do it, so that my code looks more readable.T
Thanks in advance.<issue_comment>username_1: You can use `array#some` to check if a `role` which is stored in an array exist in your `req.user.roles`. `array#includes` will check if the selected role exist in the `req.user.roles`.
```
if(['admin','manager','CEO'].some(role => req.user.roles.includes(role)))
```
Upvotes: 4 [selected_answer]<issue_comment>username_2: If you are okay with ES6, Array#some() do the job
```
let matched= ["admin","manager","CEO"].some(s=> req.user.roles.indexOf(s) !== -1)
```
Upvotes: 0 <issue_comment>username_3: `if(req.user.roles.indexOf('admin') !== -1 //Rest of the code}` will probably never be -1 because the array contains all the roles for which you are checking.
You need to get the logged in user's role in a variable and check if the exist in the role array,For that only one `indexOf` will be enough
```
var someRoles = 'admin'
if(req.user.roles.indexOf(someRoles )){
//some code goes here
}
```
Upvotes: 1 |
2018/03/20 | 379 | 1,289 | <issue_start>username_0: In the query given below, in the where condition the table 'a' is not accessible. How can I make it accessible without affecting the logic of the code?
Thanks in advance.
```
select *
from Training_Data.dbo.test a
cross apply (select * from Training_data.dbo.test_table) b
where exists (select 1 from a)
```<issue_comment>username_1: You can use `array#some` to check if a `role` which is stored in an array exist in your `req.user.roles`. `array#includes` will check if the selected role exist in the `req.user.roles`.
```
if(['admin','manager','CEO'].some(role => req.user.roles.includes(role)))
```
Upvotes: 4 [selected_answer]<issue_comment>username_2: If you are okay with ES6, Array#some() do the job
```
let matched= ["admin","manager","CEO"].some(s=> req.user.roles.indexOf(s) !== -1)
```
Upvotes: 0 <issue_comment>username_3: `if(req.user.roles.indexOf('admin') !== -1 //Rest of the code}` will probably never be -1 because the array contains all the roles for which you are checking.
You need to get the logged in user's role in a variable and check if the exist in the role array,For that only one `indexOf` will be enough
```
var someRoles = 'admin'
if(req.user.roles.indexOf(someRoles )){
//some code goes here
}
```
Upvotes: 1 |
2018/03/20 | 610 | 2,278 | <issue_start>username_0: I want to use a `ProcessWindowFunction` in my Apache Flink project. But I am getting some error when using process function, see below code snippet
The error is:
>
> The method process(ProcessWindowFunction,R,Tuple,TimeWindow>) in the type WindowedStream,Tuple,TimeWindow> is not applicable for the arguments (JDBCExample.MyProcessWindows)
>
>
>
My program:
```
DataStream> inputStream;
inputStream = env.addSource(new JsonArraySource());
inputStream.keyBy(0)
.window(TumblingEventTimeWindows.of(Time.minutes(10)))
.process(new MyProcessWindows());
```
My `ProcessWindowFunction`:
```
private class MyProcessWindows
extends ProcessWindowFunction, Tuple2, String, Window>
{
public void process(
String key,
Context context,
Iterable> input,
Collector> out) throws Exception
{
...
}
}
```<issue_comment>username_1: The problem are probably the generic types of the `ProcessWindowFunction`.
You are referencing the key by position (`keyBy(0)`). Therefore, the compiler cannot infer its type (`String`) and you need to change the `ProcessWindowFunction` to:
```
private class MyProcessWindows
extends ProcessWindowFunction, Tuple2, Tuple, Window>
```
By replacing `String` by `Tuple` you have now a generic placeholder for keys that you can cast to `Tuple1` when you need to access the key in the `processElement()` method:
```
public void process(
Tuple key,
Context context,
Iterable> input,
Collector> out) throws Exception {
String sKey = (String)((Tuple1)key).f0;
...
}
```
You can avoid the cast and use the proper type if you define a `KeySelector` function to extract the key, because the return type `KEY` of the `KeySelector` is known to the compiler.
Upvotes: 3 <issue_comment>username_2: What Fabian said :) Using `Tuple` should work, but does involve some ugly type casts in your `ProcessWindowFunction`. Using a `KeySelector` is easy and results in cleaner code. E.g.
```
.keyBy(new KeySelector, String>() {
@Override
public String getKey(Tuple2 in) throws Exception {
return in.f0;
}
})
```
The above then lets you define a `ProcessWindowFunction` like:
```
public class MyProcessWindows extends ProcessWindowFunction, Tuple2, String, TimeWindow> {
```
Upvotes: 2 |
2018/03/20 | 3,818 | 15,915 | <issue_start>username_0: I am developing an iOS app, my questions are as below:
1. Need to access user location every time while application is running or not?
2. Is Location not depend on the internet?
3. Apple will be approve this kind of app?
For question 1.
I am using these line for getting the user location
```
locationManager.allowsBackgroundLocationUpdates = true
locationManager.startUpdatingLocation()
```
With help of these i am able to get location when app is in foreground or background.
When application terminate
```
locationManager.startMonitoringSignificantLocationChanges()
```
**it work only when user cross the 500 meters**
then application become active and update the location
2.These are depend on the internet, while i want that receive location everytime internet exist or not.
3.Please also let me know these kind of app will be approve or not from apple.
Help/Suggestion please.
Thanks in advance.<issue_comment>username_1: 1. Yes, you can write your app such that it can receive background location fixes, as your own code shows. You'll need to ask your users for background location permission, however, which many users are usually loathe to do for both privacy and battery reasons.
2. Whether CLLocationManager uses internet (or even just Wifi access point detection) vs. GPS is very device dependent. See [this SO answer](https://stackoverflow.com/a/7346900/8441876) for details.
3. There are many apps in the App Store that do background location fixes via CLLocationManager. I'm routinely shocked at how many apps ask for Always location permission.
Upvotes: 0 <issue_comment>username_2: Your answers is here:
**Question1:** Need to access user location every time while application is running or not?
**Ans:** No, If you are using app and app is in running mode. You are continues taking update of location then you should always check the location accessibility and activenes like **UBER** app.
**Question2:** Is Location not depend on the internet?
**Ans:** Depends on your app's functionality. You are able to get current region by internet also or you can get it by using GPS.
**Question3**:Apple will be approve this kind of app?
**Ans:** Yes, If you are following proper guide lines then apple will definitely accept it. But make sure there are showing user friendly message while taking permission from user for access of location.
**Note:** Continues location update consume more power so it will speedly decrease the battery.
"it work only when user cross the 500 meters"
For this you can set the accuracy for updation of location like...
```
locationManager.desiredAccuracy = kCLLocationAccuracyBest
```
**Reference:**
[Get User's Current Location / Coordinates](https://stackoverflow.com/questions/25296691/get-users-current-location-coordinates/49167814#49167814)
<https://developer.apple.com/library/content/documentation/Performance/Conceptual/EnergyGuide-iOS/LocationBestPractices.html>
Upvotes: 2 <issue_comment>username_3: Yes we can do it with more or less than 500m I have tested it, First of all I searched a lot in google and somewhere I found that it is working but I didn't believe it because as per apple security guidelines it seems not possible so I applied it in my code and test it. And the result is awesome. It saves all location data in plist locally when the app is even force quit by user,so you can see it through that plist. I didn't remember where I saw that link but I share my bunch of direct code which can help you to understand it.
And most interesting part I am capable to call a server when the app is in terminated state which is really superb.
It seems Location Manager awake the app for some milliseconds when location changes.
LocationManager.h
```
#import
#import
#define IS\_OS\_8\_OR\_LATER ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)
@interface LocationManager : NSObject
@property (nonatomic) CLLocationManager \* anotherLocationManager;
@property (nonatomic) CLLocationCoordinate2D myLastLocation;
@property (nonatomic) CLLocationAccuracy myLastLocationAccuracy;
@property (nonatomic) CLLocationCoordinate2D myLocation;
@property (nonatomic) CLLocationAccuracy myLocationAccuracy;
@property (nonatomic) NSMutableDictionary \*myLocationDictInPlist;
@property (nonatomic) NSMutableArray \*myLocationArrayInPlist;
@property (nonatomic) BOOL afterResume;
+ (id)sharedManager;
- (void)startMonitoringLocation;
- (void)restartMonitoringLocation;
- (void)addResumeLocationToPList;
- (void)addLocationToPList:(BOOL)fromResume;
- (void)addApplicationStatusToPList:(NSString\*)applicationStatus;
@end
```
LocationManager.m
```
#import "LocationManager.h"
#import
#import "UpdateUserLocation.h"
#import "Constants.h"
@interface LocationManager ()
@property (nonatomic , strong) UpdateUserLocation \*updateUserLocation;
@end
@implementation LocationManager
//Class method to make sure the share model is synch across the app
+ (id)sharedManager {
static id sharedMyModel = nil;
static dispatch\_once\_t onceToken;
dispatch\_once(&onceToken, ^{
sharedMyModel = [[self alloc] init];
});
return sharedMyModel;
}
#pragma mark - CLLocationManager
- (void)startMonitoringLocation {
if (\_anotherLocationManager)
[\_anotherLocationManager stopMonitoringSignificantLocationChanges];
self.anotherLocationManager = [[CLLocationManager alloc]init];
\_anotherLocationManager.delegate = self;
\_anotherLocationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation;
\_anotherLocationManager.activityType = CLActivityTypeOtherNavigation;
if(IS\_OS\_8\_OR\_LATER) {
[\_anotherLocationManager requestAlwaysAuthorization];
}
[\_anotherLocationManager startMonitoringSignificantLocationChanges];
}
- (void)restartMonitoringLocation {
[\_anotherLocationManager stopMonitoringSignificantLocationChanges];
if (IS\_OS\_8\_OR\_LATER) {
[\_anotherLocationManager requestAlwaysAuthorization];
}
[\_anotherLocationManager startMonitoringSignificantLocationChanges];
}
#pragma mark - CLLocationManager Delegate
- (void)locationManager:(CLLocationManager \*)manager didUpdateLocations:(NSArray \*)locations{
NSLog(@"locationManager didUpdateLocations: %@",locations);
for (int i = 0; i < locations.count; i++) {
CLLocation \* newLocation = [locations objectAtIndex:i];
CLLocationCoordinate2D theLocation = newLocation.coordinate;
CLLocationAccuracy theAccuracy = newLocation.horizontalAccuracy;
self.myLocation = theLocation;
self.myLocationAccuracy = theAccuracy;
}
[self addLocationToPList:\_afterResume];
}
#pragma mark - Plist helper methods
// Below are 3 functions that add location and Application status to PList
// The purpose is to collect location information locally
- (NSString \*)appState {
UIApplication\* application = [UIApplication sharedApplication];
NSString \* appState;
if([application applicationState]==UIApplicationStateActive)
appState = @"UIApplicationStateActive";
if([application applicationState]==UIApplicationStateBackground)
appState = @"UIApplicationStateBackground";
if([application applicationState]==UIApplicationStateInactive)
appState = @"UIApplicationStateInactive";
return appState;
}
- (void)addResumeLocationToPList {
NSLog(@"addResumeLocationToPList");
NSString \* appState = [self appState];
self.myLocationDictInPlist = [[NSMutableDictionary alloc]init];
[\_myLocationDictInPlist setObject:@"UIApplicationLaunchOptionsLocationKey" forKey:@"Resume"];
[\_myLocationDictInPlist setObject:appState forKey:@"AppState"];
[\_myLocationDictInPlist setObject:[NSDate date] forKey:@"Time"];
[self saveLocationsToPlist];
}
- (void)addLocationToPList:(BOOL)fromResume {
NSLog(@"addLocationToPList");
NSString \* appState = [self appState];
self.myLocationDictInPlist = [[NSMutableDictionary alloc]init];
[\_myLocationDictInPlist setObject:[NSNumber numberWithDouble:self.myLocation.latitude] forKey:@"Latitude"];
[\_myLocationDictInPlist setObject:[NSNumber numberWithDouble:self.myLocation.longitude] forKey:@"Longitude"];
[\_myLocationDictInPlist setObject:[NSNumber numberWithDouble:self.myLocationAccuracy] forKey:@"Accuracy"];
[\_myLocationDictInPlist setObject:appState forKey:@"AppState"];
if (fromResume) {
[\_myLocationDictInPlist setObject:@"YES" forKey:@"AddFromResume"];
[self updatePreferredUserLocation:[NSString stringWithFormat:@"%f",self.myLocation.latitude] withLongitude:[NSString stringWithFormat:@"%f",self.myLocation.longitude]];
} else {
[\_myLocationDictInPlist setObject:@"NO" forKey:@"AddFromResume"];
}
[\_myLocationDictInPlist setObject:[NSDate date] forKey:@"Time"];
[self saveLocationsToPlist];
}
- (void)addApplicationStatusToPList:(NSString\*)applicationStatus {
NSLog(@"addApplicationStatusToPList");
NSString \* appState = [self appState];
self.myLocationDictInPlist = [[NSMutableDictionary alloc]init];
[\_myLocationDictInPlist setObject:applicationStatus forKey:@"applicationStatus"];
[\_myLocationDictInPlist setObject:appState forKey:@"AppState"];
[\_myLocationDictInPlist setObject:[NSDate date] forKey:@"Time"];
[self saveLocationsToPlist];
}
- (void)saveLocationsToPlist {
NSString \*plistName = [NSString stringWithFormat:@"LocationArray.plist"];
NSArray \*paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString \*docDir = [paths objectAtIndex:0];
NSString \*fullPath = [NSString stringWithFormat:@"%@/%@", docDir, plistName];
NSMutableDictionary \*savedProfile = [[NSMutableDictionary alloc] initWithContentsOfFile:fullPath];
if (!savedProfile) {
savedProfile = [[NSMutableDictionary alloc] init];
self.myLocationArrayInPlist = [[NSMutableArray alloc]init];
} else {
self.myLocationArrayInPlist = [savedProfile objectForKey:@"LocationArray"];
}
if(\_myLocationDictInPlist) {
[\_myLocationArrayInPlist addObject:\_myLocationDictInPlist];
[savedProfile setObject:\_myLocationArrayInPlist forKey:@"LocationArray"];
}
if (![savedProfile writeToFile:fullPath atomically:FALSE]) {
NSLog(@"Couldn't save LocationArray.plist" );
}
}
```
Appdelegate.m
```
#import "LocationManager.h"
@property (strong,nonatomic) LocationManager * locationShareModel;
- (void)applicationDidEnterBackground:(UIApplication *)application
{
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
enable when use track location at force quit
[self.locationShareModel restartMonitoringLocation];
[self.locationShareModel addApplicationStatusToPList:@"applicationDidEnterBackground"];
}
- (void)applicationDidBecomeActive:(UIApplication *)application
{
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
enable when use track location at force quit
[self.locationShareModel addApplicationStatusToPList:@"applicationDidBecomeActive"];
//Remove the "afterResume" Flag after the app is active again.
self.locationShareModel.afterResume = NO;
[self.locationShareModel startMonitoringLocation];
}
- (void)applicationWillTerminate:(UIApplication *)application
{
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
enable when use track location at force quit
[self.locationShareModel addApplicationStatusToPList:@"applicationWillTerminate"];
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
NSLog(@"AG_Didfinishlaunching");
//enable when use track location at force quit
[self trackLocation:launchOptions];
}
- (void)trackLocation:(NSDictionary *)launchOptions {
self.locationShareModel = [LocationManager sharedManager];
self.locationShareModel.afterResume = NO;
[self.locationShareModel addApplicationStatusToPList:@"didFinishLaunchingWithOptions"];
//UIAlertView * alert;
//We have to make sure that the Background App Refresh is enable for the Location updates to work in the background.
if ([[UIApplication sharedApplication] backgroundRefreshStatus] == UIBackgroundRefreshStatusDenied) {
///////// delete this alert view if no need
alert = [[UIAlertView alloc]initWithTitle:@""
message:@"The app doesn't work without the Background App Refresh enabled. To turn it on, go to Settings > General > Background App Refresh"
delegate:nil
cancelButtonTitle:@"Ok"
otherButtonTitles:nil, nil];
[alert show];
UIAlertController *showMsgAlertController = [UIAlertController alertControllerWithTitle: @"Eventseeker" message: @"To use all location servies. Please turn on Background App Refresh, go to Settings > General > Background App Refresh" preferredStyle: UIAlertControllerStyleAlert];
UIAlertAction *showMsgAlertControllerOkAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault
handler:nil];
[showMsgAlertController addAction:showMsgAlertControllerOkAction];
dispatch_async(dispatch_get_main_queue(), ^{
[self presentViewController:showMsgAlertController animated:YES completion:nil];
});
/////////
} else if ([[UIApplication sharedApplication] backgroundRefreshStatus] == UIBackgroundRefreshStatusRestricted) {
///////// delete this alert view if no need
alert = [[UIAlertView alloc]initWithTitle:@""
message:@"The functions of this app are limited because the Background App Refresh is disable."
delegate:nil
cancelButtonTitle:@"Ok"
otherButtonTitles:nil, nil];
[alert show];
/////////////////
} else {
// When there is a significant changes of the location,
// The key UIApplicationLaunchOptionsLocationKey will be returned from didFinishLaunchingWithOptions
// When the app is receiving the key, it must reinitiate the locationManager and get
// the latest location updates
// This UIApplicationLaunchOptionsLocationKey key enables the location update even when
// the app has been killed/terminated (Not in th background) by iOS or the user.
NSLog(@"UIApplicationLaunchOptionsLocationKey : %@" , [launchOptions objectForKey:UIApplicationLaunchOptionsLocationKey]);
if ([launchOptions objectForKey:UIApplicationLaunchOptionsLocationKey]) {
// This "afterResume" flag is just to show that he receiving location updates
// are actually from the key "UIApplicationLaunchOptionsLocationKey"
self.locationShareModel.afterResume = YES;
[self.locationShareModel startMonitoringLocation];
[self.locationShareModel addResumeLocationToPList];
}
}
}
```
Last but not the least don't forget to **add the permission in plist for always access location**. this is really important step to access it when app is force quit. User have to choose always use location access and must turn off battery saver mode as it disables **background refresh mode**.
Keep remember Location always access and background refresh mode for this app must be On to access the location in terminated state.
For offline mode I didn't test it. But I think It works.
Upvotes: 0 |
2018/03/20 | 723 | 2,478 | <issue_start>username_0: How to convert the collection to object so I can access the relational table data because i am getting the following error.
**Trying to get property of non-object** (View: E:\xampp\htdocs\digi\resources\views\admin\view-all-location.blade.php)
```
Controller:
$locations = Location::all();
return view('admin.view-all-location')->withLocations($locations);
View::
@if(! count($locations) > 0)
No Location Added |
@endif
@foreach($locations as $location)
| {{$location->name}} | {{ $location->company->name }} | {{$location->module->name}} | {{$location->address}} | {{$location->created\_at->format('d.m.Y')}} |
@endforeach
```<issue_comment>username_1: You should try this:
**Controller**
```
$locations = Location::with(['company','module'])->get();
return view('admin.view-all-location',compact('locations'));
```
**View**
```
@if(isset($locations) && count($locations) > 0)
@foreach($locations as $location)
| {{$location->name}} | {{ $location->company->name }} | {{$location->module->name}} | {{$location->address}} | {{$location->created\_at->format('d.m.Y')}} |
@endforeach
@else
No Location Added |
@endif
```
Upvotes: 2 <issue_comment>username_2: One of your locations doesn't have an associated `company` or `module`. Because of this, accessing `$location->company->name` or `$location->module->name` will throw the error, since you're trying to access `->name` on a `null` value.
Some of the common ways of handling this:
Combine `isset` with a ternary operator:
```
{{ isset($location->company) ? $location->company->name : '' }} |
{{ isset($location->module) ? $location->module->name : '' }} |
```
You can also use the blade `or` shorthand:
```
{{ $location->company->name or '' }} |
{{ $location->module->name or '' }} |
```
If you're on PHP7, you can use the null coalesce operator:
```
{{ $location->company->name ?? '' }} |
{{ $location->module->name ?? '' }} |
```
Upvotes: 0 <issue_comment>username_3: use `get` instead of `all`
**Controller**
```
$locations = Location::with(['company','module'])->get();
return view('admin.view-all-location',["locations"=>$locations]);
```
**View**
```
@if($locations->isEmpty())
No Location Added |
@endif
@foreach($locations as $location)
| {{$location->name}} | {{ $location->company()->name }} | {{$location->module()->name}} | {{$location->address}} | {{$location->created\_at->format('d.m.Y')}} |
@endforeach
```
Upvotes: 0 |
2018/03/20 | 860 | 2,771 | <issue_start>username_0: I want to get the Balance in below mentioned format. Balance+Balance(Row-1) I'm not sure if this explains well but adding previous rows Balance value to the current one and so on...
```
declare @tab table(Debit int,Credit int)
insert into @tab
select 1000 , NULL
union all
select 2200 , NULL
union all
select NULL , 3000
union all
select 1500 , 1500
SELECT Debit, Credit, COALESCE(SUM(Credit), SUM(Debit)) AS Balance
FROM @tab
GROUP BY Debit, Credit
```
This is what I'm getting so far.
```
Debit Credit Balance
------------------------------
1000 NULL 1000
2200 NULL 2200
NULL 3000 3000
1500 1500 1500
```
This is what I'm looking for but please don't make that too complex to understand.
```
Debit Credit Balance
------------------------------
1000 NULL 1000
2200 NULL 3200
NULL 3000 6200
1500 1500 7700
```<issue_comment>username_1: You should try this:
**Controller**
```
$locations = Location::with(['company','module'])->get();
return view('admin.view-all-location',compact('locations'));
```
**View**
```
@if(isset($locations) && count($locations) > 0)
@foreach($locations as $location)
| {{$location->name}} | {{ $location->company->name }} | {{$location->module->name}} | {{$location->address}} | {{$location->created\_at->format('d.m.Y')}} |
@endforeach
@else
No Location Added |
@endif
```
Upvotes: 2 <issue_comment>username_2: One of your locations doesn't have an associated `company` or `module`. Because of this, accessing `$location->company->name` or `$location->module->name` will throw the error, since you're trying to access `->name` on a `null` value.
Some of the common ways of handling this:
Combine `isset` with a ternary operator:
```
{{ isset($location->company) ? $location->company->name : '' }} |
{{ isset($location->module) ? $location->module->name : '' }} |
```
You can also use the blade `or` shorthand:
```
{{ $location->company->name or '' }} |
{{ $location->module->name or '' }} |
```
If you're on PHP7, you can use the null coalesce operator:
```
{{ $location->company->name ?? '' }} |
{{ $location->module->name ?? '' }} |
```
Upvotes: 0 <issue_comment>username_3: use `get` instead of `all`
**Controller**
```
$locations = Location::with(['company','module'])->get();
return view('admin.view-all-location',["locations"=>$locations]);
```
**View**
```
@if($locations->isEmpty())
No Location Added |
@endif
@foreach($locations as $location)
| {{$location->name}} | {{ $location->company()->name }} | {{$location->module()->name}} | {{$location->address}} | {{$location->created\_at->format('d.m.Y')}} |
@endforeach
```
Upvotes: 0 |
2018/03/20 | 768 | 2,692 | <issue_start>username_0: Currently I have the following code to handle an incoming GET request:
```
#view.py
def handle_request(request):
if request.method == 'GET':
return response
```
this code can handle a simple GET request the form:
```
curl http://some_url/
```
But now I want to add basic http authentication:
```
curl --user username:password http://some_url/
```
I want to modify my views.py code to look like:
```
def handle_request(request):
if request.method == 'GET':
if username == some_hard_coded_approved_username and password == <PASSWORD>:
return response
else:
response = HttpResponse("")
response.status\_code = 401
return response
```
How do I implement this line to parse username and password from http request:
```
if username == some_hard_coded_approved_username and password == <PASSWORD>:
```<issue_comment>username_1: You should try this:
**Controller**
```
$locations = Location::with(['company','module'])->get();
return view('admin.view-all-location',compact('locations'));
```
**View**
```
@if(isset($locations) && count($locations) > 0)
@foreach($locations as $location)
| {{$location->name}} | {{ $location->company->name }} | {{$location->module->name}} | {{$location->address}} | {{$location->created\_at->format('d.m.Y')}} |
@endforeach
@else
No Location Added |
@endif
```
Upvotes: 2 <issue_comment>username_2: One of your locations doesn't have an associated `company` or `module`. Because of this, accessing `$location->company->name` or `$location->module->name` will throw the error, since you're trying to access `->name` on a `null` value.
Some of the common ways of handling this:
Combine `isset` with a ternary operator:
```
{{ isset($location->company) ? $location->company->name : '' }} |
{{ isset($location->module) ? $location->module->name : '' }} |
```
You can also use the blade `or` shorthand:
```
{{ $location->company->name or '' }} |
{{ $location->module->name or '' }} |
```
If you're on PHP7, you can use the null coalesce operator:
```
{{ $location->company->name ?? '' }} |
{{ $location->module->name ?? '' }} |
```
Upvotes: 0 <issue_comment>username_3: use `get` instead of `all`
**Controller**
```
$locations = Location::with(['company','module'])->get();
return view('admin.view-all-location',["locations"=>$locations]);
```
**View**
```
@if($locations->isEmpty())
No Location Added |
@endif
@foreach($locations as $location)
| {{$location->name}} | {{ $location->company()->name }} | {{$location->module()->name}} | {{$location->address}} | {{$location->created\_at->format('d.m.Y')}} |
@endforeach
```
Upvotes: 0 |
2018/03/20 | 615 | 2,147 | <issue_start>username_0: I'm trying to sort an array of custom objects by their date, but the dates are stored as string in **.medium** dateStyle. However, some of the objects also have an empty string as their date.
How can I still sort arrays with an empty date?
Here is my code:
```
let objA = testObj(dateProp: "Mar 13, 2018")
let objB = testObj(dateProp: "Apr 13, 2018")
let objC = testObj(dateProp: "Apr 12, 2018")
let objD = testObj(dateProp: "")
let arr: [testObj] = [objA, objB, objC]
let sortedArr = arr.sorted(by: { DateHandler.shared.convertStringToDate(string: $0.dateProp)?.compare(DateHandler.shared.convertStringToDate(string: $1.dateProp)!) == .orderedDescending })
print(sortedArr)
```
The DateHandler.shared.convertStringtoDate just converts the String to Date, but the **force unwrapping an optional** is causing the code to break when there is a blank string instead of a date.<issue_comment>username_1: Just extend sorting closure
```
let sortedArr = arr.sorted { (first, second) -> Bool in
let dateFormatter = DateFormatter()
guard let firstDate = dateFormatter.date(from: first.dateProp) else {
return false
}
guard let secondDate = dateFormatter.date(from: second.dateProp) else {
return true
}
return firstDate < secondDate
}
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: Here is solution Thanks `username_1`
```
let sortedArr = arr.sorted { (first, second) -> Bool in
guard let firstDate = convertStrDateToDate(first.dateProp) else {
return false
}
guard let secondDate = convertStrDateToDate(second.dateProp) else {
return true
}
return firstDate < secondDate
}
```
**Convert String date to Date**
```
func convertStrDateToDate(_ date:String) -> Date? {
let inputFormatter = DateFormatter()
inputFormatter.timeZone = NSTimeZone.local
inputFormatter.dateFormat = "MMM dd, yyyy"
let date = inputFormatter.date(from: date)
return date
}
```
**Output**
Mar 13, 2018
Apr 12, 2018
Apr 13, 2018
Upvotes: 0 |
2018/03/20 | 448 | 1,731 | <issue_start>username_0: I have been trying to create an active directory for my environment. So I chose Microsoft Azure. I have been able to create the users to the directory and also created a VM of windows server 2012 now what I want is that the systems[Attached here is the snap](https://i.stack.imgur.com/uEm6y.jpg) in the organization can directly connect to the domain that I have provided in Microsoft Azure. kindly help me out on this or provide me with a link that can help me out<issue_comment>username_1: Just extend sorting closure
```
let sortedArr = arr.sorted { (first, second) -> Bool in
let dateFormatter = DateFormatter()
guard let firstDate = dateFormatter.date(from: first.dateProp) else {
return false
}
guard let secondDate = dateFormatter.date(from: second.dateProp) else {
return true
}
return firstDate < secondDate
}
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: Here is solution Thanks `username_1`
```
let sortedArr = arr.sorted { (first, second) -> Bool in
guard let firstDate = convertStrDateToDate(first.dateProp) else {
return false
}
guard let secondDate = convertStrDateToDate(second.dateProp) else {
return true
}
return firstDate < secondDate
}
```
**Convert String date to Date**
```
func convertStrDateToDate(_ date:String) -> Date? {
let inputFormatter = DateFormatter()
inputFormatter.timeZone = NSTimeZone.local
inputFormatter.dateFormat = "MMM dd, yyyy"
let date = inputFormatter.date(from: date)
return date
}
```
**Output**
Mar 13, 2018
Apr 12, 2018
Apr 13, 2018
Upvotes: 0 |
2018/03/20 | 413 | 1,483 | <issue_start>username_0: A table with terabytes of data in bigquery got multiple columns set as string format but actually they contain datetime strings like
2016-10-24 15:00:00
I tried answer from [this link](https://stackoverflow.com/a/36071426/7260022) to convert (CAST) the fields into timestamp format as below
```
SELECT
CAST( MURDER_DATE AS TIMESTAMP) AS CONVERTED_MURDER_DATE, *
FROM `death_list`;
```
That works but it converts all strings into timestamps with UTC timezone as below
```
2007-03-23 15:00:00.000 UTC
```
I need the data in a different timezone. Any clue?<issue_comment>username_1: Try using
```
DATETIME(CAST( MURDER_DATE AS TIMESTAMP), "Australia/Sydney"))
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: To my view, it seems to be a current limitation of BigQuery:
* *Timestamp* type is always stored in UTC format. And you have no way to add any "timezone" information to it.
* *Datetime* type nor stores any information about the timezone. You could still have a internal convention in your team/company that says that all the Datetime columns are stored in your local timezone, but I personally find it very awkward.
What we've decided so far in our company is to store everything in Timestamp (thus UTC format), and we never use Datetime due to lack of precision regarding the time zone. Then, if a client wants to get the information in another timezone, it has to do the conversion itself when reading the data.
Upvotes: 1 |
2018/03/20 | 395 | 1,511 | <issue_start>username_0: I need to insert the arrays like locations,commodities into an object which is in this case is refdata. I need to insert the array to object **one by one** ..as i have done in the code below:-
But i am not getting the desired output.Any help will be appreciated.
```js
var refdata = {
locations: [],
commodities: []
}
var locations=[
{
"symbol": "IND",
"name": "INDIA"
}
]
var commodities= [
{
"name": "Aluminium",
"symbol": "AL"
}
]
this.refdata={locations};
this.refdta={commodities};
console.log(this.refdata)
```<issue_comment>username_1: Try using
```
DATETIME(CAST( MURDER_DATE AS TIMESTAMP), "Australia/Sydney"))
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: To my view, it seems to be a current limitation of BigQuery:
* *Timestamp* type is always stored in UTC format. And you have no way to add any "timezone" information to it.
* *Datetime* type nor stores any information about the timezone. You could still have a internal convention in your team/company that says that all the Datetime columns are stored in your local timezone, but I personally find it very awkward.
What we've decided so far in our company is to store everything in Timestamp (thus UTC format), and we never use Datetime due to lack of precision regarding the time zone. Then, if a client wants to get the information in another timezone, it has to do the conversion itself when reading the data.
Upvotes: 1 |
2018/03/20 | 1,321 | 4,433 | <issue_start>username_0: I was working on a code snippet to get all substrings from a given string.
Here is the code that I use
```
var stringList = new List();
for (int length = 1; length < mainString.Length; length++)
{
for (int start = 0; start <= mainString.Length - length; start++)
{
var substring = mainString.Substring(start, length);
stringList.Add(substring);
}
}
```
It looks not so great to me, with two for loops. Is there any other way that I can achieve this with better time complexity.
I am stuck on the point that, for getting a substring, I will surely need two loops. Is there any other way I can look into ?<issue_comment>username_1: The number of substrings in a string is `O(n^2)`, so one loop inside another is the best you can do. You are correct in your code structure.
Here's how I would've phrased your code:
```
void Main()
{
var stringList = new List();
string s = "1234";
for (int i=0; i
```
Upvotes: 3 <issue_comment>username_2: You do need 2 `for` loops
[Demo here](https://dotnetfiddle.net/7ZjqpU)
```
var input = "asd sdf dfg";
var stringList = new List();
for (int i = 0; i < input.Length; i++)
{
for (int j = i; j < input.Length; j++)
{
var substring = input.Substring(i, j-i+1);
stringList.Add(substring);
}
}
foreach(var item in stringList)
{
Console.WriteLine(item);
}
```
**Update**
You cannot improve on the iterations.
However you can improve performance, by using `fixed` arrays and pointers
Upvotes: 2 <issue_comment>username_3: In some cases you can significantly increase execution speed by reducing object allocations. In this case by using a single `char[]` and [`ArraySegment`](https://msdn.microsoft.com/en-us/library/1hsbd92d(v=vs.110).aspx) to process substrings. This will also lead to use of less address space and decrease in garbage collector load.
Relevant excerpt from [Using the StringBuilder Class in .NET](https://learn.microsoft.com/en-us/dotnet/standard/base-types/stringbuilder) page on Microsoft Docs:
>
> The [String](https://learn.microsoft.com/en-us/dotnet/api/system.string) object is immutable. Every time you use one of the methods in the [System.String](https://learn.microsoft.com/en-us/dotnet/api/system.string) class, you create a new string object in memory, which requires a new allocation of space for that new object. In situations where you need to perform repeated modifications to a string, the overhead associated with creating a new [String](https://learn.microsoft.com/en-us/dotnet/api/system.string) object can be costly.
>
>
>
Example implementation:
```
static List> SubstringsOf(char[] value)
{
var substrings = new List>(capacity: value.Length \* (value.Length + 1) / 2 - 1);
for (int length = 1; length < value.Length; length++)
for (int start = 0; start <= value.Length - length; start++)
substrings.Add(new ArraySegment(value, start, length));
return substrings;
}
```
For more information check [Fundamentals of Garbage Collection](https://learn.microsoft.com/en-us/dotnet/standard/garbage-collection/fundamentals) page on Microsoft Docs, [what is the use of ArraySegment class?](https://stackoverflow.com/questions/4600024/what-is-the-use-of-arraysegmentt-class) discussion on StackOverflow, [ArraySegment Structure](https://msdn.microsoft.com/en-us/library/1hsbd92d(v=vs.110).aspx) page on MSDN and [List.Capacity](https://msdn.microsoft.com/en-us/library/y52x03h2(v=vs.110).aspx) page on MSDN.
Upvotes: 2 <issue_comment>username_4: Well, `O(n**2)` *time* complexity is inevitable, however you can try impove *space* consumption. In many cases, you don't want all the substrings being *materialized*, say, as a `List`:
```
public static IEnumerable AllSubstrings(string value) {
if (value == null)
yield break; // Or throw ArgumentNullException
for (int length = 1; length < value.Length; ++length)
for (int start = 0; start <= value.Length - length; ++start)
yield return value.Substring(start, length);
}
```
For instance, let's count all substrings in `"abracadabra"` which start from `a` and longer than `3` characters. Please, notice that all we have to do is to *loop* over susbstrings *without* saving them into a list:
```
int count = AllSubstrings("abracadabra")
.Count(item => item.StartsWith("a") && item.Length > 3);
```
If for any reason you want a `List`, just add `.ToList()`:
```
var stringList = AllSubstrings(mainString).ToList();
```
Upvotes: 0 |
2018/03/20 | 1,478 | 4,787 | <issue_start>username_0: [](https://i.stack.imgur.com/0gy6S.png)
I am using Android Studio 3.0
Build #AI-171.4408382, built on October 21, 2017
JRE: 1.8.0\_152-release-915-b01 amd64
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
Windows 7 6.1
public class LogTestActivity extends AppCompatActivity {
```
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_log_test);
Log.d("","AAAAAA-------");
Log.d("","AAAAAA-BBBBBBB");
```
// Log.d("AAAAA-------","AAAAAA-------"); //doesn't show log
// Log.d("AAAAAA-BBBBBBB","AAAAAA-BBBBBBB");//doesn't show log
```
}
```
}
I try to use the Logcat to see logs. but some time logcat doesn't work .
sometimes filter wokr but usually does not work, so I use No Filters,
Can I use "Show only selected application" filter?
I think Android Studio Setting is wrong.
pleas help me Thanks<issue_comment>username_1: The number of substrings in a string is `O(n^2)`, so one loop inside another is the best you can do. You are correct in your code structure.
Here's how I would've phrased your code:
```
void Main()
{
var stringList = new List();
string s = "1234";
for (int i=0; i
```
Upvotes: 3 <issue_comment>username_2: You do need 2 `for` loops
[Demo here](https://dotnetfiddle.net/7ZjqpU)
```
var input = "asd sdf dfg";
var stringList = new List();
for (int i = 0; i < input.Length; i++)
{
for (int j = i; j < input.Length; j++)
{
var substring = input.Substring(i, j-i+1);
stringList.Add(substring);
}
}
foreach(var item in stringList)
{
Console.WriteLine(item);
}
```
**Update**
You cannot improve on the iterations.
However you can improve performance, by using `fixed` arrays and pointers
Upvotes: 2 <issue_comment>username_3: In some cases you can significantly increase execution speed by reducing object allocations. In this case by using a single `char[]` and [`ArraySegment`](https://msdn.microsoft.com/en-us/library/1hsbd92d(v=vs.110).aspx) to process substrings. This will also lead to use of less address space and decrease in garbage collector load.
Relevant excerpt from [Using the StringBuilder Class in .NET](https://learn.microsoft.com/en-us/dotnet/standard/base-types/stringbuilder) page on Microsoft Docs:
>
> The [String](https://learn.microsoft.com/en-us/dotnet/api/system.string) object is immutable. Every time you use one of the methods in the [System.String](https://learn.microsoft.com/en-us/dotnet/api/system.string) class, you create a new string object in memory, which requires a new allocation of space for that new object. In situations where you need to perform repeated modifications to a string, the overhead associated with creating a new [String](https://learn.microsoft.com/en-us/dotnet/api/system.string) object can be costly.
>
>
>
Example implementation:
```
static List> SubstringsOf(char[] value)
{
var substrings = new List>(capacity: value.Length \* (value.Length + 1) / 2 - 1);
for (int length = 1; length < value.Length; length++)
for (int start = 0; start <= value.Length - length; start++)
substrings.Add(new ArraySegment(value, start, length));
return substrings;
}
```
For more information check [Fundamentals of Garbage Collection](https://learn.microsoft.com/en-us/dotnet/standard/garbage-collection/fundamentals) page on Microsoft Docs, [what is the use of ArraySegment class?](https://stackoverflow.com/questions/4600024/what-is-the-use-of-arraysegmentt-class) discussion on StackOverflow, [ArraySegment Structure](https://msdn.microsoft.com/en-us/library/1hsbd92d(v=vs.110).aspx) page on MSDN and [List.Capacity](https://msdn.microsoft.com/en-us/library/y52x03h2(v=vs.110).aspx) page on MSDN.
Upvotes: 2 <issue_comment>username_4: Well, `O(n**2)` *time* complexity is inevitable, however you can try impove *space* consumption. In many cases, you don't want all the substrings being *materialized*, say, as a `List`:
```
public static IEnumerable AllSubstrings(string value) {
if (value == null)
yield break; // Or throw ArgumentNullException
for (int length = 1; length < value.Length; ++length)
for (int start = 0; start <= value.Length - length; ++start)
yield return value.Substring(start, length);
}
```
For instance, let's count all substrings in `"abracadabra"` which start from `a` and longer than `3` characters. Please, notice that all we have to do is to *loop* over susbstrings *without* saving them into a list:
```
int count = AllSubstrings("abracadabra")
.Count(item => item.StartsWith("a") && item.Length > 3);
```
If for any reason you want a `List`, just add `.ToList()`:
```
var stringList = AllSubstrings(mainString).ToList();
```
Upvotes: 0 |
2018/03/20 | 1,052 | 4,157 | <issue_start>username_0: I am trying to make a pure js mvc app where I update an h1 with the text of an input field. I got to the point that the the value of the input in the model can be logged nicely but for some reason the h1 is not changing at all.
Could you give me some help that why is that and how to solve it?
my code:
```js
window.onload = function() {
var model = new Model();
var controller = new Controller(model);
var view = new View(controller);
};
function Model() {
this.inputtext = "zzzzz";
this.heading = this.inputtext;
console.log('model called');
};
function Controller(model) {
var controller = this;
this.model = model;
this.handleEvent = function(e) {
switch (e.type) {
case "click":
controller.clickHandler(e.target);
break;
case "input":
controller.keyupHandler(e.target);
break;
default:
console.log(e.target);
}
}
this.getModelHeading = function() {
console.log("from getmodel: " + controller.model.inputtext + "heading " + controller.model.heading);
return controller.model.heading;
}
this.keyupHandler = function(target) {
controller.model.inputtext = target.value;
controller.getModelHeading();
}
console.log('controller called');
};
function View(controller) {
this.controller = controller;
this.heading = document.getElementById("heading");
this.heading.innerHTML = controller.getModelHeading();
this.inputtext = document.getElementById("inputtext");
this.inputtext.addEventListener('input', controller);
console.log('view called');
}
```
```html
Vanilla MVC Framework
```<issue_comment>username_1: You update the h1 element only in the constructor of View class.
In keyUp event handler you update the only model but you haven't reassigned the view.heading.innerHtml value.
Only your View should know about where in DOM to display a model.property. Therefore, my suggestion to you add this code in your View:
```
function View(controller) {
var _self = this;
this.controller = controller;
this.heading = document.getElementById("heading");
updateHeading.call(_self);
this.inputtext = document.getElementById("inputtext");
this.inputtext.addEventListener('input', function(e){
controler.handleEvent(e);
updateHeading.call(_self);
});
console.log('view called');
function updateHeading(){
this.heading.innerHTML = controller.getModelHeading();
}
}
```
Upvotes: 0 <issue_comment>username_2: You need to link the view to the controller, then modify the view from the controller.
```js
window.onload = function() {
var model = new Model();
var controller = new Controller(model);
var view = new View(controller);
};
function Model() {
this.inputtext = "zzzzz";
this.heading = this.inputtext;
console.log('model called');
};
function Controller(model) {
var controller = this;
this.model = model;
this.handleEvent = function(e) {
switch (e.type) {
case "click":
controller.clickHandler(e.target);
break;
case "input":
controller.keyupHandler(e.target);
break;
default:
console.log(e.target);
}
}
this.getModelHeading = function() {
// console.log("from getmodel: " + controller.model.inputtext + "heading " + controller.model.heading);
controller.model.heading = controller.model.inputtext;
return controller.model.heading;
}
this.keyupHandler = function(target) {
controller.model.inputtext = target.value;
controller.view.heading.innerHTML=controller.getModelHeading();
}
console.log('controller called');
};
function View(controller) {
this.controller = controller;
this.heading = document.getElementById("heading");
this.heading.innerHTML = controller.getModelHeading();
this.inputtext = document.getElementById("inputtext");
this.inputtext.addEventListener('input', controller);
controller.view = this;
console.log('view called');
}
```
```html
Vanilla MVC Framework
```
Upvotes: 2 [selected_answer] |
2018/03/20 | 864 | 2,921 | <issue_start>username_0: I have the following code which uses both `Rc` and `Box`; what is the difference between those? Which one is better?
```
use std::rc::Rc;
fn main() {
let a = Box::new(1);
let a1 = &a
let a2 = &a
let b = Rc::new(1);
let b1 = b.clone();
let b2 = b.clone();
println!("{} {}", a1, a2); //=> 1 1
println!("{} {}", b1, b2); //=> 1 1
}
```
[playground link](https://play.rust-lang.org/?gist=f969bf51c9ff678d7f7267794bf0218f&version=stable)<issue_comment>username_1: [`Rc`](https://doc.rust-lang.org/std/rc/) provides shared ownership so by default its contents can't be mutated, while [`Box`](https://doc.rust-lang.org/std/boxed/) provides exclusive ownership and thus mutation is allowed:
```
use std::rc::Rc;
fn main() {
let mut a = Box::new(1);
let mut b = Rc::new(1);
*a = 2; // works
*b = 2; // doesn't
}
```
In addition `Rc` cannot be sent between threads, because it doesn't implement `Send`.
The bottom line is they are meant for different things: if you don't need shared access, use `Box`; otherwise, use `Rc` (or `Arc` for multi-threaded shared usage) and keep in mind you will be needing `Cell` or `RefCell` for internal mutability.
Upvotes: 7 [selected_answer]<issue_comment>username_2: Looking at the example given in the description, I think the real question here is "when to use `Rc` versus `&Box`" (note the ampersand).
Both `Rc` and `&Box` store the underlying data on the heap, neither can be sent across threads, and both allow immutable sharing (demonstrated by the aforementioned example). However, the biggest difference is that `Rc` gives you a shared (immutable) *owned* value while with `&Box` you get a shared (immutable) *reference*.
In the `Rc` case, the underlying data will be dropped (freed/deallocated) whenever the last owner (whether the original one or any cloned one) gets dropped – that's the idea of reference counting. In the `&Box` case, however, there is only one owner: any shared references to it will become invalid immediately after the owner gets out of scope.
Said differently, contrary to a `Rc::clone()`, binding a variable to a new `&Box` (`let a2 = &a` in the example) will not make it live any longer than it would otherwise.
As a concrete example, the following is valid:
```rust
use std::rc::Rc;
fn main() {
let rc_clone;
{
let rc = Rc::new(1);
rc_clone = rc.clone();
// rc gets out of scope here but as a "shared owner", rc_clone
// keeps the underlying data alive.
}
println!("{}", rc_clone); // Ok.
}
```
But this isn't:
```rust
fn main() {
let b_ref;
{
let b = Box::new(1);
b_ref = &b
// b gets out of scope here and since it is the only owner,
// the underlying data gets dropped.
}
println!("{}", b_ref); // Compilation error: `b` does not live long enough.
}
```
Upvotes: 5 |
2018/03/20 | 664 | 1,614 | <issue_start>username_0: I have a table which looks like.
```
ID Var Date1 Date2
1 A 2017-06-01 12:05:18 2017-06-25 06:08:04
2 B 2017-07-01 18:05:22 2017-07-20 18:25:04
3 C 2017-07-10 23:09:15 Null
4 D 2017-07-10 14:09:45 2017-08-01 09:45:12
5 E 2017-08-12 12:05:18 2017-09-04 07:15:04
```
I want to fetch those rows where difference between `Date2` and `Date1` is >10 days.
I have tried below mentioned query but it didn't work.
```
select ID from table_1 where date(Date2-Date1)>10 and date(Date1)>'2017-05-01';
```
And how to add column which show the days difference.<issue_comment>username_1: ```
select ID from table where DATEDIFF(Date1, Date2) > 10
```
Upvotes: 0 <issue_comment>username_2: Try
```
select ID from table_1 where Date2-Date1>10;
```
Upvotes: 0 <issue_comment>username_3: Try DATEDIFF() function:
Quoting the manual's page :
>
> DATEDIFF() returns expr1 – expr2 expressed as a value in days from one
> date to the other. expr1 and expr2 are date or date-and-time
> expressions. Only the date parts of the values are used in the
> calculation
>
>
>
Try the below query :
```
SELECT ID
FROM TABLE_1
WHERE DATEDIFF(Date2,Date1)>10;
```
Follow the link to the demo:
>
> <http://sqlfiddle.com/#!9/056aab/4>
>
>
>
Upvotes: 1 [selected_answer]<issue_comment>username_4: You have to use timestamp value
```
select ID from table_1 t1 where (UNIX_TIMESTAMP(t1.Date2)-UNIX_TIMESTAMP(t1.Date1)>864000)
```
where 864000 is the timestamp value of 10 days
Upvotes: 1 |
2018/03/20 | 561 | 2,401 | <issue_start>username_0: i am using angular 2/4 for one of my projects and i am in a situation where i have to download a file on submitting the request. I am doing currently.
```
this._http.post('url', body, { headers: urlEncodedHeader, observe: 'response', responseType: 'arraybuffer' })
.subscribe((data) => {
let blob = new Blob([data.body], { 'type': 'application/octet-stream' });
saveAs(blob, 'file.zip');
})
```
The file size could be very huge so i want the browser to handle the request instead of parsing the data and creating a blob in the application side. So i read somewhere that we can create a form element dynamically and give the handle to the browser instead of letting the application handle the blob and storing in the memory. So i tried
```
post_to_url(path, params, method) {
method = method || "post";
var form = document.createElement("form");
form.setAttribute("method", method);
form.setAttribute("action", path);
for (var key in params) {
if (params.hasOwnProperty(key)) {
var hiddenField = document.createElement("input");
hiddenField.setAttribute("type", "hidden");
hiddenField.setAttribute("token", key);
hiddenField.setAttribute("value", params[key]);
form.appendChild(hiddenField);
}
}
document.body.appendChild(form);
form.submit();
}
```
This doesnt seem to be working, the page always redirects to some error page. So my query is, how to download a huge file without hanging the browser. Please help.<issue_comment>username_1: Maybe simply generate link to downloading file on `post`:
```
this._http.post('url', body, { headers: urlEncodedHeader, observe: 'response', responseType: 'arraybuffer' })
.subscribe((data) => {
let link = data.body; // //http://path/to/file;
window.open(link);
// or
var link = document.createElement('a');
link.href = link
link.click();
});
```
Upvotes: 0 <issue_comment>username_2: The problem was i was doing
```
hiddenField.setAttribute("token", key);
```
instead of
```
hiddenField.setAttribute("name", key);
```
Changing to the name solved my issue
Upvotes: 2 [selected_answer] |
2018/03/20 | 1,420 | 4,893 | <issue_start>username_0: I am getting the list of Invoice details by Invoice Id.
Now i want to update AmountDue by respective Invoice Id.
i tried by below code:
ByInvoiceId.AmountDue = Convert.ToDecimal(100.00);
public\_app\_api.Invoices.Update(ByInvoiceId);
but..Error as
"A validation exception occurred"
What's the reason behind and How to solve this?<issue_comment>username_1: There are a number of ways to change the amount due on an invoice, however changing the value of the property directly is not one of them.
The amount due on an invoice is driven by the totals of the line items on the invoice minus the total of payments and allocated credit. One way to change the amount due is to change the values of your line items or add/remove some line items. You won't be able to change the invoice if it has been paid/partially paid.
Another way you could change the amount due on an invoice is to add a payment against the invoice or allocate credit from a credit note, prepayment, or overpayment to the invoice
Upvotes: 2 <issue_comment>username_2: In addition to username_1's answer.
You can't change the line amounts on an AUTHORISED invoice via the c# API. You have to VOID the invoice and create a new one. You can however update DRAFT and SUBMITTED ones by updating the line items.
EDIT: Here is some code to help you. This is create invoice code, but amending one is essentially the same.
```
public XeroTransferResult CreateInvoices(IEnumerable invoices, string user, string status)
{
\_user = XeroApiHelper.User(user);
var invoicestatus = InvoiceStatus.Draft;
if (status == "SUBMITTED")
{
invoicestatus = InvoiceStatus.Submitted;
}
else if (status == "AUTHORISED")
{
invoicestatus = InvoiceStatus.Authorised;
}
var api = XeroApiHelper.CoreApi();
var xinvs = new List();
foreach (var inv in invoices)
{
var items = new List();
foreach (var line in inv.Lines)
{
decimal discount = 0;
if (line.PriceBeforeDiscount != line.Price)
{
discount = (decimal)(1 - line.Price / line.PriceBeforeDiscount) \* 100;
}
items.Add(new LineItem
{
AccountCode = line.AccountCode,
Description = line.PublicationName != "N/A" ? line.PublicationName + " - " + line.Description : line.Description,
TaxAmount = (decimal)line.TaxAmount,
Quantity = 1,
UnitAmount = (decimal)line.PriceBeforeDiscount,
DiscountRate = discount,
TaxType = line.XeroCode,
ItemCode = line.ItemCode
});
}
var person = inv.Company.People.FirstOrDefault(p => p.IsAccountContact);
if (person == null)
{
person = inv.Company.People.FirstOrDefault(p => p.IsPrimaryContact);
}
var ninv = new Invoice
{
Number = inv.ClientInvoiceId,
Type = InvoiceType.AccountsReceivable,
Status = invoicestatus,
Reference = inv.Reference,
Contact = new Contact
{
Name = inv.Company.OrganisationName,
//ContactNumber = "MM" + inv.Company.CompanyId.ToString(),
FirstName = person.FirstName,
LastName = person.LastName,
EmailAddress = person.Email,
Phones = new List()
{
new Phone {PhoneNumber = person.Telephone, PhoneType = PhoneType.Default},
new Phone {PhoneNumber = person.Mobile, PhoneType = PhoneType.Mobile}
},
Addresses = new List
{ new Address
{
//AttentionTo = inv.Company.People.FirstOrDefault(p => p.IsAccountContact) == null
//? inv.Company.People.FirstOrDefault(p=> p.IsPrimaryContact).FullName
//: inv.Company.People.FirstOrDefault(p => p.IsAccountContact).FullName,
//AddressLine1 = inv.Company.OrganisationName,
AddressLine1 = inv.Company.Address.Address1,
AddressLine2 = inv.Company.Address.Address2 ?? "",
AddressLine3 = inv.Company.Address.Address3 ?? "",
Region = inv.Company.Address.CountyState,
City = inv.Company.Address.TownCity,
PostalCode = inv.Company.Address.PostCode,
}
}
},
AmountDue = (decimal)inv.TotalAmount,
Date = inv.InvoiceDate,
DueDate = inv.DueDate,
LineItems = items,
LineAmountTypes = LineAmountType.Exclusive
};
if (SessionContext.TransferContactDetailsToXero == false)
{
ninv.Contact = new Contact
{
Id = inv.Company.XeroId ?? Guid.Empty,
Name = inv.Company.OrganisationName
};
}
xinvs.Add(ninv);
}
var success = true;
var xinvresult = new List();
try
{
api.SummarizeErrors(false);
xinvresult = api.Invoices.Create(xinvs).ToList();
}
catch (ValidationException ex)
{
// Something's gone wrong
}
foreach (var inv in xinvresult)
{
var mminvoice = invoices.FirstOrDefault(i => i.ClientInvoiceId == inv.Number);
if (inv.Errors != null && inv.Errors.Count > 0)
{
success = false;
if (mminvoice != null)
{
var errors = new List();
foreach (var err in inv.Errors)
{
errors.Add(new XeroError { ErrorDescription = err.Message });
}
mminvoice.XeroErrors = errors;
}
}
else
{
mminvoice.XeroTransferDate = DateTime.Now;
mminvoice.XeroId = inv.Id;
mminvoice.XeroErrors = new List();
}
}
return new XeroTransferResult
{
Invoices = invoices,
Success = success
};
}
```
Upvotes: 2 |
2018/03/20 | 1,365 | 4,742 | <issue_start>username_0: What should i use if i need to make a scheduled email let us say every 12 midnight with query finding data that represents as a request for each approver. im using sql server and php<issue_comment>username_1: There are a number of ways to change the amount due on an invoice, however changing the value of the property directly is not one of them.
The amount due on an invoice is driven by the totals of the line items on the invoice minus the total of payments and allocated credit. One way to change the amount due is to change the values of your line items or add/remove some line items. You won't be able to change the invoice if it has been paid/partially paid.
Another way you could change the amount due on an invoice is to add a payment against the invoice or allocate credit from a credit note, prepayment, or overpayment to the invoice
Upvotes: 2 <issue_comment>username_2: In addition to username_1's answer.
You can't change the line amounts on an AUTHORISED invoice via the c# API. You have to VOID the invoice and create a new one. You can however update DRAFT and SUBMITTED ones by updating the line items.
EDIT: Here is some code to help you. This is create invoice code, but amending one is essentially the same.
```
public XeroTransferResult CreateInvoices(IEnumerable invoices, string user, string status)
{
\_user = XeroApiHelper.User(user);
var invoicestatus = InvoiceStatus.Draft;
if (status == "SUBMITTED")
{
invoicestatus = InvoiceStatus.Submitted;
}
else if (status == "AUTHORISED")
{
invoicestatus = InvoiceStatus.Authorised;
}
var api = XeroApiHelper.CoreApi();
var xinvs = new List();
foreach (var inv in invoices)
{
var items = new List();
foreach (var line in inv.Lines)
{
decimal discount = 0;
if (line.PriceBeforeDiscount != line.Price)
{
discount = (decimal)(1 - line.Price / line.PriceBeforeDiscount) \* 100;
}
items.Add(new LineItem
{
AccountCode = line.AccountCode,
Description = line.PublicationName != "N/A" ? line.PublicationName + " - " + line.Description : line.Description,
TaxAmount = (decimal)line.TaxAmount,
Quantity = 1,
UnitAmount = (decimal)line.PriceBeforeDiscount,
DiscountRate = discount,
TaxType = line.XeroCode,
ItemCode = line.ItemCode
});
}
var person = inv.Company.People.FirstOrDefault(p => p.IsAccountContact);
if (person == null)
{
person = inv.Company.People.FirstOrDefault(p => p.IsPrimaryContact);
}
var ninv = new Invoice
{
Number = inv.ClientInvoiceId,
Type = InvoiceType.AccountsReceivable,
Status = invoicestatus,
Reference = inv.Reference,
Contact = new Contact
{
Name = inv.Company.OrganisationName,
//ContactNumber = "MM" + inv.Company.CompanyId.ToString(),
FirstName = person.FirstName,
LastName = person.LastName,
EmailAddress = person.Email,
Phones = new List()
{
new Phone {PhoneNumber = person.Telephone, PhoneType = PhoneType.Default},
new Phone {PhoneNumber = person.Mobile, PhoneType = PhoneType.Mobile}
},
Addresses = new List
{ new Address
{
//AttentionTo = inv.Company.People.FirstOrDefault(p => p.IsAccountContact) == null
//? inv.Company.People.FirstOrDefault(p=> p.IsPrimaryContact).FullName
//: inv.Company.People.FirstOrDefault(p => p.IsAccountContact).FullName,
//AddressLine1 = inv.Company.OrganisationName,
AddressLine1 = inv.Company.Address.Address1,
AddressLine2 = inv.Company.Address.Address2 ?? "",
AddressLine3 = inv.Company.Address.Address3 ?? "",
Region = inv.Company.Address.CountyState,
City = inv.Company.Address.TownCity,
PostalCode = inv.Company.Address.PostCode,
}
}
},
AmountDue = (decimal)inv.TotalAmount,
Date = inv.InvoiceDate,
DueDate = inv.DueDate,
LineItems = items,
LineAmountTypes = LineAmountType.Exclusive
};
if (SessionContext.TransferContactDetailsToXero == false)
{
ninv.Contact = new Contact
{
Id = inv.Company.XeroId ?? Guid.Empty,
Name = inv.Company.OrganisationName
};
}
xinvs.Add(ninv);
}
var success = true;
var xinvresult = new List();
try
{
api.SummarizeErrors(false);
xinvresult = api.Invoices.Create(xinvs).ToList();
}
catch (ValidationException ex)
{
// Something's gone wrong
}
foreach (var inv in xinvresult)
{
var mminvoice = invoices.FirstOrDefault(i => i.ClientInvoiceId == inv.Number);
if (inv.Errors != null && inv.Errors.Count > 0)
{
success = false;
if (mminvoice != null)
{
var errors = new List();
foreach (var err in inv.Errors)
{
errors.Add(new XeroError { ErrorDescription = err.Message });
}
mminvoice.XeroErrors = errors;
}
}
else
{
mminvoice.XeroTransferDate = DateTime.Now;
mminvoice.XeroId = inv.Id;
mminvoice.XeroErrors = new List();
}
}
return new XeroTransferResult
{
Invoices = invoices,
Success = success
};
}
```
Upvotes: 2 |
2018/03/20 | 1,311 | 3,630 | <issue_start>username_0: I am new to web designing, Is it possible to change `font-size` of **card-title** and **card image size** according to **different screen sizes** in bootstrap 4. Because when it come for small screen size its too large with.
[](https://i.stack.imgur.com/Ar2tW.png)
Here is my HTML code
```

##### Pixel perfect design
Some quick example text to build on the card title and make up the bulk of the card's At nos hinc posthac, sitientis piros Afros. Petierunt uti sibi concilium totius

##### Design Tageted
Some quick example text to build on the card title and make up the bulk of the card's At nos hinc posthac, sitientis piros Afros. Petierunt uti sibi concilium totius

##### Finalize a FSL
Some quick example text to build on the card title and make up the bulk of the card's At nos hinc posthac, sitientis piros Afros. Petierunt uti sibi concilium totius
```
Here is my CSS code example for how I manage `p{}`.
So Do I have to do same thing for `card-title` or if there a other way of doing it ?
```
@media (min-width: 0px) { p{font-size: 0.7rem;}}
@media (min-width: 576px) { p{font-size: 0.6rem;}}
@media (min-width: 768px) { p {font-size: 0.8rem;}}
@media (min-width: 992px) { p {font-size: 0.8rem;}}
@media (min-width: 1200px) { p {font-size: 1rem;}}
```
And What should I do for images for different screen sizes?
```
.card-img-top{
width: 80px;
height:80px;
}
```
Thanks for your suggestions!<issue_comment>username_1: Well as `rem` works relative to the root element of document i.e. `html`...and by default browsers have
```
html {
font-size: 16px;
}
```
So with this concept try to change only the `html` font value not all elements font...
```css
html {
font: 16px Verdana
}
h1 {
font-size: 3rem;
}
h2 {
font-size: 2rem;
}
@media (max-width:400px) {
html {
font-size: 12px;
}
}
```
```html
foo
===
bar
---
```
A **[Fiddle Link](https://fiddle.jshell.net/bhuwanb9/egko12fa/)** for editing
Upvotes: 0 <issue_comment>username_2: Try this code. But you have to adjust the size of text and title and but this will work for you sure
```css
.card-img-top {
width: 80px;
height: 80px;
}
@media (min-width: 0px) {
.responsive-text {
font-size: 0.7rem;
}
.responsive-title {
font-size: 20px;
}
}
@media (min-width: 576px) {
.responsive-text {
font-size: 0.6rem;
}
.responsive-title {
font-size: 0.7em;
}
}
@media (min-width: 768px) {
.responsive-text {
font-size: 0.8rem;
}
.responsive-title {
font-size: 0.7em;
}
}
@media (min-width: 992px) {
.responsive-text {
font-size: 0.8rem;
}
.responsive-title {
font-size: 0.7em;
}
}
@media (min-width: 1200px) {
.responsive-text {
font-size: 1rem;
}
.responsive-title {
font-size: 0.7em;
}
}
```
```html

Pixel perfect design
Some quick example text to build on the card title and make up the bulk of the card's At nos hinc posthac, sitientis piros Afros. Petierunt uti sibi concilium totius

Design Tageted
Some quick example text to build on the card title and make up the bulk of the card's At nos hinc posthac, sitientis piros Afros. Petierunt uti sibi concilium totius

Finalize a FSL
Some quick example text to build on the card title and make up the bulk of the card's At nos hinc posthac, sitientis piros Afros. Petierunt uti sibi concilium totius
```
Upvotes: 1 |
2018/03/20 | 781 | 3,122 | <issue_start>username_0: I am new to dimensional modeling and have read a lot of material (star-schema, dimension/fact tables, SCD, <NAME>'s - The Data Warehouse Toolkit book, etc). So I have a good conceptual understanding of dimensional modeling constructs but finding it hard to apply to a usecase due to lack of experience and need some guidance.
Consider Twitter for example, I want to design a dimensional model to calculate -
1. DAU (Daily active users) = number of users who logged in and accessed twitter via website or mobile app on a given day
2. MAU (Monthly active users) = number of users who logged in and accessed twitter via website or mobile app in last 30 days including measurement date
3. User engagement = total(clicks + favorites + replies + retweets) on a tweet
These metrics over a period (like month) is the summation of these metrics on each day in that period.
I want to write SQLs to calculate these metrics for every quarter by region (eg: US and rest of world) and calculate year-over-year growth (or decline) in these metrics.
Eg: [](https://i.stack.imgur.com/F4v3G.jpg)
Here are some details that I thought about -
>
> Factless (transaction) fact table for user login activity with grain of 1 row per user per login : **user\_login\_fact\_schema** (user\_dim\_key, date\_dim\_key, user\_location\_dim\_key, access\_method\_dim\_key)
>
>
> Factless (transaction) fact table for user activity with grain of 1 row per user per activity : **user\_activity\_fact\_schema** (user\_dim\_key, date\_dim\_key, user\_location\_dim\_key, access\_method\_dim\_key, post\_key, activity\_type\_key)
>
>
>
Does this sounds correct? How should my model look like? What other dimensions/facts can I add here?
Wonder if I should collapse these 2 tables into 1 and have activity\_type for logins as 'login', but there can be a huge number of logins without any activity so this will skew the data. Am I missing anything else?<issue_comment>username_1: You should keep the data on different tables to make sure you dont mix different grains.
**user\_login\_fact\_schema** can be a materalized view based on **user\_activity\_fact\_schema** filtering for activity type=login and including some logic to exclude duplicates (i.e. one login per user per day, if you are talking about daily active users)
Upvotes: 2 <issue_comment>username_2: Your model seems correct, it answers the questions on the graph you posted.
It could make sense to aggregate those two fact tables into one fact table joined with a "UserAction" dimension, mostly because a login can be interpreted as just another user action.
However, having separate fact tables focused on one metric (or process) may be preferable because it enables you to introduce measures/metrics into the tables, i.e. when your fact tables stop being factless. It also spares you a join with another dimension (UserAction) but that is becoming a bit less relevant these days, where storage and DB processing power are just getting cheaper.
Upvotes: 3 [selected_answer] |
2018/03/20 | 2,892 | 11,461 | <issue_start>username_0: While firing `Intent` `finish` activity i am getting this error
```
03-20 11:05:16.991 8566-8566/com.example.jenya1.ebilling E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.jenya1.ebilling, PID: 8566
java.lang.ClassCastException: droidninja.filepicker.FilePickerDelegate cannot be cast to android.app.Activity
at com.example.jenya1.ebilling.adapter.MaterialAdapter$1$1.onClick(MaterialAdapter.java:142)
at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:166)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6541)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
```
This line causing error
```
((Activity)mContext).finish(); //error
```
calling apapter class
```
private void loadMaterialRequest() {
final ProgressBar progressBar = (ProgressBar) findViewById(R.id.progressBar);
//getting the progressbar
//making the progressbar visible
progressBar.setVisibility(View.VISIBLE);
albumList.clear();
//creating a string request to send request to the url
StringRequest stringRequest = new StringRequest(Request.Method.GET, HttpUrl+token+"&type="+type,
new Response.Listener() {
@Override
public void onResponse(String response) {
//hiding the progressbar after completion
progressBar.setVisibility(View.INVISIBLE);
try {
//getting the whole json object from the response
JSONObject obj = new JSONObject(response);
JSONArray heroArray = obj.getJSONArray("response");
//now looping through all the elements of the json array
for (int i = 0; i < heroArray.length(); i++) {
//getting the json object of the particular index inside the array
JSONObject heroObject = heroArray.getJSONObject(i);
//creating a hero object and giving them the values from json object
Material hero = new Material(
heroObject.getInt("Request\_id"),
heroObject.getString("Site\_name"),
heroObject.getString("User\_id"),
heroObject.getString("Item\_name"),
heroObject.getString("Quantity"),
heroObject.getString("Country"),
heroObject.getString("Request\_date"),
heroObject.getString("Request\_status"));
//adding the hero to herolist
albumList.add(hero);
}
//Log.e("list", String.valueOf(albumList));
//creating custom adapter object
adapter = new MaterialAdapter(getApplicationContext(),albumList);
//adding the adapter to listview
recyclerView.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e("error", String.valueOf(error));
}
});
//creating a request queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//adding the string request to request queue
requestQueue.add(stringRequest);
}
```
I am trying to `Intent` when user click on alert dialog yes button
This is my adapter class:
```
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.example.jenya1.ebilling.MaterialHistoryActivity;
import com.example.jenya1.ebilling.R;
import com.example.jenya1.ebilling.model.HistoryQuotation;
import com.example.jenya1.ebilling.model.Material;
import java.util.ArrayList;
import java.util.List;
/**
* Created by <NAME> on 18/03/18.
*/
public class MaterialAdapter extends RecyclerView.Adapter {
private Context mContext;
private List albumList;
private List lstfavquoteid;
String quote\_id;
ArrayList arryfavquoteid;
Typeface tf;
ArrayList imageserver,imageList;
int count;
int status=0;
private int mExpandedPosition=-1;
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView title,quantity,site,date,note,req\_id,status;
ImageView delete;
LinearLayout lndetail,lnapprove,lnreject,lnoperation;
CardView cdview;
public MyViewHolder(View view) {
super(view);
title = (TextView) view.findViewById(R.id.txttitle);
req\_id = (TextView) view.findViewById(R.id.txtreqid);
quantity = (TextView) view.findViewById(R.id.txtquantity);
date = (TextView) view.findViewById(R.id.txtdate);
site = (TextView) view.findViewById(R.id.txtsite);
note = (TextView) view.findViewById(R.id.txtnotes);
status = (TextView) view.findViewById(R.id.txtstatus);
delete=(ImageView)view.findViewById(R.id.imgmdelete);
lndetail = (LinearLayout) view.findViewById(R.id.lndetails);
lnapprove = (LinearLayout) view.findViewById(R.id.lnapprove);
lnreject = (LinearLayout) view.findViewById(R.id.lnreject);
lnoperation = (LinearLayout) view.findViewById(R.id.lnstatusoperation);
cdview = (CardView) view.findViewById(R.id.card\_view);
}
}
public MaterialAdapter(Context mContext, List albumList) {
this.mContext = mContext;
this.albumList = albumList;
}
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.raw\_material\_history, parent, false);
return new MyViewHolder(itemView);
}
@Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {
arryfavquoteid = new ArrayList();
imageserver = new ArrayList();
tf = Typeface.createFromAsset(mContext.getAssets(), "fonts/HKNova-Medium.ttf");
holder.title.setTypeface(tf);
holder.req\_id.setTypeface(tf);
holder.quantity.setTypeface(tf);
holder.date.setTypeface(tf);
holder.site.setTypeface(tf);
holder.note.setTypeface(tf);
final Material album = albumList.get(position);
holder.title.setText(album.getItem\_name());
holder.req\_id.setText("#"+album.getId());
holder.quantity.setText(album.getQuantity());
holder.site.setText(album.getSite\_id());
String input = album.getRequest\_date();
input = input.replace(" ", "\n");
holder.date.setText(input);
holder.note.setText("Notes : "+album.getCountry());
holder.delete.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// Toast.makeText(mContext, "Delete...", Toast.LENGTH\_SHORT).show();
AlertDialog.Builder alert = new AlertDialog.Builder(
view.getContext());
alert.setTitle("Alert!!");
alert.setMessage("Are you sure to delete record");
alert.setPositiveButton("YES", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
MaterialHistoryActivity.deleterequest(mContext,album.getId());
notifyDataSetChanged();
Intent i=new Intent(mContext,MaterialHistoryActivity.class);
mContext.startActivity(i);
((Activity)mContext).finish(); //error
dialog.dismiss();
}
});
alert.setNegativeButton("NO", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alert.show();
}
});
if (mExpandedPosition == position) {
if(album.getRequest\_status().equals("1"))
{
holder.status.setText("Approved");
holder.status.setVisibility(View.VISIBLE);
holder.status.setTextColor(Color.GREEN);
holder.lnoperation.setVisibility(View.GONE);
}else if(album.getRequest\_status().equals("2"))
{
holder.status.setText("Rejected");
holder.status.setVisibility(View.VISIBLE);
holder.status.setTextColor(Color.RED);
holder.lnoperation.setVisibility(View.GONE);
}
else
{
holder.status.setVisibility(View.GONE);
holder.lnoperation.setVisibility(View.VISIBLE);
}
//creating an animation
Animation slideDown = AnimationUtils.loadAnimation(mContext, R.anim.slide\_down);
//toggling visibility
holder.lndetail.setVisibility(View.VISIBLE);
//adding sliding effect
holder.lndetail.startAnimation(slideDown);
}
else
{
holder.lndetail.setVisibility(View.GONE);
}
holder.cdview.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//getting the position of the item to expand it
mExpandedPosition = position;
//reloding the list
notifyDataSetChanged();
}
});
holder.lnapprove.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// Toast.makeText(mContext, "Approve...", Toast.LENGTH\_SHORT).show();
MaterialHistoryActivity.materialpermission(mContext,album.getId(),1);
}
});
holder.lnreject.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// Toast.makeText(mContext, "Reject...", Toast.LENGTH\_SHORT).show();
MaterialHistoryActivity.materialpermission(mContext,album.getId(),2);
}
});
}
@Override
public int getItemCount() {
return albumList.size();
}
}
```
Any help would be highly appreciated.<issue_comment>username_1: You are passing the Application Context not the Activity Context in your adapter.
getApplicationContext();
Wherever you are passing it pass this or ActivityName.this instead.
Since you are trying to cast the Context you pass (Application not Activity as you thought) to an Activity with
(Activity)
you get this exception because you can't cast the Application to Activity since Application is not a sub-class of Activity.
Upvotes: 1 <issue_comment>username_2: let see:
```
((Activity)mContext).finish();
```
The log say mContext is kind of FilePickerDelegate. So check your Adapter init function. I think you pass context as "this", but "this" reference to FilePickerDelegate. So change it to YourActivity.this ( with activity) or getActivity( in fragment)
Upvotes: 3 [selected_answer]<issue_comment>username_3: Instead of Context use Activity in your adapter. As Activity can be cast to context but context can not be cast to activity.
```
Activity avtivity;
public MaterialAdapter(Activity activity, List albumList) {
this.activity = activity;
this.albumList = albumList;
}
```
In your calling activity when you initialize your adapter Call this adapter like below.
```
new MaterialAdapter(.this, yourList);
```
Upvotes: 0 <issue_comment>username_4: ```
view.getContext().startActivity(new Intent(mContext, MaterialHistoryActivity.class));
```
Upvotes: 0 |
2018/03/20 | 2,698 | 7,916 | <issue_start>username_0: When run my project package, i have getting above title error, after i trying to install that packages using
>
> npm install xml2json
>
>
>
but, i have getting below error only, can you pls give me suggestions or idea to get out from this issue...
```
D:\xampp\htdocs\podio>npm install xml2json
> [email protected] install D:\xampp\htdocs\podio\node_modules\node-expat
> node-gyp rebuild
D:\xampp\htdocs\podio\node_modules\node-expat>if not defined npm_config_node_gyp
(node "C:\Program Files\nodejs\node_modules\npm\bin\node-gyp-bin\\..\..\node_mo
dules\node-gyp\bin\node-gyp.js" rebuild ) else (node "" rebuild )
Warning: Missing input files:
D:\xampp\htdocs\podio\node_modules\node-expat\build\deps\libexpat\..\..\..\deps\
libexpat\version.c
Building the projects in this solution one at a time. To enable parallel build,
please add the "/m" switch.
MSBUILD : error MSB3428: Could not load the Visual C++ component "VCBuild.exe".
To fix this, 1) install the .NET Framework 2.0 SDK, 2) install Microsoft Visua
l Studio 2005 or 3) add the location of the component to the system path if it
is installed elsewhere. [D:\xampp\htdocs\podio\node_modules\node-expat\build\b
inding.sln]
gyp ERR! build error
gyp ERR! stack Error: `C:\Windows\Microsoft.NET\Framework\v4.0.30319\msbuild.exe
` failed with exit code: 1
gyp ERR! stack at ChildProcess.onExit (C:\Program Files\nodejs\node_modules\
npm\node_modules\node-gyp\lib\build.js:276:23)
gyp ERR! stack at emitTwo (events.js:106:13)
gyp ERR! stack at ChildProcess.emit (events.js:191:7)
gyp ERR! stack at Process.ChildProcess._handle.onexit (internal/child_proces
s.js:219:12)
gyp ERR! System Windows_NT 6.3.9600
gyp ERR! command "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodej
s\\node_modules\\npm\\node_modules\\node-gyp\\bin\\node-gyp.js" "rebuild"
gyp ERR! cwd D:\xampp\htdocs\podio\node_modules\node-expat
gyp ERR! node -v v6.11.5
gyp ERR! node-gyp -v v3.4.0
gyp ERR! not ok
npm ERR! Windows_NT 6.3.9600
npm ERR! argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\
node_modules\\npm\\bin\\npm-cli.js" "install" "xml2json"
npm ERR! node v6.11.5
npm ERR! npm v3.10.10
npm ERR! code ELIFECYCLE
npm ERR! [email protected] install: `node-gyp rebuild`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] install script 'node-gyp rebuild'.
npm ERR! Make sure you have the latest version of node.js and npm installed.
npm ERR! If you do, this is most likely a problem with the node-expat package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR! node-gyp rebuild
npm ERR! You can get information on how to open an issue for this project with:
npm ERR! npm bugs node-expat
npm ERR! Or if that isn't available, you can get their info via:
npm ERR! npm owner ls node-expat
npm ERR! There is likely additional logging output above.
npm ERR! Please include the following file with any support request:
npm ERR! D:\xampp\htdocs\podio\npm-debug.log
```
Edit :: 1
After i have installed updated visual studio 2005 to 2012 im getting below error when i have run **npm install xml2json** and npm install xml2json --unsafe-perm,
```
C:\Users\Desktop\New folder\action>npm install xml2json
> [email protected] install C:\Users\Hoffensoft\node_modules\node-expat
> node-gyp rebuild
C:\Users\Hoffensoft\node_modules\node-expat>if not defined npm_config_node_gyp (
node "C:\Program Files\nodejs\node_modules\npm\bin\node-gyp-bin\\..\..\node_modu
les\node-gyp\bin\node-gyp.js" rebuild ) else (node "" rebuild )
Warning: Missing input files:
C:\Users\Hoffensoft\node_modules\node-expat\build\deps\libexpat\..\..\..\deps\li
bexpat\version.c
Building the projects in this solution one at a time. To enable parallel build,
please add the "/m" switch.
xmlparse.c
xmltok.c
xmlrole.c
c:\users\hoffensoft\node_modules\node-expat\deps\libexpat\lib\siphash.h(201): w
arning C4244: 'initializing' : conversion from '__int64' to 'char', possible lo
ss of data (..\..\..\deps\libexpat\lib\xmlparse.c) [C:\Users\Hoffensoft\node_mo
dules\node-expat\build\deps\libexpat\expat.vcxproj]
win_delay_load_hook.cc
expat.vcxproj -> C:\Users\Hoffensoft\node_modules\node-expat\build\Release\\l
ibexpat.lib
node-expat.cc
win_delay_load_hook.cc
C:\Users\Hoffensoft\node_modules\nan\nan.h(75): fatal error C1060: compiler is
out of heap space (..\node-expat.cc) [C:\Users\Hoffensoft\node_modules\node-exp
at\build\node_expat.vcxproj]
gyp ERR! build error
gyp ERR! stack Error: `C:\Windows\Microsoft.NET\Framework\v4.0.30319\msbuild.exe
` failed with exit code: 1
gyp ERR! stack at ChildProcess.onExit (C:\Program Files\nodejs\node_modules\
npm\node_modules\node-gyp\lib\build.js:276:23)
gyp ERR! stack at emitTwo (events.js:106:13)
gyp ERR! stack at ChildProcess.emit (events.js:191:7)
gyp ERR! stack at Process.ChildProcess._handle.onexit (internal/child_proces
s.js:219:12)
gyp ERR! System Windows_NT 6.3.9600
gyp ERR! command "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodej
s\\node_modules\\npm\\node_modules\\node-gyp\\bin\\node-gyp.js" "rebuild"
gyp ERR! cwd C:\Users\Hoffensoft\node_modules\node-expat
gyp ERR! node -v v6.11.5
gyp ERR! node-gyp -v v3.4.0
gyp ERR! not ok
npm WARN enoent ENOENT: no such file or directory, open 'C:\Users\Hoffensoft\pac
kage.json'
npm WARN Hoffensoft No description
npm WARN Hoffensoft No repository field.
npm WARN Hoffensoft No README data
npm WARN Hoffensoft No license field.
npm ERR! Windows_NT 6.3.9600
npm ERR! argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\
node_modules\\npm\\bin\\npm-cli.js" "install" "xml2json"
npm ERR! node v6.11.5
npm ERR! npm v3.10.10
npm ERR! code ELIFECYCLE
npm ERR! [email protected] install: `node-gyp rebuild`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] install script 'node-gyp rebuild'.
npm ERR! Make sure you have the latest version of node.js and npm installed.
npm ERR! If you do, this is most likely a problem with the node-expat package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR! node-gyp rebuild
npm ERR! You can get information on how to open an issue for this project with:
npm ERR! npm bugs node-expat
npm ERR! Or if that isn't available, you can get their info via:
npm ERR! npm owner ls node-expat
npm ERR! There is likely additional logging output above.
npm ERR! Please include the following file with any support request:
npm ERR! C:\Users\Hoffensoft\Desktop\New folder\action\npm-debug.log
```
Thanks in advance, <NAME><issue_comment>username_1: I have solved this. If you notice this part of the command `else (node "" rebuild )` what I think is happening is that it is incorrectly evaluating `if not defined npm_config_node_gyp` as `false` and trying to run nothing instead of node-gyp. What you need to do is define your `npm_config_node_gyp` variable. You can do this like so:
`export npm_config_node_gyp=` remember that Windows will need double backslashes. For me, it looked like this:
`export npm_config_node_gyp=C:\\Users\\781990\\AppData\\Roaming\\nvm\\v6.11.0\\node_modules\\node-gyp`
Edit:
There is another step after my fix. When executing my code, the expat bindings were missing. To fix it, add the bin folder and node-gyp executable to the `npm_config_node_gyp` variable and run `node-gyp rebuild` in the `node_modules\node-expat` folder. e.g.
`export npm_config_node_gyp=C:\\Users\\781990\\AppData\\Roaming\\nvm\\v6.11.0\\node_modules\\node-gyp\\bin\\node-gyp.js`
`cd node_modules\node-expat`
`node-gyp rebuild`
Upvotes: 0 <issue_comment>username_2: I have solved this
Use this command `npm install xml2json-light`
and change `let parser = require('xml2json');` to `let parser = require('xml2json-light');`
It worked for me
Upvotes: 2 |
2018/03/20 | 595 | 2,520 | <issue_start>username_0: Unable to connect to Informix db2 from Fluent Migrator (.net/c#) on the local instance. (Windows 10 running on AWS EC2)
Getting this after invoking the migrator executable:
[+] Beginning Transaction
!!! ERROR [HY011] [IBM] CLI0126E Operation invalid at this time. SQLSTATE=HY011
I am able to connect to the db instance via the dbaccess cli utility.
I also tried to remove all the actual migration sql statements and scripts from the migration solution and the same error happens if trying to run a totally empty migration, so the issue is likely a connection or transaction issue.
Any ideas will be appreciated. Thanks.
\_\_
More detials as requested from responses:
The connection info is this:
```
```
Both the database and the application that connects to it are located on the same machine, which is hosted on AWS. So the connection it's trying to make is to the DB on the same box.<issue_comment>username_1: What you mean by Informix DB2, the Informix and DB2 are two separate database servers. Information from the error text snippet I am assuming you are using driver with DRDA protocol (likely IBM DB2 .NET or DB2 CLI).If so make sure you have enabled DRDA port on the Informix server and connect to that port.If the Informix server you are using is being provisioned from AWS, it only allow secured/encrypted connections. Then you may need do use SSL based connection after SSL setup. If you are using DRDA protocol how did you get DBACCESS working, there is lot of confusion here
Upvotes: 0 <issue_comment>username_1: Then the Driver you are using is a DB2.NET driver that can connect to Informix server by using DRDA protocol.Make sure the port number you are using is DRDA port specified on the SQLHOST file of Informix.Unless you are using Entity Framework, I would encourage to use the Informix native .NET driver. When you use the Informix native driver it uses Informix native protocol, which is SQLI. The native driver is efficient and better supported compared to the DRDA one.When you use the native driver make sure the port you are connecting is configured for SQLI.
Upvotes: 1 <issue_comment>username_2: After putting extensive logging inside the calling application the problem was narrowed down to the BeginTaansaction call. The error was caused by the absence of transaction logging on the database.
The issue was fixed by adding transaction logging to DB definition e.g.
```
CREATE DATABASE %database% WITH BUFFERED LOG;
```
Upvotes: 1 [selected_answer] |
2018/03/20 | 377 | 1,439 | <issue_start>username_0: Sorry if this is a really obvious question, but I've been trying to find something like it in a number of places, and I'm not sure if it just doesn't exist or if I'm using the wrong language to describe what I need.
If, for example, I have a number of TextViews in different parts of my activity, and I want all of them to open the same activity when clicked on, how would I do this without specifying each of their IDs individually in an if statement in the Java? In HTML I would use a class attribute to group them together, but I can't find a similar feature in XML.
Thanks for your help!<issue_comment>username_1: Write your xml code of EditText as follows
```
```
And in Java file write method
```
public void editTextClick(View v) {
// does something very interesting
Log.d("MainActivity","EditText pressed");
}
```
I hope this will help you,
Happy Coding
Upvotes: 0 <issue_comment>username_2: If your intention is to prevent code repetition and tedious code repetition, then one way is to use [ButterKnife](http://jakewharton.github.io/butterknife/). Something link below would work:
```
@OnClick({R.id.view_id1, R.id.view_id2, R.id.view_id3})
public void onClick(View view) {
// TODO: Handle click
}
```
Or, as the other answer suggests, you can have `android:onClick` attribute on each of those views which points to same method in Java code.
Upvotes: 2 [selected_answer] |
2018/03/20 | 384 | 1,549 | <issue_start>username_0: Hello Am trying to create many to many relationship but I failed. I have two table requests\_table and Users\_table and the relationship is many to many I introduce associative table called request\_user with attribute of user\_id, request\_id and user\_reqId(primary key). what I want is to submit data(user\_id and request\_id) to the associative entity when user request for anything?. help please....<issue_comment>username_1: Many-to-many relations are slightly more complicated than hasOne and hasMany relationships. An example of such a relationship is a user with many roles, where the roles are also shared by other users. For example, many users may have the role of "Admin". To define this relationship, three database tables are needed: users, roles, and role\_user. The role\_user table is derived from the alphabetical order of the related model names, and contains the user\_id and role\_id columns.
Many-to-many relationships are defined by writing a method that returns the result of the belongsToMany method.
Happy coding:)-
Upvotes: 2 [selected_answer]<issue_comment>username_2: You should try this:
**request\_tbl.php**
```
public function users() {
return $this->belongsToMany(User::class, 'request_user');
}
```
**user.php**
```
public function requests()
{
return $this->belongsToMany(RequestTbl::class, 'request_user');
}
```
**Controller**
```
$request_tbl = new requests_table();
$users = $request->users;
$request_tbl->users()->sync($users);
```
Upvotes: 0 |
2018/03/20 | 473 | 1,512 | <issue_start>username_0: I've installed `lm-sensors`, but when I run `pwmconfig` command as root, it throws an error:
```
/usr/sbin/pwmconfig: There are no pwm-capable sensor modules installed
```
My laptop is an MSI Gs63VR Stealth Pro core Intel i7 CPU
Thank you!<issue_comment>username_1: A simple search for the error message yielded several hits on Google. All of the top hits are from before this question was posted.
[This guide on AskUbuntu](https://askubuntu.com/a/46135/52781) may be helpful, or [this one](https://iandw.net/2014/10/12/fancontrol-under-ubuntu-14-04-resolving-usrsbinpwmconfig-there-are-no-pwm-capable-sensor-modules-installed/).
Likely the issue you're having can be solved with a linux kernel option. Add this to your Grub command-line: `acpi_enforce_resources=lax`
```
sudo sed -E -i 's/(GRUB_CMDLINE_LINUX_DEFAULT=.+)"$/\1 acpi_enforce_resources=lax"/' /etc/default/grub
sudo update-grub
```
then reboot.
Upvotes: 3 <issue_comment>username_2: On my MSI GF76 Katana 11SC-483X there are no pwm-capable sensors detected in linux.
This tool helped me to control fans: <https://github.com/dmitry-s93/MControlCenter#installation-from-the-archive>
Added this tool to Startup Applications on my Ubuntu 22.04 (used custom curve) - it works like a charm!
It works much better than MSI Control Center on windows. May be I'm doing something wrong but my manual tests for windows MSI Control Center have bad results (custom curve) - fans sometimes speed up, sometimes not.
Upvotes: 0 |
2018/03/20 | 555 | 1,755 | <issue_start>username_0: Hi I have a code and I didn't make any change, but I am getting `Type mismatch error`. It was working properly previously.
Code :
```
Private Sub UserForm_Initialize()
Dim r As Integer
Dim c As Integer
Me.ComboBox1.RowSource = "Intro!A3:A" & Range("A" & Rows.Count).End(xlUp).Row
r = Application.Match("c", Columns(1), 0)
c = Application.Match("cc", Rows(1), 0)
TextBox1.Value = Cells(r, c).Value
TextBox2.Value = Cells(r, c + 1).Value
TextBox3.Value = Cells(r, c + 2).Value
TextBox4.Value = Cells(r, c + 3).Value
End Sub
```
Ran using `f8` through code found error when reaching here :
```
c = Application.Match("cc", Rows(1), 0)
```
Objective of this line to find match in first row<issue_comment>username_1: I suppose there is no 'cc' in first row. In this case `Application.Match` returns an Error object which can't be assigned to an integer.
Upvotes: 2 [selected_answer]<issue_comment>username_2: When using `Match` you should always prepare your code for the scenario where `Match` failed to find the value (or String) you are looking for.
You can do that by using:
```
If Not IsError(Application.Match("cc", Columns(1), 0)) Then
```
***Modified Code***
```
Dim r As Variant
Dim c As Variant
Me.ComboBox1.RowSource = "Intro!A3:A" & Range("A" & Rows.Count).End(xlUp).Row
If Not IsError(Application.Match("c", Columns(1), 0)) Then
r = Application.Match("c", Columns(1), 0)
Else
' in case "c" is not found
MsgBox "critical error finding 'c'"
End If
If Not IsError(Application.Match("cc", Columns(1), 0)) Then
c = Application.Match("cc", Columns(1), 0)
Else
' in case "cc" is not found
MsgBox "critical error finding 'cc'"
End If
```
Upvotes: 2 |
2018/03/20 | 950 | 2,787 | <issue_start>username_0: I am trying to get the first element value from array of character containing float.
The character array size is 7, and it's containing two float elements hence size can be assumed 8. I want to get only the first element ignoring anything about 2nd value.
Here is my code-
```
int main()
{
char cArr[7] = {2.0085,4.52};
char* charPtr = nullptr;
charPtr=cArr;
cout<<"char[0] :"<<*charPtr<
```
Here is my output:
```none
g++ b.cpp -o b.exe -std=c++0x
b.cpp: In function 'int main()':
b.cpp:6:29: warning: narrowing conversion of '2.0085000000000002e+0' from 'double' to 'char' inside { } [-Wnarrowing]
char cArr[7] = {2.0085,4.52};
^
b.cpp:6:29: warning: narrowing conversion of '4.5199999999999996e+0' from 'double' to 'char' inside { } [-Wnarrowing]
./b.exe
char[0] :
char[0] :1.43773e-42
```
I am expecting:
```none
char[0] :2.0085
```
Any suggestions with the code change?<issue_comment>username_1: >
> Any suggestions with the code change?
>
>
>
You actually want this:
```
float cArr[2] = { 2.0085, 4.52 };
float *fPtr = cArr;
```
Upvotes: 0 <issue_comment>username_2: It seems like what you are trying to make your array hold this:
```
float fArr[2] = { 2.0085, 4.52 };
char cArr[7];
memcpy(cArr, fArr, 7);
```
The code you gave does not give you access to the bytes of a float's representation. `memcpy` will.
However, it's still not allowed to read a `float` out of the char array through pointer casting. That is a violation of strict aliasing, and results in undefined behavior. To read four bytes from the array and treat them as the representation of a float, you need a second call to `memcpy`.
Upvotes: 1 <issue_comment>username_3: If I understand your question correct, you have a text string with comma separated decimal point values. Like: "2.0085,4.52"
Now you want to extract the first decimal point value (i.e. "2.0085") and convert it to a float (i.e. like `float f = 2.0085`).
There are two major problems with your code:
1) The text string initialization is wrong and the char array is too short.
2) You can't do the conversion by casting pointers. You need to call special function that does the conversion (e.g. `atof`).
One way to do it is like this:
```
#include
#include
int main()
{
// Initialize text string with comma seperated decimal point values
char cArr[32] = "2.0085,4.52";
// Extract the first decimal point text string
char\* p = std::strtok(cArr, ",");
std::cout << "First text string: " << p << std::endl;
// Convert the text representation to a float representation
float f = std::atof(p);
std::cout << "First float value: " << f << std::endl;
return 0;
}
```
Output:
```
First text string: 2.0085
First float value: 2.0085
```
Upvotes: 0 |
2018/03/20 | 852 | 2,564 | <issue_start>username_0: Hi Here I'm comparing to double values equal or not. but its returing always false even if both Double values are Equal.
```
let latestlogoValue = log(Double(125))/log(5.0)
let latestlogIntValue:Int = Int(latestlogoValue)
print(latestlogoValue)
print(Double(latestlogIntValue))
print(Double(latestlogIntValue) == Double(latestlogoValue)) //Always returning false
```<issue_comment>username_1: That is happened because of Double type's precision
If we print your values
```
print(String(format: "a float number: %.55f", latestlogoValue))
print(String(format: "a float number: %.55f", Double(latestlogIntValue)))
```
we'll see difference in values:
```
a float number: 3.00000000000000044408920985006261616945266723632812500
a float number: 3.00000000000000000000000000000000000000000000000000000
```
So the values are different, if you need to compare float or double values use comparing them with some precision
Upvotes: 0 <issue_comment>username_2: Double or float value comparison with == sign, will not give you the exact answer. You may think that the two values are equal to each other but they are slightly different. Doubles are stored differently in memory. You can test it by printing as String like below-
```
print(String(format: "%.20f", Double(latestlogoValue))) //3.00000000000000044409
print(String(format: "%.20f", Double(latestlogIntValue))) //3.00000000000000000000
```
So you can update your comparison function as
```
func isDoubleEqual(_ first: Double, _ second: Double) -> Bool {
return fabs(first - second) < Double.ulpOfOne
}
```
Upvotes: 2 <issue_comment>username_3: Look at the precesion values are different they are not identical.
Just print them out.
```
print(Double(latestlogoValue).debugDescription) // 3.0000000000000004
print(Double(latestlogIntValue).debugDescription) // 3.0
```
And you are comparing the same which results always false.
```
print(Double(latestlogIntValue) == Double(latestlogoValue))
// 3.0000000000000004 == 3.0 results false obvious
```
Upvotes: 0 <issue_comment>username_4: ```
let latestlogoValue = log(Double(125))/log(5.0)
let latestlogIntValue:Int = Int(latestlogoValue)
print(latestlogoValue)
print(Double(latestlogIntValue))
print(Double(latestlogIntValue) == Double(latestlogoValue))
```
Here Double(latestlogIntValue) & Double(latestlogoValue)) are getting different values . Compare the values with Int you will get true
```
print(Int(latestlogIntValue) == Int(latestlogoValue)) // true
```
Upvotes: 0 |
2018/03/20 | 1,460 | 5,594 | <issue_start>username_0: I have a web application that is developed in jquery and spring mvc...all is working perfectly...but now I want to use React JS in my application...i want to create a form in react js and send ajax request to my spring mvc controller...I know how to do it with jquery but not with react js....kindly tell me a way to create a form and send a request to the spring mvc controler....
this is my controller method where I want to get request...
```
@RequestMapping(value = "/saveuser", method = RequestMethod.POST)
public @ResponseBody String Save(/*@Valid Users user, BindingResult result,*/HttpServletRequest request, Model model,
@RequestParam(required = false) Boolean reverseBeforeSave) {
String userName = request.getParameter("username");
String password = request.getParameter("password");
String firstName = request.getParameter("first_name");
String lastName = request.getParameter("last_name");
System.out.println("save method");
String[] roleNames = request.getParameterValues("roles");
userService.saveUserandRoles(userName, password, firstName, lastName, roleNames);
return "success";
}
```
I went through different solutions in StackOverflow and have searched on google but I am not getting any proper result.<issue_comment>username_1: You need to send XMLHttp Request to server from your react.js application.
example:
```
var http = new XMLHttpRequest();
var url = "http:///saveuser";
var params = "param1=param1Value¶m2=param2Value";
http.open("POST", url, true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.onreadystatechange = function() {
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
}
http.send(params);
```
you can also use some beautiful libraries like [axios](https://github.com/axios/axios), [fetch](https://github.com/github/fetch), [superagent](https://github.com/visionmedia/superagent), [request](https://github.com/request/request) etc.
Upvotes: 2 <issue_comment>username_2: One of the later APIs usually used for communicating is **`fetch`**, that is also slowly becoming a browser standard.
`fetch` API Doc
---------------
<https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API>
`fetch` Usage
=============
More at: <https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch>
```
fetch('http://example.com/movies.json', { // optional fetch options
body: JSON.stringify(data), // you may send any data, encoded as you wish. shall match content-type
cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
credentials: 'same-origin', // include, same-origin, *omit
headers: {
'content-type': 'application/json'
},
method: 'POST', // *GET, POST, PUT, DELETE, etc.
mode: 'cors', // no-cors, cors, *same-origin
redirect: 'follow', // *manual, follow, error
referrer: 'no-referrer', // *client, no-referrer
})
.then(function(response) {
// manipulate response object
// check status @ response.status etc.
return response.json(); // parses json
})
.then(function(myJson) {
// use parseed result
console.log(myJson);
});
```
Crossbrowser compatibility
==========================
Since browsers are not always uniform, you might consider using a polyfill, like `whatwg-fetch` @ <https://github.com/github/fetch>
Form in react with fetch
========================
```
import React from 'react';
export class ReactForm extends React.Component {
constructor(props) {
super(props);
this.state = {
username: '',
password: '',
first_name: '',
last_name: '',
};
}
onSubmit(e) {
e.preventDefault();
fetch('http://example.com/movies.json', {
body: JSON.stringify(this.state),
cache: 'no-cache',
credentials: 'same-origin',
headers: {
'content-type': 'application/json'
},
method: 'POST',
mode: 'cors',
redirect: 'follow',
referrer: 'no-referrer',
})
.then(function (response) {
console.log(response);
if (response.status === 200) {
alert('Saved');
} else {
alert('Issues saving');
}
// you cannot parse your "success" response, since that is not a valid JSON
// consider using valid JSON req/resp pairs.
// return response.json();
});
}
render() {
return (
this.setState({username: e.target.value})}/>
this.setState({password: e.target.value})}/>
this.setState({first\_name: e.target.value})}/>
this.setState({last\_name: e.target.value})}/>
Submit
);
}
}
```
Upvotes: 2 <issue_comment>username_3: Install axios
```
$ npm install axios
```
Import axios
```
import axios from 'axios';
```
Example GET request
```
axios.get('https://api.example.com/')
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
```
Example POST request
```
var body = {
firstName: 'testName',
lastName: 'testLastName'
};
axios.post('https://api.example.com/', body)
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
```
Upvotes: 3 <issue_comment>username_4: Use one of this: axios,fetch or XMLHttpRequest. Project Axios has stoped from owner, fetch use more codes than axios and the last one is complex
Upvotes: 0 |
2018/03/20 | 312 | 1,237 | <issue_start>username_0: I cannot see Hive as a listed data source in power BI . Is there a way to connect Hive database with power bi desktop. also is there any limitation?<issue_comment>username_1: Hive ODBC Driver should be installed and configured in the system in order to connect with Power BI. Once ODBC Driver is successfully configured then connect using below way in Power BI.
Home -> Get Data -> More -> Other -> ODBC
Upvotes: 1 <issue_comment>username_2: Have a look here [Create Hive ODBC data source](https://learn.microsoft.com/en-us/azure/hdinsight/hadoop/apache-hadoop-connect-excel-hive-odbc-driver#create-hive-odbc-data-source)
The hive sample table Hive table comes with all HDInsight clusters.
Sign in to Power BI Desktop.
Click the Home tab, click Get Data from the External data, and then select More.
1. [connect data image](https://i.stack.imgur.com/Z6Szw.png)
2. From the Get Data pane, click Other from the left, click ODBC from the right, and then click Connect on the bottom.
3. From the From ODBC pane, select the data source name you created in the last section, and then click OK.
4. From the Navigator pane, expand ODBC->HIVE->default, select hive sampletable, and then click Load.
Thanks.
Upvotes: 0 |
2018/03/20 | 1,766 | 6,398 | <issue_start>username_0: I'm supposed to show different time formats according to the language in my app. When the device is English the user should get the time format like this:
>
> 18 March 2018, 2.30 pm
>
>
>
But when the user's device is German he should get the time format like this:
>
> 18.03.2018, 14:30 Uhr
>
>
>
Is there any way to do this by formatting the time `String` with `SimpleDateFormat` or am I supposed to do this in another way and if so, how am I able to do this?<issue_comment>username_1: I didn't think it would work, but it did. Just put the format you like into the string xml file for me it was:
```
dd MMMM yyyy, hh.mm a
dd.MM.yyyy, HH:mm
```
Then use it in the SDF like this:
```
SimpleDateFormat fmtOut = new SimpleDateFormat(context.getString(R.string.date_time_format), Locale.getDefault());
```
for the "Uhr" at the end of the german format i added a placeholder String that looks like this:
```
%s
%s Uhr
```
and i return the formated date with the String.format() method:
```
return String.format(context.getString(R.string.date_time_string), fmtOut.format(date));
```
Upvotes: 2 [selected_answer]<issue_comment>username_2: Try this code snippet. hope it will solve the issue.
```
java.sql.Date date1 = new java.sql.Date((new Date()).getTime());
SimpleDateFormat formatNowDay = new SimpleDateFormat("dd");
SimpleDateFormat formatNowYear = new SimpleDateFormat("yyyy");
SimpleDateFormat sdf12 = new SimpleDateFormat("hh:mm aa");
SimpleDateFormat sdf24 = new SimpleDateFormat("HH:mm");
SimpleDateFormat germanSdf = new SimpleDateFormat("dd.MM.yyyy");
String currentDay = formatNowDay.format(date1);
String currentYear = formatNowYear.format(date1);
String time12 = sdf12.format(date1);
String time24 = sdf24.format(date1);
String germanTime = germanSdf.format(date1);
Calendar mCalendar = Calendar.getInstance();
String currentMonth = mCalendar.getDisplayName(Calendar.MONTH, Calendar.LONG, Locale.getDefault());
String engTime = currentDay+" "+currentMonth+" "+currentYear+", "+time12;
String germanFormat = germanTime+", "+time24+" Uhr";
```
Upvotes: 0 <issue_comment>username_3: One alternative is to use a [`java.text.DateFormat`](https://developer.android.com/reference/java/text/DateFormat.html):
```
DateFormat df = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, Locale.ENGLISH);
```
The date and time styles (first and second parameters) can be either `SHORT`, `MEDIUM`, `LONG` or `FULL`. And you can use `Locale.getDefault()` to get the device's default language, if you want.
I'm not sure which combination of styles give what you want - all of them gave me different outputs and none gave me the one you described.
That's because locale specific formats are embeeded in the JVM, and I'm not sure how it varies among different API levels and devices.
If the solution above works, then it's fine. Otherwise, an alternative is to make specific patterns per locale:
```
// get device's locale
Locale locale = Locale.getDefault();
String pattern = "";
// check language
if ("en".equals(locale.getLanguage())) {
// english
pattern = "dd MMMM yyyy, h.mm a";
} else if ("de".equals(locale.getLanguage())) {
// german
pattern = "dd.MM.yyyy, HH:mm 'Uhr'";
} else {
pattern = // use some default pattern for other languages?
}
SimpleDateFormat sdf = new SimpleDateFormat(pattern, locale);
String formattedDate = sdf.format(new Date());
```
One detail is that, in my JVM, the AM/PM symbols for English locale are in uppercase, so you may want to adjust it by doing:
```
// change AM/PM to am/pm (only for English)
if ("en".equals(locale.getLanguage())) {
formattedDate = formattedDate.toLowerCase();
}
```
java.time API
-------------
In API level 26, you can use the [java.time API](https://developer.android.com/reference/java/time/package-summary.html). For lower levels, there's a [nice backport](https://github.com/JakeWharton/ThreeTenABP), with the same classes and functionalities.
This is much better to work with. The code might look similar, but the classes themselves solves [lots of internal issues of the old API](https://eyalsch.wordpress.com/2009/05/29/sdf/).
You can first try to get JVM's localized patterns and see if they match your output:
```
Locale locale = Locale.getDefault();
FormatStyle style = FormatStyle.MEDIUM;
String pattern = DateTimeFormatterBuilder.getLocalizedDateTimePattern(style, style, IsoChronology.INSTANCE, locale);
DateTimeFormatter fmt = DateTimeFormatter.ofPattern(pattern, locale);
```
Or do the same as above:
```
// get device's locale
Locale locale = Locale.getDefault();
String pattern = "";
// check language
if ("en".equals(locale.getLanguage())) {
// english
pattern = "dd MMMM yyyy, h.mm a";
} else if ("de".equals(locale.getLanguage())) {
// german
pattern = "dd.MM.yyyy, HH:mm 'Uhr'";
} else {
pattern = ""; // use some default pattern?
}
DateTimeFormatter fmt = DateTimeFormatter.ofPattern(pattern, locale);
String formattedDate = LocalDateTime.now().format(fmt);
```
In my tests, I've got the same problem of having uppercase AM/PM for English. You can solve this by calling `toLowerCase()` as above, but this API also allows you to create a more flexible formatter.
And the formatters are thread-safe (while `SimpleDateFormat` isn't), so you could create a static map of formatters based on the language and reuse them as many times you want:
```
// map of formatters
Map formatterMap = new HashMap<>();
// English formatter
Map customAmPmSymbols = new HashMap<>();
customAmPmSymbols.put(0L, "am");
customAmPmSymbols.put(1L, "pm");
DateTimeFormatter f = new DateTimeFormatterBuilder()
// date/time
.appendPattern("dd MMMM yyyy, h.mm ")
// custom AM/PM symbols (lowercase)
.appendText(ChronoField.AMPM\_OF\_DAY, customAmPmSymbols)
// create formatter
.toFormatter(Locale.ENGLISH);
// add to map
formatterMap.put("en", f);
// German formatter
formatterMap.put("de", DateTimeFormatter.ofPattern("dd.MM.yyyy, HH:mm 'Uhr'", Locale.GERMAN));
// get device's locale
Locale locale = Locale.getDefault();
DateTimeFormatter fmt = formatterMap.get(locale.getLanguage());
if (fmt != null) {
String formattedDate = LocalDateTime.now().format(fmt);
}
```
Upvotes: 0 |
2018/03/20 | 1,148 | 4,262 | <issue_start>username_0: I'm trying to do random write (Benchmark test) to a file using multiple threads (pthread). Looks like if I comment out `mutex lock` the created file size is less than actual as if Some writes are getting lost (always in some multiple of chunk size). But if I keep the mutex it's always exact size.
Is my code have a problem in other place and mutex is not really required ([as suggested](https://stackoverflow.com/a/49257771/1647320) by @evan ) or mutex is necessary here
```
void *DiskWorker(void *threadarg) {
FILE *theFile = fopen(fileToWrite, "a+");
....
for (long i = 0; i < noOfWrites; ++i) {
//pthread_mutex_lock (&mutexsum);
// For Random access
fseek ( theFile , randomArray[i] * chunkSize , SEEK_SET );
fputs ( data , theFile );
//Or for sequential access (in this case above 2 lines would not be here)
fprintf(theFile, "%s", data);
//sequential access end
fflush (theFile);
//pthread_mutex_unlock(&mutexsum);
}
.....
}
```<issue_comment>username_1: You definitely need a mutex because you are issuing several different file commands. The underlying file subsystem can't possibly know how many file commands you are going to call to complete your whole operation.
So you need the mutex.
In your situation you may find you get better performance putting the mutex *outside* the loop. The reason being that, otherwise, switching between threads may cause excessive skipping between different parts of the disk. Hard disks take about `10ms` to move the read/write head so that could potentially slow things down a lot.
So it might be a good idea to benchmark that.
Upvotes: 2 [selected_answer]<issue_comment>username_2: You are opening a file using "append mode". According to C11:
>
> Opening a file with append mode (`'a'` as the first character in the
> mode argument) causes all subsequent writes to the file to be forced
> to the then current end-of-file, regardless of intervening calls to
> the `fseek` function.
>
>
>
C standard does not specified how exactly this should be implemented, but on POSIX system this is usually implemented using `O_APPEND` flag of [`open`](https://linux.die.net/man/3/open) function, while flushing data is done using function `write`. Note that `fseek` call in your code should have no effect.
I think POSIX requires this, as it describes how redirecting output in append mode (`>>`) is done by [the shell](http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_07_03):
>
> Appended output redirection shall cause the file whose name results
> from the expansion of word to be opened for output on the designated
> file descriptor. The file is opened as if the open() function as
> defined in the System Interfaces volume of POSIX.1-2008 was called
> with the O\_APPEND flag. If the file does not exist, it shall be
> created.
>
>
>
And since most programs use `FILE` interface to send data to `stdout`, this probably *requires* `fopen` to use `open` with `O_APPEND` and `write` (and not functions like `pwrite`) when writing data.
So if on your system `fopen` with `'a'` mode uses `O_APPEND` and flushing is done using `write` and your kernel and filesystem correctly implement `O_APPEND` flag, using mutex should have no effect as writes [do not intervene](https://linux.die.net/man/3/write):
>
> If the `O_APPEND` flag of the file status flags is set, the file
> offset shall be set to the end of the file prior to each write and no
> intervening file modification operation shall occur between changing
> the file offset and the write operation.
>
>
>
Note that not all filesystems support this behavior. Check [this](https://stackoverflow.com/a/35256561/1143634) answer.
---
As for my answer to your previous question, my suggestion was to remove mutex as it should have no effect on the size of a file (and it didn't have any effect on my machine).
Personally, I never really used `O_APPEND` and would be hesitant to do so, as its behavior might not be supported at some level, plus its behavior is weird on Linux (see "bugs" section of [`pwrite`](https://linux.die.net/man/2/pwrite)).
Upvotes: 2 |
2018/03/20 | 514 | 1,665 | <issue_start>username_0: I'm trying to port my code on google Colaboratory.
It's weird that even I did
```
!pip3 install xml
```
in my code.
It still require me to install lxml.
Does anybody have the problem??
```
****Requirement already satisfied: lxml in /usr/local/lib/python3.6/dist-packages****
---------------------------------------------------------------------------
ImportError Traceback (most recent call last)
in ()
48 #df = financial\_statement(2017,3)
...
/usr/local/lib/python3.6/dist-packages/pandas/io/html.py in \_parser\_dispatch(flavor)
695 else:
696 if not \_HAS\_LXML:
--> 697 raise ImportError("lxml not found, please install it")
698 return \_valid\_parsers[flavor]
699
\*\*ImportError: lxml not found, please install it\*\*
\*\*code:\*\*
!pip3 install lxml
import requests
import pandas as pd
import numpy as np
import keras
import lxml
import html5lib
from bs4 import BeautifulSoup
f\_states= pd.read\_html('https://simple.wikipedia.org/wiki/List\_of\_U.S.\_states')
```<issue_comment>username_1: After install use pip or apt, you need to restarting the runtime using “Runtime / Restart runtime…”
Upvotes: 3 <issue_comment>username_2: I was also trying on google colab. i have tried every thing for 2 hours finally this worked for me.
```
url = 'https://simple.wikipedia.org/wiki/List_of_U.S._states'
pd.read_html(url, flavor='html5lib`)
```
Official document suggests:
>
> The default of None tries to use lxml to parse and if that fails it falls back on bs4 + html5lib.
>
>
> <http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_html.html>
>
>
>
Upvotes: 1 |
2018/03/20 | 332 | 1,141 | <issue_start>username_0: I am trying to write a WPF application using c# and the with the help of [Prism 6.3 library](https://github.com/PrismLibrary/Prism). I watched all available tutorials on [pluralsight.com](https://app.pluralsight.com/library/search?q=prism) for Prism by @BrianLagunas . But not of them show how to do data validation.
I need to add input validation before I submit the data to the database.
How can I add validation rule, and how can I check if the form is valid before I save the data to the database?<issue_comment>username_1: After install use pip or apt, you need to restarting the runtime using “Runtime / Restart runtime…”
Upvotes: 3 <issue_comment>username_2: I was also trying on google colab. i have tried every thing for 2 hours finally this worked for me.
```
url = 'https://simple.wikipedia.org/wiki/List_of_U.S._states'
pd.read_html(url, flavor='html5lib`)
```
Official document suggests:
>
> The default of None tries to use lxml to parse and if that fails it falls back on bs4 + html5lib.
>
>
> <http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_html.html>
>
>
>
Upvotes: 1 |
2018/03/20 | 1,244 | 4,957 | <issue_start>username_0: I need to collect some data from a user, through bot that uses microsoft bot framework and store those data in a Azure database? anyone can help with proper code examples and links? Thanks in advance.
***Requirements***: need to ask from a particular user, his nsme, email address and phone number and store them in a data base.<issue_comment>username_1: Yes, you can use a bot to collect information from a user. On the development of bot exists the concept of form which allow us to create a flow of question to the user. The SQL side will be managed as we are used to do with C#, a connection string along with an INSERT statement. [Here](https://learn.microsoft.com/en-us/bot-framework/dotnet/bot-builder-dotnet-formflow) you will find documentation about forms. These are two samples using forms: [(1)](https://github.com/Microsoft/BotBuilder-Samples/tree/master/CSharp/demo-ContosoFlowers) and [(2)](https://github.com/Microsoft/BotBuilder-Samples/tree/master/CSharp/core-MultiDialogs).
Basically you create an entity with the fields you need to collect data. With this we create the form flow and with the entity the bot will ask for the information to the user. It will show options and present a final summary.
The following code shows you how to connect to SQL Azure Database using C#:
```
using System;
using System.Data.SqlClient; // System.Data.dll
//using System.Data; // For: SqlDbType , ParameterDirection
namespace csharp_db_test
{
class Program
{
static void Main(string[] args)
{
try
{
var cb = new SqlConnectionStringBuilder();
cb.DataSource = "your_server.database.windows.net";
cb.UserID = "your_user";
cb.Password = "<PASSWORD>";
cb.InitialCatalog = "your_database";
using (var connection = new SqlConnection(cb.ConnectionString))
{
connection.Open();
Submit_Tsql_NonQuery(connection, "2 - Create-Tables",
Build_2_Tsql_CreateTables());
Submit_Tsql_NonQuery(connection, "3 - Inserts",
Build_3_Tsql_Inserts());
Submit_Tsql_NonQuery(connection, "4 - Update-Join",
Build_4_Tsql_UpdateJoin(),
"@csharpParmDepartmentName", "Accounting");
Submit_Tsql_NonQuery(connection, "5 - Delete-Join",
Build_5_Tsql_DeleteJoin(),
"@csharpParmDepartmentName", "Legal");
Submit_6_Tsql_SelectEmployees(connection);
}
}
catch (SqlException e)
{
Console.WriteLine(e.ToString());
}
Console.WriteLine("View the report output here, then press any key to end the program...");
Console.ReadKey();
}
```
[Here](https://learn.microsoft.com/en-us/azure/sql-database/sql-database-design-first-database-csharp) you will find more information about how to connect to SQL Azure from C#.
Upvotes: -1 <issue_comment>username_2: >
> just need to ask from a particular user, his nsme, email address and phone number and store them in a data base
>
>
>
To achieve this requirement, you can refer to the following sample code to collect user information.
```
[Serializable]
public class RootDialog : IDialog
{
string name;
string email;
string phone;
public Task StartAsync(IDialogContext context)
{
context.Wait(MessageReceivedAsync);
return Task.CompletedTask;
}
private async Task MessageReceivedAsync(IDialogContext context, IAwaitable result)
{
var activity = await result as Activity;
if (activity.Text.ToLower().Contains("ok"))
{
PromptDialog.Text(
context: context,
resume: ResumeGetName,
prompt: "Please share your name",
retry: "Please try again."
);
}
else
{
context.Done(this);
}
//context.Wait(MessageReceivedAsync);
}
public async Task ResumeGetName(IDialogContext context, IAwaitable Username)
{
string uname = await Username;
name = uname;
PromptDialog.Text(
context: context,
resume: ResumeGetEmail,
prompt: "Please share your Email",
retry: "Please try again."
);
}
public async Task ResumeGetEmail(IDialogContext context, IAwaitable UserEmail)
{
string uemail = await UserEmail;
email = uemail;
PromptDialog.Text(
context: context,
resume: ResumeGetPhone,
prompt: "Please share your Phone Number",
retry: "Please try again."
);
}
public async Task ResumeGetPhone(IDialogContext context, IAwaitable mobile)
{
string response = await mobile;
phone = response;
//in this Resume handler, you can save the data that you collected from user into your sql database
await context.PostAsync($"your name:{name}, email:{email}, phonenumber: {phone}");
context.Done(this);
}
}
```
**Test result:**
[](https://i.stack.imgur.com/8brGu.png)
Upvotes: 1 [selected_answer] |
2018/03/20 | 671 | 2,042 | <issue_start>username_0: ```
#include
#include
int main() {
char a[] = "1234:once:echo hello";
int i = 0;
while(i < strlen(a)) {
if(a[i] == ':') {
break;
}
i++;
}
a = a + i;
printf("%s\n", a);
}
```
This program just iterates through string a until it hits ':', then I want to a to become ":once:echo hello" which I tried doing by adding i. Not sure why it isn't working I remember something similar work in the past.<issue_comment>username_1: There are a couple of issues with your example code. First you are not incrementing the value of `i` inside the while loop which is creating an infinite loop. As Jonathan has suggested in the comments you'd be better off using a `for` loop instead of a `while` loop.
Secondly, you can't increment an array in C. When I try to compile your example using `clang` I get `error: array type 'char [21]' is not assignable`
You can achieve your goal by doing the pointer arithmetic in the `printf` statement rather than trying to save the new value back into `a`.
```
#include
#include
int main() {
char a[] = "1234:once:echo hello";
int i;
for (i = 0; i < strlen(a); i++) {
if(a[i] == ':') {
break;
}
}
printf("%s\n", a + i);
}
```
Upvotes: 1 <issue_comment>username_2: If I understand you simply want to walk through your text and locate the first `':'` and then print the remainder of `a` from that point until the end, you can do it quite easily with the index generated by your loop, e.g.
```
#include
#include
int main( void) {
char a[] = "1234:once:echo hello";
int i = 0;
while (a[i]) { /\* loop over each char \*/
if (a[i] == ':') /\* 1st semi-colon found \*/
break; /\* exit loop \*/
i++; /\* increment index \*/
}
printf ("%s\n", a + i); /\* output string from index \*/
}
```
**Example Use/Output**
```
$ ./bin/walkarray
:once:echo hello
```
Upvotes: 2 [selected_answer]<issue_comment>username_3: ```
int i = 0;
while ( a[i] && a[i] != ":") i++; // loop ends when a[i] is NULL or a[i] is ":"
char *b = &a[i];
printf("%s", b);
```
Upvotes: 0 |
2018/03/20 | 798 | 3,160 | <issue_start>username_0: I am creating a formGroup Validation based on a toggle value
```
public toggle:boolean=false;
ngOnInit(): void {
this.formGroup = this.formBuilder.group({
formArray: this.formBuilder.array([
this.formBuilder.group({
toggleFormCtrl: [this.toggle, null],
fnameFormCtrl: ['', this.checkInputs.bind(this)],
lnameFormCtrl: ['', this.checkInputs.bind(this)],
addressFormCtrl: ['', this.checkMiInput.bind(this)]
}),
])
});
}
checkInputs(c: FormControl) {
if (this.toggle) {
return c.value === '' ? null : {
checkinputs: {
valid: false
}
};
} else {
return c.value ? null : {
checkinputs: {
valid: false
}
};
}
}
checkMiInput(c: FormControl) {
if (this.toggle) {
return c.value ? null : {
checkMiInput: {
valid: false
}
};
} else {
return c.value === '' ? null : {
checkMiInput: {
valid: false
}
};
}
}
```
Based on the toggle value I want to validate the form. When toggle value is `true`, the form should validate formControl `addressFormCtrl` and when the toggle is false, it should validate `fnameFormCtrl` and `lnameFormCtrl`
My code isn't working well. What am I missing?<issue_comment>username_1: Transform toogle into a observable as Subject, now you suscribe to the new subject. In the suscription you can use the method named **setValidators** that replace you form control validators with you want.
<https://angular.io/api/forms/AbstractControl#setValidators>
Example, toogle.suscription(value => this.updateValidators(value));
Upvotes: 2 <issue_comment>username_2: I turn on/off my validation with a method like this:
```
setNotification(notifyVia: string): void {
const phoneControl = this.customerForm.get('phone');
if (notifyVia === 'text') {
phoneControl.setValidators(Validators.required);
} else {
phoneControl.clearValidators();
}
phoneControl.updateValueAndValidity();
}
```
This code uses `setValidators` to set the validator for the control and `clearValidators` to clear the validators for the control.
In your case, you would need to turn it off and on for several controls.
Notice also the `updateValueAndValidity`. This is required to ensure that the validators are actually changed.
This code is called from the `ngOnInit` method with code like this:
```
this.customerForm.get('notification').valueChanges
.subscribe(value => this.setNotification(value));
```
If the user changes the `notification` radio button, the code in the `subscribe` method is executed and calls `setNotification`.
Upvotes: 4 [selected_answer]<issue_comment>username_3: You need an function with:
```
this.form['controls']['view'].setValidators([Validators.required]);
this.form['controls']['view'].patchValue(yourValue);
```
I use this code if get cetain properties from the backed based on input.
I noticed when set the validator it need to patch the value to otherwise it not update for some reason.
Upvotes: 0 |
2018/03/20 | 494 | 1,591 | <issue_start>username_0: I have a form in my blade with 2 dates for user to select like:
```html
{{csrf\_field()}}
From
To
Filter Date
```
So in my controller function I have did this:
```
$dateFrom = [$request->from];
$dateTo = [$request->to];
```
Then I tried to `dd();` the value of `datefrom` and `dateto` and I am able to show it, but now I want to know how can I display this 2 values back in my blade file?
In my return view I have `compact()` the 2 values also.<issue_comment>username_1: you can use laravel form model binding to show selected values in laravel blade.
or
```
```
here $to is your returning date from controller to view in compact
Upvotes: 1 <issue_comment>username_2: Try and update your output method from the comment from the post above to:
...
```
$dateFrom = $request->from;
$dateTo = $request->to;
$data = [
'companyID' => $companyID,
'match' => $match,
'noAnswer' => $noAnswer,
'missing' => $missing,
'email' => $email,
'pdf' => $pdf,
'image' => $image,
'video' => $video,
'text' => $text,
'totalMedia' => $totalMedia,
'dateFrom' => $dateFrom,
'dateTo' => $dateTo
];
return view('AltHr.Chatbot.viewgraph', $data);
```
...
Since you stated this is live loading the request to the page you may want to add
`$request->flash();`
to top beginning of the receiving method.
Upvotes: 0 <issue_comment>username_3: Firstly use Carbon in your Controller
```
use Carbon\Carbon;
```
then do this in your blade file
```
```
you can also format the date if you like to
```
```
Upvotes: 1 |
2018/03/20 | 1,421 | 5,862 | <issue_start>username_0: I want user to select date from `date picker dialogue` and use the date selected.
I have made a date picker dialogue, only problem is when dialogue opens the date shows 1/1/1990, then user have to come to present year. I want to open the dialogue box with the `today's` date.
Below is my code-
```
public class MyClass extends AppCompatActivity {
Calendar cal;
Button selectDate;
DatePickerDialog datePicker;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_trains_bw_stations);
selectDate=findViewById(R.id.select_date);
selectDate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
cal=Calendar.getInstance();
int day=cal.get(Calendar.DAY_OF_MONTH);
int month=cal.get(Calendar.MONTH);
int year=cal.get(Calendar.YEAR);
datePicker=new DatePickerDialog(TrainsBwStations.this, new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int mYear, int mMonth, int mDayOfMonth) {
Log.d("Rail","Year-"+mYear);
Log.d("Rail","Month-"+mMonth);
Log.d("Rail","Day-"+mDayOfMonth);
}
},day,month,year);
datePicker.show();
}
});
}
}
```<issue_comment>username_1: ```
Calendar c = Calendar.getInstance();
int mYear = c.get(Calendar.YEAR);
int mMonth = c.get(Calendar.MONTH);
int mDay = c.get(Calendar.DAY_OF_MONTH);
DatePickerDialog dialog = new DatePickerDialog(Class.this, Class.this,
mYear, mMonth, mDay);
dialog.show();
```
Upvotes: 1 <issue_comment>username_2: Try this:
```
Calendar c = Calendar.getInstance();
year = c.get(Calendar.YEAR);
month = c.get(Calendar.MONTH);
day = c.get(Calendar.DAY_OF_MONTH);
// set current date into datepicker
datePicker.init(year, month, day, null);
```
Upvotes: 0 <issue_comment>username_3: Please use this
```
Calendar c = Calendar.getInstance();
SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy");
String date = df.format(c.getTime());
datePickerDialog.updateDate(Integer.parseInt(date.split("/")[2]),Integer.parseInt(date.split("/")[1]),Integer.parseInt(date.split("/")[0]));
datePickerDialog.setTitle("");
datePickerDialog.show();
```
Upvotes: 0 <issue_comment>username_4: try below code
```
public class MyClass extends AppCompatActivity {
Calendar cal;
Button selectDate;
DatePickerDialog datePicker;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_trains_bw_stations);
selectDate=findViewById(R.id.select_date);
selectDate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
cal = Calendar.getInstance();
final DatePickerDialog.OnDateSetListener dateA = new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
// TODO Auto-generated method stub
cal.set(Calendar.YEAR, year);
cal.set(Calendar.MONTH, monthOfYear);
cal.set(Calendar.DAY_OF_MONTH, dayOfMonth);
}
};
new DatePickerDialog(MyClass.this, dateA, cal.get(Calendar.YEAR),
cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH)).show();
}
});
}
}
```
Upvotes: 1 [selected_answer]<issue_comment>username_5: Here your get Date in String format later you can convert in as per your need
```
//Defining it in Class Activity before onCreate.. or you can define in onCreate..
private Calendar calendar;
private int year, month, day;
String formattedDate, toDate, fromDate, pickUpdate;
//Inside onCreate...
calendar = Calendar.getInstance();
year = calendar.get(Calendar.YEAR);
month = calendar.get(Calendar.MONTH);
day = calendar.get(Calendar.DAY_OF_MONTH);
//on button click or any view click.. paste the below code..
toTV = (TextView) findViewById(R.id.toTV);
toTV.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//have a look at **to** after YourActivity.this
DatePickerDialog datePickerDialog = new DatePickerDialog(YourActivity.this, to, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
//This is used to set the date to select current and future date not the past dates..uncomment if you want to use it...
//datePickerDialog.getDatePicker().setMinDate(System.currentTimeMillis());
datePickerDialog.show();
}
});
//outside oncreate which is a calender pop-up...
//Here **to** is object which called in onClick of dateBT
DatePickerDialog.OnDateSetListener to = new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
String day = dayOfMonth + "";
if (dayOfMonth < 9) {
day = "0" + dayOfMonth;
}
String monthString = (String.valueOf(month + 1));
if (month < 9) {
monthString = "0" + monthString;
}
formattedDate = String.valueOf(year) + "/" + monthString
+ "/" + day;
dateTV.setText(formattedDate);
date = formattedDate;
}
};
```
Upvotes: 0 |
2018/03/20 | 1,317 | 5,042 | <issue_start>username_0: Is there any header files or extension that I can use to make multi thread on Borland 5.02?
I want to make a program that animates two lines going in different speed, in an infinite loop.
Something like this
```
#include
#include
#include
#include
void linesmov(int seconds);
main()
{
// Thread 1
linesmov(5);
//Thread 2
linesmov(30);
}
void linesmov(int mseconds){
int i=0;
while (true){
i=i+1;
clrscr(); // Or system("cls"); If you may...
gotoxy(i,15); cout << "\_\_\_\_||\_\_\_\_||\_\_\_\_";
Sleep(mseconds);
if (i>115){ i=0; }
}
}
```
Yes.. I know that people are going to go and say, GET A NEW COMPILER,
My school uses old compiler as a "standard" on scoring, so please bear with me.<issue_comment>username_1: ```
Calendar c = Calendar.getInstance();
int mYear = c.get(Calendar.YEAR);
int mMonth = c.get(Calendar.MONTH);
int mDay = c.get(Calendar.DAY_OF_MONTH);
DatePickerDialog dialog = new DatePickerDialog(Class.this, Class.this,
mYear, mMonth, mDay);
dialog.show();
```
Upvotes: 1 <issue_comment>username_2: Try this:
```
Calendar c = Calendar.getInstance();
year = c.get(Calendar.YEAR);
month = c.get(Calendar.MONTH);
day = c.get(Calendar.DAY_OF_MONTH);
// set current date into datepicker
datePicker.init(year, month, day, null);
```
Upvotes: 0 <issue_comment>username_3: Please use this
```
Calendar c = Calendar.getInstance();
SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy");
String date = df.format(c.getTime());
datePickerDialog.updateDate(Integer.parseInt(date.split("/")[2]),Integer.parseInt(date.split("/")[1]),Integer.parseInt(date.split("/")[0]));
datePickerDialog.setTitle("");
datePickerDialog.show();
```
Upvotes: 0 <issue_comment>username_4: try below code
```
public class MyClass extends AppCompatActivity {
Calendar cal;
Button selectDate;
DatePickerDialog datePicker;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_trains_bw_stations);
selectDate=findViewById(R.id.select_date);
selectDate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
cal = Calendar.getInstance();
final DatePickerDialog.OnDateSetListener dateA = new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
// TODO Auto-generated method stub
cal.set(Calendar.YEAR, year);
cal.set(Calendar.MONTH, monthOfYear);
cal.set(Calendar.DAY_OF_MONTH, dayOfMonth);
}
};
new DatePickerDialog(MyClass.this, dateA, cal.get(Calendar.YEAR),
cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH)).show();
}
});
}
}
```
Upvotes: 1 [selected_answer]<issue_comment>username_5: Here your get Date in String format later you can convert in as per your need
```
//Defining it in Class Activity before onCreate.. or you can define in onCreate..
private Calendar calendar;
private int year, month, day;
String formattedDate, toDate, fromDate, pickUpdate;
//Inside onCreate...
calendar = Calendar.getInstance();
year = calendar.get(Calendar.YEAR);
month = calendar.get(Calendar.MONTH);
day = calendar.get(Calendar.DAY_OF_MONTH);
//on button click or any view click.. paste the below code..
toTV = (TextView) findViewById(R.id.toTV);
toTV.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//have a look at **to** after YourActivity.this
DatePickerDialog datePickerDialog = new DatePickerDialog(YourActivity.this, to, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
//This is used to set the date to select current and future date not the past dates..uncomment if you want to use it...
//datePickerDialog.getDatePicker().setMinDate(System.currentTimeMillis());
datePickerDialog.show();
}
});
//outside oncreate which is a calender pop-up...
//Here **to** is object which called in onClick of dateBT
DatePickerDialog.OnDateSetListener to = new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
String day = dayOfMonth + "";
if (dayOfMonth < 9) {
day = "0" + dayOfMonth;
}
String monthString = (String.valueOf(month + 1));
if (month < 9) {
monthString = "0" + monthString;
}
formattedDate = String.valueOf(year) + "/" + monthString
+ "/" + day;
dateTV.setText(formattedDate);
date = formattedDate;
}
};
```
Upvotes: 0 |
2018/03/20 | 1,599 | 6,136 | <issue_start>username_0: I have Ubuntu 16.04 , lampp server, PHP version 7.x i am trying to install latest version of OctoberCMS.
I have done everything from setting up database to setting up proper file permissions in my local server.
But I am keep getting the error saying
```
The operation timed out. Please increase the server's timeout and try again.
```
Below is the screenshot what I am getting when I am trying to install OctoberCMS.
[](https://i.stack.imgur.com/KSXmt.png)
Here is the **Apache** link they are referring in error page - <https://httpd.apache.org/docs/2.4/mod/core.html#timeout>
I went through with this and did some research and went through with this thread <https://github.com/octobercms/october/issues/3176>
Here I found saying to increase **fastcgi\_read\_timeout** but I guess its only for **nginx** server as I m yet to find in **apache** to increase the **fastcgi\_read\_timeout** in apache server.
Do I need to install **nginx** ?
Can someone guide me the proper way to solve this issue ?
>
> PS: The thing is, I had clicked on "Try Again" button after sometime and installation was successfully done but I just wonder why the error came and should I resolve this from server side instead of ignoring this error as everything seems to be working now.
>
>
> I also found out this <https://askubuntu.com/a/781195>.
>
>
> Here they are suggesting to update `config.default.php` (/usr/share/phpmyadmin/libraries/config.default.php) file, where you can find out like this line below:
>
>
> `$cfg['ExecTimeLimit'] = 300;`
>
>
> To Make it to
>
>
> `$cfg['ExecTimeLimit'] = 0;`
>
>
> Do I need to follow this to be able to make installation work error free next time or is there any other workaround?
>
>
><issue_comment>username_1: ```
Calendar c = Calendar.getInstance();
int mYear = c.get(Calendar.YEAR);
int mMonth = c.get(Calendar.MONTH);
int mDay = c.get(Calendar.DAY_OF_MONTH);
DatePickerDialog dialog = new DatePickerDialog(Class.this, Class.this,
mYear, mMonth, mDay);
dialog.show();
```
Upvotes: 1 <issue_comment>username_2: Try this:
```
Calendar c = Calendar.getInstance();
year = c.get(Calendar.YEAR);
month = c.get(Calendar.MONTH);
day = c.get(Calendar.DAY_OF_MONTH);
// set current date into datepicker
datePicker.init(year, month, day, null);
```
Upvotes: 0 <issue_comment>username_3: Please use this
```
Calendar c = Calendar.getInstance();
SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy");
String date = df.format(c.getTime());
datePickerDialog.updateDate(Integer.parseInt(date.split("/")[2]),Integer.parseInt(date.split("/")[1]),Integer.parseInt(date.split("/")[0]));
datePickerDialog.setTitle("");
datePickerDialog.show();
```
Upvotes: 0 <issue_comment>username_4: try below code
```
public class MyClass extends AppCompatActivity {
Calendar cal;
Button selectDate;
DatePickerDialog datePicker;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_trains_bw_stations);
selectDate=findViewById(R.id.select_date);
selectDate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
cal = Calendar.getInstance();
final DatePickerDialog.OnDateSetListener dateA = new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
// TODO Auto-generated method stub
cal.set(Calendar.YEAR, year);
cal.set(Calendar.MONTH, monthOfYear);
cal.set(Calendar.DAY_OF_MONTH, dayOfMonth);
}
};
new DatePickerDialog(MyClass.this, dateA, cal.get(Calendar.YEAR),
cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH)).show();
}
});
}
}
```
Upvotes: 1 [selected_answer]<issue_comment>username_5: Here your get Date in String format later you can convert in as per your need
```
//Defining it in Class Activity before onCreate.. or you can define in onCreate..
private Calendar calendar;
private int year, month, day;
String formattedDate, toDate, fromDate, pickUpdate;
//Inside onCreate...
calendar = Calendar.getInstance();
year = calendar.get(Calendar.YEAR);
month = calendar.get(Calendar.MONTH);
day = calendar.get(Calendar.DAY_OF_MONTH);
//on button click or any view click.. paste the below code..
toTV = (TextView) findViewById(R.id.toTV);
toTV.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//have a look at **to** after YourActivity.this
DatePickerDialog datePickerDialog = new DatePickerDialog(YourActivity.this, to, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
//This is used to set the date to select current and future date not the past dates..uncomment if you want to use it...
//datePickerDialog.getDatePicker().setMinDate(System.currentTimeMillis());
datePickerDialog.show();
}
});
//outside oncreate which is a calender pop-up...
//Here **to** is object which called in onClick of dateBT
DatePickerDialog.OnDateSetListener to = new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
String day = dayOfMonth + "";
if (dayOfMonth < 9) {
day = "0" + dayOfMonth;
}
String monthString = (String.valueOf(month + 1));
if (month < 9) {
monthString = "0" + monthString;
}
formattedDate = String.valueOf(year) + "/" + monthString
+ "/" + day;
dateTV.setText(formattedDate);
date = formattedDate;
}
};
```
Upvotes: 0 |
2018/03/20 | 1,011 | 2,777 | <issue_start>username_0: I apologize if my question is stupid. I just stared learning regex a few hours back.
I am trying to extract all hashtags
* until it reaches a space or newline
* cannot have more than two # in a row
Special characters are allowed until it reaches a space/a hastag/newline
Here is my current regex: `\#{1}(\S|\N)`
I tried changing it to `\#{1}.+(\S|\N)` because i assumed the `.+` will allow it to keep matching until it reaches a new line or space
```
======================TESTHASH========================
#3!x_j@`(/l3W#qfSnl#6R7x1b,jBb0p#Oq/:o#!tH3AITK^Yyp#B,
#qwe#%#T &#v#v#N###O###2#` `S}^&9 #M # Aa23%2##p#?#w#a
#123#9#Z a%h#&#C###;###? a#u#g#Q#r#8# #a#A#l#p#r#b#}#c
#R#M#(#p###K###l###1###b 2#D\'>.w/Y_2 sha2&2{] #4x$D~kR
#lbTb1k3# #Dlo ## #j# #W H#tjsR.Lzkc #B*xt&nFty?il#jp
#>p8BTU2###PW!aB###z###-VM (s82hdk#T 8sUJWfuy2#-#f~fh)
#d{jyi|^ofYD#q)!#special~!@$%^&*()#_+`-=[];\',./?><\":}{
======================TESTHASH========================
</code></pre>
```<issue_comment>username_1: I made a few changes to your regex to get it match these:
[](https://i.stack.imgur.com/9p3oo.png)
This is the regex:
```
\#.*?(?=\s|\n|\#|$)
```
Changes I've made:
* used a lazy "zero or more" quantifier `*?`. This means that it will keep matching until `(?=\s|\n|\#|$)` is not true, whereas with a greedy quantifier, it will match all the way to the end of the line, then backtracks until `(?=\s|\n|\#|$)` is true.
* removed `{1}`, this is unnecessary
* added more options to the end. I've added `\#` and `$`. They are characters that when encountered, should stop the match.
* used a lookahead. This avoids getting another `#` into the match.
[Demo](https://regex101.com/r/dxnSGx/1)
Upvotes: 2 <issue_comment>username_2: ```
\#[^\s\#]*(\s|\#)
```
Matches a # followed by any number of chars other than whitespace and # which is followed by a whitespace or #
This should work
Upvotes: 0 <issue_comment>username_3: **How about `#[^#\s\n]+`?**
* It matches all hashtags.
* It stops at spaces and newlines.
* It doesn't match two hashtags in a row. (This sentence is a bit ambiguous; is `##` two hashtags of length zero, or zero hashtags? `#[^#\s\n]*` is equivalent to username_1's regex, but without the look-ahead. `#[^#\s\n]+` additionally requires that hashtags don't have zero characters after them.)
* All characters allowed after hashtag except hashtag, space and newline.
**This is what `#[^#\s\n]+` matches:**
[](https://i.stack.imgur.com/BSRwH.png)
It seems to secretly spell out "NICE"; I wonder if this is an exercise and you're using StackOverflow to think for you? :-)
Upvotes: 3 [selected_answer] |
2018/03/20 | 685 | 2,215 | <issue_start>username_0: i want to redirect directly into 9apps using [this link](https://mx-player.en.9apps.com/) and then 9apps display applcation which is takes from above link is it possible like
```
Intent i = new Intent(Intent.ACTION_VIEW);
i.setPackage("com.mobile.indiaapp");
i.setData(Uri.parse("https://mx-player.en.9apps.com/");
context.startActivity(i
);
```
please help me<issue_comment>username_1: I made a few changes to your regex to get it match these:
[](https://i.stack.imgur.com/9p3oo.png)
This is the regex:
```
\#.*?(?=\s|\n|\#|$)
```
Changes I've made:
* used a lazy "zero or more" quantifier `*?`. This means that it will keep matching until `(?=\s|\n|\#|$)` is not true, whereas with a greedy quantifier, it will match all the way to the end of the line, then backtracks until `(?=\s|\n|\#|$)` is true.
* removed `{1}`, this is unnecessary
* added more options to the end. I've added `\#` and `$`. They are characters that when encountered, should stop the match.
* used a lookahead. This avoids getting another `#` into the match.
[Demo](https://regex101.com/r/dxnSGx/1)
Upvotes: 2 <issue_comment>username_2: ```
\#[^\s\#]*(\s|\#)
```
Matches a # followed by any number of chars other than whitespace and # which is followed by a whitespace or #
This should work
Upvotes: 0 <issue_comment>username_3: **How about `#[^#\s\n]+`?**
* It matches all hashtags.
* It stops at spaces and newlines.
* It doesn't match two hashtags in a row. (This sentence is a bit ambiguous; is `##` two hashtags of length zero, or zero hashtags? `#[^#\s\n]*` is equivalent to username_1's regex, but without the look-ahead. `#[^#\s\n]+` additionally requires that hashtags don't have zero characters after them.)
* All characters allowed after hashtag except hashtag, space and newline.
**This is what `#[^#\s\n]+` matches:**
[](https://i.stack.imgur.com/BSRwH.png)
It seems to secretly spell out "NICE"; I wonder if this is an exercise and you're using StackOverflow to think for you? :-)
Upvotes: 3 [selected_answer] |
2018/03/20 | 609 | 1,838 | <issue_start>username_0: Unable to build my project. showing error message
Error:(2, 0) Plugin with id 'io.fabric' not found.
Error:(62, 13) Failed to resolve: com.crashlytics.sdk.android:crashlytics:2.7.1
Steps followed
[](https://i.stack.imgur.com/aEP3m.png)
<https://firebase.google.com/docs/crashlytics/upgrade-from-crash-reporting>
[](https://i.stack.imgur.com/TmyPM.png)
<https://codelabs.developers.google.com/codelabs/firebase-android/#14>
If anyone have any idea please share your idea.
Thanks in advance.<issue_comment>username_1: make some change in dependency ..
apply plugin: 'io.fabric'
```
compile 'com.google.firebase:firebase-core:11.8.0'
compile('com.crashlytics.sdk.android:crashlytics:2.9.1@aar') {
transitive = true
}
apply plugin: 'com.google.gms.google-services'
```
project lavel dependency
```
repositories {
maven {
url 'https://maven.fabric.io/public'
}
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.0.0'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
classpath 'com.google.gms:google-services:3.2.0'
classpath 'io.fabric.tools:gradle:1.25.1'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
```
Upvotes: 1 <issue_comment>username_2: I had the same problem, the line that gave me the error was this one:
>
> classpath 'io.fabric.tools:gradle:1.24.4'
>
>
>
When I switched to
>
> classpath 'io.fabric.tools:gradle:1.25.4'
>
>
>
it compiled correctly
I've found the updated lines of code here:
<https://firebase.google.com/docs/crashlytics/get-started>
Upvotes: 0 |
2018/03/20 | 841 | 2,721 | <issue_start>username_0: Apologies if my question is not that clear. I'm new to Django and it's my first time to ask questions here as I can't seem to find solutions to my problem.
I've done research on how to use multiple models in Django template and succeeded to do so, however, one of my requirement is that each trucker in the list should show corresponding number of registered truck units but I can't seem to do this.
The output should be like this:
```
Truckers List
Registered Trucker Number of units
Trucker #1 10
Trucker #2 5
...
Trucker #n 3
```
Should you have suggestions I highly appreciate it. Im using Django version 2.0.1 and Python 3.6 on Windows if that's relevant.
Here is my code:
***models.py***
```
class Trucker(models.Model):
name = models.CharField(max_length=50)
def __str__(self):
return self.name
class TruckUnit(models.Model):
plate_number = models.CharField(max_length=7)
trucker = models.ForeignKey(Trucker, related_name='truckunits', on_delete=models.CASCADE)
def __str__(self):
return self.plate_number
```
***views.py***
```
class TruckerList(generic.ListView):
model = Trucker
context_object_name = 'trucker_list'
queryset = Trucker.objects.all().order_by('name')
template_name = 'trip_monitor/trucker_list.html'
def get_context_data(self. **kwargs):
context = super(TruckerList, self).get_context_data(**kwargs)
context['units'] = TruckUnit.objects.all()
context['truckers'] = self.queryset
return context
```
***urls.py***
```
from django.urls import path
from . import views
urlpatterns = [
path('truckers/', views.TruckerList.as_view(), name='trucker_list'),
]
```
***trucker\_list.html***
```
{% extends 'base.html' %}
{% block content %}
### Trucker List
{% if trucker_list %}
| Registered Truckers | Number of units |
| --- | --- |
{% for trucker in trucker\_list %}
| {{ trucker.name }} | {{ units.count }} |
{% endfor %}
{% else %}
No registered truckers yet
{% endif %}
{% endblock %}
```<issue_comment>username_1: just put the query inside your get\_context\_data, create a new context value like:
>
>
> >
> > context['products'] = Products.objects.all()
> >
> >
> >
>
>
>
and you will have the queryset at your template.
I hope it help you
Upvotes: 0 <issue_comment>username_2: You can do
```
from django.db.models import Count
```
Then
```
queryset = Trucker.objects.all().annotate(Count("truckunits")).order_by('name')
```
Then in template
```
{% for trucker in trucker_list %}
| {{ trucker.name }} | {{ trucker.truckunits\_\_count }} |
{% endfor %}
```
Upvotes: 3 [selected_answer] |
2018/03/20 | 1,027 | 4,295 | <issue_start>username_0: I'm trying to solve the order problem I'm facing with several approaches that I found here on [SO](https://stackoverflow.com/questions/42886224/preserve-order-of-results-when-operating-asynchronously-on-a-list?rq=1) without a success.
I have a method, where I'm loading some data for an array of [leaflet](http://leafletjs.com/index.html) layers:
```
private loadSelectedTileLayersCapabilities(): void {
let tempTileLayer;
this.selectedTileLayerIds.forEach(
(selectedTileLayer: string) => {
tempTileLayer = this.getTileLayerById(selectedTileLayer);
this.capabilitiesService.getTileLayerDimensions(tempTileLayer.url, tempTileLayer.name, tempTileLayer.id)
.subscribe(
dimensions => this.displayNewTileLayer(dimensions)
);
}
);
}
```
And then I have a method, where the `http` call is happening:
```
public getTileLayerDimensions(urlToFormat: string, tileLayerName: string, tileLayerId: string): Observable {
const capabilitiesUrl = `serviceUrl`;
return this.httpClient.get(capabilitiesUrl, {responseType: "text"})
.map(res => {
// Doing stuff with data
return dataForLayer;
});
}
```
The problem is, the `displayNewTileLayer(dimensions)` method is called in random order. Is there a way to preserve the order in which the items were stored in
`selectedTileLayerIds` array?<issue_comment>username_1: Since the http-calls are asynchronous, the responses may *not* arrive in the same order the requests were made. What you could do is to create a list of requests, create a [forkJoin](https://www.learnrxjs.io/operators/combination/forkjoin.html) and wait for all responses to resolve. You can then call the `displayNewTileLayer(dimensions)`-method for all responses.
Here is an example
```
const httpCalls = []; // store the requests here
for (let i = 0; i < 3; i++) {
httpCalls.push(this.http.get('someUrl').map(response => response));
}
forkJoin(httpCalls).subscribe(res => {
// all responses completed. returns an array of data (one for each response).
console.log('res', res);
});
```
In you case, this code may work: (code not tested, and you may have to import the forkJoin operator in your code)
`import { forkJoin } from 'rxjs/observable/forkJoin';`
```
private loadSelectedTileLayersCapabilities(): void {
let tempTileLayer;
let requests = []:
this.selectedTileLayerIds.forEach(
(selectedTileLayer: string) => {
tempTileLayer = this.getTileLayerById(selectedTileLayer);
const request = this.capabilitiesService.getTileLayerDimensions(tempTileLayer.url, tempTileLayer.name, tempTileLayer.id)
requests.push(request);
}
);
forkJoin(requests).subscribe(res => {
res.forEach(dimension => this.displayNewTileLayer(dimension));
})
}
```
Upvotes: 4 [selected_answer]<issue_comment>username_2: I would consider to use the `concat` operator.
Your code would look like the following
```
private loadSelectedTileLayersCapabilities(): void {
let tempTileLayer;
let concatObs;
this.selectedTileLayerIds.forEach(
(selectedTileLayer: string) => {
tempTileLayer = this.getTileLayerById(selectedTileLayer);
const httpCall = this.capabilitiesService.getTileLayerDimensions(tempTileLayer.url, tempTileLayer.name, tempTileLayer.id);
if (!concatObs) {
concatObs = httpCall);
} else {
concatObs.concat(httpCall);
}
}
);
concatObs.subscribe(
dimensions => this.displayNewTileLayer(dimensions)
);
}
```
This way concatObs emits in the same order as the array `selectedTileLayersIds`. You should consider though if it is possible to move the sequencing logic to the server, i.e. have a service that receives an array of ids (`selectedTileLayersIds`) and returns and array of dimensions. In this way you would reduce the network traffic and avoid having a chain of sequential synchronous http calls.
Upvotes: 2 |
2018/03/20 | 453 | 1,349 | <issue_start>username_0: <https://www.elastic.co/guide/en/elasticsearch/reference/current/nested.html>
Consider:
```
PUT my_index
{
"mappings": {
"_doc": {
"properties": {
"user": {
"type": "nested"
}
}
}
}
}
PUT my_index/_doc/1
{
"group" : "fans",
"user" : [
{
"first" : "John",
"last" : "Smith"
},
{
"first" : "Alice",
"last" : "White"
}
]
}
```
When I run a painless script like:
```
ctx._source.user.add({
"first" : "Foo",
"last" : "Bar"
})
```
It is not working. I tried but cannot find any related documents or discussion started by other.<issue_comment>username_1: <https://www.elastic.co/guide/en/elasticsearch/reference/5.4/modules-scripting-painless-syntax.html#painless-maps>
You can create a map like `['first': 'Foo', 'last': 'Bar', 'sthElse': 100]` then add it.
So:
```
ctx._source.user.add([
"first" : "Foo",
"last" : "Bar"
])
```
Please note that map in painless can be mixed type.
Upvotes: 5 [selected_answer]<issue_comment>username_2: ```
POST my_index/_doc/1/_update
{
"script": {
"lang": "painless",
"inline": "ctx._source.user.add(params.object)",
"params": {
"object": {
"first" : "Foo",
"last" : "Bar"
}
}
}
}
```
Upvotes: 2 |
2018/03/20 | 283 | 851 | <issue_start>username_0: I just want to pass page title inside script using php.
```
val = document.title;
```
like below code.
```
"Val" : echo $val;"
```<issue_comment>username_1: <https://www.elastic.co/guide/en/elasticsearch/reference/5.4/modules-scripting-painless-syntax.html#painless-maps>
You can create a map like `['first': 'Foo', 'last': 'Bar', 'sthElse': 100]` then add it.
So:
```
ctx._source.user.add([
"first" : "Foo",
"last" : "Bar"
])
```
Please note that map in painless can be mixed type.
Upvotes: 5 [selected_answer]<issue_comment>username_2: ```
POST my_index/_doc/1/_update
{
"script": {
"lang": "painless",
"inline": "ctx._source.user.add(params.object)",
"params": {
"object": {
"first" : "Foo",
"last" : "Bar"
}
}
}
}
```
Upvotes: 2 |
2018/03/20 | 627 | 1,909 | <issue_start>username_0: I have two times, say `timeS = '00.00.00'` and `timeE = '10.00.00'`
I want to get the time difference between the two times. One way is the following manner,
```
//create date format
var timeStart = new Date("01/01/2007 " + timeS).getHours();
var timeEnd = new Date("01/01/2007 " + timeE).getHours();
var hourDiff = timeEnd - timeStart;
```
Here, I had to get the desired result using the **Date** format. Is there any other way to achieve this, without explicitly making a **Date** object?
**Note**: Instead of marking it a `duplicate`, do observe that I am asking for some other alternative ways.<issue_comment>username_1: You need to convert this `time` to a `Date` first
```
var convertToMS = time => {
var d = new Date(1,1,1);
d.setHours.apply( d, time.split(".").map( Number ) );
return d.getTime();
};
var diffOutput = convertToMS( timeE ) - convertToMS( timeS );
```
**Demo**
```js
var convertToMS = time => {
var d = new Date();
d.setHours.apply(d, time.split(".").map(Number));
return d.getTime();
};
var timeS = '00.00.00';
var timeE = '10.00.00';
var diffOutput = convertToMS(timeE) - convertToMS(timeS);
console.log(diffOutput)
```
**Edit**
As suggested by @RobG, check this alternate solution using `UTC`
```
var convertToMS = time => Date.UTC(1,1,1, ...time.split('.'));
```
Upvotes: 1 <issue_comment>username_2: Convert the `hh.mm.ss` format into equivalent seconds by parsing.
```js
var timeS = '00.00.00';
var timeE = '10.00.00';
function convertToSeconds(timeString) {
var timeSplit = timeString.split('.');
return timeSplit.reduce((result, item, index) => {
return result + Number(item) * Math.pow(60, timeSplit.length - index - 1)
}, 0);
}
const secondDifference = convertToSeconds(timeE) - convertToSeconds(timeS);
console.log(secondDifference);
```
Upvotes: 3 [selected_answer] |
2018/03/20 | 574 | 2,278 | <issue_start>username_0: I am overriding the find method and add the where condition globally thats working fine here is my code
```
class Order extends \common\components\ActiveRecord
```
**`\common\components\ActiveRecord`**
```
namespace common\components;
use Yii;
use yii\db\ActiveRecord as BaseActiveRecord;
class ActiveRecord extends BaseActiveRecord{
public static function find() {
return parent::find()
->where(['=',static::tableName().'.company_id',Yii::$app->user->identity->company_id])
->andWhere(['=',static::tableName().'.branch_id',Yii::$app->user->identity->branch_id]);
}
}
```
The find is not working when i call the model from view like this
```
echo \common\models\Order::find()->where(['status'=>'0'])->count();
```<issue_comment>username_1: Use `andWhere()` so your default condition not get overridden :
```
class ActiveRecord extends BaseActiveRecord {
public static function find() {
return parent::find()
->andWhere(['=',static::tableName().'.company_id',Yii::$app->user->identity->company_id])
->andWhere(['=',static::tableName().'.branch_id',Yii::$app->user->identity->branch_id]);
}
}
```
Upvotes: 1 <issue_comment>username_2: Try to change with onCondition()
```
class ActiveRecord extends BaseActiveRecord {
public static function find() {
return parent::find()
->onCondition([
['=',static::tableName().'.company_id',Yii::$app->user->identity->company_id],
['=',static::tableName().'.branch_id',Yii::$app->user->identity->branch_id]
]);
}
}
```
Upvotes: 1 <issue_comment>username_3: Since you're using `where()` inside the find function that you're using in `ActiveRecord` and then where() in this statement
```
echo \common\models\Order::find()->where(['status'=>'0'])->count();
```
the second ends up overriding the first
What you need to do is to use andWhere() in all the cases where you need the original conditions that you put in ActiveRecord to work. Try thus:
```
echo \common\models\Order::find()->andWhere(['status'=>'0'])->count();
```
This should work.
**And again remember, use andWhere() in all places where the original condition needs to be applied**
Upvotes: 3 [selected_answer] |
2018/03/20 | 969 | 3,846 | <issue_start>username_0: I have a client that requires two buttons on the form. One that saves the progress of an uncompleted form. So this form will still need to validate the fields but will just ignore the required validation. The other button will need to run the complete validation included required fields.
I am using the stock standard asp.net core project which I believe uses jquery-validation-unobtrusive and is based on the model for the view.
What I am trying to do is when the "Save Progress" button is clicked to remove all the required validation and submit the form. However none of the code that I have found on stack overflow or the internet works for my scenario.
I have tried:
```
function foo() {
$('#FamilyName').rules("remove", "required");
return true
}
```
and
```
function foo() {
var settings = $('#Registration').validate().settings;
for (var i in settings.rules) {
delete settings.rules[i].required;
}
}
```
both of the above two attempts successfully find and remove rules but when the form is submitted validation still fails for the field in question.
I am stumped and not sure how to proceed.<issue_comment>username_1: With your code you dispabled the client side validation. In order to make it work, you have two options. The first option is to remove the required from your model. The second is to remove the server side validation and write your own code in order to check the submited values.
```
// Remove this.
if (!ModelState.IsValid)
{
return View(model);
}
```
You can make custom validation like this.
```
if (boolean expression)
{
ModelState.AddModelError("Property", "Error message.");
return View(model);
}
```
Replace the boolean expression with a check that you want to make, the Property with the property name which failed the validation and the Error message with the message that you want to display.
Upvotes: 0 <issue_comment>username_2: Changing the `required` rule(s) on the client does not affect server side validation. Your `[Required]` attribute validation is still executed during the model binding process, therefore `ModelState` will be invalid, and you would manually need to check each property to determine if its invalid because of a `[Required]` attribute, or because of one of your other validation attributes.
In addition, you will need to add all the rules back again (or re-parse the `$.validator`) to get the client side validation for your normal submit.
Instead, include a `bool` property in your view model, so that you can use a conditional `[RequiredIf]` attribute (you could use a [foolproof](https://github.com/leniel/foolproof) attribute, or the one in [this project](https://github.com/stephenmuecke/mvc-conditionalvalidation)).
Your model would then include
```
public bool IsDraft { get; set; }
[RequiredIf("IsDraft", false, ErrorMessage = "...")]
public string FamilyName { get; set; }
```
and in the view
```
@Html.HiddenFor(m => m.IsDraft)
@Html.LabelFor(m => m.FamilyName)
@Html.TextBoxFor(m => m.FamilyName)
@Html.ValidationMessageFor(m => m.FamilyName)
```
and the associated scripts
```
$('#Progress').click(function() {
$('#IsDraft').val('True');
$(yourForm).submit();
});
$('#Final').click(function() {
$('#IsDraft').val('False');
$(yourForm).submit();
});
```
Upvotes: 2 [selected_answer]<issue_comment>username_3: If you are using ASP, why not use an ASP Button?
```
```
Then the script is:
```
function ValidationCheck()
{
var value = $("#TextBox1").val();
if ((value === null) || (value == ""))
{
alert("Enter text!"); return false;
}
return true; }
```
This way you can control the validation better.
An even better way would be to do validations on the server side with modal pop-ups etc.
Upvotes: 0 |
2018/03/20 | 1,040 | 3,556 | <issue_start>username_0: I am new to Python. Working with `2.7` for class.
The teacher set a project in which we are to code a program that takes a piece of a Monty Python script (input by user), stores it in a list of lists, replaces a specific name in the script with the user's name and prints the revised script out to console.
The issue I am running into is in my third function `replace_name`, the `parameters are the list of lists, old name, new name`.
However, I am getting
>
> NameError:'word\_list' is not defined
>
>
>
I understand that if a variable is not defined in the Main then it is local to its function.
I thought though, that by using return in the function that that information is stored to be used by subsequent functions.
Am I wrong?
```
def new_name(): #prompts for user's name. checks if input is valid
while True:
name = raw_input("Please enter your name.\n")
if len(name) < 1:
print "Invalid, please enter your name.\n"
else:
return name
def orig_script():#reads in script, splits into list of lists
word_list = []
script = raw_input("Please enter script, one line at a time. Enter 'done' to exit. \n")
if len(script) < 1:
print "Empty text field. Please try again.\n"
while script != 'done':#splits string input,adds to list
words = script.split()
word_list.append(words)
script = raw_input("Please enter script, one line at a time. Enter 'done' to exit.\n ")
if len(script) < 1:
print "Empty text field. Please try again.\n"
return word_list
def replace_name(word_list,old_name,new_name):#replaces old name with new name in list. creates new list from changes.
new_list = []
for sentences in range(word_list):
sentence = word_list[sentences]
for words in range(sentece):
word = sentence[words]
if word == old_name:
sentence[words] == new_name
new_list.append(sentence)
print new_list#debugging-change to return
new_name()
orig_script()
replace_name(word_list, Robin, new_name)
```
If my indentation is a bit off here, I apologize.
I tried to correct it from the copy/paste.
There are no indentation errors given in repl.it.
```
Traceback (most recent call last):
File "python", line 45, in
NameError: name 'word\_list' is not defined
```<issue_comment>username_1: Pass the parameter in you function argument.
Ex.
```
#take the o/p of variable in another one and pass in funcation
return_val = orig_script()
old_name = ["jack", "mike" , "josh"]
new_name= ["jen" , "ros" , "chan"]
#calling replace name funcation
replace_name(return_val,old_name,new_name)
```
Upvotes: 0 <issue_comment>username_2: You did not assign any of the `word_list, Robin, new_name` variables. Returning a variable of a particular name does not bind it to any type of external variable on its own, especially not one of the same name.
For example, you need to assign the return value explicitly to its own variable.
```
word_list = orig_script()
name = new_name()
replace_name(word_list, "old name", name)
```
---
Also
```
for sentences in range(len(word_list)):
sentence = word_list[sentences]
```
Is the same as
```
for sentence in word_list:
```
Note: You do have a typo in `sentece` and this is a comparison, not an assignment `sentence[words] == new_name`
---
Bonus, I think you can rewrite `replace_name` as
```
def replace_name(word_list,old_name,new_name):
return [[new_name if w == old_name else old_name for w in sentence] for sentence in word_list]
```
Upvotes: 1 |
2018/03/20 | 524 | 1,707 | <issue_start>username_0: help me please. I need to test view title with rspec, capybara. I have spec:
```
require 'rails_helper'
RSpec.describe 'static_pages/home' do
it "display correct title" do
render
expect(response).to have_title('Home page')
end
end
```
home.html.erb:
```
djeje Home pagexbdkek
Hello
```
RSpec is passed without failures,
but I need to check if title is exactly the same as in spec, not just looking for substring.<issue_comment>username_1: Pass the parameter in you function argument.
Ex.
```
#take the o/p of variable in another one and pass in funcation
return_val = orig_script()
old_name = ["jack", "mike" , "josh"]
new_name= ["jen" , "ros" , "chan"]
#calling replace name funcation
replace_name(return_val,old_name,new_name)
```
Upvotes: 0 <issue_comment>username_2: You did not assign any of the `word_list, Robin, new_name` variables. Returning a variable of a particular name does not bind it to any type of external variable on its own, especially not one of the same name.
For example, you need to assign the return value explicitly to its own variable.
```
word_list = orig_script()
name = new_name()
replace_name(word_list, "old name", name)
```
---
Also
```
for sentences in range(len(word_list)):
sentence = word_list[sentences]
```
Is the same as
```
for sentence in word_list:
```
Note: You do have a typo in `sentece` and this is a comparison, not an assignment `sentence[words] == new_name`
---
Bonus, I think you can rewrite `replace_name` as
```
def replace_name(word_list,old_name,new_name):
return [[new_name if w == old_name else old_name for w in sentence] for sentence in word_list]
```
Upvotes: 1 |
2018/03/20 | 1,035 | 3,564 | <issue_start>username_0: Ive got a problem with svg2png, i want to convert my svg file to png and it says in gulp task that it's UnhandledPromiseRejectionWarning
```
var gulp = require('gulp'),
svgSprite = require('gulp-svg-sprite'),
rename = require('gulp-rename'),
del = require('del'),
svg2png = require('gulp-svg2png');
// var config consist of mode we used, and it used the css mode
var config = {
mode: {
css: {
sprite: 'sprite.svg',
render: {
css: {
template: './gulp/template/sprite.css'
}
}
}
}
}
gulp.task('beginClean', function() {
return del(['./app/temp/sprite', './app/assets/images/sprites']);
});
gulp.task('createSprite', ['beginClean'], function() {
return gulp.src('./app/assets/images/icons/**/*.svg')
.pipe(svgSprite(config))
.pipe(gulp.dest("./app/temp/sprite/"));
});
gulp.task('createPngCopy', ['createSprite'], function() {
return gulp.src('./app/temp/sprite/css/*.svg')
.pipe(svg2png())
.pipe(gulp.dest('./app/temp/sprite/css'));
});
gulp.task('copySpriteGraphic', ['createPngCopy'], function() {
return gulp.src('./app/temp/sprite/css/**/*.{svg,png}')
.pipe(gulp.dest('./app/assets/images/sprites'));
});
gulp.task('copySpriteCSS', ['createSprite'], function() {
return gulp.src('./app/temp/sprite/css/*.css')
.pipe(rename('_sprite.css'))
.pipe(gulp.dest('./app/assets/styles/modules'));
});
gulp.task('endClean', ['copySpriteGraphic', 'copySpriteCSS'], function() {
return del('./app/temp/sprite');
});
gulp.task('icons', ['beginClean', 'createSprite', 'createPngCopy', 'copySpriteGraphic', 'copySpriteCSS', 'endClean']);
```
and when i run it on my command line "gulp icons" it says
```
(node:8400) UnhandledPromiseRejectionWarning
(node:8400) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:8400) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
```<issue_comment>username_1: Pass the parameter in you function argument.
Ex.
```
#take the o/p of variable in another one and pass in funcation
return_val = orig_script()
old_name = ["jack", "mike" , "josh"]
new_name= ["jen" , "ros" , "chan"]
#calling replace name funcation
replace_name(return_val,old_name,new_name)
```
Upvotes: 0 <issue_comment>username_2: You did not assign any of the `word_list, Robin, new_name` variables. Returning a variable of a particular name does not bind it to any type of external variable on its own, especially not one of the same name.
For example, you need to assign the return value explicitly to its own variable.
```
word_list = orig_script()
name = new_name()
replace_name(word_list, "old name", name)
```
---
Also
```
for sentences in range(len(word_list)):
sentence = word_list[sentences]
```
Is the same as
```
for sentence in word_list:
```
Note: You do have a typo in `sentece` and this is a comparison, not an assignment `sentence[words] == new_name`
---
Bonus, I think you can rewrite `replace_name` as
```
def replace_name(word_list,old_name,new_name):
return [[new_name if w == old_name else old_name for w in sentence] for sentence in word_list]
```
Upvotes: 1 |
2018/03/20 | 843 | 2,965 | <issue_start>username_0: I have an application where I read csv files and do some transformations and then push them to elastic search from spark itself. Like this
```
input.write.format("org.elasticsearch.spark.sql")
.mode(SaveMode.Append)
.option("es.resource", "{date}/" + type).save()
```
I have several nodes and in each node, I run 5-6 `spark-submit` commands that push to `elasticsearch`
I am frequently getting Errors
```
Could not write all entries [13/128] (Maybe ES was overloaded?). Error sample (first [5] error messages):
rejected execution of org.elasticsearch.transport.TransportService$7@32e6f8f8 on EsThreadPoolExecutor[bulk, queue capacity = 200, org.elasticsearch.common.util.concurrent.EsThreadPoolExecutor@4448a084[Running, pool size = 4, active threads = 4, queued tasks = 200, completed tasks = 451515]]
```
My Elasticsearch cluster has following stats -
```
Nodes - 9 (1TB space,
Ram >= 15GB ) More than 8 cores per node
```
I have modified following parameters for elasticseach
```
spark.es.batch.size.bytes=5000000
spark.es.batch.size.entries=5000
spark.es.batch.write.refresh=false
```
Could anyone suggest, What can I fix to get rid of these errors?<issue_comment>username_1: The bulk queue in your ES cluster is hitting its capacity (200) . Try increasing it. See this page for how to change the bulk queue capacity.
<https://www.elastic.co/guide/en/elasticsearch/reference/current/modules-threadpool.html>
Also check this other SO answer where OP had a very similar issue and was fixed by increasing the bulk pool size.
[Rejected Execution of org.elasticsearch.transport.TransportService Error](https://stackoverflow.com/questions/37855803/rejected-execution-of-org-elasticsearch-transport-transportservice-error)
Upvotes: 0 <issue_comment>username_2: This occurs because the bulk requests are incoming at a rate greater than elasticsearch cluster could process and the bulk request queue is full.
The default bulk queue size is 200.
You should handle ideally this on the client side :
1) by reducing the number the spark-submit commands running concurrently
2) Retry in case of rejections by tweaking the `es.batch.write.retry.count` and
`es.batch.write.retry.wait`
Example:
```
es.batch.write.retry.wait = "60s"
es.batch.write.retry.count = 6
```
On elasticsearch cluster side :
1) check if there are too many shards per index and try reducing it.
This [blog](https://www.elastic.co/blog/how-many-shards-should-i-have-in-my-elasticsearch-cluster) has a good discussion on criteria for tuning the number of shards.
2) as a last resort increase the [thread\_pool.index.bulk.queue\_size](https://www.elastic.co/guide/en/elasticsearch/reference/current/modules-threadpool.html)
Check this [blog](https://www.elastic.co/blog/why-am-i-seeing-bulk-rejections-in-my-elasticsearch-cluster) with an extensive discussion on bulk rejections.
Upvotes: 4 [selected_answer] |
2018/03/20 | 414 | 1,449 | <issue_start>username_0: How to send `$this->uname` & `$this->email` to controller data to controller/ctrl\_crud.php
**create.php**
```
php
include 'FullScreenLayout.php';
class index {
public $uname, $email;
public function get_data() {
if ( isset($_POST) ) {
$this-uname = $_POST['form_uname'];
$this->email = $_POST['form_email'];
}
}
public function createForm(){
$createHTML = <<
Submit
EOT;
return $createHTML;
}
}
$ObjFullScreenLayout = new FullScreenLayout();
$ObjIndex = new index();
$ObjIndex->get\_data();
echo $ObjFullScreenLayout->header();
echo $ObjIndex->createForm();
echo $ObjFullScreenLayout->footer();
?>
```
**controller/ctrl\_crud.php**
```
php
class ctrl_crud {
}
?
```<issue_comment>username_1: Just add an action to your form that points to the page you want to send the data like so:
```
```
Upvotes: 0 <issue_comment>username_2: Send those data to the **constructor**
```
include 'controller/ctrl_crud.php';
public function get_data() {
if ( isset($_POST) ) {
$this->uname = $_POST['form_uname'];
$this->email = $_POST['form_email'];
new ctrl_crud($this->uname, $this->email);
}
}
```
**controller/ctrl\_crud.php**
```
class ctrl_crud {
function __construct($uname, $email){
// use uname and email here
}
}
```
Upvotes: 2 [selected_answer] |
2018/03/20 | 900 | 3,346 | <issue_start>username_0: I am getting this warning message. How can I fix this.
**Warning**: IB Designables: Ignoring user defined runtime attribute for key path `radius` on instance of `UIButton`. Hit an exception when attempting to set its value: [ setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key `radius`.
Here is custom **UIButtonRounded** class
```
@IBDesignable class UIButtonRounded: UIButton
{
override func layoutSubviews() {
super.layoutSubviews()
updateCornerRadius()
}
@IBInspectable var rounded: Bool = false {
didSet {
updateCornerRadius()
}
}
@IBInspectable var border: Bool = false {
didSet {
updateCornerRadius()
}
}
@IBInspectable var radious: CGFloat = 0 {
didSet {
updateCornerRadius()
}
}
func updateCornerRadius() {
layer.cornerRadius = rounded ? radious : 0
layer.masksToBounds = true
if(border){
layer.borderWidth = 1.3
layer.borderColor = UIColor(named:"color_bg_white")?.cgColor
}
}
}
```
[](https://i.stack.imgur.com/voEaH.png)
[](https://i.stack.imgur.com/iYtL7.png)
[](https://i.stack.imgur.com/0NwA7.png)
Thanks In advance.<issue_comment>username_1: It's working for me:
```
import UIKit
@IBDesignable
class DesignableView: UIView {
}
@IBDesignable
class DesignableButton: UIButton {
}
@IBDesignable
class DesignableLabel: UILabel {
}
extension UIView {
@IBInspectable
var cornerRadius: CGFloat {
get {
return layer.cornerRadius
}
set {
layer.cornerRadius = newValue
}
}
@IBInspectable
var borderWidth: CGFloat {
get {
return layer.borderWidth
}
set {
layer.borderWidth = newValue
}
}
@IBInspectable
var borderColor: UIColor? {
get {
if let color = layer.borderColor {
return UIColor(cgColor: color)
}
return nil
}
set {
if let color = newValue {
layer.borderColor = color.cgColor
} else {
layer.borderColor = nil
}
}
}
@IBInspectable
var shadowRadius: CGFloat {
get {
return layer.shadowRadius
}
set {
layer.shadowRadius = newValue
}
}
@IBInspectable
var shadowOpacity: Float {
get {
return layer.shadowOpacity
}
set {
layer.shadowOpacity = newValue
}
}
@IBInspectable
var shadowOffset: CGSize {
get {
return layer.shadowOffset
}
set {
layer.shadowOffset = newValue
}
}
@IBInspectable
var shadowColor: UIColor? {
get {
if let color = layer.shadowColor {
return UIColor(cgColor: color)
}
return nil
}
set {
if let color = newValue {
layer.shadowColor = color.cgColor
} else {
layer.shadowColor = nil
}
}
}
}
```
Upvotes: -1 [selected_answer]<issue_comment>username_2: If you make a value and change it later it will still exists in the user defined runtime attributes in the Identity Inspector. Go there and delete the old value.
Upvotes: 1 |
2018/03/20 | 602 | 1,867 | <issue_start>username_0: ```
$.ajax({
type:'POST',
data:({value:10}),
url:'count.php',
success:function(data){
var data=jQuery.parseJSON(data);
console.log(data);
if(data.status==true){
var table=data.data.row;
var staffs=data.staff.STAFF;
var users=staffs.join();
var user = '\'' + users.split(',').join('\',\'') + '\'';
$("#my_multi_select2").multiSelect('select', [user]);
//$("#my_multi_select2").multiSelect('select',['3','4']);
}
}
})
```
my user value is '3','4','5','6'
How could i pass this as a variable to multiselect selected value
please please help me.....<issue_comment>username_1: You just need to make the pass the values to the multiselect as an array:
```js
jQuery(document).ready(function($){
var users = '3,4,5,6';
var userarray = users.split(',');
$("#my_multi_select2").val( userarray );
console.log( userarray );
});
```
```html
User 1
User 2
User 3
User 4
User 5
User 6
User 7
User 8
```
Per your example:
```
$.ajax({
type: 'POST',
data: ({value:10}),
url: 'count.php',
success: function(data){
var data = jQuery.parseJSON(data);
console.log(data);
if( data.status == true ){
var table = data.data.row;
var staffs = data.staff.STAFF; //staffs = [["3"],["2"],["4"],["5"]]
var users = staffs.join(); //users = "3,2,4,5"
var userArr = users.split(','); //userArr = ["3", "2", "4", "5"]
$("#my_multi_select2").val(userArr);
}
}
});
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: Well answered by username_1. but still sharing what i tried.
```
function selectme(){
$('#public-methods').val(['elem\_1', 'elem\_2']);
};
[select elems](#)
elem 1
elem 2
elem 3
elem 4
elem 5
```
Upvotes: 0 |
2018/03/20 | 608 | 1,945 | <issue_start>username_0: I have excel table in below format.
Sr. No. Column 1 (X) Column 2(Y) Column 3(Z)
1 X Y Z
2 Y Z
3 Y
4 X Y
5 X
I want to tranpose it in following format in MS Excel.
Sr. No. Value
1 X
1 Y
1 Z
2 Y
2 Z
3 Y
4 X
4 Y
5 X
Actual data contains more than 30 columns which needs to be transposed into 2 columns.
Please guide me.<issue_comment>username_1: You just need to make the pass the values to the multiselect as an array:
```js
jQuery(document).ready(function($){
var users = '3,4,5,6';
var userarray = users.split(',');
$("#my_multi_select2").val( userarray );
console.log( userarray );
});
```
```html
User 1
User 2
User 3
User 4
User 5
User 6
User 7
User 8
```
Per your example:
```
$.ajax({
type: 'POST',
data: ({value:10}),
url: 'count.php',
success: function(data){
var data = jQuery.parseJSON(data);
console.log(data);
if( data.status == true ){
var table = data.data.row;
var staffs = data.staff.STAFF; //staffs = [["3"],["2"],["4"],["5"]]
var users = staffs.join(); //users = "3,2,4,5"
var userArr = users.split(','); //userArr = ["3", "2", "4", "5"]
$("#my_multi_select2").val(userArr);
}
}
});
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: Well answered by username_1. but still sharing what i tried.
```
function selectme(){
$('#public-methods').val(['elem\_1', 'elem\_2']);
};
[select elems](#)
elem 1
elem 2
elem 3
elem 4
elem 5
```
Upvotes: 0 |
2018/03/20 | 738 | 2,061 | <issue_start>username_0: So basically i have this markup
```
1
2
3
4
5
6
```
[](https://i.stack.imgur.com/z4AIK.png)
How will i be able to have alternate width for the first & second div per row?
I tried `article:nth-child`+ diff stepping to target alternate divs, but i cant find the right combination of stepping
Edit: I really can't edit the HTML structure since this is a WordPress plugin output<issue_comment>username_1: You will need to use **[:nth-child()](https://developer.mozilla.org/en-US/docs/Web/CSS/%3Anth-child)** selector here...
Actually here the pattern is repeating itself after every 4th element...So you will need to taregt `4n`, `4n+1`, `4n+2` and `4n+3`
```css
.container {
display: flex;
flex-wrap: wrap;
}
article {
display: flex;
align-items: center;
justify-content: center;
height: 100px;
border: 5px solid #fff;
background: gray;
box-sizing: border-box;
color: #fff;
font: bold 20px Verdana;
}
article:nth-child(4n),
article:nth-child(4n+1) {
width: 25%
}
article:nth-child(4n+2),
article:nth-child(4n+3) {
width: 75%
}
```
```html
1
2
3
4
5
6
7
8
9
10
11
12
```
Upvotes: 3 <issue_comment>username_2: 1
2
3
4
5
6
```
article
{
float:left;
height:50px;
width: 30%;
background: #444;
margin: 0 0 5px 0;
}
article:nth-child(2n) {
background: #f0f;
width: 70%;
float: right;
}
article:nth-child(3n) {
width: 70%;
}
article:nth-child(4n) {
width: 30%;
float: right;
}
```
Upvotes: 1 <issue_comment>username_3: you should apply class for correct adjustment of articles use only two class with width 66% and 33%
Upvotes: 2 <issue_comment>username_4: You can use flexbox. With display: flex;flex-wrap: wrap; on ".container" and flex-grow: 1;flex-shrink:1; on article. The article will get the width based on the content.
With flexbox you can do anything, here is a good tutorial <https://css-tricks.com/snippets/css/a-guide-to-flexbox/>
Upvotes: 1 |
2018/03/20 | 1,289 | 5,271 | <issue_start>username_0: I am trying to delete file from my External/Removable SD Card. But I got following error:
```
remove failed: EACCES (Permission denied) : /storage/987F-099F/SDNumber/Voc_112_1.png
```
I basically need to move file from my removable SD card to my device storage.
But I am not able to do that also.
I can fetch all the files from my removable SD card.
Here is code for how I am fetching files from removable SD card:
```
final String[] columns = {MediaStore.Images.Media.DATA, MediaStore.Images.Media._ID, MediaStore.Images.Media.DISPLAY_NAME};
final String orderBy = MediaStore.Images.Media.DISPLAY_NAME;
Cursor cursor = context.getContentResolver().query(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns, null,
null, orderBy);
```
From this when I try to move file from SD card to device external storage it gives me error like this:
```
rename failed: EXDEV (Cross-device link) : /storage/987F-099F/SDNumber/Voc_112_1.png
```
Then, I move ahead and trying to copy that file. Copy file works great. But, then after I need to delete that file but it also doesn't work and gives error like this:
```
remove failed: EACCES (Permission denied) : /storage/987F-099F/SDNumber/Voc_112_1.png
```
Basically my whole code is like this:
```
public static void moveFile(Context context, File srcFile, File destFile) {
boolean rename = srcFile.renameTo(destFile);
if (!rename) {
copyFile(srcFile.getAbsolutePath(), destFile.getAbsolutePath());
boolean deleted = deleteFile(srcFile.getAbsolutePath());
if (!deleted) {
deleted = delete(context, srcFile);
Log.e("moveFile", "deleted : " + deleted);
}
}
}
public static boolean copyFile(String sourceFilePath, String destFilePath) {
InputStream inputStream = null;
try {
inputStream = new FileInputStream(sourceFilePath);
} catch (FileNotFoundException e) {
throw new RuntimeException("FileNotFoundException occurred. ", e);
}
return writeFile(destFilePath, inputStream);
}
public static boolean deleteFile(String path) {
if (path == null || path.trim().length() == 0) {
return true;
}
File file = new File(path);
if (!file.exists()) {
return true;
}
if (file.isFile()) {
return file.delete();
}
if (!file.isDirectory()) {
return false;
}
for (File f : file.listFiles()) {
if (f.isFile()) {
f.delete();
} else if (f.isDirectory()) {
deleteFile(f.getAbsolutePath());
}
}
return file.delete();
}
```
I am also trying to delete using content resolver:
```
public static boolean delete(final Context context, final File file) {
final String where = MediaStore.MediaColumns.DATA + "=?";
final String[] selectionArgs = new String[] {
file.getAbsolutePath()
};
final ContentResolver contentResolver = context.getContentResolver();
final Uri filesUri = MediaStore.Files.getContentUri("external");
contentResolver.delete(filesUri, where, selectionArgs);
if (file.exists()) {
contentResolver.delete(filesUri, where, selectionArgs);
}
return !file.exists();
}
```
But none of this function works. That file still appear in my gallery.
Please let me know where I am going wrong and what is missing here.
I am also checking runtime permission for Read and Write external storage.
Here is my Manifest.xml
```
```
Thanks!<issue_comment>username_1: Are you requesting storage permission at `runtime`? Even if you add uses-permission in manifest, still you need to ask user to grant permissions at runtime. Here is code:
```
/ Storage Permissions
private static final int REQUEST_EXTERNAL_STORAGE = 1;
private static String[] PERMISSIONS_STORAGE = {
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE
};
/**
* Checks if the app has permission to write to device storage
*
* If the app does not has permission then the user will be prompted to grant permissions
*
* @param activity
*/
public static void verifyStoragePermissions(Activity activity) {
// Check if we have write permission
int permission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (permission != PackageManager.PERMISSION_GRANTED) {
// We don't have permission so prompt the user
ActivityCompat.requestPermissions(
activity,
PERMISSIONS_STORAGE,
REQUEST_EXTERNAL_STORAGE
);
}
}
```
Read more about the runtime permission request here: <https://developer.android.com/training/permissions/requesting.html>
Upvotes: -1 <issue_comment>username_2: >
> rename failed: EXDEV (Cross-device link) : /storage/987F-099F/SDNumber/Voc\_112\_1.png
>
>
>
Removable SD cards are read only (using file scheme) since Android 4.4+.
To be able to write use the storage access framework.
Upvotes: 0 |
2018/03/20 | 1,206 | 4,918 | <issue_start>username_0: I know it sounds crazy, but just curious how I can reduce the if loop iteration for following? I have tried using `guard let` but stucked at some place.
```
{
if arenaEventItems == nil || arenaEventItems.count <= 0 {
return
}
if (arenaEventItems.count > 0 && (self.arenaEvents?.monthsDictObjList.count)! > 0){
if (self.tableView != nil){
if let arrVisibleRows = self.tableView.indexPathsForVisibleRows as? [IndexPath]{
if (self.tableView.indexPathsForVisibleRows!.count > 0){
let indexPath : IndexPath = self.tableView.indexPathsForVisibleRows!.first!
if let dict = self.arenaEvents?.monthsDictObjList[indexPath.row] {
if(self.arenaHeaderView != nil) && (dict.count) > 0 {
self.arenaHeaderView?.setMonthTitle(string: (dict.keys.first!))
let selectedMonthTitle = (dict.keys.first!)
for month in (self.arenaEvents?.uniqueMonthOnlyList)! {
if (selectedMonthTitle.contains(month)){
selectedMonthIndex = (self.arenaEvents?.uniqueMonthOnlyList.index(of: month)!)!
break
}
}
}
}
}
}
}
}
}
```<issue_comment>username_1: You can combine all the conditions in "if" and get something like this:
```
if let eventItems = arenaEventItems,
eventItems.count > 0,
let events = self.arenaEvents,
!events.monthsDictObjList.isEmpty,
let tableView = self.tableView,
let arrVisibleRows = self.tableView.indexPathsForVisibleRows as? [IndexPath],
!arrVisibleRows.isEmpty,
let indexPath : IndexPath = arrVisibleRows.first,
let dict = events.monthsDictObjList[indexPath.row],
let headerView = self.arenaHeaderView,
!dict.isEmpty {
headerView.setMonthTitle(string: (dict.keys.first!))
let selectedMonthTitle = (dict.keys.first!)
for month in events.uniqueMonthOnlyList! {
if (selectedMonthTitle.contains(month)){
selectedMonthIndex = (events.uniqueMonthOnlyList.index(of: month)!)!
break
}
}
}
```
Upvotes: 0 <issue_comment>username_2: You can reduce it like that, without any forced unwrapping or nesting:
```
guard let arenaEventItems = arenaEventItems,
!arenaEventItems.isEmpty,
let arenaEvents = self.arenaEvents,
!arenaEvents.monthsDictObjList.isEmpty,
let arenaHeaderView = self.arenaHeaderView,
let indexPath = self.tableView?.indexPathsForVisibleRows?.first,
let selectedMonthTitle = arenaEvents.monthsDictObjList[indexPath.row].keys.first
else {
return
}
arenaHeaderView.setMonthTitle(string: selectedMonthTitle)
if let monthIndex = arenaEvents.uniqueMonthOnlyList.index(where: { selectedMonthTitle.contains($0) }) {
selectedMonthIndex = monthIndex
}
```
* you replace `if ... return` with `guard !... else return` to avoid nesting
* you replace `.count > 0` with `!...isEmpty` as best practice
* you replace multiple access to `self.something?` with `if let something = self.something` to avoid threading issues
* you unloop `for ... in ... { if (...) { ... } }` to `.index(where: ...)`
Upvotes: 1 <issue_comment>username_3: You should consider restructuring your code, your code is not readable and incomprehensible for anyone who look at it. Since, you are using Swift, it is really easy to write such code with **guard ... else**, **if ... let**
pattern.
Some improvements that you can do on class is have your view non nil ie make them implicitly unwrapped optional, since you will always be connecting them to storyboard.
```
@IBOutlet var tableView: UITableView!
@IBOutlet var arenaHeaderView: ArenaHeaderView!
```
Also, you have arrays which can go to nil, why do you want it to be nil. You could simply initialize an empty array and dictionaries. That way you can reduce some more comparison code like so,
```
arenaEventItems: [String: String] = [:]
```
With that changes and a bit of refactoring, you could possibly rewrite your code to something like this,
```
guard !arenaEventItems.isEmpty,
let arenaEvents = arenaEvents,
let indexPath = tableView.indexPathsForVisibleRows?.first,
let dict = arenaEvents.monthsDictObjList[indexPath.row],
let selectedMonthTitle = dict.keys.first
else {
return
}
arenaHeaderView.setMonthTitle(string: selectedMonthTitle)
for month in arenaEvents.uniqueMonthOnlyList where selectedMonthTitle.contains(month) {
if let selectedIndex = arenaEvents.uniqueMonthOnlyList.index(of: month) {
selectedMonthIndex = selectedIndex
break
}
}
```
Upvotes: 0 |
2018/03/20 | 1,510 | 5,615 | <issue_start>username_0: Code Snippet from a ARM linker file:
```
....
__RW_START_ = .;
...
...
...
...
__RW_END_ = .;
__RW_SIZE__ = __RW_END__ - __RW_START_;
....
```
Referring the variables **RW\_START**, **RW\_END** & **RW\_SIZE** from above linker in the below C source file.
Code Snippet from a C source file:
```
....
#define _MAP_REGION_FULL_SPEC(_pa, _va, _sz, _attr, _gr) \
{ \
.base_pa = (_pa), \
.base_va = (_va), \
.size = (_sz), \
.attr = (_attr), \
.granularity = (_gr), \
}
#define MAP_REGION(_pa, _va, _sz, _attr) \
_MAP_REGION_FULL_SPEC(_pa, _va, _sz, _attr, REGION_DEFAULT_GRANULARITY)
#define MAP_REGION_FLAT(adr, sz, attr) MAP_REGION(adr, adr, sz, attr)
extern unsigned long __RW_START__;
extern unsigned long __RW_END__;
extern unsigned long __RW_SIZE__;
#define BL2_EL3_RW_START (const unsigned long)(&__RW_START__)
#define BL2_EL3_RW_SIZE (const unsigned long) ((&__RW_END__) - (&__RW_START__))
//#define BL2_EL3_RW_SIZE (const unsigned long) (&__RW_SIZE__)
#define LS_BL2_EL3_RW_MEM MAP_REGION_FLAT(BL2_EL3_RW_START, \
BL2_EL3_RW_SIZE, \
MT_DEVICE | MT_RW | MT_SECURE)
...
...
typedef struct mmap_region {
unsigned long long base_pa;
uintptr_t base_va;
size_t size;
mmap_attr_t attr;
size_t granularity;
} mmap_region_t;
const mmap_region_t plat_ls_mmap = LS_BL2_EL3_RW_MEM; //compiler error
...
...
```
Question: Explain the below two observation:
1. ARM Compiler gives following error when BL2\_EL3\_RW\_SIZE is defined as above:
error: initializer element is not constant
.size = (\_sz), \
^
2. ARM Compiler gives no error when BL2\_EL3\_RW\_SIZE is defined as above(in commented lines).<issue_comment>username_1: You can combine all the conditions in "if" and get something like this:
```
if let eventItems = arenaEventItems,
eventItems.count > 0,
let events = self.arenaEvents,
!events.monthsDictObjList.isEmpty,
let tableView = self.tableView,
let arrVisibleRows = self.tableView.indexPathsForVisibleRows as? [IndexPath],
!arrVisibleRows.isEmpty,
let indexPath : IndexPath = arrVisibleRows.first,
let dict = events.monthsDictObjList[indexPath.row],
let headerView = self.arenaHeaderView,
!dict.isEmpty {
headerView.setMonthTitle(string: (dict.keys.first!))
let selectedMonthTitle = (dict.keys.first!)
for month in events.uniqueMonthOnlyList! {
if (selectedMonthTitle.contains(month)){
selectedMonthIndex = (events.uniqueMonthOnlyList.index(of: month)!)!
break
}
}
}
```
Upvotes: 0 <issue_comment>username_2: You can reduce it like that, without any forced unwrapping or nesting:
```
guard let arenaEventItems = arenaEventItems,
!arenaEventItems.isEmpty,
let arenaEvents = self.arenaEvents,
!arenaEvents.monthsDictObjList.isEmpty,
let arenaHeaderView = self.arenaHeaderView,
let indexPath = self.tableView?.indexPathsForVisibleRows?.first,
let selectedMonthTitle = arenaEvents.monthsDictObjList[indexPath.row].keys.first
else {
return
}
arenaHeaderView.setMonthTitle(string: selectedMonthTitle)
if let monthIndex = arenaEvents.uniqueMonthOnlyList.index(where: { selectedMonthTitle.contains($0) }) {
selectedMonthIndex = monthIndex
}
```
* you replace `if ... return` with `guard !... else return` to avoid nesting
* you replace `.count > 0` with `!...isEmpty` as best practice
* you replace multiple access to `self.something?` with `if let something = self.something` to avoid threading issues
* you unloop `for ... in ... { if (...) { ... } }` to `.index(where: ...)`
Upvotes: 1 <issue_comment>username_3: You should consider restructuring your code, your code is not readable and incomprehensible for anyone who look at it. Since, you are using Swift, it is really easy to write such code with **guard ... else**, **if ... let**
pattern.
Some improvements that you can do on class is have your view non nil ie make them implicitly unwrapped optional, since you will always be connecting them to storyboard.
```
@IBOutlet var tableView: UITableView!
@IBOutlet var arenaHeaderView: ArenaHeaderView!
```
Also, you have arrays which can go to nil, why do you want it to be nil. You could simply initialize an empty array and dictionaries. That way you can reduce some more comparison code like so,
```
arenaEventItems: [String: String] = [:]
```
With that changes and a bit of refactoring, you could possibly rewrite your code to something like this,
```
guard !arenaEventItems.isEmpty,
let arenaEvents = arenaEvents,
let indexPath = tableView.indexPathsForVisibleRows?.first,
let dict = arenaEvents.monthsDictObjList[indexPath.row],
let selectedMonthTitle = dict.keys.first
else {
return
}
arenaHeaderView.setMonthTitle(string: selectedMonthTitle)
for month in arenaEvents.uniqueMonthOnlyList where selectedMonthTitle.contains(month) {
if let selectedIndex = arenaEvents.uniqueMonthOnlyList.index(of: month) {
selectedMonthIndex = selectedIndex
break
}
}
```
Upvotes: 0 |
2018/03/20 | 1,084 | 3,918 | <issue_start>username_0: I have the following code:
```
X = np.array([[2,2,2,4,5,6],[1,2,3,3,3,4]])
mu = np.mean(X,axis=1)
```
**My Problem:**
When I try to subtract the mean from the data (`X` - `mu`), I get the following error:
`operands could not be broadcast together with shapes (2,6) (2,)`
This makes sense but still having trouble trying to subtract the mean from this data, X. I am expecting the following result:
```
1.5 1.5 1.5 0.5 1.5 2.5
1.67 0.67 0.33 0.33 0.33 1.33
```<issue_comment>username_1: You can combine all the conditions in "if" and get something like this:
```
if let eventItems = arenaEventItems,
eventItems.count > 0,
let events = self.arenaEvents,
!events.monthsDictObjList.isEmpty,
let tableView = self.tableView,
let arrVisibleRows = self.tableView.indexPathsForVisibleRows as? [IndexPath],
!arrVisibleRows.isEmpty,
let indexPath : IndexPath = arrVisibleRows.first,
let dict = events.monthsDictObjList[indexPath.row],
let headerView = self.arenaHeaderView,
!dict.isEmpty {
headerView.setMonthTitle(string: (dict.keys.first!))
let selectedMonthTitle = (dict.keys.first!)
for month in events.uniqueMonthOnlyList! {
if (selectedMonthTitle.contains(month)){
selectedMonthIndex = (events.uniqueMonthOnlyList.index(of: month)!)!
break
}
}
}
```
Upvotes: 0 <issue_comment>username_2: You can reduce it like that, without any forced unwrapping or nesting:
```
guard let arenaEventItems = arenaEventItems,
!arenaEventItems.isEmpty,
let arenaEvents = self.arenaEvents,
!arenaEvents.monthsDictObjList.isEmpty,
let arenaHeaderView = self.arenaHeaderView,
let indexPath = self.tableView?.indexPathsForVisibleRows?.first,
let selectedMonthTitle = arenaEvents.monthsDictObjList[indexPath.row].keys.first
else {
return
}
arenaHeaderView.setMonthTitle(string: selectedMonthTitle)
if let monthIndex = arenaEvents.uniqueMonthOnlyList.index(where: { selectedMonthTitle.contains($0) }) {
selectedMonthIndex = monthIndex
}
```
* you replace `if ... return` with `guard !... else return` to avoid nesting
* you replace `.count > 0` with `!...isEmpty` as best practice
* you replace multiple access to `self.something?` with `if let something = self.something` to avoid threading issues
* you unloop `for ... in ... { if (...) { ... } }` to `.index(where: ...)`
Upvotes: 1 <issue_comment>username_3: You should consider restructuring your code, your code is not readable and incomprehensible for anyone who look at it. Since, you are using Swift, it is really easy to write such code with **guard ... else**, **if ... let**
pattern.
Some improvements that you can do on class is have your view non nil ie make them implicitly unwrapped optional, since you will always be connecting them to storyboard.
```
@IBOutlet var tableView: UITableView!
@IBOutlet var arenaHeaderView: ArenaHeaderView!
```
Also, you have arrays which can go to nil, why do you want it to be nil. You could simply initialize an empty array and dictionaries. That way you can reduce some more comparison code like so,
```
arenaEventItems: [String: String] = [:]
```
With that changes and a bit of refactoring, you could possibly rewrite your code to something like this,
```
guard !arenaEventItems.isEmpty,
let arenaEvents = arenaEvents,
let indexPath = tableView.indexPathsForVisibleRows?.first,
let dict = arenaEvents.monthsDictObjList[indexPath.row],
let selectedMonthTitle = dict.keys.first
else {
return
}
arenaHeaderView.setMonthTitle(string: selectedMonthTitle)
for month in arenaEvents.uniqueMonthOnlyList where selectedMonthTitle.contains(month) {
if let selectedIndex = arenaEvents.uniqueMonthOnlyList.index(of: month) {
selectedMonthIndex = selectedIndex
break
}
}
```
Upvotes: 0 |
2018/03/20 | 1,023 | 3,889 | <issue_start>username_0: ```js
var posts = [{
id: 1,
title: 'new post'
},
{
id: 2,
title: 'old post'
}
];
var comment = {
postId: 1,
content: 'Great Post'
};
function postForComment(posts, comment) {
return posts.find(function(post) {
return post.id === comment.postId
});
}
var c = postForComment(posts, comment);
console.log(c);
```
In the above code, the output is as expected, but I am unable to understand the usage of the return statement inside the function `postForComment`. Why is it using two return functions and which return function is going where?<issue_comment>username_1: ```
posts.find(function(post){
return post.id===comment.postId
});
```
You can consider the above code snippet to be independent. In this case this function will return the value of `post` which satisfied `post.id === comment.postId`.
The returned value is received by the function `postForComment`. The first return value inside `postForComment` will in turn pass this value to the variable `c`
```
function postForComment(posts,comment){
return posts.find(function(post){
return post.id===comment.postId
});
}
```
In this code snippet there are two functions. The second `return` statement returns the value of the first post value that satisfies the condition. in `posts.find`, each value of posts is passed to the function as the variable post. When the condition is satisfied the function inside will return the value of the post that satisfied the condition `post.id === comment.postId`. The first `return` statement is so that the value that is returned by `posts.find` is returned to the caller of the function. That is the variable c will receive the value that is returned by `posts.find`
Upvotes: 1 <issue_comment>username_2: Simply put, each `function` needs to return its result, and here there are two, nested.
The `postForComment` returns its result with
```
return posts.find(...)
```
But also inside `posts.find` is a `function`, which also need to return its result.
```
function(post) {
return post.id === comment.postId
}
```
So if the `function` inside `posts.find` (generally called a *callback function*) doesn't return anything, `postForComment` won't have anything to return either.
Upvotes: 2 [selected_answer]<issue_comment>username_3: [find](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find) function accepts a callback function, in your case the callback function is
```
function(post) {
return post.id === comment.postId
}
```
So the inner `return` is the return from that `callback` function & the outer return is the return from the `postForComment` function
Upvotes: 0 <issue_comment>username_4: The first return in postForComment make this function returning the value found in posts.
The return inside the callback function passed to posts.find is here because array.prototype.find expects a callback that returns true or false
Upvotes: 0 <issue_comment>username_5: A simplified version of your code is shown below. The `find()` function iterates on all the `posts` and calls `compareIDs()`, passing the current post as a parameter.
When `compareIDs()` returns true, `find` will stop iterating and return the current post, which will get stored in `matchingPost`.
Now `matchingPost` will be returned from `postForComment()` and get stored in `c`.
HTH
```js
var posts = [{
id: 1,
title: 'new post'
},
{
id: 2,
title: 'old post'
}
];
var comment = {
postId: 1,
content: 'Great Post'
};
function postForComment(posts, comment) {
var matchingPost = posts.find(function compareIDs(post) {
return post.id === comment.postId
});
return matchingPost;
}
var c = postForComment(posts, comment);
console.log(c);
```
Upvotes: 0 |
2018/03/20 | 546 | 2,429 | <issue_start>username_0: In my webapp architecture i have an api gateway which proxies requests to my microservices, also there is a a common microservice which other microservices can query via rest api. All of these run on node servers.
i want the microservices to only be approachable from the api gateway, besides the common server which can also be approachable from the other microservices. what is the best network architecture to make this happen and do i need to handle authentication between the servers in some way?
[](https://i.stack.imgur.com/uW4Te.png)<issue_comment>username_1: Security needs to be handled at multiple layers and as such its a really broad topic. I will however share some pointers which you can explore further.
First thing first any security comes at a cost. And it's a trade off that you need to do.
If you can ensure that services are available only to the other services and API gateway, then you can delegate application layer security to API gateway and strip the security headers at API gateway itself and continue to have free communication between services. It is like creating restricted zone with ip restrictions (or other means on from where can service be accessed), and api gateway or reverse proxy handling all the external traffic. This will allow you to concentrate on few services as far as security is concerned. Point that you should note here is that you will be losing on authorization part as well but you can retain it if you want to.
If you are using AWS you need to look into security groups and VPN etc to set up a secure layer.
A part of security is also to ensure the service is accessible all the time and is not susceptible to DDOS. API gateways do have a means of safeguarding against such threats.
Upvotes: 1 <issue_comment>username_2: For the ‘API gateway’ front-end authentication you could use [OATH2](https://developers.google.com/identity/protocols/OAuth2) and for the back-end part you can use [OpenID connect](http://openid.net/connect/) which will allow you to use a key value that is relevant to the user, like for example a uuid and use this to set access control at the Microservice level, behind the API Gateway.
You can find in the next link further information about [OpenID connect](https://developers.google.com/identity/protocols/OpenIDConnect) authentication.
Upvotes: 0 |
2018/03/20 | 417 | 1,521 | <issue_start>username_0: I am an android developer and learning react native.
I made an app in React Native and now I want to release my app in android play store and apple store but I don't know where do I put my react native project code/files?
I had put react native code in my PHP(Linux) server but it's not working, it says file not found 404.
please guide, Thanks<issue_comment>username_1: You need to generate build standalone signed apk.
Generating Signed APK
<https://facebook.github.io/react-native/docs/signed-apk-android.html>
1) first create keystore file and put in android folder location
2) setting up gradle for keystore
3) run comman
```
react-native run-android --variant=release
```
after success run command you will file apk-release.apk in andorid/app/build/outputs/apk/ location
then you can uplaod apk to app store
Upvotes: 2 <issue_comment>username_2: **If your app doesn't need detach** (for example doesn't use bluetooth) you can use `create-react-native-app` and put your app code inside new project. That way you can publish your app to <https://expo.io/> . It's a great way to publish your app without Google Play and App Store.
1. Here is instruction for creating new react native app with expo kit:
<https://facebook.github.io/react-native/docs/getting-started.html>
2. And here is how to publish it into expo:
<https://docs.expo.io/versions/v25.0.0/guides/publishing.html#how-to-publish>
**All you need is** `create-react-native-app` and `exp` command line tools.
Upvotes: 0 |
2018/03/20 | 390 | 1,424 | <issue_start>username_0: I'm integrating python with windbg and I want to edit a local variable value from the script. For that I need to know how to edit local variable values in windbg command line.
I know I can get value by variable, but how to edit the same variable?<issue_comment>username_1: You need to generate build standalone signed apk.
Generating Signed APK
<https://facebook.github.io/react-native/docs/signed-apk-android.html>
1) first create keystore file and put in android folder location
2) setting up gradle for keystore
3) run comman
```
react-native run-android --variant=release
```
after success run command you will file apk-release.apk in andorid/app/build/outputs/apk/ location
then you can uplaod apk to app store
Upvotes: 2 <issue_comment>username_2: **If your app doesn't need detach** (for example doesn't use bluetooth) you can use `create-react-native-app` and put your app code inside new project. That way you can publish your app to <https://expo.io/> . It's a great way to publish your app without Google Play and App Store.
1. Here is instruction for creating new react native app with expo kit:
<https://facebook.github.io/react-native/docs/getting-started.html>
2. And here is how to publish it into expo:
<https://docs.expo.io/versions/v25.0.0/guides/publishing.html#how-to-publish>
**All you need is** `create-react-native-app` and `exp` command line tools.
Upvotes: 0 |
2018/03/20 | 581 | 1,904 | <issue_start>username_0: I created my own theme
import { createMuiTheme } from 'material-ui/styles';
```
export const MyTheme = createMuiTheme({
palette: {
primary: {
light: '#757ce8',
main: '#3f50b5',
dark: '#002884',
contrastText: '#fff',
},
secondary: {
light: '#ff7961',
main: '#f44336',
dark: '#ba000d',
contrastText: '#000',
},
error: {
light: '#FF5F57',
main: '#CE160C',
dark: '#380300',
//contrastText: will be calculated to contast with palette.primary.main
}
}
});
```
Using it in my app
```
```
But how can I change `MenuItem` hover style in `Menu` and `Select` using a theme?
[](https://i.stack.imgur.com/y8Nqv.png)
[](https://i.stack.imgur.com/MpU1h.png)<issue_comment>username_1: You can use simple CSS trick to change the **MenuItem** color on hover
Here is sample code
```
import React from 'react';
import './testJS.css'
import Menu from 'material-ui/Menu';
import MenuItem from 'material-ui/MenuItem';
class TestJS extends React.Component {
constructor(props) {
super(props);
}
render() {
return(
)};
}
export default TestJS;
```
and add following lines in your CSS file, need to use **!important** in order to override the default material-UI CSS
```
.menu-item{
background: #dcdcdc !important;
}
.menu-item:hover{
background: #0e7be9 !important;
}
```
Upvotes: -1 <issue_comment>username_2: Implemented hover and selected items styles using a theme
```
export const MyTheme = createMuiTheme({
palette: {
action: {
selected: '#E7A615',
hover: '#FFD371',
disabled: '#9B9B9B'
}
}
});
```
Upvotes: 3 |
2018/03/20 | 471 | 1,727 | <issue_start>username_0: I am currently developing an android app which live streams the video to the kinesis video streams and the ability to play the stream in some other devices.
**What i did:**
I followed the link <https://docs.aws.amazon.com/kinesisvideostreams/latest/dg/producer-sdk-android.html> and was able to stream the video to the kinesis stream, which i could see in the stream dashboard page.
Now to consume the stream and play it in the device i found the java sample of it - <https://docs.aws.amazon.com/kinesisvideostreams/latest/dg/parser-library.html>. After some trial and error i was able to render the video in the JFrame.
**Question:**
My question is, isn't there an end-to-end support to produce and consume the kinesis video streams completely in android?<issue_comment>username_1: You can use simple CSS trick to change the **MenuItem** color on hover
Here is sample code
```
import React from 'react';
import './testJS.css'
import Menu from 'material-ui/Menu';
import MenuItem from 'material-ui/MenuItem';
class TestJS extends React.Component {
constructor(props) {
super(props);
}
render() {
return(
)};
}
export default TestJS;
```
and add following lines in your CSS file, need to use **!important** in order to override the default material-UI CSS
```
.menu-item{
background: #dcdcdc !important;
}
.menu-item:hover{
background: #0e7be9 !important;
}
```
Upvotes: -1 <issue_comment>username_2: Implemented hover and selected items styles using a theme
```
export const MyTheme = createMuiTheme({
palette: {
action: {
selected: '#E7A615',
hover: '#FFD371',
disabled: '#9B9B9B'
}
}
});
```
Upvotes: 3 |
2018/03/20 | 482 | 1,757 | <issue_start>username_0: Version Android SDK 5.1
I do this Code.
```
String path = Environment.getExternalStorageDirectory().getPath();
String innerPath = "/xxxx/strage/Download/"
StringPath = path + innerPath;
File[] files = new File(targetPath).listFiles();
for(File f:files){
f.delete();
}
```
after execute this code, I checked Dir by "FileCommander.apk" I confirm deleted.
but when conect this Android to PC And Check this Directory, not deleted.
Please help me.<issue_comment>username_1: ```
String innerPath = "/xxxx/strage/Download/"
```
seems like strage is written wrong.
shouldnt it mean `String innerPath = "/xxxx/storage/Download/"` ?
Upvotes: 0 <issue_comment>username_2: ```
File file= new File(android.os.Environment.getExternalStorageDirectory(),"MyFolder"); // My Folder is Folder
if (file.isDirectory())
{
listFile = file.listFiles();
for (int i = 0; i < listFile.length; i++)
{
if(String.valueOf(listFile[i].getAbsoluteFile()).equals("/storage/emulated/0/MyFolder/Adu.jpg")){//absolute path
File f=new File(String.valueOf(listFile[i].getAbsoluteFile()));
f.delete();
}
Log.d(myTag, "Response : "+listFile[i].getAbsolutePath());
}
}
```
Upvotes: 1 <issue_comment>username_3: This is unfortunately a [known old Android bug](https://issuetracker.google.com/issues/36956498), which google does not care about.
In short:
Sometimes depending on the way the file was created, it is not showing in the media device storage, when Android device is connected to the PC as MTP device. They should appear (or disappear in your case) after reboot, but there are known situations when reboot didn't help too.
Upvotes: 1 [selected_answer] |
2018/03/20 | 273 | 1,005 | <issue_start>username_0: While running HTML validator on my HTML code, the following error is encountered:
>
> Error: Attribute src not allowed on element a at this point.
>
>
>
The code snippet where the error occurs is:
How can I fix? Some internet pages tells me go with `data-src` rather than `src` attribute, while there is no information on Facebook regarding this.<issue_comment>username_1: The tag in HTML does not take in an attribute of `src`. The `href` attribute should work just fine in your code. Your code should look like:
```
```
But if you say the reason why you need a `src` attribute in your code maybe there's a workaround otherwise just use JavaScript for any kind of DOM manipulation.
Upvotes: 1 <issue_comment>username_2: `src` can't be used with tag. To see the list for its support, [click here](https://www.w3schools.com/tags/att_src.asp).
Upvotes: 1 <issue_comment>username_3: Simply Use **`data-`** with all attr for example
```
```
Upvotes: 3 [selected_answer] |
2018/03/20 | 412 | 1,078 | <issue_start>username_0: How to get length of each string in array element ["a", "a2", "b", "a2", "d"] just like "a" length is 1 and " a2" length is 2. how to i will check length of all strings insides array in swift.<issue_comment>username_1: You could do something like:
```
let result = ["a", "a2", "b", "a2", "d"].map {$0.count}
// result is [1, 2, 1, 2, 1]
```
Upvotes: 2 <issue_comment>username_2: `String.count` will do the work for you...
```
var strArray = ["a", "a2", "b", "a2", "d"]
strArray.forEach { (str) in
print(str.count)
}
```
Output:
>
> 1
> 2
> 1
> 2
> 1
>
>
>
Upvotes: 0 <issue_comment>username_3: ```
// Swift 4x
for arr in array {
print(arr.count)
}
// Swift 3x
for arr in array {
print(arr.characters.count)
}
```
Try above solution will get all the elements counts, and I have provide a solution in both swift 3 and swift 4.
Upvotes: 0 <issue_comment>username_4: ```
var strArray = ["a", "a2", "b", "a2", "d"]
for(index, element) in strArray.enumerated()
{
print(element.count)
}
```
//Output : 1 2 1 2 1
Upvotes: -1 |
2018/03/20 | 563 | 1,903 | <issue_start>username_0: As far as I know, the member function pointer only can be assigned to the pointer to member function type, and converted to any other except this will violate the standard, right?
And when calling `std::bind(&T::memberFunc, this)`, it should return a dependent type which depend on `T`.(*in std of VC++ version, it's a class template called `_Binder`*).
So the question becomes to why one `std::funcion` can cover all `_Binder`*(VC++ version)* types.
```
class A
{
public:
void func(){}
};
class B
{
public:
void func(){}
};
std::function f[2];
A a;
B b;
f[0] = std::bind(&A::func, &a);
f[1] = std::bind(&B::func, &b);
```
And I can't picture what type of the member of std::funcion which stored the function would be like, unless I am wrong from the first beginning.
[This question](https://stackoverflow.com/questions/37636373/how-stdbind-works-with-member-functions) only covered the member function need to be called with it's instance.
But mine is about why one `std::function` type can hold all `T` types.<issue_comment>username_1: In short what is happening is that `std::bind(&A::func, &a)` returns an object of a class *similar* to
```
class InternalClass
{
A* a_; // Will be initialized to &a
public:
void operator()(void)
{
a_->func();
}
};
```
[Note that this is highly simplified]
The callable `operator()` function is what is matches the `void(void)` signature of the `std::function`.
Upvotes: 2 <issue_comment>username_2: I think the implementation would probably like this:
```
template
class std::bind
{
public:
std::bind(callable_t call, param_t p)
{
_func = [call, p]()/* using lambda to capture all data for future calling */
{
p->call();
};
}
operator std::function()
{
return \_func;
}
private:
std::function \_func;
};
```
And **lambda** is the key.
Upvotes: 1 [selected_answer] |
2018/03/20 | 1,431 | 4,322 | <issue_start>username_0: I have an assignment, where I'm to sort a list from low to high. But my program gives out an inverse of the expected order. This is my futile attempt at the assignment. Please help me I am genuinely stuck. Hopefully it is a noob mistake.
```
from random import *
def main():
# initializing variables
numList = []; #the list of integers
numListLength = 25; #the number of integers in numList array
maxShuffles = 1000; #the number of times numList is to be shuffled
#populating numList
while len(numList) < numListLength :
randomElement = randint(-100, 100)
numList.append(randomElement)
printNow("List before shuffling: " )
printNow(numList)
#shuffle the list multiple times
shuffleCount = 0
while shuffleCount < maxShuffles :
i = randrange( 0, len(numList) )
j = randrange( 0, len(numList) )
if i < j :
#compare the contents of those locations
if numList[i] < numList[j] :
#swap the contents
original_i = numList[i]
original_j = numList[j]
numList[i] = original_j
numList[j] = original_i
elif j < i :
if numList[j] < numList[i] :
#swap the contents
original_i = numList[i]
original_j = numList[j]
numList[i] = original_j
numList[j] = original_i
#increment shuffleCounter
shuffleCount = shuffleCount + 1
#shuffling done, display results
printNow("List after shuffling: ")
printNow(numList)
main()
```<issue_comment>username_1: ```
from random import *
def main():
# initializing variables
numList = []; #the list of integers
numListLength = 25; #the number of integers in numList array
maxShuffles = 1000; #the number of times numList is to be shuffled
#populating numList
while len(numList) < numListLength :
randomElement = randint(-100, 100)
numList.append(randomElement)
printNow("List before shuffling: " )
printNow(numList)
#shuffle the list multiple times
shuffleCount = 0
while shuffleCount < maxShuffles :
i = randrange( 0, len(numList) )
j = randrange( 0, len(numList) )
if i < j :
#compare the contents of those locations
if numList[i] > numList[j] : #Inverted < sign
#swap the contents
original_i = numList[i]
original_j = numList[j]
numList[i] = original_j
numList[j] = original_i
elif j < i :
if numList[j] > numList[i] : #Inverted < sign
#swap the contents
original_i = numList[i]
original_j = numList[j]
numList[i] = original_j
numList[j] = original_i
else: #Handling i==j case
continue
#increment shuffleCounter
shuffleCount = shuffleCount + 1
#shuffling done, display results
printNow("List after shuffling: ")
printNow(numList)
main()
```
Upvotes: 1 [selected_answer]<issue_comment>username_2: In order to print the reverse order of what your program prints, change your `i < j` to `i > j` and `j < i` to `i < j`. Do the same for your `numList[i] > numList[j]`.
Your code will now print something like:
```
List before shuffling:
[26, 52, -58, 48, -91, -53, -20, -7, 78, -74, 10, -8, 29, -57, 31, 80, -76, -48, 45, -59, -46, -23, 33, -64, -89]
List after shuffling:
[-91, -89, -76, -74, -64, -59, -58, -57, -53, -46, -48, -23, -20, -8, -7, 10, 26, 29, 31, 33, 45, 48, 52, 78, 80]
```
Upvotes: 0 <issue_comment>username_3: ```
from random import randint, randrange
def main():
# initializing variables
num_list_length = 25 # the number of integers in num_list array
max_shuffles = 1000 # the number of times num_list is to be shuffled
# populating num_list
num_list = [randint(-100,100) for i in range(num_list_length)]
print("List before shuffling: " )
print(num_list)
# shuffle the list multiple times
for shuffle_count in range(max_shuffles):
i = randrange(0, len(num_list))
j = randrange(0, len(num_list))
if i > j: # ensure i is always smaller than j
i, j = j, i
#compare the contents of those locations
if num_list[i] < num_list[j]:
num_list[i], num_list[j] = num_list[j], num_list[i]
#shuffling done, display results
print("List after shuffling: ")
print(num_list)
if __name__ == "__main__":
main()
```
Upvotes: 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.