date
stringlengths 10
10
| nb_tokens
int64 60
629k
| text_size
int64 234
1.02M
| content
stringlengths 234
1.02M
|
---|---|---|---|
2018/03/22 | 1,007 | 3,453 | <issue_start>username_0: I am trying to remove a div element with javascript.I have following code but for some reason it is not working
HTML:
```
-
-
-
-
```
my JS
```
function removediv(input) {
document.getElementById('yes-drop').removeChild(input.parentNode);
}
```
[Fiddle Link](https://jsfiddle.net/hcnrbu3k/3/)
In the fiddle I want to remove the element once when it is dragged.(After dragging a clone of element is formed
**Update 1**
My main aim is that I should be able to remove any of those element when I click the button for that particular element
**Update 2**
In my fiddle when I drag a element a copy of that element is created.I want to remove/delete that copy of element when button is clicked<issue_comment>username_1: Implement `OnInit` while declaring the component's class and move your initialization code to `ngOnInit` function.
```
@Component({
...
})
export class componentClass implements OnInit {
...
ngOnInit() {
// initialization code block
}
}
```
Mention that Angular(Version2+) provides [life hook](https://angular.io/guide/lifecycle-hooks) for a component from been created to been destroyed.
---
For `ng-init` at `ng-repeat` part, From Angular2, you should use `ngFor` instead and `ngFor` only allows a limited set of local variables to be defined, see **[DOC](https://angular.io/api/common/NgForOf#local-variables)**.
Upvotes: 2 <issue_comment>username_2: I did not understand your request, could you explain yourself better?
why do not you try to use the @component ...
```
@Component({
selector: 'tag-selector',
templateUrl: './pagina.html',
styleUrls: ['./pagina.css']
})
export class Controller{
your code
}
```
Edit:
if you declare the $scope out of Init, it should work anyway
```
angular.module("app", [])
.controller("controller", function($scope) {
$scope.init = function() {
};
$scope.modules = [{
label: 'Module A',
children: [
'Module A - 1',
'Module A - 2',
'Module A - 3'
]
}, {
label: 'Module B',
children: [
'Module B - 1',
'Module B - 2',
'Module B - 3'
]
}, {
label: 'Module C',
children: [
'Module C - 1',
'Module C - 2',
'Module C - 3'
]
}];
});
```
I'm sorry, but I'm not sure I fully understood the question ...
Upvotes: 0 <issue_comment>username_3: You could do it like this.
You loop over your array with \*ngFor. The button toggles the corresponding boolean value, which defines if your element is shown or not (with the \*ngIf directive)
```
@Component({
selector: 'my-app',
template: `
toggle
{{module.label}}
----------------
- {{child}}
`,
})
```
Then initialize your variables:
```
export class AppComponent {
modules:any[];
show:boolean[];
constructor() {
this.modules = [
{
label: 'Module A',
children: [
'Module A - 1',
'Module A - 2',
'Module A - 3'
]
},
{
label: 'Module B',
children: [
'Module B - 1',
'Module B - 2',
'Module B - 3'
]
},
{
label: 'Module C',
children: [
'Module C - 1',
'Module C - 2',
'Module C - 3'
]
}
];
this.show = this.modules.map(()=>true);
}
}
```
Upvotes: 3 [selected_answer] |
2018/03/22 | 905 | 3,210 | <issue_start>username_0: I integrated Fire-base Notification CRUL Code with Codeigniter. sometimes I am getting an error but not all the times.
I have integrated below code to the controller
Controller Code
```
$newDate=Date('m-d-Y H:i:s');
$test_str=$user->us_name. ' Clocked at '.$newDate;
$res = array();
$res['data']['title'] = $user->us_name.' - Clocked In';
$res['data']['is_background'] = "TRUE";
$res['data']['message'] = $test_str;
$res['data']['image'] = 'http://api.androidhive.info/images/minion.jpg';
$res['data']['payload'] = 'individual';
$res['data']['timestamp'] = date('Y-m-d G:i:s');
$res['data']['act_tab'] = 0;
$cur_id1=$this->db->query("Select token from devices")->result();
foreach($cur_id1 as $cur_id) {
$fields = array('to' => $cur_id->token,'data' => $res);
$this->notif_model->sendPushNotification($fields);
}
```
Model Code
```
function sendPushNotification($fields) {
// Set POST variables
$url = 'https://fcm.googleapis.com/fcm/send';
$headers = array(
'Authorization: key=MyServerKey',
'Content-Type: application/json'
);
// Open connection
$ch = curl_init();
// Set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Disabling SSL Certificate support temporarly
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
// Execute post
$result = curl_exec($ch);
if ($result === FALSE) {
die('Curl failed: ' . curl_error($ch));
}
// Close connection
curl_close($ch);
return $result;
}
```
While running this sometimes I am getting the error
>
> Curl failed: OpenSSL SSL\_connect: SSL\_ERROR\_SYSCALL in connection to fcm.googleapis.com:443
>
>
><issue_comment>username_1: Try to add
`curl_setopt($ch, CURLOPT_SSLVERSION, 3);`
Upvotes: 1 <issue_comment>username_2: ```
function sendPushNotification($fields) {
// Set POST variables
$url = 'https://fcm.googleapis.com/fcm/send';
$headers = array(
'Authorization: key=MyServerKey',
'Content-Type: application/json'
);
// Open connection
$ch = curl_init();
// Set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSLVERSION, 3);
// Disabling SSL Certificate support temporarly
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
// Execute post
$result = curl_exec($ch);
if ($result === FALSE) {
die('Curl failed: ' . curl_error($ch));
}
// Close connection
curl_close($ch);
return $result;
}
```
Upvotes: 0 |
2018/03/22 | 590 | 2,239 | <issue_start>username_0: Open File
This is my gradle file:
```
apply plugin: 'com.android.application'
android {
compileSdkVersion 27
buildToolsVersion "27.0.1"
defaultConfig {
applicationId "com.landdrops.cricketfantacy.androidbottom"
minSdkVersion 21
targetSdkVersion 27
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs')
implementation 'com.android.support:appcompat-v7:27.0.1'
implementation 'com.android.support:design:27.0.1'
implementation 'com.android.support.constraint:constraint-layout:1.0.2'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test.runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:2.2.2'
}
```
I am getting
>
> Error:(23, 0) Could not find method implementation() for arguments [directory 'libs'] on object of type org.gradle.api.internal.artifacts.dsl.dependencies.DefaultDependencyHandler.
> Open File
>
>
><issue_comment>username_1: I was able to correct this error by updating most dependencies to current version (not sure that necessary, and when the most current version conflicted with a dependency of another component, I reverted one release back and it cleared up the mismatch. At this time, I am using 27.1.0 for appCompat, design. (I use 27.0.3 for build tools tho)
Gradle wrapper to version 4.4 (this was actually prompted for me to do when loading an outdated project and updating the plugin)
Adjusted project build.gradle to use:
classpath 'com.android.tools.build:gradle:3.1.1'
Upvotes: 2 [selected_answer]<issue_comment>username_2: For my Java library project I needed to use `java-library` plugin instead of `java`:
```
- apply plugin: 'java'
+ apply plugin: 'java-library'
```
Upvotes: 6 |
2018/03/22 | 636 | 2,412 | <issue_start>username_0: I am working with `RecyclerView`, the adapter and XML is the same for `RecyclerView` in 3 activities. The issue is in `getItemCount()` because 3 different types of `ArrayList` is populated within the same adapter.
How can I use different types of `ArrayList` with the same adapter?<issue_comment>username_1: I suggest you build an Interface which is implemented by the 3 ArrayList extensions you created and that contains the method you need for the recycler adapter.
Upvotes: 0 <issue_comment>username_2: First you need to create 3 Getter-Setter. e.g.
`ModelA` , `ModelB`, `ModelC`
Now create a arraylist of `Object` which accept any type of class object. e.g
```
ArrayList objectList = new ArrayList<>();
```
Now add your models in `objectList` when you needed like `objectList.add(modelA);`
here `modelA` is object of `ModelA` class.
Now you have to use this `objectList` in your adapter and then the main part comes, You have to create conditions in your adapter's `onBindViewHolder` method. Like this,
```
if(objectList.get(position) instanceof ModelA){
//TODo your ModelA operations
}else if (objectList.get(position) instanceof ModelB){
//TODo your ModelB operations
}else if (objectList.get(position) instanceof ModelC){
//TODo your ModelC operations
}
```
This works for you because you have same layout for all otherwise you have to play with `ViewTypes`
Upvotes: 2 [selected_answer]<issue_comment>username_3: This adapter class implementation can give you some idea of what you want to achieve
```
class GenericAdapter extends RecyclerView.Adapter {
private List data;
GenericAdapter(List data) {
this.data = data;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
...
...
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.bindData(data.get(position));
}
@Override
public int getItemCount() {
return data.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
...
...
ViewHolder(View itemView) {
super(itemView);
// bind the view references
...
...
}
void bindData(Object data) {
if (data instanceof Model1) {
// bind data for model class 1
...
...
} else if (data instanceof Model2) {
// bind data for model class 2
...
...
} else if (data instanceof Model3) {
// bind data for model class 3
...
...
}
}
}
}
```
Upvotes: 1 |
2018/03/22 | 643 | 2,320 | <issue_start>username_0: on click of a button I am trying to find the closest class containing a string. The HTML looks like:
```
Click me
```
and my JavaScript is
```
$('.clickme').on('mouseup', function(event) {
var description = $(this).closest('div[class*=:contains(feature)]').attr('class');
console.log("Description "+description);
});
```
All I am getting in console is:
```
Description undefined
```<issue_comment>username_1: Assuming it's really a substring check you want (not a class selector), you don't want the `contains(...)` bit, that's what `*=` means:
```js
$('.clickme').on('mouseup', function(event) {
var description = $(this).closest('div[class*=feature]').attr('class');
// Change here -------------------------------^^^^^^^
console.log("Description "+description);
});
```
```html
Click me
```
If the string may contain quotes or other characters that don't fit the definition of a [CSS identifier](https://www.w3.org/TR/CSS21/syndata.html#value-def-identifier) (or if you just want to be cautious), put quotes around the value: `.closest('div[class*="feature I am"]')`
---
In your example, though, `feature` is a class so you'd want to use a class selector (`.closest("div.feature")`).
Upvotes: 2 <issue_comment>username_2: Just use class selector with `.closest()` no need to use `:contains()`
```js
$('.clickme').on('mouseup', function(event) {
var description = $(this).closest('.feature').attr('class');
console.log("Description "+description);
});
```
```html
Click me
```
Upvotes: 1 <issue_comment>username_3: Replace contains with `class*="feature"`
```js
$('.clickme').on('mouseup', function(event) {
var description = $(this).closest('div[class*="feature"]').attr('class');
console.log("Description " + description);
});
```
```html
Click me
```
Upvotes: 0 <issue_comment>username_4: ```js
$('.clickme').on('mouseup', function(event) {
var description = $(this).closest("[class^=feature]").prop('class');
console.log("Description "+description);
});
```
```html
Click me
```
the selector should be like this for wildcard.
Upvotes: 0 <issue_comment>username_5: keep the string inside the double quotes
```
var description = $(this).closest('div[class*=:contains("feature")]').attr('class');
```
Upvotes: 0 |
2018/03/22 | 952 | 3,259 | <issue_start>username_0: What is the difference between skipWhile and filter operators?
```
const source = interval(1000);
const example = source.pipe(skipWhile(val => val < 5));
const subscribe = example.subscribe(val => console.log(val));
const source = interval(1000);
const example = source.pipe(filter(val => val > 5));
const subscribe = example.subscribe(val => console.log(val));
```<issue_comment>username_1: The difference is that upon its expression evaluating to `false`, skipWhile changes over to **mirroring** its source observable - so it will cease to filter out any further values.
For example:
```
Observable.from([1,2,3,4,5])
.pipe(filter(val => val % 2 == 0)) // filters out odd numbers
.subscribe(val => console.log(val)); // emits 2,4
Observable.from([1,2,3,4,5])
.pipe(skipWhile(val => val % 2 == 1)) // filters odd numbers until an even number comes along
.subscribe(val => console.log(val)); // emits 2,3,4,5
```
Upvotes: 7 [selected_answer]<issue_comment>username_2: ```
Observable.from(["Citizen 1","Citizen 2","President","Citizen 3","Citizen 4"])
.pipe(filter(val => val == "President")) // Only let the president into the bunker.
.subscribe(val => console.log(val)); // emits President
Observable.from(["Citizen 1","Citizen 2","President", "Citizen 3","Citizen 4"])
.pipe(skipWhile(val => val != "President")) // Let the citizens enter the bunker, but only after the president enters.
.subscribe(val => console.log(val)); // emits President, Citizen 3, Citizen 4
```
Upvotes: 4 <issue_comment>username_3: `skipWhile` operator will ignore the emissions until the specified condition becomes false, but after that, it will continue to take values from the source observable as is.
```
const randomNumbersLessThanEqualToTen = interval(1000).pipe(map((num) => {
const randomNumber = Math.floor(Math.random()*num);
console.log('Random Number Generated', randomNumber);
return randomNumber;
}), skipWhile(num => num < 10));
randomNumbersLessThanEqualToTen.subscribe((number) => {
console.log('Number not skipped', number);
});
```
o/p
```
Random Number Generated 6
Random Number Generated 0
Random Number Generated 5
Random Number Generated 0
Random Number Generated 5
Random Number Generated 11
Number not skipped 11
Random Number Generated 6
```
As soon as 11 (i.e. num < 10 === false) got generated and emitted all the generated numbers were taken and printed.
Here is an example of `filter`:
```
const randomNumbers = interval(1000).pipe(map((num) => {
const randomNumber = Math.floor(Math.random() * num);
console.log('Random Number Generated', randomNumber);
return randomNumber;
}), filter(num => num > 10));
randomNumbers.subscribe((number) => {
console.log('Number is greater than 10 -->', number);
});
```
o/p
```
Random Number Generated 7
Random Number Generated 11
Number is greater than 10 --> 11
Random Number Generated 13
Number is greater than 10 --> 13
Random Number Generated 13
Number is greater than 10 --> 13
Random Number Generated 3
Random Number Generated 2
```
So above output simply showcased that filter simply filters the emissions on the basis of the condition specified and it filters throughout the lifetime of observable.
Upvotes: 3 |
2018/03/22 | 2,492 | 10,836 | <issue_start>username_0: I've been struggling with the new `NotificationChannels` which is introduced in API 26 and up.
I'm developing an app with an option to choose whether to be notified in four cases:
1. Sound and Vibrate.
2. Sound only.
3. Vibrate only.
4. No sound or vibrate, just a pop-up.
In all cases, my app notify with sound and vibrate whatever I choose.
My code is:
```
NotificationCompat.Builder builder;
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
builder = new NotificationCompat.Builder(context, CHANNEL_ID);
int importance;
NotificationChannel channel;
//Boolean for choosing Sound
if(sound) {
importance = NotificationManager.IMPORTANCE_DEFAULT;
} else {
importance = NotificationManager.IMPORTANCE_LOW;
}
channel = new NotificationChannel(CHANNEL_ID, CHANNEL_NAME, importance);
channel.setDescription(CHANNEL_DESC);
//Boolean for choosing Vibrate
if(vibrate) {
channel.enableVibration(true);
} else {
channel.enableVibration(false);
}
notificationManager.createNotificationChannel(channel);
} else {
builder = new NotificationCompat.Builder(context);
}
if(sound && vibrate) {
//Sound and Vibrate
builder.setDefaults(Notification.DEFAULT_ALL);
} else if(sound && !vibrate) {
//Sound
builder.setDefaults(Notification.DEFAULT_SOUND);
} else if(!sound && vibrate) {
//Vibrate
builder.setDefaults(Notification.DEFAULT_VIBRATE);
} else if(!sound && !vibrate) {
//None
//Do nothing! just notification with no sound or vibration
}
builder.setSmallIcon(R.drawable.ic_logo)
.setContentTitle(title)
.setContentText(text)
.setAutoCancel(true)
.setOnlyAlertOnce(false)
.setPriority(Notification.PRIORITY_MAX);
```
Also, I change `CHANNEL_ID` every time I run the app, so it gets a fresh Channel ID every time just for testing until I find a solution.
Of course, it works fine with API less than 26.
Thank you, guys!<issue_comment>username_1: i found this in the documentation. May be it will help you :
>
> On Android 8.0 (API level 26) and above, importance of a notification is determined by the importance of the channel the notification was posted to. Users can change the importance of a notification channel in the system settings (figure 12). On Android 7.1 (API level 25) and below, importance of each notification is determined by the notification's priority.
>
>
>
And also :
>
> Android O introduces notification channels to provide a unified system to help users manage notifications. When you target Android O, you must implement one or more notification channels to display notifications to your users. If you don't target Android O, your apps behave the same as they do on Android 7.0 when running on Android O devices.
>
>
>
And finally :
>
> * Individual notifications must now be put in a specific channel.
> * Users can now turn off notifications per channel, instead of turning off all notifications from an app.
> * Apps with active notifications display a notification "badge" on top of their app icon on the home/launcher screen.
> * Users can now snooze a notification from the drawer. You can set an automatic timeout for a notification.
> * Some APIs regarding notification behaviors were moved from Notification to NotificationChannel. For example, use NotificationChannel.setImportance() instead of NotificationCompat.Builder.setPriority() for Android 8.0 and higher.
>
>
>
Upvotes: 4 [selected_answer]<issue_comment>username_2: Thank you all guys,
I managed to solve it by simply creating a `NotificationCompat.Builder` and `NotificationChannel` for each and every case, and notify each `Builder` when its condition is met.
I don't know if this is the best practice, but I'll try to optimize the code later, if anyone has an opinion on that feel free. But it worked so fine now.
Here's my code:
```
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationCompat.Builder builder_all, builder_sound, builder_vibrate, builder_none;
NotificationChannel channel_all = new NotificationChannel(CHANNEL_ID_ALL, CHANNEL_NAME_ALL, NotificationManager.IMPORTANCE_HIGH);
channel_all.enableVibration(true);
notificationManager.createNotificationChannel(channel_all);
NotificationChannel channel_sound = new NotificationChannel(CHANNEL_ID_SOUND, CHANNEL_NAME_SOUND, NotificationManager.IMPORTANCE_HIGH);
channel_sound.enableVibration(false);
notificationManager.createNotificationChannel(channel_sound);
NotificationChannel channel_vibrate = new NotificationChannel(CHANNEL_ID_VIBRATE, CHANNEL_NAME_VIBRATE, NotificationManager.IMPORTANCE_HIGH);
channel_vibrate.setSound(null, null);
channel_vibrate.enableVibration(true);
notificationManager.createNotificationChannel(channel_vibrate);
NotificationChannel channel_none = new NotificationChannel(CHANNEL_ID_NONE, CHANNEL_NAME_NONE, NotificationManager.IMPORTANCE_HIGH);
channel_none.setSound(null, null);
channel_none.enableVibration(false);
notificationManager.createNotificationChannel(channel_none);
//Boolean for Sound or Vibrate are chosen
if(sound && vibrate) {
builder_all = new NotificationCompat.Builder(context, CHANNEL_ID_ALL);
builder_all.setSmallIcon(R.drawable.ic_logo)
.setContentTitle(title)
.setContentText(text)
.setAutoCancel(true)
.setOnlyAlertOnce(false);
switch (transition) {
case Geofence.GEOFENCE_TRANSITION_ENTER:
builder_all.setSmallIcon(R.drawable.ic_entered_white);
break;
case Geofence.GEOFENCE_TRANSITION_EXIT:
builder_all.setSmallIcon(R.drawable.ic_left_white);
break;
}
notificationManager.notify(notificationID, builder_all.build());
} else if(sound && !vibrate) {
builder_sound = new NotificationCompat.Builder(context, CHANNEL_ID_SOUND);
builder_sound.setSmallIcon(R.drawable.ic_logo)
.setContentTitle(title)
.setContentText(text)
.setAutoCancel(true)
.setOnlyAlertOnce(false);
switch (transition) {
case Geofence.GEOFENCE_TRANSITION_ENTER:
builder_sound.setSmallIcon(R.drawable.ic_entered_white);
break;
case Geofence.GEOFENCE_TRANSITION_EXIT:
builder_sound.setSmallIcon(R.drawable.ic_left_white);
break;
}
notificationManager.notify(notificationID, builder_sound.build());
} else if(!sound && vibrate) {
builder_vibrate = new NotificationCompat.Builder(context, CHANNEL_ID_VIBRATE);
builder_vibrate.setSmallIcon(R.drawable.ic_logo)
.setContentTitle(title)
.setContentText(text)
.setAutoCancel(true)
.setOnlyAlertOnce(false);
switch (transition) {
case Geofence.GEOFENCE_TRANSITION_ENTER:
builder_vibrate.setSmallIcon(R.drawable.ic_entered_white);
break;
case Geofence.GEOFENCE_TRANSITION_EXIT:
builder_vibrate.setSmallIcon(R.drawable.ic_left_white);
break;
}
notificationManager.notify(notificationID, builder_vibrate.build());
} else if(!sound && !vibrate) {
builder_none = new NotificationCompat.Builder(context, CHANNEL_ID_NONE);
builder_none.setSmallIcon(R.drawable.ic_logo)
.setContentTitle(title)
.setContentText(text)
.setAutoCancel(true)
.setOnlyAlertOnce(false);
switch (transition) {
case Geofence.GEOFENCE_TRANSITION_ENTER:
builder_none.setSmallIcon(R.drawable.ic_entered_white);
break;
case Geofence.GEOFENCE_TRANSITION_EXIT:
builder_none.setSmallIcon(R.drawable.ic_left_white);
break;
}
notificationManager.notify(notificationID, builder_none.build());
}
} else {
NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
if(sound && vibrate) {
//Sound and Vibrate
builder.setDefaults(Notification.DEFAULT_ALL);
} else if(sound && !vibrate) {
//Sound
builder.setDefaults(Notification.DEFAULT_SOUND);
} else if(!sound && vibrate) {
//Vibrate
builder.setDefaults(Notification.DEFAULT_VIBRATE);
} else if(!sound && !vibrate) {
//None
//Do nothing! just notification with no sound or vibration
}
builder.setSmallIcon(R.drawable.ic_logo)
.setContentTitle(title)
.setContentText(text)
.setAutoCancel(true)
.setOnlyAlertOnce(false)
.setPriority(Notification.PRIORITY_MAX);
switch (transition) {
case Geofence.GEOFENCE_TRANSITION_ENTER:
builder.setSmallIcon(R.drawable.ic_entered_white);
break;
case Geofence.GEOFENCE_TRANSITION_EXIT:
builder.setSmallIcon(R.drawable.ic_left_white);
break;
}
notificationManager.notify(notificationID, builder.build());
}
```
Upvotes: 3 <issue_comment>username_3: If your sound and vibrate bools come from your app settings, then note that the intention is you should remove those from your app and send the user to the channel settings instead:
"After you create a notification channel, you cannot change the notification channel's visual and auditory behaviors programmatically—only the user can change the channel behaviors from the system settings. To provide your users easy access to these notification settings, you should add an item in your app's settings UI that opens these system settings."
<https://developer.android.com/training/notify-user/channels#UpdateChannel>
Upvotes: 0 |
2018/03/22 | 2,145 | 9,307 | <issue_start>username_0: I'm using Entity Framework Core in context of a ASP.Net Core MVC application. A snippet of the data model looks like that:
```
public class Seminar
{
public int ID { get; set; }
public string Name { get; set; }
public Person Teacher { get; set; }
public int TeacherID { get; set; }
public IList Students { get; set; }
public Seminar()
{
Students = new List();
}
}
```
EF automatically assigns the property `TeacherID` to reflect the ID of the entity `Teacher` (foreign key). This is quite handy to be used in ASP.Net. Is there any similar concept for the to-many-reference `Students`?
At the end I would like to create a multi-select in ASP.Net. Hence, I need a list of IDs of assigned `Students` to this seminar.<issue_comment>username_1: i found this in the documentation. May be it will help you :
>
> On Android 8.0 (API level 26) and above, importance of a notification is determined by the importance of the channel the notification was posted to. Users can change the importance of a notification channel in the system settings (figure 12). On Android 7.1 (API level 25) and below, importance of each notification is determined by the notification's priority.
>
>
>
And also :
>
> Android O introduces notification channels to provide a unified system to help users manage notifications. When you target Android O, you must implement one or more notification channels to display notifications to your users. If you don't target Android O, your apps behave the same as they do on Android 7.0 when running on Android O devices.
>
>
>
And finally :
>
> * Individual notifications must now be put in a specific channel.
> * Users can now turn off notifications per channel, instead of turning off all notifications from an app.
> * Apps with active notifications display a notification "badge" on top of their app icon on the home/launcher screen.
> * Users can now snooze a notification from the drawer. You can set an automatic timeout for a notification.
> * Some APIs regarding notification behaviors were moved from Notification to NotificationChannel. For example, use NotificationChannel.setImportance() instead of NotificationCompat.Builder.setPriority() for Android 8.0 and higher.
>
>
>
Upvotes: 4 [selected_answer]<issue_comment>username_2: Thank you all guys,
I managed to solve it by simply creating a `NotificationCompat.Builder` and `NotificationChannel` for each and every case, and notify each `Builder` when its condition is met.
I don't know if this is the best practice, but I'll try to optimize the code later, if anyone has an opinion on that feel free. But it worked so fine now.
Here's my code:
```
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationCompat.Builder builder_all, builder_sound, builder_vibrate, builder_none;
NotificationChannel channel_all = new NotificationChannel(CHANNEL_ID_ALL, CHANNEL_NAME_ALL, NotificationManager.IMPORTANCE_HIGH);
channel_all.enableVibration(true);
notificationManager.createNotificationChannel(channel_all);
NotificationChannel channel_sound = new NotificationChannel(CHANNEL_ID_SOUND, CHANNEL_NAME_SOUND, NotificationManager.IMPORTANCE_HIGH);
channel_sound.enableVibration(false);
notificationManager.createNotificationChannel(channel_sound);
NotificationChannel channel_vibrate = new NotificationChannel(CHANNEL_ID_VIBRATE, CHANNEL_NAME_VIBRATE, NotificationManager.IMPORTANCE_HIGH);
channel_vibrate.setSound(null, null);
channel_vibrate.enableVibration(true);
notificationManager.createNotificationChannel(channel_vibrate);
NotificationChannel channel_none = new NotificationChannel(CHANNEL_ID_NONE, CHANNEL_NAME_NONE, NotificationManager.IMPORTANCE_HIGH);
channel_none.setSound(null, null);
channel_none.enableVibration(false);
notificationManager.createNotificationChannel(channel_none);
//Boolean for Sound or Vibrate are chosen
if(sound && vibrate) {
builder_all = new NotificationCompat.Builder(context, CHANNEL_ID_ALL);
builder_all.setSmallIcon(R.drawable.ic_logo)
.setContentTitle(title)
.setContentText(text)
.setAutoCancel(true)
.setOnlyAlertOnce(false);
switch (transition) {
case Geofence.GEOFENCE_TRANSITION_ENTER:
builder_all.setSmallIcon(R.drawable.ic_entered_white);
break;
case Geofence.GEOFENCE_TRANSITION_EXIT:
builder_all.setSmallIcon(R.drawable.ic_left_white);
break;
}
notificationManager.notify(notificationID, builder_all.build());
} else if(sound && !vibrate) {
builder_sound = new NotificationCompat.Builder(context, CHANNEL_ID_SOUND);
builder_sound.setSmallIcon(R.drawable.ic_logo)
.setContentTitle(title)
.setContentText(text)
.setAutoCancel(true)
.setOnlyAlertOnce(false);
switch (transition) {
case Geofence.GEOFENCE_TRANSITION_ENTER:
builder_sound.setSmallIcon(R.drawable.ic_entered_white);
break;
case Geofence.GEOFENCE_TRANSITION_EXIT:
builder_sound.setSmallIcon(R.drawable.ic_left_white);
break;
}
notificationManager.notify(notificationID, builder_sound.build());
} else if(!sound && vibrate) {
builder_vibrate = new NotificationCompat.Builder(context, CHANNEL_ID_VIBRATE);
builder_vibrate.setSmallIcon(R.drawable.ic_logo)
.setContentTitle(title)
.setContentText(text)
.setAutoCancel(true)
.setOnlyAlertOnce(false);
switch (transition) {
case Geofence.GEOFENCE_TRANSITION_ENTER:
builder_vibrate.setSmallIcon(R.drawable.ic_entered_white);
break;
case Geofence.GEOFENCE_TRANSITION_EXIT:
builder_vibrate.setSmallIcon(R.drawable.ic_left_white);
break;
}
notificationManager.notify(notificationID, builder_vibrate.build());
} else if(!sound && !vibrate) {
builder_none = new NotificationCompat.Builder(context, CHANNEL_ID_NONE);
builder_none.setSmallIcon(R.drawable.ic_logo)
.setContentTitle(title)
.setContentText(text)
.setAutoCancel(true)
.setOnlyAlertOnce(false);
switch (transition) {
case Geofence.GEOFENCE_TRANSITION_ENTER:
builder_none.setSmallIcon(R.drawable.ic_entered_white);
break;
case Geofence.GEOFENCE_TRANSITION_EXIT:
builder_none.setSmallIcon(R.drawable.ic_left_white);
break;
}
notificationManager.notify(notificationID, builder_none.build());
}
} else {
NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
if(sound && vibrate) {
//Sound and Vibrate
builder.setDefaults(Notification.DEFAULT_ALL);
} else if(sound && !vibrate) {
//Sound
builder.setDefaults(Notification.DEFAULT_SOUND);
} else if(!sound && vibrate) {
//Vibrate
builder.setDefaults(Notification.DEFAULT_VIBRATE);
} else if(!sound && !vibrate) {
//None
//Do nothing! just notification with no sound or vibration
}
builder.setSmallIcon(R.drawable.ic_logo)
.setContentTitle(title)
.setContentText(text)
.setAutoCancel(true)
.setOnlyAlertOnce(false)
.setPriority(Notification.PRIORITY_MAX);
switch (transition) {
case Geofence.GEOFENCE_TRANSITION_ENTER:
builder.setSmallIcon(R.drawable.ic_entered_white);
break;
case Geofence.GEOFENCE_TRANSITION_EXIT:
builder.setSmallIcon(R.drawable.ic_left_white);
break;
}
notificationManager.notify(notificationID, builder.build());
}
```
Upvotes: 3 <issue_comment>username_3: If your sound and vibrate bools come from your app settings, then note that the intention is you should remove those from your app and send the user to the channel settings instead:
"After you create a notification channel, you cannot change the notification channel's visual and auditory behaviors programmatically—only the user can change the channel behaviors from the system settings. To provide your users easy access to these notification settings, you should add an item in your app's settings UI that opens these system settings."
<https://developer.android.com/training/notify-user/channels#UpdateChannel>
Upvotes: 0 |
2018/03/22 | 931 | 3,113 | <issue_start>username_0: I am using a bunch class to transform a dict to an object.
```
class Bunch(object):
""" Transform a dict to an object """
def __init__(self, kwargs):
self.__dict__.update(kwargs)
```
The problem is , i have a key with a dot in its name({'test.this':True}).
So when i call:
```
spam = Bunch({'test.this':True})
dir(spam)
```
I have the attibute:
```
['__class__',
'__delattr__',
...
'__weakref__',
'test.this']
```
But i can't access it:
```
print(spam.test.this)
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
in ()
----> 1 print(spam.test.this)
AttributeError: 'Bunch' object has no attribute 'test'
```
i got an AttributeError.
How can i access this attribute?<issue_comment>username_1: Try spam["test.this"] or spam.get("test.this")
Upvotes: -1 <issue_comment>username_2: Implement [`__getitem__(self, key)`](https://docs.python.org/3/reference/datamodel.html?emulating-container-types#object.__getitem__):
```
class D():
def __init__(self, kwargs):
self.__dict__.update(kwargs)
def __getitem__(self, key):
return self.__dict__.get(key)
d = D({"foo": 1, "bar.baz": 2})
print(d["foo"])
print(d["bar.baz"])
```
**Edit:**
I don't recommend accessing `d.__dict__` directly from a client of a `D` instance. Client code like this
```
d = D({"foo": 1, "bar.baz": 2})
print(d.__dict__.get("bar.baz"))
```
is trying to reach into the underpants of `d` and requires knowledge about implementation details of `D`.
Upvotes: 2 <issue_comment>username_3: You can use [`getattr`](https://docs.python.org/3/library/functions.html#getattr):
```
>>> getattr(spam, 'test.this')
True
```
Alternatively, you can get the value from the object's `__dict__`. Use [`vars`](https://docs.python.org/3/library/functions.html#vars) to get `spam`'s dict:
```
>>> vars(spam)['test.this']
True
```
Upvotes: 3 [selected_answer]<issue_comment>username_4: A correct suggestion would be to avoid using dot in the variables.
And even if we use somehow, its better to get it using **getattr**.
```
getattr(spam, 'test.this')
```
If we are being stubborn by avoid standards so this may help.
```
class Objectify(object):
def __init__(self, obj):
for key in obj:
if isinstance(obj[key], dict):
self.__dict__.update(key=Objectify(obj[key]))
else:
self.__dict__.update(key=obj[key])
class Bunch(object):
""" Transform a dict to an object """
def __init__(self, obj, loop=False):
for key in obj:
if isinstance(obj[key], dict):
self.__dict__.update(key=Objectify(obj[key]))
else:
self.__dict__.update(key=obj[key])
spam1 = Bunch({'test': {'this': True}})
print(spam1.test.this)
spam2 = Bunch({'test': {'this': {'nested_this': True}}})
print(spam2.test.this.nested_this)
```
Not provided **test.this** as the key. You may want to create a nested dict iterating through the keys having dots.
Upvotes: 0 |
2018/03/22 | 441 | 1,980 | <issue_start>username_0: I am making an app in which I want to have a page where I show a language selection page. So far I've included English, Hindi, and Marathi, with English set as the default.
My question is:
1. how to change the whole application language in Selected Language?
2. After choose the language whenever I reopen the application its give previous chosen language?<issue_comment>username_1: Put your all text in String file. For each language create separate String file(Deutsch values-de/strings.xml, French values-fr/strings.xml)
and while you need to change language call following function. For English language set **"en"** for another set corresponding key
#Kotlin
```
val config = resources.configuration
val locale = Locale("en")
Locale.setDefault(locale)
config.locale = locale
resources.updateConfiguration(config, resources.displayMetrics)
```
#Android Java
```
Configuration config = getBaseContext().getResources().getConfiguration();
Locale locale = new Locale("en");
Locale.setDefault(locale);
config.locale = locale;
getBaseContext().getResources().updateConfiguration(config,
getBaseContext().getResources().getDisplayMetrics());
```
Upvotes: 3 <issue_comment>username_2: ```
String lang= "en";
public void changeLang(String lang) {
Configuration config = getBaseContext().getResources().getConfiguration();
if (!"".equals(lang) && !config.locale.getLanguage().equals(lang)) {
locale = new Locale(lang);
Locale.setDefault(locale);
Configuration conf = new Configuration(config);
conf.locale = locale;
getBaseContext().getResources().updateConfiguration(conf, getBaseContext().getResources().getDisplayMetrics());
}
}
```
Try out this method....This will definitely work..
As you select your preferred language, pass your selected language code in this method and this will change the language of whole application.
Upvotes: 1 |
2018/03/22 | 820 | 3,453 | <issue_start>username_0: I am developing a web page using react with typescript in visual studio 2017 and am very new to it. I am having some trouble accessing the parameters passed to a component and making a parameter optional. Below is my code:-
routes.tsx:
```
export const routes =
//<= this works, but i want id parameter to be optional. I tried (/:id) but the component does not render if i do this.
```
Home.tsx:
```
export class Home extends React.Component, {}> {
public render() {
console.log(this.props.match.params); //<= I can see the id which i pass in the console
return
{this.props.match.params} //<= this does not work and gives me a runtime error 'Unhandled rejection Invariant Violation: Objects are not valid as a React child (found: object with keys {id}). If you meant to render a collection of children, use an array instead or wrap the object using createFragment(object) from the React add-ons'
=============================================================================================================================================================================================================================================================================================================================================
```
1)How do i provide optional parameters to a component?
2)How do i display the passed parameter in Home component?
Any help would be appreciated. Thanks in advance<issue_comment>username_1: Use a `?` like this to pass an optional parameter:
[Start reading here](https://reacttraining.com/react-router/web/api/Route/path-string) to find out more
To display the variable, use `{this.props.match.params.id}`. If you want to handle the case when id is not present, something like this can be used:
`{this.props.match.params.id || 'sorry lol no id is specified'}`
To clarify why you get an error: "params" is an object that holds all parameters. React does not know how to display an object. If you want to display an object, you could use `JSON.stringify(params)` but I dont think that is what you're looking for.
Upvotes: 2 <issue_comment>username_2: The problem is that you want to render Object because this.props.match.params points to whole object, so you either have to stringify or ask for certain property like Id.
```
{JSON.stringify(this.props.match.params)}
```
or
```
{this.props.match.params.id}
ofcourse that for this thing you have to accept id as parametr /home/:id
```
Since you are using typescript it depends if you are writing class(Component) or function, either way the error you are geting is because you havent typed it correctly, but since you are reffering to this.props, I will assume its class.
```
class App extends React.Component {}
interface Props {
match: any;
}
```
Yes its weak typing, but unless you import typing directly from the library, it would take you a while to type the whole thing, plus doing it in each file would be stupid.
Upvotes: 0 <issue_comment>username_3: Using `?` as said by @username_1 to pass an optional parameter worked for me.
As far as retrieving the id property from params what i did was create an object for this.props.match.params and then use that object to retrieve the id. Following is the code i used:-
```
let data = Object.create(this.props.match.params);
```
and then
```
data.id
```
will retrieve my id without giving any compilation errors in typescript
Upvotes: 3 [selected_answer] |
2018/03/22 | 877 | 3,204 | <issue_start>username_0: My AngularJS client passes the date value in epoch milliseconds to my server which uses C#.NET. My client and server resides in different time zones. I am passing the date value from client side as following which returns the epoch milliseconds:
```
var date = $scope.date.getTime()
```
If I had a date selected from my client as '***Tue Jan 16 2018 00:00:00 GMT+0530 (India Standard Time)***' the epoch value corresponds to ***1516041000000***
But when I pass this epoch to my server side the GMT/UTC time,i.e, ***Monday, January 15, 2018 6:30:00 PM*** is getting saved to my database.
I was trying to pass the GMT offset to my server via my API header and add the offset value to the UTC time. But this causes issues when there is daylight saving since the offset is different for various date values.
```
DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
var savedDate = epoch.AddMilliseconds(long.Parse(passedDateEpoch)).AddMinutes(ClientGmtOffset);
```
Is there any way to save the entered exact date in server database using the epoch time value itself. I don't want any time part or incorrect dates to be saved into the database.<issue_comment>username_1: Use a `?` like this to pass an optional parameter:
[Start reading here](https://reacttraining.com/react-router/web/api/Route/path-string) to find out more
To display the variable, use `{this.props.match.params.id}`. If you want to handle the case when id is not present, something like this can be used:
`{this.props.match.params.id || 'sorry lol no id is specified'}`
To clarify why you get an error: "params" is an object that holds all parameters. React does not know how to display an object. If you want to display an object, you could use `JSON.stringify(params)` but I dont think that is what you're looking for.
Upvotes: 2 <issue_comment>username_2: The problem is that you want to render Object because this.props.match.params points to whole object, so you either have to stringify or ask for certain property like Id.
```
{JSON.stringify(this.props.match.params)}
```
or
```
{this.props.match.params.id}
ofcourse that for this thing you have to accept id as parametr /home/:id
```
Since you are using typescript it depends if you are writing class(Component) or function, either way the error you are geting is because you havent typed it correctly, but since you are reffering to this.props, I will assume its class.
```
class App extends React.Component {}
interface Props {
match: any;
}
```
Yes its weak typing, but unless you import typing directly from the library, it would take you a while to type the whole thing, plus doing it in each file would be stupid.
Upvotes: 0 <issue_comment>username_3: Using `?` as said by @username_1 to pass an optional parameter worked for me.
As far as retrieving the id property from params what i did was create an object for this.props.match.params and then use that object to retrieve the id. Following is the code i used:-
```
let data = Object.create(this.props.match.params);
```
and then
```
data.id
```
will retrieve my id without giving any compilation errors in typescript
Upvotes: 3 [selected_answer] |
2018/03/22 | 1,095 | 3,655 | <issue_start>username_0: An old question recently reoccurred: What is the correct way of setting `CMAKE_MODULE_PATH`? But this applies to pretty much any list. However there might be a difference for general text, but IMO only when that text might contain semicolons.
Precondition: That variable might be unset, empty, or set
Options:
1. `set (CMAKE_MODULE_PATH ${CMAKE_CURRENT_SOURCE_DIR}/cmakeModules ${CMAKE_MODULE_PATH})`
2. `set (CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmakeModules" ${CMAKE_MODULE_PATH})`
3. `list(APPEND CMAKE_MODULE_PATH ${CMAKE_CURRENT_SOURCE_DIR}/cmakeModules)`
4. `list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmakeModules")`
5. `if (NOT CMAKE_MODULE_PATH)
set (CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmakeModules")
else()
set (CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmakeModules;${CMAKE_MODULE_PATH}")
endif()`
To include some reasoning:
a) 1. might fail, when there are spaces in the path so one has to use 2. to avoid this. Is this correct?
b) 3/4 looks like the better/more concise way. Again are the spaces required?
c) 5. Has (ugly) special case handling which 1-4 avoid. Is this required?
Related: [cmake: when to quote variables?](https://stackoverflow.com/questions/35847655/cmake-when-to-quote-variables)
But I'm still unsure, when to use quotes especially when dealing with paths and lists.
Bonus: What exactly does happen during evaluation? If all `${...}` would get replaced by the value of the variable before it is passed to the function then e.g. the following would not work and requires spaces. But it does work as intended:
```
set(FOO_DIR "my space path")
set(CMAKE_LIST /usr)
set(CMAKE_LIST ${CMAKE_LIST} ${FOO_DIR}/foo)
oder: list(APPEND CMAKE_LIST ${FOO_DIR}/foo)
```
This also applies to calls to other functions. E.g.:
```
set_target_properties(MYTARGET PROPERTIES
IMPORTED_LOCATION ${FOO_DIR}/foo
)
```
Question is: Why? Where in the standard is this specified?<issue_comment>username_1: a) True
b) False. And yes, I prefer this way too.
c) False
Upvotes: 1 <issue_comment>username_2: Both `set` and `list` are valid for append a value to a list:
```
list(APPEND CMAKE_MODULE_PATH ${CMAKE_CURRENT_SOURCE_DIR}/cmakeModules)
```
or
```
set (CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} ${CMAKE_CURRENT_SOURCE_DIR}/cmakeModules)
```
The first form (with 'list') is preferred, as it is shorter and doesn't duplicate the variable's name.
---
Resulted list is **not affected** by quoting appended value. That is, quotes in such cases are just a matter of taste.
**NOTE 1**: Quoting doesn't affect only for specific cases (`set` and `list` commands). In other cases quoting could be crucial.
**NOTE 2**: If current path contains semicolon (`;`) , it will be wrongly treated either quoted or unquoted.
---
### Why quotes are meaningless here
Assuming variable `A` contains semicolon(s), like
```
set(A "a/b;c/d")
```
treatements of
```
${A}/cmakeModules
```
and
```
"${A}/cmakeModules"
```
are *different* when **passed to the function**: the first case is treated as two parameters, but the second - as single parameter. You may view that difference in `message()` calls:
```
# give: a/bc/d/cmakeModules
message(STATUS ${A}/cmakeModules)
# give: a/b;c/d/cmakeModules
message(STATUS "${A}/cmakeModules")
```
But both these treatments give the same effect in `list` command:
```
set(B "m") # Initial value
# Either command below sets B to 3(!) values: m;a/b;c/d/cmakeModules
list(APPEND B ${A}/cmakeModules)
list(APPEND B "${A}/cmakeModules")
```
It could be treated as "CMake variables contains flatten lists".
Upvotes: 2 |
2018/03/22 | 648 | 2,421 | <issue_start>username_0: I am trying to run my first program on Android Studio 3.0.1. However when i fire up the emulator, it comes transparent and nothing shows up on it.
[](https://i.stack.imgur.com/IyUMv.png)<issue_comment>username_1: i am able to resolve the same.In the setting for emulator , select software emulation instead of automatic and it worked.Hope it works for all
Upvotes: 1 <issue_comment>username_2: Start virtual device. On the additional panel click button "...", go to Settings, select tab Advanced, change OpenGL renderer, restart virtual device. For me helps ANGLE (D3D11) or "SwiftShader" options
Upvotes: 2 <issue_comment>username_3: If you use a laptop with optmus technology, try going to device manager and disabling your Intel HD graphics.
Upvotes: 0 <issue_comment>username_4: If you are using NVIDIA GPU and on the same time you have Integrated graphics card, it's possible to experience graphics emulation issues. You can verify which GPU executes current emulation. If it's NVIDIA you can try to select force usage of Integrated GPU:
1. Open Emulator in Android studio
2. Verify you have transparent screen on device
3. Open "NVIDIA Control Panel" Application
4. Go to "3D Settings" -> "Manage 3D Settings" -> Tab "Program Settings"
[see how screen looks like](https://i.stack.imgur.com/oX8Rn.png) -> Click button "Add" in "1. Select a program to customize" and choose "/qemu\_system-x86\_x64.exe" -> In "2. Select the preferred graphics processor for this program" set "Integrated graphics"
5. Restart AVD emulator
6. Done
Upvotes: 1 <issue_comment>username_5: I was able to resolve this problem by changing the emulator settings to software emulation.
`Tools > AVD manager > Edit (Edit icon) >` change `graphics` to `software emulation`. (by default it shows Automatic Emulation )
[](https://i.stack.imgur.com/xCfVf.png)
[](https://i.stack.imgur.com/G57zW.png)
Upvotes: 4 <issue_comment>username_6: I tried all the above options but then had to apply one more setting for whatever reason.
On the emulator, hit the "..." to get to Extended Controls. Then at the bottom of the drawer is the "Settings". In the general tab, toggle "Show window frame around device" and it no longer became transperrant.
Upvotes: 1 |
2018/03/22 | 809 | 2,876 | <issue_start>username_0: I am facing some problem to parse the date format `dd-m-y` with `SimpleDateFormat` class in Java.
So is there any date formatter for this date format type (`12-oct-14`)?<issue_comment>username_1: ```
SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yy")
```
If you are using Java 8 or 9, then please refer [this](https://stackoverflow.com/questions/22463062/how-to-parse-format-dates-with-localdatetime-java-8)
Upvotes: 3 <issue_comment>username_2: ```
String format = "dd-MMM-yy";
SimpleDateFormat sdf = new SimpleDateFormat(format);
System.out.println(sdf.format(new Date()));
System.out.println(sdf.parse("12-oct-14"));
```
Result:
>
> 22-Mar-18
>
> Sun Oct 12 00:00:00 UTC 2014
>
>
>
Upvotes: 1 <issue_comment>username_3: First step: create a `DateTimeFormatter` by using the format you need and the `ofPattern()` method.
Second step: create two `LocalDate` objects with the `.parse(CharSequence text, DateTimeFormatter format)` method.
Third step: use `firstDate.untill(secondDate)` and receive a `Period` object.
Fourth step: use `.getDays()` method to get the number of days from the `Period` object.
Upvotes: 1 <issue_comment>username_4: The other answers might have worked, but there's a little detail that most people often forget.
The month name in your input ("oct") is in English (or in some other language where October's abbreviation is "oct", but I'm assuming English here, as this doesn't change the answer).
When you create a `SimpleDateFormat`, it uses the JVM default locale (represented by the class `java.util.Locale`). In your case, `new SimpleDateFormat("dd-MMM-yy")` worked because your JVM's default locale probably is already English.
But the default locale can be changed, even at runtime, and even by other applications running in the same JVM. In other words, you have no control over it and no guarantees at all that the default will always be English.
In this case, if you *know* that the input is always in English, it's safer and much better to explicity use a `java.util.Locale` in the formatter:
```
SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yy", Locale.ENGLISH);
```
Even better is to use - if available to you - the [Java 8's date/time API](https://docs.oracle.com/javase/tutorial/datetime/). This API is much better than `SimpleDateFormat`, because [it solves many of the problems this class has](https://eyalsch.wordpress.com/2009/05/29/sdf/).
The code might look harder in the beginning, but it's totally worth to learn the new API:
```
DateTimeFormatter fmt = new DateTimeFormatterBuilder()
// case insensitive, for month name
.parseCaseInsensitive()
// pattern for day-month-year
.appendPattern("dd-MMM-yy")
// use English for month name
.toFormatter(Locale.ENGLISH);
System.out.println(LocalDate.parse("12-oct-14", fmt));
```
Upvotes: 2 |
2018/03/22 | 996 | 3,552 | <issue_start>username_0: <https://codepen.io/evie4411/pen/geWzNM>
I would like to have control of how wide my text is.
And both < hr > elements, I would like to extend and retract depending on the width of the text within them.
Right now, the text spreads right across the screen and I would like it to fit within the width of the menu... but I would need flexibility when I work on other elements of my site.
Below, is the css for the whole screen element an it has worked for me well so far across all pages, and i would love if this could stay the same- I am scared of my site looking like a bundle of margins and borders- please see the code pen for the rest
```
.outer {
min-height: 100vh;
position: relative;
z-index: 2;
overflow: hidden;
justify-content: center;
display: flex;
flex-direction: column;
align-items: center;
}
```
Many Thanks!!<issue_comment>username_1: ```
SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yy")
```
If you are using Java 8 or 9, then please refer [this](https://stackoverflow.com/questions/22463062/how-to-parse-format-dates-with-localdatetime-java-8)
Upvotes: 3 <issue_comment>username_2: ```
String format = "dd-MMM-yy";
SimpleDateFormat sdf = new SimpleDateFormat(format);
System.out.println(sdf.format(new Date()));
System.out.println(sdf.parse("12-oct-14"));
```
Result:
>
> 22-Mar-18
>
> Sun Oct 12 00:00:00 UTC 2014
>
>
>
Upvotes: 1 <issue_comment>username_3: First step: create a `DateTimeFormatter` by using the format you need and the `ofPattern()` method.
Second step: create two `LocalDate` objects with the `.parse(CharSequence text, DateTimeFormatter format)` method.
Third step: use `firstDate.untill(secondDate)` and receive a `Period` object.
Fourth step: use `.getDays()` method to get the number of days from the `Period` object.
Upvotes: 1 <issue_comment>username_4: The other answers might have worked, but there's a little detail that most people often forget.
The month name in your input ("oct") is in English (or in some other language where October's abbreviation is "oct", but I'm assuming English here, as this doesn't change the answer).
When you create a `SimpleDateFormat`, it uses the JVM default locale (represented by the class `java.util.Locale`). In your case, `new SimpleDateFormat("dd-MMM-yy")` worked because your JVM's default locale probably is already English.
But the default locale can be changed, even at runtime, and even by other applications running in the same JVM. In other words, you have no control over it and no guarantees at all that the default will always be English.
In this case, if you *know* that the input is always in English, it's safer and much better to explicity use a `java.util.Locale` in the formatter:
```
SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yy", Locale.ENGLISH);
```
Even better is to use - if available to you - the [Java 8's date/time API](https://docs.oracle.com/javase/tutorial/datetime/). This API is much better than `SimpleDateFormat`, because [it solves many of the problems this class has](https://eyalsch.wordpress.com/2009/05/29/sdf/).
The code might look harder in the beginning, but it's totally worth to learn the new API:
```
DateTimeFormatter fmt = new DateTimeFormatterBuilder()
// case insensitive, for month name
.parseCaseInsensitive()
// pattern for day-month-year
.appendPattern("dd-MMM-yy")
// use English for month name
.toFormatter(Locale.ENGLISH);
System.out.println(LocalDate.parse("12-oct-14", fmt));
```
Upvotes: 2 |
2018/03/22 | 2,430 | 6,725 | <issue_start>username_0: I have a `Datatable` in my C# code
```
DataTable dtDetails;
```
My Datatable how following records;
```
id | tid | code | pNameLocal | qty | price
-------------------------------------------------
1 |101 | 101 | some_local_name | 2 |20.36
2 |102 | 202 | some_local_name | 1 |15.30 // exactly same entry
3 |102 | 202 | some_local_name | 1 |15.30 // exactly same entry
4 |102 | 202 | some_local_name | 1 |10.00 //same entry as same tid but price is different
5 |102 | 202 | some_local_name | 2 |15.30 //same entry as same tid but different qty
6 |102 | 202 | some_local_name2 | 1 |15.30 //same entry as same tid but pNameLocal different
7 |103 | 202 | some_local_name | 1 |15.30 // different entry of same product see different tid
8 |104 | 65 | some_local_name | 5 |05.00
9 |105 | 700 | some_local_name | 2 |07.01 // does not exist in "dtProduct"
```
what to do is records which are exactly same but entered multiple times to be merged into one, but keeping their `qty` column and `price` column updated, for example in above `DaraRows` **id 2 and 3 have exactly same record as id 1**, this should be one record and update `qty` and `price` by adding from duplicate records which are exactly same. this should update in same `DataTable` or in new.<issue_comment>username_1: You can take the DataTable as enumarable, and use Linq to create your new DataTable. The code would look something like this:
```
DataTable newDt = dt.AsEnumerable()
.GroupBy(r => r.Field("tid"))
.Select(g => {
var row = dt.NewRow();
row["tid"] = g.Key;
row["code"] = g.First(r => r["code"] != null).Field("code");
row["pNameLocal"] = g.First(r => r["pNameLocal"] != null).Field("pNameLocal");
row["qty"] = g.Sum(r => r.Field("qty"));
row["price"] = g.Sum(r => r.Field("price"));
return row;
}).CopyToDataTable();
```
See sample console application below, setting up sample data, executing the grouping and displaying the original and result Datatables.
```
using System;
using System.Data;
using System.Linq;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
var dt = FillUpTestTable();
DumpDataTable(dt);
DataTable newDt = dt.AsEnumerable()
.GroupBy(r => r.Field("tid"))
.Select(g => {
var row = dt.NewRow();
row["tid"] = g.Key;
row["code"] = g.First(r => r["code"] != null).Field("code");
row["pNameLocal"] = g.First(r => r["pNameLocal"] != null).Field("pNameLocal");
row["qty"] = g.Sum(r => r.Field("qty"));
row["price"] = g.Sum(r => r.Field("price"));
return row;
}).CopyToDataTable();
Console.WriteLine();
Console.WriteLine("Result: ");
Console.WriteLine();
DumpDataTable(newDt);
Console.ReadLine();
}
private static DataTable FillUpTestTable()
{
DataTable dt = new DataTable();
dt.Columns.Add("id", typeof(int));
dt.Columns.Add("tid", typeof(int));
dt.Columns.Add("code", typeof(int));
dt.Columns.Add("pNameLocal", typeof(string));
dt.Columns.Add("qty", typeof(int));
dt.Columns.Add("price", typeof(double));
dt.Rows.Add(1, 101, 101, "some\_local\_name", 2, 20.36);
dt.Rows.Add(2, 102, 202, "some\_local\_name", 2, 15.30);
dt.Rows.Add(3, 102, 202, "some\_local\_name", 2, 15.30);
dt.Rows.Add(4, 102, 202, "some\_local\_name", 2, 10.00);
dt.Rows.Add(5, 102, 202, "some\_local\_name", 2, 15.30);
dt.Rows.Add(6, 102, 202, "some\_local\_name2", 1, 15.30);
dt.Rows.Add(7, 103, 202, "some\_local\_name", 2, 15.30);
dt.Rows.Add(8, 104, 202, "some\_local\_name", 2, 05.00);
dt.Rows.Add(9, 105, 202, "some\_local\_name", 2, 07.01);
return dt;
}
private static void DumpDataTable(DataTable newDt)
{
foreach (DataRow dataRow in newDt.Rows)
{
foreach (var item in dataRow.ItemArray)
{
Console.Write(item + " | ");
}
Console.WriteLine();
}
}
}
```
}
Upvotes: 2 <issue_comment>username_2: This is what you can do If rows are to be distinct based on **ALL COLUMNS**.
```
DataTable newDatatable = dt.DefaultView.ToTable(true, "tid", "code", "pNameLocal", "qty", "price");
```
The columns you mention here, only those will be returned back in newDatatable.
Upvotes: 0 <issue_comment>username_3: You need like this in datatable:
```
SELECT tid, code, pNameLocal, sum(qty),sum(price) FROM @tbl
group by tid, code, pNameLocal,qty, price
```
You can use linq. Try following code. I tried to use your sample records.
```
DataTable dt = new DataTable();
DataColumn[] dcCol = {
new DataColumn("id",typeof(int)),
new DataColumn("tid", typeof(int)),
new DataColumn("code", typeof(int)),
new DataColumn("pNameLocal", typeof(string)),
new DataColumn("qty", typeof(int)),
new DataColumn("price", typeof(decimal))
};
dt.Columns.AddRange(dcCol);
dt.Rows.Add(1, 101, 101, "some_local_name", 2, 20.36);
dt.Rows.Add(2, 102, 202, "some_local_name", 1, 10.00);
dt.Rows.Add(3, 102, 202, "some_local_name", 1, 15.30);
dt.Rows.Add(4, 102, 202, "some_local_name", 1, 10.00);
dt.Rows.Add(5, 102, 202, "some_local_name", 2, 15.30);
dt.Rows.Add(6, 102, 202, "some_local_name2", 1, 15.30);
dt.Rows.Add(7, 103, 202, "some_local_name", 1, 15.30);
dt.Rows.Add(8, 104, 65, "some_local_name", 5, 05.00);
dt.Rows.Add(9, 105, 700, "some_local_name", 2, 07.01);
var dtnew = from r in dt.AsEnumerable()
group r by new
{
tid = r.Field("tid"),
code = r.Field("code"),
pNameLocal = r.Field("pNameLocal"),
qty = r.Field("qty"),
price = r.Field("price")
} into grp
select new
{
tid1 = grp.Key.tid,
code1 = grp.Key.code,
pNameLocal1 = grp.Key.pNameLocal,
SumQty = grp.Sum(r => grp.Key.qty),
sumPrice = grp.Sum(r => grp.Key.price)
};
```
Upvotes: 1 <issue_comment>username_4: You can use `GroupBy` on an anonymous type containing all columns apart from count and price:
```
var aggregatedRowData = dtDetails.AsEnumerable()
.Select(r => new
{
tid = r.Field("tid"),
code = r.Field("code"),
pNameLocal = r.Field("pNameLocal"),
qty = r.Field("qty"),
price = r.Field("price"),
})
.GroupBy(x => new { x.tid, x.code, x.pNameLocal })
.Select(grp => new
{
grp.Key.tid,
grp.Key.code,
grp.Key.pNameLocal,
qty = grp.Sum(x => x.qty),
price = grp.Sum(x => x.price)
});
DataTable aggregatedTable = dtDetails.Clone(); // empty, same columns
foreach (var x in aggregatedRowData)
aggregatedTable.Rows.Add(x.tid, x.code, x.pNameLocal, x.qty, x.price);
```
Upvotes: 1 |
2018/03/22 | 942 | 2,758 | <issue_start>username_0: I wanted to answer to [this question](https://stackoverflow.com/questions/49385950/haskell-removing-adjacent-duplicates-from-a-list) using `until`. But that does not work and I've concluded that I don't understand `until`.
So I take the function given by the OP, verbatim:
```
removeAdjDups :: (Eq a) => [a] -> [a]
removeAdjDups [] = []
removeAdjDups [x] = [x]
removeAdjDups (x : y : ys)
| x == y = removeAdjDups ys
| otherwise = x : removeAdjDups (y : ys)
```
Then I write a `True/False` function retuning whether there is a duplicate:
```
hasAdjDups :: (Eq a) => [a] -> Bool
hasAdjDups [] = False
hasAdjDups [x] = False
hasAdjDups (x : y : ys)
| x == y = True
| otherwise = hasAdjDups (y : ys)
```
Finally I use `until` as follows:
```
f :: (Eq a) => [a] -> [a]
f x = until hasAdjDups removeAdjDups x
```
And that does not work :
```
> hasAdjDups "aabccddcceef"
True
> removeAdjDups "aabccddcceef"
"bf"
> f "aabccddcceef"
"aabccddcceef"
```
I misunderstand `until`, or I did a mistake ?<issue_comment>username_1: You are probably forgetting a `not`:
```
f :: (Eq a) => [a] -> [a]
f x = until (not . hasAdjDups) removeAdjDups x
f "aabccddcceef" -- "bf"
```
Upvotes: 2 <issue_comment>username_2: The [**`until :: (a -> Bool) -> (a -> a) -> a -> a`**](http://hackage.haskell.org/package/base-4.11.0.0/docs/Prelude.html#v:until) is documented as:
>
> `until p f` yields the result of **applying `f` until `p` holds**.
>
>
>
It is implemented like:
>
>
> ```
> until p f = go
> where
> go x | p x = x
> | otherwise = go (f x)
>
> ```
>
>
So you provide a predicate `p`, and a function `f`. The function is also given an initial value `x`. By using recursion, it first checks if `p x` holds. In case it does, it returns `x`, otherwise, it makes a recursive call with `f x` as the new `x`.
So a more clean (but less efficient) implementation is probably:
```
until p f x | p x = x
| otherwise = until p f (f x)
```
If we analyze your function, we see:
```
f x = until hasAdjDups removeAdjDups x
```
So that means `f` will terminale removing adjacent duplicate characters from the moment it *has* adjacent duplicate characters. You probably want the opposite predicate:
```
f x = until (not . hasAdjDups) removeAdjDups x
```
Or even shorter:
```
f = until (not . hasAdjDups) removeAdjDups
```
Upvotes: 4 [selected_answer]<issue_comment>username_3: Well, `until` repeatedly applies the transformation to the value *until* the predicate matches. In your case, the input already `hasAdjDups`, so `removeAdjDups` is never called. You might be looking for `while`:
```
while = until . (not .)
```
Upvotes: 2 |
2018/03/22 | 1,285 | 4,072 | <issue_start>username_0: i have this kind of table
```
+----+------------+-------+------------+
| id | company_id | price | periods |
+----+------------+-------+------------+
| 1 | A1 | 500 | 2016-07-12 |
| 2 | A2 | 540 | 2018-01-21 |
| 3 | A1 | 440 | 2017-01-19 |
| 4 | A2 | 330 | 2016-01-12 |
| 5 | A3 | 333 | 2018-01-22 |
+----+------------+-------+------------+
```
and at first i want to just select the maximum `periods` and group them by `company_id` by using this query
```
SELECT salesreport.* FROM salesreport
INNER JOIN (SELECT company_id, MAX(periods) AS max_periods FROM salesreport WHERE periods < 2016-01-01 GROUP BY company_id) AS latest_report
ON salesreport.company_id = latest_report.company_id AND salesreport.periods = latest_report.max_periods;
```
and it will returning table like this
```
+----+------------+-------+------------+
| id | company_id | price | periods |
+----+------------+-------+------------+
| 2 | A2 | 540 | 2018-01-21 |
| 3 | A1 | 440 | 2017-01-19 |
| 5 | A3 | 333 | 2018-01-22 |
+----+------------+-------+------------+
```
but now i want to also make a limit on which maximum periods that i want to get along with grouping so, let say i want `periods <= 2017-01-01` then what i expect is
```
+----+------------+-------+------------+
| id | company_id | price | periods |
+----+------------+-------+------------+
| 1 | A1 | 500 | 2016-07-12 |
| 4 | A2 | 330 | 2016-01-12 |
+----+------------+-------+------------+
```
i tried to use `having` and also the normal `where` but none of them works
```
SELECT salesreport.* FROM salesreport
INNER JOIN (SELECT company_id, MAX(periods) AS max_periods FROM salesreport GROUP BY company_id HAVING MAX(periods) < 2017-01-01) AS latest_report
ON salesreport.company_id = latest_report.company_id AND salesreport.periods = latest_report.max_periods;
SELECT salesreport.* FROM salesreport
INNER JOIN (SELECT company_id, MAX(periods) AS max_periods FROM salesreport WHERE periods < 2017-01-01 GROUP BY company_id ) AS latest_report
ON salesreport.company_id = latest_report.company_id AND salesreport.periods = latest_report.max_periods;
```
and then i realize that maybe because of `MAX(periods)` but how do i get the highest value in groupBy if not using this aggregate? so maybe someone that are expert of query can give a insight to understand and solve this issue....
**Update**
thanks to @Accountant, he create this to help us see and find a solution, feel free to experiment on here <http://sqlfiddle.com/#!9/a7ae29/31><issue_comment>username_1: You just missed to put single qoute on the date value. This is working based on sqlfiddle demo by userid: accountant
Correct: MAX(periods) < '2017-01-01'
old: MAX(periods) < 2017-01-01
Upvotes: 2 <issue_comment>username_2: Use `sub-query` with *correlated* approach
```
select * from salesreport s
where periods = (select max(periods) from salesreport
where company_id = s.company_id and periods <= '2017-01-01')
```
Upvotes: 1 <issue_comment>username_3: Try this, Just get max data only where period is <'2017-01-01'
```
SELECT salesreport.* FROM salesreport
INNER JOIN
(
SELECT company_id, MAX(periods) AS max_periods
FROM salesreport where periods<'2017-01-01'
GROUP BY company_id
) AS latest_report
ON salesreport.company_id = latest_report.company_id
AND salesreport.periods = latest_report.max_periods;
```
Upvotes: 2 [selected_answer]<issue_comment>username_4: You don't need to compare MAX date, you just need to compare date (periods). Also remove `HAVING` clause.
```
SELECT salesreport.* FROM salesreport INNER JOIN (SELECT company_id, MAX(periods) AS max_periods FROM salesreport WHERE periods < '2017-01-01' GROUP BY company_id) AS latest_report ON salesreport.company_id = latest_report.company_id AND salesreport.periods = latest_report.max_periods
```
Please try this, it should work for you.
Upvotes: 0 |
2018/03/22 | 6,960 | 24,682 | <issue_start>username_0: All of a sudden, I am getting this error while building APK
```
Error:Execution failed for task ':app:transformResourcesWithMergeJavaResForDevDebug'.
> More than one file was found with OS independent path 'META-INF/android.arch.lifecycle_runtime.version'
```
I went through a lot of StackOverflow post related to `META-INF` issue such as `exclude 'META-INF/***' (LICENSE, NOTICE` etc etc) in `packagingOptions` but it's not working. I have uninstalled Java 9 also and installed JDK8. Here is the output when I run with `--stacktrace` option
```
Executing tasks: [:app:assembleDevDebug]
Parallel execution with configuration on demand is an incubating feature.
Configuration 'compile' in project ':app' is deprecated. Use 'implementation' instead.
registerResGeneratingTask is deprecated, use registerGeneratedFolders(FileCollection)
registerResGeneratingTask is deprecated, use registerGeneratedFolders(FileCollection)
registerResGeneratingTask is deprecated, use registerGeneratedFolders(FileCollection)
registerResGeneratingTask is deprecated, use registerGeneratedFolders(FileCollection)
:app:preBuild UP-TO-DATE
:app:preDevDebugBuild UP-TO-DATE
:app:compileDevDebugAidl UP-TO-DATE
:app:compileDevDebugRenderscript UP-TO-DATE
:app:checkDevDebugManifest UP-TO-DATE
:app:generateDevDebugBuildConfig UP-TO-DATE
:app:greendaoPrepare UP-TO-DATE
:app:greendao UP-TO-DATE
:app:prepareLintJar UP-TO-DATE
:app:generateDevDebugResValues UP-TO-DATE
:app:generateDevDebugResources UP-TO-DATE
:app:processDevDebugGoogleServices
Parsing json file: /Users/shikhardeep/StudioProjects/HOGAndroid_New/app/src/debug/google-services.json
:app:mergeDevDebugResources UP-TO-DATE
:app:createDevDebugCompatibleScreenManifests UP-TO-DATE
:app:processDevDebugManifest UP-TO-DATE
:app:splitsDiscoveryTaskDevDebug UP-TO-DATE
:app:processDevDebugResources UP-TO-DATE
:app:generateDevDebugSources UP-TO-DATE
:app:dataBindingExportBuildInfoDevDebug UP-TO-DATE
:app:javaPreCompileDevDebug UP-TO-DATE
:app:transformDataBindingWithDataBindingMergeArtifactsForDevDebug UP-TO-DATE
:app:compileDevDebugJavaWithJavac UP-TO-DATE
:app:compileDevDebugNdk NO-SOURCE
:app:compileDevDebugSources UP-TO-DATE
:app:mergeDevDebugShaders UP-TO-DATE
:app:compileDevDebugShaders UP-TO-DATE
:app:generateDevDebugAssets UP-TO-DATE
:app:mergeDevDebugAssets UP-TO-DATE
:app:transformClassesWithDexBuilderForDevDebug UP-TO-DATE
:app:transformClassesWithMultidexlistForDevDebug UP-TO-DATE
:app:transformDexArchiveWithDexMergerForDevDebug UP-TO-DATE
:app:mergeDevDebugJniLibFolders UP-TO-DATE
:app:transformNativeLibsWithMergeJniLibsForDevDebug UP-TO-DATE
:app:processDevDebugJavaRes NO-SOURCE
:app:transformResourcesWithMergeJavaResForDevDebug FAILED
FAILURE: Build failed with an exception.
* What went wrong:
Execution failed for task ':app:transformResourcesWithMergeJavaResForDevDebug'.
> More than one file was found with OS independent path 'META-INF/android.arch.lifecycle_runtime.version'
* Try:
Run with --info or --debug option to get more log output.
* Exception is:
org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':app:transformResourcesWithMergeJavaResForDevDebug'.
at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:100)
at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:70)
at org.gradle.api.internal.tasks.execution.SkipUpToDateTaskExecuter.execute(SkipUpToDateTaskExecuter.java:63)
at org.gradle.api.internal.tasks.execution.ResolveTaskOutputCachingStateExecuter.execute(ResolveTaskOutputCachingStateExecuter.java:54)
at org.gradle.api.internal.tasks.execution.ValidatingTaskExecuter.execute(ValidatingTaskExecuter.java:58)
at org.gradle.api.internal.tasks.execution.SkipEmptySourceFilesTaskExecuter.execute(SkipEmptySourceFilesTaskExecuter.java:88)
at org.gradle.api.internal.tasks.execution.ResolveTaskArtifactStateTaskExecuter.execute(ResolveTaskArtifactStateTaskExecuter.java:52)
at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:52)
at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.java:54)
at org.gradle.api.internal.tasks.execution.ExecuteAtMostOnceTaskExecuter.execute(ExecuteAtMostOnceTaskExecuter.java:43)
at org.gradle.api.internal.tasks.execution.CatchExceptionTaskExecuter.execute(CatchExceptionTaskExecuter.java:34)
at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker$1.run(DefaultTaskGraphExecuter.java:248)
at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:336)
at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:328)
at org.gradle.internal.progress.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:197)
at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:107)
at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:241)
at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:230)
at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker.processTask(DefaultTaskPlanExecutor.java:124)
at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker.access$200(DefaultTaskPlanExecutor.java:80)
at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker$1.execute(DefaultTaskPlanExecutor.java:105)
at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker$1.execute(DefaultTaskPlanExecutor.java:99)
at org.gradle.execution.taskgraph.DefaultTaskExecutionPlan.execute(DefaultTaskExecutionPlan.java:625)
at org.gradle.execution.taskgraph.DefaultTaskExecutionPlan.executeWithTask(DefaultTaskExecutionPlan.java:580)
at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker.run(DefaultTaskPlanExecutor.java:99)
at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor.process(DefaultTaskPlanExecutor.java:60)
at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter.execute(DefaultTaskGraphExecuter.java:128)
at org.gradle.execution.SelectedTaskExecutionAction.execute(SelectedTaskExecutionAction.java:37)
at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:37)
at org.gradle.execution.DefaultBuildExecuter.access$000(DefaultBuildExecuter.java:23)
at org.gradle.execution.DefaultBuildExecuter$1.proceed(DefaultBuildExecuter.java:43)
at org.gradle.execution.DryRunBuildExecutionAction.execute(DryRunBuildExecutionAction.java:46)
at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:37)
at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:30)
at org.gradle.initialization.DefaultGradleLauncher$ExecuteTasks.run(DefaultGradleLauncher.java:311)
at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:336)
at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:328)
at org.gradle.internal.progress.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:197)
at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:107)
at org.gradle.initialization.DefaultGradleLauncher.runTasks(DefaultGradleLauncher.java:202)
at org.gradle.initialization.DefaultGradleLauncher.doBuildStages(DefaultGradleLauncher.java:132)
at org.gradle.initialization.DefaultGradleLauncher.executeTasks(DefaultGradleLauncher.java:107)
at org.gradle.internal.invocation.GradleBuildController$1.call(GradleBuildController.java:78)
at org.gradle.internal.invocation.GradleBuildController$1.call(GradleBuildController.java:75)
at org.gradle.internal.work.DefaultWorkerLeaseService.withLocks(DefaultWorkerLeaseService.java:152)
at org.gradle.internal.invocation.GradleBuildController.doBuild(GradleBuildController.java:100)
at org.gradle.internal.invocation.GradleBuildController.run(GradleBuildController.java:75)
at org.gradle.tooling.internal.provider.runner.BuildModelActionRunner.run(BuildModelActionRunner.java:53)
at org.gradle.launcher.exec.ChainingBuildActionRunner.run(ChainingBuildActionRunner.java:35)
at org.gradle.launcher.exec.ChainingBuildActionRunner.run(ChainingBuildActionRunner.java:35)
at org.gradle.tooling.internal.provider.ValidatingBuildActionRunner.run(ValidatingBuildActionRunner.java:32)
at org.gradle.launcher.exec.RunAsBuildOperationBuildActionRunner$1.run(RunAsBuildOperationBuildActionRunner.java:43)
at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:336)
at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:328)
at org.gradle.internal.progress.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:197)
at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:107)
at org.gradle.launcher.exec.RunAsBuildOperationBuildActionRunner.run(RunAsBuildOperationBuildActionRunner.java:40)
at org.gradle.tooling.internal.provider.SubscribableBuildActionRunner.run(SubscribableBuildActionRunner.java:51)
at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:45)
at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:29)
at org.gradle.launcher.exec.BuildTreeScopeBuildActionExecuter.execute(BuildTreeScopeBuildActionExecuter.java:39)
at org.gradle.launcher.exec.BuildTreeScopeBuildActionExecuter.execute(BuildTreeScopeBuildActionExecuter.java:25)
at org.gradle.tooling.internal.provider.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.java:71)
at org.gradle.tooling.internal.provider.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.java:45)
at org.gradle.tooling.internal.provider.ServicesSetupBuildActionExecuter.execute(ServicesSetupBuildActionExecuter.java:51)
at org.gradle.tooling.internal.provider.ServicesSetupBuildActionExecuter.execute(ServicesSetupBuildActionExecuter.java:32)
at org.gradle.tooling.internal.provider.GradleThreadBuildActionExecuter.execute(GradleThreadBuildActionExecuter.java:36)
at org.gradle.tooling.internal.provider.GradleThreadBuildActionExecuter.execute(GradleThreadBuildActionExecuter.java:25)
at org.gradle.tooling.internal.provider.ParallelismConfigurationBuildActionExecuter.execute(ParallelismConfigurationBuildActionExecuter.java:43)
at org.gradle.tooling.internal.provider.ParallelismConfigurationBuildActionExecuter.execute(ParallelismConfigurationBuildActionExecuter.java:29)
at org.gradle.tooling.internal.provider.StartParamsValidatingActionExecuter.execute(StartParamsValidatingActionExecuter.java:64)
at org.gradle.tooling.internal.provider.StartParamsValidatingActionExecuter.execute(StartParamsValidatingActionExecuter.java:29)
at org.gradle.tooling.internal.provider.SessionFailureReportingActionExecuter.execute(SessionFailureReportingActionExecuter.java:55)
at org.gradle.tooling.internal.provider.SessionFailureReportingActionExecuter.execute(SessionFailureReportingActionExecuter.java:42)
at org.gradle.tooling.internal.provider.SetupLoggingActionExecuter.execute(SetupLoggingActionExecuter.java:58)
at org.gradle.tooling.internal.provider.SetupLoggingActionExecuter.execute(SetupLoggingActionExecuter.java:33)
at org.gradle.launcher.daemon.server.exec.ExecuteBuild.doBuild(ExecuteBuild.java:67)
at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
at org.gradle.launcher.daemon.server.exec.WatchForDisconnection.execute(WatchForDisconnection.java:37)
at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
at org.gradle.launcher.daemon.server.exec.ResetDeprecationLogger.execute(ResetDeprecationLogger.java:26)
at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
at org.gradle.launcher.daemon.server.exec.RequestStopIfSingleUsedDaemon.execute(RequestStopIfSingleUsedDaemon.java:34)
at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
at org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.call(ForwardClientInput.java:74)
at org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.call(ForwardClientInput.java:72)
at org.gradle.util.Swapper.swap(Swapper.java:38)
at org.gradle.launcher.daemon.server.exec.ForwardClientInput.execute(ForwardClientInput.java:72)
at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
at org.gradle.launcher.daemon.server.exec.LogAndCheckHealth.execute(LogAndCheckHealth.java:55)
at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
at org.gradle.launcher.daemon.server.exec.LogToClient.doBuild(LogToClient.java:62)
at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
at org.gradle.launcher.daemon.server.exec.EstablishBuildEnvironment.doBuild(EstablishBuildEnvironment.java:82)
at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
at org.gradle.launcher.daemon.server.exec.StartBuildOrRespondWithBusy$1.run(StartBuildOrRespondWithBusy.java:50)
at org.gradle.launcher.daemon.server.DaemonStateCoordinator$1.run(DaemonStateCoordinator.java:297)
at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:63)
at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:46)
at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:55)
Caused by: com.android.builder.merge.DuplicateRelativeFileException: More than one file was found with OS independent path 'META-INF/android.arch.lifecycle_runtime.version'
at com.android.builder.merge.StreamMergeAlgorithms.lambda$acceptOnlyOne$2(StreamMergeAlgorithms.java:75)
at com.android.builder.merge.StreamMergeAlgorithms.lambda$select$3(StreamMergeAlgorithms.java:100)
at com.android.builder.merge.IncrementalFileMergerOutputs$1.create(IncrementalFileMergerOutputs.java:86)
at com.android.builder.merge.DelegateIncrementalFileMergerOutput.create(DelegateIncrementalFileMergerOutput.java:61)
at com.android.build.gradle.internal.transforms.MergeJavaResourcesTransform$1.create(MergeJavaResourcesTransform.java:379)
at com.android.builder.merge.IncrementalFileMerger.updateChangedFile(IncrementalFileMerger.java:221)
at com.android.builder.merge.IncrementalFileMerger.mergeChangedInputs(IncrementalFileMerger.java:190)
at com.android.builder.merge.IncrementalFileMerger.merge(IncrementalFileMerger.java:77)
at com.android.build.gradle.internal.transforms.MergeJavaResourcesTransform.transform(MergeJavaResourcesTransform.java:411)
at com.android.build.gradle.internal.pipeline.TransformTask$2.call(TransformTask.java:222)
at com.android.build.gradle.internal.pipeline.TransformTask$2.call(TransformTask.java:218)
at com.android.builder.profile.ThreadRecorder.record(ThreadRecorder.java:102)
at com.android.build.gradle.internal.pipeline.TransformTask.transform(TransformTask.java:213)
at org.gradle.internal.reflect.JavaMethod.invoke(JavaMethod.java:73)
at org.gradle.api.internal.project.taskfactory.DefaultTaskClassInfoStore$IncrementalTaskAction.doExecute(DefaultTaskClassInfoStore.java:173)
at org.gradle.api.internal.project.taskfactory.DefaultTaskClassInfoStore$StandardTaskAction.execute(DefaultTaskClassInfoStore.java:134)
at org.gradle.api.internal.project.taskfactory.DefaultTaskClassInfoStore$StandardTaskAction.execute(DefaultTaskClassInfoStore.java:121)
at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter$1.run(ExecuteActionsTaskExecuter.java:122)
at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:336)
at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:328)
at org.gradle.internal.progress.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:197)
at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:107)
at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeAction(ExecuteActionsTaskExecuter.java:111)
at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:92)
... 102 more
* Get more help at https://help.gradle.org
BUILD FAILED in 2s
28 actionable tasks: 2 executed, 26 up-to-date
```
**This is my app/build.gradle file:**
```
buildscript {
repositories {
maven { url 'https://maven.fabric.io/public' }
maven { url 'https://oss.sonatype.org/content/repositories/snapshots' }
}
dependencies {
classpath 'io.fabric.tools:gradle:1.+'
}
}
repositories {
mavenCentral()
maven { url 'https://maven.fabric.io/public' }
maven { url 'https://oss.sonatype.org/content/repositories/snapshots' }
maven { url 'http://static.clmbtech.com/maven' }
}
apply plugin: 'com.android.application'
apply plugin: 'io.fabric'
apply plugin: 'org.greenrobot.greendao'
apply plugin: 'com.android.application'
android {
compileSdkVersion 27
defaultConfig {
applicationId ""
minSdkVersion 19
targetSdkVersion 27
versionCode 63
versionName "2.2.8"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
vectorDrawables.useSupportLibrary = true
multiDexEnabled true
}
dataBinding {
enabled = true
}
packagingOptions {
exclude 'jsr305\_annotations/Jsr305\_annotations.gwt.xml'
exclude 'error\_prone/Annotations.gwt.xml'
exclude 'third\_party/java\_src/error\_prone/project/annotations/Annotations.gwt.xml'
exclude 'third\_party/java\_src/error\_prone/project/annotations/Google\_internal.gwt.xml'
}
dexOptions {
preDexLibraries true
maxProcessCount 8
jumboMode true
javaMaxHeapSize "2g"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
flavorDimensions "default"
productFlavors {
dev {
versionNameSuffix "-dev"
resConfigs "en", "xxhdpi"
ext.enableCrashlytics = false
}
prod {
}
}
}
greendao {
schemaVersion 1
}
dependencies {
implementation 'com.android.support:multidex:1.0.3'
implementation fileTree(include: ['\*.jar'], dir: 'libs')
androidTestImplementation('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
//All Dependencies
implementation 'com.android.support:appcompat-v7:27.1.0'
implementation 'com.android.support:design:27.1.0'
implementation 'com.android.support:recyclerview-v7:27.1.0'
implementation 'com.longtailvideo.jwplayer:jwplayer-core:+'
implementation 'com.longtailvideo.jwplayer:jwplayer-common:+'
implementation('com.longtailvideo.jwplayer:jwplayer-ima:+') {
exclude group: "com.google.android.gms"
}
implementation 'com.google.ads.interactivemedia.v3:interactivemedia:3.6.0'
implementation 'com.google.android.gms:play-services-ads:11.8.0'
implementation('com.crashlytics.sdk.android:crashlytics:2.6.7@aar') {
transitive = true
}
}
apply plugin: 'com.google.gms.google-services'
```
When i searched for this file: `META-INF/android.arch.lifecycle_runtime.version` I get 2 locations:
```
/Users/shikhardeep/.gradle/caches/transforms-1/files-1.1/runtime-1.1.0.aar/f7273cc34aac547da4a88fd1c25f0f2f/jars/classes.jar!/META-INF/android.arch.lifecycle_runtime.version
/Users/shikhardeep/.gradle/caches/modules-2/files-2.1/com.google.ads.interactivemedia.v3/interactivemedia/3.8.2/abbc5b12ce9ca95049dce9a22cfe7a7f6709aaee/interactivemedia-3.8.2.jar!/META-INF/android.arch.lifecycle_runtime.version
```
and both of them only contains a value `1.1.0`
One more thing: for this dependency `implementation 'com.android.support:appcompat-v7:27.1.0'` I am getting this warning `All com.android.support libraries must use the exact same version` for a last couple of months. I don't think so this is the root cause of build failure as I was able to build APK (dev as well as release) till yesterday. There is no change in gradle file except `versionCode` and `versionName` (which I increment after a release).
**UPDATE 1:**
I have solved that `All com.android.support libraries must use the exact same version` by adding these but still the error persists
```
implementation 'com.android.support:cardview-v7:27.1.0'
implementation 'com.android.support:customtabs:27.1.0'
implementation 'com.android.support:animated-vector-drawable:27.1.0'
implementation 'com.android.support:exifinterface:27.1.0'
```
**UPDATE 2:**
I found this GitHub issue and it seems similar to my case: <https://github.com/google/ExoPlayer/issues/3911>.
I followed the approach mentioned by one of the commentator <NAME> and now I am able to build but I am not sure whether it's the right way or not.
**UPDATE 3:**
Although build was successful but I noticed that I am not able to play most of the media URLs. Same media URLs are working fine on live App. I am using JWPlayer SDK for media streaming. Everytime I open the VideoActivity, I get `onError()` callback with error message: `Invalid HTTP response code: 404: Not Found`. According to JWPlayer changelog: <https://developer.jwplayer.com/sdk/android/docs/developer-guide/about/release-notes/> they have updated the SDK on Mar21, 2018 and since that day I am also getting the error. In the SDK setup instructions <https://developer.jwplayer.com/sdk/android/docs/developer-guide/getting-started/library-project-setup/> they have recommended to use + while including dependencies. If I try to build by specifying a lower version (2.8.0) in gradle. I get an error while syncing: `Failed to resolve: com.longtailvideo.jwplayer:jwplayer-core:2.8.0`<issue_comment>username_1: **In my case**, I've excluded only path 'META-INF/LICENSE' on `yourProject/app/build.gradle` inside `android{}` . Here it is
```
packagingOptions {
exclude 'META-INF/LICENSE'
}
```
After it Clean Project and Rebuild Project.
**If above case doesn't work** for you then You can add this in `yourProject/app/build.gradle` inside `android{}`
```
packagingOptions {
exclude 'META-INF/DEPENDENCIES'
exclude 'META-INF/LICENSE'
exclude 'META-INF/LICENSE.txt'
exclude 'META-INF/license.txt'
exclude 'META-INF/NOTICE'
exclude 'META-INF/NOTICE.txt'
exclude 'META-INF/notice.txt'
exclude 'META-INF/ASL2.0'
}
```
Upvotes: 2 <issue_comment>username_2: You can try using `pickFirst` something like this:
```
packagingOptions {
// this is the lazy option.
//pickFirst 'META-INF/*'
pickFirst 'META-INF/android.arch.lifecycle_runtime.version'
}
```
Upvotes: 2 <issue_comment>username_3: The recommended solution per Detox android setup guide:
You need to add this to the android section of your `android/app/build.gradle`:
```
packagingOptions {
exclude 'META-INF/LICENSE'
}
```
reference <https://github.com/wix/detox/blob/master/docs/Introduction.Android.md#troubleshooting>
Upvotes: 0 <issue_comment>username_4: In buil.gradule ( module ) include under {android ... and before default configuration this line
android.packagingOptions.resources.pickFirsts += "\*\*/\*.pickFirst"
Upvotes: 0 |
2018/03/22 | 388 | 1,577 | <issue_start>username_0: In the vendor bills, when a customer invoice has been created,there will be a message\_ids field which creates and sends messages to the concerned persons who are all listed in the followers list. By default,this works like when an invoice is created and a message is entered, after that while clicking on the send button, a notification message will be sent to that followers inbox which will be located in discuss module.
**Without clicking the new message and sending the message, i want to send a notification to the followers that the state has been changed when i change the state**<issue_comment>username_1: write an onchange function for field state and create a message record for the followers.
eg:
```
@api.depends('states')
def func():
# create a message record with appropriate data
return
```
Upvotes: 0 <issue_comment>username_2: Just add `track_visibility='onchage'` in state field declaration in .py file.
Upvotes: -1 <issue_comment>username_3: In python:
```
state = fields.Selection([
('draft', 'Draft'),
('open', 'Open'),
('paid', 'Paid'),
('cancel', 'Cancelled'),
], string='Status',track_visibility='onchange')
@api.multi
def _track_subtype(self, init_values):
self.ensure_one()
if 'state' in init_values and self.state == 'sale':
return 'custom_invoice.mt_invoices_confirmed'
return super(SaleOrder, self)._track_subtype(init_values)
```
In xml:
```
Approval Request
sale.order
Request Approval
```
Upvotes: 2 [selected_answer] |
2018/03/22 | 1,075 | 4,425 | <issue_start>username_0: What is [`git request-pull`](https://git-scm.com/docs/git-request-pull) and how does it compare to making a `pull request`, e.g. [on github](https://help.github.com/articles/creating-a-pull-request/)?
**1.** How is it supposed to be used?
**2.** Can it be used as replacement for pull requests (e.g. on github)?
**3.** What are the advantages of using it?<issue_comment>username_1: The `git request-pull` command *predates* hosting services. As noted in comments, it's meant for a workflow that tends to include running `git format-patch` and `git send-email` to pass patches around via email. Once the patches have been tested and approved, the patch-generator might make the commits accessible on a public server that they or their company provide, and send a final email message to the project maintainer announcing that they have the cleaned-up, rebased, etc., project-topic ready for merging.
For example, suppose a guy named <NAME> has a Linux kernel patch for a file system. He has a clone of the Linux kernel tree, as of some Linux release. His patch consists of one giant commit to a dozen or so files, which he sends to the file-system maintenance list, with a subject line:
```
PATCH: make the foo file system better
```
The feedback on the file-system maintenance mailing list first says: break this into at least six smaller parts. Phil Systeme breaks up his Phile System patch into eight logical smaller patches, each of which does something useful and still builds. He sends out 9 messages this time:
```
[PATCH v2 0/8]: make the foo file system better
(description of what the patch series is about)
[PATCH v2 1/8]: split up the xyzzy function
As a prerequisite for improving the foo file system, break
a large function into several smaller ones that each do one
thing. We'll use this later to work better and add new features.
[PATCH v2 2/8]: ...
```
This time, he gets feedback that says it looks better but he forgot to account for the fact that ARM cpus require one special thing and MIPS CPUs require a different special thing. So he sends out a third round of `[PATCH v3 m/n]` messages, and so on.
Eventually, the file system maintenance lieutenant(s) agree that this patch should go in. Now Phil, or the lieutenant, converts the emailed patches to actual Git commits, applied to a current development kernel, or to a maintenance kernel, or whatever. <NAME> trusts this person enough at this point that this person can say: "here is a Git repository with new commits that you should add to the kernel." Linus can then `git pull` directly from this other repository, or more likely, `git fetch` from there and decide whether and how to merge them, or whether to insult the person. :-)
---
Hosting services like GitHub and Bitbucket claim, or feel, or whatever verb you like here, that their "pull request" mechanism is superior to all this email. In some ways, it pretty clearly is; but their enthusiasm for hiding the actual *commit graph*, which really does matter if you're going to use a true merge, is kind of a mystery to me.
Upvotes: 4 [selected_answer]<issue_comment>username_2: **1.** A `Pull Request` supports the controlled adoption of code modifications into a given code base **over a Web-UI**, provided by a hoster (e.g. github, bitbucket). [Example.](https://guides.github.com/introduction/flow/)
**2.** `git request-pull` is a git command that eases the process of contributing patches **over email** without depending to the services of a single hoster. [Example.](https://github.com/torvalds/linux/blob/master/Documentation/process/submitting-patches.rst#16-sending-git-pull-requests)
```
+-----------------+--------------------------------+--------------------------+
| Action | Pull Request | git request-pull |
+-----------------+--------------------------------+--------------------------+
| authentication | Register and login at hoster | Full Name, Signed Email |
| description | Web-Ui | Patch, Email |
| discussion | Web-Ui | Email, Mailinglist |
| review | Web-Ui | Email, Mailinglist |
| adoption | One button `merge` action | git pull/push |
+-----------------+--------------------------------+--------------------------+
```
Upvotes: 2 |
2018/03/22 | 583 | 1,871 | <issue_start>username_0: If I have the following:
```
public enum Attribute {
ONE, TWO, THREE
}
private Map mAttributesMap = new HashMap<>();
mAttributesMap.put(Attribute.ONE.name(), 5);
mAttributesMap.put(Attribute.TWO.name(), 5);
```
So how can I get the key of `mAttibutesMap`? And how to increment it?<issue_comment>username_1: You can not edit directly a map, but you can replace a value using:
```
mAttributesMap.put(Attribute.ONE.name(), 10);
```
Upvotes: 2 <issue_comment>username_2: **1.** First you could directly use a `Map` and `put` like this :
```
mAttributesMap.put(Attribute.ONE, 5);
mAttributesMap.put(Attribute.TWO, 5);
```
---
**2.** To increment the value of a key, you can do as follow, get the value, and `put` it again with `+1`, because the `key` already exists it will just replace the existing one (keys in a map are **unique**) :
```
public void incrementValueFromKey(Attribute key){
mAttributesMap.computeIfPresent(key, (k, v) -> v + 1);
}
```
---
**3.** To have a more generic solution you could do :
```
public void incrementValueFromKey(Attribute key, int increment){
mAttributesMap.computeIfPresent(key, (k, v) -> v + increment);
}
```
Upvotes: 4 [selected_answer]<issue_comment>username_3: If you know that the key exists in the HashMap, you can do the following:
```
int currentValue = mAttributesMap.get(Attribute.ONE.name());
mAttributesMap.put(Attribute.ONE.name(), currentValue+1);
```
If the key may or may not exist in the HashMap, you can do the following:
```
int currentValue = 0;
if (mAttributesMap.containsKey(Attribute.ONE.name())) {
currentValue = mAttributesMap.get(Attribute.ONE.name());
}
mAttributesMap.put(Attribute.ONE.name(), currentValue+1);
```
I hope this helps you! Thank you. Peace.
p.s. This is my updated version of username_1's answer on Mar 22 '18 at 8:22.
Upvotes: 1 |
2018/03/22 | 277 | 1,149 | <issue_start>username_0: I'm using angular google maps module for my Angular application (5.x.x) every things working fine except for the point that satellite toggle button is not showing which is default feature of google maps API. I saw on google official documentation screen there's an option to disable satellite view but don't know how to implement it in angular google maps API.
```
```
Whereas lat and lng are simple variable with values<issue_comment>username_1: add these attributes `[fullscreenControl]='true' [mapTypeControl]='true'` in
```
```
Upvotes: 5 [selected_answer]<issue_comment>username_2: If you want to add toggle button (Map and Satellite) like default map then you should have to put below code:
```
```
Upvotes: 4 <issue_comment>username_3: When you are using JavaScript.
```
map = new google.maps.Map(document.getElementById('map'), {
center: {
lat: -33.86,
lng: 151.209
},
zoom: 13,
minZoom: 3,
mapTypeControl: true,
gestureHandling: 'greedy'
});
```
Upvotes: 0 |
2018/03/22 | 2,083 | 6,896 | <issue_start>username_0: I am trying to use Google Charts and populate it using external JSON file, which I have created in PHP via json\_encode().
So I got google charts working, with static random data from example, which is:
```
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Time', 'Temperature', 'Humidty'],
['2018-03-09 13:28:49', 1000, 400],
['2018-03-09 13:28:59', 1170, 460],
['2018-03-09 14:28:49', 660, 1120],
['2018-03-09 17:28:49', 1030, 540],
['2018-03-09 13:28:49', 1030, 540]
]);
```
So basically as I understand var data should be replaced with entries from my JSON file, which is formatted in the following manner:
```
[{"id":"1","temp":"24.40","hum":"28.30","insert_date":"2018-03-09 13:28:49"},{"id":"2","temp":"24.50","hum":"28.60","insert_date":"2018-03-09 13:29:59"}]
```
So the data I need would be temp, hum and insert date. So, the question is how do I parse it?
I've been trying for hours and haven't been able to figure it out.
Thanks<issue_comment>username_1: In your page at bottom just initialize data to javascript variable and use it in chart function but note it drawChart() or file having this function should be included after that variable. Example is as bellow:
```
var php\_data = "<?=$json\_data?>";
function drawChart() {
var data = google.visualization.arrayToDataTable(php\_data);
```
an other solution is to pass data to drawchart function as variable like bellow:
```
var php\_data = "<?=$json\_data?>";
function drawChart(php\_data) {
var data = google.visualization.arrayToDataTable(php\_data);
```
Upvotes: 0 <issue_comment>username_2: recommend using ajax to get data from php
to create a google data table directly from json,
the json must be in a specific format, see...
[Format of the Constructor's JavaScript Literal data Parameter](https://developers.google.com/chart/interactive/docs/reference#dataparam)
`google.visualization.arrayToDataTable` will not work with the json sample you posted
but, you can parse the json manually, row by row...
```
$.each(jsonData, function (index, row) {
data.addRow([
new Date(row.insert_date),
parseFloat(row.temp),
parseFloat(row.hum)
]);
});
```
recommend using the following setup...
`google.charts.load` will wait for the page to load,
no need for --> `$(document).ready` -- or similar function
once google loads, create the chart and data table,
these only need to be created once
then use ajax to get the data, and draw the chart
if you want to continuously add more data to the same chart,
wait for the chart's `'ready'` event, then get more data
see following working snippet,
for example purposes, the sample data you provided is used in the ajax `fail` callback,
which can be removed...
```js
google.charts.load('current', {
packages: ['corechart']
}).then(function () {
// create chart
var container = $('#chart_div').get(0);
var chart = new google.visualization.LineChart(container);
var options = {
chartArea: {
height: '100%',
width: '100%',
top: 60,
left: 60,
right: 60,
bottom: 60
},
hAxis: {
format: 'M/d HH:mm:ss',
title: 'Time'
},
height: '100%',
legend: {
position: 'top'
},
width: '100%'
};
// create data table
var data = new google.visualization.DataTable();
data.addColumn('datetime', 'x');
data.addColumn('number', 'Temperature');
data.addColumn('number', 'Humidity');
// after the chart draws, wait 60 seconds, get more data
google.visualization.events.addListener(chart, 'ready', function () {
window.setTimeout(getData, 60000);
});
getData();
function getData() {
$.ajax({
url: 'data.php',
dataType: 'json'
}).done(function (jsonData) {
loadData(jsonData);
}).fail(function (jqXHR, textStatus, errorThrown) {
var jsonData = [{"id":"1","temp":"24.40","hum":"28.30","insert_date":"2018-03-09 13:28:49"},{"id":"2","temp":"24.50","hum":"28.60","insert_date":"2018-03-09 13:29:59"},{"id":"2","temp":"24.50","hum":"28.60","insert_date":"2018-03-09 13:31:10"}];
loadData(jsonData);
});
}
function loadData(jsonData) {
// load json data
$.each(jsonData, function (index, row) {
data.addRow([
new Date(row.insert_date),
parseFloat(row.temp),
parseFloat(row.hum)
]);
});
drawChart();
}
$(window).resize(drawChart);
function drawChart() {
// draw chart
chart.draw(data, options);
}
});
```
```css
html, body {
height: 100%;
margin: 0px 0px 0px 0px;
overflow: hidden;
padding: 0px 0px 0px 0px;
}
.chart {
height: 100%;
}
```
```html
```
Upvotes: 2 [selected_answer]<issue_comment>username_3: I am aready created my json file, so I read frm ajax like this
```
function setSensor(sensor)
{
$.ajax({
url:"QueryPHPFile.php",
method:'POST',
data: {varData: data},
beforeSend: function(){}
}).done(function(res){
res = JSON.parse(res);
google.charts.load('current', {packages: ['corechart', 'line']});
google.charts.setOnLoadCallback(function() {muestra2(res); });
}).fail(function(){
}).always(function(){});
}
```
and then I have function muestra2 like this where res is also my json file
```
function muestra2(res)
{
// console.log(res);
var data = null;
data = new google.visualization.DataTable();
data.addColumn('date', 'hAxis');
data.addColumn('number', 'vAxis');
var total = [];
var ValueFloat;
for (var i = res.length - 1; i >= 0; i--) {
ValueFloat = parseFloat(res[i] ['NameLabelInYourJsonFile']);
var date2= res[i]['Fecha'];
var esplit = date2.split("-",3); //Format to date separated
total.push([ new Date (esplit[0] , esplit[1] -1, esplit[2]),lecturaConvertida]); // new Date( , , )
}
data.addRows(total);
var options = {
hAxis: {
title: 'hAxis Name',
format: 'd MMM'
},
vAxis: {
title: 'vAxis Name'
},
backgroundColor: '#ffffff', //fondo de la grafica
width: 700,
lineWidth: 1,
height: 400,
title: 'Name Graphic',
};
var chart = new google.visualization.LineChart(document.getElementById('line-chart'));
chart.draw(data, options);
}
```
with the res.lenght we know hoy record are in the Json File.
For date you must use insert with newData, looking for more about this in the documentation, i hope this help you
Upvotes: 0 |
2018/03/22 | 353 | 1,351 | <issue_start>username_0: I have project that was created in another IDE that is build for a specific microcontroler. In the code `far`is used quite often and it is comprehended by the IDE and compiler.
I would like to use eclipse to edit the code, because it is more convinient to use. But it generates a lot of warnings and errors in the editor because he can not resolve the `far`.
I could create a macro `#define far`, but I would have to remove it when I want to compile the code. I don't compile with eclipse, because getting the compiler to work there is cumbersome and might introduce problems.
So is there a possibility that eclipse itself can handle the `far` for its syntax check?<issue_comment>username_1: After I searched a bit more I found an answer here:
<https://www.eclipse.org/forums/index.php/t/72375/>
Go to the menu:
Project -> Properties -> C/C++ General -> Path and Symbols ->
Symbols
and add a Symbol called `far` with the value `/* */`.
I just left the value empty and it worked.
Upvotes: 1 [selected_answer]<issue_comment>username_2: Another approach that involves modifying your code rather than the project settings would be:
```
#ifdef __CDT_PARSER__
#define far
#endif
```
`__CDT_PARSER__` is a macro that is automatically defined by CDT's parser when it processes your code, but not by any compiler.
Upvotes: 1 |
2018/03/22 | 521 | 1,794 | <issue_start>username_0: Is it possible to fetch a webpack envvar outside the node / js scope?
I'm developing with vueJS and TYPO3 and want to load the JS files from node server, when it runs. Otherwise, I want to load the built JS files from the project folder.
TYPO3 has conditions for file loading, in dependence of an Apache envvar.
```
SetEnv TYPO3_CONTEXT Development
```
Questions:
1. Is it possible to set an apache2 envvar when launching a node devserver by webpack?
2. If not, is it possible to hook in that process and write a temporary htaccess file with the var in it, place it in a specific directory and delete it, when I stop the node server?
Background:
In TYPO3, js and css includes are configured by TypeScript.
In Prod Env:
```
page.includeJSFooter.app = path/to/build/name.js
```
This load can be changed by condition:
```
[applicationContext = Development]
page.includeJSFooter.app = http://192.168.100.38:8080/app.build.js
[end]
```
Now I want to set this context, as soon as I start my node dev server that builds the files on the fly:
```
webpack-dev-server --open --config webpack.dev.js
```<issue_comment>username_1: After I searched a bit more I found an answer here:
<https://www.eclipse.org/forums/index.php/t/72375/>
Go to the menu:
Project -> Properties -> C/C++ General -> Path and Symbols ->
Symbols
and add a Symbol called `far` with the value `/* */`.
I just left the value empty and it worked.
Upvotes: 1 [selected_answer]<issue_comment>username_2: Another approach that involves modifying your code rather than the project settings would be:
```
#ifdef __CDT_PARSER__
#define far
#endif
```
`__CDT_PARSER__` is a macro that is automatically defined by CDT's parser when it processes your code, but not by any compiler.
Upvotes: 1 |
2018/03/22 | 793 | 2,610 | <issue_start>username_0: I've seen it mentioned in docs, etc the vue.config.js file.
And also noted previously these are handled in the webpack config file, etc in 2.0.
But I can't find either file in my project folder created with vue cli 3.0... Where is the config files and why isn't it anywhere in the top level folders, etc?<issue_comment>username_1: >
> Where is the config files and why isn't it anywhere in the top level folders, etc?
>
>
>
The initial project doesn't require the file to exist because you just created a project with fresh "default" settings that don't require any config.
Just create it yourself. it's even mentioned in the [README](https://github.com/vuejs/vue-cli/blob/dev/docs/README.md#configuration):
>
> Many aspects of a Vue CLI project can be configured **by placing** a vue.config.js file at the root of your project. The file **may** already exist depending on the features you selected when creating the project.
>
>
>
(*emphasis mine*)
Edit: now to be found here: <https://cli.vuejs.org/config/#global-cli-config>
Upvotes: 7 [selected_answer]<issue_comment>username_2: There is no need for "config" directory anymore.
if you want to define "environment variables" you can do that in ".env" file
Just like:
```
VUE_APP_TITLE=Test
```
You can also create ".env" file for each environment
Like:
`.env.development` for development mode
`.env.production` for production mode.
For more information please read:
<https://cli.vuejs.org/guide/mode-and-env.html#example-staging-mode>
Upvotes: 3 <issue_comment>username_3: `vue.config.js` is now an optional config file.
Refer: <https://cli.vuejs.org/config/#vue-config-js>
Upvotes: 3 <issue_comment>username_4: The file by default does **not** exists as it was mentioned by Linus. You need to create manually `vue.config.js` file in a root location of your project, i.e. on the same level where is `package.json`.
Upvotes: 4 <issue_comment>username_5: Check this out:
1. Create
>
> vue.config.js
>
>
>
in your vue project at the same level with
>
> package.json
>
>
>
2. Specify the host and the port:`module.exports = { devServer: { host: "localhost", port: "8080" } }`
3. Run:
>
> npm run serve
>
>
>
in your vue folder.
Check out this screenshot:
[Hope it helps!](https://i.stack.imgur.com/3B8mg.png)
PS: If you want to disable running the app on a local host check out this post: [How do I disable running an app on the local network when using vue-cli?](https://stackoverflow.com/questions/52829363/how-do-i-disable-running-an-app-on-the-local-network-when-using-vue-cli)
Upvotes: 0 |
2018/03/22 | 2,047 | 7,024 | <issue_start>username_0: I have created the below procedure which ran just fine before I added the bold code. Now it's inserting 100 records at a time. It's been more than a hour and it has inserted only 4000 records. There are 2 million records to be inserted. Is there any way I can fasten the execution?
```
create or replace PROCEDURE LOAD_ADDRESS_PROCEDURE AS
CNTY varchar2(100);
ST varchar2(100);
createdby_value varchar2(50);
**defaultAddress_value varchar2(1);**
CURSOR C1 is
SELECT ADDRESS, CITY, STATE, ZIP, COUNTRY, seasonal_start_day, seasonal_start_month, seasonal_end_day, seasonal_end_month, key_address_id, key_account_id, BAD_ADDRESS,
CREATED, CREATED_BY, address_type,
(select siebel_country_name from STATE_AND_COUNTRY_VALUES_LIST where s.COUNTRY IS NULL and s.state = siebel_state_abbreviation) newCNTY,
(select SF_COUNTRY_ABBREVIATION FROM STAGE_COUNTRY WHERE SIEBEL_COUNTRY = s.Country) newCountry,
(select SF_COUNTRY_ABBREVIATION FROM STAGE_COUNTRY
WHERE SIEBEL_COUNTRY = (select siebel_country_name from STATE_AND_COUNTRY_VALUES_LIST where s.COUNTRY IS NULL and s.state = siebel_state_abbreviation)) newCountry1,
(SELECT SIEBEL_LOGIN from STAGE_USER where KEY_USER_ID = s.CREATED_BY) SiebelLogin,
(SELECT SALESFORCE_USER from STAGE_USER where KEY_USER_ID = s.CREATED_BY) SFUSER,
(SELECT KEY_USER_ID from STAGE_USER where KEY_USER_ID = s.CREATED_BY) KeyUserID,
**(SELECT KEY_PRIMARY_ADDRESS_ID FROM STAGE_ACCOUNT WHERE KEY_PRIMARY_ADDRESS_ID = s.KEY_ADDRESS_ID) defaultAddress**
FROM STAGE_ADDRESS s;
BEGIN
FOR i IN C1 LOOP
ST := i.state;
CNTY := i.country;
/*if(i.newCountry = i.newCNTY) then*/
/*if (i.country is null) then
CNTY := i.newCountry1;
end if;
comment end*/
if (i.state = 'NA') then
ST := NULL;
end if;
/*end if;*/
/*
if(CNTY != i.newCountry) then
CNTY := i.newCountry;
end if;
if(i.newCountry is null) then
CNTY := NULL;
end if;
comment end*/
IF(CNTY IS NULL) THEN
CNTY := i.newCountry1;
ELSE
CNTY := i.newCountry;
END IF;
IF(i.CREATED_BY = i.KeyUserID AND i.SFUSER = 'MIGRATIONUSER') THEN
createdby_value := 'MIGRATIONUSER';
ELSE
createdby_value := i.KeyUserID;
END IF;
**IF(i.defaultAddress IS NOT NULL) THEN
defaultAddress_value := 'Y';
ELSE
defaultAddress_value := 'N';
END IF;**
INSERT INTO LOAD_ADDRESS(NPSP__MAILINGSTREET__C, NPSP__MAILINGCITY__C, NPSP__MAILINGSTATE__C, NPSP__MAILINGPOSTALCODE__C, NPSP__MAILINGCOUNTRY__C, NPSP__SEASONAL_START_DAY__C,
NPSP__SEASONAL_START_MONTH__C, NPSP__SEASONAL_END_DAY__C, NPSP__SEASONAL_END_MONTH__C, ERP_EXTERNAL_ID_C, NPSP__HOUSEHOLD_ACCOUNT__C, ADDRESS_STATUS_OVERRIDE, CREATED,
CREATED_BY, NPSP_ADDRESS_TYPE_C, **NPSP__DEFAULT_ADDRESS__C**) VALUES
(i.ADDRESS, REGEXP_REPLACE(i.CITY, '|||||', ' '), ST, i.ZIP, CNTY, i.seasonal_start_day, i.seasonal_start_month, i.seasonal_end_day, i.seasonal_end_month, i.key_address_id, i.key_account_id,
DECODE(i.BAD_ADDRESS,'Y','1','N','0'), i.CREATED, createdby_value, i.address_type, **defaultAddress_value**);
COMMIT;
END LOOP;
END LOAD_ADDRESS_PROCEDURE;
```<issue_comment>username_1: I'd suggest you to completely rewrite SELECT. You should probably use **joins** with STAGE\_USER, STAGE\_COUNTRY and any other table(s) that query uses.
There are some IFs which could be (at least, I hope so) rewritten by using CASE (or DECODE), which would make it possible to use *fast* SQL (a direct INSERT INTO) instead of *slow* PL/SQL (in a loop).
BTW, you're committing within the loop - remove COMMIT outside.
Upvotes: 0 <issue_comment>username_2: You could rewrite your procedure to do all the logic in a single insert statement, something like:
```
INSERT INTO load_address
(npsp__mailingstreet__c,
npsp__mailingcity__c,
npsp__mailingstate__c,
npsp__mailingpostalcode__c,
npsp__mailingcountry__c,
npsp__seasonal_start_day__c,
npsp__seasonal_start_month__c,
npsp__seasonal_end_day__c,
npsp__seasonal_end_month__c,
erp_external_id_c,
npsp__household_account__c,
address_status_override,
created,
created_by,
npsp_address_type_c,
npsp__default_address__c)
SELECT address,
regexp_replace(i.city, '|||||', ' '),
CASE
WHEN state = 'NA' THEN
NULL
ELSE
state
END state,
zip,
CASE
WHEN country IS NULL THEN
newcountry1
ELSE
newcountry
END country,
seasonal_start_day,
seasonal_start_month,
seasonal_end_day,
seasonal_end_month,
key_address_id,
key_account_id,
DECODE(bad_address, 'Y', '1', 'N', '0'),
created,
CASE
WHEN created_by = keyuserid
AND sfuser = 'MIGRATIONUSER' THEN
sfuser
ELSE
keyuserid
END createdby_value,
address_type,
CASE
WHEN default_address IS NOT NULL THEN
'Y'
ELSE
'N'
END defaultaddress_value
FROM (SELECT address,
city,
state,
zip,
country,
seasonal_start_day,
seasonal_start_month,
seasonal_end_day,
seasonal_end_month,
key_address_id,
key_account_id,
bad_address,
created,
created_by,
address_type,
(SELECT siebel_country_name
FROM state_and_country_values_list
WHERE s.country IS NULL
AND s.state = siebel_state_abbreviation) newcnty,
(SELECT sf_country_abbreviation
FROM stage_country
WHERE siebel_country = s.country) newcountry,
(SELECT sf_country_abbreviation
FROM stage_country
WHERE siebel_country = (SELECT siebel_country_name
FROM state_and_country_values_list
WHERE s.country IS NULL
AND s.state = siebel_state_abbreviation)) newcountry1,
su.siebel_login siebellogin,
su.salesforce_user sfuser,
su.key_user_id keyuserid,
(SELECT key_primary_address_id
FROM stage_account
WHERE key_primary_address_id = s.key_address_id) defaultaddress
FROM stage_address s
LEFT OUTER JOIN stage_user su ON s.created_by = su.key_user_id);
```
I have moved your scalar subqueries on status\_user to an outer join, since joining is likely to be more efficient than querying the same table 3 times. You could probably do something similar with the other scalar subqueries (i.e. combining them into a couple of joins or something) but I've left that for you to play with.
Upvotes: 3 [selected_answer] |
2018/03/22 | 907 | 3,215 | <issue_start>username_0: I want to add **web pack** **provided Plugins** to use JQuery globally.
Some articles says
>
> You need to put it in webpack.config.js under plugins:[]
>
>
>
But when I look at my `webpack.config.js` there is no such `plugins` object.
Then I create `plugins` object manually under the `module` array.
After that when I try to run the project using npm run dev
it doesn't run.
I want to add this plugin to the `webpack.config.js`
```
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery'
})
```
How do I do this?
This is my webpack.config.js file
```
var path = require('path')
var webpack = require('webpack')
module.exports = {
entry: './src/main.js',
output: {
path: path.resolve(__dirname, './dist'),
publicPath: '/dist/',
filename: 'build.js'
},
module: {
rules: [
{
test: /\.css$/,
use: [
'vue-style-loader',
'css-loader'
],
}, {
test: /\.vue$/,
loader: 'vue-loader',
options: {
loaders: {
}
// other vue-loader options go here
}
},
{
test: /\.js$/,
loader: 'babel-loader',
exclude: /node_modules/
},
{
test: /\.(png|jpg|gif|svg)$/,
loader: 'file-loader',
options: {
name: '[name].[ext]?[hash]'
}
}
]
},
plugins[
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery'
}),
new webpack.ProvidePlugin({
Vue: ['vue/dist/vue.esm.js', 'default']
})
],
resolve: {
alias: {
'vue$': 'vue/dist/vue.esm.js'
},
extensions: ['*', '.js', '.vue', '.json']
},
devServer: {
historyApiFallback: true,
noInfo: true,
overlay: true
},
performance: {
hints: false
},
devtool: '#eval-source-map'
}
if (process.env.NODE_ENV === 'production') {
module.exports.devtool = '#source-map'
// http://vue-loader.vuejs.org/en/workflow/production.html
module.exports.plugins = (module.exports.plugins || []).concat([
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: '"production"'
}
}),
new webpack.optimize.UglifyJsPlugin({
sourceMap: true,
compress: {
warnings: false
}
}),
new webpack.LoaderOptionsPlugin({
minimize: true
})
])
}
```<issue_comment>username_1: Try this in **build/webpack.dev.conf.js** and **build/webpack.prod.conf.js**:
```
plugins: [
// ...
new webpack.ProvidePlugin({
$: 'jquery',
jquery: 'jquery',
'window.jQuery': 'jquery',
jQuery: 'jquery'
})
]
```
jQuery becomes globally available to all your modules:
Upvotes: 0 <issue_comment>username_2: If you take a quick look at the webpack documentation for plugins [here](https://webpack.js.org/concepts/plugins/#configuration), you would see where the `plugins` object belongs.
The good news is: your webpack config already looks correct - you put the plugins array as a direct child of the config, after `module`, instead of inside it. You only miss a `:` colon after `plugins`, which likely is a typo.
So I don't see a reason what should not work.
Upvotes: 2 [selected_answer] |
2018/03/22 | 1,603 | 7,112 | <issue_start>username_0: is it possible to bind an UWP `CommandBar` to something like a `ObservableCollection` or so?
What i want to achieve ist to bind my `CommandBar` of my `NavigationView` to an Object of a specific `Page` so that the `AppBarButton` change dynamicaly depending on the current `Page`
What i tryed:
**MainPage.xaml**
```
```
**SomePage.xaml.cs**
```
public ObservableCollection AppBarButtonList = new ObservableCollection {
new AppBarButton { Icon = new SymbolIcon(Symbol.Accept), Label="Bla" },
new AppBarButton{Icon=new SymbolIcon(Symbol.Add),Label="Add"}
};
```
But the `CommandBar` shows nothing.
Thanks.<issue_comment>username_1: My original solution was using the `PrimaryCommands` property to bind the commands, but it turns out this property is read-only.
My solution to the problem will be using behaviors.
First add a reference to `Microsoft.Xaml.Behaviors.Uwp.Managed` from NuGet.
Then add the following behavior to your project:
```
public class BindableCommandBarBehavior : Behavior
{
public ObservableCollection PrimaryCommands
{
get { return (ObservableCollection)GetValue(PrimaryCommandsProperty); }
set { SetValue(PrimaryCommandsProperty, value); }
}
public static readonly DependencyProperty PrimaryCommandsProperty = DependencyProperty.Register(
"PrimaryCommands", typeof(ObservableCollection), typeof(BindableCommandBarBehavior), new PropertyMetadata(default(ObservableCollection), UpdateCommands));
private static void UpdateCommands(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs dependencyPropertyChangedEventArgs)
{
if (!(dependencyObject is BindableCommandBarBehavior behavior)) return;
var oldList = dependencyPropertyChangedEventArgs.OldValue as ObservableCollection;
if (dependencyPropertyChangedEventArgs.OldValue != null)
{
oldList.CollectionChanged -= behavior.PrimaryCommandsCollectionChanged;
}
var newList = dependencyPropertyChangedEventArgs.NewValue as ObservableCollection;
if (dependencyPropertyChangedEventArgs.NewValue != null)
{
newList.CollectionChanged += behavior.PrimaryCommandsCollectionChanged;
}
behavior.UpdatePrimaryCommands();
}
private void PrimaryCommandsCollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
UpdatePrimaryCommands();
}
private void UpdatePrimaryCommands()
{
if (PrimaryCommands != null)
{
AssociatedObject.PrimaryCommands.Clear();
foreach (var command in PrimaryCommands)
{
AssociatedObject.PrimaryCommands.Add(command);
}
}
}
protected override void OnDetaching()
{
base.OnDetaching();
if (PrimaryCommands != null)
{
PrimaryCommands.CollectionChanged -= PrimaryCommandsCollectionChanged;
}
}
}
```
This behavior essentially creates a fake `PrimaryCommands` property that is bindable and also observes collection changed events. Whenever a change occurs, the commands are rebuilt.
Finally, the problem in your code is that your `AppBarButtonList` is just a field, not a property. Change it like this:
```
public ObservableCollection AppBarButtonList { get; } = new ObservableCollection {
new AppBarButton { Icon = new SymbolIcon(Symbol.Accept), Label="Bla" },
new AppBarButton{Icon=new SymbolIcon(Symbol.Add),Label="Add"}
};
```
Notice the `{get ;}` which was added before the assignment operator.
Now you can use the behavior in XAML like this:
```
```
This is by no means a perfect solution and could be improved upon to allow different collection types binding and more, but it should cover your scenario. An alternative solution would be to implement a custom version of command bar, with new additional dependency property directly on the type, but I used behavior to make it clearer for the user that this is an "added" functionality, not a built-in one.
Upvotes: 2 <issue_comment>username_2: I found this answer very helpful. I did some more adjustments, like using a DataTemplateSelector to remove UI references like "AppBarButton" from the bindable data source.
```
public class BindableCommandBarBehavior : Behavior
{
public static readonly DependencyProperty PrimaryCommandsProperty = DependencyProperty.Register(
"PrimaryCommands", typeof(object), typeof(BindableCommandBarBehavior),
new PropertyMetadata(null, UpdateCommands));
public static readonly DependencyProperty ItemTemplateSelectorProperty = DependencyProperty.Register(
"ItemTemplateSelector", typeof(DataTemplateSelector), typeof(BindableCommandBarBehavior),
new PropertyMetadata(null, null));
public DataTemplateSelector ItemTemplateSelector
{
get { return (DataTemplateSelector)GetValue(ItemTemplateSelectorProperty); }
set { SetValue(ItemTemplateSelectorProperty, value); }
}
public object PrimaryCommands
{
get { return GetValue(PrimaryCommandsProperty); }
set { SetValue(PrimaryCommandsProperty, value); }
}
protected override void OnDetaching()
{
base.OnDetaching();
if (PrimaryCommands is INotifyCollectionChanged notifyCollectionChanged)
{
notifyCollectionChanged.CollectionChanged -= PrimaryCommandsCollectionChanged;
}
}
private void UpdatePrimaryCommands()
{
if (AssociatedObject == null)
return;
if (PrimaryCommands == null)
return;
AssociatedObject.PrimaryCommands.Clear();
if (!(PrimaryCommands is IEnumerable enumerable))
{
AssociatedObject.PrimaryCommands.Clear();
return;
}
foreach (var command in enumerable)
{
var template = ItemTemplateSelector.SelectTemplate(command, AssociatedObject);
if (!(template?.LoadContent() is FrameworkElement dependencyObject))
continue;
dependencyObject.DataContext = command;
if (dependencyObject is ICommandBarElement icommandBarElement)
AssociatedObject.PrimaryCommands.Add(icommandBarElement);
}
}
protected override void OnAttached()
{
base.OnAttached();
UpdatePrimaryCommands();
}
private void PrimaryCommandsCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
UpdatePrimaryCommands();
}
private static void UpdateCommands(DependencyObject dependencyObject,
DependencyPropertyChangedEventArgs dependencyPropertyChangedEventArgs)
{
if (!(dependencyObject is BindableCommandBarBehavior behavior)) return;
if (dependencyPropertyChangedEventArgs.OldValue is INotifyCollectionChanged oldList)
{
oldList.CollectionChanged -= behavior.PrimaryCommandsCollectionChanged;
}
if (dependencyPropertyChangedEventArgs.NewValue is INotifyCollectionChanged newList)
{
newList.CollectionChanged += behavior.PrimaryCommandsCollectionChanged;
}
behavior.UpdatePrimaryCommands();
}
}
```
The DataTemplateSelector:
```
public class CommandBarMenuItemTemplateSelector : DataTemplateSelector
{
public DataTemplate CbMenuItemTemplate { get; set; }
protected override DataTemplate SelectTemplateCore(object item, DependencyObject container)
{
if (item is ContextAction)
{
return CbMenuItemTemplate;
}
return base.SelectTemplateCore(item, container);
}
}
```
Xaml for templates:
```
```
Usage:
```
```
Where ContextActions is a ObservableCollection of my class ContextAction.
Upvotes: 0 |
2018/03/22 | 729 | 2,564 | <issue_start>username_0: The name `attribute_name:"position"` is very rare and I want to check that if the property exists I want to push it to the new array. However, every time I try to add a condition it gives me errors.
`[0].attribute_name` inside the `for` loop is giving me trouble. There may or may not be two arrays inside `activity_attributes`. But I want to make a call bases on first array, if the `itemloop[i].activity_attributes[0].attribute_name` push them to new array.
[](https://i.stack.imgur.com/JGrQW.png)
```
if(res.status == "success") {
var itemloop = res.response.activities;
var social_post_link = [];
for(var i=0; i
```<issue_comment>username_1: Use should use the [hasOwnProperty](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty) method
```
if(itemloop[i].activity_attributes[0].hasOwnProperty('attribute_name') && itemloop[i].activity_attributes[0].attribute_name == "position")
```
You code should be like
```
if(res.status == "success") {
var itemloop = res.response.activities;
var social_post_link = [];
for(var i=0; i
```
Upvotes: 1 <issue_comment>username_2: You can use `if('attribute_name' in yourObject)` to achieve that.
**Demo.**
```js
var res = {
status: 'success',
response: {
activities : [
{
activity_attributes: [
{
attribute_name: 'position'
}
]
},
{
activity_attributes: [
{
test: 'test'
}
]
}
]
}
};
if(res.status == "success") {
var itemloop = res.response.activities;
var social_post_link = [];
for(var i=0; i
```
Upvotes: 2 [selected_answer]<issue_comment>username_3: instead of `activity_attributes[0].attribute_name` ,try using `activity_attributes[0]['attribute_name'] == 'position'`
Upvotes: 0 <issue_comment>username_4: [`Array.prototype.filter()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter) and `Array.prototype.map()` can be combined to construct new `arrays` based on `predicated rules` such as `attribute_name == 'position'` and `return` child `values`.
See below for a practical example.
```
if (res.status == 'success') {
const itemloop = res.response.activities
const social_post_link = itemloop.filter(x => x.attribute_name == 'position').map(x => x.activity_attributes)
console.log(social_post_link)
}
```
Upvotes: 1 |
2018/03/22 | 827 | 3,029 | <issue_start>username_0: I have a generic list manager class ListManager which I use to store Animal objects in the AnimalManager subclass to the list manager.
In the Animal class I have added the IComparer interface and added a Compare method.
For some reason i get an error in the ListManager in the sort method se code below.
in ListManager....
```
//Method for sorting.
public void SortComp(T aType)
{
aList.Sort(aType); //This is where I get the error
}
```
in Animal....
```
//Def field sortby enum with default value name
private SortBy compareField = SortBy.Name;
//Getter and setter
public SortBy CompareField
{
get { return compareField; }
set
{
compareField = value;
}
}
//Method (as specified by IComparer) for comparing two objects. Makes use of CompareTo method
public int Compare(Animal x, Animal y)
{
//Depending on how the comparefield is set do different sorting
switch (compareField)
{
case SortBy.Name:
return x.Name.CompareTo(y.Name);
case SortBy.ID:
return x.ID.CompareTo(y.ID);
default:
return x.Name.CompareTo(y.Name);//Just in case
}
}
```<issue_comment>username_1: Use should use the [hasOwnProperty](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty) method
```
if(itemloop[i].activity_attributes[0].hasOwnProperty('attribute_name') && itemloop[i].activity_attributes[0].attribute_name == "position")
```
You code should be like
```
if(res.status == "success") {
var itemloop = res.response.activities;
var social_post_link = [];
for(var i=0; i
```
Upvotes: 1 <issue_comment>username_2: You can use `if('attribute_name' in yourObject)` to achieve that.
**Demo.**
```js
var res = {
status: 'success',
response: {
activities : [
{
activity_attributes: [
{
attribute_name: 'position'
}
]
},
{
activity_attributes: [
{
test: 'test'
}
]
}
]
}
};
if(res.status == "success") {
var itemloop = res.response.activities;
var social_post_link = [];
for(var i=0; i
```
Upvotes: 2 [selected_answer]<issue_comment>username_3: instead of `activity_attributes[0].attribute_name` ,try using `activity_attributes[0]['attribute_name'] == 'position'`
Upvotes: 0 <issue_comment>username_4: [`Array.prototype.filter()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter) and `Array.prototype.map()` can be combined to construct new `arrays` based on `predicated rules` such as `attribute_name == 'position'` and `return` child `values`.
See below for a practical example.
```
if (res.status == 'success') {
const itemloop = res.response.activities
const social_post_link = itemloop.filter(x => x.attribute_name == 'position').map(x => x.activity_attributes)
console.log(social_post_link)
}
```
Upvotes: 1 |
2018/03/22 | 847 | 3,015 | <issue_start>username_0: I am trying to sent my form data to node js and retrieve at there.But I am failed to do it with form data object.
```
handleSubmit(data) {
console.log(data);
const forms=new FormData();
forms.append('fname','pranab');
let promise=fetch('http://localhost:8080/reactTest', {
method:'POST',
mode:'CORS',
body:JSON.stringify(forms),
headers:{
'Content-Type':'application/json',
'Accept':'application/json'
}
}).then(res =>res.json()).then(result => console.log(result))
}
```
in the above code I am sending form data object to the serve side.At the server side I am trying to retrieve it using below code.
```
app.post('/reactTest',function(req,res) {
var contents=req.body;
console.log(contents);
return res.send({status:'working'});
})
```
but it displays nothing in the console.What the issue here is?
**output is**
```
titech@titech-System-Product-Name:/var/www/html/nodejs$ node index.js
port listening on 8080
{}
```
when i trying to console it with 'req.body.fname' it gives 'undefined' as output in place of '{}'.<issue_comment>username_1: Use should use the [hasOwnProperty](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty) method
```
if(itemloop[i].activity_attributes[0].hasOwnProperty('attribute_name') && itemloop[i].activity_attributes[0].attribute_name == "position")
```
You code should be like
```
if(res.status == "success") {
var itemloop = res.response.activities;
var social_post_link = [];
for(var i=0; i
```
Upvotes: 1 <issue_comment>username_2: You can use `if('attribute_name' in yourObject)` to achieve that.
**Demo.**
```js
var res = {
status: 'success',
response: {
activities : [
{
activity_attributes: [
{
attribute_name: 'position'
}
]
},
{
activity_attributes: [
{
test: 'test'
}
]
}
]
}
};
if(res.status == "success") {
var itemloop = res.response.activities;
var social_post_link = [];
for(var i=0; i
```
Upvotes: 2 [selected_answer]<issue_comment>username_3: instead of `activity_attributes[0].attribute_name` ,try using `activity_attributes[0]['attribute_name'] == 'position'`
Upvotes: 0 <issue_comment>username_4: [`Array.prototype.filter()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter) and `Array.prototype.map()` can be combined to construct new `arrays` based on `predicated rules` such as `attribute_name == 'position'` and `return` child `values`.
See below for a practical example.
```
if (res.status == 'success') {
const itemloop = res.response.activities
const social_post_link = itemloop.filter(x => x.attribute_name == 'position').map(x => x.activity_attributes)
console.log(social_post_link)
}
```
Upvotes: 1 |
2018/03/22 | 913 | 3,155 | <issue_start>username_0: I get unexpected token error for spread operator, how can I do it build the bundle without removing the code ?
Here is my webpack config file
```
Unexpected token (85:32)
83 | console.log(
84 | 'return value 1 ' +
> 85 | JSON.stringify({ value: { ...this.value(), ...newState } })
| ^
86 | )
87 | return {
88 | value: {
```
var path = require('path')
```
module.exports = {
entry: path.resolve(__dirname, 'partner/index.js'),
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.js'
},
module: {
rules: [
{
test: /\.js$/, // Check for all js files
loader: 'babel-loader',
query: {
presets: ['babel-preset-es2015'].map(require.resolve)
},
exclude: /node_modules\/(?!other-module)/
}
]
},
stats: {
colors: true
},
devtool: 'source-map',
resolve: { symlinks: false }
}
```
However this webpack works but I need to use previous one
```
module.exports = {
entry: {
partner: '../workout-example/partner/index.js',
test: '../workout-example/test/example.spec.js'
},
target: 'web',
mode: 'development',
node: {
fs: 'empty'
},
output: {
filename: '[name]_bundle.js'
}
}
```<issue_comment>username_1: Use should use the [hasOwnProperty](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty) method
```
if(itemloop[i].activity_attributes[0].hasOwnProperty('attribute_name') && itemloop[i].activity_attributes[0].attribute_name == "position")
```
You code should be like
```
if(res.status == "success") {
var itemloop = res.response.activities;
var social_post_link = [];
for(var i=0; i
```
Upvotes: 1 <issue_comment>username_2: You can use `if('attribute_name' in yourObject)` to achieve that.
**Demo.**
```js
var res = {
status: 'success',
response: {
activities : [
{
activity_attributes: [
{
attribute_name: 'position'
}
]
},
{
activity_attributes: [
{
test: 'test'
}
]
}
]
}
};
if(res.status == "success") {
var itemloop = res.response.activities;
var social_post_link = [];
for(var i=0; i
```
Upvotes: 2 [selected_answer]<issue_comment>username_3: instead of `activity_attributes[0].attribute_name` ,try using `activity_attributes[0]['attribute_name'] == 'position'`
Upvotes: 0 <issue_comment>username_4: [`Array.prototype.filter()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter) and `Array.prototype.map()` can be combined to construct new `arrays` based on `predicated rules` such as `attribute_name == 'position'` and `return` child `values`.
See below for a practical example.
```
if (res.status == 'success') {
const itemloop = res.response.activities
const social_post_link = itemloop.filter(x => x.attribute_name == 'position').map(x => x.activity_attributes)
console.log(social_post_link)
}
```
Upvotes: 1 |
2018/03/22 | 512 | 1,801 | <issue_start>username_0: I have a simple form like this:
```
Name:
```
And some vanilla JS code to detect when the form is submitted:
```
document.addEventListener('submit', doFancyThings);
```
But the `doFancyThings` function is only triggered if I click the submit button, not if I press the enter key on my keyboard. How can I, using only plain javascript, listen for the enter key submit event, to also trigger my `doFancyThings` function?
I've had a look in the [Event reference at MDN](https://developer.mozilla.org/en-US/docs/Web/Events) and as far as I understand the submit event is only triggered when "The submit button is pressed". However, as the form is undoubtly submitted on enter key press, it ought to be firing some sort of event too, I reckon.
According to [submit - Event reference](https://developer.mozilla.org/en-US/docs/Web/Events/submit) the "event is fired only on the form element, not the button or submit input." Which sounds a bit contrary to the previous quote, and even less understandable why my listener doesn't trigger on the enter key.<issue_comment>username_1: >
> not if I press the enter key
>
>
>
Use a `form`
```js
document.addEventListener('submit', doFancyThings);
function doFancyThings(e) {
console.log('Enter pressed')
e.preventDefault()
}
```
```html
Name:
Click
```
Upvotes: -1 <issue_comment>username_2: try this
```js
var form = document.querySelector("form");
form.onsubmit = function(e) {
doFancyThings();
e.preventDefault(); // for preventing redirect
};
form.onkeydown = function(e) {
if (e.keyCode == 13) {
doFancyThings();
e.preventDefault(); // for preventing redirect
}
};
function doFancyThings() {
alert("hmmm");
};
```
```html
Name:
```
Upvotes: -1 |
2018/03/22 | 885 | 3,222 | <issue_start>username_0: I am confused about the Express built-in error handler.
I don't provide a custom error handler, but I do pass error via `next(err)` like the documentation says, Express just log a `[object object]` string.
Here are some simplified code:
```
var express = require('express');
var app = express();
app.get('/', function(req, res){
next({})
});
app.listen(3000);
```
And when I do `curl http://localhost:3000` in the terminal, just got `[object object]`.
So my questions are:
1. **What does the `[object object]` mean?**
2. **How does the built-in error handler process the error?**
3. **Why is there no output about the error stack?**<issue_comment>username_1: **1**
`[object Object]` is what `toString()` of JSON object.
Try `JSON.stringify(object)` to see what is inside.
**2, 3**
There is no built-in error handler in express.
If you read through [here](https://expressjs.com/en/guide/error-handling.html)
You'll see they have define error-handling middleware which have four arguments after all the `app.use`.
```
var express = require('express');
var app = express();
app.get('/', function(req, res){
next({}) // try change to next(new Error('Something wrong')) and see the log
});
app.use(function (err, req, res, next) {
console.error(err)
res.status(500).send('Something broke!')
})
app.listen(3000);
```
Upvotes: 0 <issue_comment>username_2: Express uses node module [finalhandler](https://github.com/pillarjs/finalhandler#readme), that also handles the errors, when specified in `next` handler. Each time the `error` in `next` is not `null` or `undefined`, it tries to get from the `error` object `status`, `headers` and `message` itself. Related to `[object Object]` response, I guess, it's the message of the error which placed in the `html` response, and if the message is of type `Object`, it gives `[object Object]` as result when coerced to the `String`.
When getting message from the error, `finalhandler` looks for env (production or not), and based on that retrieves a message. If in development (which is default), the message will be retrieved from `error.stack', so making something like this:
```
next(new Error('Unauthorized'));
```
will give `Unauthorized` in express html error response, because in the development environment `finalhandler` will look for the `error.stack' as a message.
In production, specifying status code, will give error messages based on the status code:
```
NODE_ENV=production node server.js
next({ status: 401 });
```
Gives:
```
Error
```
Unauthorized
```
```
Putting an empty object literals as an error (in development):
```
next({});
```
ends up `finalhandler` receiving `undefined` from `error.stack`(when trying to extract message from the error), and then calling `error.toString()`.
>
> Why is there no output about the error stack?
>
>
>
Some helpful information can be received by setting environment variables for [debug](https://github.com/visionmedia/debug#readme). `finalhendler` also uses `degub` module. To not pollute the terminal with unnecessary information, its namespace can be used for enabling debugging:
```
DEBUG=finalhandler node server.js
```
Upvotes: 2 [selected_answer] |
2018/03/22 | 2,476 | 8,816 | <issue_start>username_0: To identify a thread, we must do the following:
1) Get and save its id.
2) Within a function running in the thread, get the thread's id again and compare it with the saved id.
Eg: <http://coliru.stacked-crooked.com/a/8f608dff835f96d0>
(The program is from Josuttis' book "The C++ Standard Library", 2nd Ed.)
```
thread::id master_tid {};
/// declarations
void doSomething();
int main()
{
thread master {doSomething};
master_tid = master.get_id();
thread slave {doSomething};
/// ...
/// join with threads
master.join();
slave.join();
cout << "done" << endl;
}
void doSomething()
{
if (this_thread::get_id() == master_tid)
cout << "master thread ..."
<< endl;
else
cout << "NOT master thread ..."
<< endl;
/// ...
}
```
The output is:
```
master thread ...
NOT master thread ...
done
```
However, the above scheme works only IF there is no delay between invoking the doSomething() function and saving the master thread’s id.
If such a delay is introduced, the doSomething() function won't be able to discriminate between the master thread and any other, since, when it runs, the master thread's id hasn't *yet* been saved in the referenced variable.
Eg: <http://coliru.stacked-crooked.com/a/0bff325f872ba9c2>
```
thread::id master_tid {};
/// declarations
void doSomething();
int main()
{
thread master {doSomething};
thread slave {doSomething};
/// delay
this_thread::sleep_for(seconds {1});
master_tid = master.get_id();
/// ...
/// join with threads
master.join();
slave.join();
cout << "done" << endl;
}
void doSomething()
{
/// ...
}
```
Now, because of the delay, the output is as follows:
```
NOT master thread ...
NOT master thread ...
done
```
Therefore, I'd like to ask, how can we make this scheme work perfectly? Do we need to use condition variables to communicate between the main thread and the other threads, indicating if the thread id has been saved?
Or, is there some simpler way?<issue_comment>username_1: I am not sure I understand the question completely, but isn't it possible to pass the executed function an additional parameter which defines if it the master thread or not?
```
void doSomething(bool isMaster) {
if (isMaster)
cout << "master thread ..."
<< endl;
else
cout << "NOT master thread ..."
<< endl;
}
std::thread master = std::thread(doSomething, true);
std::thread slave = std::thread(doSomething, false);
```
Personally I would split `doSomething` into a general part and a specific part and then either create special functions for master and slave or define it in a lambda.
```
std::thread master = std::thread([]() {
doMasterStuff();
doSomething();
});
std::thread slave([]() {
doSlaveStuff();
doSomething();
});
```
Or I would use the template method pattern
```
class ThreadFunction {
private:
void doSpecific() = 0;
void doSomething() { ... }
public:
void operator()() {
doSpecific();
doSomething();
}
};
class MasterThread: public ThreadFunc {
void doSpecific() {
cout << "master thread ..."
<< endl;
}
};
```
Or create a class which gets the specific part as a "strategy".
```
template
class ThreadFunc2 {
private:
T specific;
void doSomething() { ... };
public:
ThreadFunc2(T s): specific( std::move(s) ) {}
void operator()() {
specific();
doSomething();
}
};
std::thread master([]() {
cout << "master thread ..." << endl;
});
```
Upvotes: 0 <issue_comment>username_2: In fact your problem is that you crate 2 threads and you compare their id to a none initialized value.
Indeed we have a look to the scheduling
```
--------------------------------------------> main time
| | | |
master slave sleep attribute id
--------------------------------------------> master time
|
do_something
--------------------------------------------> slave time
|
do_something
```
A way to make them able to see if they are master or salve is to use a bool that tells is the master or the salve has been identified.
```
int main()
{
bool know_master = false;
thread master {doSomething};
thread slave {doSomething};
/// delay
this_thread::sleep_for(seconds {1});
master_tid = master.get_id();
know_master = true;
/// ...
/// join with threads
master.join();
slave.join();
cout << "done" << endl;
}
void doSomething()
{
while (! know_master) {
//sleep here
}
if (this_thread::get_id() == master_tid)
cout << "master thread ..."
<< endl;
else
cout << "NOT master thread ..."
<< endl;
/// ...
}
```
Upvotes: 0 <issue_comment>username_3: ### Identifying a thread *on Linux*
In addition to other answers, on Linux (specifically), you could identify a thread by using first [pthread\_setname\_np(3)](http://man7.org/linux/man-pages/man3/pthread_setname_np.3.html) (near the start of the thread's function) and `pthread_getname_np` afterwards. You can also get a unique tid with the [gettid(2)](http://man7.org/linux/man-pages/man2/gettid.2.html) syscall (which returns some unique integer).
The disadvantage of `pthread_getname_np` is that you have to call `pthread_setname_np` once before (for your own explicitly created threads, it is easy; for threads created by some library, it is harder).
The disadvantage of `gettid` is that it is not wrapped by the C library. However, that wrapping is trivial to code:
```
static inline pid_t mygettid(void) { return syscall(SYS_gettid, 0L); }
```
You need [syscall(2)](http://man7.org/linux/man-pages/man2/syscall.2.html) and
Both `pthread_getname_np` and `gettid` may be Linux specific, but they can be used to uniquely identify your thread.
### general hints about threads
As a rule of thumb, you'll better pass some thread-unique data at thread creation time e.g. to [pthread\_create(3)](http://man7.org/linux/man-pages/man3/pthread_create.3.html) or as explicit (second and more) argument to [`std::thread`](http://en.cppreference.com/w/cpp/thread/thread/thread) constructor, notably if you want to use `pthread_setname_np` in your thread's function (and in most other cases).
So you would declare `void doSomething(int);` and do construct your threads using
```
thread master {doSomething,10};
thread slave {doSomething,42};
```
The choice of 10 and 42 is arbitrary, and you might declare instead something like
`void doSomething(std::string)` and then have
`thread master {doSomething, std::string{"masterth"}};` etc...
Upvotes: 0 <issue_comment>username_1: All threads have to wait until the `master_tid` is assigned. Instead of manual `sleep_for`, which is error prone and will eventually lead to bugs in your program, you should use a synchronization mechanism. In your case, where you want all threads wait for a condition, you can use a condition variable. [However, I would just pass different functions to master and slave, or pass a parameter.](https://stackoverflow.com/a/49424032/2169853)
```
#include
#include
#include
std::mutex m;
std::condition\_variable cv;
thread::id master\_tid {};
bool ready = false;
/// declarations
void doSomething() {
std::unique\_lock lk(m);
cv.wait(lk, []{return ready;});
// master\_tid is now assigned
if (this\_thread::get\_id() == master\_tid)
cout << "master thread ..."
<< endl;
else
cout << "NOT master thread ..."
<< endl;
}
int main()
{
thread master {doSomething};
thread slave {doSomething};
{
std::lock\_guard lk(m);
ready = true;
master\_tid = master.get\_id();
}
cv.notify\_all();
/// ...
/// join with threads
master.join();
slave.join();
cout << "done" << endl;
}
```
Upvotes: 3 [selected_answer]<issue_comment>username_4: This problem is trivially solved with `std::future`.
example:
```
#include
#include
#include
#include
/// declarations
void doSomething(std::shared\_future future\_master\_thread);
int main()
{
std::promise promise\_master\_thread;
auto shared\_master\_thread = promise\_master\_thread.get\_future().share();
std::thread master {std::bind(doSomething, shared\_master\_thread)};
promise\_master\_thread.set\_value(master.get\_id());
std::thread slave {std::bind(doSomething, shared\_master\_thread)};
/// ...
/// join with threads
master.join();
slave.join();
std::cout << "done" << std::endl;
}
void doSomething(std::shared\_future future\_master\_thread)
{
if (std::this\_thread::get\_id() == future\_master\_thread.get())
std::cout << "master thread ..."
<< std::endl;
else
std::cout << "NOT master thread ..."
<< std::endl;
/// ...
}
```
Upvotes: 1 |
2018/03/22 | 1,887 | 6,902 | <issue_start>username_0: I'd like to build a wrapper class, that does something before and after each emitted value of an Observable.
Here's what I came up with:
```
class Wrapper {
wrapped$: Observable;
\_dataSubject = new Subject();
data$ = this.\_dataSubject.pipe(
tap(\_ => console.log("BEFORE"),
//
// map( ??? )
//
);
constructor(wrapped$: Observable) {
this.wrapped$ = wrapped$.pipe(
tap(\_ => console.log("AFTER")
);
}
}
let subject = new Subject();
let wrapper = new Wrapper(subject);
wrapper.data$.subscribe(val => console.log(val));
subject.next("foo")
```
The console output should be:
```
BEFORE
foo
AFTER
```
I can't figure out how to connect the `$wrapped` Observable with the `_dataSubject`.
But maybe I'm completely wrong and it needs a different approach.<issue_comment>username_1: What about something like this
```
import {Observable} from 'rxjs';
export class DoBeforeAfter {
wrapped$: Observable;
constructor(wrapped$: Observable, doFunction: (data: any) => void) {
this.wrapped$ = Observable.of(null)
.do(\_ => console.log("BEFORE"))
.switchMap(\_ => wrapped$)
.do(doFunction)
.do(\_ => console.log('AFTER'));
}
}
```
to be consumed like this
```
const source = Observable.of('NOW');
const beforeAfter = new DoBeforeAfter(source, data => console.log(data));
beforeAfter.wrapped$.subscribe(
null,
error => console.error(error),
() => console.log('DONE')
```
)
It looks a bit cumbersome, but maybe it can help
Upvotes: 5 [selected_answer]<issue_comment>username_2: The best way (though complicated) is to create a new operator, similar to `tap` but that does something before and after the value is emitted.
You can see it working in the example (it's in ES6, as SO code snippets don't accept TypeScript, but you'll get the idea)
```js
function wrap(before, after) {
return function wrapOperatorFunction(source) {
return source.lift(new WrapOperator(before, after));
};
}
class WrapOperator {
constructor(before, after) {
this.before = before;
this.after = after;
}
call(subscriber, source) {
return source.subscribe(new WrapSubscriber(subscriber, this.before, this.after));
}
}
class WrapSubscriber extends Rx.Subscriber {
constructor(destination, before, after) {
super(destination);
this.before = before;
this.after = after;
}
_next(value) {
this.before ? this.before(value) : null;
this.destination.next(value);
this.after ? this.after(value) : null;
}
}
// Now:
const observable = Rx.Observable.from([1, 2, 3, 4]);
observable.pipe(
wrap(value => console.log('before', value), value => console.log('after', value))
).subscribe(value => console.log('value emitted', value), null, () => console.log('complete'));
// For what you want:
// let's simulate that, for each value in the array, we'll fetch something from an external service:
// we want the before to be executed when we make the request, and the after to be executed when it finishes. In this // case, we just combine two wrap operators and flatMap, for example:
observable.pipe(
wrap(value => console.log('BEFORE REQUEST', value)),
Rx.operators.flatMap(value => {
const subject = new Rx.Subject();
setTimeout(() => { subject.next(value); subject.complete(); }, 5000);
return subject;
}),
wrap(undefined, value => console.log('AFTER REQUEST', value))
).subscribe(value => console.log('value emitted', value), null, () => console.log('complete'));
```
As stated, maybe a bit complicated, but it integrates seamlessly with RxJS operators and it is always a good example to know how to create our own operators :-)
For what you say in your comment, you can check the last example. There, I combine two `wrap` operators. The first one only uses the `before` callback, so it only executes something before a value is been emitted. As you see, because the source observable is from an array, the four `before` callbacks are executed immediately. Then, we apply `flatMap`. To it, we apply a new `wrap`, but this time with just the `after` callback. So, this callback is only called after the observables returned by `flatMap` yield their values.
Of course, if instead an observable from an array, you'd have one made from an event listener, you'd have:
1. `before` callback is executed just before the event fired is pushed by the observable.
2. The asynchronous observable executes.
3. The asynchronous observable yields values after a time t.
4. The `after` callback is executed.
This is where having operators pays off, as they're easily combined. Hope this suits you.
Upvotes: 2 <issue_comment>username_3: So, from what I understood, you can do something like this:
```
class Wrapper {
\_dataSubject: Subject;
wrapped$: Observable;
constructor(wrapped$: Subject) {
this.\_dataSubject = wrapped$;
this.wrapped$ = this.\_dataSubject.pipe(
tap(\_ => console.log("BEFORE")),
tap(data => console.log(data)),
tap(\_ => console.log("AFTER"))
);
}
}
```
And then:
```
let subject = new Subject();
let wrapper = new Wrapper(subject);
wrapper.wrapped$.subscribe();
subject.next("foo")
```
Upvotes: 2 <issue_comment>username_4: Thanks for all your input!
I now came up with my own solution. The `AFTER` and `DATA` output are in the wrong order, but I figured out that this isn't important as long as they come at the same time
The code still needs some refactoring, but at least it works for now!
```
class Wrapper {
_taskDoneSubject = new Subject();
taskDone$ = this.\_taskDoneSubject.asObservable();
wrappedSwitchMap(wrapped: (val: T) => Observable): OperatorFunction {
return switchMap(val => { // can also be done using mergeMap
this.\_taskDoneSubject.next(false);
return wrapped(val).pipe(
tap(\_ => this.\_taskDoneSubject.next(true))
);
});
}
}
```
Usage:
```
test(valueEmittingObservable: Observable) {
let wrapper = new Wrapper();
wrapper.taskDone$.subscribe(val => console.log("task done? ", val);
valueEmittingObservable.pipe(
// wrapper.wrappedSwitchMap(val => anObservableThatTakesAWhile(val))
wrapper.wrappedSwitchMap(val => of("foo").pipe(delay(5000)) // simulated
).subscribe(val => console.log("emitted value: ", val);
}
```
Output:
```
task done? false
(... 5 seconds delay ...)
task done? true
emitted value: foo
```
Or if it's emitting faster than 5 seconds:
```
task done? false
(... 1 second until next emit ...)
task done? false
(... 5 seconds delay ...)
task done? true
emitted value: foo
```
Upvotes: 0 <issue_comment>username_5: If you wanted to do this without a class using RxJs 6:
```js
return of(null)
.pipe(tap(_ => {
console.log('BEFORE');
}))
.pipe(switchMap(_ => wrappedObservable))
.pipe(tap(_ => {
console.log('AFTER');
}))
```
Upvotes: 0 |
2018/03/22 | 1,832 | 6,659 | <issue_start>username_0: I have checkboxes on my page:
```
```
I also have links to select and deselect all checkboxes:
```
* [Select all](#)
* [Deselect all](#)
```
This code selects and deselects the checkboxes:
```
$('#select-all-list').on('click', function() {
$('.select-doc').prop('checked', true);
});
$('#deselect-all-list').on('click', function() {
$('.select-doc').prop('checked', true);
});
```
**The problem is: when I select all checkboxes - I can't uncheck some of them manually (directly with my mouse). How do I do it?**<issue_comment>username_1: What about something like this
```
import {Observable} from 'rxjs';
export class DoBeforeAfter {
wrapped$: Observable;
constructor(wrapped$: Observable, doFunction: (data: any) => void) {
this.wrapped$ = Observable.of(null)
.do(\_ => console.log("BEFORE"))
.switchMap(\_ => wrapped$)
.do(doFunction)
.do(\_ => console.log('AFTER'));
}
}
```
to be consumed like this
```
const source = Observable.of('NOW');
const beforeAfter = new DoBeforeAfter(source, data => console.log(data));
beforeAfter.wrapped$.subscribe(
null,
error => console.error(error),
() => console.log('DONE')
```
)
It looks a bit cumbersome, but maybe it can help
Upvotes: 5 [selected_answer]<issue_comment>username_2: The best way (though complicated) is to create a new operator, similar to `tap` but that does something before and after the value is emitted.
You can see it working in the example (it's in ES6, as SO code snippets don't accept TypeScript, but you'll get the idea)
```js
function wrap(before, after) {
return function wrapOperatorFunction(source) {
return source.lift(new WrapOperator(before, after));
};
}
class WrapOperator {
constructor(before, after) {
this.before = before;
this.after = after;
}
call(subscriber, source) {
return source.subscribe(new WrapSubscriber(subscriber, this.before, this.after));
}
}
class WrapSubscriber extends Rx.Subscriber {
constructor(destination, before, after) {
super(destination);
this.before = before;
this.after = after;
}
_next(value) {
this.before ? this.before(value) : null;
this.destination.next(value);
this.after ? this.after(value) : null;
}
}
// Now:
const observable = Rx.Observable.from([1, 2, 3, 4]);
observable.pipe(
wrap(value => console.log('before', value), value => console.log('after', value))
).subscribe(value => console.log('value emitted', value), null, () => console.log('complete'));
// For what you want:
// let's simulate that, for each value in the array, we'll fetch something from an external service:
// we want the before to be executed when we make the request, and the after to be executed when it finishes. In this // case, we just combine two wrap operators and flatMap, for example:
observable.pipe(
wrap(value => console.log('BEFORE REQUEST', value)),
Rx.operators.flatMap(value => {
const subject = new Rx.Subject();
setTimeout(() => { subject.next(value); subject.complete(); }, 5000);
return subject;
}),
wrap(undefined, value => console.log('AFTER REQUEST', value))
).subscribe(value => console.log('value emitted', value), null, () => console.log('complete'));
```
As stated, maybe a bit complicated, but it integrates seamlessly with RxJS operators and it is always a good example to know how to create our own operators :-)
For what you say in your comment, you can check the last example. There, I combine two `wrap` operators. The first one only uses the `before` callback, so it only executes something before a value is been emitted. As you see, because the source observable is from an array, the four `before` callbacks are executed immediately. Then, we apply `flatMap`. To it, we apply a new `wrap`, but this time with just the `after` callback. So, this callback is only called after the observables returned by `flatMap` yield their values.
Of course, if instead an observable from an array, you'd have one made from an event listener, you'd have:
1. `before` callback is executed just before the event fired is pushed by the observable.
2. The asynchronous observable executes.
3. The asynchronous observable yields values after a time t.
4. The `after` callback is executed.
This is where having operators pays off, as they're easily combined. Hope this suits you.
Upvotes: 2 <issue_comment>username_3: So, from what I understood, you can do something like this:
```
class Wrapper {
\_dataSubject: Subject;
wrapped$: Observable;
constructor(wrapped$: Subject) {
this.\_dataSubject = wrapped$;
this.wrapped$ = this.\_dataSubject.pipe(
tap(\_ => console.log("BEFORE")),
tap(data => console.log(data)),
tap(\_ => console.log("AFTER"))
);
}
}
```
And then:
```
let subject = new Subject();
let wrapper = new Wrapper(subject);
wrapper.wrapped$.subscribe();
subject.next("foo")
```
Upvotes: 2 <issue_comment>username_4: Thanks for all your input!
I now came up with my own solution. The `AFTER` and `DATA` output are in the wrong order, but I figured out that this isn't important as long as they come at the same time
The code still needs some refactoring, but at least it works for now!
```
class Wrapper {
_taskDoneSubject = new Subject();
taskDone$ = this.\_taskDoneSubject.asObservable();
wrappedSwitchMap(wrapped: (val: T) => Observable): OperatorFunction {
return switchMap(val => { // can also be done using mergeMap
this.\_taskDoneSubject.next(false);
return wrapped(val).pipe(
tap(\_ => this.\_taskDoneSubject.next(true))
);
});
}
}
```
Usage:
```
test(valueEmittingObservable: Observable) {
let wrapper = new Wrapper();
wrapper.taskDone$.subscribe(val => console.log("task done? ", val);
valueEmittingObservable.pipe(
// wrapper.wrappedSwitchMap(val => anObservableThatTakesAWhile(val))
wrapper.wrappedSwitchMap(val => of("foo").pipe(delay(5000)) // simulated
).subscribe(val => console.log("emitted value: ", val);
}
```
Output:
```
task done? false
(... 5 seconds delay ...)
task done? true
emitted value: foo
```
Or if it's emitting faster than 5 seconds:
```
task done? false
(... 1 second until next emit ...)
task done? false
(... 5 seconds delay ...)
task done? true
emitted value: foo
```
Upvotes: 0 <issue_comment>username_5: If you wanted to do this without a class using RxJs 6:
```js
return of(null)
.pipe(tap(_ => {
console.log('BEFORE');
}))
.pipe(switchMap(_ => wrappedObservable))
.pipe(tap(_ => {
console.log('AFTER');
}))
```
Upvotes: 0 |
2018/03/22 | 781 | 3,104 | <issue_start>username_0: I have 3 activities, that connect like this:
A -> B -> C.
On A you input a text that will be used in C, then B opens and you input another text to be used in C. But when C opens, produces null errors.
I came up with a solution, to start A then go directly to C and onCreate of C, start B as if it was going from A to B.
Is there a better solution? Is my solution decent or will it cause more problems than it fixes? Thanks for any help.<issue_comment>username_1: There are several options - `Intent` extras, `SharedPreferences`, `SQLite` database, internal/external storage, `Application` class, static data classes etc.
For situation you've explained, I recommend using `SharedPreferences` to store data, it's relatively easy approach and you can access stored data at any time from any `Activity` or class, here is a simple usage guide:
**Input data into SharedPreferences:**
```
SharedPreferences.Editor editor = getSharedPreferences("YourPrefsFile", MODE_PRIVATE).edit();
editor.putString("name", "Elena");
editor.putInt("idName", 12);
editor.apply();
```
**Get data from SharedPreferences:**
```
SharedPreferences prefs = getSharedPreferences("YourPrefsFile", MODE_PRIVATE);
String restoredText = prefs.getString("text", null);
if (restoredText != null) {
String name = prefs.getString("name", "");
int idName = prefs.getInt("idName", 0);
}
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: You have 4 solutions in this case the
1. first one is which you mentioned
2. the second one is using an intent with put extra in every activity that you will go from
3. the third solution is using a static variables so that the variables will not be affected if activity reopened (not recommended)
4. the fourth one you can use shared preference to save the data (which will be the best solution in my opinion)
Upvotes: 1 <issue_comment>username_3: This is not a very good idea as their may be delays in starting the activity as you would be doing some other operations as well in the onCreate method of activity B and C. Will cause performance issues in future due to delay in showing the activity.
Things you can do...
* If the data is very small lets say a key value pair then why not use shared preferences.
* Or use a database to store the data as and when it gets created, after which when the activity is created query it and show it.
Upvotes: 0 <issue_comment>username_4: I think, You can **pass the input to next activity through intent**.
Since it is a text input,
```
intent.putExtra("A_Activity_Input","YourinputString"); //in activity A
```
Then Activity B starts, Get the string using
```
String Input_A_Activity=getIntent().getStringExtra("A_Activity_Input");
```
After When you are starting C activity from B, send both data using intent
```
intent.putExtra("A_Activity_Input",Input_A_Activity);
intent.putExtra("B_Activity_Input","YourinputString");
```
In Activity C, Get the string from the intent.
Since you just need a data to process, **Storing it in SQL or SharedPref or something else wastes memory**
Upvotes: 0 |
2018/03/22 | 739 | 3,009 | <issue_start>username_0: I have an online JSON file that shows the latest country earthquakes, the listView adapter in my app receives data from this JSON file and the refresh is manually by user`s swipe, but now I am adding an automatic and timely basis refresh mode to my list, the questions is:
**How can I create a system notification after a new quake is detected?**<issue_comment>username_1: There are several options - `Intent` extras, `SharedPreferences`, `SQLite` database, internal/external storage, `Application` class, static data classes etc.
For situation you've explained, I recommend using `SharedPreferences` to store data, it's relatively easy approach and you can access stored data at any time from any `Activity` or class, here is a simple usage guide:
**Input data into SharedPreferences:**
```
SharedPreferences.Editor editor = getSharedPreferences("YourPrefsFile", MODE_PRIVATE).edit();
editor.putString("name", "Elena");
editor.putInt("idName", 12);
editor.apply();
```
**Get data from SharedPreferences:**
```
SharedPreferences prefs = getSharedPreferences("YourPrefsFile", MODE_PRIVATE);
String restoredText = prefs.getString("text", null);
if (restoredText != null) {
String name = prefs.getString("name", "");
int idName = prefs.getInt("idName", 0);
}
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: You have 4 solutions in this case the
1. first one is which you mentioned
2. the second one is using an intent with put extra in every activity that you will go from
3. the third solution is using a static variables so that the variables will not be affected if activity reopened (not recommended)
4. the fourth one you can use shared preference to save the data (which will be the best solution in my opinion)
Upvotes: 1 <issue_comment>username_3: This is not a very good idea as their may be delays in starting the activity as you would be doing some other operations as well in the onCreate method of activity B and C. Will cause performance issues in future due to delay in showing the activity.
Things you can do...
* If the data is very small lets say a key value pair then why not use shared preferences.
* Or use a database to store the data as and when it gets created, after which when the activity is created query it and show it.
Upvotes: 0 <issue_comment>username_4: I think, You can **pass the input to next activity through intent**.
Since it is a text input,
```
intent.putExtra("A_Activity_Input","YourinputString"); //in activity A
```
Then Activity B starts, Get the string using
```
String Input_A_Activity=getIntent().getStringExtra("A_Activity_Input");
```
After When you are starting C activity from B, send both data using intent
```
intent.putExtra("A_Activity_Input",Input_A_Activity);
intent.putExtra("B_Activity_Input","YourinputString");
```
In Activity C, Get the string from the intent.
Since you just need a data to process, **Storing it in SQL or SharedPref or something else wastes memory**
Upvotes: 0 |
2018/03/22 | 849 | 3,232 | <issue_start>username_0: using the code below
```
$matchs = DiraChatLog::where('status','=','Match')->whereBetween('date_access', [$request->from, $request->to])->get();
foreach ($matchs as $key => $match) {
$array[] = [
$match->status => $match->date_access,
];
}
dd($array);
```
i get the output
[](https://i.stack.imgur.com/cCRJu.jpg)
now i want to merge the 4 arrays to 1.. how can i do that? my ouuput should be `array:1> date => value`
i have tried array\_merge() and array\_push() and it didnt work<issue_comment>username_1: There are several options - `Intent` extras, `SharedPreferences`, `SQLite` database, internal/external storage, `Application` class, static data classes etc.
For situation you've explained, I recommend using `SharedPreferences` to store data, it's relatively easy approach and you can access stored data at any time from any `Activity` or class, here is a simple usage guide:
**Input data into SharedPreferences:**
```
SharedPreferences.Editor editor = getSharedPreferences("YourPrefsFile", MODE_PRIVATE).edit();
editor.putString("name", "Elena");
editor.putInt("idName", 12);
editor.apply();
```
**Get data from SharedPreferences:**
```
SharedPreferences prefs = getSharedPreferences("YourPrefsFile", MODE_PRIVATE);
String restoredText = prefs.getString("text", null);
if (restoredText != null) {
String name = prefs.getString("name", "");
int idName = prefs.getInt("idName", 0);
}
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: You have 4 solutions in this case the
1. first one is which you mentioned
2. the second one is using an intent with put extra in every activity that you will go from
3. the third solution is using a static variables so that the variables will not be affected if activity reopened (not recommended)
4. the fourth one you can use shared preference to save the data (which will be the best solution in my opinion)
Upvotes: 1 <issue_comment>username_3: This is not a very good idea as their may be delays in starting the activity as you would be doing some other operations as well in the onCreate method of activity B and C. Will cause performance issues in future due to delay in showing the activity.
Things you can do...
* If the data is very small lets say a key value pair then why not use shared preferences.
* Or use a database to store the data as and when it gets created, after which when the activity is created query it and show it.
Upvotes: 0 <issue_comment>username_4: I think, You can **pass the input to next activity through intent**.
Since it is a text input,
```
intent.putExtra("A_Activity_Input","YourinputString"); //in activity A
```
Then Activity B starts, Get the string using
```
String Input_A_Activity=getIntent().getStringExtra("A_Activity_Input");
```
After When you are starting C activity from B, send both data using intent
```
intent.putExtra("A_Activity_Input",Input_A_Activity);
intent.putExtra("B_Activity_Input","YourinputString");
```
In Activity C, Get the string from the intent.
Since you just need a data to process, **Storing it in SQL or SharedPref or something else wastes memory**
Upvotes: 0 |
2018/03/22 | 1,165 | 3,550 | <issue_start>username_0: Given a set of consecutive numbers from `1` to `n`, I'm trying to find the number of subsets that do not contain consecutive numbers.
E.g., for the set `[1, 2, 3]`, some possible subsets are `[1, 2]` and `[1, 3]`. The former would not be counted while the latter would be, since 1 and 3 are not consecutive numbers.
Here is what I have:
```rb
def f(n)
consecutives = Array(1..n)
stop = (n / 2.0).round
(1..stop).flat_map { |x|
consecutives.combination(x).select { |combo|
consecutive = false
combo.each_cons(2) do |l, r|
consecutive = l.next == r
break if consecutive
end
combo.length == 1 || !consecutive
}
}.size
end
```
It works, but I need it to work faster, under 12 seconds for `n <= 75`. How do I optimize this method so I can handle high `n` values no sweat?
I looked at:
* [Check if array is an ordered subset](https://stackoverflow.com/questions/47636783/)
* [How do I return a group of sequential numbers that might exist in an array?](https://stackoverflow.com/questions/6258971/)
* [Check if an array is subset of another array in Ruby](https://stackoverflow.com/questions/10567430/)
and some others. I can't seem to find an answer.
Suggested duplicate is [Count the total number of subsets that don't have consecutive elements](https://stackoverflow.com/questions/44485629/count-the-total-number-of-subsets-that-dont-have-consecutive-elements), although that question is slightly different as I was asking for this optimization in Ruby and I do not want the empty subset in my answer. That question would have been very helpful had I initially found that one though! But SergGr's answer is exactly what I was looking for.<issue_comment>username_1: let number of subsets with no consecutive numbers from{i...n} be f(i), then f(i) is the sum of:
1) f(i+1) , the number of such subsets without i in them.
2) f(i+2) + 1 , the number of such subsets with i in them (hence leaving out i+1 from the subset)
So,
```
f(i)=f(i+1)+f(i+2)+1
f(n)=1
f(n-1)=2
```
f(1) will be your answer.
You can solve it using matrix exponentiation(<http://zobayer.blogspot.in/2010/11/matrix-exponentiation.html>) in O(logn) time.
Upvotes: 1 <issue_comment>username_2: Although @user3150716 idea is correct the details are wrong. Particularly you can see that for `n = 3` there are 4 subsets: `[1]`,`[2]`,`[3]`,`[1,3]` while his formula gives only 3. That is because he missed the subset `[3]` (i.e. the subset consisting of just `[i]`) and that error accumulates for larger `n`. Also I think it is easier to think if you start from `1` rather than `n`. So the correct formulas would be
```
f(1) = 1
f(2) = 2
f(n) = f(n-1) + f(n-2) + 1
```
Those formulas are easy to code using a simple loop in constant space and `O(n)` speed:
```
def f(n)
return 1 if n == 1
return 2 if n == 2
# calculate
# f(n) = f(n-1) + f(n - 2) + 1
# using simple loop
v2 = 1
v1 = 2
i = 3
while i <= n do
i += 1
v1, v2 = v1 + v2 + 1, v1
end
v1
end
```
You can see this online together with the original code [here](https://repl.it/repls/RingedMajorArchitects)
This should be pretty fast for any `n <= 75`. For much larger `n` you might require some additional tricks like noticing that `f(n)` is actually one less than a [Fibonacci number](https://en.wikipedia.org/wiki/Fibonacci_number)
```
f(n) = Fib(n+2) - 1
```
and there is a closed formula for Fibonacci number that theoretically can be computed faster for big `n`.
Upvotes: 3 [selected_answer] |
2018/03/22 | 2,352 | 7,307 | <issue_start>username_0: I need help with a little css.
I have two clickable text areas (like in the code pen below). If i click the first one the first text and img need to be shown and if i click the second textfield the second text and img need to be show.
I didn't get it. I´m too stupid.
I prefer css only. If there is no other way JS is also possible.
```css
.test{
float:left;
background-color: gray; /*only when active*/
margin: 5px;
padding:5px;
}
.text1{
display:block;
background-color:gray;
}
.text2{
display: none;
background-color:gray;
}
.img1 img{
max-width: 600px;}
.img2 img{
max-width: 600px;
display: none}
```
```html


Click Area 1
Click Area 2
Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.
Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.
```<issue_comment>username_1: This should be the behavior you want:
Using bootstrap tab:
<https://jsfiddle.net/ramseyfeng/ewhnv0ua/>
```
* [Click Area 1](#home)
* [Click Area 2](#menu1)

Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.

aLorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.
```
Upvotes: 0 <issue_comment>username_2: Below is an idea to do it using pure css.
you can change the position with help of media queries.
```css
.test{
float:left;
background-color: gray; /*only when active*/
margin: 5px;
padding:5px;
}
.text1{
display:block;
background-color:gray;
}
.text2{
display: none;
background-color:yellow;
}
.img1 img{
max-width: 600px;}
.img2 img{
max-width: 600px;
display: none}
.relative{
position:relative;
}
.tabContent{
display:none;
position:absolute;
top: 30px;
left:0;
}
a.test:focus + p.tabContent{
display:inline;
}
```
```html
[Click Area 1](#)
Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.
[Click Area 2](#)
Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.
```
Upvotes: -1 |
2018/03/22 | 1,706 | 4,902 | <issue_start>username_0: If I have a vector `(def v [1 2 3])`, I can replace the first element with `(assoc v 0 666)`, obtaining `[666 2 3]`
But if I try to do the same after mapping over the vector:
```
(def v (map inc [1 2 3]))
(assoc v 0 666)
```
the following exception is thrown:
```
ClassCastException clojure.lang.LazySeq cannot be cast to clojure.lang.Associative
```
What's the most idiomatic way of editing or updating a single element of a lazy sequence?
Should I use `map-indexed` and alter only the index 0 or realize the lazy sequence into a vector and then edit it via assoc/update?
The first has the advantage of maintaining the laziness, while the second is less efficient but maybe more obvious.
I guess for the first element I can also use drop and cons.
Are there any other ways? I was not able to find any examples anywhere.<issue_comment>username_1: >
> What's the most idiomatic way of editing or updating a single element of a lazy sequence?
>
>
>
There's no *built-in* function for modifying a single element of a sequence/list, but `map-indexed` is probably the closest thing. It's not an efficient operation for lists. Assuming you don't *need* laziness, I'd pour the sequence into a vector, which is what `mapv` does i.e. `(into [] (map f coll))`. Depending on how you use your modified sequence, it may be just as performant to vectorize it and modify.
You could write a function using `map-indexed` to do something similar and lazy:
```
(defn assoc-seq [s i v]
(map-indexed (fn [j x] (if (= i j) v x)) s))
```
Or if you want to do this work in one pass lazily without vector-izing, you can also use a transducer:
```
(sequence
(comp
(map inc)
(map-indexed (fn [j x] (if (= 0 j) 666 x))))
[1 2 3])
```
Realizing your use case is to only modify the first item in a lazy sequence, then you can do something simpler while preserving laziness:
```
(concat [666] (rest s))
```
Update re: comment on optimization: username_2's `assoc-at` function is ~8ms faster when updating the 500,000th element in a 1,000,000 element lazy sequence, so you should use his answer if you're looking to squeeze every bit of performance out of an inherently inefficient operation:
```
(def big-lazy (range 1e6))
(crit/bench
(last (assoc-at big-lazy 500000 666)))
Evaluation count : 1080 in 60 samples of 18 calls.
Execution time mean : 51.567317 ms
Execution time std-deviation : 4.947684 ms
Execution time lower quantile : 47.038877 ms ( 2.5%)
Execution time upper quantile : 65.604790 ms (97.5%)
Overhead used : 1.662189 ns
Found 6 outliers in 60 samples (10.0000 %)
low-severe 4 (6.6667 %)
low-mild 2 (3.3333 %)
Variance from outliers : 68.6139 % Variance is severely inflated by outliers
=> nil
(crit/bench
(last (assoc-seq big-lazy 500000 666)))
Evaluation count : 1140 in 60 samples of 19 calls.
Execution time mean : 59.553335 ms
Execution time std-deviation : 4.507430 ms
Execution time lower quantile : 54.450115 ms ( 2.5%)
Execution time upper quantile : 69.288104 ms (97.5%)
Overhead used : 1.662189 ns
Found 4 outliers in 60 samples (6.6667 %)
low-severe 4 (6.6667 %)
Variance from outliers : 56.7865 % Variance is severely inflated by outliers
=> nil
```
The `assoc-at` version is 2-3x faster when updating the *first* item in a large lazy sequence, but it's no faster than `(last (concat [666] (rest big-lazy)))`.
Upvotes: 4 [selected_answer]<issue_comment>username_2: i would probably go with something generic like this, if this functionality is really needed (which i strongly doubt about):
```
(defn assoc-at [data i item]
(if (associative? data)
(assoc data i item)
(if-not (neg? i)
(letfn [(assoc-lazy [i data]
(cond (zero? i) (cons item (rest data))
(empty? data) data
:else (lazy-seq (cons (first data)
(assoc-lazy (dec i) (rest data))))))]
(assoc-lazy i data))
data)))
user> (assoc-at {:a 10} :b 20)
;; {:a 10, :b 20}
user> (assoc-at [1 2 3 4] 3 101)
;; [1 2 3 101]
user> (assoc-at (map inc [1 2 3 4]) 2 123)
;; (2 3 123 5)
```
another way is to use `split-at`:
```
(defn assoc-at [data i item]
(if (neg? i)
data
(let [[l r] (split-at i data)]
(if (seq r)
(concat l [item] (rest r))
data))))
```
notice that both this functions short circuit the coll traversal, which mapping approach doesn't. Here some quick and dirty benchmark:
```
(defn massoc-at [data i item]
(if (neg? i)
data
(map-indexed (fn [j x] (if (== i j) item x)) data)))
(time (last (assoc-at (range 10000000) 0 1000)))
;;=> "Elapsed time: 747.921032 msecs"
9999999
(time (last (massoc-at (range 10000000) 0 1000)))
;;=> "Elapsed time: 1525.446511 msecs"
9999999
```
Upvotes: 2 |
2018/03/22 | 726 | 2,767 | <issue_start>username_0: I have created 3 div having the same class in a parent , and on the child element i am adding the active class and on click of second child adding the active class again but this time i want to remove the active state for first element.
How can i remove it in effective way?
Here is my code
```
default
hover
active
```
Here is my javascript
```
var elements = document.querySelectorAll('.tab');
for (var i = 0; i < elements.length; i++) {
elements[i].classList.remove('active');
elements[i].onclick = function (event) {
console.log("ONCLICK");
if (event.target.innerHTML === this.innerHTML) {
this.classList.add("active");
}
}
}
```<issue_comment>username_1: You are not removing the `active` class from all elements when `click` event is triggered. So, what you can do is to loop over again to all the `div` and remove the `active` class on `click` event. I have created a custom function `removeClass()` that removes the `active` class on `click` event.
```js
var elements = document.querySelectorAll('.tab');
for (var i = 0; i < elements.length; i++) {
elements[i].classList.remove('active');
elements[i].onclick = function (event) {
console.log("ONCLICK");
//remove all active class
removeClass();
if (event.target.innerHTML === this.innerHTML) {
this.classList.add("active");
}
}
}
function removeClass(){
for (var i = 0; i < elements.length; i++) {
elements[i].classList.remove('active');
}
}
```
```css
.active{
color: green;
}
```
```html
default
hover
active
```
Upvotes: 4 [selected_answer]<issue_comment>username_2: I suppose it depends how many `div`s you will ultimately have, and if only one `div` should be active at a time, but I think it would be more efficient to just find the active `div` and remove the class from that one rather than looping through all of them e.g.
```
var oldActiveElement = document.querySelector('.active');
oldActiveElement.classList.remove('active');
var newActiveElement = event.target;
newActiveElement.classList.add('active');
```
Upvotes: 2 <issue_comment>username_3: Since all of them have a class called `tab`, make sure you remove the class or property of `active` from all the classes by targeting the class `tab` and it would remove from all without doing any loop. Then add the property to the current one that is clicked.
```
$(".tab").click(function(){
$(".tab").removeClass('active');
$("this").addClass('active');
});
```
If the class is in the parent you can do sth like
```
$(".tab").click(function({
$(".tab").parent().removeClass('active');
$("this").parent().addClass('active');
});
```
Upvotes: 0 |
2018/03/22 | 697 | 2,222 | <issue_start>username_0: I want to get **navbar** but I m not getting it after many failed attempts I came here for help.
```html
Portofolio
Toggle navigation
[Brand](#)
* [Link (current)](#)
* [Link](#)
* [Dropdown](#)
+ [Action](#)
+ [Another action](#)
+ [Something else here](#)
+
+ [Separated link](#)
+
+ [One more separated link](#)
Submit
* [Link](#)
* [Dropdown](#)
+ [Action](#)
+ [Another action](#)
+ [Something else here](#)
+
+ [Separated link](#)
```
I took the code for navbar default from **official website** [here](https://getbootstrap.com/docs/3.3/components/#navbar)
but it only showing **"Brand"** nothing else. What to do to get the navbar? I even did the CSS>POPPER>JS Order but I am not getting wt I am doing wrong any help would be greatly helpful<issue_comment>username_1: It works perfectly if you pay attention to the version number.
Bootstrap 3 code certainly won't work with Bootstrap 4 css and vice versa.
Here's a working example of a Bootstrap 4 navbar:
```html
[Navbar](#)
* [Home (current)](#)
* [Link](#)
* [Dropdown](#)
[Action](#)
[Another action](#)
[Something else here](#)
* [Disabled](#)
Search
```
Reference:
<https://getbootstrap.com/docs/4.0/components/navbar/>
Upvotes: 4 [selected_answer]<issue_comment>username_2: Replace just the link and script files
```
Portofolio
Toggle navigation
[Brand](#)
* [Link (current)](#)
* [Link](#)
* [Dropdown](#)
+ [Action](#)
+ [Another action](#)
+ [Something else here](#)
+
+ [Separated link](#)
+
+ [One more separated link](#)
Submit
* [Link](#)
* [Dropdown](#)
+ [Action](#)
+ [Another action](#)
+ [Something else here](#)
+
+ [Separated link](#)
```
Upvotes: 0 <issue_comment>username_3: Use the correct example for your version. You're including bootstrap 4, but use an example for version 3.3.
Below is for bootstrap 4:
```html
Portofolio
[Navbar](#)
* [Home (current)](#)
* [Link](#)
* [Dropdown](#)
[Action](#)
[Another action](#)
[Something else here](#)
* [Disabled](#)
Search
```
Upvotes: 2 <issue_comment>username_4: please add this links in your head section and then design your navbar properly
Upvotes: 0 |
2018/03/22 | 1,608 | 6,370 | <issue_start>username_0: We are facing one issue in our project i.e. Data verification issue.
The project is about Replication of data from Sybase to oracle DBs.
The table structures for Table A across Sybase, Oracle is same.
Same column and primary key combination across all the databases.
e.g. If Sybase has Table A with columns a, b and C
same table with same name and same columns will be available in different databses.
We are done with replication stuff part.But we faced some silent failure like data discrepancy just wondering if there will any tool already available for this.
Any information on his would be helpful. Thanks.<issue_comment>username_1: I've worked on a few migration projects and a key part has always been data reconciliation.
I can only talk about the approaches we took, based on constraints around tools available and minimising downtime, and constraints of available space.
In all cases I took to writing scripts that worked on two levels - summary view and "deep dive". We couldn't find any tools readily available that did what we wanted in a timely enough manner. In fact even the migration tools we found had limitations (datapump, sqlloader, golden gate, etc) and hand coded scripts to handle the bits that we found to be lacking or too slow in the standard tools.
The summary view varied from project to project. It was part functional based (do the accounting figures for transactions match) for the users to verify, and part technical. For smaller tables we could just write simple reports and the diff was straight forward.
For larger tables we wrote technical reports that looked at bands of data (e.g group the PK into 1000s) collect all the column data and produce checksum, generating a report for each table like:
```
PK ID Range Start Checksum
----------------- -----------
100000 22773377829
200000 38938938282
.
.
```
Corresponding table pairs from each database were then were "diff"d against each other to highlight discrepancies. Any differences that were found could then be looked at in more detail.
The scripts were written in such a way to allow them to run in parallel looking at discrete bands. Te band ranges were tunable as well to get the best throughput. This obviously sped things up.
The scripts were shell scripts firing off sqlplus reports, and similar for the source database.
On one project there wasn't enough diskspace to do these reports, so I wrote a Java program that queried the two databases side by side, using block queues to fetch and compare rowsets. Being in memory meant this was super fast.
For the "deep dive" we looked at the details for key tables, or for tables that reports a checksum difference.
For the user reports, the users would specify what they wanted to see, and we wrote the reports accordingly.
On the last project, the only discrepancies found were caused by character set conversion issues (people names with accents weren't handled correctly).
On projects where the overall dataset was smaller we extracted the data to XML files and wrote a Java tool to processes pairs and report differences.
Upvotes: 0 <issue_comment>username_2: Sybase (now SAP) has a couple products that can be used for data comparisons and reconciliation:
* `rs_subcmp` - an older, 32-bit tool that comes with the `Sybase Replication Server` product that can be used to compare data between
source and target; SQL reconciliation scripts can be generated from
the differences and then applied to the target to bring it in sync
with the source; if your tables are more than 1GB in size you can
still use `rs_subcmp` but you'll need to create multiple comparison
jobs (via `where` clauses) to work on different subsets of your tables
[I don't recall if `rs_subcmp` can be use for heterogeneous
replication setsup, eg, ASE-Oracle.]
* `Data Assurance (DA)` - the newer, 64-bit product ... also from
Sybase ... which can also compare data and (re)sync the target(s)
from the source (either via SQL reconciliation scripts or directly);
`DA` is capable of handling comparisons between a handful of
different RDBMS products (eg, ASE-Oracle); I'm currently working on a
project where one of the requirements is to validate (and reconcile
where needed) 200+TB of data being migrated from Oracle to HANA and
I'm using `DA` for the validation/reconciliation portion of the project
As @username_1 has hinted at with his answer, there's a good bit of effort involved to compare data and generate code to reconcile the differences. Rolling your own code is doable but will entail a lot of work. If you've got the money you'll likely find 3rd party tools can get most/all of the work done for you.
If you used a 3rd party product to replicate your data from Sybase to Oracle, you may want to see if the same vendor has a comparison/validation/reconciliation tool you could use.
Upvotes: 1 <issue_comment>username_3: The SAP/Sybase rs\_subcmp tool is pretty powerful and also pretty hard to use. For details see:
<https://help.sap.com/viewer/075940003f1549159206fcc89d020515/16.0.3.3/en-US/feb58db1bd1c1014b134ef4efef25563.html?q=rs_subcmp>
You have to pass it key field information, but once you do that, it can retry/restart the compare streams after transient differences. Pretty fancy.
rs\_subcmp expects to work on Sybase data source. So to compare against Oracle, you'd probably have to setup one of those Sybase-to-Oracle gateway products ($$$$$).
Could you install the Oracle ODBC drivers and configure them to allow Sybase clients to access Oracle? I'm guessing not (but that's outside the range of my experience).
Note the "-h" option for rs\_subcmp. The docs just say it runs a "fast comparison", but what it's actually doing is running queries using the hashbytes() function. Something like:
```
select keyfield1,keyfield2, hashbytes("Md5",datacol1,datacol2,datacol3)
from mytable
```
So this sort of query might be good for the "summary view" type comparison discussed above (if the Oracle STANDARD\_HASH() function output matches up with the Sybase hashbytes() function (again, outside my experience))
Note, as of ASE 16, there was a bug with the hash() & hashbytes() functions running the Md5 hash option against large varbinary columns where they could use up all procedure cache, potentially crashing the server (CR 811073)
Upvotes: 0 |
2018/03/22 | 483 | 1,334 | <issue_start>username_0: I'm writing simple function which returns maskable array of zeros and ones to array of numbers.
If number is a power of two maskable index will be one if not then zero.
It works fine without passing my simple function isPower() , but when I do pass it. weird things happen.
I want my code works with
```
if(isPower(nums[i]))
```
Without or condition
```
#include
int \*isPowerOf2(int num, int\*nums,int \*result);
int isPower(int num);
int main(void)
{
int array[]= {1,2,2,4,4,3,4,3,3,4,4,4,4,4};
int size=0;
int \*result=NULL;
result=isPowerOf2(14,array,&size);
for(int i=0; i
```<issue_comment>username_1: At times like this it pays to check what you're actually computing:
```
#include
int main() {
printf("%d %d\n",!(7&6),((7&6==0) ? 1 : 0)); //Not a power of 2
printf("%d %d\n",!(8&7),((8&7==0) ? 1 : 0)); //Power of 2
return 0;
}
```
Returns:
```
0 0
1 0
```
If you think about it a bit, should make sense. Or does it? [Operator precedence](http://en.cppreference.com/w/c/language/operator_precedence) is killing you here. Why would the bottom right be 0?
Upvotes: 3 [selected_answer]<issue_comment>username_2: Befare that
(1 & 2) is a bitwise operand while
(1 && 2) is the logical operand.
So to be clear:
(1 & 2) == 0 is something completely different than !(1 & 2).
Upvotes: 1 |
2018/03/22 | 350 | 1,114 | <issue_start>username_0: How to use `bs4` with `find_all` with the class tag with space?
```
container = containers[0]
product_container = container.find_all('div',{'class': 's-item-container'})
product_name = product_container.find_all('div', {'class': 'a-fixed-left-grid-col'})
print (product_name)
```
the div class tag is "`a-fixed-left-grid-col a-col-right`", how can i deliver the `find_all` functions?<issue_comment>username_1: You can directly use the class name with spaces as the value for `class` if the tags you want have the format .
```
soup.find_all('tag', {'class': 'classname1 classname2 ...'})
```
You can also use a list of classes:
```
soup.find_all('tag', {'class': ['class1', 'class2']})
```
But, the second method will match all the tags of the following type:
* `class="class1"`
* `class="class2"`
* `class="class1 class2"`
* `class="class2 class1"` (this is exactly same as above)
Upvotes: 1 <issue_comment>username_2: I am using select now to locate class with multiple tags
container.select('div.a-fixed-left-grid-col.a-col-right')
Many thanks for all your helps.
Upvotes: 0 |
2018/03/22 | 1,009 | 2,491 | <issue_start>username_0: Code:
```
x <- c(1, 1, 3, 2, 3, 5)
x[x < 3] <- x[x < 3] * 100
x
```
Output:
```
[1] 100 100 3 200 3 5
```
I expected to get the output “`[1] 100 100 200`”. How does R remember the indexes where `x < 3?` Because when running `x[x < 3]`, you get the output “`1,1,2`” (and the indexes of those numbers are `1,2,4)`.
Hence, R remember the values where `x < 3`, and manipulates those values. But how does R know the indexes of those values?<issue_comment>username_1: If you look at what is x < 3 you'll find it yields
```
[1] TRUE TRUE FALSE TRUE FALSE FALSE
```
so `x[x<3] <- x[x < 3] * 100` means multiply by 100 the first, second and fourth value of x (`x[x < 3]*100`) and replace the first, second and fourth value of x by these new values (`x[x<3] <-`).
Upvotes: 1 <issue_comment>username_2: It's not remembering the locations of the `x < 3` values. The left-hand side of your equation is explicitly the locations of the `x < 3` values.
So the thing on the right might be `(100, 100, 200)`, but the thing on the left is *the placeholders at places 1, 2 and 4*.
Upvotes: 1 <issue_comment>username_3: If you want to get the result of your call you need to assign it to a new variable:
```
x2 <- (x[x < 3] <- x[x<3] * 100)
x2
#[1] 100 100 200
```
Note that `x` will still be changed (as a result of your assignment `x[x < 3] <- x[x<3] * 100`).
If that is not desired, you can simply do:
```
x2 <- x[x<3]*100
x2
#[1] 100 100 200
x
#[1] 1 1 3 2 3 5
```
Upvotes: 3 [selected_answer]<issue_comment>username_4: In your code, you ask R to go to `x` and multiple each value less than `3` by `100` that is in this code `x[x < 3]*100`. R, in this case, looks for the place of your element. That is, the code goes to `x` values and takes them one by one. The one that obeys the condition is then multiplied by `100`. Then, the code returns you all the values of `x`. The correct way is to assign a name to your specific values as @username_3 answer.
In addition, it is a good idea to write a general function for your convenience. Here is a function.
```
myfun <- function(x, n){
res <- lapply(x, function(i) (if (i < n) {i *100}else{0}))
res
}
```
or simply use the comment of @username_3.
```
myfun <- function(x, n){
res <- x[x < n]*100
res
}
myfun(x, 3)
x <- list(1, 1, 3, 2, 3, 5)
n=3
```
Then,
```
> myfun(x, 3)
[[1]]
[1] 100
[[2]]
[1] 100
[[3]]
[1] 0
[[4]]
[1] 200
[[5]]
[1] 0
[[6]]
[1] 0
```
Upvotes: 1 |
2018/03/22 | 1,540 | 3,829 | <issue_start>username_0: I have a dataframe that is generated by the following code
```
l_ids = c(1, 1, 1, 2, 2, 2, 2)
l_months = c(5, 5, 5, 88, 88, 88, 88)
l_calWeek = c(201708, 201709, 201710, 201741, 201742, 201743, 201744)
value = c(5, 6, 3, 99, 100, 1001, 1002)
dat <- setNames(data.frame(cbind(l_ids, l_months, l_calWeek, value)),
c("ids", "months", "calWeek", "value"))
```
and looks like this:
```
+----+-------+----------+-------+
| Id | Month | Cal Week | Value |
+----+-------+----------+-------+
| 1 | 5 | 201708 | 4.5 |
| 1 | 5 | 201709 | 5 |
| 1 | 5 | 201710 | 6 |
| 2 | 88 | 201741 | 75 |
| 2 | 88 | 201742 | 89 |
| 2 | 88 | 201743 | 90 |
| 2 | 88 | 201744 | 51 |
+----+-------+----------+-------+
```
I would like to randomly sample a calendar week from each id-month group (the months are not calendar months). Then I would like to keep all id-month combination prior to the sample months.
An example output could be: suppose the sampling output returned cal week 201743 for the group id=2 and month=88 and 201709 for the group id=1 and month=5, then the final ouput should be
```
+----+-------+----------+-------+
| Id | Month | Cal Week | Value |
+----+-------+----------+-------+
| 1 | 5 | 201708 | 4.5 |
| 1 | 5 | 201709 | 5 |
| 2 | 88 | 201741 | 75 |
| 2 | 88 | 201742 | 89 |
2 | 88 | 201743 | 90 |
+----+-------+----------+-------+
```
I tried to work with dplyr's sample\_n function (which is going to give me the random calendar week by id-month group, but then I do not know how to get all calendar weeks prior to that date. Can you help me with this. If possible, I would like to work with dplyr.
Please let me know in case you need further information.
Many thanks<issue_comment>username_1: If you look at what is x < 3 you'll find it yields
```
[1] TRUE TRUE FALSE TRUE FALSE FALSE
```
so `x[x<3] <- x[x < 3] * 100` means multiply by 100 the first, second and fourth value of x (`x[x < 3]*100`) and replace the first, second and fourth value of x by these new values (`x[x<3] <-`).
Upvotes: 1 <issue_comment>username_2: It's not remembering the locations of the `x < 3` values. The left-hand side of your equation is explicitly the locations of the `x < 3` values.
So the thing on the right might be `(100, 100, 200)`, but the thing on the left is *the placeholders at places 1, 2 and 4*.
Upvotes: 1 <issue_comment>username_3: If you want to get the result of your call you need to assign it to a new variable:
```
x2 <- (x[x < 3] <- x[x<3] * 100)
x2
#[1] 100 100 200
```
Note that `x` will still be changed (as a result of your assignment `x[x < 3] <- x[x<3] * 100`).
If that is not desired, you can simply do:
```
x2 <- x[x<3]*100
x2
#[1] 100 100 200
x
#[1] 1 1 3 2 3 5
```
Upvotes: 3 [selected_answer]<issue_comment>username_4: In your code, you ask R to go to `x` and multiple each value less than `3` by `100` that is in this code `x[x < 3]*100`. R, in this case, looks for the place of your element. That is, the code goes to `x` values and takes them one by one. The one that obeys the condition is then multiplied by `100`. Then, the code returns you all the values of `x`. The correct way is to assign a name to your specific values as @username_3 answer.
In addition, it is a good idea to write a general function for your convenience. Here is a function.
```
myfun <- function(x, n){
res <- lapply(x, function(i) (if (i < n) {i *100}else{0}))
res
}
```
or simply use the comment of @username_3.
```
myfun <- function(x, n){
res <- x[x < n]*100
res
}
myfun(x, 3)
x <- list(1, 1, 3, 2, 3, 5)
n=3
```
Then,
```
> myfun(x, 3)
[[1]]
[1] 100
[[2]]
[1] 100
[[3]]
[1] 0
[[4]]
[1] 200
[[5]]
[1] 0
[[6]]
[1] 0
```
Upvotes: 1 |
2018/03/22 | 1,345 | 5,021 | <issue_start>username_0: When i want to get some records with joined data from the referenced tables, Sequelize adds the reference columns twice: the normal one and a copy of them, written just a little bit different.
This is my model:
```
module.exports = function(sequelize, DataTypes) {
return sequelize.define('result', {
id: {
type: DataTypes.INTEGER(10),
allowNull: false,
primaryKey: true,
autoIncrement: true
},
test_id: {
type: DataTypes.INTEGER(10),
allowNull: false,
references: {
model: 'test',
key: 'id'
}
},
item_id: {
type: DataTypes.INTEGER(10),
allowNull: false,
references: {
model: 'item',
key: 'id'
}
},
}, // and many other fields
{
tableName: 'result',
timestamps: false, // disable the automatic adding of createdAt and updatedAt columns
underscored:true
});
}
```
In my repository I have a method, which gets the result with joined data. And I defined the following associations:
```
const Result = connection.import('../../models/storage/result');
const Item = connection.import('../../models/storage/item');
const Test = connection.import('../../models/storage/test');
Result.belongsTo(Test, {foreignKey: 'test_id'});
Test.hasOne(Result);
Result.belongsTo(Item, {foreignKey: 'item_id'});
Item.hasOne(Result);
// Defining includes for JOIN querys
var include = [{
model: Item,
attributes: ['id', 'header_en']
}, {
model: Test,
attributes: ['label']
}];
var getResult = function(id) {
return new Promise((resolve, reject) => { // pass result
Result.findOne({
where: { id : id },
include: include,
// attributes: ['id',
// 'test_id',
// 'item_id',
// 'result',
// 'validation'
// ]
}).then(result => {
resolve(result);
});
});
}
```
The function produces the following query:
```
SELECT `result`.`id`, `result`.`test_id`, `result`.`item_id`, `result`.`result`, `result`.`validation`, `result`.`testId`, `result`.`itemId`, `item`.`id` AS `item.id`, `item`.`title` AS `item.title`, `test`.`id` AS `test.id`, `test`.`label` AS `test.label` FROM `result` AS `result` LEFT OUTER JOIN `item` AS `item` ON `result`.`item_id` = `item`.`id` LEFT OUTER JOIN `test` AS `test` ON `result`.`test_id` = `test`.`id` WHERE `result`.`id` = '1';
```
Notice the extra itemId, testId it wants to select from the result table. I don't know where this happens. This produces:
```
Unhandled rejection SequelizeDatabaseError: Unknown column 'result.testId' in 'field list'
```
It only works when i specify which attributes to select.
**EDIT:** my tables in the database already have references to other tables with item\_id and test\_id. Is it then unnecessary to add the associations again in the application code like I do?
A result always has one item and test it belongs to.
How can i solve this?
Thanks in advance,
Mike<issue_comment>username_1: Sequelize uses these column name by adding an id to the model name by default. If you want to stop it, there is an option that you need to specify.
`underscored: true`
You can specify this property on application level and on model level.
Also, you can turn off the timestamps as well. You need to use the timestamp option.
`timestamps: false`
Upvotes: 2 <issue_comment>username_2: **SOLUTION:**
```
Result.belongsTo(Test, {foreignKey: 'test_id'});
// Test.hasMany(Result);
Result.belongsTo(Item, {foreignKey: 'item_id'});
// Item.hasOne(Result);
```
Commenting out the hasOne, hasMany lines did solve the problem. I think I messed it up by defining the association twice. :|
Upvotes: 3 [selected_answer]<issue_comment>username_3: Although your solution fixes your immediate problem, it is ultimately not what you should be doing, as the cause of your problem is misunderstood there. For example, you MUST make that sort of association if making a Super Many-to-Many relationship (which was my problem that I was trying to solve when I found this thread). Fortunately, the [Sequelize documentation](https://sequelize.org/master/manual/advanced-many-to-many.html) addresses this under **Aliases and custom key names**.
Sequelize automatically aliases the foreign key unless you tell it specifically what to use, so `test_id` becomes `testId`, and `item_id` becomes `itemId` by default. Since those fields are not defined in your `Result` table, Sequelize assumes they exist when generating the insert set, and fails when the receiving table turns out not to have them! So your issue is less associating tables twice than it is that one association is assuming extra, non-existing fields.
I suspect a more complete solution for your issue would be the following:
**Solution**
```
Result.belongsTo(Test, {foreignKey: 'test_id'});
Test.hasMany(Result, {foreignKey: 'test_id'});
Result.belongsTo(Item, {foreignKey: 'item_id'});
Item.hasOne(Result, {foreignKey: 'item_id'});
```
A similar solution fixed my nearly identical problem with some M:N tables.
Upvotes: 1 |
2018/03/22 | 760 | 3,002 | <issue_start>username_0: I used selenium 2.53.1 and tried invoking browser but browser throws Windows authentication pop up. Once Windows authentication pop up comes driver.get() will throw exception in selenium 2.42 but the same scenario is not working in 2.53. Driver is not throwing any exception and stays idle for long time in 2.53
Browser used firefox.
Eg: url
driver. Get("<https://www.engprod-character.net/>");
Windows Authentication pop up window occur expection requires user credentials.
In selenium 2.42 : as driver is unable to invoke browser it throws exception, so that i catch that exception and handle the authentication pop up by using robot fw code.
Browser : firefox 29
In selenium 2.53: driver is not throwing any exception. So i couldn't able to handle it.
Browser : Firefox 46
Why selenium 2.53 is not throwing exception. Do we have any alternate other than using autoIT.<issue_comment>username_1: Sequelize uses these column name by adding an id to the model name by default. If you want to stop it, there is an option that you need to specify.
`underscored: true`
You can specify this property on application level and on model level.
Also, you can turn off the timestamps as well. You need to use the timestamp option.
`timestamps: false`
Upvotes: 2 <issue_comment>username_2: **SOLUTION:**
```
Result.belongsTo(Test, {foreignKey: 'test_id'});
// Test.hasMany(Result);
Result.belongsTo(Item, {foreignKey: 'item_id'});
// Item.hasOne(Result);
```
Commenting out the hasOne, hasMany lines did solve the problem. I think I messed it up by defining the association twice. :|
Upvotes: 3 [selected_answer]<issue_comment>username_3: Although your solution fixes your immediate problem, it is ultimately not what you should be doing, as the cause of your problem is misunderstood there. For example, you MUST make that sort of association if making a Super Many-to-Many relationship (which was my problem that I was trying to solve when I found this thread). Fortunately, the [Sequelize documentation](https://sequelize.org/master/manual/advanced-many-to-many.html) addresses this under **Aliases and custom key names**.
Sequelize automatically aliases the foreign key unless you tell it specifically what to use, so `test_id` becomes `testId`, and `item_id` becomes `itemId` by default. Since those fields are not defined in your `Result` table, Sequelize assumes they exist when generating the insert set, and fails when the receiving table turns out not to have them! So your issue is less associating tables twice than it is that one association is assuming extra, non-existing fields.
I suspect a more complete solution for your issue would be the following:
**Solution**
```
Result.belongsTo(Test, {foreignKey: 'test_id'});
Test.hasMany(Result, {foreignKey: 'test_id'});
Result.belongsTo(Item, {foreignKey: 'item_id'});
Item.hasOne(Result, {foreignKey: 'item_id'});
```
A similar solution fixed my nearly identical problem with some M:N tables.
Upvotes: 1 |
2018/03/22 | 722 | 2,837 | <issue_start>username_0: *I am new user to ruby on rails. I have some question please give the answer as early as possible*
**What is the Best way to Create a Database For Your Projects in Rails?**
>
> 1.Scaffold generator
>
>
> 2.Manually Design Database
>
>
><issue_comment>username_1: After installing the Rails then create a project using `rails new project_name` then `cd project_name` then run `rake db:create` it will create a database.
You can modify `database` name like by default rails uses a database e.g `name_development` or `name_production` you can modify this on go to `project/config/database.yml`.
The `rails new project_name` command creates default database adapter e.g `sqlite3` you can define this which adapter he use by default while rails project create.
The `sqlite` is a development database you should change database adapter while going to production like `postgresql` or `mysql` or `mongodb`...
If you need to use `mysql` by default then run below command
```
rails new project_name -d mysql
```
If you need to use `postgresql` by default then run below command
```
rails new project_name -d postgres
```
It will create a database adapter by default which you need.
***Note:*** You can use both for a command like `rake new project_name` or `rails new project_name`
You need to the read the [`Rails Guides`](http://guides.rubyonrails.org/getting_started.html) carefully for understand basic Rails. This tutorial assumes you have basic Rails knowledge.
Also here are the [`Rails Commands`](http://guides.rubyonrails.org/command_line.html)
>
> Ruby on rails Database setup using scaffold generator or Manually
>
>
>
The scaffold works after create a database.
You can see the [active record basics](http://guides.rubyonrails.org/active_record_basics.html) and for basic association you can see the [Michael Hartley tutorial](https://www.railstutorial.org/book/user_microposts) this is good tutorial for new RoR programmer.
After all you need to design manually using `reference` or defining by `index` foreign key
Upvotes: 1 <issue_comment>username_2: First of all decide what kind of database are you going to use. (Msql2 or Postgres are mostly used)
Then design the schema on a paper or anywhere else.
And whenever you're sure. Now everything comes down to 2 different things.
1. You want things to be created automatically. for example: Views, CRUD for database operations in controllers.
2. You want to control things on your own. Now create model from rails commands, write associations, and begin writing your code and define routes as well.
NOTE: Point 2 is implemented when you're going to create a custom application and you may need operations other than basic crud.
Now, you can tell us. What actually you want to achieve and people will help you.
Upvotes: 0 |
2018/03/22 | 1,216 | 4,803 | <issue_start>username_0: I'm working on a project at the moment which requires me to set up a distributed network simulator, I had it working with taking output from a file and parsing through each line with a buffered reader as you can see below but I want to now use a predefined array and make my bufferedReader take input from that instead I've looked up a few solutions online to help me put this array into the buffered Reader but non seem to have worked.
I'm getting no errors when running and terminating the code but just seems to be stuck in an endless loop at some point and I presume it's the new buffered reader segment using the array instead. The idea behind this was to make the process simpler than re-writing many segments to fit around the array parsing and instead find a simpler way by having the array in the buffered Reader but as this is proving difficult I may have to resort to changing. I have tested if the array is being initialised correctly and that's not the problem so it's one less thing to take into consideration.
```
**Previous code:**
private void parseFile(String fileName) throws IOException {
System.out.println("Parsing Array");
Path path = Paths.get(fileName);
try (BufferedReader br = Files.newBufferedReader(path)) {
String line = null;
line = br.readLine(); // Skip first line
while ((line = br.readLine()) != null) {
parseLine(line);
}
} catch (IOException x) {
System.err.format("IOException: %s%n", x);
}
}
```
The recommendation online was to use an input stream with the buffered reader for it but that didn't seem to work at all as it over wrote the array, any recommendations on what I can use for the buffered reader segment would be grand.
The Array method above is just a void creating the array which is called before the method so the array should be initialised I presume, If anyone can look over and potentially let me know where I'm going wrong and problems that would be amazing if not I appreciate your time to read this anyway, Thanks for your time.
```
New Code Attempt:
//Creating array to parse.
private void createArray(){
myStringArray[0] = "Node_id Neighbours";
myStringArray[1] = "1 2 10";
myStringArray[2] = "2 3 1";
myStringArray[3] = "3 4 2";
myStringArray[4] = "4 5 3";
myStringArray[5] = "5 6 4";
myStringArray[6] = "6 7 5";
myStringArray[7] = "7 8 6";
myStringArray[8] = "8 9 7";
myStringArray[9] = "9 10 8";
myStringArray[10] = "10 1 9";
myStringArray[11] = "ELECT 1 2 3 4 5 6 7 8 9";
}
private void parseArray() throws IOException {
//InputStreamReader isr = new InputStreamReader(System.in);
System.out.println("Parsing Array");
// try (BufferedReader br = Files.newBufferedReader(path))
try (BufferedReader br = new BufferedReader(isr)) {
for(int i=0;i<12;i++)
{
String line = null;
line = br.readLine(); // Skip first line
while ((myStringArray[i] = br.readLine()) != null) {
parseLine(line);
}
}
} catch (IOException x) {
System.err.format("IOException: %s%n", x);
}
}
```
Answer: You cannot do this with buffered reader. I fixed it like this if this is any use to anyone. Thanks a lot to @L.Spillner for the explanation and answer.
code fix:
```
private void parseArray() throws IOException {
System.out.println("Parsing Array");
for(int i=1;i<12;i++) //First row ignored.
{
String line = null;
line = myStringArray[i];
//Begin parsing process of each entity.
parseLine(line);
}
}
```<issue_comment>username_1: Answer is you can't. Thanks for the feedback though guys and got it working through just looping through the array and assigning each item to line.
Upvotes: 0 <issue_comment>username_2: Let's kick it off with a precise answer to the Question.
**You cannot put anything into a `BufferedReader` directly.** Especially when it's some kind of data structure like an array.
The `BufferedReader`'s purpose is to handle I/O Operations, input operations to be more precise. According to the [javadoc](https://docs.oracle.com/javase/8/docs/api/java/io/Reader.html) the `BufferedReader` takes a `Reader` as an argument. `Reader` is an abstract class which contains 'tools' to handle character `InputStreams`.
The way the `BufferedReader`'s `readLine()` method works is: Any character arriving on the `InputStream` gets stored in a buffer until a `\n` (new line/linefeed) or `\r` (carriage retun) arrives. When one of these two special characters show up the buffer gets interpreted as a String and is returned to the call.
Upvotes: 1 |
2018/03/22 | 1,493 | 5,256 | <issue_start>username_0: I'm trying to create a program having the following steps:
1) Get all xml files from a user given path
2) Open each of the files (if any) and search for nodes where it is in the format `...`
3) Get the value of the nodes and search the exact value in the [database xml](https://codeshare.io/21bMmz) inside the nodes
4) If found, get the attribute value of its parent node minus the string **<http://dx.doi.org/>**
5) Add a node in the xml file after the node with the value like `...VALUE of the rdf:about attribute`
Here is a sample [input file](https://codeshare.io/5v0mjm) and the [desired output](https://codeshare.io/5XldEo) for that file.
What I have tried:
```
string pathToUpdatedFile = @"D:\test\Jobs";
var files=Directory.GetFiles(pathToUpdatedFile,"*.xml");
foreach (var file in files)
{
var fundingDoc = XDocument.Load(@"D:\test\database.xml");
XNamespace rdf=XNamespace.Get("http://www.w3.org/1999/02/22-rdf-syntax-ns#");
XNamespace skosxl = XNamespace.Get("http://www.w3.org/2008/05/skos-xl#");
XNamespace skos=XNamespace.Get("http://www.w3.org/2004/02/skos/core#");
var targetAtt = fundingDoc.Descendants(skos+"Concept").Elements(skosxl+"prefLabel")
.ToLookup(s => (string)s.Element(skosxl+"literalForm"), s => (string)s.Parent.Attribute(rdf+"about"));
XDocument outDoc = XDocument.Parse(File.ReadAllText(file),LoadOptions.PreserveWhitespace);
foreach (var f in outDoc.Descendants("funding-source").Elements("institution-wrap"))
{
if (f.Element("institution-id") == null)
{
var name = (string)f.Element("institution");
var x = targetAtt[name].FirstOrDefault(); // just take the first one
if (x != null)
f.Add(new XElement("institution-id", new XAttribute("institution-id-type","fundref"),x.Substring(@"http://dx.doi.org/".Length)));
}
outDoc.Save(file);
}
Console.ReadLine();
```
But it is not working...Can somebody help...<issue_comment>username_1: See code below :
```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.Data;
using System.Data.OleDb;
namespace ConsoleApplication31
{
class Program
{
const string FILENAME = @"c:\temp\test.xml";
const string DATABASE = @"c:\temp\test1.xml";
static void Main(string[] args)
{
XDocument doc = XDocument.Load(FILENAME);
XElement article = doc.Root;
XNamespace ns = article.GetDefaultNamespace();
XDocument docDatabase = XDocument.Load(DATABASE);
XElement rdf = docDatabase.Root;
XNamespace nsSkosxl = rdf.GetNamespaceOfPrefix("skosxl");
XNamespace nsRdf = rdf.GetNamespaceOfPrefix("rdf");
List prefLabels = rdf.Descendants(nsSkosxl + "prefLabel").ToList();
Dictionary> dictLabels = prefLabels.GroupBy(x => (string)x.Descendants(nsSkosxl + "literalForm").FirstOrDefault(), y => (string)y.Element(nsSkosxl + "Label").Attribute(nsRdf + "about"))
.ToDictionary(x => x.Key, y => y.ToList());
List fundingSources = article.Descendants(ns + "funding-source").ToList();
foreach (XElement fundingSource in fundingSources)
{
XElement institutionWrap = fundingSource.Element(ns + "institution-wrap");
string institution = (string)fundingSource;
if (dictLabels.ContainsKey(institution))
{
institutionWrap.Add(new XElement("institution-id", new object[] {
new XAttribute("institution-id-type","fundref"),
dictLabels[institution]
}));
}
else
{
Console.WriteLine("Dictionary doesn't contain : '{0}'", institution);
}
}
Console.ReadLine();
}
}
}
```
Upvotes: 1 <issue_comment>username_2: I think this is what you are looking for (MODIFIED username_1's CODE A LITTLE)
```
const string FILENAME = @"c:\temp\test.xml";
const string DATABASE = @"c:\temp\test1.xml";
public static void Main(string[] args)
{
XDocument doc = XDocument.Load(FILENAME);
XElement article = doc.Root;
XNamespace ns = article.GetDefaultNamespace();
XDocument docDatabase = XDocument.Load(DATABASE);
XElement rdf = docDatabase.Root;
XNamespace nsSkosxl = rdf.GetNamespaceOfPrefix("skosxl");
XNamespace nsSkos = rdf.GetNamespaceOfPrefix("skos");
XNamespace nsRdf = rdf.GetNamespaceOfPrefix("rdf");
List prefLabels = rdf.Descendants(nsSkos + "Concept").ToList();
Dictionary> dictLabels = prefLabels.GroupBy(x => (string)x.Descendants(nsSkosxl + "literalForm").FirstOrDefault(), y => (string)y.Parent.Element(nsSkos+"Concept").Attribute(nsRdf + "about").Value.Substring(18))
.ToDictionary(x => x.Key, y => y.ToList());
List fundingSources = article.Descendants(ns + "funding-source").ToList();
foreach (XElement fundingSource in fundingSources)
{
XElement institutionWrap = fundingSource.Element(ns + "institution-wrap");
string institution = (string)fundingSource;
if (dictLabels.ContainsKey(institution))
{
institutionWrap.Add(new XElement("institution-id", new object[] {
new XAttribute("institution-id-type","fundref"),
dictLabels[institution]
}));
}
}
doc.Save(FILENAME);
Console.WriteLine("Done");
Console.ReadLine();
}
```
Upvotes: 0 |
2018/03/22 | 1,385 | 4,588 | <issue_start>username_0: I have the following pandas dataframe:
```
DB Table Column Format
Retail Orders ID INTEGER
Retail Orders Place STRING
Dept Sales ID INTEGER
Dept Sales Name STRING
```
I want to loop on the Tables, while generating a SQL for creating the tables. e.g.
```
create table Retail.Orders ( ID INTEGER, Place STRING)
create table Dept.Sales ( ID INTEGER, Name STRING)
```
What I've already done is get distinct db & tables using `drop_duplicate` and then for each table apply a filter and concatenate the strings to create a sql.
```
def generate_tables(df_cols):
tables = df_cols.drop_duplicates(subset=[KEY_DB, KEY_TABLE])[[KEY_DB, KEY_TABLE]]
for index, row in tables.iterrows():
db = row[KEY_DB]
table = row[KEY_TABLE]
print("DB: " + db)
print("Table: " + table)
sql = "CREATE TABLE " + db + "." + table + " ("
cols = df_cols.loc[(df_cols[KEY_DB] == db) & (df_cols[KEY_TABLE] == table)]
for index, col in cols.iterrows():
sql += col[KEY_COLUMN] + " " + col[KEY_FORMAT] + ", "
sql += ")"
print(sql)
```
Is there a better approach to iterate over the dataframe?<issue_comment>username_1: If looping is what you want, then yes .iterrows() is the most efficient way to get through a pandas frame. EDIT: From other answer, and link here - [Does iterrows have performance issues?](https://stackoverflow.com/questions/24870953/does-iterrows-have-performance-issues) - I believe that .itertuples() is actually a better generator for performance.
However, depending on the size of the dataframe you might be better off using some pandas groupby functions to assist
consider something like this
```
# Add a concatenation of the column name and format
df['col_format'] = df['Column'] + ' ' + df['Format']
# Now create a frame which is the groupby of the DB/Table rows and
# concatenates the tuples of col_format correctly
y1 = (df.groupby(by=['DB', 'Table'])['col_format']
.apply(lambda x: '(' + ', '.join(x) + ')'))
# Reset the index to bring the keys/indexes back in as columns
y2 = y1.reset_index()
# Now create a Series of all of the SQL statements
all_outs = 'Create Table ' + y2['DB'] + '.' + y2['Table'] + ' ' + y2['col_format']
# Look at them!
all_outs.values
Out[44]:
array(['Create Table Dept.Sales (ID INTEGER, Name STRING)',
'Create Table Retail.Orders (ID INTEGER, Place STRING)'], dtype=object)
```
Hope this helps!
Upvotes: 1 <issue_comment>username_2: This is the way I would do it. First create a dictionary via `df.itertuples` [more efficient than `df.iterrows`], then use `str.format` to include the values seamlessly.
Uniqueness is guaranteed in dictionary construction by using `set`.
I also convert to a generator so you can iterate it efficiently if you wish; it's always possible to exhaust the generator via `list` as below.
```
from collections import defaultdict
d = defaultdict(set)
for row in df.itertuples():
d[(row[1], row[2])].add((row[3], row[4]))
def generate_tables_jp(d):
for k, v in d.items():
yield 'CREATE TABLE {0}.{1} ({2})'\
.format(k[0], k[1], ', '.join([' '.join(i) for i in v]))
list(generate_tables_jp(d))
```
Result:
```
['CREATE TABLE Retail.Orders (ID INTEGER, Place STRING)',
'CREATE TABLE Dept.Sales (ID INTEGER, Name STRING)']
```
Upvotes: 2 <issue_comment>username_3: You can use first assemble the info per line in an extra column, and then use `groupby.sum`
```
queries = df[KEY_COLUMN] + ' ' + df[KEY_FORMAT] + ', '
queries.index = df.set_index(index_labels).index
```
>
>
> ```
> DB Table
> Retail Orders ID INTEGER,
> Orders Place STRING,
> Dept Sales ID INTEGER,
> Sales Name STRING,
> dtype: object
>
> ```
>
>
```
queries = queries.groupby(index_labels).sum().str.strip(', ')
```
>
>
> ```
> DB Table
> Dept Sales ID INTEGER, Name STRING
> Retail Orders ID INTEGER, Place STRING
> dtype: object
>
> ```
>
>
```
def format_queries(queries):
query_pattern = 'CREATE TABLE %s.%s (%s)'
for (db, table), text in queries.items():# idx, table, text
query = query_pattern % (db, table, text)
yield query
list(format_queries(queries))
```
>
>
> ```
> ['CREATE TABLE Dept.Sales (ID INTEGER, Name STRING)',
> 'CREATE TABLE Retail.Orders (ID INTEGER, Place STRING)']
>
> ```
>
>
This way you don't need the `lambda`. I don't know whether this approach or the `itertuples` will be fastest
Upvotes: 0 |
2018/03/22 | 9,516 | 34,265 | <issue_start>username_0: I have a input like
```
string input = "14 + 2 * 32 / 60 + 43 - 7 + 3 - 1 + 0 * 7 + 87 - 32 / 34";
// up to 10MB string size
int result = Calc(input); // 11
```
* the calculation is from left to right, number by number
* the numbers are 0 to 99
* multiplication before addition is ignored so `14 + 2 * 32` is `512`
* the possible calculations are `+-*/`
* division by `0` is not possible so after a `/` can't be a `0`
My Approach
```
public static int Calc(string sInput)
{
int iCurrent = sInput.IndexOf(' ');
int iResult = int.Parse(sInput.Substring(0, iCurrent));
int iNext = 0;
while ((iNext = sInput.IndexOf(' ', iCurrent + 4)) != -1)
{
iResult = Operate(iResult, sInput[iCurrent + 1], int.Parse(sInput.Substring((iCurrent + 3), iNext - (iCurrent + 2))));
iCurrent = iNext;
}
return Operate(iResult, sInput[iCurrent + 1], int.Parse(sInput.Substring((iCurrent + 3))));
}
public static int Operate(int iReturn, char cOperator, int iOperant)
{
switch (cOperator)
{
case '+':
return (iReturn + iOperant);
case '-':
return (iReturn - iOperant);
case '*':
return (iReturn * iOperant);
case '/':
return (iReturn / iOperant);
default:
throw new Exception("Error");
}
}
```
I need the **fastest** way to get a result.
**Question:** is there a way to make this calculation faster? I have multiple threads but I use only one.
**Update:**
Test-Case: (I've removed the division by 0 bug and removed the `StringBuilder.ToString()` from the `StopWatch` measurement)
```
Random rand = new Random();
System.Text.StringBuilder input = new System.Text.StringBuilder();
string operators = "+-*/";
input.Append(rand.Next(0, 100));
for (int i = 0; i < 1000000; i++)
{
int number = rand.Next(0, 100);
char coperator = operators[rand.Next(0, number > 0 ? 4 : 3)];
input.Append(" " + coperator + " " + number);
}
string calc = input.ToString();
System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();
watch.Start();
int result = Calc(calc);
watch.Stop();
```<issue_comment>username_1: NOTE
====
Per comments, this answer does not give a performant solution.
I'll leave it here as there are points to be considered / which may be of interest to others finding this thread in future; but as people have said below, this is far from the most performant solution.
---
Original Answer
---------------
The .net framework already supplies a way to handle formulas given as strings:
```
var formula = "14 + 2 * 32 / 60 + 43 - 7 + 3 - 1 + 0 * 7 + 87 - 32 / 34";
var result = new DataTable().Compute(formula, null);
Console.WriteLine(result); //returns 139.125490196078
```
---
Initial feedback based on comments
----------------------------------
Per the comments thread I need to point out some things:
### Does this work the way I've described?
No; this follows the normal rules of maths.
I assume that your amended rules are to simplify writing code to handle them, rather than because you want to support a new branch of mathematics? If that's the case, I'd argue against that. People will expect things to behave in a certain way; so you'd have to ensure that anyone sending equations to your code was primed with the knowledge to expect the rules of this new-maths rather than being able to use their existing expectations.
There isn't an option to change the rules here; so if your requirement is to change the rules of maths, this won't work for you.
### Is this the Fastest Solution
No. However it should perform well given MS spend a lot of time optimising their code, and so will likely perform faster than any hand-rolled code to do the same (though admittedly this code does a lot more than just support the four main operators; so it's not doing exactly the same).
Per MatthewWatson's specific comment (i.e. calling the DataTable constructor incurs a significant overhead) you'd want to create and then re-use one instance of this object. Depending on what your solution looks like there are various ways to do that; here's one:
```
interface ICalculator //if we use an interface we can easily switch from datatable to some other calulator; useful for testing, or if we wanted to compare different calculators without much recoding
{
T Calculate(string expression) where T: struct;
}
class DataTableCalculator: ICalculator
{
readonly DataTable dataTable = new DataTable();
public DataTableCalculator(){}
public T Calculate(string expression) where T: struct =>
(T)dataTable.Compute(expression, null);
}
class Calculator: ICalculator
{
static ICalculator internalInstance;
public Calculator(){}
public void InitialiseCalculator (ICalculator calculator)
{
if (internalInstance != null)
{
throw new InvalidOperationException("Calculator has already been initialised");
}
internalInstance = calculator;
}
public T Calculate(string expression) where T: struct =>
internalInstance.Calculate(expression);
}
//then we use it on our code
void Main()
{
var calculator1 = new Calculator();
calculator1.InitialiseCalculator(new DataTableCalculator());
var equation = "14 + 2 \* 32 / 60 + 43 - 7 + 3 - 1 + 0 \* 7 + 87 - 32 / 34";
Console.WriteLine(calculator1.Calculate(equation)); //139.125490196078
equation = "1 + 2 - 3 + 4";
Console.WriteLine(calculator1.Calculate(equation)); //4
calculator1 = null;
System.GC.Collect(); //in reality we'd pretty much never do this, but just to illustrate that our static variable continues fro the life of the app domain rather than the life of the instance
var calculator2 = new Calculator();
//calculator2.InitialiseCalculator(new DataTableCalculator()); //uncomment this and you'll get an error; i.e. the calulator should only be initialised once.
equation = "1 + 2 - 3 + 4 / 5 \* 6 - 7 / 8 + 9";
Console.WriteLine(calculator2.Calculate(equation)); //12.925
}
```
NB: The above solution uses a static variable; some people are against use of statics. For this scenario (i.e. where during the lifetime of the application you're only going to require one way of doing calculations) this is a legitimate use case. If you wanted to support switching the calculator at runtime a different approach would be required.
---
Update after Testing & Comparing
--------------------------------
Having run some performance tests:
* The `DataTable.Compute` method's biggest problem is that for equations the size of which you're dealing with it throws a `StackOverflowException`; (i.e. based on your equation generator's loop `for (int i = 0; i < 1000000; i++)`.
* For a single operation with a smaller equation (`i < 1000`), the compute method (including constructor and `Convert.ToInt32` on the `double` result) takes almost 100 times longer.
* for the single operation I also encountered overflow exceptions more often; i.e. because the result of the operations had pushed the value outside the bounds of supported data types...
* Even if we move the constructor/initialise call outside of the timed area and remove the conversion to int (and run for thousands of iterations to get an average), your solution comes in 3.5 times faster than mine.
Link to the docs: <https://msdn.microsoft.com/en-us/library/system.data.datatable.compute%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396>
Upvotes: 3 <issue_comment>username_2: Edit edit: updated with latest versions by The General and Mirai Mann:
If you want to know which horse is fastest: race the horses. Here are `BenchmarkDotNet` results comparing various answers from this question (I **have not** merged their code into my full example, because that feels wrong - only the numbers are presented) with repeatable but large random input, via:
```
static MyTests()
{
Random rand = new Random(12345);
StringBuilder input = new StringBuilder();
string operators = "+-*/";
var lastOperator = '+';
for (int i = 0; i < 1000000; i++)
{
var @operator = operators[rand.Next(0, 4)];
input.Append(rand.Next(lastOperator == '/' ? 1 : 0, 100) + " " + @operator + " ");
lastOperator = @operator;
}
input.Append(rand.Next(0, 100));
expression = input.ToString();
}
private static readonly string expression;
```
with sanity checks (to check they all do the right thing):
```
Original: -1426
NoSubStrings: -1426
NoSubStringsUnsafe: -1426
username_44: -1426
MiraiMann1: -1426
```
we get timings (note: `Original` is OP's version in the question; `NoSubStrings[Unsafe]` is my versions from below, and two other versions from other answers by user-name):
(lower "Mean" is better)
(note; there is a **newer** version of Mirai Mann's implementation, but I no longer have things setup to run a new test; but: fair to assume it should be better!)
Runtime: .NET Framework 4.7 (CLR 4.0.30319.42000), 32bit LegacyJIT-v4.7.2633.0
```
Method | Mean | Error | StdDev |
------------------- |----------:|----------:|----------:|
Original | 104.11 ms | 1.4920 ms | 1.3226 ms |
NoSubStrings | 21.99 ms | 0.4335 ms | 0.7122 ms |
NoSubStringsUnsafe | 20.53 ms | 0.4103 ms | 0.6967 ms |
username_44 | 15.50 ms | 0.3020 ms | 0.5369 ms |
MiraiMann1 | 15.54 ms | 0.3096 ms | 0.4133 ms |
```
Runtime: .NET Framework 4.7 (CLR 4.0.30319.42000), 64bit RyuJIT-v4.7.2633.0
```
Method | Mean | Error | StdDev | Median |
------------------- |----------:|----------:|----------:|----------:|
Original | 114.15 ms | 1.3142 ms | 1.0974 ms | 114.13 ms |
NoSubStrings | 21.33 ms | 0.4161 ms | 0.6354 ms | 20.93 ms |
NoSubStringsUnsafe | 19.24 ms | 0.3832 ms | 0.5245 ms | 19.43 ms |
username_44 | 13.97 ms | 0.2795 ms | 0.2745 ms | 13.86 ms |
MiraiMann1 | 15.60 ms | 0.3090 ms | 0.4125 ms | 15.53 ms |
```
Runtime: .NET Core 2.1.0-preview1-26116-04 (CoreCLR 4.6.26116.03, CoreFX 4.6.26116.01), 64bit RyuJIT
```
Method | Mean | Error | StdDev | Median |
------------------- |----------:|----------:|----------:|----------:|
Original | 101.51 ms | 1.7807 ms | 1.5786 ms | 101.44 ms |
NoSubStrings | 21.36 ms | 0.4281 ms | 0.5414 ms | 21.07 ms |
NoSubStringsUnsafe | 19.85 ms | 0.4172 ms | 0.6737 ms | 19.80 ms |
username_44 | 14.06 ms | 0.2788 ms | 0.3723 ms | 13.82 ms |
MiraiMann1 | 15.88 ms | 0.3153 ms | 0.5922 ms | 15.45 ms |
```
---
Original answer from before I added `BenchmarkDotNet`:
------------------------------------------------------
If I was trying this, I'd be **tempted** to have a look at the `Span` work in 2.1 previews - the point being that a `Span` can be sliced without allocating (and a `string` can be converted to a `Span` without allocating); this would allow the string carving and parsing to be performed without any allocations. However, reducing allocations is *not always* quite the same thing as raw performance (although they are related), so to know if it was faster: you'd need to race your horses (i.e. compare them).
If `Span` isn't an option: you can still do the same thing by tracking an `int offset` manually and just \*never using `SubString`)
In either case (`string` or `Span`): if your operation only needs to cope with a certain subset of representations of integers, I might be tempted to hand role a custom `int.Parse` equivalent that doesn't apply as many rules (cultures, alternative layouts, etc), and which works without needing a `Substring` - for example it could take a `string` and `ref int offset`, where the `offset` is updated to be *where the parse stopped* (either because it hit an operator or a space), and which worked.
Something like:
```
static class P
{
static void Main()
{
string input = "14 + 2 * 32 / 60 + 43 - 7 + 3 - 1 + 0 * 7 + 87 - 32 / 34";
var val = Evaluate(input);
System.Console.WriteLine(val);
}
static int Evaluate(string expression)
{
int offset = 0;
SkipSpaces(expression, ref offset);
int value = ReadInt32(expression, ref offset);
while(ReadNext(expression, ref offset, out char @operator, out int operand))
{
switch(@operator)
{
case '+': value = value + operand; break;
case '-': value = value - operand; break;
case '*': value = value * operand; break;
case '/': value = value / operand; break;
}
}
return value;
}
static bool ReadNext(string value, ref int offset,
out char @operator, out int operand)
{
SkipSpaces(value, ref offset);
if(offset >= value.Length)
{
@operator = (char)0;
operand = 0;
return false;
}
@operator = value[offset++];
SkipSpaces(value, ref offset);
if (offset >= value.Length)
{
operand = 0;
return false;
}
operand = ReadInt32(value, ref offset);
return true;
}
static void SkipSpaces(string value, ref int offset)
{
while (offset < value.Length && value[offset] == ' ') offset++;
}
static int ReadInt32(string value, ref int offset)
{
bool isNeg = false;
char c = value[offset++];
int i = (c - '0');
if(c == '-')
{
isNeg = true;
i = 0;
// todo: what to do here if `-` is not followed by [0-9]?
}
while (offset < value.Length && (c = value[offset++]) >= '0' && c <= '9')
i = (i * 10) + (c - '0');
return isNeg ? -i : i;
}
}
```
Next, I might consider whether it is worthwhile switching to `unsafe` to remove the double length checks. So I'd implement it *both ways*, and test it with something like BenchmarkDotNet to see whether it is worth it.
---
Edit: here is is with `unsafe` added and BenchmarkDotNet usage:
```
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Running;
using System;
static class P
{
static void Main()
{
var summary = BenchmarkRunner.Run();
System.Console.WriteLine(summary);
}
}
public class MyTests
{
const string expression = "14 + 2 \* 32 / 60 + 43 - 7 + 3 - 1 + 0 \* 7 + 87 - 32 / 34";
[Benchmark]
public int Original() => EvalOriginal.Calc(expression);
[Benchmark]
public int NoSubStrings() => EvalNoSubStrings.Evaluate(expression);
[Benchmark]
public int NoSubStringsUnsafe() => EvalNoSubStringsUnsafe.Evaluate(expression);
}
static class EvalOriginal
{
public static int Calc(string sInput)
{
int iCurrent = sInput.IndexOf(' ');
int iResult = int.Parse(sInput.Substring(0, iCurrent));
int iNext = 0;
while ((iNext = sInput.IndexOf(' ', iCurrent + 4)) != -1)
{
iResult = Operate(iResult, sInput[iCurrent + 1], int.Parse(sInput.Substring((iCurrent + 3), iNext - (iCurrent + 2))));
iCurrent = iNext;
}
return Operate(iResult, sInput[iCurrent + 1], int.Parse(sInput.Substring((iCurrent + 3))));
}
public static int Operate(int iReturn, char cOperator, int iOperant)
{
switch (cOperator)
{
case '+':
return (iReturn + iOperant);
case '-':
return (iReturn - iOperant);
case '\*':
return (iReturn \* iOperant);
case '/':
return (iReturn / iOperant);
default:
throw new Exception("Error");
}
}
}
static class EvalNoSubStrings {
public static int Evaluate(string expression)
{
int offset = 0;
SkipSpaces(expression, ref offset);
int value = ReadInt32(expression, ref offset);
while (ReadNext(expression, ref offset, out char @operator, out int operand))
{
switch (@operator)
{
case '+': value = value + operand; break;
case '-': value = value - operand; break;
case '\*': value = value \* operand; break;
case '/': value = value / operand; break;
default: throw new Exception("Error");
}
}
return value;
}
static bool ReadNext(string value, ref int offset,
out char @operator, out int operand)
{
SkipSpaces(value, ref offset);
if (offset >= value.Length)
{
@operator = (char)0;
operand = 0;
return false;
}
@operator = value[offset++];
SkipSpaces(value, ref offset);
if (offset >= value.Length)
{
operand = 0;
return false;
}
operand = ReadInt32(value, ref offset);
return true;
}
static void SkipSpaces(string value, ref int offset)
{
while (offset < value.Length && value[offset] == ' ') offset++;
}
static int ReadInt32(string value, ref int offset)
{
bool isNeg = false;
char c = value[offset++];
int i = (c - '0');
if (c == '-')
{
isNeg = true;
i = 0;
}
while (offset < value.Length && (c = value[offset++]) >= '0' && c <= '9')
i = (i \* 10) + (c - '0');
return isNeg ? -i : i;
}
}
static unsafe class EvalNoSubStringsUnsafe
{
public static int Evaluate(string expression)
{
fixed (char\* ptr = expression)
{
int len = expression.Length;
var c = ptr;
SkipSpaces(ref c, ref len);
int value = ReadInt32(ref c, ref len);
while (len > 0 && ReadNext(ref c, ref len, out char @operator, out int operand))
{
switch (@operator)
{
case '+': value = value + operand; break;
case '-': value = value - operand; break;
case '\*': value = value \* operand; break;
case '/': value = value / operand; break;
default: throw new Exception("Error");
}
}
return value;
}
}
static bool ReadNext(ref char\* c, ref int len,
out char @operator, out int operand)
{
SkipSpaces(ref c, ref len);
if (len-- == 0)
{
@operator = (char)0;
operand = 0;
return false;
}
@operator = \*c++;
SkipSpaces(ref c, ref len);
if (len == 0)
{
operand = 0;
return false;
}
operand = ReadInt32(ref c, ref len);
return true;
}
static void SkipSpaces(ref char\* c, ref int len)
{
while (len != 0 && \*c == ' ') { c++;len--; }
}
static int ReadInt32(ref char\* c, ref int len)
{
bool isNeg = false;
char ch = \*c++;
len--;
int i = (ch - '0');
if (ch == '-')
{
isNeg = true;
i = 0;
}
while (len-- != 0 && (ch = \*c++) >= '0' && ch <= '9')
i = (i \* 10) + (ch - '0');
return isNeg ? -i : i;
}
}
```
Upvotes: 4 <issue_comment>username_3: The following solution is a finite automaton. Calc(input) = O(n). For better performance, this solution does not use `IndexOf`, `Substring`, `Parse`, string concatenation, or repeated reading of value (fetching `input[i]` more than once)... just a character processor.
```
static int Calculate1(string input)
{
int acc = 0;
char last = ' ', operation = '+';
for (int i = 0; i < input.Length; i++)
{
var current = input[i];
switch (current)
{
case ' ':
if (last != ' ')
{
switch (operation)
{
case '+': acc += last - '0'; break;
case '-': acc -= last - '0'; break;
case '*': acc *= last - '0'; break;
case '/': acc /= last - '0'; break;
}
last = ' ';
}
break;
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
if (last == ' ') last = current;
else
{
var num = (last - '0') * 10 + (current - '0');
switch (operation)
{
case '+': acc += num; break;
case '-': acc -= num; break;
case '*': acc *= num; break;
case '/': acc /= num; break;
}
last = ' ';
}
break;
case '+': case '-': case '*': case '/':
operation = current;
break;
}
}
if (last != ' ')
switch (operation)
{
case '+': acc += last - '0'; break;
case '-': acc -= last - '0'; break;
case '*': acc *= last - '0'; break;
case '/': acc /= last - '0'; break;
}
return acc;
}
```
---
And another implementation. It reads 25% less from the input. I expect that it has 25% better performance.
```
static int Calculate2(string input)
{
int acc = 0, i = 0;
char last = ' ', operation = '+';
while (i < input.Length)
{
var current = input[i];
switch (current)
{
case ' ':
if (last != ' ')
{
switch (operation)
{
case '+': acc += last - '0'; break;
case '-': acc -= last - '0'; break;
case '*': acc *= last - '0'; break;
case '/': acc /= last - '0'; break;
}
last = ' ';
i++;
}
break;
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
if (last == ' ')
{
last = current;
i++;
}
else
{
var num = (last - '0') * 10 + (current - '0');
switch (operation)
{
case '+': acc += num; break;
case '-': acc -= num; break;
case '*': acc *= num; break;
case '/': acc /= num; break;
}
last = ' ';
i += 2;
}
break;
case '+': case '-': case '*': case '/':
operation = current;
i += 2;
break;
}
}
if (last != ' ')
switch (operation)
{
case '+': acc += last - '0'; break;
case '-': acc -= last - '0'; break;
case '*': acc *= last - '0'; break;
case '/': acc /= last - '0'; break;
}
return acc;
}
```
---
I implemented one more variant:
```
static int Calculate3(string input)
{
int acc = 0, i = 0;
var operation = '+';
while (true)
{
var a = input[i++] - '0';
if (i == input.Length)
{
switch (operation)
{
case '+': acc += a; break;
case '-': acc -= a; break;
case '*': acc *= a; break;
case '/': acc /= a; break;
}
break;
}
var b = input[i];
if (b == ' ') i++;
else
{
a = a * 10 + (b - '0');
i += 2;
}
switch (operation)
{
case '+': acc += a; break;
case '-': acc -= a; break;
case '*': acc *= a; break;
case '/': acc /= a; break;
}
if (i >= input.Length) break;
operation = input[i];
i += 2;
}
return acc;
}
```
Results in abstract points:
* Calculate1 230
* Calculate2 192
* Calculate3 111
Upvotes: 5 [selected_answer]<issue_comment>username_4: Update
======
My original answer was just a bit of fun late at night trying to put this in `unsafe` and I failed miserably (actually didn't work at all and was slower). However I decided to give this another shot.
The premise was to make everything inline, to remove as much `IL` as I could, keep everything in `int` or `char*`, and make my code pretty. I further optimized this by removing the switch, `Ifs` will be more efficient in this situation, also we can order them in the most logical way. And lastly, if we remove the amount of checks for things we do and assume the input is correct we can remove even more overhead by just assuming things like; if the `char` is > `'0'` it must be a number. If it's a space we can do some calculations, else it must be an operator.
This is my last attempt with 10,000,000 calculations run 100 times to get an average, each test does a `GC.Collect()` and `GC.WaitForPendingFinalizers()` so we aren't fragmenting the memory.
**Results**
```
Test : ms : Cycles (rough) : Increase
-------------------------------------------------------------------
OriginalCalc : 1,295 : 4,407,795,584 :
MarcEvalNoSubStrings : 241 : 820,660,220 : 437.34%, * 5.32
MarcEvalNoSubStringsUnsafe : 206 : 701,980,373 : 528.64%, * 6.28
MiraiMannCalc1 : 225 : 765,678,062 : 475.55%, * 5.75
MiraiMannCalc2 : 183 : 623,384,924 : 607.65%, * 7.07
MyCalc4 : 156 : 534,190,325 : 730.12%, * 8.30
MyCalc5 : 146 : 496,185,459 : 786.98%, * 8.86
MyCalc6 : 134 : 455,610,410 : 866.41%, * 9.66
```
Fastest Code so far
```
unsafe int Calc6(ref string expression)
{
int res = 0, val = 0, op = 0;
var isOp = false;
// pin the array
fixed (char* p = expression)
{
// Let's not evaluate this 100 million times
var max = p + expression.Length;
// Let's go straight to the source and just increment the pointer
for (var i = p; i < max; i++)
{
// numbers are the most common thing so let's do a loose
// basic check for them and push them in to our val
if (*i >= '0') { val = val * 10 + *i - 48; continue; }
// The second most common thing are spaces
if (*i == ' ')
{
// not every space we need to calculate
if (!(isOp = !isOp)) continue;
// In this case 4 ifs are more efficient then a switch
// do the calculation, reset out val and jump out
if (op == '+') { res += val; val = 0; continue; }
if (op == '-') { res -= val; val = 0; continue; }
if (op == '*') { res *= val; val = 0; continue; }
if (op == '/') { res /= val; val = 0; continue; }
// this is just for the first op
res = val; val = 0; continue;
}
// anything else is considered an operator
op = *i;
}
if (op == '+') return res + val;
if (op == '-') return res - val;
if (op == '*') return res * val;
if (op == '/') return res / val;
throw new IndexOutOfRangeException();
}
}
```
**Previous**
```
unsafe int Calc4(ref string expression)
{
int res = 0, val = 0, op = 0;
var isOp = false;
fixed (char* p = expression)
{
var max = p + expression.Length;
for (var i = p; i < max; i++)
switch (*i)
{
case ' ':
isOp = !isOp;
if (!isOp) continue;
switch (op)
{
case '+': res += val; val = 0; continue;
case '-': res -= val; val = 0; continue;
case '*': res *= val; val = 0; continue;
case '/': res /= val; val = 0; continue;
default: res = val; val = 0; continue;
}
case '+': case '-': case '*': case '/': op = *i; continue;
default: val = val * 10 + *i - 48; continue;
}
switch (op)
{
case '+': return res + val;
case '-': return res - val;
case '*': return res * val;
case '/': return res / val;
default : return -1;
}
}
}
```
How I measured the *Thread* cycles
```
static class NativeMethods {
public static ulong GetThreadCycles() {
ulong cycles;
if (!QueryThreadCycleTime(PseudoHandle, out cycles))
throw new System.ComponentModel.Win32Exception();
return cycles;
}
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool QueryThreadCycleTime(IntPtr hThread, out ulong cycles);
private static readonly IntPtr PseudoHandle = (IntPtr)(-2);
}
```
Original Post
=============
I thought I'd try to be smart and use fixed and max this out with millions of calculations
```
public static unsafe int Calc2(string sInput)
{
var buf = "";
var start = sInput.IndexOf(' ');
var value1 = int.Parse(sInput.Substring(0, start));
string op = null;
var iResult = 0;
var isOp = false;
fixed (char* p = sInput)
{
for (var i = start + 1; i < sInput.Length; i++)
{
var cur = *(p + i);
if (cur == ' ')
{
if (!isOp)
{
op = buf;
isOp = true;
}
else
{
var value2 = int.Parse(buf);
switch (op[0])
{
case '+': iResult += value1 + value2; break;
case '-': iResult += value1 - value2; break;
case '*': iResult += value1 * value2; break;
case '/': iResult += value1 / value2; break;
}
value1 = value2;
isOp = false;
}
buf = "";
}
else
{
buf += cur;
}
}
}
return iResult;
}
private static void Main(string[] args)
{
var input = "14 + 2 * 32 / 60 + 43 - 7 + 3 - 1 + 0 * 7 + 87 - 32 / 34";
var sb = new StringBuilder();
sb.Append(input);
for (var i = 0; i < 10000000; i++)
sb.Append(" + " + input);
var sw = new Stopwatch();
sw.Start();
Calc2(sb.ToString());
sw.Stop();
Console.WriteLine($"sw : {sw.Elapsed:c}");
}
```
Results were 2 seconds slower than the original!
Upvotes: 2 <issue_comment>username_5: Here is a Java fun fact. I implemented the same thing in Java and it runs about 20 times faster than [Mirai Mann](https://stackoverflow.com/a/49424758/1129332) implementation in C#. On my machine 100M chars input string took about 353 milliseconds.
Below is the code that creates and tests the result.
Also, note that while it's a good Java/C# performance tester this is not an optimal solution. A better performance can be achieved by multithreading it. It's possible to calculate portions of the string and then combine the result.
```
public class Test {
public static void main(String...args){
new Test().run();
}
private void run() {
long startTime = System.currentTimeMillis();
Random random = new Random(123);
int result = 0;
StringBuilder input = new StringBuilder();
input.append(random.nextInt(99) + 1);
while (input.length() < 100_000_000){
int value = random.nextInt(100);
switch (random.nextInt(4)){
case 0:
input.append("-");
result -= value;
break;
case 1: // +
input.append("+");
result += value;
break;
case 2:
input.append("*");
result *= value;
break;
case 3:
input.append("/");
while (value == 0){
value = random.nextInt(100);
}
result /= value;
break;
}
input.append(value);
}
String inputData = input.toString();
System.out.println("Test created in " + (System.currentTimeMillis() - startTime));
startTime = System.currentTimeMillis();
int testResult = test(inputData);
System.out.println("Completed in " + (System.currentTimeMillis() - startTime));
if(result != testResult){
throw new Error("Oops");
}
}
private int test(String inputData) {
char[] input;
try {
Field val = String.class.getDeclaredField("value");
val.setAccessible(true);
input = (char[]) val.get(inputData);
} catch (NoSuchFieldException | IllegalAccessException e) {
throw new Error(e);
}
int result = 0;
int startingI = 1;
{
char c = input[0];
if (c >= '0' && c <= '9') {
result += c - '0';
c = input[1];
if (c >= '0' && c <= '9') {
result += (c - '0') * 10;
startingI++;
}
}
}
for (int i = startingI, length = input.length, value=0; i < length; i++) {
char operation = input[i];
i++;
char c = input[i];
if(c >= '0' && c <= '9'){
value += c - '0';
c = input[i + 1];
if(c >= '0' && c <= '9'){
value = value * 10 + (c - '0');
i++;
}
}
switch (operation){
case '-':
result -= value;
break;
case '+':
result += value;
break;
case '*':
result *= value;
break;
case '/':
result /= value;
break;
}
value = 0;
}
return result;
}
}
```
When you read the code then you can see that I used a small hack when converting the string to a char array. I mutated the string in order to avoid additional memory allocations for the char array.
Upvotes: 1 |
2018/03/22 | 442 | 1,599 | <issue_start>username_0: Is there a way to retrieve all data in local storage in one single call?
Without using specific key (getItem('key').
What I like is to load all data and then check them for a certain prefix.<issue_comment>username_1: This will give you all the keys
```
var local = localStorage;
for (var key in local) {
console.log(key);
}
```
Also you can use [`Object.keys()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys).
The `Object.keys()` method returns an array of a given object's own enumerable properties, in the same order as that provided by a for...in loop (the difference being that a for-in loop enumerates properties in the prototype chain as well).
```
console.log(Object.keys(localStorage))
```
Upvotes: 1 <issue_comment>username_2: ```
Object.getOwnPropertyNames(localStorage)
.filter(key => localStorage[key].startsWith("e"))
.map(key => localStorage[key]);
```
Upvotes: 2 <issue_comment>username_3: If you want to get certain items that staty with your custom prefix, you can first at all retrieve all `localStorage` keys, filter it, and then retrieve the data:
**ES5**
```
var prefix = 'your-prefix:'
var filteredStorage = Object.keys(localStorage)
.filter(function(key) {
return key.startsWith(prefix)
})
.map(function(key){
return localStorage.getItem(key)
})
```
**ES2015**
```
let prefix = 'your-prefix:'
let filteredStorage = Object.keys(localStorage)
.filter(key => key.startsWith(prefix))
.map(key => localStorage.getItem(key))
```
Upvotes: 2 [selected_answer] |
2018/03/22 | 223 | 715 | <issue_start>username_0: I want to make video responsive in html.For that i'm using video tag.
Following is the code i've tried.
```
```
Now when i opened the website which contains the video in mobile phone , what i'm getting is there will be a play button , but can't play anything.Please help..<issue_comment>username_1: You can use "max-width:100%" check snippet below..
```css
video {
max-width: 100%;
height: auto;
}
```
```html
```
Upvotes: 1 <issue_comment>username_2: Use Css Property-
```
video {
width: 100%;
height: auto;
}
```
Upvotes: 1 <issue_comment>username_3: Have you tried this
```
video {
width: 100% !important;
height: auto !important;
}
```
Upvotes: 0 |
2018/03/22 | 252 | 851 | <issue_start>username_0: Hi I am trying to build a long term Excel sheet for my church scheduling. I want to be able to format a cell fill if that cell has contents. eg. I want it to go green if I have entered the name of the preacher for a particular day. Alternatively colour red if there is no entry. It doesn't have to be both, one or the other would be OK. Excel seems to be happy for me to format a cell contents but not the fill.<issue_comment>username_1: You can use "max-width:100%" check snippet below..
```css
video {
max-width: 100%;
height: auto;
}
```
```html
```
Upvotes: 1 <issue_comment>username_2: Use Css Property-
```
video {
width: 100%;
height: auto;
}
```
Upvotes: 1 <issue_comment>username_3: Have you tried this
```
video {
width: 100% !important;
height: auto !important;
}
```
Upvotes: 0 |
2018/03/22 | 312 | 1,069 | <issue_start>username_0: I am trying to change the memory\_limit in php.ini, the php.ini is saving fine with new memory size, but i keep getting the same memory size issue?? I am using Laravel 5.5 with Homestead.
Would appreciate if someone could help me out. Thanks!
Here is the code m trying to run (importing data from one db to another, rest of the tables are fine except for one)
```
$repair = DB::connection('db')->table('tablename')->get();
DB::beginTransaction();
foreach ($repair as $repairs) {
Model::create([
'column' => $repairs->column,
...so on
]);
};
DB::commit();
```<issue_comment>username_1: You can use "max-width:100%" check snippet below..
```css
video {
max-width: 100%;
height: auto;
}
```
```html
```
Upvotes: 1 <issue_comment>username_2: Use Css Property-
```
video {
width: 100%;
height: auto;
}
```
Upvotes: 1 <issue_comment>username_3: Have you tried this
```
video {
width: 100% !important;
height: auto !important;
}
```
Upvotes: 0 |
2018/03/22 | 465 | 1,414 | <issue_start>username_0: I'm trying to get the coordinates from a scanned QR-code using the pyzbar module. If I use the following code below to do this:
```
test = decode(img)
print(test)
```
I get the following result:
[Decoded(data=b'Part4', type='QRCODE', rect=Rect(left=172, top=332, width=75, height=76))]
The problem however, is that I do not know how to just extract the rect part of this string. I'm using spyder, and if I go to the variable explorer to try and see how the variable is built-up, I get the following error:
AttributeError("Can't get attribute 'Rect' on ",)
Anyone know what could be it?<issue_comment>username_1: As you can see in [the source code](https://github.com/NaturalHistoryMuseum/pyzbar/blob/8e3e87da17ddd794842b2fcbbe0dd86c692d7511/pyzbar/pyzbar.py#L26), `Decoded` is a [namedtuple](https://docs.python.org/3/library/collections.html#collections.namedtuple). So your `test` is a list of namedtuples. You can get the rect of the first result like this:
```
rect = test[0].rect
```
Upvotes: 2 [selected_answer]<issue_comment>username_2: there is another way that helps.
you can change the data to Numpy array and use it with OpenCV and other libs will be easier.
Exp:(import OpenCV, Numpy libs)
```
points = np.array(decoded_objects_by_pyzbar[0].polygon, np.int32)
cv.polylines(img,[points],True,(0,255,255),9)
cv.imshow("detected code", frame)
```
Upvotes: 0 |
2018/03/22 | 425 | 1,269 | <issue_start>username_0: I am making a homework in LaTeX. I need to use the fractions. And here I have a problem.
First fraction is displayed fine, code:
```
\rho = \frac{m}{V}, \hfill (1)
```
Its looks like it should. The problem is with next fractions. All are displayed in one denominator.
This is badly displayed when its not equation, for example: `x=\frac{wq}{21}`.
Here is my code: <https://www.sharelatex.com/read/ntwzrgmkzxpn>
How to display fractions correctly?<issue_comment>username_1: As you can see in [the source code](https://github.com/NaturalHistoryMuseum/pyzbar/blob/8e3e87da17ddd794842b2fcbbe0dd86c692d7511/pyzbar/pyzbar.py#L26), `Decoded` is a [namedtuple](https://docs.python.org/3/library/collections.html#collections.namedtuple). So your `test` is a list of namedtuples. You can get the rect of the first result like this:
```
rect = test[0].rect
```
Upvotes: 2 [selected_answer]<issue_comment>username_2: there is another way that helps.
you can change the data to Numpy array and use it with OpenCV and other libs will be easier.
Exp:(import OpenCV, Numpy libs)
```
points = np.array(decoded_objects_by_pyzbar[0].polygon, np.int32)
cv.polylines(img,[points],True,(0,255,255),9)
cv.imshow("detected code", frame)
```
Upvotes: 0 |
2018/03/22 | 1,523 | 4,847 | <issue_start>username_0: I'm trying to remove the duplicates in the results of a query involving listagg.
I'm using this syntax:
```
REGEXP_REPLACE (LISTAGG (PR.NAME, ',' ) WITHIN GROUP (ORDER BY 1),
'([^,]+)(,\1)+',
'\1') AS PRODUCERS
```
However, occurrences including chinese characters are not removed:
[](https://i.stack.imgur.com/GctIw.png)
Any idea ?<issue_comment>username_1: (I can't see images; company policy).
Why wouldn't you remove duplicates *before* applying LISTAGG? Something like
```
select listagg(x.distinct_name, ',') within group (order by 1) producers
from (select DISTINCT name distinct_name
from some_table
) x
```
Upvotes: 0 <issue_comment>username_2: Another way to remove duplicates is to use window functions and `case`:
```
select listagg(case when seqnum = 1 then name end, ',') within group (order by 1) as producers
from (select . . .,
row_number() over (partition by name order by name) as seqnum
from . . .
) t
```
This does require modifications to the rest of the query, but you should still be able to do the rest of the aggregations and computations.
Upvotes: 0 <issue_comment>username_3: Your regular expression does not work. If the `LISTAGG` output is `A,A,AA` then the regular expression `([^,]+)(,\1)+` does not check that it has matched a complete element of your list and will match `A,A,A` which is 2½ elements of the list and will give the output `AA` instead of the expected `A,AA`. Worse, if you have the string `BA,BABAB,BABD` then the regular expression will replace `BA,BA` with `BA` and then replace `BAB,BAB` with `BAB` and you end up with the string `BABABD` which does not match any of the elements of the original list.
An example demonstrating this is:
[SQL Fiddle](http://sqlfiddle.com/#!4/aa6bf7/1)
**Oracle 11g R2 Schema Setup**:
```
CREATE TABLE names ( id, name ) AS
SELECT 1, 'A' FROM DUAL UNION ALL
SELECT 2, 'A' FROM DUAL UNION ALL
SELECT 3, 'B' FROM DUAL UNION ALL
SELECT 4, 'C' FROM DUAL UNION ALL
SELECT 5, 'A' FROM DUAL UNION ALL
SELECT 6, 'AA' FROM DUAL UNION ALL
SELECT 7, 'A' FROM DUAL UNION ALL
SELECT 8, 'BA' FROM DUAL UNION ALL
SELECT 9, 'A' FROM DUAL
/
```
**Query 1**:
```
SELECT REGEXP_REPLACE (
LISTAGG (NAME, ',' ) WITHIN GROUP (ORDER BY 1),
'([^,]+)(,\1)+',
'\1'
) AS constant_sort
FROM names
```
**[Results](http://sqlfiddle.com/#!4/aa6bf7/1/0)**:
```
| CONSTANT_SORT |
|---------------|
| AA,BA,C |
```
If you want to get the distinct elements then you can use `DISTINCT` (as per [username_1's answer](https://stackoverflow.com/a/49424283/1509264)) or you can [`COLLECT`](https://docs.oracle.com/cloud/latest/db112/SQLRF/functions031.htm#SQLRF06304) the values into a user-defined collection and then use the [`SET` function](https://docs.oracle.com/database/121/SQLRF/functions177.htm#SQLRF06308) to remove duplicates. You can then pass this de-duplicated collection to a table collection expression and use `LISTAGG` to get your output:
**Oracle 11g R2 Schema Setup**:
```
CREATE TYPE StringList IS TABLE OF VARCHAR2(4000)
/
```
**Query 2**:
```
SELECT (
SELECT LISTAGG( column_value, ',' )
WITHIN GROUP ( ORDER BY ROWNUM )
FROM TABLE( n.unique_names )
) AS agg_names
FROM (
SELECT SET( CAST( COLLECT( name ORDER BY NAME ) AS StringList ) )
AS unique_names
FROM names
) n
```
**[Results](http://sqlfiddle.com/#!4/aa6bf7/1/1)**:
```
| AGG_NAMES |
|-------------|
| A,AA,B,BA,C |
```
Regarding your comment:
>
> in the context of a bigger query involving a lot of join and given my begginers skills I would have no idea how to implement this model
>
>
>
For example, if your query was:
```
SELECT REGEXP_REPLACE(
LISTAGG (PR.NAME, ',' ) WITHIN GROUP (ORDER BY 1),
'([^,]+)(,\1)+',
'\1'
) AS PRODUCERS,
other_column1,
other_column2
FROM table1 pr
INNER JOIN table2 t2
ON (pr.some_condition = t2.some_condition )
WHERE t2.some_other_condition = 'TRUE'
GROUP BY other_column1, other_column2
```
Then you can change it to:
```
SELECT (
SELECT LISTAGG( COLUMN_VALUE, ',' ) WITHIN GROUP ( ORDER BY ROWNUM )
FROM TABLE( t.PRODUCERS )
) AS producers,
other_column1,
other_column2
FROM (
SELECT SET( CAST( COLLECT( PR.name ORDER BY PR.NAME ) AS StringList ) )
AS PRODUCERS,
other_column1,
other_column2
FROM table1 pr
INNER JOIN table2 t2
ON (pr.some_condition = t2.some_condition )
WHERE t2.some_other_condition = 'TRUE'
GROUP BY other_column1, other_column2
) t
```
Upvotes: 2 [selected_answer] |
2018/03/22 | 731 | 2,589 | <issue_start>username_0: What is the difference between this two implementations of Singleton. Does creating of variable \_instance in parent class make it work differently from the second class?
```
class SingletonA(object):
_instance = None
def __new__(cls, *args, **kwargs):
if not cls._instance:
cls._instance = object.__new__(cls, *args, **kwargs)
return cls._instance
class SingletonB(object):
def __new__(cls, *args, **kwargs):
if not hasattr(cls, "_instance"):
cls._instance = object.__new__(cls, *args, **kwargs)
return cls._instance
# sample usage
class A(SingletonA):
pass
print(A() == A()) #True
```<issue_comment>username_1: For the code posted, there is no difference.
If your subclasses implement [`__bool__`](https://docs.python.org/3/reference/datamodel.html#object.__bool__) or [`__len__`](https://docs.python.org/3/reference/datamodel.html#object.__len__) however, the first example will fail, as `not self._instance` could return `True` even when an instance has been set. You really want to use `if self._instance is None:` instead:
```
>>> class AlwaysFalse(object):
... def __bool__(self): return False
...
>>> if not AlwaysFalse():
... print("It doesn't exist? Should we create a new one?")
...
It doesn't exist? Should we create a new one?
>>> AlwaysFalse() is None
False
```
Other than that, the differences are cosmetic.
You also want to use identity testing to check if a singleton implementation work correctly; a subclass could implement the [`__eq__` method](https://docs.python.org/3/reference/datamodel.html#object.__eq__) and return `True` even if the two objects are distinct (so not singletons):
```
>>> class EqualNotSingleton(object):
... def __eq__(self, other): return True
...
>>> EqualNotSingleton() == EqualNotSingleton()
True
>>> EqualNotSingleton() is EqualNotSingleton()
False
```
Upvotes: 4 [selected_answer]<issue_comment>username_2: Agreed with @<NAME> answer,
Besides, provide another way to implement Singleton, called Borg, which share the same state:
```
class Borg:
_shared_state = {}
def __new__(cls, *args, **kwargs):
obj = super(Borg, cls).__new__(cls, *args, **kwargs)
obj.__dict__ = cls._shared_state
return obj
class S1(Borg):
pass
class S2(Borg):
pass
assert S1() is not S1()
S1().v = 1
assert S1().v == S1().v
assert S1().v == S2().v
class S3(Borg):
# if want to have a different state
_shared_state = {}
pass
S3().v = 2
assert S3().v != S1().v
```
Upvotes: 1 |
2018/03/22 | 1,637 | 6,270 | <issue_start>username_0: The actual JSON,that I need to parse in swift4 is,
```
{
"class": {
"semester1": [
{
"name": "Kal"
},
{
"name": "Jack"
},
{
"name": "Igor"
}
],
"subjects": [
"English",
"Maths"
]
},
"location": {
"Dept": [
"EnglishDept",
],
"BlockNo": 1000
},
"statusTracker": {
"googleFormsURL": "beacon.datazoom.io",
"totalCount": 3000
}
}
```
The code that I'd tried but failed to execute is,
```
struct Class: Decodable {
let semester: [internalComponents]
let location: [location]
let statusTracker: [statusTracker]
enum CodingKeys: String, CodingKey {
case semester = "semester1"
case location = "location"
case statusTracker = "statusTracker"
}
}
struct location: Decodable {
let Dept: [typesSubIn]
let BlockNo: Int
}
struct statusTracker: Decodable {
let googleFormsURL: URL
let totalCount: Int
}
struct internalComponents: Decodable {
let semester1: [semsIn]
let subjects: [subjectsIn]
}
struct semsIn: Decodable {
let nameIn: String
}
struct subjectsIn: Decodable {
let subjects: String
}
struct Dept: Decodable {
let Depts: String
}
```
I know it's completely wrong can someone give the actual format? I'm actually confused with the format for "subjects".It's not compiling as a whole too.<issue_comment>username_1: It looks like you sterilize `Class` object in wrong way. It should looks like:
```
struct Class: Decodable {
let class: [internalComponents]
let location: [location]
let statusTracker: [statusTracker]
}
```
Upvotes: 0 <issue_comment>username_2: There are a few things here causing your issue.
* You have no top level item, I added Response struct
* Location, class and statusTracker are both at the same level, not under class.
* In your class struct, your items are set as arrays but they aren't arrays
* To debug these types of issues, wrap your decode in a do catch block and print out the error. it will tell you the reason it failed to parse
Try this code from my playground:
```
let jsonData = """
{
"class": {
"semester1": [{
"name": "Kal"
}, {
"name": "Jack"
}, {
"name": "Igor"
}],
"subjects": [
"English",
"Maths"
]
},
"location": {
"Dept": [
"EnglishDept"
],
"BlockNo": 1000
},
"statusTracker": {
"googleFormsURL": "beacon.datazoom.io",
"totalCount": 3000
}
}
""".data(using: .utf8)!
struct Response: Decodable {
let cls: Class
let location: Location
let statusTracker: statusTracker
enum CodingKeys: String, CodingKey {
case cls = "class"
case location
case statusTracker
}
}
struct Class: Decodable {
let semester: [SemesterStudents]
let subjects: [String]
enum CodingKeys: String, CodingKey {
case semester = "semester1"
case subjects
}
}
struct Location: Decodable {
let dept: [String]
let blockNo: Int
enum CodingKeys: String, CodingKey {
case dept = "Dept"
case blockNo = "BlockNo"
}
}
struct statusTracker: Decodable {
let googleFormsURL: URL
let totalCount: Int
}
struct SemesterStudents: Decodable {
let name: String
}
struct Dept: Decodable {
let Depts: String
}
do {
let result = try JSONDecoder().decode(Response.self, from: jsonData)
print(result)
} catch let error {
print(error)
}
```
Upvotes: 0 <issue_comment>username_3: There are many issues.
You are making a common mistake by ignoring the root object partially.
Please take a look at the JSON: On the top level there are 3 keys `class`, `location` and `statusTracker`. The values for all 3 keys are dictionaries, there are no arrays.
Since `class` (lowercase) is a reserved word, I'm using `components`. By the way please conform to the naming convention that struct names start with a capital letter.
```
struct Root : Decodable {
let components : Class
let location: Location
let statusTracker: StatusTracker
enum CodingKeys: String, CodingKey { case components = "class", location, statusTracker }
}
```
There are many other problems. Here a consolidated version of the other structs
```
struct Class: Decodable {
let semester1: [SemsIn]
let subjects : [String]
}
struct Location: Decodable {
let dept : [String]
let blockNo : Int
enum CodingKeys: String, CodingKey { case dept = "Dept", blockNo = "BlockNo" }
}
struct SemsIn: Decodable {
let name: String
}
struct StatusTracker: Decodable {
let googleFormsURL: String // URL is no benefit
let totalCount: Int
}
```
Now decode `Root`
```
do {
let result = try decoder.decode(Root.self, from: data)
} catch { print(error) }
```
Upvotes: 2 <issue_comment>username_4: Another approach is to create an intermediate model that closely matches the JSON, let Swift generate the methods to decode it, and then pick off the pieces that you want in your final data model:
```
// snake_case to match the JSON
fileprivate struct RawServerResponse: Decodable {
struct User: Decodable {
var user_name: String
var real_info: UserRealInfo
}
struct UserRealInfo: Decodable {
var full_name: String
}
struct Review: Decodable {
var count: Int
}
var id: Int
var user: User
var reviews_count: [Review]
}
struct ServerResponse: Decodable {
var id: String
var username: String
var fullName: String
var reviewCount: Int
init(from decoder: Decoder) throws {
let rawResponse = try RawServerResponse(from: decoder)
// Now you can pick items that are important to your data model,
// conveniently decoded into a Swift structure
id = String(rawResponse.id)
username = rawResponse.user.user_name
fullName = rawResponse.user.real_info.full_name
reviewCount = rawResponse.reviews_count.first!.count
}
}
```
Upvotes: 0 |
2018/03/22 | 388 | 1,661 | <issue_start>username_0: I'm using bootstrap modal for login and register. I want to open register modal in after closing login modal on same button. Now register modal is opening on click of button on login pop up. After clicking on overlay the both pop going close but overlay is not hiding.
So for hiding first modal I used `data-dismiss="modal"` for closing first modal but it's not opening another modal. I want to close both modal on clicking on overlay or hide first modal and then show another modal. If it's possible without jQuery then great. Please help
```html
Bootstrap Example
Modal Example
-------------
Login
login
register
register
```<issue_comment>username_1: I can't imagine how the modal show inside modal, but do you think this is what you want?
```
Bootstrap Example
Modal Example
-------------
Login
login
register
register
$("#register-button").click(function(){
$("#register").modal("show")
})
```
Upvotes: 1 <issue_comment>username_2: Yes, this possible without jquery. Your html(modal code) is not organized proper way. You can not use a modal within a modal. You have to be separate each modal.
```html
Bootstrap Example
Modal Example
-------------
Login
login
register
register
```
Upvotes: 1 <issue_comment>username_3: Why do you want to show a modal inside a modal. try this one. when login button clicks it will open login modal then register button->click - open register modal.
```
Modal Example
-------------
Login
login
register
register
$("#btn\_register").click(function(){
$("#login").modal("hide");
$("#register").modal("show");
});
```
Upvotes: 0 |
2018/03/22 | 1,002 | 3,628 | <issue_start>username_0: I've just started to learn c++ and I have some example code right here that shows a problem with a local variable and a pointer.
```
#include
using namespace std;
int\* f1 (int n) {
int\* p = &n
return p;
}//f1
void f2 (int na) {
int nb = na;
}//f2
int main () {
int\* nn = f1 (101);
f2 (2002);
cout << \*nn << endl;
}//main
/\*
2002 // output MinGW 6.2.0
\*/
```
Unfortunately, I cannot find an explanation why this happens. As far as I understood p is returned to the caller so nn should equal 101 but it somehow gets assigned to the parameter that was given to f2? I'm really confused. I'm also sorry if this is a really basic question.<issue_comment>username_1: This instruction:
```
int* p = &n
```
assigns a pointer to a *local, automatic* variable `n`.
That variable is destroyed at the end of `f1()`, so as soon as you execute
```
return p;
```
the pointer becomes **invalid**. Storing it in `nn` and using a pointed value by dereferencing it with `*nn` triggers an **Undefined Behavior** - you can't know what happens after.
What actually happens *in your specific case* (credit to @Caleth) is probably that the `n` variable is stored on the machine stack, and the very same location is then used by `na` of `f2()`, hence it gets overwritten with the `2002` value of the parameter to `f2`.
But **never** rely on such effects! Variables needn't be allocated in the same manner for different functions, e.g. stack frames can be stacked one by one and freed several subsequent calls later (I've seen such behavior in - IIRC - a Watcom C compiler many years ago), or `na` could be allocated in the microprocessor's register. Anyway even if they are located on the stack and in the same place of the stack, they needn't keep the same value! The stack can be used by other mechanisms, not necessarily visible in your source code.
P.S.
The same happens in C, not just in C++. Using `cout` with its `<<` operators doesn't matter in the problem.
Upvotes: 4 [selected_answer]<issue_comment>username_2: As [username_1 notes in his/her answer](https://stackoverflow.com/a/49424322/2445184), you are in undefined behavior territory as soon as you are returning a pointer to a local variable. Here is what actually happens under the hood: Your local variables are stored on the function call stack, which changes state at every function call/return. When a function returns, it generally does not clear the stack memory that it used, so it may appear to remain valid. But by the language standard, that memory pretty much ceases to exist, and any pointer pointing into it becomes invalid immediately. I hope the ASCII art will help you understand what's really going on.
```
Before call of f1():
| main(): nn |
| ?????????? |
|
v
???
During execution of f1():
| main(): nn | f1(): n | f1(): p |
| ?????????? | 101 | &n |
| ^ /
v \________/
???
After f1() returns (nn is invalid as n does not exist anymore):
| main(): nn | unused space |
| invalid | 101 | &n |
\ ^
\________/
During execution of f2() (nn is still invalid, but seems to point to na now):
| main(): nn | f2(): na | f2(): nb |
| invalid | 2002 | 2002 |
\ ^
\________/
After f2() returns, nn is still invalid, but points to the memory that was once occupied by na:
| main(): nn | unused space |
| invalid | 2002 | 2002 |
\ ^
\________/
```
Upvotes: 0 |
2018/03/22 | 1,073 | 3,849 | <issue_start>username_0: I have a http post request which returns ID. I then try to pass that ID into another function. However, inside the next function I have a timeout that will loop the function to check the status. The ID returns undefined each time inside the timeout function.
**First Function**
Here I have 'res' which is a result from another function. I grab the status ID from the returned json and send it to 'getAlbum'.
```
anotherFunction(res) {
this.getAlbum(res);
}
```
**GetAlbum**
If I do a console log immediately inside this function, it correct emits the correct ID. However, if I do it inside the 'checkAblumStatus' function, the id part is undefined.
```
getAlbum(id){
var statusID = id.status_id;
console.log('id = ' + statusID) // returns id
var statusIDRequest = 'url' + statusID;
var checkAblumStatus = function (statusIDRequest) {
console.log('statusIDRequest = ' + statusIDRequest) // returns undefined for the ID part
this.http.get(statusIDRequest).subscribe(res => {
if (res.status == "completed") {
// completed
} else if (res.status == "failed") {
// failed
} else {
setTimeout(checkAblumStatus, 1000);
}
});
};
setTimeout(checkAblumStatus, 1000);
}
```
Any help here would be very grateful :)<issue_comment>username_1: This happens because of the scope of your variables.
```
var checkAblumStatus = function (statusIDRequest) {
console.log('statusIDRequest = ' + statusIDRequest) // returns undefined for the ID part
this.http.get(statusIDRequest).subscribe(res => {
if (res.status == "completed") {
// completed
} else if (res.status == "failed") {
// failed
} else {
setTimeout(checkAblumStatus, 1000);
}
});
};
```
In the context of your function, `this` references the function itself, not your object.
You need to use a closure or a fat arrow like this.
```
var checkAblumStatus = (statusIDRequest) => {
```
You also need to provide a avariable to your calls.
```
setTimeout(checkAblumStatus(variable), 1000);
```
Upvotes: 2 [selected_answer]<issue_comment>username_2: you can pass the id for the function as follow
```
function getAlbum(id){
var statusID = id.status_id;
console.log('id = ' + statusID) // returns id
var statusIDRequest = 'url' + statusID;
var checkAblumStatus = ((statusIDRequest) => {
console.log('statusIDRequest = ' + statusIDRequest) // returns undefined for the ID part
this.http.get(statusIDRequest).subscribe(res => {
if (res.status == "completed") {
// completed
} else if (res.status == "failed") {
// failed
} else {
setTimeout(checkAblumStatus, 1000);
}
});
})(statusIDRequest);
setTimeout(checkAblumStatus, 1000);
}
```
Upvotes: 0 <issue_comment>username_3: You get confused with variable and param name.
```
var statusIDRequest = 'url' + statusID;
^ ^ // this variable
var checkAblumStatus = function (statusIDRequest) {
^ ^ // .. is not the same not this param
```
Change the name of the variable like this, so you don't get rid of the name:
```
getAlbum(id){
var statusID = id.status_id;
console.log('id = ' + statusID) // returns id
var statusID = 'url' + statusID;
var checkAblumStatus = function (statusIDRequest) {
console.log('statusIDRequest = ' + statusIDRequest) // returns the ID part
this.http.get(statusIDRequest).subscribe(res => {
if (res.status == "completed") {
// completed
} else if (res.status == "failed") {
// failed
} else {
setTimeout( () => checkAblumStatus (statusIDRequest), 1000);
}
});
};
setTimeout(() => checkAblumStatus(statusID), 1000);
}
```
Upvotes: 0 |
2018/03/22 | 365 | 1,287 | <issue_start>username_0: I'm writing a WordPress plugin and have a checkbox in a form.
If the checkbox is checked it saves the value to the database and shows up checked in the form. However if the checkbox is checked it outputs `checked='checked'` in the form.
So the checkbox works like it needs to work but I cant see why it outputs `checked='checked'` to the form.
```
public function display() {
$html = '';
// Add an nonce field so we can check for it later.
wp_nonce_field( basename( __FILE__ ), 'nonce_check_value' );
$html .= 'Name metabox: ';
$html .= '';
$html .= 'What do you need?
=================
';
$html .= 'Checkbox: ';
$checkedByUser = get_post_meta( get_the_ID(), 'CMBUserCheckbox', true );
$html .= '';
echo $html;
}
```
The output on screen is as followed
[](https://i.stack.imgur.com/lp20D.png)<issue_comment>username_1: The [`checked()`](https://codex.wordpress.org/Function_Reference/checked) function `echo`s by default. Use `false` in the last parameter to return the string instead of echo.
```
$html .= '';
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: Using wordpress Checked() function you can do this
```
>
```
Upvotes: 0 |
2018/03/22 | 410 | 1,278 | <issue_start>username_0: I try to achieve ion segment button with icon and text like tab bar but getting differently.
what i have tried so far
```
Heizöl
Diesel
<NAME>
<NAME>
<NAME>
```
[](https://i.stack.imgur.com/CChOh.png)
I have try to get it with super tabs like this
```
```
the result would be
[](https://i.stack.imgur.com/LEAdC.png)
but here i need to style this it is difficult to reduce tab bar height and adjust text size.<issue_comment>username_1: **Need to change `.html`**
```
Heizöl
Diesel
<NAME>
<NAME>
<NAME>
```
**And also need to override `$segment-button-md-height` in variable.scss like**
```
$segment-button-md-height:55px;
```
**Output:**
[](https://i.stack.imgur.com/9EBie.png)
Upvotes: 4 [selected_answer]<issue_comment>username_2: You need to do something like this
```
Heizöl
```
Then Inspect element after ionic serve in browser.
A new class associated with the element will come.
Then with css after or before effect you will place the image on custom icon.
It is tested and tried method.
Upvotes: 0 |
2018/03/22 | 1,704 | 5,870 | <issue_start>username_0: i have this array of banned characters in VB.NET how can i convert it?
Original VB.NET Banned Characters:
```
Public BannedChars() As String = New String() {" ", ",", ".", ";", "/", "\", "!", """", "(", ")", "£", "$", "%", "^", "&", "*", "{", "}", "[", "]", "@", "#", "'", "~", "<", ">", "?", "+", "=", "-", "|", "¬", "`"}
```
Tried C# Banned Characters but didn't work:
```
public string[] BannedChars = new string[] {" ", ",", ".", ";", "/", "\", "!", """", "(", ")", "£", "$", " % ", " ^ ", " & ", " * ", "{ ", "}", "[", "]", "@", "#", "'", "~", "<", ">", "?", "+", "=", "-", "|", "¬", "`"};
```
Errors:
```
CS1003 C# Syntax error, ',' expected
CS0623 C# Array initializers can only be used in a variable or field initializer. Try using a new expression instead.
CS0023 C# Operator '!' cannot be applied to operand of type 'string'
CS1056 C# Unexpected character '£'
CS0019 C# Operator '%' cannot be applied to operands of type 'string' and 'string'
CS0019 C# Operator '*' cannot be applied to operands of type 'string' and 'string'
```
Any helps apppreciated!
Thanks
C.<issue_comment>username_1: Your question is *vague* one. If you want array of **characters**, use `char`, not `string` type:
```
public char[] BannedChars = new char[] {
' ', ',', '.', ';', '/', '\\', '!', '\'', '(', ')', '£', '$',
'%', '^', '&', '*', '{', '}', '[', ']', '@', '#', '"',
'~', '<', '>', '?', '+', '=', '-', '|', '¬', '`'};
```
*escapement* is another issue: in C# we use `\` for this:
```
'\\', '\''
```
In case you want a single **string** (which can be viewed as a readonly array of characters):
```
public string BannedChars = new string(new char[] {
' ', ',', '.', ';', '/', '\\', '!', '\'', '(', ')', '£', '$',
'%', '^', '&', '*', '{', '}', '[', ']', '@', '#', '"',
'~', '<', '>', '?', '+', '=', '-', '|', '¬', '`'});
```
Finally, if you want **array of strings**:
```
public string[] BannedChars = new string[] {
" ", ",", ".", ";", "/", "\\", "!", "'", "(", ")", "£", "$",
"%", "^", "&", "*", "{", "}", "[", "]", "@", "#", "\"",
"~", "<", ">", "?", "+", "=", "-", "|", "¬", "`"});
```
please, once more, notice escapements (e.g. we don't double escaped quotation: not `""""`, but `"\""`):
```
"\\", "\""
```
**Edit:** If you are going to check if a string contains any banned character, I suggest using `HashSet` instead of array:
```
// static : you have just one set of banned char, don't you?
public static readonly HashSet BannedChars = new HashSet() {
' ', ',', '.', ';', '/', '\\', '!', '\'', '(', ')', '£', '$',
'%', '^', '&', '\*', '{', '}', '[', ']', '@', '#', '"',
'~', '<', '>', '?', '+', '=', '-', '|', '¬', '`'
};
...
string Mytext = @"some string with many characters: 'a', 'b'; which can be banned...";
if (MyText.Any(c => BannedChars.Contains(c))) {
// At least one Banned char has been found...
}
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: I can see the issue fairly clearly here but that may not always be the case, so please do provide better descriptions in future.
In this case, it is escaping that is the issue. In VB, the double-quote is the only character that needs escaping in literal strings and that is done with another double-quote. C# supports many escape sequences and the backslash is the escape character. That means that you escape a double-quote with a backslash and you also need to escape a backslash with another backslash, e.g.
```
string[] arr = new[] {"\\", "\""};
```
I think that that should sort you out but we'll see if other issues arise after fixing that.
Upvotes: 2 <issue_comment>username_3: C# uses lowercase keywords, so change `Public` to `public` and `New` to `new`.
C# puts types before variables instead of `As` clauses, so remove `As` and move `String` before `BannedChars`.
C# uses square brackets for arrays instead of parentheses, so replace `()` with `[]`.
C# puts declares array types with the brackets within the type rather than after the variable (legacy VB), so put `[]` after `String`.
C# allows omitting the base type of an array initializer rather than requiring the whole type or omitting it entirely along with the `new` keyword as VB does, so remove `String` from the initializer.
C# string literals take many forms. The closest to VB's are called verbatim strings and they are opened with `@"` and closed with `"` and stutter for literal " like VB does, so put `@` before every opening `"`.
C# terminates statements with a semicolon while VB does not (that's the simplest way to say it), so append a `;`.
```
public String[] BannedChars = new [] {
@" ", @",", @".", @";", @"/", @"\", @"!", @"""", @"(", @")",
@"£", @"$", @"%", @"^", @"&", @"*", @"{", @"}", @"[", @"]",
@"@", @"#", @"'", @"~", @"<", @">", @"?", @"+", @"=", @"-",
@"|", @"¬", @"`" };
```
.NET Datatypes (applies to Java, JavaScript, …)
-----------------------------------------------
As for what's a character: `String` holds zero or more characters. `Char` holds one character, a half or even less. `Char` is a UTF-16 code unit. `String` is a counted sequence UTF-16 code units. One or two UTF-16 code units represent a Unicode codepoint. A grapheme cluster is a sequence of one base codepoint followed by a sequence of combining codepoints. Text renders display grapheme clusters; users call them characters. Some codepoints are "composed" as in they are intended to mean the same thing as a different base codepoint with a specific combining codepoint. That makes comparing strings rather difficult. So, Unicode libraries provide normalization functions to either compose or decompose "composed" codepoints.
So, it appears that an array of strings could be a good choice for your code, especially since that's what the original code uses.
Upvotes: 1 |
2018/03/22 | 588 | 1,747 | <issue_start>username_0: So, in jQuery I can find the total number of a type of element with .find('selector').length, but how do I find out what n of the total the element is?
ie: How can I get back the information (n) that I've clicked on the first or second (or nth) button?
eg:
```
| | |
| --- | --- |
|
...
|
...
|
```<issue_comment>username_1: You should use the [index](https://api.jquery.com/index/) method of jQuery.
```js
$( "div" ).click(function() {
// `this` is the DOM element that was clicked
var index = $( "div" ).index( this );
$( "span" ).text( "That was div index #" + index );
});
```
```css
div {
background: yellow;
margin: 5px;
}
span {
color: red;
}
```
```html
Click a div!
First div
Second div
Third div
```
**In your case it will be something like this.**
```js
$("button").click(function() {
console.log($('button').index(this));
});
```
```html
| | |
| --- | --- |
|
...
One |
...
Two |
```
Upvotes: 1 <issue_comment>username_2: You can use `index()` to get the position of the `button` you clicked.
```js
$('.add-resource-link').click(function(){
var nButton = $('.add-resource-link').index(this);
console.log('Button index is ' + nButton);
});
```
```html
| | |
| --- | --- |
|
...
1 |
...
2 |
```
Upvotes: 2 <issue_comment>username_3: You can use `index()` to get find out what element number you clicked on
```
$( ".add-resource-link" ).index( this );
```
**demo**
```js
$(".add-resource-link").click(function(){
var index = $( ".add-resource-link" ).index( this );
console.log(index)
})
```
```html
| | |
| --- | --- |
|
...
click |
...
click |
```
Upvotes: 3 [selected_answer] |
2018/03/22 | 904 | 3,641 | <issue_start>username_0: I have ten projects in SVN which are independent on one another. Now i want to migrate to git. In order to maintain all the projects in git, what is the best approach for doing that. All the ten projects in SVN are not dependent on one another and all are in different languages like Java, C#,...<issue_comment>username_1: I think you should convert all projects to git.
How to do this: [How do I migrate a SVN repo with history to a new git repo](https://stackoverflow.com/questions/79165/how-do-i-migrate-an-svn-repository-with-history-to-a-new-git-repository?rq=1)
If you need a local installation, you can take a look at GitLab CE [gitlab](https://about.gitlab.com/)
Upvotes: 0 <issue_comment>username_2: If you projects are Independent, totally unrelated and will never interact together and no one is ever going to have the need to pull multiple of your projects anyways, just keep them as 10 repositories.
If you have independent but related projects which you would like in a "solution" still create 10 repositories, but look into Git-submodules, so that you have a Parent repository which has a relation towards other git repositories
### Method 1:
[Cleanly Migrate Your Subversion Repository To a GIT Repository](http://jonmaddox.com/2008/03/05/cleanly-migrate-your-subversion-repository-to-a-git-repository/)
### Method 2:
If you've got local source code you want to add to a new remote new git repository without 'cloning' the remote first, do the following (create your empty remote repository in bitbucket/github etc, then push up your source)
1. Create the remote repository, and get the URL such as `git://github.com/youruser/somename.git` (or any remote host repository service)
2. Locally, at the root directory of your source,
`git init`
3. Locally, add and commit what you want in your initial repo (for everything,
`git add .`
`git commit -m 'initial commit comment')`
4. to attach your remote repo with the name 'origin' (like cloning would do)
`git remote add origin [URL From Step 1]`
5. to push up your master branch (change master to something else for a different branch):
`git push -u origin master`
Upvotes: 0 <issue_comment>username_3: I would suggest creating a separate git repository for each of the projects.
If however, you need to group the repositories together so that your development team can easily checkout the entire stack of technologies, you can use [Git Sub Modules](https://git-scm.com/book/en/v2/Git-Tools-Submodules)
```
git submodule add
git submodule add
```
This will create a .gitmodules file that you could edit if need be
Upvotes: 0 <issue_comment>username_4: We had a similar use case where there was different technology projects present in SVN. We followed the same structure and created a project and a repository in GIT. Then when the individual teams started working on their modules or if the build jobs need only specific checkouts from the git repo, sparse checkout was used.
Upvotes: 0 <issue_comment>username_5: Below are the things I am clear on your question :
1. All the projects are independent.
2. You may have the different sets of users accessing each project and you have to maintain permissions for different user sets.
Based on these things please find my suggestion :
1. It is better to maintain a separate repo for each project in Git
2. You can restrict the set of users working on each project
3. It is easy to pull the code related to the particular project like for C# copy you can get it in visual studio using C# repo and For Java copy you can get it in eclipse using Java Repo.
Upvotes: 3 [selected_answer] |
2018/03/22 | 1,462 | 7,093 | <issue_start>username_0: I'm trying to let my Android Wear watch face determine the current location of the device. This has worked before but after uninstalling and reinstalling the package, it just fails. I think I did everything right and it has already worked like that. I have no idea what the issue is or even how to catch it. Here's the relevant code:
```
class MyWatchFaceService : CanvasWatchFaceService() {
override fun onCreateEngine(): Engine {
return Engine()
}
inner class Engine : CanvasWatchFaceService.Engine() {
private lateinit var fusedLocationClient: FusedLocationProviderClient
private var lastKnownLocation: Location? = null
override fun onCreate(holder: SurfaceHolder) {
super.onCreate(holder)
fusedLocationClient = LocationServices.getFusedLocationProviderClient(this@MyWatchFaceService)
updateLocation()
}
fun updateLocation() {
Logger.getAnonymousLogger().info("updateLocation")
try {
fusedLocationClient.lastLocation
.addOnSuccessListener { location: Location? ->
if (location != null) {
// Location available, use it and update later
Logger.getAnonymousLogger().info("- location available")
lastKnownLocation = location
}
}
.addOnFailureListener {ex: Exception ->
Logger.getAnonymousLogger().warning("- location NOT accessible (inner): " + ex.toString())
}
} catch (ex: SecurityException) {
// Nothing we can do, no location available
Logger.getAnonymousLogger().warning("- location NOT accessible: " + ex.toString())
}
Logger.getAnonymousLogger().info("updateLocation (end)")
}
}
}
```
I then find this in the log:
```
03-22 09:41:59.521 7390-7390/de.unclassified.watchface1 I/null: updateLocation
03-22 09:41:59.536 7390-7390/de.unclassified.watchface1 I/null: updateLocation (end)
03-22 09:41:59.830 7390-7405/de.unclassified.watchface1 E/AndroidRuntime: FATAL EXCEPTION: GoogleApiHandler
Process: de.unclassified.watchface1, PID: 7390
java.lang.SecurityException: Client must have ACCESS_COARSE_LOCATION or ACCESS_FINE_LOCATION permission to perform any location operations.
at android.os.Parcel.readException(Parcel.java:1684)
at android.os.Parcel.readException(Parcel.java:1637)
at com.google.android.gms.internal.zzeu.zza(Unknown Source)
at com.google.android.gms.internal.zzcfa.zzif(Unknown Source)
at com.google.android.gms.internal.zzcfd.getLastLocation(Unknown Source)
at com.google.android.gms.internal.zzcfk.getLastLocation(Unknown Source)
at com.google.android.gms.location.zzg.zza(Unknown Source)
at com.google.android.gms.common.api.internal.zze.zza(Unknown Source)
at com.google.android.gms.common.api.internal.zzbo.zzb(Unknown Source)
at com.google.android.gms.common.api.internal.zzbo.zzaiw(Unknown Source)
at com.google.android.gms.common.api.internal.zzbo.onConnected(Unknown Source)
at com.google.android.gms.common.internal.zzac.onConnected(Unknown Source)
at com.google.android.gms.common.internal.zzn.zzakr(Unknown Source)
at com.google.android.gms.common.internal.zze.zzw(Unknown Source)
at com.google.android.gms.common.internal.zzi.zzaks(Unknown Source)
at com.google.android.gms.common.internal.zzh.handleMessage(Unknown Source)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.os.HandlerThread.run(HandlerThread.java:61)
03-22 09:41:59.843 7390-7405/de.unclassified.watchface1 I/Process: Sending signal. PID: 7390 SIG: 9
```
So it does call my `updateLocation` function, then leaves again, and then there is an exception. But it's not from calling my code as far as I can see. Where does it come from? It doesn't have a stack trace with source files.
The package already has all relevant permissions, as before, along with some more for other tasks.
```
```
So what's going on here and why does neither the try/catch nor the failure listener do something?<issue_comment>username_1: COARSE Location is dangerous, hence, Google forces you to request it in runtime, just declare in Android Manifest is not enough. Please refer this link for a sample: <https://developer.android.com/training/permissions/requesting.html>
A quick code is here:
```
if (ContextCompat.checkSelfPermission(thisActivity,
Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(thisActivity,
arrayOf(Manifest.permission.ACCESS_FINE_LOCATION),
0x0)
}
```
You should request both Fine and Coarse permissions.
Upvotes: 1 <issue_comment>username_2: Before you start the service, or better, provide the user with that service, you need to make sure that they permit giving you their coarse/fine location, thus you need to give them the option in an Activity.
Think of it this way, you service runs in `background` and you need the user's permission to do your work, and you cannot assume that the user is present when the service is running. so you have to require the permission when the user is present, which is when the Activity is running.
Upvotes: 0 |
2018/03/22 | 402 | 1,330 | <issue_start>username_0: I can not run in the single `.js` file, if there is the `import xxx from xxx`.
`[](https://i.stack.imgur.com/AR5nu.jpg)`
I use the single file to debug the imported `ts_config`, how can I do this in WebStorm?
---
**EDIT-1**
The configuration choices are bellow:
[](https://i.stack.imgur.com/xUK3Z.jpg)
Tell me how to do with this?<issue_comment>username_1: You are using older version of `nodejs` and `import` keyword is not supported in v6.6. Please use version 8 or above for `import` keyword to work without using any transpiler like babel.
Upvotes: 1 <issue_comment>username_2: The functionality you are trying to use is part of the `ES Modules` specification.
However, [`ES Modules`](https://nodejs.org/api/esm.html#esm_ecmascript_modules) are NOT stable in `Node.js` as of version `v9.9.0`, and should not be used in production.
This functionality is under development, and expected to be stable-released with `Node.js v10.0.0`.
Right now, you can do:
```
const ts_config = require('./tsconfig.json);
```
Upvotes: 2 [selected_answer]<issue_comment>username_3: Are you exporting your tsConfig?
```
export default
{
// json here...
}
```
Upvotes: 0 |
2018/03/22 | 369 | 1,416 | <issue_start>username_0: I currently have a situation where templates for the cells of a DataGrid are created at runtime because the property names are dynamic and not known at design time. For example the "ColumnName" is used here (from a DataColumn) as the path for the Binding to get a colour to fill an ellipse:
```
myCellTemplate = " " &
""
```
Is there any way I can achieve the same but have my DataTemplate in a ResourceDictionary instead of in code behind? Being able to edit the templates in the usual manner would be much more preferable.
Thanks.<issue_comment>username_1: You are using older version of `nodejs` and `import` keyword is not supported in v6.6. Please use version 8 or above for `import` keyword to work without using any transpiler like babel.
Upvotes: 1 <issue_comment>username_2: The functionality you are trying to use is part of the `ES Modules` specification.
However, [`ES Modules`](https://nodejs.org/api/esm.html#esm_ecmascript_modules) are NOT stable in `Node.js` as of version `v9.9.0`, and should not be used in production.
This functionality is under development, and expected to be stable-released with `Node.js v10.0.0`.
Right now, you can do:
```
const ts_config = require('./tsconfig.json);
```
Upvotes: 2 [selected_answer]<issue_comment>username_3: Are you exporting your tsConfig?
```
export default
{
// json here...
}
```
Upvotes: 0 |
2018/03/22 | 1,198 | 3,955 | <issue_start>username_0: I have a window tool named "**Run Dashboard**" in Project A, but I can't activate this window in Project B. Does anyone know how to solve this? This feature appeared in IntelliJ IDEA version 2017.3.
This is what I see in Project A:

This is what I see in Project B:

This option is present but not activatable out in Project B:

but it's activatable in Project A:
<issue_comment>username_1: Add the run configurations to the **Configurations available in Run Dashboard** list in the [Edit Run/Debug Configurations dialog](https://www.jetbrains.com/help/idea/creating-and-editing-run-debug-configurations.html) under the **Defaults** (**Templates** in the [current IDE versions](https://i.stack.imgur.com/rtMoq.png)) node:
[](https://i.stack.imgur.com/KUhJv.png)
In Spring Boot projects Run Dashboard becomes enabled automatically if you have more than one run/debug configuration of this type.
Upvotes: 7 [selected_answer]<issue_comment>username_2: @username_1 is right, you need to have more than one "Spring boot run/debug configuration". Try to duplicate the one you already have and IntelliJ will automaticaly prompt you to run the dashboard.
Upvotes: 3 <issue_comment>username_3: I use Idea 2019.3 and this is how I managed to activate it.
1. Open Services Tool Window (my shortcut is ALT+8)
2. Add your Spring boot application if Idea didn't automatically recognized it.
[](https://i.stack.imgur.com/NnheR.png)
[](https://i.stack.imgur.com/d65mB.png)
Upvotes: 2 <issue_comment>username_4: My project is Spring Cloud project. So I add Spring Boot with the below flow.
**Edit Configuratio**n
[](https://i.stack.imgur.com/RdZk7.png)
Select **Default** > **Configurations available in Run Dashboard** > add **Spring Boot** > **Apply** > **OK**
[](https://i.stack.imgur.com/bcOoH.png)
Then we can see the **Run Dashboard** view in the left down side.
[](https://i.stack.imgur.com/6JAZv.png)
Upvotes: 0 <issue_comment>username_5: I use IntelliJ IDEA ULTIMATE 2019.1 version.
Steps to activate the feature: Run -> Edit Configurations...-> Templates -> Add "**Spring Boot**"
[](https://i.stack.imgur.com/ch717.png)
Upvotes: 2 <issue_comment>username_6: ***In Intellij 2020*** now Dashboard is by the name of **Services** see below screenshot and by default, the view is like this
[](https://i.stack.imgur.com/kDQda.png)
To get back to the old view of the **initial version of spring-dashboard**.
Right-click on Services -> Enable '**Show Service Tree**'
[](https://i.stack.imgur.com/V6ZEg.png)
[](https://i.stack.imgur.com/te6ue.png)
Upvotes: 3 <issue_comment>username_7: step1: enter "Services" tag
[](https://i.stack.imgur.com/BV99p.png)
step2: click on "add service" and choose "Add Configuration Type" with "Spring boot" selected.
[](https://i.stack.imgur.com/ZS5lA.png)
Upvotes: 0 |
2018/03/22 | 461 | 1,650 | <issue_start>username_0: I just recently incurred a lot of problem with selenium, especially with clicking the button and switch to the dialog box.
The main problem is that I can run it in my own laptop the Dell E7250 with is 12.5", but when I moved it to another computer which is also Dell but 14", the button cannot be clicked and all the code seems to be useless. While it did run well in my own laptop.
So I make a guess, that selenium performance will be affected by the dimension of the device, is it correct?
Hi, this is my code, I can run it with the 12.5" device, but when I transferred to the Dell E7250 device, it can no longer run.
[My code](https://drive.google.com/file/d/13Y3HOxWJpCb2GsiNgTBvRtyVgL6cKDTZ/view?usp=sharing).<issue_comment>username_1: Try using [`driver.set_window_size()`](http://selenium-python.readthedocs.io/api.html) so you can work with a constant window size across different devices.
Of course, I guess if you set a really high number for the window size you might have performances issues. But you can work with a small window size and scroll to your element using something like [this](https://stackoverflow.com/questions/3401343/scroll-element-into-view-with-selenium).
Upvotes: 1 <issue_comment>username_2: Try to use the following code:
```
driver.set_window_size("your_width", "your_height", driver.window_handles[0])
```
where `driver.window_handles[0]` is the applied main window in the browser. Also, the last parameter is optional (can be omitted) and applied by default to the main window.
In such a way, you can test your responsive markup for any devices.
Hope it helps you!
Upvotes: 2 |
2018/03/22 | 398 | 1,251 | <issue_start>username_0: I was wondering if there is a way to switch a column under an other one using a function. Basically if I have a dataframe as follow:
```
a <- data.frame("A" = 1:5, "B" = 2:6)
A B
1 1 2
2 2 3
3 3 4
4 4 5
5 5 6
```
I would like to get something like:
```
A
1 1
2 2
3 3
4 4
5 5
6 2
7 3
8 4
9 5
10 6
```<issue_comment>username_1: Try using [`driver.set_window_size()`](http://selenium-python.readthedocs.io/api.html) so you can work with a constant window size across different devices.
Of course, I guess if you set a really high number for the window size you might have performances issues. But you can work with a small window size and scroll to your element using something like [this](https://stackoverflow.com/questions/3401343/scroll-element-into-view-with-selenium).
Upvotes: 1 <issue_comment>username_2: Try to use the following code:
```
driver.set_window_size("your_width", "your_height", driver.window_handles[0])
```
where `driver.window_handles[0]` is the applied main window in the browser. Also, the last parameter is optional (can be omitted) and applied by default to the main window.
In such a way, you can test your responsive markup for any devices.
Hope it helps you!
Upvotes: 2 |
2018/03/22 | 359 | 1,342 | <issue_start>username_0: I want to do a word embedding + BLSTM in keras using a functional model. I have to declare the input as:
```
inputs = Input(shape=(X,))
```
Which should be the value of `X` here? Since the inputs will be sentences, I am not very sure what I should put in there.<issue_comment>username_1: Well one way or the other keras always need multidimensional numpy arraysas input.
The first dimension, which you don't have to specify is the batch\_size. Keras will set it automatically to None.
I don't know how you want to do your embedding but one thing you could insert is something like this: (batch\_size, len of sentence, number of characters)
then your X would be (len of sentence, number of characters)
Upvotes: 0 <issue_comment>username_2: For [Keras LSTM](https://keras.io/layers/recurrent/) the input tensor must be of dimensions `(batch_size, timesteps, input_dim)`. If you are not using `stateful=True` then specify `batch_size` of `None`, e.g. `inputs = Input(shape=(None, Tx, Xn))`, where `Tx` is the sentence length. `Xn` is going to be the word index which you then map through `Embedding` layer.
See [Using pre-trained word embeddings in a Keras model](https://blog.keras.io/using-pre-trained-word-embeddings-in-a-keras-model.html) for details of how to feed sentences into `Embedding` layer.
Upvotes: 1 |
2018/03/22 | 1,336 | 2,692 | <issue_start>username_0: I have three matrices:
```
A = [1 2 3;
4 5 6;
7 8 9]
B = [10 11 12;
13 14 15;
16 17 18;
19 20 21;
22 23 24;
25 26 27]
C = [28 29 30;
31 32 33;
34 35 36;
37 38 39;
40 41 42;
43 44 45;
46 47 48;
49 50 51;
52 53 54]
```
I want to merge one row from `A`, two rows from `B`, three rows from `C` to get a new matrix `D`:
```
D = [ 1 2 3;
10 11 12;
13 14 15;
28 29 30;
31 32 33;
34 35 36;
4 5 6;
16 17 18;
19 20 21;
37 38 39;
40 41 42;
43 44 45;
7 8 9;
22 23 24;
25 26 27;
46 47 48;
49 50 51;
52 53 54]
```
How to do this?<issue_comment>username_1: You can use a *for* loop and *vertcat* to perform what you are requesting.
```
D=[];
for aa = 1:length(A(:,1))
D = vertcat(D,A(aa,:),B((aa*2-1):(aa*2),:),C((aa*3-2):(aa*3),:));
end
D =
1 2 3
10 11 12
13 14 15
28 29 30
31 32 33
34 35 36
4 5 6
16 17 18
19 20 21
37 38 39
40 41 42
43 44 45
7 8 9
22 23 24
25 26 27
46 47 48
49 50 51
52 53 54
```
edit: As mentioned by <NAME>, this code isn't efficient especially when arrays get very large. an indexing method and pre-aliquating variables is a much better method.
Upvotes: 1 <issue_comment>username_2: You will end up with `18` rows. You can find the rows for each of your matrices using
```
mod(1:18,6)
```
which returns
```
[1 2 3 4 5 0 1 2 3 4 5 0 1 2 3 4 5 0]
```
So you want the rows of `A` to correspond to `1` in the above vector, `B` is for `[2,3]` and `C` for `[4,5,0]`.
Initialize a matrix of zeros:
```
D = zeros(18,3)
```
put in `A`
```
D(mod(1:18,6)==1,:) = A
```
similarly for `B` and `C`
```
D(ismember(mod(1:18,6),[2,3]),:) = B
D(ismember(mod(1:18,6),[4,5,0]),:) = C
```
It's neater to make some intermediate variables:
```
n = size([A;B;C],1)
D = zeros(n,size(A,2))
idx = mod(1:n,6)
idx_A = idx==1
idx_B = ismember(idx,[2,3])
idx_C = ismember(idx,[4,5,0])
D(idx_A,:) = A
D(idx_B,:) = B
D(idx_C,:) = C
```
Upvotes: 3 [selected_answer]<issue_comment>username_3: To solve your particular problem, only with indexing.
```
D=zeros(size([A;B;C],1),size(A,2)) % Intializing
D(1:6:end,:)=A; % We want 1rA, 2rB, 3rC, so row of A are in row 1, 7, etc
D(2:6:end,:)=B(1:2:end,:); % 1st row of B are in row 2, 8, etc
D(3:6:end,:)=B(2:2:end,:); % 2nd row of B are in row 3, 9, etc
D(4:6:end,:)=C(1:3:end,:); % etc
D(5:6:end,:)=C(2:3:end,:);
D(6:6:end,:)=C(3:3:end,:);
```
Upvotes: 0 |
2018/03/22 | 393 | 1,559 | <issue_start>username_0: When I want to refresh my tableView from the Main Thread it gives me this error: Thread 1: fatal error unexpectedly found nil while unwrapping an optional value which meant that the tableView doesn't have an outlet to the ViewController. But the tableView is linked to the ViewController. What am I doing wrong?
This is the error:
[](https://i.stack.imgur.com/FB0Wj.png)
This is the ViewController and outlets:
[](https://i.stack.imgur.com/YHAe2.png)
```
DispatchQueue.main.sync(){
print("Requestlist Finished Downloading")
if(Constants.activeViewController == 1){
self.tableViewRequestlist .reloadData()
Constants.busyRequest = false
}
else{
Constants.busyRequest = false
}
Constants.requestlistDownloaded = true
}
```<issue_comment>username_1: One possibility is that the viewcontroller gets deinitilized due to some reason before loading any views. To check that, put a breakpoint in viewDidLoad() method and another in the deinit() method.
If this is not the case then the IBoutlets must have not been linked with the viewcontroller.
Upvotes: 0 <issue_comment>username_2: Use `self.tableViewRequestlist.reloadData()` instead of
`self.tableViewRequestlist .reloadData()`
Though Xcode doesn't throw a compile time error for this but compiler will look for variable name without space.
Upvotes: 2 [selected_answer] |
2018/03/22 | 709 | 2,090 | <issue_start>username_0: I know next to nothing about SQL I am trying to make an SQL Query in Microsoft SQL Server Management Studio where the records are received from within a dynamic period (`24th of last month - 23rd of this month`). Currently I need to edit the dates manually or add them in via an excel VBA macro where the two points in time are declared as two variants. I've been looking around the internet, trying a few things like:
```
WHERE DATEPART(m,day_id)=DATEPART(m,DATEADD(m,-1,getdate()))
AND DATEPART (yyyy,day_id)=DATEPART(yyyy,DATEADD(m,-1,getdate()))
```
but this doesn't count for 24th-23rd and gives a syntax error.
Here's my code where I need to manually edit dates:
```
SELECT
reviewer_name,
CAST(ddd_id AS date) AS day_id,
report_id,
report_name,
amount_events,
group_name,
percent_checked_events,
comment AS SPL_comment
FROM reports_history_GA
WHERE (closed != 1
AND ddd_id > '2017-01-01'
AND [percent_checked_events] != '100'
AND report_name NOT LIKE '%ther_jo%'
AND report_name NOT LIKE 'QATeam'
AND comment NOT LIKE '%escal%')
OR (ddd_id <= '2018-02-23'
AND check_start_date > '2018-02-23'
AND comment NOT LIKE '%escal%')
ORDER BY dd_id ASC
```<issue_comment>username_1: this will gives you the dates
```
select [24th of last month] = dateadd(month, datediff(month, 0, getdate()) - 1, 23),
[23rd of current month] = dateadd(month, datediff(month, 0, getdate()), 22)
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: ```
SELECT CAST('24 '+ RIGHT(CONVERT(CHAR(11),DATEADD(MONTH,-1,GETDATE()),113),8) AS date) AS LastMonth,
CAST('23 '+ RIGHT(CONVERT(CHAR(11),GETDATE(),113),8) AS date) AS CurrentMonth
```
Output:
```
LastMonth CurrentMonth
2018-02-24 2018-03-23
```
Upvotes: 1 <issue_comment>username_3: Here's alternative to accepted answer:
```
select cast(dateadd(month,-1,dateadd(day,24 - datepart(day,getdate()),getdate())) as date) [24th of previous month],
cast(dateadd(day,23 - datepart(day,getdate()),getdate()) as date) [23rd of current month]
```
Upvotes: 1 |
2018/03/22 | 595 | 1,990 | <issue_start>username_0: When checking out the length property on a string I made a mistake and forgot the quotes around `length`. Instead of an error, one of the characters appeared from the string.
```
const string = 'name'
s[length]
>> "a"
```
I have done other combinations and usually get the second letter returned. So is the word `length` being converted into a Boolean, which is then converted to a number? Or, is something else going on?
Update. this is all I did:
```
const a = [1,2,3]
>> undefined
a["length"]
>> 3
const s = 'name'
>> undefined
s[length]
>> "a"
s['length']
>> 4
length
>> 1
a[length]
>> 2
```<issue_comment>username_1: In the default scope, length will evaluate to [window.length](https://developer.mozilla.org/en-US/docs/Web/API/Window/length), which is the number of frames or iframes in the window (usually 0, but in your case maybe 1?)
Edit: A quick look at the meaning of the different examples in your updated question.
```
const a = [1,2,3]; // Array of length 3
a["length"]; // equals a.length , 3
const s = 'name'; // String of length 4
s[length]; // s[window.length], s[1], 'a'
s['length']; // equals s.length, 4
length; // equals window.length, 1
a[length] // equals a[window.length], a[1] , 2
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: Usually you do `s.length` as length is property of String.
If you have `length` variable somewhere in your code, then it's typecasted to integer.
If you do not have it, then `undefined` is converted to integer.
---
`s[length]` converts to `s[0]` in your case
Upvotes: 0 <issue_comment>username_3: Not an answer, but a general piece of advice:
use `s.length` instead of `s['length']`
You avoid the mistake you just ran into.
I personally only use square brackets when I'm accessing values in a plain old array or when I need to use a variable or a property name that compilers don't like (ie. `s[myVar]` or `s['some-property']`).
Upvotes: 1 |
2018/03/22 | 472 | 1,621 | <issue_start>username_0: I have custom structure url for wordpress permalinks. How to setup the permalinks like /blog/%category%/%postname%. but this permalink structure is not working.
For example blog url should be:
```
/blog/categoryname/postname
```<issue_comment>username_1: In the default scope, length will evaluate to [window.length](https://developer.mozilla.org/en-US/docs/Web/API/Window/length), which is the number of frames or iframes in the window (usually 0, but in your case maybe 1?)
Edit: A quick look at the meaning of the different examples in your updated question.
```
const a = [1,2,3]; // Array of length 3
a["length"]; // equals a.length , 3
const s = 'name'; // String of length 4
s[length]; // s[window.length], s[1], 'a'
s['length']; // equals s.length, 4
length; // equals window.length, 1
a[length] // equals a[window.length], a[1] , 2
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: Usually you do `s.length` as length is property of String.
If you have `length` variable somewhere in your code, then it's typecasted to integer.
If you do not have it, then `undefined` is converted to integer.
---
`s[length]` converts to `s[0]` in your case
Upvotes: 0 <issue_comment>username_3: Not an answer, but a general piece of advice:
use `s.length` instead of `s['length']`
You avoid the mistake you just ran into.
I personally only use square brackets when I'm accessing values in a plain old array or when I need to use a variable or a property name that compilers don't like (ie. `s[myVar]` or `s['some-property']`).
Upvotes: 1 |
2018/03/22 | 684 | 2,382 | <issue_start>username_0: I'm trying to seed my database. And currently, I'm trying to get the price of a product that has the ID of `$index`. My seeder looks like this.
```
foreach(range(1,25) as $index)
{
DB::table('orderitems')->insert([
'order_id' => rand(1, 25),
'product_id' => $index,
'price' => '',
'created_at' => Carbon::now(),
'updated_at' => Carbon::now(),
]);
}
```
I foreach this seed 25 times. What I'm trying to achieve is to get the price of each product with the given id. Say, for instance, product\_id is 10. I want the price of the product with the ID 10. The relations are fine. I can do something like $product->price and it works fine. How can I achieve this?
the database looks like this
```
Products
name
description
price
period
```
Thanks in advance!<issue_comment>username_1: You can get product price by product id using query like code given as bellow:
```
foreach(range(1,25) as $index)
{
$product = DB::table("products")->where('id',$index)->first();
DB::table('orderitems')->insert([
'order_id' => rand(1, 25),
'product_id' => $index,
'price' => $product->price,
'created_at' => Carbon::now(),
'updated_at' => Carbon::now(),
]);
}
```
Upvotes: 2 [selected_answer]<issue_comment>username_2: you can try this way.
```
foreach(range(1,25) as $index)
{
$price = App\Products::->find($index)->price;
DB::table('orderitems')->insert([
'order_id' => rand(1, 25),
'product_id' => $index,
'price' => $price,
'created_at' => Carbon::now(),
'updated_at' => Carbon::now(),
]);
}
```
Upvotes: 0 <issue_comment>username_3: ```
'price' => Product::where('id',$index)->first()->price,
```
Upvotes: 2 <issue_comment>username_4: Try this:
```
$range = range(1,25);
$productIds = Product::whereIn('id', $range)->pluck('price', 'id');
foreach($range as $index)
{
DB::table('orderitems')->insert([
'order_id' => rand(1, 25),
'product_id' => $index,
'price' => $productIds[$index] ?? null,
'created_at' => Carbon::now(),
'updated_at' => Carbon::now(),
]);
}
```
Upvotes: 1 |
2018/03/22 | 1,014 | 2,694 | <issue_start>username_0: I have 2 for loops:
```
for (int i = n; i >= 1; i -= 2)
{
....
}
for(int i = 3; i <= n; i += 2)
{
....
}
```
which goes like, if `n = 7`, then `i` will get the values (in that order):
```
7, 5, 3, 1, 3, 5, 7
```
the code is the same is the for loops. It would be better if I could merge these two for loops. I'm new to C#. Any suggestions?
Edit: `n` is always odd<issue_comment>username_1: I'm not sure it will help, but here is one way to get that output using a single for loop:
```
var list = new List() {1};
for(var i = 3; i <= n; i+=2)
{
list.Insert(0, i);
list.Add(i);
}
// if n is 7, list now contains 7,5,3,1,3,5,7.
```
[You can see a live demo on rextester.](http://rextester.com/PXUVT60211)
Upvotes: 2 [selected_answer]<issue_comment>username_2: It was quite fun to do so I will post my answer. Not sure it is better than just extracting the content of the loop in a seperate method.
```
using System.Linq;
var n = 18;
var odds = Enumerable.Range(1,n-1).Where(i=>i%2==1).ToList();
var reverseOdds = new List(odds);
reverseOdds.Reverse();
var indexes = reverseOdds.Concat(odds.Skip(1));
and then your loop
foreach (var index in indexes)
{
...
}
```
Upvotes: 2 <issue_comment>username_3: Why not *extract* the loops as a *method*? Especially if
>
> the code is the **same** is the for loops.
>
>
>
Something like this:
```
private static IEnumerable MyLoop(int n) {
for (int i = n; i >= 1; i -= 2)
yield return i;
// Let's support even n like 10
for (int i = n % 2 == 0 ? 2 : 3; i <= n; i += 2)
yield return i;
}
```
Then you can use it as a *loop*:
```
n = 7;
foreach (int i in MyLoop(7)) {
...
}
```
And can *easily play* with the method:
```
// Obtain an array: [8, 6, 4, 2, 0, 2, 4, 6, 8]
int[] array = MyLoop(8).ToArray();
// Join items and print them on the console
Console.Write(string.Join(", ", MyLoop(7)));
```
Outcome:
```
7, 5, 3, 1, 3, 5, 7
```
Upvotes: 2 <issue_comment>username_4: "Simple" `for` loop:
```
int max = 7;
int min = 1;
bool up = false;
for (int i = max; i <= max; up |= (i == min), i = (up ? i + 2 : i - 2))
{
...
}
```
It's a shame you can't declare `up` inside the `for` loop definition itself...
Upvotes: 1 <issue_comment>username_5: It's my solution:
```
public static void Main(string[] args)
{
int N = 7;
Console.WriteLine("Sequence: " + string.Join(", ", genSequence(new List(), N)));
}
private static List genSequence(List lst, int n)
{
lst.Add(n);
if (n > 1)
genSequence(lst, n - 2).Add(n);
return lst;
}
```
live demo here: <http://rextester.com/QXNH15306>
Upvotes: 1 |
2018/03/22 | 817 | 3,058 | <issue_start>username_0: Here is how I can set selects using pure JS. Plain, simple and effective:
```
1
2
$("#mySelect").value = '1'
```
Not with React. This approach for some reason doesn't work in React. Select values are not updated. Why? How can I do in React?
I have a usual DOM with a `[reset]` button. On click `reset` the default browser behavior is to clear all form fields. Why I can't set select after it?
```
onReset(ev) {
// First I update state.
// And AFTER the DOM has been updated,
// I want to set selects programatically using refs
this.setState((state, props) => {
return {
birthday: moment(this.props.user.birthday),
error: null,
foo: this.props.foo
}
}, () => {
// These both approaches do not work! Why?
this.country.value = this.props.user.country;
this.role.value = this.props.user.role;
ReactDOM.findDOMNode(this.country).value = this.props.user.country;
ReactDOM.findDOMNode(this.role).value = this.props.user.role;
});
}
render() {
return (
{ this.onReset(ev) } }>
this.country = node } defaultValue={this.props.user.country}>
USA
Canada
this.role = node } defaultValue={this.props.user.role}>
Admin
User
)
}
```
I know I can do it using controlled components. Please don't advice it because I need to the approach above, I have quite a big form that is rendered slowly when every field is a controlled field.
Here is my original question <https://github.com/facebook/react/issues/12422>
UPD:
[](https://i.stack.imgur.com/9Clu3.png)<issue_comment>username_1: Its not that the value of select options are not changing with refs, but because there is nothing to trigger to DOM update, you aren't able to see the change. You should reset the select value before calling `setState` which shouldn't be a problem since states being set are not dependent on the dropdown state.
```
onReset(ev) {
// First I update state.
// Both reset and DOM update will happen simultaneously with this approach
this.country.value = this.props.user.country;
this.role.value = this.props.user.role;
this.setState((state, props) => {
return {
birthday: moment(this.props.user.birthday),
error: null,
foo: this.props.foo
}
});
}
```
Upvotes: 0 <issue_comment>username_2: Callback is not equal to asynchronous! Actually, you did have changed the value. It just then get reset by browser's reset event handler. Same as the above no-react demo. You can make it work this way:
```
this.setState((state, props) => {
return {
birthday: moment(this.props.user.birthday),
error: null,
foo: this.props.foo
}
}, () => {
// make it asynchronous
setTimeout(() => {
this.country.value = this.props.user.country;
this.role.value = this.props.user.role;
}, 0)
});
```
Upvotes: 2 [selected_answer] |
2018/03/22 | 1,057 | 3,298 | <issue_start>username_0: After reading and talking about Java 10s new reserved type name **`var`**
([JEP 286: Local-Variable Type Inference](http://openjdk.java.net/jeps/286)), one question arose in the discussion.
When using it with literals like:
```
var number = 42;
```
is `number` now an `int` or an `Integer`? If you just use it with comparison operators or as a parameter it usually doesn't matter thanks to autoboxing and -unboxing.
But due to `Integer`s member functions it *could matter*.
So which type is created by `var`, a primitive `int` or class `Integer`?<issue_comment>username_1: `var` asks the compiler to infer the type of the variable from the type of the initializer, and the natural type of `42` is `int`. So `number` will be an `int`. That is what the [JLS example says](https://docs.oracle.com/javase/specs/jls/se10/html/jls-14.html#jls-14.4.1):
```
var a = 1; // a has type 'int'
```
And I would be surprised if it worked any other way, when I write something like this, I definitely expect a primitive.
If you need a `var` as boxed primitive, you could do:
```
var x = (Integer) 10; // x is now an Integer
```
Upvotes: 6 [selected_answer]<issue_comment>username_2: Let's test it. With jshell:
```
jshell> Integer boxed1 = 42000;
boxed1 ==> 42000
jshell> Integer boxed2 = 42000;
boxed2 ==> 42000
jshell> System.out.println(boxed1 == boxed2);
false
jshell> var infered1 = 42000;
infered1 ==> 42000
jshell> var infered2 = 42000;
infered2 ==> 42000
jshell> System.out.println(infered1 == infered2);
true
```
In the first comparison, the two variables are not the same; they're different instances. The second comparison is however true, hence an int must've been infered here.
Note: To try it at home, use values outside <-128, 128). Integer instances in that range are cached.
Upvotes: 3 <issue_comment>username_3: According to the [proposed specification changes](https://bugs.openjdk.java.net/browse/JDK-8151553) in 14.4.1 *Local Variable Declarators and Types*:
>
> If *LocalVariableType* is `var`, then let *T* be the type of the initializer expression when treated as if it did not appear in an assignment context, and were thus a standalone expression ([15.2](https://docs.oracle.com/javase/specs/jls/se9/html/jls-15.html#jls-15.2)). The type of the local variable is the upward projection of *T* with respect to all synthetic type variables mentioned by *T* (4.10.5).
>
>
>
In other words, the inferred type for the local variable is the type that the initializer expression would have if it were used as a standalone expression. `42` as a standalone expression has type `int`, ergo, the variable `number` is of type `int`.
*Upward projection* is a term defined in the spec changes that doesn't apply to simple cases like this.
Upvotes: 4 <issue_comment>username_4: The compiler treats `var number = 42;` similarly to `int number = 42;`
```
public void method(Integer i) {
System.out.print("Integer method");
}
public void method(int i) {
System.out.print("int method");
}
var n = 42; // n has type 'int'
method(n); // => "int method"
```
And auto-boxing when:
```
public void method(Integer i) {
System.out.print("Integer method");
}
var n = 42; // a has type 'int'
method(n); // => "Integer method"
```
Upvotes: 1 |
2018/03/22 | 1,607 | 4,543 | <issue_start>username_0: Having the 2 following arrays:
```
[
{"id":1,"value":40},
{"id":2,"value":30}
]
```
And:
```
[
{"userId":1,"worth":20},
{"userId":2,"worth":10}
]
```
What I want to have in the end, is the following result:
```
[
{"id":1,"value":20},
{"id":2,"value":10}
]
```
So here, I want to replace in the first array, the values with those in the second array, according to the ìd`. I made something like that:
```
foreach ($array2 as $k => $v) {
array_filter($array1), function($item) use($value) {
$item['id'] == $v['userId'] ? $item['value'] = $v['worth'] :$item['value'] = $item['value'];
});
}
```
It is working for those given arrays, but if you have arrays with more than 1 million data, it will never be done !
The question is, if there are some PHP functions which can do this hard work?
Update
------
The arrays format is updated and now I should use the following format:
```
[
0 => stdClass {"id":1,"value":40},
1 => stdClass {"id":2,"value":30}
]
```
And:
```
[
0 => Statement {"userId":1,"worth":20},
1 => Statement {"userId":2,"worth":10}
]
```
Result of Var\_dump:
--------------------
Array 1:
```
array (size=2)
0 =>
object(stdClass)[2721]
public 'value' => float 84
public 'id' => int 1229
1 =>
object(stdClass)[2707]
public 'value' => float 144
public 'id' => int 1712
```
Array 2:
```
array (size=2)
0 =>
object(Bank\Accounting\Statement)[2754]
public 'worth' => float 572
public 'userId' => int 1229
1 =>
object(Bank\Accounting\Statement)[2753]
protected 'worth' => float 654
protected 'userId' => int 1712
```<issue_comment>username_1: You can use `array_column` to make the `userId` as the key and `worth` as the value.
Use `map` to reiterate the first array. Check if the key exist, if exist replace the `value`.
```
$arr1 = [{"id":1,"value":40},{"id":2,"value":30}];
$arr2 = [{"userId":1,"worth":20},{"userId":2,"worth":10}];
//Use array_column to make the userId as the key and worth as the value.
$arr2 = array_column($arr2, 'worth', 'userId');
//Use `map` to reiterate the first array. Check if the key exist on $arr2, if exist replace the `value`. If not replace it with empty string.
$results = array_map( function($v) use ( $arr2 ) {
$valueInArr2 = array_search($v->id, array_column($arr2, 'userId'));
$v->value = $valueInArr2 ? $valueInArr2 : "";
return $v;
}, $arr1);
echo "
```
";
print_r( $results);
echo "
```
";
```
This will result to:
```
Array
(
[0] => Array
(
[id] => 1
[value] => 20
)
[1] => Array
(
[id] => 2
[value] => 10
)
)
```
---
**Update:** Using Object. I have not tested this.
```
$arr1 = .....;
$arr2 = .....;
//Make the object into array
$arr2 = array_reduce($arr2, function($c,$v) {
$c[ $v->userId ] = array(
'worth' => $v->worth;
'userId' => $v->userId;
);
return $c;
},array());
//Update the first array
$results = array_map( function( $v ) use ( $arr2 ) {
$val = array( 'id' => $v->id );
$val['value'] = isset( $arr2[ $v->id ] ) ? $arr2[ $v->id ] : "";
return $v;
}, $arr1);
```
Upvotes: 2 [selected_answer]<issue_comment>username_2: you can try this way (using laravel collection):
```
$arr1 = '[{"id":1,"value":40},{"id":2,"value":30}]';
$arr2 = '[{"userId":1,"worth":20},{"userId":2,"worth":10}]';
$arr1 = json_decode($arr1, true);
$arr2 = json_decode($arr2, true);
$col2 = collect($arr2);
foreach ($arr1 as &$value) {
$value['value'] = $col2->where('userId', $value['id'])->first()['worth'];
}
echo "
```
";
print_r($arr1);
```
```
Output:
```
Array
(
[0] => Array
(
[id] => 1
[value] => 20
)
[1] => Array
(
[id] => 2
[value] => 10
)
)
```
Upvotes: 1 <issue_comment>username_3: After building a simple associative lookup/dictionary array, loop over the first array, modify the `value` elements by reference, and update the values if the id is found in the lookup. If the id is not found, leave the original value.
Code: ([Demo](https://3v4l.org/NhO39))
```
$arr1 = json_decode('[{"id":1,"value":40},{"id":2,"value":30}]', true);
$arr2 = json_decode('[{"userId":1,"worth":20},{"userId":2,"worth":10}]', true);
$lookup = array_column($arr2, 'worth', 'userId');
foreach ($arr1 as ['id' => $id, 'value' => &$value]) {
$value = $lookup[$id] ?? $value;
}
var_export($arr1);
```
Upvotes: 0 |
2018/03/22 | 730 | 2,644 | <issue_start>username_0: I want to protect a high-level risk feature with 2FA. Historically, we use
2FA SMS. I want to propose the same feature but ideally, I wish to be able
to integrate also native Keycloak OTP authenticator (more secure).
That' s why based on keycloak-sms-authenticator-sns https://github.com/nickpack/keycloak-sms-authenticator-sns> , I have
improved this authenticator (I will make a merge request soonly).
I have searched in Keycloak 3.4.3 documentation but using the same realm, I
haven't seen any feature to ask 2FA when the final user want to access to a
specific resource.
Role mechanism allows managing access (403 - 200) but it seems that it isn't
cover my use case.
I 'm not sure that UMA 2.0 could be offering this feature. Moreover, It
isn't yet implemented.
Level of assurance seems very well but it isn't yet implemented and it would
be difficult to do it.
I could include a servlet filter on the business application (JBoss adapter)
to route user to 2FA authenticator when he wants to access the resource.
But in this case, I have to propagate a state between Keycloak and Java
adapter to not ask 2FA code for each access.
It could be a little bit tricky in cluster mode (stateless service).
Have you any idea to cover this use case easily based on native keycloak
features?
If that isn't the case, in your opinion, what is the best solution (see
above)? (easiest integration for maintainability, clustering support and 2FA
technic agnostic)
Thank you for sharing your experience.<issue_comment>username_1: It seems that you are looking for a kind of Step-up authentication. This isn't yet implemented in Keycloak, but there's an existing jira ticket for this [here](https://issues.jboss.org/browse/KEYCLOAK-847).
There was also already a discussion on the [mailinglist](http://lists.jboss.org/pipermail/keycloak-user/2016-November/008311.html) (and maybe some other threads I didn't find currently).
I also stumbled upon a "[Conditional OTP Form Authenticator](https://gist.github.com/thomasdarimont/ad3aa0e36d33d067dba2)" from <NAME>, a very active Keycloak community commiter.
HTH in some way.
Upvotes: 3 <issue_comment>username_2: Keycloak will support OOTB step-up authentication in the next release (keycloak version 17). Nowadays this feature is not officially released, but you can test it building keycloak from source (branch: main).
On the other hand, here is article about [Keycloak step-up authentication-for Web Apps and API](https://embesozzi.medium.com/keycloak-step-up-authentication-for-web-and-api-3ef4c9f25d42) with some findings, perhaps It would help you.
Upvotes: 2 |
2018/03/22 | 1,545 | 5,617 | <issue_start>username_0: This is a question I got in an interview. It is little hard to explain, please bear with me.
Imagine a Railway Ticketing Counter.
* Initially there are 3 counters.
* There is a security guard who keeps a check on the people so that no one breaks the line.
* Each counter has 2 people waiting in line. The people waiting in line came in as per the alphabetical order.
* A new 4th counter is being opened. And there are two new persons G and H about to join the line.
You are the security guard, now you get to choose who can be processed at the new counter.
[](https://i.stack.imgur.com/P4xev.png)
Counters are marked 1, 2, 3 and 4 (blue boxes). People waiting in line are marked A, B, C and so on. Here A came first, followed by B and then C etc.
I was asked to give the answer and the logic behind the answer.
The interviewer kept on asking more questions on my answers.
For example - when I said,
* I will ask D and E to move to the 4th counter;
* G will stand behind A and H will stand behind B
The interviewer argued saying how is it that E and G get the same preference (priority).
After few minutes of such arguments, I told like this seems to be a simple scheduling problem which can easily be solved if there was a common queue and the security guard sends the next person on the queue to a vacant counter following FCFS.
[](https://i.stack.imgur.com/r9AN6.png)
However, the interviewer was not impressed.
Is there a different approach which I missed? What is the right way to answer such questions?
PS: I didn't get through this round :(<issue_comment>username_1: My suggestion would be
D->4, E->1, F->2, G->3, H->4
on the premise that each person will take the same amount of time at the counter. This way everyone will be processed in the right order.
If each person will take a different unknown time at the counter then a queue is the only valid solution (besides switching the lines each time someone got processed which is effectively the same).
Upvotes: 2 <issue_comment>username_2: If people are coming in alphabetical order AND each one get served in roughly the same time, then IMO the most "fair" solution would be to mode `D` to a new counter, move `E` after `A`, move `F` after `B` then let `G` and `H` to move in, i.e.:
```
1 2 3 4 1 2 3 4
---------- ----------
A B C >> A B C D
D E F E F G H
```
The logic is that since `A` came first, he should be served first, so `E` will get to the counter faster standing after `A` rather than standing after `B`.
**Update from the comments:**
To avoid many movements:
```
1 2 3 4 1 2 3 4 1 2 3 4
---------- ---------- ----------
A B C >> A B C D >> A B C D
D E F E F G E F H
G H
```
For four people in line:
```
1 2 3 4 1 2 3 4 1 2 3 4
---------- ---------- ----------
A B C A B C D A B C D
D E F >> E F H >> G E F H
G H I G I L J K I L
J K L J K M N O P
M N O P
```
Upvotes: 2 <issue_comment>username_3: Given my background in the topic and more years in the industry than I'll admit here ... :-) ... I have a hypothesis as to why you didn't make the next round: this is not so much a program design question as a behaviour question.
This class of interview question is often not about the solution, but about your problem-solving *approach*. I (interviewer) gave you a problem with several open possibilities. First of all, this is "obviously" a metaphor for an OS multi-processing situation. I want an ideal candidate to
1. Question the ticket-counter paradigm's applicability to the OS situation: what assumptions exist in the real world that don't apply to a process queue?
2. Determine the rubric for evaluating a solution.
3. Ask for more information on permitted operations.
4. Ask for a distribution of service times, arrival times, etc. to demonstrate knowledge of the scheduling paradigm.
5. Inquire about costs & trade-offs.
Armed with a better description of the problem, *now* I want you to work through a solution, consistently engaging your customer (me) in the general approach and the specifics. This is a critical part of the Agile approach, for instance. Also, I want to see how you explain things I don't understand.
Note that item #2 is *very* important: if your true customer for this is a corrupt security guard retiring at the end of the shift, then the correct solution might be to hold a bribery bidding war for access to the open counter.
Here's *your* homework for the next interview: what assumptions are necessary to make your given solution a good one? How can you validate those assumptions with your customer?
My immediate questions include the ones above, and ...
* What defines a good solution? best solution? unacceptable?
* What's the cost of moving a person from where they are to another place?
+ Can I take someone out of a window line and back into the queue?
+ Can I change order in the queue (i.e. common usage of "queue" rather than the canonical data structure)?
+ Can I switch someone directly from one window line to another?
* Do I *have* to serve every customer?
* Is that the entire queue, or is this a continuous process?
This is where my typing caught up with my thought processes, a fair point to stop.
Upvotes: 3 [selected_answer] |
2018/03/22 | 867 | 3,029 | <issue_start>username_0: I am using jquery 3.2.1 with .NET framework 4.5.2 MVC.
I have an jquery ajax call to an mvc controller. If the action is successful, the return is
```
return new HttpStatusCodeResult(200, "success message");
```
and when it fails,
```
return new HttpStatusCodeResult(400, "failure message");
```
and here is my javascript call:
```
var promise = $.ajax({
method: 'POST',
url: '/Home/TestAjaxAsync',
// ...
});
promise.done(function(results) {
console.log("got success: ");
console.log(results);
});
promise.fail(function(err) {
console.log("got error: ");
console.log(err);
});
```
all of this is working perfectly on local machine in visual studio IIS express, and when hosted locally. I can send the request and get "success message" and "failure message" in statusText property with status code.
But when hosted in production server remotely, this stops working. I am able to send the request successfully and receive the response successfully and get "success message" for 200 OK. But for 400, 401, 403 or any other error codes, the statusText is always "error". Sometimes, the custom message is shown in responseText as a YSOD with full html markup.
I have tried the following also but could not get it to working on production server at all.
```
return new HttpStatusCodeResult(HttpStatusCode.BadRequest, "failure message");
```<issue_comment>username_1: As by [jQuery Documentation](http://api.jquery.com/jquery.ajax/)
================================================================
>
> **jqXHR.done(function( data, textStatus, jqXHR ) {});**
>
>
> An alternative construct to the success callback option, refer to deferred.done() for implementation details.
>
>
> **jqXHR.fail(function( jqXHR, textStatus, errorThrown ) {});**
>
>
> An alternative construct to the error callback option, the .fail() method replaces the deprecated .error() method. Refer to deferred.fail() for implementation details.
>
>
>
The first argument of `done(function(...))` is `data`, but the first argument of `fail(function(...))` is `jqXHR`, which..
>
> is a superset of the browser's native XMLHttpRequest object
>
>
>
You should try
--------------
```
promise.fail(function (jqXHR) {
console.log("got error: ");
console.log(jqXHR.responseText);
});
```
or
```
promise.fail(function (jqXHR, textStatus) {
console.log("got error: ");
console.log(textStatus);
});
```
or
```
promise.fail(function (jqXHR, textStatus, errorThrown) {
console.log("got error: ");
console.log(errorThrown);
});
```
Depending on what works best for you.
Upvotes: 2 <issue_comment>username_2: >
> Add baseurl with your Ajax url parameter.
>
>
>
```
var geturl = window.location;
var baseurl = geturl.protocol + "//" +geturl.host + "//" + geturl.pathname.split('/')[1];
```
url : baseurl + 'controller/action'
Upvotes: 0 <issue_comment>username_3: try this when it fails:
```
throw new HttpException(400, "bad request");
```
Upvotes: 0 |
2018/03/22 | 784 | 2,619 | <issue_start>username_0: I am trying to transform an input list into a palindrome. For instance:
```
Input: [1,2,3]
Output: [1,2,3,3,2,1]
```
Basically I need to add a reversed list. My problem lies in the following:
```
palindrize::[a]->[a]
palindrize list | null list = []
palindrize (x:xs)=(x:xs)++revert(x:xs) where
revert list | null list =[]
revert (x:xs)= (revert xs):(x:[]) ---Here
```
How can I create a guard or a condition to when there is only one element create a list out of it (applying the `(myelement:[])`)? I would need somehow to say: `revert` can get a list or an element, if it's an element apply `(element:[])` on it.<issue_comment>username_1: I think you make things too complex. First of all, Haskell has already a [**`reverse :: [a] -> [a]`**](http://hackage.haskell.org/package/base-4.11.0.0/docs/Prelude.html#v:reverse) that reverses the list, so we can make it:
```
palindrize :: [a] -> [a]
palindrize l = l ++ reverse l
```
Furthermore there is no need to use a guard here. We can perform pattern matching: this is safer since the compiler can then guarantee us that all patterns are covered. So we can write it like:
```
revert :: [a] -> [a]
revert [] = []
revert (x:xs) = (revert xs):(x:[]) -- error!
```
But this will result in a type error. Indeed, the `(:)` constructor has type `(:) :: a -> [a] -> [a]`, but `revert xs` will result in type `[a]`. In situations like that one, it is best to use an *accumulator*: a parameter that we initialize for instance with the empty list, and then each recursive call update and at the end of the recursive process return. For example:
```
revert :: [a] -> [a]
revert = go []
where go xs [] = xs
go xs (x:ys) = go (x:xs) ys
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: First, you can not write `list : element`, nor `list : (element : [])` since types would not match: whatever is found at the left side of `:` must have the same type as the elements of the list found at the right side.
You can, however, append two lists using `++`, like `list ++ (element : [])` or `list ++ [element]`.
Second, to pattern match against a single element list, you can use
```
foo [] = ... -- empty list case
foo [x] = ... -- single element list case
foo (x1:x2:rest) = ... -- two elements or more case
```
If you prefer, the single element case can also be written `foo (x:[]) = ...`.
Note that `foo [] = ...` is equivalent to `foo list | null list = ...`, but simpler. If possible, forget guards: they should only be used when pattern matching is not enough.
Upvotes: 1 |
2018/03/22 | 2,984 | 11,989 | <issue_start>username_0: We are planning a migration from an on-premises TFS to VSTS very shortly. Ahead of the migration, I've run the pre-requisite Validation task and obtained a warning that the current TPC database size exceeds the maximum DacPac limit.
A snippet of the database validation is provided below:
```
The full database size is 187411 MB.
The database metadata size is 28145 MB.
The database blob size is 159266 MB.
The top 10 largest tables are:
===================================================
Table name Size in MB
dbo.tbl_Content 168583
dbo.tbl_BuildInformation2 3233
===================================================
The File owners are:
===================================================
Owner Size in MB
Build+Git 67410
TeamTest 59261
VersionControl 18637
```
It is obvious from the above that the dbo.tbl\_Content table is the main contributor to the excessive database size and from a VSTS operation perspective, Build+Git and TeamTest are the main culprits. My intention is therefore to focus on the above objects for any database clean up to reduce size.
Question is, how can I achieve this in the most effective and best possible way on the above three objects - dbo.tbl\_Content, Build+Git and TeamTest?<issue_comment>username_1: I've written an extensive post on all the ways to clean up TFS prior to import:
* <https://username_1.net/tfs-clean-up-your-project-collection/>
But remember that there is an alternate path that requires a temporary IaaS server setup in Azure with SQL Server and TFS/Azure DevOps Server installed on it. That path may be simpler and faster than trying to clean up what you have and is equally supported.
---
Extract below:
To prepare your TFS Project Collection for migration, you may want to remove (stale) old data to reduce the database size first.
Most actions are already documented here. Queries that can aid in detecting where your space is allocated are also found in this recent support ticket.
Delete old workspaces
---------------------
Deleting workspaces and shelvesets can reduce your migration and upgrade times considerably. either use the `tf` commandline or leverage a tool like the TFS SideKicks to identify and delete these.
Build results
-------------
Not just build results, but often overlooked the actual build records can take up a considerable amount of data. Use `tfsbuild destroy` (XAML) to permanently delete the build records. In the past, I've encountered clients who had 1.8 million "hidden" builds in their database and removing them shaved off quite a considerable amount of data. These records were kept around for the warehouse.
In case you run into very slow execution of tfsbuild, [you may need this patched version it has a few fixes that prevent it from trying to download all the build logs](https://www.dropbox.com/s/1ooujqx41yold01/TFSBuild_2015_patched.7z?dl=0) for every build in your system just to get to the build ids.
Old team projects
-----------------
Of course, destroying old team projects can give back a lot of data. Anything you don't need to send to azure helps. You could also consider splitting the collection and to leave behind the old projects. That will give you the option to detach that collection and store it somewhere, should you ever need that data again.
Redundant files
---------------
Deleted branches are a very common hidden size hog. When deleting things in TFVC, they are not actually deleted, they're just hidden. Finding deleted files and especially old development or feature branches can give you back a lot of data. Use `tf destroy` to get rid of them.
You may also want to look for checked in nuget package folders, those can quickly rack up a lot of space as well.
Code Lens index
---------------
Team Foundation Server 2013 introduced server side indexing of TFVC controlled files to allow Visual Studio access to data on who changed which files when directly in the UI. This server-side index can grow quite quickly depending on the size of your code base and churn.
You can control the index through the `tfsconfig codeindex` command. You can specify up to how long ago you want to index `/indexHistoryPeriod:#months`, delete the index altogether `/destroyCodeIndex` or exclude specific problematic files `/ignoreList:add $/path`.
Code Lens is also referenced to as Code Sense and Code Index internally in the product.
[More can be found here](https://learn.microsoft.com/en-us/visualstudio/ide/codeindex-command?view=vs-2015).
In case deleting the index times out, [you read this post on StackOverflow with additional guidance](https://serverfault.com/questions/958090/tfs-2015-codesense-cleanup/). Be careful, manually running SQL on the TFS collection DB's isn't supported.
Test Attachments
----------------
Ohh yes, especially when you use test attachments, these can grow like crazy, depending on your TFS version either use the built-in test attachment cleanup features or use the Test Attachment Cleaner from the TFS power tools.
XAML Builds
-----------
The build definitions themselves won't take a lot of database space, but the build results may. But those have been covered in a previous section.
In the past, I've had to patch tfbuid.exe to handle (very) large amounts of build records, as it tends to try and fetch all build data locally before proceeding with the delete action. You may need to rely on the TFS Client Object Model to achieve a similar result.
Git Repositories
----------------
You may have data in your git repositories that are no longer accessible due to force pushes or deleted branches. It's also possible that certain data in Git could be packed more efficiently. To clean your repositories you have to clone them locally, clean them up, delete the remote repo from TFS and push the cleaned copy to a new repository (you can use the same name as the old one). Doing this will break references with existing build definitions and you will have to fix these up. While you're at it, you could also run the [BFG repo Cleaner](https://rtyley.github.io/bfg-repo-cleaner/) and convert the repositories to enable Git-LFS support to handle large binary files in your repositories more elegantly.
```
git clone --mirror https://tfs/project/repo
# optionally run BFG repo cleaner at this point
git reflog expire --expire=now --all
git gc --prune=now --aggressive
git repack -adf
# Delete and recreate the remote repository with the same name
git push origin --all
git push origin --tags
```
Work item (attachments)
-----------------------
Work items can gather up a considerable amount of data, especially when people start attaching large attachments to them. You can use `witadmin destroywi` to delete work items with unreasonably large attachments. To retain the work item, but delete its attachments you can delete the attachments from the current work item and then clone it. After cloning, destroy the old work item to allow the attachments to be cleaned up.
Old work items that you no longer need (say the sprint items from 6 years ago) can also be deleted. [My colleague René has a nice tool that allows you to bulk-destroy by first creating the appropriate work item query](https://roadtoalm.com/2015/01/14/bulk-destroy-work-items-from-team-foundation-server/).
Be sure to run the cleanup jobs
-------------------------------
TFS often doesn't immediately prune data from the database, in many cases, it just marks stuff as deleted for later processing. To force the cleanup to happen immediately, run the following stored procedures on your Project Collection database:
```
EXEC prc_CleanupDeletedFileContent 1
# You may have to run the following command multiple times, the last
# parameter is the batch size, if there are more items to prune than the
# passed in number, you will have to run it multiple times
EXEC prc_DeleteUnusedFiles 1, 0, 100000
```
That 100000 at the end is the number of marked items to process. If you've deleted a lot of content you may need to run that last procedure a couple of times before everything will be deleted.
Other useful queries
--------------------
To identify how much data is stored in each section, there are a few useful queries you can run. The actual query depends on your TFS version, but since you're preparing for migration I suspect you're on TFS 2017 or 2018 at the moment.
Find the largest tables:
```
SELECT TOP 10
o.name,
SUM(reserved_page_count) * 8.0 / 1024 SizeInMB,
SUM(
CASE
WHEN p.index_id <= 1 THEN p.row_count
ELSE 0
END) Row_Count
FROM sys.dm_db_partition_stats p
JOIN sys.objects o
ON p.object_id = o.object_id
GROUP BY o.name
ORDER BY SUM(reserved_page_count) DESC
```
Find the largest content contributors:
```
SELECT Owner =
CASE
WHEN OwnerId = 0 THEN 'Generic'
WHEN OwnerId = 1 THEN 'VersionControl'
WHEN OwnerId = 2 THEN 'WorkItemTracking'
WHEN OwnerId = 3 THEN 'TeamBuild'
WHEN OwnerId = 4 THEN 'TeamTest'
WHEN OwnerId = 5 THEN 'Servicing'
WHEN OwnerId = 6 THEN 'UnitTest'
WHEN OwnerId = 7 THEN 'WebAccess'
WHEN OwnerId = 8 THEN 'ProcessTemplate'
WHEN OwnerId = 9 THEN 'StrongBox'
WHEN OwnerId = 10 THEN 'FileContainer'
WHEN OwnerId = 11 THEN 'CodeSense'
WHEN OwnerId = 12 THEN 'Profile'
WHEN OwnerId = 13 THEN 'Aad'
WHEN OwnerId = 14 THEN 'Gallery'
WHEN OwnerId = 15 THEN 'BlobStore'
WHEN OwnerId = 255 THEN 'PendingDeletion'
END,
SUM(CompressedLength) / 1024.0 / 1024.0 AS BlobSizeInMB
FROM tbl_FileReference AS r
JOIN tbl_FileMetadata AS m
ON r.ResourceId = m.ResourceId
AND r.PartitionId = m.PartitionId
WHERE r.PartitionId = 1
GROUP BY OwnerId
ORDER BY 2 DESC
```
If file containers are the issue:
```
SELECT
CASE
WHEN Container = 'vstfs:///Buil' THEN 'Build'
WHEN Container = 'vstfs:///Git/' THEN 'Git'
WHEN Container = 'vstfs:///Dist' THEN 'DistributedTask'
ELSE Container
END AS FileContainerOwner,
SUM(fm.CompressedLength) / 1024.0 / 1024.0 AS TotalSizeInMB
FROM
(SELECT DISTINCT LEFT(c.ArtifactUri, 13) AS Container,
fr.ResourceId,
ci.PartitionId
FROM tbl_Container c
INNER JOIN tbl_ContainerItem ci
ON c.ContainerId = ci.ContainerId
AND c.PartitionId = ci.PartitionId
INNER JOIN tbl_FileReference fr
ON ci.fileId = fr.fileId
AND ci.DataspaceId = fr.DataspaceId
AND ci.PartitionId = fr.PartitionId) c
INNER JOIN tbl_FileMetadata fm
ON fm.ResourceId = c.ResourceId
AND fm.PartitionId = c.PartitionId
GROUP BY c.Container
ORDER BY TotalSizeInMB DESC
```
Upvotes: 1 <issue_comment>username_2: My TFS 2015 server was hosting several GIT repositories, some having very large files (with LFS). Using TFS web interface, I deleted some test repos which was taking much storage in tbl\_content, I noticed that files were not removed from database.
I tried almost everything. tf delete is useless because repo was already removed.
Stored procedures prc\_\* did not help very much. Just reduced size from 50 GB to 41 GB
The only way to properly cleanup the tbl\_content database is following SQL query:
```
DELETE FROM tbl_content WHERE ResourceId IN (SELECT A.[ResourceId]
FROM [dbo].[tbl_Content] As A
WHERE A.ResourceId NOT IN (SELECT X.ResourceId FROM tbl_filemetadata as X)
AND A.ResourceId NOT IN (SELECT Y.ResourceId from tbl_filereference as Y))
```
This procedure took more than half an hour. After that I performed a database shrink. And now table size is 17 GB.
Now I will move all GIT repositories from TFS to self hosted Gitea server. Very lightweight and efficient server compared to greedy and unmaintenable TFS...
Upvotes: 0 |
2018/03/22 | 1,653 | 6,583 | <issue_start>username_0: I have declared some static variables in my solution as below,
```
using System;
using System.Collections.Generic;
using System.Configuration;
namespace SSPWAS.Utilities
{
public class Constants
{
public static string ApproverlevelL1 = "M23";
public static string ApproverlevelL2 = "Cre";
public static string ApproverlevelL3 = "Free34";
public static string ApproverlevelL4 = "CDF";
public static string ApproverlevelL5 = "FM";
}
}
```
My question is, If i try to set it the like below then i get the error as :
>
> An object reference is required for the non-static field, method, or
> property
>
>
>
```
using System;
using System.Collections.Generic;
using System.Configuration;
namespace SSPWAS.Utilities
{
public class Constants
{
public static string ApproverlevelL1 = getLevel("1");
public static string ApproverlevelL2 = getLevel("2");
public static string ApproverlevelL3 = getLevel("3");
public static string ApproverlevelL4 = getLevel("4");
public static string ApproverlevelL5 = getLevel("5");
}
}
public string getLevel(string levelID)
{
string levelName;
//logic here
return levelName;
}
```
So how can i achieve this?<issue_comment>username_1: Looks like you are trying to call an instance method (non-static) from a static property.
Try making your method static:
```
public string getLevel(string levelID)
{
string levelName;
//logic here
return levelName;
}
```
Upvotes: 1 <issue_comment>username_2: Do you mean this:
```
using System;
using System.Collections.Generic;
using System.Configuration;
namespace SSPWAS.Utilities
{
public static class Constants
{
public static string ApproverlevelL1 = getLevel("1");
public static string ApproverlevelL2 = getLevel("2");
public static string ApproverlevelL3 = getLevel("3");
public static string ApproverlevelL4 = getLevel("4");
public static string ApproverlevelL5 = getLevel("5");
private static string getLevel(string levelID)
{
string levelName;
logic here
return levelName;
}
}
}
```
Upvotes: 0 <issue_comment>username_3: Your "constants" are not constant. Make them `readonly` if you want them to behave like constants while making use of initialising static members with values. You could also make them properties and use just the `get` accessor to call the `getLevel` method.
As others have pointed out you cannot call a non-static member from within a static member, without instantiating an instance of the non-static class.
Your `getLevel` method also needs to be in its own class. As it stands it doesn't belong to a class or namespace. If you want it in its own separate class then just set the method to static.
.NET naming conventions recommend you use Pascal Casing for methods. So rename your `getLevel` method.
```
using System;
using System.Collections.Generic;
using System.Configuration;
namespace SSPWAS.Utilities
{
public static class Constants
{
// Use readonly static members
public static readonly string
ApproverlevelL1 = GetLevel("1"),
ApproverlevelL2 = GetLevel("2"),
ApproverlevelL3 = GetLevel("3"),
ApproverlevelL4 = GetLevel("4"),
ApproverlevelL5 = GetLevel("5");
// Or you could use the latest convenient syntax
public static string ApproverLevelL6 => GetLevel("6");
// Or you could use readonly properties
public static string ApproverLevelL7 { get { return GetLevel("7"); } }
private static string GetLevel(string levelId)
{
//... do logic
return "";
}
}
}
```
Or if you want the method in its own class:
```
public static class Constants
{
// Use readonly static members
public static readonly string
ApproverlevelL1 = Level.Get("1"),
ApproverlevelL2 = Level.Get("2"),
ApproverlevelL3 = Level.Get("3"),
ApproverlevelL4 = Level.Get("4"),
ApproverlevelL5 = Level.Get("5");
// Or you could use the latest convenient syntax
public static string ApproverLevelL6 => Level.Get("6");
// Or you could use readonly properties
public static string ApproverLevelL7 { get { return Level.Get("7"); } }
}
public class Level
{
public static string Get(string levelId)
{
//... do logic
return "";
}
}
```
Upvotes: 0 <issue_comment>username_4: If your issue is that you want the getLevel method to be in a different class, you could add a Function into your static class and override it with the method.
```
using System;
using System.Collections.Generic;
using System.Configuration;
namespace SSPWAS.Utilities
{
public class Constants
{
public static Func getLevel = x => string.Empty;
// added get accessor to make these read only
public static string ApproverlevelL1 { get; } = getLevel("1");
public static string ApproverlevelL2 { get; } = getLevel("2");
public static string ApproverlevelL3 { get; } = getLevel("3");
public static string ApproverlevelL4 { get; } = getLevel("4");
public static string ApproverlevelL5 { get; } = getLevel("5");
}
public class WhateverClass
{
public string getLevel(string levelID)
{
string levelName;
//logic here
return levelName;
}
// call this before accessing the fields in your Constants class
public void Init()
{
Constants.getLevel = x => getLevel(x);
}
}
}
```
The only reason I can think of to do this is maybe you have two applications using this static class and they need to get the level differently. Maybe one uses actual constant values and another reads a database, etc.
If you don't require this then the simplest answer is to actually put the method into the class as a static method:
```
namespace SSPWAS.Utilities
{
public class Constants
{
public static string getLevel(string levelID)
{
string levelName;
//logic here
return levelName;
}
// added get accessor to make these read only
public static string ApproverlevelL1 { get; } = getLevel("1");
public static string ApproverlevelL2 { get; } = getLevel("2");
public static string ApproverlevelL3 { get; } = getLevel("3");
public static string ApproverlevelL4 { get; } = getLevel("4");
public static string ApproverlevelL5 { get; } = getLevel("5");
}
}
```
Upvotes: 0 |
Subsets and Splits